@isdk/ai-tool 0.1.1 → 0.1.2

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-COXUI4Q3.mjs +1 -0
  2. package/dist/funcs.js +1 -1
  3. package/dist/funcs.mjs +1 -1
  4. package/dist/index.d.mts +29 -28
  5. package/dist/index.d.ts +29 -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 +182 -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/index.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,{AIArgProcessor:()=>Hn,AIChatRoles:()=>U,AIMessageTypes:()=>B,AIStream:()=>ze,AITextGenerationFinishReasons:()=>V,AbortError:()=>O,AbortErrorCode:()=>S,ActionNames:()=>w,AlreadyExistsError:()=>C,AlreadyExistsErrorCode:()=>v,AsyncFeatureBits:()=>Nn,AsyncFeatures:()=>In,BaseError:()=>$,CancelableAbility:()=>Vn,ChoiceArgProcessor:()=>Jn,ClientToolFuncSchema:()=>rs,ClientTools:()=>es,CommonError:()=>A,ConfigFile:()=>Kr.Config,DefaultAsyncSemaphoreCapacity:()=>yn,ErrorCode:()=>b,EventBusName:()=>Oe,EventClient:()=>ws,EventName:()=>Ce,EventServer:()=>xs,EventToolFunc:()=>os,FStringPromptTemplate:()=>oe,FewShotPromptTemplate:()=>he,FilenameReservedRegex:()=>fr,GolangPromptTemplate:()=>ue,HFBuiltins:()=>Kt,HFEnvironment:()=>Xt,HFInterpreter:()=>Dt,HFTemplate:()=>Zt,HfPromptTemplate:()=>ee,IntSet:()=>wn,InternalErrorCode:()=>g,NotFoundError:()=>T,NotFoundErrorCode:()=>x,NotImplementationError:()=>k,NotImplementedErrorCode:()=>E,PASSING_SCORE:()=>d,PromptExampleSelector:()=>G,PromptTemplate:()=>W,PromptTemplateTypes:()=>z,PromptTypes:()=>L,RStreamErrCode:()=>Pe,RateLimit:()=>$n,ReadableStreamError:()=>qe,RemoteToolFuncSchema:()=>m,ResClientTools:()=>ds,ResServerTools:()=>gs,ResponseRStreamErrCode:()=>Me,SSEChannel:()=>Ie,SSEChannelAlreadyClosedErrCode:()=>Ne,Semaphore:()=>Sn,ServerToolFuncSchema:()=>ss,ServerTools:()=>ns,TaskAbortController:()=>qn,TemplateArgProcessor:()=>Wn,ToolAsyncCancelableBit:()=>jn,ToolAsyncMultiTaskBit:()=>On,ToolAsyncPriorityBit:()=>Fn,ToolFunc:()=>Rn,ToolFuncSchema:()=>Pn,WindowsReservedNameRegex:()=>pr,XXHashAlgorithm:()=>cr,_lrucache:()=>us,backendEventable:()=>je,base32768:()=>rr,countRegexMatches:()=>Un,createAbilityInjector:()=>p.createAbilityInjector,createCallbacksTransformer:()=>Je,createEmptyReadableStream:()=>Be,createEndWithRepetitionDetector:()=>qr,createError:()=>j,createEventStreamTransformer:()=>_e,createHfValueFunc:()=>re,createLRUCache:()=>ls,dateToText:()=>q,defaultTemplateFormat:()=>J,event:()=>as,eventClient:()=>ms,eventServer:()=>vs,expandEnv:()=>we,expandObjEnv:()=>me,extNameLevel:()=>Ar,fileIsExists:()=>Ur,filenameReservedRegex:()=>br,filterValidFnScope:()=>Rr,formatISO:()=>I.formatISO,getAllEnumKeys:()=>Cr,getConfigFileNames:()=>rn,getConfigs:()=>nn,getKeysPath:()=>Pr,getMultiLevelExtname:()=>$r,getRealFilepath:()=>Jr,getResponseErrorReadableStream:()=>Ve,hfParse:()=>Ct,hfTokenize:()=>nt,interpolateEnv:()=>de,interpolateFString:()=>se,interpolateGolangTemplate:()=>ce,isModelNameMatched:()=>Tr,isValidFilename:()=>Er,isValidFilepath:()=>xr,isWebStream:()=>Re,jsonFilterToWhere:()=>ln,jsonToMarkdownStr:()=>dn,loadFileFromPaths:()=>_r,loadTextFromPaths:()=>zr,lrucache:()=>hs,makeToolFuncCancelable:()=>Bn,matchUrlProtocol:()=>hn,messagesToText:()=>_,mimeType:()=>Zr.mimeType,paramsSizeToScaleStr:()=>fn,parseCommand:()=>Qn,parseDateFormat:()=>N.parse,parseFString:()=>ne,parseISO:()=>I.parseISO,parseJsJson:()=>Fr,parseObjectArgInfo:()=>Zn,parseObjectArgumentInfos:()=>Dn,parseObjectArguments:()=>zn,parseObjectArgumentsAsArgInfos:()=>Yn,parseYaml:()=>en,quoteStr:()=>Gn,reControlCharsRegex:()=>gr,readFilenamesRecursiveSync:()=>Dr,readableFromAsyncIterable:()=>De,registerCoreTools:()=>Ss,registerYamlTag:()=>tn,sanitizeFilename:()=>vr,sanitizeFilepath:()=>Sr,saveConfigFile:()=>sn,scaleStrToParamsSize:()=>pn,sortedValues:()=>le,splitSentence:()=>$e,stringifyYaml:()=>Yr.stringify,textToDate:()=>M,throwError:()=>F,toDate:()=>I.toDate,toDateTime:()=>P,trimStartOfStreamHelper:()=>Le,truncTo:()=>Ae,uuid:()=>Ze,uuidNIL:()=>Ge.NIL,uuidParse:()=>Ge.parse,uuidStringify:()=>Ge.stringify,uuidValidate:()=>Ge.validate,uuidVersion:()=>Ge.version,uuidv1:()=>Ge.v1,uuidv4:()=>Ge.v4,uuidv5:()=>Ge.v5,wait:()=>ke,xxhash:()=>ur,xxhash32:()=>or,xxhash64:()=>ar,xxhashAsStr:()=>lr}),module.exports=(t=h,c(r({},"__esModule",{value:!0}),t));var f={};a(f,{AIArgProcessor:()=>Hn,AIChatRoles:()=>U,AIMessageTypes:()=>B,AIStream:()=>ze,AITextGenerationFinishReasons:()=>V,AbortError:()=>O,AbortErrorCode:()=>S,ActionNames:()=>w,AlreadyExistsError:()=>C,AlreadyExistsErrorCode:()=>v,BaseError:()=>$,CancelableAbility:()=>Vn,ChoiceArgProcessor:()=>Jn,CommonError:()=>A,ConfigFile:()=>Kr.Config,DefaultAsyncSemaphoreCapacity:()=>yn,ErrorCode:()=>b,EventBusName:()=>Oe,EventName:()=>Ce,FStringPromptTemplate:()=>oe,FewShotPromptTemplate:()=>he,FilenameReservedRegex:()=>fr,GolangPromptTemplate:()=>ue,HFBuiltins:()=>Kt,HFEnvironment:()=>Xt,HFInterpreter:()=>Dt,HFTemplate:()=>Zt,HfPromptTemplate:()=>ee,IntSet:()=>wn,InternalErrorCode:()=>g,NotFoundError:()=>T,NotFoundErrorCode:()=>x,NotImplementationError:()=>k,NotImplementedErrorCode:()=>E,PASSING_SCORE:()=>d,PromptExampleSelector:()=>G,PromptTemplate:()=>W,PromptTemplateTypes:()=>z,PromptTypes:()=>L,RStreamErrCode:()=>Pe,RateLimit:()=>$n,ReadableStreamError:()=>qe,RemoteToolFuncSchema:()=>m,ResponseRStreamErrCode:()=>Me,SSEChannel:()=>Ie,SSEChannelAlreadyClosedErrCode:()=>Ne,Semaphore:()=>Sn,TaskAbortController:()=>qn,TemplateArgProcessor:()=>Wn,WindowsReservedNameRegex:()=>pr,XXHashAlgorithm:()=>cr,backendEventable:()=>je,base32768:()=>rr,countRegexMatches:()=>Un,createAbilityInjector:()=>p.createAbilityInjector,createCallbacksTransformer:()=>Je,createEmptyReadableStream:()=>Be,createEndWithRepetitionDetector:()=>qr,createError:()=>j,createEventStreamTransformer:()=>_e,createHfValueFunc:()=>re,dateToText:()=>q,defaultTemplateFormat:()=>J,expandEnv:()=>we,expandObjEnv:()=>me,extNameLevel:()=>Ar,fileIsExists:()=>Ur,filenameReservedRegex:()=>br,filterValidFnScope:()=>Rr,formatISO:()=>I.formatISO,getAllEnumKeys:()=>Cr,getConfigFileNames:()=>rn,getConfigs:()=>nn,getKeysPath:()=>Pr,getMultiLevelExtname:()=>$r,getRealFilepath:()=>Jr,getResponseErrorReadableStream:()=>Ve,hfParse:()=>Ct,hfTokenize:()=>nt,interpolateEnv:()=>de,interpolateFString:()=>se,interpolateGolangTemplate:()=>ce,isModelNameMatched:()=>Tr,isValidFilename:()=>Er,isValidFilepath:()=>xr,isWebStream:()=>Re,jsonFilterToWhere:()=>ln,jsonToMarkdownStr:()=>dn,loadFileFromPaths:()=>_r,loadTextFromPaths:()=>zr,makeToolFuncCancelable:()=>Bn,matchUrlProtocol:()=>hn,messagesToText:()=>_,mimeType:()=>Zr.mimeType,paramsSizeToScaleStr:()=>fn,parseCommand:()=>Qn,parseDateFormat:()=>N.parse,parseFString:()=>ne,parseISO:()=>I.parseISO,parseJsJson:()=>Fr,parseObjectArgInfo:()=>Zn,parseObjectArgumentInfos:()=>Dn,parseObjectArguments:()=>zn,parseObjectArgumentsAsArgInfos:()=>Yn,parseYaml:()=>en,quoteStr:()=>Gn,reControlCharsRegex:()=>gr,readFilenamesRecursiveSync:()=>Dr,readableFromAsyncIterable:()=>De,registerYamlTag:()=>tn,sanitizeFilename:()=>vr,sanitizeFilepath:()=>Sr,saveConfigFile:()=>sn,scaleStrToParamsSize:()=>pn,sortedValues:()=>le,splitSentence:()=>$e,stringifyYaml:()=>Yr.stringify,textToDate:()=>M,throwError:()=>F,toDate:()=>I.toDate,toDateTime:()=>P,trimStartOfStreamHelper:()=>Le,truncTo:()=>Ae,uuid:()=>Ze,uuidNIL:()=>Ge.NIL,uuidParse:()=>Ge.parse,uuidStringify:()=>Ge.stringify,uuidValidate:()=>Ge.validate,uuidVersion:()=>Ge.version,uuidv1:()=>Ge.v1,uuidv4:()=>Ge.v4,uuidv5:()=>Ge.v5,wait:()=>ke,xxhash:()=>ur,xxhash32:()=>or,xxhash64:()=>ar,xxhashAsStr:()=>lr});var p=require("custom-ability"),d=.618,w=["get","post","put","delete","patch","list","res"],m={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"}},y=require("abstract-error"),b=(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))(b||{}),g=500,E=501,x=404,v=409,S=499,$=class t extends y.AbstractError{static createErrorClass(e,r,n=t){return(0,y.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}},A=class extends ${constructor(t,e,r=g){super(t,r,e)}},k=class extends A{constructor(t,e){t||(t="Not Implementation."),super(t,e,501)}};A[E]=k;var T=class extends A{static{this.code=x}constructor(t,e){super(`Could not find ${t}.`,e,x),this.data={what:t}}};A[x]=T;var C=class extends A{static{this.code=v}constructor(t,e){super(`The ${t} already exists.`,e,v),this.data={what:t}}};A[v]=C;var O=class extends A{static{this.code=S}constructor(t,e){e||(e="AbortError"),super(t?`The operation was aborted for ${t}.`:"The operation was aborted.",e,S),t&&(this.data={what:t})}};function j(t,e,r=g){const n=new(A[r]||A)(t,e,r);return"number"!=typeof n.code&&(n.code=r),n}function F(t,e,r=g){throw j(t,e,r)}A[S]=O;var N=require("date-fns"),I=require("date-fns"),R="MMMM d, y 'at' h:m:s b 'GMT'x";function P(t){let e;try{"string"==typeof t?e=(0,N.parseISO)(t):"number"==typeof t?e=new Date(t):t instanceof Date&&(e=t)}catch(t){console.error(t)}return e}function M(t,e=R){return(0,N.parse)(t,e,new Date)}function q(t,e=R){return(0,N.format)(t,e)}var V=["stop","length","content-filter","tool-calls","abort","error","other",null],B=["human","ai","generic","system","tool"],U=["user","assistant","system","tool","tool_calls"];function _(t){let e="";for(const r of t)if(r.content){e+=r.role.toLowerCase()+":";let t=r.createdAt;if(t){const r=P(t);r&&(e+=" ["+q(r)+"]")}e+=" "+r.content+"\n"}return e}var L=["chat","char","plan"],z=["internal","hf","fill"],D=require("custom-factory");var J="default",W=class t extends D.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||J,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||J);if(e)return Reflect.construct(e,arguments);throw new A(`Prompt template type ${n} not found`,"PromptTemplate",400)}}_initialize(t){throw new k("Not implemented","PromptTemplate")}initialize(e){this.constructor!==t&&(Object.assign(this,this.toJSON(e)),e?.ignoreInitialize||this._initialize(e))}_format(t){throw new k("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 H(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 K=!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=>{K=t}));var G=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,K?n:H(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()}},X=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"}),Z=Object.freeze({set:X.Set,for:X.For,in:X.In,is:X.Is,if:X.If,else:X.Else,endif:X.EndIf,elif:X.ElseIf,endfor:X.EndFor,and:X.And,or:X.Or,not:X.Not,"not in":X.NotIn,macro:X.Macro,endmacro:X.EndMacro,true:X.BooleanLiteral,false:X.BooleanLiteral,True:X.BooleanLiteral,False:X.BooleanLiteral}),Y=class{constructor(t,e){this.value=t,this.type=e}};function Q(t){return/\w/.test(t)}function tt(t){return/[0-9]/.test(t)}var et=[["{%",X.OpenStatement],["%}",X.CloseStatement],["{{",X.OpenExpression],["}}",X.CloseExpression],["(",X.OpenParen],[")",X.CloseParen],["{",X.OpenCurlyBracket],["}",X.CloseCurlyBracket],["[",X.OpenSquareBracket],["]",X.CloseSquareBracket],[",",X.Comma],[".",X.Dot],[":",X.Colon],["|",X.Pipe],["<=",X.ComparisonBinaryOperator],[">=",X.ComparisonBinaryOperator],["==",X.ComparisonBinaryOperator],["!=",X.ComparisonBinaryOperator],["<",X.ComparisonBinaryOperator],[">",X.ComparisonBinaryOperator],["+",X.AdditiveBinaryOperator],["-",X.AdditiveBinaryOperator],["*",X.MultiplicativeBinaryOperator],["/",X.MultiplicativeBinaryOperator],["%",X.MultiplicativeBinaryOperator],["=",X.Equals]],rt=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function nt(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=rt.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===X.CloseStatement||t===X.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 Y(t,X.Text));continue}}i((t=>/\s/.test(t)));const e=n[s];if("-"===e||"+"===e){const t=r.at(-1)?.type;if(t===X.Text||void 0===t)throw new SyntaxError(`Unexpected character: ${e}`);switch(t){case X.Identifier:case X.NumericLiteral:case X.BooleanLiteral:case X.StringLiteral:case X.CloseParen:case X.CloseSquareBracket:break;default:{++s;const t=i(tt);r.push(new Y(`${e}${t}`,t.length>0?X.NumericLiteral:X.UnaryOperator));continue}}}for(const[t,e]of et){if(n.slice(s,s+t.length)===t){r.push(new Y(t,e)),s+=t.length;continue t}}if("'"!==e&&'"'!==e)if(tt(e)){const t=i(tt);r.push(new Y(t,X.NumericLiteral))}else{if(!Q(e))throw new SyntaxError(`Unexpected character: ${e}`);{const t=i(Q),e=Object.hasOwn(Z,t)?Z[t]:X.Identifier;e===X.In&&r.at(-1)?.type===X.Not?(r.pop(),r.push(new Y("not in",X.NotIn))):r.push(new Y(t,e))}}else{++s;const t=i((t=>t!==e));r.push(new Y(t,X.StringLiteral)),++s}}return r}var st=class{constructor(){this.type="Statement"}},it=class extends st{constructor(t){super(),this.body=t,this.type="Program"}},ot=class extends st{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r,this.type="If"}},at=class extends st{constructor(t,e,r,n){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=n,this.type="For"}},ct=class extends st{constructor(t,e){super(),this.assignee=t,this.value=e,this.type="Set"}},ut=class extends st{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r,this.type="Macro"}},lt=class extends st{constructor(){super(...arguments),this.type="Expression"}},ht=class extends lt{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r,this.type="MemberExpression"}},ft=class extends lt{constructor(t,e){super(),this.callee=t,this.args=e,this.type="CallExpression"}},pt=class extends lt{constructor(t){super(),this.value=t,this.type="Identifier"}},dt=class extends lt{constructor(t){super(),this.value=t,this.type="Literal"}},wt=class extends dt{constructor(){super(...arguments),this.type="NumericLiteral"}},mt=class extends dt{constructor(){super(...arguments),this.type="StringLiteral"}},yt=class extends dt{constructor(){super(...arguments),this.type="BooleanLiteral"}},bt=class extends dt{constructor(){super(...arguments),this.type="ArrayLiteral"}},gt=class extends dt{constructor(){super(...arguments),this.type="TupleLiteral"}},Et=class extends dt{constructor(){super(...arguments),this.type="ObjectLiteral"}},xt=class extends lt{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r,this.type="BinaryExpression"}},vt=class extends lt{constructor(t,e){super(),this.operand=t,this.filter=e,this.type="FilterExpression"}},St=class extends lt{constructor(t,e){super(),this.iterable=t,this.test=e,this.type="SelectExpression"}},$t=class extends lt{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r,this.type="TestExpression"}},At=class extends lt{constructor(t,e){super(),this.operator=t,this.argument=e,this.type="UnaryExpression"}},kt=class extends lt{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 lt{constructor(t,e){super(),this.key=t,this.value=e,this.type="KeywordArgumentExpression"}};function Ct(t){const e=new it([]);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 X.Text:e=new mt(n(X.Text,"Expected text token").value);break;case X.OpenStatement:e=function(){let e;switch(n(X.OpenStatement,"Expected opening statement token"),t[r].type){case X.Set:++r,e=a(),n(X.CloseStatement,"Expected closing statement token");break;case X.If:++r,e=c(),n(X.OpenStatement,"Expected {% token"),n(X.EndIf,"Expected endif token"),n(X.CloseStatement,"Expected %} token");break;case X.Macro:++r,e=function(){const t=x();if("Identifier"!==t.type)throw new SyntaxError("Expected identifier following macro statement");const e=y();n(X.CloseStatement,"Expected closing statement token");const r=[];for(;i(X.OpenStatement,X.EndMacro);)r.push(s());return new ut(t,e,r)}(),n(X.OpenStatement,"Expected {% token"),n(X.EndMacro,"Expected endmacro token"),n(X.CloseStatement,"Expected %} token");break;case X.For:++r,e=function(){const t=u(!0);if(!(t instanceof pt||t instanceof gt))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${t.type} instead`);n(X.In,"Expected `in` keyword following loop variable");const e=l();n(X.CloseStatement,"Expected closing statement token");const a=[];for(;i(X.OpenStatement,X.EndFor)&&i(X.OpenStatement,X.Else);)a.push(s());const c=[];if(o(X.OpenStatement,X.Else))for(++r,++r,n(X.CloseStatement,"Expected closing statement token");i(X.OpenStatement,X.EndFor);)c.push(s());return new at(t,e,a,c)}(),n(X.OpenStatement,"Expected {% token"),n(X.EndFor,"Expected endfor token"),n(X.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${t[r].type} ${t[r].value}`)}return e}(),e.isStatement=!0;break;case X.OpenExpression:e=function(){n(X.OpenExpression,"Expected opening expression token");const t=l();return n(X.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(X.Equals)){++r;const e=a();return new ct(t,e)}return t}function c(){const e=l();n(X.CloseStatement,"Expected closing statement token");const i=[],a=[];for(;t[r]?.type!==X.OpenStatement||t[r+1]?.type!==X.ElseIf&&t[r+1]?.type!==X.Else&&t[r+1]?.type!==X.EndIf;)i.push(s());if(t[r]?.type===X.OpenStatement&&t[r+1]?.type!==X.EndIf)if(++r,o(X.ElseIf))n(X.ElseIf,"Expected elseif token"),a.push(c());else for(n(X.Else,"Expected else token"),n(X.CloseStatement,"Expected closing statement token");t[r]?.type!==X.OpenStatement||t[r+1]?.type!==X.EndIf;)a.push(s());return new ot(e,i,a)}function u(t=!1){const e=t?x:l,n=[e()],s=o(X.Comma);for(;s&&(++r,n.push(e()),o(X.Comma)););return s?new gt(n):n[0]}function l(){return function(){const t=h();if(o(X.If)){++r;const e=h();if(o(X.Else)){++r;const n=h();return new ot(e,[t],[n])}return new St(t,e)}return t}()}function h(){let e=f();for(;o(X.Or);){const n=t[r];++r;const s=f();e=new xt(n,e,s)}return e}function f(){let e=p();for(;o(X.And);){const n=t[r];++r;const s=p();e=new xt(n,e,s)}return e}function p(){let e;for(;o(X.Not);){const n=t[r];++r;const s=p();e=new At(n,s)}return e??function(){let e=d();for(;o(X.ComparisonBinaryOperator)||o(X.In)||o(X.NotIn);){const n=t[r];++r;const s=d();e=new xt(n,e,s)}return e}()}function d(){let e=g();for(;o(X.AdditiveBinaryOperator);){const n=t[r];++r;const s=g();e=new xt(n,e,s)}return e}function w(){const e=function(){let e=x();for(;o(X.Dot)||o(X.OpenSquareBracket);){const s=t[r];let i;++r;const o=s.type!==X.Dot;if(o)i=b(),n(X.CloseSquareBracket,"Expected closing square bracket");else if(i=x(),"Identifier"!==i.type)throw new SyntaxError("Expected identifier following dot operator");e=new ht(e,i,o)}return e}();return o(X.OpenParen)?m(e):e}function m(t){let e=new ft(t,y());return o(X.OpenParen)&&(e=m(e)),e}function y(){n(X.OpenParen,"Expected opening parenthesis for arguments list");const t=function(){const t=[];for(;!o(X.CloseParen);){let e=l();if(o(X.Equals)){if(++r,!(e instanceof pt))throw new SyntaxError("Expected identifier for keyword argument");const t=l();e=new Tt(e,t)}t.push(e),o(X.Comma)&&++r}return t}();return n(X.CloseParen,"Expected closing parenthesis for arguments list"),t}function b(){const t=[];let e=!1;for(;!o(X.CloseSquareBracket);)o(X.Colon)?(t.push(void 0),++r,e=!0):(t.push(l()),o(X.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 kt(...t)}return t[0]}function g(){let e=E();for(;o(X.MultiplicativeBinaryOperator);){const n=t[r];++r;const s=E();e=new xt(n,e,s)}return e}function E(){let t=function(){let t=w();for(;o(X.Pipe);){++r;let e=x();if(!(e instanceof pt))throw new SyntaxError("Expected identifier for the filter");o(X.OpenParen)&&(e=m(e)),t=new vt(t,e)}return t}();for(;o(X.Is);){++r;const e=o(X.Not);e&&++r;let n=x();if(n instanceof yt&&(n=new pt(n.value.toString())),!(n instanceof pt))throw new SyntaxError("Expected identifier for the test");t=new $t(t,e,n)}return t}function x(){const e=t[r];switch(e.type){case X.NumericLiteral:return++r,new wt(Number(e.value));case X.StringLiteral:return++r,new mt(e.value);case X.BooleanLiteral:return++r,new yt("true"===e.value.toLowerCase());case X.Identifier:return++r,new pt(e.value);case X.OpenParen:{++r;const e=u();if(t[r].type!==X.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${t[r].type} instead`);return++r,e}case X.OpenSquareBracket:{++r;const t=[];for(;!o(X.CloseSquareBracket);)t.push(l()),o(X.Comma)&&++r;return++r,new bt(t)}case X.OpenCurlyBracket:{++r;const t=new Map;for(;!o(X.CloseCurlyBracket);){const e=l();n(X.Colon,"Expected colon between key and value in object literal");const s=l();t.set(e,s),o(X.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 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 jt(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 Nt=class{constructor(t=void 0){this.type="RuntimeValue",this.builtins=new Map,this.value=t}__bool__(){return new Pt(!!this.value)}toString(){return""+this.value}toJSON(){return this.value}},It=class extends Nt{constructor(){super(...arguments),this.type="NumericValue"}},Rt=class t extends Nt{constructor(){super(...arguments),this.type="StringValue",this.builtins=new Map([["upper",new Ut((()=>new t(this.value.toUpperCase())))],["lower",new Ut((()=>new t(this.value.toLowerCase())))],["strip",new Ut((()=>new t(this.value.trim())))],["title",new Ut((()=>new t(Ft(this.value))))],["length",new It(this.value.length)],["rstrip",new Ut((()=>new t(this.value.trimEnd())))],["lstrip",new Ut((()=>new t(this.value.trimStart())))]])}},Pt=class extends Nt{constructor(){super(...arguments),this.type="BooleanValue"}},Mt=class extends Nt{constructor(t,e){super(t),this.orgValue=e,this.type="ObjectValue",this.builtins=new Map([["get",new Ut((([t,e])=>{if(!(t instanceof Rt))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new _t}))],["items",new Ut((()=>new Vt(Array.from(this.value.entries()).map((([t,e])=>new Vt([new Rt(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 Pt(this.value.size>0)}},qt=class extends Mt{constructor(){super(...arguments),this.type="KeywordArgumentsValue"}},Vt=class extends Nt{constructor(){super(...arguments),this.type="ArrayValue",this.builtins=new Map([["length",new It(this.value.length)]])}__bool__(){return new Pt(this.value.length>0)}},Bt=class extends Vt{constructor(){super(...arguments),this.type="TupleValue"}},Ut=class extends Nt{constructor(){super(...arguments),this.type="FunctionValue"}},_t=class extends Nt{constructor(){super(...arguments),this.type="NullValue"}},Lt=class extends Nt{constructor(){super(...arguments),this.type="UndefinedValue"}},zt=class{constructor(t){this.parent=t,this.variables=new Map([["namespace",new Ut((t=>{if(0===t.length)return new Mt(new Map);if(1!==t.length||!(t[0]instanceof Mt))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 Ut],["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 Vt||t instanceof Rt],["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,Jt(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 Lt}catch{return new Lt}}},Dt=class{constructor(t){this.global=t??new zt}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 Pt(r.value==n.value);case"!=":return new Pt(r.value!=n.value)}if(r instanceof Lt||n instanceof Lt)throw new Error("Cannot perform operation on undefined values");if(r instanceof _t||n instanceof _t)throw new Error("Cannot perform operation on null values");if(r instanceof It&&n instanceof It)switch(t.operator.value){case"+":return new It(r.value+n.value);case"-":return new It(r.value-n.value);case"*":return new It(r.value*n.value);case"/":return new It(r.value/n.value);case"%":return new It(r.value%n.value);case"<":return new Pt(r.value<n.value);case">":return new Pt(r.value>n.value);case">=":return new Pt(r.value>=n.value);case"<=":return new Pt(r.value<=n.value)}else if(r instanceof Vt&&n instanceof Vt){if("+"===t.operator.value)return new Vt(r.value.concat(n.value))}else if(n instanceof Vt){const e=void 0!==n.value.find((t=>t.value===r.value));switch(t.operator.value){case"in":return new Pt(e);case"not in":return new Pt(!e)}}if((r instanceof Rt||n instanceof Rt)&&"+"===t.operator.value)return new Rt(r.toString()+n.toString());if(r instanceof Rt&&n instanceof Rt)switch(t.operator.value){case"in":return new Pt(n.value.includes(r.value));case"not in":return new Pt(!n.value.includes(r.value))}if(r instanceof Rt&&n instanceof Mt)switch(t.operator.value){case"in":return new Pt(n.value.has(r.value));case"not in":return new Pt(!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 Ut)return s.value([r],e);if(r instanceof Vt)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 It(r.value.length);case"reverse":return new Vt(r.value.reverse());case"sort":return new Vt(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 Rt)switch(n.value){case"length":return new It(r.value.length);case"upper":return new Rt(r.value.toUpperCase());case"lower":return new Rt(r.value.toLowerCase());case"title":return new Rt(Ft(r.value));case"capitalize":return new Rt(r.value.charAt(0).toUpperCase()+r.value.slice(1));case"trim":return new Rt(r.value.trim());case"trimStart":return new Rt(r.value.trimStart());case"trimEnd":return new Rt(r.value.trimEnd());case"indent":return new Rt(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 It){if("abs"===n.value)return new It(Math.abs(r.value));throw new Error(`Unknown NumericValue filter: ${n.value}`)}if(r instanceof Mt)switch(n.value){case"items":return new Vt(Array.from(r.value.entries()).map((([t,e])=>new Vt([new Rt(t),e]))));case"length":return new It(r.value.size);case"string":return new Rt(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 Ut){const[t,s]=this.evaluateArguments(n.args,e);return s.size>0&&t.push(new qt(s)),i.value([r,...t],e)}if(r instanceof Vt){switch(s){case"selectattr":{if(r.value.some((t=>!(t instanceof Mt))))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 Vt(a)}case"map":{const[,t]=this.evaluateArguments(n.args,e);if(t.has("attribute")){const e=t.get("attribute");if(!(e instanceof Rt))throw new Error("attribute must be a string");const n=t.get("default"),s=r.value.map((t=>{if(!(t instanceof Mt))throw new Error("items in map must be an object");return t.value.get(e.value)??n??new Lt}));return new Vt(s)}throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${s}`)}if(r instanceof Rt){if("indent"===s){const[t,s]=this.evaluateArguments(n.args,e),i=t.at(0)??s.get("width")??new It(4);if(!(i instanceof It))throw new Error("width must be a number");const o=t.at(1)??s.get("first")??new Pt(!1),a=t.at(2)??s.get("blank")??new Pt(!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 Rt(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 Pt(t.negate?!s:s)}evaluateUnaryExpression(t,e){const r=this.evaluate(t.argument,e);if("not"===t.operator.value)return new Pt(!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 Rt(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 qt(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 Vt||t instanceof Rt))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 It||n instanceof Lt))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof It||s instanceof Lt))throw new Error("Slice stop must be numeric or undefined");if(!(i instanceof It||i instanceof Lt))throw new Error("Slice step must be numeric or undefined");return t instanceof Vt?new Vt(jt(t.value,n.value,s.value,i.value)):new Rt(jt(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 Rt(t.property.value);if(r instanceof Mt){if(!(n instanceof Rt))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 Vt||r instanceof Rt)if(n instanceof It)s=r.value.at(n.value),r instanceof Rt&&(s=new Rt(r.value.at(n.value)));else{if(!(n instanceof Rt))throw new Error(`Cannot access property with non-string/non-number: got ${n.type}`);s=r.builtins.get(n.value)}else{if(!(n instanceof Rt))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.builtins.get(n.value)}return s instanceof Nt?s:new Lt}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 Mt))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 _t}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 zt(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 Vt))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 zt(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 It(e+1)],["index0",new It(e)],["revindex",new It(i.length-e)],["revindex0",new It(i.length-e-1)],["first",new Pt(0===e)],["last",new Pt(e===i.length-1)],["length",new It(i.length)],["previtem",e>0?i[e-1]:new Lt],["nextitem",e<i.length-1?i[e+1]:new Lt]]);r.setVariable("loop",new Mt(n)),o[e](r);a+=this.evaluateBlock(t.body,r).value,c=!1}if(c){a+=this.evaluateBlock(t.defaultBlock,r).value}return new Rt(a)}evaluateMacro(t,e){return e.setVariable(t.name.value,new Ut(((e,r)=>{const n=new zt(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 _t}evaluate(t,e){if(void 0===t)return new Lt;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 It(Number(t.value));case"StringLiteral":return new Rt(t.value);case"BooleanLiteral":return new Pt(t.value);case"ArrayLiteral":return new Vt(t.value.map((t=>this.evaluate(t,e))));case"TupleLiteral":return new Bt(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 Rt))throw new Error(`Object keys must be strings: got ${t.type}`);r.set(t.value,this.evaluate(s,e))}return new Mt(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 Jt(t){switch(typeof t){case"number":return new It(t);case"string":return new Rt(t);case"boolean":return new Pt(t);case"undefined":return new Lt;case"object":return null===t?new _t:Array.isArray(t)?new Vt(t.map(Jt)):new Mt(new Map(Object.entries(t).map((([t,e])=>[t,Jt(e)]))),t);case"function":return new Ut(((e,r)=>{const n=e.map((t=>Wt(t)));return Jt(t(...n)??null)}));default:throw new Error(`Cannot convert to runtime value: ${t}`)}}function Wt(t){let e=t;if(Array.isArray(t))e=t.map((t=>Wt(t)));else if(t instanceof Map)e={},t.forEach(((t,r)=>{e[r]=Wt(t)}));else switch(t.type){case"NullValue":e=null;break;case"UndefinedValue":e=void 0;break;case"ArrayValue":e=t.value.map((t=>Wt(t)));break;case"KeywordArgumentsValue":case"ObjectValue":e=t.orgValue?t.orgValue:Wt(t.value),"KeywordArgumentsValue"===t.type&&Object.setPrototypeOf(e,{jinja_kargs:!0});break;default:t.type&&(e=t.value)}return e}function Ht(t,e=0){return Math.floor(Math.random()*(t-e+1))+e}var Kt={randomInt:Ht,select:function(t,e){if(Array.isArray(t)||"string"==typeof t)return void 0===e?e=Ht(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[Ht(r.length-1)]}return t[e]}},tojson:function(t,e,r){return e&&"object"==typeof e&&(e.depth&&(r=e.depth),e=e.indent),Gt(t,e,r)}};function Gt(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=>Gt(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}": ${Gt(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 Xt=class extends zt{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()}},Zt=class t{static{this.global=new Xt}constructor(t,e={}){const r=nt(t,e={lstrip_blocks:!0,trim_blocks:!0,...e});this.parsed=Ct(r)}render(e){const r=new zt(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 Dt(r).run(this.parsed).toString()}};function Yt(t,e){let r;switch(t.type){case"Identifier":r=t.value;break;case"MemberExpression":r=Yt(t.object,e);break;case"FilterExpression":r=Yt(t.operand,e);break;case"Set":{e||(e=[]);const n=Yt(t.assignee);n&&e.push(n),r=Yt(t.value,e);break}}return r&&e?.includes(r)&&(r=void 0),r}function Qt(t){let e;if("Program"===t.type)e=t.body.some((t=>Qt(t)));else e=t.isStatement;return e}function te(t,e){let r=[];if(Array.isArray(t))r=t.map((t=>te(t,e))).filter(Boolean).flat();else switch(t.type){case"Program":r=t.body.map((t=>te(t,e))).filter(Boolean).flat();break;case"If":r=[Yt(t.test,e),...te(t.body,e),...te(t.alternate,e)].filter(Boolean);break;case"BinaryExpression":r=[Yt(t.left,e),Yt(t.right,e)].filter(Boolean);break;case"For":{const n=Yt(t.loopvar);n&&(e||(e=[]),e.push(n)),r=[Yt(t.iterable,e),...te(t.body,e)].filter(Boolean);break}case"CallExpression":r=[Yt(t.callee,e),...te(t.args,e)].filter(Boolean);break;default:r=[Yt(t,e)].filter(Boolean)}return r}Zt.global.assign(Kt);var ee=class extends W{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 Zt(r)}catch(t){}return e&&(n=Qt(e.parsed)),n}getVariables(t=this.compiledTemplate){return te(t.parsed,[]).filter(((t,e,r)=>r.indexOf(t)===e))}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new A("Prompt template must be a string","PromptTemplate",400);this.compiledTemplate=new Zt(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return this.compiledTemplate.render(t)}};function re(t){return function(e){return t}}function ne(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 se(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 ie(t){const e=new Set;return t.forEach((t=>{"variable"===t.type&&e.add(t.name)})),[...e]}W.register(ee,{name:"hf",aliases:["huggingface","internal","default"]});var oe=class extends W{static isTemplate(t){let e,r,n=!1;if("object"==typeof t?(r=t.template,e=t.compiledTemplate):r=t,!e&&r)try{e=ne(r)}catch(t){}if(e){n=ie(e).length>0}return n}getVariables(t=this.compiledTemplate){return ie(t)}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new A("Prompt template must be a string","PromptTemplate",400);this.compiledTemplate=ne(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return se(this.compiledTemplate,t)}};function ae(t,e){return"string"==typeof e&&(e=e.split(".").filter((t=>t.length))),e.reduce(((t,e)=>t?.[e]),t)}function ce(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 ae(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):ae(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=ae(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=ae(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):ae(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=ae(e,n);let o;return o=isNaN(s)?i[s.substring(1,s.length-1)]:i[parseInt(s,10)],o||""}))}(n,e,r),n}W.register(oe,{name:"fstring",aliases:["python","f-string","langchain"]});var ue=class extends W{static isTemplate(t){const e="string"==typeof t?t:t.template;return e?.includes("{{")&&e.includes("}}")}getVariables(t){const e={};return ce(t,e,!0),[...Object.keys(e)]}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new A("Prompt template must be a string","PromptTemplate",400);this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables(e)}_format(t){return ce(this.template,t)}};function le(t){return Object.keys(t).sort().map((e=>t[e]))}W.register(ue,{name:"golang",aliases:["localai","ollama"]});var he=class extends W{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 W?t.examplePrompt:W.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=le(t);r.length>0&&e.push(...r)}const r=[this.prefix,...e,this.suffix].join(this.exampleSeparator),n=this.templateFormat;return await W.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}};W.register(he,{name:"fewshot",aliases:["few_shot"]});var fe=/(\\)?(\$)(?!\()(\{?)([\w.]+)(?::?-((?:\$\{(?:\$\{(?:\$\{[^}]*\}|[^}])*}|[^}])*}|[^}])+))?(\}?)/gi;function pe(t){return t.replace(/\\\$/g,"$")}function de(t,e,r){return t.replace(fe,((n,s,i,o,a,c,u)=>"\\"===s?n.slice(1):e[a]?e[a]===r[a]?e[a]:de(e[a],e,r):r[a]?r[a]===t?r[a]:de(r[a],e,r):c?c.startsWith("$")?de(c,e,r):c:""))}function we(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]?de(n,e,t.parsed):e[r]:de(n,e,t.parsed),t.parsed[r]=n?pe(n):n}for(const r in t.parsed)e[r]=t.parsed[r];return t}function me(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=de(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]=me(t[n],e,r))}else for(const[n,s]of Object.entries(t))"string"!=typeof s&&"object"!=typeof s||(t[n]=me(s,e,r))}return t}var ye="@",be=/(\S.+?[.!?])(?=\s+|$)|(\S.+?)(?=[\n]|$)/g,ge=/([A-Z][a-z]{1,2}\.)\s(\w)/g,Ee=/(\.[a-zA-Z]\.)\s(\w)/g,xe=new RegExp("([A-Z][a-z]{1,2}\\.)"+ye+"(\\w)","g"),ve=new RegExp("(\\.[a-zA-Z]\\.)"+ye+"(\\w)","g");function Se(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 $e(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=Se(s,ye,[ge,Ee]),o=Array.from(i.matchAll(be));if(o.length)for(let t=0;t<o.length;t++){let e=Se(o[t][0]," ",[xe,ve]);n.push(e)}else n.push(s)}return n}function Ae(t,e=2,r=.5){const n=10**e;return Math.trunc((t+Number.EPSILON+r/n)*n)/n}async function ke(t){return new Promise((e=>setTimeout(e,t)))}var Te=require("custom-ability"),Ce="event",Oe="event-bus";var je=(0,Te.createAbilityInjector)((function(t){return class{static get emitter(){if(!this._emitter){const t=this.get(Oe)?.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 Ne=498,Ie=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||F("Channel closed","SSEChannel",Ne);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||F("Channel closed","SSEChannel",Ne);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 Re(t){return t instanceof ReadableStream||t instanceof WritableStream}var Pe=600,Me=601,qe=class extends ${constructor(t,e=Pe){super(t,500)}};function Ve(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 qe(`Response error: ${e}`,Me))}}})}return new ReadableStream({start(t){t.error(new qe("Response error: No response body",Me))}})}function Be(){return new ReadableStream({start(t){t.close()}})}var Ue=require("eventsource-parser");function _e(t){const e=new TextDecoder;let r;return new TransformStream({async start(e){r=(0,Ue.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 Le(){let t=!0;return e=>(t&&(e=e.trimStart())&&(t=!1),e)}function ze(t,e){if(!t.ok)return Ve(t.body);let r=t.body||new ReadableStream({start(t){t.close()}});return r instanceof ReadableStream||(r=ReadableStream.from(r)),r.pipeThrough(_e(e))}function De(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 Je(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 We={};a(We,{XXHashAlgorithm:()=>cr,base32768:()=>rr,uuid:()=>Ze,uuidNIL:()=>Ge.NIL,uuidParse:()=>Ge.parse,uuidStringify:()=>Ge.stringify,uuidValidate:()=>Ge.validate,uuidVersion:()=>Ge.version,uuidv1:()=>Ge.v1,uuidv4:()=>Ge.v4,uuidv5:()=>Ge.v5,xxhash:()=>ur,xxhash32:()=>or,xxhash64:()=>ar,xxhashAsStr:()=>lr});var He=require("uuid"),Ke=l(require("base32768")),Ge=require("uuid"),Xe={1:He.v1,4:He.v4,5:He.v5};function Ze(t=1,e){const r=Xe[t];return e?Ke.encode(r(null,[])):r()}var Ye={};a(Ye,{XXHashAlgorithm:()=>cr,base32768:()=>rr,xxhash:()=>ur,xxhash32:()=>or,xxhash64:()=>ar,xxhashAsStr:()=>lr});var Qe=l(require("xxhashjs")),tr=l(require("base32768")),er=require("json-canonicalize");u(Ye,require("json-canonicalize"));var rr=tr,{h32:nr,h64:sr}=Qe.default,ir=588213;function or(t,e=16){return"object"==typeof t&&(t=(0,er.canonicalize)(t)),nr(t,ir).toString(e)}function ar(t,e=16){return"object"==typeof t&&(t=(0,er.canonicalize)(t)),sr(t,ir).toString(e)}var cr=(t=>(t[t.xxhash64=111]="xxhash64",t[t.xxhash32=112]="xxhash32",t))(cr||{});function ur(t,e=111,r=ir){let n;return t.buffer&&(t=t.buffer),112!==e?(n=sr(t,r),n=new Uint16Array([n._a00,n._a16,n._a32,n._a48]),n=new Uint8Array(n.buffer)):(n=nr(t,r),n=new Uint16Array([n._low,n._high]),n=new Uint8Array(n.buffer)),n}function lr(t,e=111,r=ir){return tr.encode(ur(t,e,r))}u(We,Ye),u(f,We);var hr=l(require("path")),fr=/[<>:"/\\|?*\u0000-\u001F]/,pr=/^(con|prn|aux|nul|com\d|lpt\d)$/i,dr=100,wr=/^\.+(\\|\/)|^\.+$/,mr=/\.+$/,yr=/[\u0000-\u001F\u0080-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069]/;function br(){return new RegExp(fr.source,"g")}function gr(){return new RegExp(yr.source,"g")}function Er(t){return t&&!(fr.test(t)||gr().test(t)||wr.test(t)||mr.test(t))}function xr(t){const e=t.split(hr.default.sep);return("/"===t[0]||e[0]&&hr.default.dirname(e[0])===e[0])&&e.shift(),e.every(Er)}function vr(t,e={}){const r=e.replacement||"!";if((fr.test(r)||yr.test(r))&&F("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(wr,r)).replace(br(),r)).replace(gr(),r)).replace(mr,""),r.length>0){"."===t[0]||"."!==t[0]||(t=r+t),"."===t[t.length-1]&&(t+=r)}t=pr.test(t)?t+r:t;const n="number"==typeof e.maxLength?e.maxLength:dr;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 Sr(t,e={}){const r=t.split(hr.default.sep);let n;("/"===t[0]||r[0]&&hr.default.dirname(r[0])===r[0])&&(n=r.shift());const s=r.map((t=>vr(t,e)));return void 0!==n&&s.unshift(n),s.join(hr.default.sep)}function $r(t,e=1){let r="";for(;e--;){const e=hr.default.extname(t);if(!e)break;r=e+r,t=hr.default.basename(t,e)}return r}function Ar(t){return t.split(".").length-1}var kr=require("util-ex");function Tr(t,e){if("string"!=typeof t)throw new A("modelName must be a string","isModelNameMatched",400);switch(typeof e){case"string":if((0,kr.isRegExpStr)(e)){const r=(e=(0,kr.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,kr.isRegExpStr)(r)){const n=(e=(0,kr.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 Or=require("lodash-es"),jr=require("util-ex");function Fr(t,e){if(e&&(e=Rr(e)),e){const r=Object.keys(e);if(r.length){const n=Object.values(e);return(0,jr.newFunction)("expression",r,`return ${t}`)(...n)}}return(0,jr.newFunction)("expression",[],`return ${t}`)()}var Nr=/^[a-zA-Z_$][0-9a-zA-Z_$]*$/,Ir=t=>Nr.test(t);function Rr(t){if(t){const e=Object.keys(t),r=e.length,n=e.filter((e=>Ir(e)&&null!==t[e]));if(r===n.length)return t;if(n.length)return t=(0,Or.pick)(t,n)}}function Pr(t){return t?Mr(t,[],""):[]}function Mr(t,e,r="."){return Array.isArray(t)?t.flatMap(((t,r)=>Mr(t,[...e,`[${r}]`]))):(n=t)&&n.constructor===Object?Object.entries(t).flatMap((([t,n])=>Mr(n,[...e,r+t]))):[e.join("")];var n}function qr(t){if(t<2)throw new A("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 Vr=l(require("path")),Br=l(require("fs"));function Ur(t){const e=Br.statSync(t,{throwIfNoEntry:!1});return e?.isFile()}function _r(t,e,r,n){const s=n?.signal,i=n?.exclude;let o;if(Vr.default.isAbsolute(t)?o=Ur(t)?t:Lr(Vr.default.basename(t),[Vr.default.dirname(t)],{extNames:r,exclude:i,signal:s}):(e||(e=["."]),o=Lr(t,e,{extNames:r,exclude:i,signal:s})),!o)throw new T(t,"loadFileFromPaths");{const t=o;o=Br.readFileSync(o),n&&(n.filepath=t)}return o}function Lr(t,e,{extNames:r,signal:n,exclude:s=[]}){let i;const o=r?r.map((e=>$r(t,Ar(e)))):void 0;"string"==typeof s&&(s=[s]);for(const a of e){if(n?.aborted)throw n.reason;const e=Vr.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)&&Ur(n)){i=n;break}}else if(!s.includes(e)&&Ur(e)){i=e;break}}return i}function zr(t,e,r,n,s){let i;"string"==typeof n?(i=n,n=void 0):i=n?.encoding??"utf8";return _r(t,e,r,n).toString(i)}function Dr(t,e,r){const n=[],s="string"==typeof t?[t]:[...t],i=new Set;for(;s.length>0;){if(r?.aborted)throw r.reason;const t=Jr(s.pop()),o=Vr.default.resolve(t);if(i.has(o))continue;i.add(o);const a=Br.statSync(t,{throwIfNoEntry:!1});if(a?.isDirectory()){const r=Br.readdirSync(t,{withFileTypes:!0});for(let i=0;i<r.length;i++){const o=r[i],a=Vr.default.join(t,o.name);o.isDirectory()?s.push(a):!o.isFile()||e&&!e(a)||n.push(a)}}}return n}function Jr(t){const e=Br.lstatSync(t,{throwIfNoEntry:!1});return e?.isSymbolicLink()&&(t=Br.readlinkSync(t)),t}var Wr=require("fs"),Hr=l(require("path")),Kr=require("load-config-file"),Gr=require("yaml"),Xr=require("yaml-types"),Zr=require("mime-type/with-db"),Yr=require("yaml"),Qr=[Xr.regexp];function tn(t){Array.isArray(t)||(t=[t]);for(const e of t){-1===Qr.indexOf(e)&&Qr.push(e)}}function en(t){return(0,Gr.parse)(t,{customTags:Qr})}function rn(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,Wr.readdirSync)(t,{withFileTypes:!0,recursive:!0});for(const n of r){const r=Hr.default.join(t,n.name);n.isFile()&&e(r,n)}}(t,((t,e)=>{if(s?.includes(t))return;const o=Hr.default.extname(t),a=(0,Wr.statSync)(t);if(i.includes(o)){if(n?.hasOwnProperty(t)&&a.mtimeMs<=n[t])return;r.push(t)}})),r}function nn(t,e){return rn(t,e).map((t=>Kr.Config.loadSync(t))).filter((t=>void 0!==t))}function sn(t,e,r=1){"."===t[0]&&r++;const n=$r(t,r);(!n||n.split(".").length<=1)&&(t+=".yaml");const s=Zr.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,Gr.stringify)(e)}const i=Hr.default.dirname(t);return(0,Wr.existsSync)(i)||(0,Wr.mkdirSync)(i,{recursive:!0}),(0,Wr.writeFileSync)(t,e,{encoding:"utf8"}),t}function on(t){t instanceof Date&&(t=t.toISOString());return function(t,e){return t?`'${e}'`:String(e)}("string"==typeof t,t)}function an(t,e){return t.map((t=>ln(t,e))).join(" AND ")}function cn(t,e){return t.map((t=>ln(t,e))).join(" OR ")}function un(t,e){const r=[];return Object.keys(e).forEach((n=>{const s=e[n];switch(n){case"$lt":case"<":r.push(`${t} < ${on(s)}`);break;case"<=":case"$lte":r.push(`${t} <= ${on(s)}`);break;case"$gt":case">":r.push(`${t} > ${on(s)}`);break;case"$gte":case">=":r.push(`${t} >= ${on(s)}`);break;case"$ne":case"!=":r.push(`${t} != ${on(s)}`);break;case"=":case"$eq":r.push(`${t} = ${on(s)}`);break;case"$in":r.push(`${t} IN (${s.map((t=>on(t))).join(", ")})`);break;case"$nin":r.push(`${t} NOT IN (${s.map((t=>on(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 ln(t,e){const r=[];if("function"!=typeof e&&(e=t=>t),Array.isArray(t))r.push(an(t,e));else for(const[n,s]of Object.entries(t))if("$and"===n)r.push(`(${an(t[n],e)})`);else if("$or"===n)r.push(`(${cn(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(un(e(n),s))}return r.length>1?r.join(" AND "):r[0]}function hn(t){const e=t.indexOf("://");if(e>0)return t.substring(0,e)}function fn(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 pn(t){const e=t.match(/^\s*[+]?(\d+(?:[.]\d+)?)\s*([TBMK])?\s*$/i);if(!e)throw new A("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 dn(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":" ")+dn(t,{level:r+1,visiting:n})}}Kr.Config.register([".yml",".yaml"],en),Kr.Config.register([".json"],(function(t){return JSON.parse(t)}));var wn=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}},mn=require("events-ex"),yn=32;function bn(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 gn=class{constructor(t){this._capacity=bn(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(bn(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 mn.EventEmitter{};function xn(t){return"function"==typeof t}function vn(){return"1"}var Sn=class{constructor(t,{initFn:e=vn,pauseFn:r,resumeFn:n,capacity:s=yn}={}){if(xn(r)!==xn(n))throw new Error("pauseFn and resumeFn must be both set for pausing");this.maxConcurrency=t,this.free=new gn(t),this.waiting=new gn(s),this.releaseEmitter=new En,this.useDefaultTokens=e===vn,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 $n(t,{timeUnit:e=1e3,uniformDistribution:r=!1}={}){const n=new Sn(r?1:t),s=r?e/t:e;return async function(){await n.acquire(),setTimeout((()=>n.release()),s)}}var An,kn=require("custom-ability"),Tn=require("property-manager"),Cn=require("util-ex"),On=0,jn=1,Fn=2,Nn=(t=>(t[t.MultiTask=On]="MultiTask",t[t.Cancelable=jn]="Cancelable",t[t.Priority=Fn]="Priority",t))(Nn||{}),In=((An=In||{})[An.MultiTask=1<<On]="MultiTask",An[An.Cancelable=1<<jn]="Cancelable",An[An.Priority=1<<Fn]="Priority",An),Rn=class t extends Tn.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),wn.has(r,t)}static run(t,e){const r=this.get(t);if(r)return r.run(e);throw new T(`${t} to run`,this.name)}static runSync(t,e){const r=this.get(t);if(r)return r.runSync(e);throw new T(`${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 T(`${t} to run`,this.name)}static runWithPosSync(t,...e){const r=this.get(t);if(r)return r.runWithPosSync(...e);throw new T(`${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);F("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),wn.has(e,t)}isStream(t){return this.stream}},Pn={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,Cn._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"}};Rn.defineProperties(Rn,Pn);var Mn=require("util-ex"),qn=class extends AbortController{constructor(t){super(),(0,Mn.defineProperty)(this,"parent",t)}abort(t,e){this.signal.aborted||("string"==typeof t&&(t=new O(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 O(e.reason||"aborted")}}},Vn=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 Sn(t-1)),e}isAborted(t){const e=this.hasAsyncFeature(On);let r=this.__task_aborter;if(r&&e){if(null==t)throw new A("Missing taskId",this.name+".isAborted",400);r=r[t]}return!r||r.signal.aborted}getRunningTask(t){const e=this.hasAsyncFeature(On);let r=this.__task_aborter;if(r&&e){if(null==t)throw new A("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(On)){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(On);if(!n&&r&&this.getRunningTask())throw new A("The task is running",this.name,429);const s=t?.aborter||new qn(this);if(!(s instanceof qn)){if(!(s instanceof AbortController))throw new A("aborter should be an AbortController",this.name,400);Object.setPrototypeOf(s,new qn(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(On)){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=Je({onStart:t=>{(0,Mn.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(On)){const t=e?.taskId;if(null==t)throw new A("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)}}};Vn.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},Vn.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};var Bn=(0,kn.createAbilityInjector)(Vn,"abort",{afterInjection:function(t,e){let r=t.prototype._asyncFeatures||0;r|=In.Cancelable,e&&(e.asyncFeatures&&(r|=e.asyncFeatures),e.maxTaskConcurrency>0&&(t.prototype._maxTaskConcurrency=e.maxTaskConcurrency)),t.prototype._asyncFeatures=r}});function Un(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 _n=require("lodash-es"),Ln=require("util-ex");async function zn(t,e,r){return Dn(Yn(t,e,r),e,r)}async function Dn(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 Jn(t,e,r){const[n,s]=t;if(!n&&"|"===s[0])return"choice: {"+function(t,e){const r=Yn(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=>Kn(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(Kn(e)){if(n.separator)throw new Error("Only one separator is allowed");return n.separator=!0,"separator:"+e}}}));return s}(s,r)+"}"}async function Wn([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 W.formatIf(o);return a?(i=a,s+":"+Gn(i)):void 0}async function Hn(t,e,r){let n=Jn(t,0,r);return n||(n=await Wn(t,e,r)),n}function Kn(t){const e=t[0];return('"'===e||"'"===e)&&t[t.length-1]===e}function Gn(t){return'"'+t.replace(/(?<!\\)"(?!\\)/g,'\\"')+'"'}function Xn(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,ts.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,_n.get)(r,i))return e+":"+i+', "'+i+'":'+i;if(Xn(i))return e+":"+i;try{const t=(0,Ln.newFunction)("async expression",[],`return ${i};`,Rr(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+":"+Gn(i)}function Yn(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 Qn(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 zn(i,e,r)),{command:s.trim(),args:o}}var ts=/^\s*\(\)|\(([a-zA-Z_$][\w\d$]*)(\s*,\s*([a-zA-Z_$][\w\d$]*))*\)=>/;u(h,f,module.exports);var es=class t extends Rn{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 F("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):F(`${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 j(n,s,r)}async func(t){const e=await this.fetch(t);if(t?.stream)return e;return await e.json()}},rs={...m};es.defineProperties(es,rs);var ns=class t extends Rn{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({}){}},ss={...m};ns.defineProperties(ns,ss);var is=require("events-ex"),os=class extends Rn{constructor(){super(...arguments),this._emitter=new is.EventEmitter,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},as=new os(Oe),cs=require("secondary-cache");function us({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 ls(t,e){let r=Rn.get(t);return r||(r=new Rn(t,{func:us,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 cs.Cache(e)),r}var hs=ls("lrucache"),fs=class extends es{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))}}},ps={methods:{type:"array",assign(t,e,r,n,s){s?.isExported||e.assignMethods(t)}}};fs.defineProperties(fs,ps);var ds=class extends fs{async fetch(t,e){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let r=t.id;return r||F("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)}},ws=class extends ds{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)}},ms=new ws(Ce),ys=require("util-ex"),bs=class extends ns{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,ys.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 T(e,this.name)}};bs.defineProperties(bs,{methods:{type:"array"}});var gs=class extends bs{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}}}static{this.SpecialRpcMethodNames=w}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}},Es=as.runSync(),xs=class t extends gs{constructor(){super(...arguments),this.name=Ce,this.description="subscribe server sent event",this.result="event",this.depends={[Oe]:as}}static get sse(){return this._sse||(this._sse=new Ie),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=Es.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)||Es.on(r,t.ebListener)}unforward(e){"string"==typeof e&&(e=[e]);for(const r of e)Es.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};F("event is required","sub",400)}$unsub({event:t}){if(t)return this.unforward(t),{event:t};F("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}}F("event or data is required","pub",400)}isStream(t){return"list"===this.getMethodFromParams(t)}},vs=new xs(Ce);function Ss(){as.register(),hs.register()}
1
+ "use strict";var t,e=Object.create,n=Object.defineProperty,r=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||n(t,c,{get:()=>e[c],enumerable:!(a=r(e,c))||a.enumerable});return t},c=(t,r,s)=>(s=null!=t?e(i(t)):{},a(!r&&t&&t.__esModule?s:n(s,"default",{value:t,enumerable:!0}),t)),u={};((t,e)=>{for(var r in e)n(t,r,{get:e[r],enumerable:!0})})(u,{AIArgProcessor:()=>Lr,AIChatRoles:()=>q,AIMessageTypes:()=>P,AIStream:()=>Ue,AITextGenerationFinishReasons:()=>R,AbortError:()=>A,AbortErrorCode:()=>v,ActionNames:()=>h,AlreadyExistsError:()=>k,AlreadyExistsErrorCode:()=>g,AsyncFeatureBits:()=>Or,AsyncFeatures:()=>Tr,BaseError:()=>E,CancelableAbility:()=>Ir,ChoiceArgProcessor:()=>Ur,ClientToolFuncSchema:()=>rs,ClientTools:()=>ns,CommonError:()=>x,ConfigFile:()=>Jn.Config,DefaultAsyncSemaphoreCapacity:()=>hr,ErrorCode:()=>d,EventBusName:()=>Ae,EventClient:()=>ms,EventName:()=>ke,EventServer:()=>xs,EventToolFunc:()=>as,FStringPromptTemplate:()=>re,FewShotPromptTemplate:()=>ce,FilenameReservedRegex:()=>cn,GolangPromptTemplate:()=>oe,HFBuiltins:()=>Dt,HFEnvironment:()=>Kt,HFInterpreter:()=>_t,HFTemplate:()=>Gt,HfPromptTemplate:()=>Yt,IntSet:()=>lr,InternalErrorCode:()=>m,NotFoundError:()=>S,NotFoundErrorCode:()=>b,NotImplementationError:()=>$,NotImplementedErrorCode:()=>y,PASSING_SCORE:()=>f,PromptExampleSelector:()=>W,PromptTemplate:()=>z,PromptTemplateTypes:()=>U,PromptTypes:()=>B,RStreamErrCode:()=>Fe,RateLimit:()=>gr,ReadableStreamError:()=>Me,RemoteToolFuncSchema:()=>p,ResClientTools:()=>ds,ResServerTools:()=>vs,ResponseRStreamErrCode:()=>Ie,SSEChannel:()=>Ce,SSEChannelAlreadyClosedErrCode:()=>je,Semaphore:()=>br,ServerToolFuncSchema:()=>is,ServerTools:()=>ss,TaskAbortController:()=>Fr,TemplateArgProcessor:()=>_r,ToolAsyncCancelableBit:()=>kr,ToolAsyncMultiTaskBit:()=>Sr,ToolAsyncPriorityBit:()=>Ar,ToolFunc:()=>jr,ToolFuncSchema:()=>Cr,WindowsReservedNameRegex:()=>un,XXHashAlgorithm:()=>rn,_lrucache:()=>ls,backendEventable:()=>Oe,base32768:()=>Xe,canonicalize:()=>Ze.canonicalize,countRegexMatches:()=>Rr,createAbilityInjector:()=>l.createAbilityInjector,createCallbacksTransformer:()=>Le,createEmptyReadableStream:()=>Pe,createEndWithRepetitionDetector:()=>In,createError:()=>O,createEventStreamTransformer:()=>Ve,createHfValueFunc:()=>Qt,createLRUCache:()=>fs,dateToText:()=>M,defaultTemplateFormat:()=>L,event:()=>cs,eventClient:()=>ys,eventServer:()=>$s,expandEnv:()=>he,expandObjEnv:()=>pe,extNameLevel:()=>En,fileIsExists:()=>Pn,filenameReservedRegex:()=>wn,filterValidFnScope:()=>Cn,formatISO:()=>C.formatISO,getAllEnumKeys:()=>Sn,getConfigFileNames:()=>Yn,getConfigs:()=>Qn,getKeysPath:()=>Nn,getMultiLevelExtname:()=>vn,getRealFilepath:()=>_n,getResponseErrorReadableStream:()=>Re,hfParse:()=>kt,hfTokenize:()=>tt,interpolateEnv:()=>fe,interpolateFString:()=>ee,interpolateGolangTemplate:()=>ie,isModelNameMatched:()=>$n,isValidFilename:()=>mn,isValidFilepath:()=>yn,isWebStream:()=>Ne,jsonFilterToWhere:()=>ir,jsonToMarkdownStr:()=>ur,loadFileFromPaths:()=>qn,loadTextFromPaths:()=>Bn,lrucache:()=>hs,makeToolFuncCancelable:()=>Mr,matchUrlProtocol:()=>or,memoize:()=>es,messagesToText:()=>V,mimeType:()=>Kn.mimeType,paramsSizeToScaleStr:()=>ar,parseCommand:()=>Zr,parseDateFormat:()=>j.parse,parseFString:()=>te,parseISO:()=>C.parseISO,parseJsJson:()=>On,parseObjectArgInfo:()=>Gr,parseObjectArgumentInfos:()=>Br,parseObjectArguments:()=>Vr,parseObjectArgumentsAsArgInfos:()=>Hr,parseYaml:()=>Xn,quoteStr:()=>Jr,reControlCharsRegex:()=>dn,readFilenamesRecursiveSync:()=>Un,readableFromAsyncIterable:()=>_e,registerCoreTools:()=>Ss,registerYamlTag:()=>Zn,sanitizeFilename:()=>bn,sanitizeFilepath:()=>gn,saveConfigFile:()=>tr,scaleStrToParamsSize:()=>cr,sortedValues:()=>ae,splitSentence:()=>Ee,stringifyYaml:()=>Gn.stringify,textToDate:()=>I,throwError:()=>T,toDate:()=>C.toDate,toDateTime:()=>F,trimStartOfStreamHelper:()=>Be,truncTo:()=>xe,uuid:()=>Ke,uuidNIL:()=>De.NIL,uuidParse:()=>De.parse,uuidStringify:()=>De.stringify,uuidValidate:()=>De.validate,uuidVersion:()=>De.version,uuidv1:()=>De.v1,uuidv4:()=>De.v4,uuidv5:()=>De.v5,wait:()=>$e,xxhash:()=>sn,xxhash32:()=>en,xxhash64:()=>nn,xxhashAsStr:()=>on}),module.exports=(t=u,a(n({},"__esModule",{value:!0}),t));var l=require("custom-ability"),f=.618,h=["get","post","put","delete","patch","list","res"],p={apiRoot:{type:"string",get(){return this._apiRoot??this.constructor.apiRoot},set(t){this._apiRoot=t}},action:{type:"string",assign:(t,e,n,r,s)=>t||"post"},fetchOptions:{type:"object"},allowExportFunc:{type:"boolean"}},w=require("abstract-error"),d=(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))(d||{}),m=500,y=501,b=404,g=409,v=499,E=class t extends w.AbstractError{static createErrorClass(e,n,r=t){return(0,w.createErrorClass)(e,n,r)}constructor(t,e,n){super(t,e);const r=this.constructor;null!=e?this.code=e:r.code?this.code=r.code:this.code=r.name,n?"string"==typeof n?this.name=n:Object.assign(this,n):"string"==typeof this.code?this.name=this.code:this.name=r.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 n=new t(e.message);return n.code=e.code,n.data=e.data,n.caller=e.caller,n.message=e.error,n.stack=e.stack,n}},x=class extends E{constructor(t,e,n=m){super(t,n,e)}},$=class extends x{constructor(t,e){t||(t="Not Implementation."),super(t,e,501)}};x[y]=$;var S=class extends x{static{this.code=b}constructor(t,e){super(`Could not find ${t}.`,e,b),this.data={what:t}}};x[b]=S;var k=class extends x{static{this.code=g}constructor(t,e){super(`The ${t} already exists.`,e,g),this.data={what:t}}};x[g]=k;var A=class extends x{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,n=m){const r=new(x[n]||x)(t,e,n);return"number"!=typeof r.code&&(r.code=n),r}function T(t,e,n=m){throw O(t,e,n)}x[v]=A;var j=require("date-fns"),C=require("date-fns"),N="MMMM d, y 'at' h:m:s b 'GMT'x";function F(t){let e;try{"string"==typeof t?e=(0,j.parseISO)(t):"number"==typeof t?e=new Date(t):t instanceof Date&&(e=t)}catch(t){console.error(t)}return e}function I(t,e=N){return(0,j.parse)(t,e,new Date)}function M(t,e=N){return(0,j.format)(t,e)}var R=["stop","length","content-filter","tool-calls","abort","error","other",null],P=["human","ai","generic","system","tool"],q=["user","assistant","system","tool","tool_calls"];function V(t){let e="";for(const n of t)if(n.content){e+=n.role.toLowerCase()+":";let t=n.createdAt;if(t){const n=F(t);n&&(e+=" ["+M(n)+"]")}e+=" "+n.content+"\n"}return e}var B=["chat","char","plan"],U=["internal","hf","fill"],_=require("custom-factory");var L="default",z=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 n=e.templateFormat||L,r=t.get(n);return r.isTemplate!==t.isTemplate&&r.isTemplate(e)}}filterData(t){return Array.isArray(this.inputVariables)&&(t=Object.fromEntries(Object.entries(t).filter((([t])=>this.inputVariables.includes(t))))),t}constructor(e,n){"string"==typeof e?(n||(n={}),n.template=e):e&&(e=(n=e).template);const{templateFormat:r}=n||{};if(super(n),this.constructor===t){const e=t.get(r||L);if(e)return Reflect.construct(e,arguments);throw new x(`Prompt template type ${r} 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 n=this.data;if(e={...n,...e},n)for(const[t,r]of Object.entries(n))e[t]===r&&"function"==typeof r&&(delete e[t],e[t]=await r(e));for(const[n,r]of Object.entries(e))r instanceof t&&(delete e[n],e[n]=await r.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 n={template:e.template,data:e.data,inputVariables:e.inputVariables,compiledTemplate:e.compiledTemplate};var r;return e.templateFormat&&t.get(e.templateFormat)!==this.constructor&&(n.templateFormat=e.templateFormat),r=n,n=Object.keys(r).reduce(((t,e)=>{const n=r[e];return null!=n&&(t[e]=n),t}),{}),n}};function J(t){return(e=t)&&"function"==typeof e[Symbol.iterator]?async function*(t){const e=t[Symbol.iterator]();let n;try{for(;;){n=!1;const t=e.next();if(n=!0,t.done)return n=!1,await t.value;yield await t.value}}finally{n&&await(e.return?.().value)}}(t):t;var e}var D=!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=>{D=t}));var W=class{constructor(t,e){this.initialize(t,e)}initialize(t,e){const n=e?.maxLength;var r;n>0&&(this.maxLength=n),void 0!==e?.threshold&&(!0===e.threshold?this.threshold=.5:!1!==e.threshold&&(this.threshold=e.threshold)),this.examples=(r=t,D?r:J(r))}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 n of t){const t="number"==typeof this.threshold?Math.random():void 0;if(this.selectExample(n,t)){if(--e<0)break;yield n}}}async*[Symbol.asyncIterator](){yield*this.selectExamples()}},K=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"}),G=Object.freeze({set:K.Set,for:K.For,in:K.In,is:K.Is,if:K.If,else:K.Else,endif:K.EndIf,elif:K.ElseIf,endfor:K.EndFor,and:K.And,or:K.Or,not:K.Not,"not in":K.NotIn,macro:K.Macro,endmacro:K.EndMacro,true:K.BooleanLiteral,false:K.BooleanLiteral,True:K.BooleanLiteral,False:K.BooleanLiteral}),H=class{constructor(t,e){this.value=t,this.type=e}};function Z(t){return/\w/.test(t)}function X(t){return/[0-9]/.test(t)}var Y=[["{%",K.OpenStatement],["%}",K.CloseStatement],["{{",K.OpenExpression],["}}",K.CloseExpression],["(",K.OpenParen],[")",K.CloseParen],["{",K.OpenCurlyBracket],["}",K.CloseCurlyBracket],["[",K.OpenSquareBracket],["]",K.CloseSquareBracket],[",",K.Comma],[".",K.Dot],[":",K.Colon],["|",K.Pipe],["<=",K.ComparisonBinaryOperator],[">=",K.ComparisonBinaryOperator],["==",K.ComparisonBinaryOperator],["!=",K.ComparisonBinaryOperator],["<",K.ComparisonBinaryOperator],[">",K.ComparisonBinaryOperator],["+",K.AdditiveBinaryOperator],["-",K.AdditiveBinaryOperator],["*",K.MultiplicativeBinaryOperator],["/",K.MultiplicativeBinaryOperator],["%",K.MultiplicativeBinaryOperator],["=",K.Equals]],Q=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function tt(t,e={}){const n=[],r=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(r[s]);)if("\\"!==r[s]){if(e+=r[s++],s>=r.length)throw new SyntaxError("Unexpected end of input")}else{if(++s,s>=r.length)throw new SyntaxError("Unexpected end of input");const t=r[s++],n=Q.get(t);if(void 0===n)throw new SyntaxError(`Unexpected escaped character: ${t}`);e+=n}return e};t:for(;s<r.length;){const t=n.at(-1)?.type;if(void 0===t||t===K.CloseStatement||t===K.CloseExpression){let t="";for(;s<r.length&&("{"!==r[s]||"%"!==r[s+1]&&"{"!==r[s+1]);)t+=r[s++];if(t.length>0){n.push(new H(t,K.Text));continue}}i((t=>/\s/.test(t)));const e=r[s];if("-"===e||"+"===e){const t=n.at(-1)?.type;if(t===K.Text||void 0===t)throw new SyntaxError(`Unexpected character: ${e}`);switch(t){case K.Identifier:case K.NumericLiteral:case K.BooleanLiteral:case K.StringLiteral:case K.CloseParen:case K.CloseSquareBracket:break;default:{++s;const t=i(X);n.push(new H(`${e}${t}`,t.length>0?K.NumericLiteral:K.UnaryOperator));continue}}}for(const[t,e]of Y){if(r.slice(s,s+t.length)===t){n.push(new H(t,e)),s+=t.length;continue t}}if("'"!==e&&'"'!==e)if(X(e)){const t=i(X);n.push(new H(t,K.NumericLiteral))}else{if(!Z(e))throw new SyntaxError(`Unexpected character: ${e}`);{const t=i(Z),e=Object.hasOwn(G,t)?G[t]:K.Identifier;e===K.In&&n.at(-1)?.type===K.Not?(n.pop(),n.push(new H("not in",K.NotIn))):n.push(new H(t,e))}}else{++s;const t=i((t=>t!==e));n.push(new H(t,K.StringLiteral)),++s}}return n}var et=class{constructor(){this.type="Statement"}},nt=class extends et{constructor(t){super(),this.body=t,this.type="Program"}},rt=class extends et{constructor(t,e,n){super(),this.test=t,this.body=e,this.alternate=n,this.type="If"}},st=class extends et{constructor(t,e,n,r){super(),this.loopvar=t,this.iterable=e,this.body=n,this.defaultBlock=r,this.type="For"}},it=class extends et{constructor(t,e){super(),this.assignee=t,this.value=e,this.type="Set"}},ot=class extends et{constructor(t,e,n){super(),this.name=t,this.args=e,this.body=n,this.type="Macro"}},at=class extends et{constructor(){super(...arguments),this.type="Expression"}},ct=class extends at{constructor(t,e,n){super(),this.object=t,this.property=e,this.computed=n,this.type="MemberExpression"}},ut=class extends at{constructor(t,e){super(),this.callee=t,this.args=e,this.type="CallExpression"}},lt=class extends at{constructor(t){super(),this.value=t,this.type="Identifier"}},ft=class extends at{constructor(t){super(),this.value=t,this.type="Literal"}},ht=class extends ft{constructor(){super(...arguments),this.type="NumericLiteral"}},pt=class extends ft{constructor(){super(...arguments),this.type="StringLiteral"}},wt=class extends ft{constructor(){super(...arguments),this.type="BooleanLiteral"}},dt=class extends ft{constructor(){super(...arguments),this.type="ArrayLiteral"}},mt=class extends ft{constructor(){super(...arguments),this.type="TupleLiteral"}},yt=class extends ft{constructor(){super(...arguments),this.type="ObjectLiteral"}},bt=class extends at{constructor(t,e,n){super(),this.operator=t,this.left=e,this.right=n,this.type="BinaryExpression"}},gt=class extends at{constructor(t,e){super(),this.operand=t,this.filter=e,this.type="FilterExpression"}},vt=class extends at{constructor(t,e){super(),this.iterable=t,this.test=e,this.type="SelectExpression"}},Et=class extends at{constructor(t,e,n){super(),this.operand=t,this.negate=e,this.test=n,this.type="TestExpression"}},xt=class extends at{constructor(t,e){super(),this.operator=t,this.argument=e,this.type="UnaryExpression"}},$t=class extends at{constructor(t=void 0,e=void 0,n=void 0){super(),this.start=t,this.stop=e,this.step=n,this.type="SliceExpression"}},St=class extends at{constructor(t,e){super(),this.key=t,this.value=e,this.type="KeywordArgumentExpression"}};function kt(t){const e=new nt([]);let n=0;function r(e,r){const s=t[n++];if(!s||s.type!==e)throw new Error(`Parser Error: ${r}. ${s.type} !== ${e}.`);return s}function s(){let e;switch(t[n].type){case K.Text:e=new pt(r(K.Text,"Expected text token").value);break;case K.OpenStatement:e=function(){let e;switch(r(K.OpenStatement,"Expected opening statement token"),t[n].type){case K.Set:++n,e=a(),r(K.CloseStatement,"Expected closing statement token");break;case K.If:++n,e=c(),r(K.OpenStatement,"Expected {% token"),r(K.EndIf,"Expected endif token"),r(K.CloseStatement,"Expected %} token");break;case K.Macro:++n,e=function(){const t=E();if("Identifier"!==t.type)throw new SyntaxError("Expected identifier following macro statement");const e=y();r(K.CloseStatement,"Expected closing statement token");const n=[];for(;i(K.OpenStatement,K.EndMacro);)n.push(s());return new ot(t,e,n)}(),r(K.OpenStatement,"Expected {% token"),r(K.EndMacro,"Expected endmacro token"),r(K.CloseStatement,"Expected %} token");break;case K.For:++n,e=function(){const t=u(!0);if(!(t instanceof lt||t instanceof mt))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${t.type} instead`);r(K.In,"Expected `in` keyword following loop variable");const e=l();r(K.CloseStatement,"Expected closing statement token");const a=[];for(;i(K.OpenStatement,K.EndFor)&&i(K.OpenStatement,K.Else);)a.push(s());const c=[];if(o(K.OpenStatement,K.Else))for(++n,++n,r(K.CloseStatement,"Expected closing statement token");i(K.OpenStatement,K.EndFor);)c.push(s());return new st(t,e,a,c)}(),r(K.OpenStatement,"Expected {% token"),r(K.EndFor,"Expected endfor token"),r(K.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${t[n].type} ${t[n].value}`)}return e}(),e.isStatement=!0;break;case K.OpenExpression:e=function(){r(K.OpenExpression,"Expected opening expression token");const t=l();return r(K.CloseExpression,"Expected closing expression token"),t}(),e.isStatement=!0;break;default:throw new SyntaxError(`Unexpected token type: ${t[n].type}`)}return e}function i(...e){return n+e.length<=t.length&&e.some(((e,r)=>e!==t[n+r].type))}function o(...e){return n+e.length<=t.length&&e.every(((e,r)=>e===t[n+r].type))}function a(){const t=l();if(o(K.Equals)){++n;const e=a();return new it(t,e)}return t}function c(){const e=l();r(K.CloseStatement,"Expected closing statement token");const i=[],a=[];for(;t[n]?.type!==K.OpenStatement||t[n+1]?.type!==K.ElseIf&&t[n+1]?.type!==K.Else&&t[n+1]?.type!==K.EndIf;)i.push(s());if(t[n]?.type===K.OpenStatement&&t[n+1]?.type!==K.EndIf)if(++n,o(K.ElseIf))r(K.ElseIf,"Expected elseif token"),a.push(c());else for(r(K.Else,"Expected else token"),r(K.CloseStatement,"Expected closing statement token");t[n]?.type!==K.OpenStatement||t[n+1]?.type!==K.EndIf;)a.push(s());return new rt(e,i,a)}function u(t=!1){const e=t?E:l,r=[e()],s=o(K.Comma);for(;s&&(++n,r.push(e()),o(K.Comma)););return s?new mt(r):r[0]}function l(){return function(){const t=f();if(o(K.If)){++n;const e=f();if(o(K.Else)){++n;const r=f();return new rt(e,[t],[r])}return new vt(t,e)}return t}()}function f(){let e=h();for(;o(K.Or);){const r=t[n];++n;const s=h();e=new bt(r,e,s)}return e}function h(){let e=p();for(;o(K.And);){const r=t[n];++n;const s=p();e=new bt(r,e,s)}return e}function p(){let e;for(;o(K.Not);){const r=t[n];++n;const s=p();e=new xt(r,s)}return e??function(){let e=w();for(;o(K.ComparisonBinaryOperator)||o(K.In)||o(K.NotIn);){const r=t[n];++n;const s=w();e=new bt(r,e,s)}return e}()}function w(){let e=g();for(;o(K.AdditiveBinaryOperator);){const r=t[n];++n;const s=g();e=new bt(r,e,s)}return e}function d(){const e=function(){let e=E();for(;o(K.Dot)||o(K.OpenSquareBracket);){const s=t[n];let i;++n;const o=s.type!==K.Dot;if(o)i=b(),r(K.CloseSquareBracket,"Expected closing square bracket");else if(i=E(),"Identifier"!==i.type)throw new SyntaxError("Expected identifier following dot operator");e=new ct(e,i,o)}return e}();return o(K.OpenParen)?m(e):e}function m(t){let e=new ut(t,y());return o(K.OpenParen)&&(e=m(e)),e}function y(){r(K.OpenParen,"Expected opening parenthesis for arguments list");const t=function(){const t=[];for(;!o(K.CloseParen);){let e=l();if(o(K.Equals)){if(++n,!(e instanceof lt))throw new SyntaxError("Expected identifier for keyword argument");const t=l();e=new St(e,t)}t.push(e),o(K.Comma)&&++n}return t}();return r(K.CloseParen,"Expected closing parenthesis for arguments list"),t}function b(){const t=[];let e=!1;for(;!o(K.CloseSquareBracket);)o(K.Colon)?(t.push(void 0),++n,e=!0):(t.push(l()),o(K.Colon)&&(++n,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 $t(...t)}return t[0]}function g(){let e=v();for(;o(K.MultiplicativeBinaryOperator);){const r=t[n];++n;const s=v();e=new bt(r,e,s)}return e}function v(){let t=function(){let t=d();for(;o(K.Pipe);){++n;let e=E();if(!(e instanceof lt))throw new SyntaxError("Expected identifier for the filter");o(K.OpenParen)&&(e=m(e)),t=new gt(t,e)}return t}();for(;o(K.Is);){++n;const e=o(K.Not);e&&++n;let r=E();if(r instanceof wt&&(r=new lt(r.value.toString())),!(r instanceof lt))throw new SyntaxError("Expected identifier for the test");t=new Et(t,e,r)}return t}function E(){const e=t[n];switch(e.type){case K.NumericLiteral:return++n,new ht(Number(e.value));case K.StringLiteral:return++n,new pt(e.value);case K.BooleanLiteral:return++n,new wt("true"===e.value.toLowerCase());case K.Identifier:return++n,new lt(e.value);case K.OpenParen:{++n;const e=u();if(t[n].type!==K.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${t[n].type} instead`);return++n,e}case K.OpenSquareBracket:{++n;const t=[];for(;!o(K.CloseSquareBracket);)t.push(l()),o(K.Comma)&&++n;return++n,new dt(t)}case K.OpenCurlyBracket:{++n;const t=new Map;for(;!o(K.CloseCurlyBracket);){const e=l();r(K.Colon,"Expected colon between key and value in object literal");const s=l();t.set(e,s),o(K.Comma)&&++n}return++n,new yt(t)}default:throw new SyntaxError(`Unexpected token: ${e.type}`)}}for(;n<t.length;)e.body.push(s());return e}function At(t,e,n=1){void 0===e&&(e=t,t=0);const r=[];for(let s=t;s<e;s+=n)r.push(s);return r}function Ot(t,e,n,r=1){const s=Math.sign(r);s>=0?(e=(e??=0)<0?Math.max(t.length+e,0):Math.min(e,t.length),n=(n??=t.length)<0?Math.max(t.length+n,0):Math.min(n,t.length)):(e=(e??=t.length-1)<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),n=(n??=-1)<-1?Math.max(t.length+n,-1):Math.min(n,t.length-1));const i=[];for(let o=e;s*o<s*n;o+=r)i.push(t[o]);return i}function Tt(t){return t.replace(/\b\w/g,(t=>t.toUpperCase()))}var jt=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}},Ct=class extends jt{constructor(){super(...arguments),this.type="NumericValue"}},Nt=class t extends jt{constructor(){super(...arguments),this.type="StringValue",this.builtins=new Map([["upper",new qt((()=>new t(this.value.toUpperCase())))],["lower",new qt((()=>new t(this.value.toLowerCase())))],["strip",new qt((()=>new t(this.value.trim())))],["title",new qt((()=>new t(Tt(this.value))))],["length",new Ct(this.value.length)],["rstrip",new qt((()=>new t(this.value.trimEnd())))],["lstrip",new qt((()=>new t(this.value.trimStart())))]])}},Ft=class extends jt{constructor(){super(...arguments),this.type="BooleanValue"}},It=class extends jt{constructor(t,e){super(t),this.orgValue=e,this.type="ObjectValue",this.builtins=new Map([["get",new qt((([t,e])=>{if(!(t instanceof Nt))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new Vt}))],["items",new qt((()=>new Rt(Array.from(this.value.entries()).map((([t,e])=>new Rt([new Nt(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)}},Mt=class extends It{constructor(){super(...arguments),this.type="KeywordArgumentsValue"}},Rt=class extends jt{constructor(){super(...arguments),this.type="ArrayValue",this.builtins=new Map([["length",new Ct(this.value.length)]])}__bool__(){return new Ft(this.value.length>0)}},Pt=class extends Rt{constructor(){super(...arguments),this.type="TupleValue"}},qt=class extends jt{constructor(){super(...arguments),this.type="FunctionValue"}},Vt=class extends jt{constructor(){super(...arguments),this.type="NullValue"}},Bt=class extends jt{constructor(){super(...arguments),this.type="UndefinedValue"}},Ut=class{constructor(t){this.parent=t,this.variables=new Map([["namespace",new qt((t=>{if(0===t.length)return new It(new Map);if(1!==t.length||!(t[0]instanceof It))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 qt],["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 Rt||t instanceof Nt],["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,Lt(e))}declareVariable(t,e){if(this.variables.has(t))throw new SyntaxError(`Variable already declared: ${t}`);return this.variables.set(t,e),e}setVariable(t,e){return this.variables.set(t,e),e}resolve(t){if(this.variables.has(t))return this;if(this.parent)return this.parent.resolve(t);throw new Error(`Unknown variable: ${t}`)}lookupVariable(t){try{return this.resolve(t).variables.get(t)??new Bt}catch{return new Bt}}},_t=class{constructor(t){this.global=t??new Ut}run(t){return this.evaluate(t,this.global)}evaluateBinaryExpression(t,e){const n=this.evaluate(t.left,e);switch(t.operator.value){case"and":return n.__bool__().value?this.evaluate(t.right,e):n;case"or":return n.__bool__().value?n:this.evaluate(t.right,e)}const r=this.evaluate(t.right,e);switch(t.operator.value){case"==":return new Ft(n.value==r.value);case"!=":return new Ft(n.value!=r.value)}if(n instanceof Bt||r instanceof Bt)throw new Error("Cannot perform operation on undefined values");if(n instanceof Vt||r instanceof Vt)throw new Error("Cannot perform operation on null values");if(n instanceof Ct&&r instanceof Ct)switch(t.operator.value){case"+":return new Ct(n.value+r.value);case"-":return new Ct(n.value-r.value);case"*":return new Ct(n.value*r.value);case"/":return new Ct(n.value/r.value);case"%":return new Ct(n.value%r.value);case"<":return new Ft(n.value<r.value);case">":return new Ft(n.value>r.value);case">=":return new Ft(n.value>=r.value);case"<=":return new Ft(n.value<=r.value)}else if(n instanceof Rt&&r instanceof Rt){if("+"===t.operator.value)return new Rt(n.value.concat(r.value))}else if(r instanceof Rt){const e=void 0!==r.value.find((t=>t.value===n.value));switch(t.operator.value){case"in":return new Ft(e);case"not in":return new Ft(!e)}}if((n instanceof Nt||r instanceof Nt)&&"+"===t.operator.value)return new Nt(n.toString()+r.toString());if(n instanceof Nt&&r instanceof Nt)switch(t.operator.value){case"in":return new Ft(r.value.includes(n.value));case"not in":return new Ft(!r.value.includes(n.value))}if(n instanceof Nt&&r instanceof It)switch(t.operator.value){case"in":return new Ft(r.value.has(n.value));case"not in":return new Ft(!r.value.has(n.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${n.type} and ${r.type}`)}evaluateArguments(t,e){const n=[],r=new Map;for(const s of t)if("KeywordArgumentExpression"===s.type){const t=s;r.set(t.key.value,this.evaluate(t.value,e))}else{if(r.size>0)throw new Error("Positional arguments must come before keyword arguments");n.push(this.evaluate(s,e))}return[n,r]}evaluateFilterExpression(t,e){const n=this.evaluate(t.operand,e);if("Identifier"===t.filter.type){const r=t.filter,s=e.lookupVariable(r.value);if(s instanceof qt)return s.value([n],e);if(n instanceof Rt)switch(r.value){case"list":return n;case"first":return n.value[0];case"last":return n.value[n.value.length-1];case"length":return new Ct(n.value.length);case"reverse":return new Rt(n.value.reverse());case"sort":return new Rt(n.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: ${r.value}`)}else if(n instanceof Nt)switch(r.value){case"length":return new Ct(n.value.length);case"upper":return new Nt(n.value.toUpperCase());case"lower":return new Nt(n.value.toLowerCase());case"title":return new Nt(Tt(n.value));case"capitalize":return new Nt(n.value.charAt(0).toUpperCase()+n.value.slice(1));case"trim":return new Nt(n.value.trim());case"trimStart":return new Nt(n.value.trimStart());case"trimEnd":return new Nt(n.value.trimEnd());case"indent":return new Nt(n.value.split("\n").map(((t,e)=>0===e||0===t.length?t:" "+t)).join("\n"));case"string":return n;default:throw new Error(`Unknown StringValue filter: ${r.value}`)}else{if(n instanceof Ct){if("abs"===r.value)return new Ct(Math.abs(n.value));throw new Error(`Unknown NumericValue filter: ${r.value}`)}if(n instanceof It)switch(r.value){case"items":return new Rt(Array.from(n.value.entries()).map((([t,e])=>new Rt([new Nt(t),e]))));case"length":return new Ct(n.value.size);case"string":return new Nt(n.toString());default:throw new Error(`Unknown ObjectValue filter: ${r.value}`)}}throw new Error(`Cannot apply filter "${r.value}" to type: ${n.type}`)}if("CallExpression"===t.filter.type){const r=t.filter;if("Identifier"!==r.callee.type)throw new Error(`Unknown filter: ${r.callee.type}`);const s=r.callee.value,i=e.lookupVariable(s);if(i instanceof qt){const[t,s]=this.evaluateArguments(r.args,e);return s.size>0&&t.push(new Mt(s)),i.value([n,...t],e)}if(n instanceof Rt){switch(s){case"selectattr":{if(n.value.some((t=>!(t instanceof It))))throw new Error("`selectattr` can only be applied to array of objects");if(r.args.some((t=>"StringLiteral"!==t.type)))throw new Error("arguments of `selectattr` must be strings");const[t,s,i]=r.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=n.value.filter((e=>{const n=e.value.get(t.value);return!!n&&o(n,i)}));return new Rt(a)}case"map":{const[,t]=this.evaluateArguments(r.args,e);if(t.has("attribute")){const e=t.get("attribute");if(!(e instanceof Nt))throw new Error("attribute must be a string");const r=t.get("default"),s=n.value.map((t=>{if(!(t instanceof It))throw new Error("items in map must be an object");return t.value.get(e.value)??r??new Bt}));return new Rt(s)}throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${s}`)}if(n instanceof Nt){if("indent"===s){const[t,s]=this.evaluateArguments(r.args,e),i=t.at(0)??s.get("width")??new Ct(4);if(!(i instanceof Ct))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=n.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 Nt(l.join("\n"))}throw new Error(`Unknown StringValue filter: ${s}`)}throw new Error(`Cannot apply filter "${s}" to type: ${n.type}`)}throw new Error(`Unknown filter: ${t.filter.type}`)}evaluateTestExpression(t,e){const n=this.evaluate(t.operand,e),r=e.tests.get(t.test.value);if(!r)throw new Error(`Unknown test: ${t.test.value}`);const s=r(n);return new Ft(t.negate?!s:s)}evaluateUnaryExpression(t,e){const n=this.evaluate(t.argument,e);if("not"===t.operator.value)return new Ft(!n.value);throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let n="";for(const r of t){const t=this.evaluate(r,e);"NullValue"!==t.type&&"UndefinedValue"!==t.type&&(n+=t)}return new Nt(n)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){const[n,r]=this.evaluateArguments(t.args,e);r.size>0&&n.push(new Mt(r));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(n,e)}evaluateSliceExpression(t,e,n){if(!(t instanceof Rt||t instanceof Nt))throw new Error("Slice object must be an array or string");const r=this.evaluate(e.start,n),s=this.evaluate(e.stop,n),i=this.evaluate(e.step,n);if(!(r instanceof Ct||r instanceof Bt))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof Ct||s instanceof Bt))throw new Error("Slice stop must be numeric or undefined");if(!(i instanceof Ct||i instanceof Bt))throw new Error("Slice step must be numeric or undefined");return t instanceof Rt?new Rt(Ot(t.value,r.value,s.value,i.value)):new Nt(Ot(Array.from(t.value),r.value,s.value,i.value).join(""))}evaluateMemberExpression(t,e){const n=this.evaluate(t.object,e);let r,s;if(t.computed){if("SliceExpression"===t.property.type)return this.evaluateSliceExpression(n,t.property,e);r=this.evaluate(t.property,e)}else r=new Nt(t.property.value);if(n instanceof It){if(!(r instanceof Nt))throw new Error(`Cannot access property with non-string: got ${r.type}`);s=n.value.get(r.value)??n.builtins.get(r.value)}else if(n instanceof Rt||n instanceof Nt)if(r instanceof Ct)s=n.value.at(r.value),n instanceof Nt&&(s=new Nt(n.value.at(r.value)));else{if(!(r instanceof Nt))throw new Error(`Cannot access property with non-string/non-number: got ${r.type}`);s=n.builtins.get(r.value)}else{if(!(r instanceof Nt))throw new Error(`Cannot access property with non-string: got ${r.type}`);s=n.builtins.get(r.value)}return s instanceof jt?s:new Bt}evaluateSet(t,e){const n=this.evaluate(t.value,e);if("Identifier"===t.assignee.type){const r=t.assignee.value;e.setVariable(r,n)}else{if("MemberExpression"!==t.assignee.type)throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(t.assignee)}`);{const r=t.assignee,s=this.evaluate(r.object,e);if(!(s instanceof It))throw new Error("Cannot assign to member of non-object");if("Identifier"!==r.property.type)throw new Error("Cannot assign to member with non-identifier property");s.value.set(r.property.value,n)}}return new Vt}evaluateIf(t,e){const n=this.evaluate(t.test,e);return this.evaluateBlock(n.__bool__().value?t.body:t.alternate,e)}evaluateFor(t,e){const n=new Ut(e);let r,s;if("SelectExpression"===t.iterable.type){const e=t.iterable;s=this.evaluate(e.iterable,n),r=e.test}else s=this.evaluate(t.iterable,n);if(!(s instanceof Rt))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 Ut(n),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 n=c;if(e.value.length!==n.value.length)throw new Error(`Too ${e.value.length>n.value.length?"few":"many"} items to unpack`);u=t=>{for(let r=0;r<e.value.length;++r){if("Identifier"!==e.value[r].type)throw new Error(`Cannot unpack non-identifier type: ${e.value[r].type}`);t.setVariable(e.value[r].value,n.value[r])}}}}if(r){u(a);if(!this.evaluate(r,a).__bool__().value)continue}i.push(c),o.push(u)}let a="",c=!0;for(let e=0;e<i.length;++e){const r=new Map([["index",new Ct(e+1)],["index0",new Ct(e)],["revindex",new Ct(i.length-e)],["revindex0",new Ct(i.length-e-1)],["first",new Ft(0===e)],["last",new Ft(e===i.length-1)],["length",new Ct(i.length)],["previtem",e>0?i[e-1]:new Bt],["nextitem",e<i.length-1?i[e+1]:new Bt]]);n.setVariable("loop",new It(r)),o[e](n);a+=this.evaluateBlock(t.body,n).value,c=!1}if(c){a+=this.evaluateBlock(t.defaultBlock,n).value}return new Nt(a)}evaluateMacro(t,e){return e.setVariable(t.name.value,new qt(((e,n)=>{const r=new Ut(n);let s;e=e.slice(),"KeywordArgumentsValue"===e.at(-1)?.type&&(s=e.pop());for(let n=0;n<t.args.length;++n){const i=t.args[n],o=e[n];if("Identifier"===i.type){const t=i;if(!o)throw new Error(`Missing positional argument: ${t.value}`);r.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,r);r.setVariable(t.key.value,e)}}}return this.evaluateBlock(t.body,r)}))),new Vt}evaluate(t,e){if(void 0===t)return new Bt;switch(t.type){case"Program":return this.evalProgram(t,e);case"Set":return this.evaluateSet(t,e);case"If":return this.evaluateIf(t,e);case"For":return this.evaluateFor(t,e);case"Macro":return this.evaluateMacro(t,e);case"NumericLiteral":return new Ct(Number(t.value));case"StringLiteral":return new Nt(t.value);case"BooleanLiteral":return new Ft(t.value);case"ArrayLiteral":return new Rt(t.value.map((t=>this.evaluate(t,e))));case"TupleLiteral":return new Pt(t.value.map((t=>this.evaluate(t,e))));case"ObjectLiteral":{const n=new Map;for(const[r,s]of t.value){const t=this.evaluate(r,e);if(!(t instanceof Nt))throw new Error(`Object keys must be strings: got ${t.type}`);n.set(t.value,this.evaluate(s,e))}return new It(n,t.value)}case"Identifier":return this.evaluateIdentifier(t,e);case"CallExpression":return this.evaluateCallExpression(t,e);case"MemberExpression":return this.evaluateMemberExpression(t,e);case"UnaryExpression":return this.evaluateUnaryExpression(t,e);case"BinaryExpression":return this.evaluateBinaryExpression(t,e);case"FilterExpression":return this.evaluateFilterExpression(t,e);case"TestExpression":return this.evaluateTestExpression(t,e);default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function Lt(t){switch(typeof t){case"number":return new Ct(t);case"string":return new Nt(t);case"boolean":return new Ft(t);case"undefined":return new Bt;case"object":return null===t?new Vt:Array.isArray(t)?new Rt(t.map(Lt)):new It(new Map(Object.entries(t).map((([t,e])=>[t,Lt(e)]))),t);case"function":return new qt(((e,n)=>{const r=e.map((t=>zt(t)));return Lt(t(...r)??null)}));default:throw new Error(`Cannot convert to runtime value: ${t}`)}}function zt(t){let e=t;if(Array.isArray(t))e=t.map((t=>zt(t)));else if(t instanceof Map)e={},t.forEach(((t,n)=>{e[n]=zt(t)}));else switch(t.type){case"NullValue":e=null;break;case"UndefinedValue":e=void 0;break;case"ArrayValue":e=t.value.map((t=>zt(t)));break;case"KeywordArgumentsValue":case"ObjectValue":e=t.orgValue?t.orgValue:zt(t.value),"KeywordArgumentsValue"===t.type&&Object.setPrototypeOf(e,{jinja_kargs:!0});break;default:t.type&&(e=t.value)}return e}function Jt(t,e=0){return Math.floor(Math.random()*(t-e+1))+e}var Dt={randomInt:Jt,select:function(t,e){if(Array.isArray(t)||"string"==typeof t)return void 0===e?e=Jt(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 n=Object.keys(t);e=n[Jt(n.length-1)]}return t[e]}},tojson:function(t,e,n){return e&&"object"==typeof e&&(e.depth&&(n=e.depth),e=e.indent),Wt(t,e,n)}};function Wt(t,e,n){let r="";const s=n??0;if(null===t)r="null";else{const n=typeof t;switch(n){case"undefined":r="null";case"number":case"string":case"boolean":return JSON.stringify(t);case"object":{const n=e?" ".repeat(e):"",r="\n"+n.repeat(s),i=r+n;if(Array.isArray(t)){const n=t.map((t=>Wt(t,e,s+1)));return e?`[${i}${n.join(`,${i}`)}${r}]`:`[${n.join(", ")}]`}{const n=Array.from(Object.entries(t)).map((([t,n])=>{const r=`"${t}": ${Wt(n,e,s+1)}`;return e?`${i}${r}`:r}));return e?`{${n.join(",")}${r}}`:`{${n.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${n}`)}}return r}var Kt=class extends Ut{constructor(t){super(t),this.parent=t}assign(t){for(const[e,n]of Object.entries(t))this.set(e,n)}clear(){this.variables.clear()}},Gt=class t{static{this.global=new Kt}constructor(t,e={}){const n=tt(t,e={lstrip_blocks:!0,trim_blocks:!0,...e});this.parsed=kt(n)}render(e){const n=new Ut(t.global);n.set("false",!1),n.set("true",!0),n.set("raise_exception",(t=>{throw new Error(t)})),n.set("range",At);for(const[t,r]of Object.entries(e))n.set(t,r);return new _t(n).run(this.parsed).toString()}};function Ht(t,e){let n;switch(t.type){case"Identifier":n=t.value;break;case"MemberExpression":n=Ht(t.object,e);break;case"FilterExpression":n=Ht(t.operand,e);break;case"Set":{e||(e=[]);const r=Ht(t.assignee);r&&e.push(r),n=Ht(t.value,e);break}}return n&&e?.includes(n)&&(n=void 0),n}function Zt(t){let e;if("Program"===t.type)e=t.body.some((t=>Zt(t)));else e=t.isStatement;return e}function Xt(t,e){let n=[];if(Array.isArray(t))n=t.map((t=>Xt(t,e))).filter(Boolean).flat();else switch(t.type){case"Program":n=t.body.map((t=>Xt(t,e))).filter(Boolean).flat();break;case"If":n=[Ht(t.test,e),...Xt(t.body,e),...Xt(t.alternate,e)].filter(Boolean);break;case"BinaryExpression":n=[Ht(t.left,e),Ht(t.right,e)].filter(Boolean);break;case"For":{const r=Ht(t.loopvar);r&&(e||(e=[]),e.push(r)),n=[Ht(t.iterable,e),...Xt(t.body,e)].filter(Boolean);break}case"CallExpression":n=[Ht(t.callee,e),...Xt(t.args,e)].filter(Boolean);break;default:n=[Ht(t,e)].filter(Boolean)}return n}Gt.global.assign(Dt);var Yt=class extends z{static isTemplate(t){let e,n,r=!1;if("object"==typeof t?(n=t.template,e=t.compiledTemplate):n=t,!e&&n)try{e=new Gt(n)}catch(t){}return e&&(r=Zt(e.parsed)),r}getVariables(t=this.compiledTemplate){return Xt(t.parsed,[]).filter(((t,e,n)=>n.indexOf(t)===e))}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new x("Prompt template must be a string","PromptTemplate",400);this.compiledTemplate=new Gt(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return this.compiledTemplate.render(t)}};function Qt(t){return function(e){return t}}function te(t){const e=t.split(""),n=[],r=(t,n)=>{for(let r=n;r<e.length;r+=1)if(t.includes(e[r]))return r;return-1};let s=0;for(;s<e.length;)if("{"===e[s]&&s+1<e.length&&"{"===e[s+1])n.push({type:"literal",text:"{"}),s+=2;else if("}"===e[s]&&s+1<e.length&&"}"===e[s+1])n.push({type:"literal",text:"}"}),s+=2;else if("{"===e[s]){const t=r("}",s);if(t<0)throw new Error("Unclosed '{' in template.");n.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=r("{}",s),i=(t<0?e.slice(s):e.slice(s,t)).join("");n.push({type:"literal",text:i}),s=t<0?e.length:t}}return n}function ee(t,e){return t.reduce(((t,n)=>{let r;return r="variable"===n.type?n.name in e?t+e[n.name]:t:t+n.text,r}),"")}function ne(t){const e=new Set;return t.forEach((t=>{"variable"===t.type&&e.add(t.name)})),[...e]}z.register(Yt,{name:"hf",aliases:["huggingface","internal","default"]});var re=class extends z{static isTemplate(t){let e,n,r=!1;if("object"==typeof t?(n=t.template,e=t.compiledTemplate):n=t,!e&&n)try{e=te(n)}catch(t){}if(e){r=ne(e).length>0}return r}getVariables(t=this.compiledTemplate){return ne(t)}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new x("Prompt template must be a string","PromptTemplate",400);this.compiledTemplate=te(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return ee(this.compiledTemplate,t)}};function se(t,e){return"string"==typeof e&&(e=e.split(".").filter((t=>t.length))),e.reduce(((t,e)=>t?.[e]),t)}function ie(t,e,n){let r=function(t,e,n){return t.replace(/{{\s*re_replace\s+\.(.+?)\s+(["'])([^\2]*?)\2\s+(["'])([^\4]*?)\4\s*}}/g,((t,r,s,i,o,a)=>{if(n)return e[r]=null,t;const c=new RegExp(i,"g");return se(e,r).replace(c,a)}))}(t,e,n);return r=function(t,e,n){return t.replace(/{{\s*join\s+\.(.+?)\s+(["'])([^\2]*?)\2\s*}}/g,((t,r,s,i)=>n?(e[r]=null,t):se(e,r).join(i)))}(r,e,n),r=function(t,e,n){return t.replace(/{{\s*if\s*(\S+?)\s*}}([^{]*)({{\s*else\s*}}([^{]*))?{{\s*end\s*}}/g,((t,r,s,i,o)=>{if(n)return r.startsWith(".")&&(r=r.substring(1)),e[r]=null,t;let a;if(!r.startsWith("."))throw new Error("Functionality not implemented");{const t=se(e,r.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 ${r}: ${typeof t}`);a=t?s:o??""}}return a}))}(r,e,n),r=function(t,e,n){return t.replace(/{{\s*range\s*[.$]([^{}\s]+?)\s*}}([^{]*?){{\.}}([^{]*?){{\s*end\s*}}/g,((t,r,s,i)=>{if(n)return e[r]=null,t;const o=se(e,r);if(Array.isArray(o)){let t="";for(const e of o)t+=`${s}${e}${i}`;return t}return t}))}(r,e,n),r=function(t,e,n){return t.replace(/{{\s*\.([^{}\s]+?)\s*}}/g,((t,r)=>n?(e[r]=null,t):se(e,r)||""))}(r,e,n),r=function(t,e,n){return t.replace(/{{\s*index\s*\.(.+?)\s+(.+?)\s*}}/g,((t,r,s)=>{if(n)return e[r]=null,t;const i=se(e,r);let o;return o=isNaN(s)?i[s.substring(1,s.length-1)]:i[parseInt(s,10)],o||""}))}(r,e,n),r}z.register(re,{name:"fstring",aliases:["python","f-string","langchain"]});var oe=class extends z{static isTemplate(t){const e="string"==typeof t?t:t.template;return e?.includes("{{")&&e.includes("}}")}getVariables(t){const e={};return ie(t,e,!0),[...Object.keys(e)]}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new x("Prompt template must be a string","PromptTemplate",400);this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables(e)}_format(t){return ie(this.template,t)}};function ae(t){return Object.keys(t).sort().map((e=>t[e]))}z.register(oe,{name:"golang",aliases:["localai","ollama"]});var ce=class extends z{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 z?t.examplePrompt:z.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 n=await this.examplePrompt.format(t);e.push(n)}else if("string"==typeof t)e.push(t);else if(t){const n=ae(t);n.length>0&&e.push(...n)}const n=[this.prefix,...e,this.suffix].join(this.exampleSeparator),r=this.templateFormat;return await z.format({template:n,data:t,templateFormat:r})}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}};z.register(ce,{name:"fewshot",aliases:["few_shot"]});var ue=/(\\)?(\$)(?!\()(\{?)([\w.]+)(?::?-((?:\$\{(?:\$\{(?:\$\{[^}]*\}|[^}])*}|[^}])*}|[^}])+))?(\}?)/gi;function le(t){return t.replace(/\\\$/g,"$")}function fe(t,e,n){return t.replace(ue,((r,s,i,o,a,c,u)=>"\\"===s?r.slice(1):e[a]?e[a]===n[a]?e[a]:fe(e[a],e,n):n[a]?n[a]===t?n[a]:fe(n[a],e,n):c?c.startsWith("$")?fe(c,e,n):c:""))}function he(t){let e=process.env;t&&null!=t.processEnv&&(e=t.processEnv);for(const n in t.parsed){let r=t.parsed[n];if(!r)continue;r=Object.prototype.hasOwnProperty.call(e,n)?e[n]===t.parsed[n]?fe(r,e,t.parsed):e[n]:fe(r,e,t.parsed),t.parsed[n]=r?le(r):r}for(const n in t.parsed)e[n]=t.parsed[n];return t}function pe(t,e={},n){switch(n||(n=new WeakSet),e.processEnv||(e.processEnv={...process.env}),e.parsed||(e.parsed=e.processEnv),typeof t){case"string":t=fe(t,e.processEnv,e.parsed);break;case"object":if(n.has(t))return t;if(n.add(t),Array.isArray(t))for(let r=0;r<t.length;r++){const s=t[r];"string"!=typeof s&&"object"!=typeof s||(t[r]=pe(t[r],e,n))}else for(const[r,s]of Object.entries(t))"string"!=typeof s&&"object"!=typeof s||(t[r]=pe(s,e,n))}return t}var we="@",de=/(\S.+?[.!?])(?=\s+|$)|(\S.+?)(?=[\n]|$)/g,me=/([A-Z][a-z]{1,2}\.)\s(\w)/g,ye=/(\.[a-zA-Z]\.)\s(\w)/g,be=new RegExp("([A-Z][a-z]{1,2}\\.)"+we+"(\\w)","g"),ge=new RegExp("(\\.[a-zA-Z]\\.)"+we+"(\\w)","g");function ve(t,e,n){const r="$1"+e+"$2";let s=t;for(let t=0;t<n.length;t++)s=s.replace(n[t],r);return s}function Ee(t,e=!0){const n=(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 r=[];for(let t=0;t<n.length;t++){let s=n[t].trim();if(!s)continue;if(!e){r.push(s);continue}let i=ve(s,we,[me,ye]),o=Array.from(i.matchAll(de));if(o.length)for(let t=0;t<o.length;t++){let e=ve(o[t][0]," ",[be,ge]);r.push(e)}else r.push(s)}return r}function xe(t,e=2,n=.5){const r=10**e;return Math.trunc((t+Number.EPSILON+n/r)*r)/r}async function $e(t){return new Promise((e=>setTimeout(e,t)))}var Se=require("custom-ability"),ke="event",Ae="event-bus";var Oe=(0,Se.createAbilityInjector)((function(t){return class{static get emitter(){if(!this._emitter){const t=this.get(Ae)?.emitter;t&&(this._emitter=t,this.prototype._events=t._events)}return this._emitter}get emitter(){return this.constructor._emitter}on(e,n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.on(e,n)}once(e,n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.once(e,n)}off(e,n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.off(e,n)}emit(e,...n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return"error"===e?this.emitError.apply(this,n):r.emit.call(this,e,this.name,...n)}emitError(e,...n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.emit.call(this,"error",e,this.name,...n)}async emitAsync(e,...n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.emitAsync.call(this,e,this.name,...n)}}}),!0);function Te(t,e){return!t||t.some((t=>t instanceof RegExp?t.test(e):t===e))}var je=498,Ce=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 n,r;this.active||T("Channel closed","SSEChannel",je);let s=e;if(t||e)r=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"):"",n="id: "+r+"\n"+(e?"event: "+e+"\n":"")+(t||"data: ")+"\n\n",this.messages.push({id:r,_eventName:s,output:n});else{if(!this.clients.size)return;n="data: \n\n"}for([...this.clients].filter((t=>!s||Te(t.events,s))).forEach(((t,e)=>{t.res.write(n)}));this.messages.length>this.options.historySize;)this.messages.shift();return r}subscribe(t,e,n){this.active||T("Channel closed","SSEChannel",je);const r={req:t,res:e,events:n},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"]="*"),r.req.socket.setNoDelay(!0),r.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=>Te(r.events,t.eventName))).slice(0-u).forEach((t=>{a+=t.output})),r.res.write(a),this.clients.add(r),s>0&&setTimeout((()=>{r.res.writableEnded||this.unsubscribe(r)}),s),r.res.on("close",(()=>this.unsubscribe(r))),r}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 n=e.req.socket.remoteAddress??"";n in t||(t[n]=0),t[n]++})),t}getSubscriberCount(){return this.clients.size}};function Ne(t){return t instanceof ReadableStream||t instanceof WritableStream}var Fe=600,Ie=601,Me=class extends E{constructor(t,e=Fe){super(t,500)}};function Re(t){if(t){const e=t.getReader();return new ReadableStream({async start(t){const{done:n,value:r}=await e.read();if(!n){const e=(new TextDecoder).decode(r);t.error(new Me(`Response error: ${e}`,Ie))}}})}return new ReadableStream({start(t){t.error(new Me("Response error: No response body",Ie))}})}function Pe(){return new ReadableStream({start(t){t.close()}})}var qe=require("eventsource-parser");function Ve(t){const e=new TextDecoder;let n;return new TransformStream({async start(e){n=(0,qe.createParser)((n=>{if("data"in n&&"event"===n.type&&"[DONE]"===n.data||"done"===n.event)e.terminate();else if("data"in n){const r=t?t(n.data,{event:n.event}):n.data;r&&e.enqueue(r)}}))},transform(t){n.feed(e.decode(t))}})}function Be(){let t=!0;return e=>(t&&(e=e.trimStart())&&(t=!1),e)}function Ue(t,e){if(!t.ok)return Re(t.body);let n=t.body||new ReadableStream({start(t){t.close()}});return n instanceof ReadableStream||(n=ReadableStream.from(n)),n.pipeThrough(Ve(e))}function _e(t){let e=t[Symbol.asyncIterator]();return new ReadableStream({async pull(t){const{done:n,value:r}=await e.next();n?t.close():t.enqueue(r)},async cancel(t){await(e.return?.(t))}})}function Le(t){const e=t||{};return new TransformStream({async start(t){const n=t.error;if(t.error=r=>{n.call(t,r),e.onError&&e.onError(r)},e.onStart)try{await e.onStart(t)}catch(e){t.error(e)}},async transform(t,n){try{let r;e.onTransform&&(r=await e.onTransform(t,n)),r||(r=t),n.enqueue(r)}catch(t){n.error(t)}},async flush(t){if(e.onFinal)try{await e.onFinal(t)}catch(e){return t.error(e)}t.terminate()}})}var ze=require("uuid"),Je=c(require("base32768")),De=require("uuid"),We={1:ze.v1,4:ze.v4,5:ze.v5};function Ke(t=1,e){const n=We[t];return e?Je.encode(n(null,[])):n()}var Ge=c(require("xxhashjs")),He=c(require("base32768")),Ze=require("json-canonicalize"),Xe=He,{h32:Ye,h64:Qe}=Ge.default,tn=588213;function en(t,e=16){return"object"==typeof t&&(t=(0,Ze.canonicalize)(t)),Ye(t,tn).toString(e)}function nn(t,e=16){return"object"==typeof t&&(t=(0,Ze.canonicalize)(t)),Qe(t,tn).toString(e)}var rn=(t=>(t[t.xxhash64=111]="xxhash64",t[t.xxhash32=112]="xxhash32",t))(rn||{});function sn(t,e=111,n=tn){let r;return t.buffer&&(t=t.buffer),112!==e?(r=Qe(t,n),r=new Uint16Array([r._a00,r._a16,r._a32,r._a48]),r=new Uint8Array(r.buffer)):(r=Ye(t,n),r=new Uint16Array([r._low,r._high]),r=new Uint8Array(r.buffer)),r}function on(t,e=111,n=tn){return He.encode(sn(t,e,n))}var an=c(require("path")),cn=/[<>:"/\\|?*\u0000-\u001F]/,un=/^(con|prn|aux|nul|com\d|lpt\d)$/i,ln=100,fn=/^\.+(\\|\/)|^\.+$/,hn=/\.+$/,pn=/[\u0000-\u001F\u0080-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069]/;function wn(){return new RegExp(cn.source,"g")}function dn(){return new RegExp(pn.source,"g")}function mn(t){return t&&!(cn.test(t)||dn().test(t)||fn.test(t)||hn.test(t))}function yn(t){const e=t.split(an.default.sep);return("/"===t[0]||e[0]&&an.default.dirname(e[0])===e[0])&&e.shift(),e.every(mn)}function bn(t,e={}){const n=e.replacement||"!";if((cn.test(n)||pn.test(n))&&T("Replacement string cannot contain reserved filename characters","sanitizeFilename",400),n.length>0){const e=/([<>:"/\\|?*\u0000-\u001F]){2,}/;t=t.replace(e,"$1")}if(t=(t=(t=(t=(t=t.normalize("NFD")).replace(fn,n)).replace(wn(),n)).replace(dn(),n)).replace(hn,""),n.length>0){"."===t[0]||"."!==t[0]||(t=n+t),"."===t[t.length-1]&&(t+=n)}t=un.test(t)?t+n:t;const r="number"==typeof e.maxLength?e.maxLength:ln;if(t.length>r){const e=t.lastIndexOf(".");if(-1===e)t=t.slice(0,r);else{const n=t.slice(0,e),s=t.slice(e);t=n.slice(0,Math.max(1,r-s.length))+s}}return t}function gn(t,e={}){const n=t.split(an.default.sep);let r;("/"===t[0]||n[0]&&an.default.dirname(n[0])===n[0])&&(r=n.shift());const s=n.map((t=>bn(t,e)));return void 0!==r&&s.unshift(r),s.join(an.default.sep)}function vn(t,e=1){let n="";for(;e--;){const e=an.default.extname(t);if(!e)break;n=e+n,t=an.default.basename(t,e)}return n}function En(t){return t.split(".").length-1}var xn=require("util-ex");function $n(t,e){if("string"!=typeof t)throw new x("modelName must be a string","isModelNameMatched",400);switch(typeof e){case"string":if((0,xn.isRegExpStr)(e)){const n=(e=(0,xn.toRegExp)(e)).exec(t);if(n)return n}else if(t.toLowerCase()===e.toLowerCase())return e;break;case"object":if(Array.isArray(e)){for(const n of e)if("string"==typeof n){if((0,xn.isRegExpStr)(n)){const r=(e=(0,xn.toRegExp)(n)).exec(t);if(r)return r}else if(t.toLowerCase()===n.toLowerCase())return n}else if(n instanceof RegExp){const e=n.exec(t);if(e)return e}else if("function"==typeof n){const e=n.call(this,t);if(e)return e}}else if(e instanceof RegExp){const n=e.exec(t);if(n)return n}break;case"function":const n=e.call(this,t);if(n)return n}}function Sn(t){return Object.keys(t).filter((t=>Number.isNaN(Number(t))))}var kn=require("lodash-es"),An=require("util-ex");function On(t,e){if(e&&(e=Cn(e)),e){const n=Object.keys(e);if(n.length){const r=Object.values(e);return(0,An.newFunction)("expression",n,`return ${t}`)(...r)}}return(0,An.newFunction)("expression",[],`return ${t}`)()}var Tn=/^[a-zA-Z_$][0-9a-zA-Z_$]*$/,jn=t=>Tn.test(t);function Cn(t){if(t){const e=Object.keys(t),n=e.length,r=e.filter((e=>jn(e)&&null!==t[e]));if(n===r.length)return t;if(r.length)return t=(0,kn.pick)(t,r)}}function Nn(t){return t?Fn(t,[],""):[]}function Fn(t,e,n="."){return Array.isArray(t)?t.flatMap(((t,n)=>Fn(t,[...e,`[${n}]`]))):(r=t)&&r.constructor===Object?Object.entries(t).flatMap((([t,r])=>Fn(r,[...e,n+t]))):[e.join("")];var r}function In(t){if(t<2)throw new x("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 Mn=c(require("path")),Rn=c(require("fs"));function Pn(t){const e=Rn.statSync(t,{throwIfNoEntry:!1});return e?.isFile()}function qn(t,e,n,r){const s=r?.signal,i=r?.exclude;let o;if(Mn.default.isAbsolute(t)?o=Pn(t)?t:Vn(Mn.default.basename(t),[Mn.default.dirname(t)],{extNames:n,exclude:i,signal:s}):(e||(e=["."]),o=Vn(t,e,{extNames:n,exclude:i,signal:s})),!o)throw new S(t,"loadFileFromPaths");{const t=o;o=Rn.readFileSync(o),r&&(r.filepath=t)}return o}function Vn(t,e,{extNames:n,signal:r,exclude:s=[]}){let i;const o=n?n.map((e=>vn(t,En(e)))):void 0;"string"==typeof s&&(s=[s]);for(const a of e){if(r?.aborted)throw r.reason;const e=Mn.default.resolve(a,t);if(o)for(let t=0;t<o.length;t++){const r=e+(o[t]!==n[t]?n[t]:"");if(!s.includes(r)&&Pn(r)){i=r;break}}else if(!s.includes(e)&&Pn(e)){i=e;break}}return i}function Bn(t,e,n,r,s){let i;"string"==typeof r?(i=r,r=void 0):i=r?.encoding??"utf8";return qn(t,e,n,r).toString(i)}function Un(t,e){const n=[],r="string"==typeof t?[t]:[...t],s=new Set,i=e?.signal,o=e?.isFileMatched,a=e?.level;let c=0;for(;r.length>0;){if(i?.aborted)throw i.reason;const t=_n(r.pop()),e=Mn.default.resolve(t);if(s.has(e))continue;s.add(e);const u=Rn.statSync(t,{throwIfNoEntry:!1});if(u?.isDirectory()){const e=Rn.readdirSync(t,{withFileTypes:!0});for(let s=0;s<e.length;s++){const i=e[s],a=Mn.default.join(t,i.name);i.isDirectory()?r.push(a):!i.isFile()||o&&!o(a)||n.push(a)}if(c++,a&&c>=a)break}}return n}function _n(t){const e=Rn.lstatSync(t,{throwIfNoEntry:!1});return e?.isSymbolicLink()&&(t=Rn.readlinkSync(t)),t}var Ln=require("fs"),zn=c(require("path")),Jn=require("load-config-file"),Dn=require("yaml"),Wn=require("yaml-types"),Kn=require("mime-type/with-db"),Gn=require("yaml"),Hn=[Wn.regexp];function Zn(t){Array.isArray(t)||(t=[t]);for(const e of t){-1===Hn.indexOf(e)&&Hn.push(e)}}function Xn(t){return(0,Dn.parse)(t,{customTags:Hn})}function Yn(t,e){const n=[],r=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 n=(0,Ln.readdirSync)(t,{withFileTypes:!0,recursive:!0});for(const r of n){const n=zn.default.join(t,r.name);r.isFile()&&e(n,r)}}(t,((t,e)=>{if(s?.includes(t))return;const o=zn.default.extname(t),a=(0,Ln.statSync)(t);if(i.includes(o)){if(r?.hasOwnProperty(t)&&a.mtimeMs<=r[t])return;n.push(t)}})),n}function Qn(t,e){return Yn(t,e).map((t=>Jn.Config.loadSync(t))).filter((t=>void 0!==t))}function tr(t,e,n=1){"."===t[0]&&n++;const r=vn(t,n);(!r||r.split(".").length<=1)&&(t+=".yaml");const s=Kn.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,Dn.stringify)(e)}const i=zn.default.dirname(t);return(0,Ln.existsSync)(i)||(0,Ln.mkdirSync)(i,{recursive:!0}),(0,Ln.writeFileSync)(t,e,{encoding:"utf8"}),t}function er(t){t instanceof Date&&(t=t.toISOString());return function(t,e){return t?`'${e}'`:String(e)}("string"==typeof t,t)}function nr(t,e){return t.map((t=>ir(t,e))).join(" AND ")}function rr(t,e){return t.map((t=>ir(t,e))).join(" OR ")}function sr(t,e){const n=[];return Object.keys(e).forEach((r=>{const s=e[r];switch(r){case"$lt":case"<":n.push(`${t} < ${er(s)}`);break;case"<=":case"$lte":n.push(`${t} <= ${er(s)}`);break;case"$gt":case">":n.push(`${t} > ${er(s)}`);break;case"$gte":case">=":n.push(`${t} >= ${er(s)}`);break;case"$ne":case"!=":n.push(`${t} != ${er(s)}`);break;case"=":case"$eq":n.push(`${t} = ${er(s)}`);break;case"$in":n.push(`${t} IN (${s.map((t=>er(t))).join(", ")})`);break;case"$nin":n.push(`${t} NOT IN (${s.map((t=>er(t))).join(", ")})`);break;case"$regex":n.push(`${t} REGEXP '${s.source}'`);break;case"$like":n.push(`${t} LIKE '${s}'`);break;case"$nlike":n.push(`${t} NOT LIKE '${s}'`);break;case"$glob":n.push(`${t} GLOB '${s}'`);break;case"$nglob":n.push(`${t} NOT GLOB '${s}'`);break;default:throw new Error(`Unsupported condition operator: ${r}`)}})),n.join(" AND ")}function ir(t,e){const n=[];if("function"!=typeof e&&(e=t=>t),Array.isArray(t))n.push(nr(t,e));else for(const[r,s]of Object.entries(t))if("$and"===r)n.push(`(${nr(t[r],e)})`);else if("$or"===r)n.push(`(${rr(t[r],e)})`);else{const t=typeof s;if(null==s)n.push(`${e(r)} IS NULL`);else if(s instanceof Date)n.push(`${e(r)}='${s.toISOString()}'`);else if("object"!==t||Array.isArray(s))if("string"===t)n.push(`${e(r)}='${s}'`);else{if("number"!==t&&"boolean"!==t)throw new Error(`Unsupported value type for key ${r}`);n.push(`${e(r)}=${s}`)}else n.push(sr(e(r),s))}return n.length>1?n.join(" AND "):n[0]}function or(t){const e=t.indexOf("://");if(e>0)return t.substring(0,e)}function ar(t,e=0){let n,r=t*10**e;return t>=1e12?(r=Math.round(r/1e12),n="T"):t>=1e9?(r=Math.round(r/1e9),n="B"):t>=1e6?(r=Math.round(r/1e6),n="M"):t>=1e3?(r=Math.round(r/1e3),n="K"):(r=Math.round(r),n=""),r/=10**e,r.toFixed(e)+n}function cr(t){const e=t.match(/^\s*[+]?(\d+(?:[.]\d+)?)\s*([TBMK])?\s*$/i);if(!e)throw new x("Invalid formatted parameter size string.","scaleToSize",400);const n=parseFloat(e[1]),r=e[2]?.toLowerCase();switch(r){case"t":return 1e12*n;case"b":return 1e9*n;case"m":return 1e6*n;case"k":return 1e3*n;default:return n}}function ur(t,e){const n=e?.level||0,r=e?.visiting||new Set,s=e?.objectTag||"*",i=e?.arrayTag||"-";let o=[];const a=" ".repeat(2*n);if(null!=t)switch(typeof t){case"object":r.has(t)?o=["[Circular]"]:(r.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":" ")+ur(t,{level:n+1,visiting:r})}}Jn.Config.register([".yml",".yaml"],Xn),Jn.Config.register([".json"],(function(t){return JSON.parse(t)}));var lr=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}},fr=require("events-ex"),hr=32;function pr(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 wr=class{constructor(t){this._capacity=pr(t),this._length=0,this._front=0,this.arr=[]}push(t){const e=this._length;this.checkCapacity(e+1);const n=this._front+e&this._capacity-1;return this.arr[n]=t,this._length=e+1,n}pop(){const t=this._length;if(0===t)return;const e=this._front+t-1&this._capacity-1,n=this.arr[e];return this.arr[e]=void 0,this._length=t-1,n}shift(){const t=this._length;if(0===t)return;const e=this._front,n=this.arr[e];return this.arr[e]=void 0,this._front=e+1&this._capacity-1,this._length=t-1,n}get length(){return this._length}checkCapacity(t){this._capacity<t&&this.resizeTo(pr(1.5*this._capacity+16))}resizeTo(t){const e=this._capacity;this._capacity=t;const n=this._front,r=this._length;if(n+r>e){const t=n+r&e-1;!function(t,e,n,r,s){for(let i=0;i<s;++i)n[i+r]=t[i+e],t[i+e]=void 0}(this.arr,0,this.arr,e,t)}}},dr=class extends fr.EventEmitter{};function mr(t){return"function"==typeof t}function yr(){return"1"}var br=class{constructor(t,{initFn:e=yr,pauseFn:n,resumeFn:r,capacity:s=hr}={}){if(mr(n)!==mr(r))throw new Error("pauseFn and resumeFn must be both set for pausing");this.maxConcurrency=t,this.free=new wr(t),this.waiting=new wr(s),this.releaseEmitter=new dr,this.useDefaultTokens=e===yr,this.pauseFn=n,this.resumeFn=r,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 n=0;n<t;n++)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,n)=>{this.pauseFn&&!this.paused&&(this.paused=!0,this.pauseFn());const r=this.waiting.push({resolve:e,reject:n});return t&&t.addEventListener("abort",(()=>{this.waiting[r]=void 0;const e=t.reason instanceof Error?t.reason:new Error(t.reason||"aborted");t.alreadyRejected=!0,n(e)})),r}))}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 gr(t,{timeUnit:e=1e3,uniformDistribution:n=!1}={}){const r=new br(n?1:t),s=n?e/t:e;return async function(){await r.acquire(),setTimeout((()=>r.release()),s)}}var vr,Er=require("custom-ability"),xr=require("property-manager"),$r=require("util-ex"),Sr=0,kr=1,Ar=2,Or=(t=>(t[t.MultiTask=Sr]="MultiTask",t[t.Cancelable=kr]="Cancelable",t[t.Priority=Ar]="Priority",t))(Or||{}),Tr=((vr=Tr||{})[vr.MultiTask=1<<Sr]="MultiTask",vr[vr.Cancelable=1<<kr]="Cancelable",vr[vr.Priority=1<<Ar]="Priority",vr),jr=class t extends xr.AdvancePropertyManager{static{this.items={}}static get(t){return this.items[t]}static list(){return this.items}static getByTag(t){let e;for(const n in this.list()){const r=this.get(n);let s=r.tags;if("string"==typeof s){if(s===t){e=r;break}}else if(Array.isArray(s)&&s.indexOf(t)>=0){e=r;break}}return e}static getAllByTag(t){let e=[];for(const n in this.list()){const r=this.get(n);let s=r.tags;"string"==typeof s?s===t&&e.push(r):Array.isArray(s)&&s.indexOf(t)>=0&&e.push(r)}return e}static hasAsyncFeature(t){const e=this.prototype;let n=e.asyncFeatures;return e._asyncFeatures&&(n|=e._asyncFeatures),lr.has(n,t)}static run(t,e){const n=this.get(t);if(n)return n.run(e);throw new S(`${t} to run`,this.name)}static runSync(t,e){const n=this.get(t);if(n)return n.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 n=this.get(t);if(n)return n.runWithPos(...e);throw new S(`${t} to run`,this.name)}static runWithPosSync(t,...e){const n=this.get(t);if(n)return n.runWithPosSync(...e);throw new S(`${t} to run`,this.name)}static getFuncWithPos(t){const e=this.get(t);return e?.getFuncWithPos()}static register(e,n={}){switch(typeof e){case"string":n.name=e;break;case"function":n.func=e;break;case"object":n=e}e=n.name;let r=!!this.get(e);if(r)r=!1;else{if(!(n instanceof t))return r=new this(n),r.register();this.items[e]=n,r=n}return r}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,n=this.depends;if(n){const e=Object.keys(n);for(const r of e){const e=n[r];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={},n=Object.keys(this.params);let r=Math.min(n.length,t.length);for(let s=0;s<r;s++)e[n[s]]=t[s];t=[e]}return t}obj2ArrParams(t){const e=[];if(t&&this.params&&Array.isArray(this.params)){const n=Object.keys(t);let r=Math.min(n.length,this.params.length);for(let s=0;s<r;s++)e.push(t[n[s]])}return e}runSync(t){const e=this.params&&Array.isArray(this.params);if(Array.isArray(t)){if(e)return this.func(...t);T("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),lr.has(e,t)}isStream(t){return this.stream}},Cr={name:{type:"string"},description:{type:"string"},func:{type:"function",assign(t,e,n,r,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,$r._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"}};jr.defineProperties(jr,Cr);var Nr=require("util-ex"),Fr=class extends AbortController{constructor(t){super(),(0,Nr.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")}}},Ir=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 br(t-1)),e}isAborted(t){const e=this.hasAsyncFeature(Sr);let n=this.__task_aborter;if(n&&e){if(null==t)throw new x("Missing taskId",this.name+".isAborted",400);n=n[t]}return!n||n.signal.aborted}getRunningTask(t){const e=this.hasAsyncFeature(Sr);let n=this.__task_aborter;if(n&&e){if(null==t)throw new x("Missing taskId",this.name+".getRunningTask",400);n=n[t]}return n?.signal.aborted&&(e?this.__task_aborter[t]=void 0:this.__task_aborter=void 0,n=void 0),n}getRunningTaskCount(){let t;if(this.hasAsyncFeature(Sr)){const e=this.__task_aborter;t=e&&Object.entries(e).filter((([t,n])=>{if(!n?.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 n=this.super,r=this.self||this;return t=n?n.call(r,t):this._generateAsyncTaskId(t,e)}createAborter(t,e,n=!0){const r=this.hasAsyncFeature(Sr);if(!r&&n&&this.getRunningTask())throw new x("The task is running",this.name,429);const s=t?.aborter||new Fr(this);if(!(s instanceof Fr)){if(!(s instanceof AbortController))throw new x("aborter should be an AbortController",this.name,400);Object.setPrototypeOf(s,new Fr(this))}if(r){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 n=this.super,r=this.self||this;n?n.call(r,t,e):r._cleanMultiTaskAborter(t,e)}cleanTaskAborter(t){if(this.hasAsyncFeature(Sr)){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,n){const r=this.createAborter(e,n?.taskId,n?.raiseError);void 0===e&&(e={}),"object"==typeof e&&(e.aborter=r);let s=t(e,r).then((t=>{if(t&&t instanceof ReadableStream){const e=()=>{this.cleanTaskAborter(r)},n=Le({onStart:t=>{(0,Nr.defineProperty)(r,"streamController",t)},onFinal:e,onError:e,onTransform:(t,e)=>(t&&"object"==typeof t&&(t.taskId=r.id),t)});t=t.pipeThrough(n)}else this.cleanTaskAborter(r);return t})).catch((t=>{throw this.cleanTaskAborter(r),t})).finally((()=>{r.timeoutId&&(clearTimeout(r.timeoutId),r.timeoutId=void 0)}));return s.task=r,s}runAsyncCancelableTask(t={},e,n){let r=this.createTaskPromise(e,t,n);const s=this.semaphore;if(s){const t=r,e=t.task;r=s.acquire(e.signal).then((()=>t)).finally((()=>{s.release()})),r.task=e}return r}abort(t,e){let n=this.__task_aborter;if(n){const r=n;if(this.hasAsyncFeature(Sr)){const t=e?.taskId;if(null==t)throw new x("Missing data.taskId",this.name+".abort",400);n=n[t],this.cleanMultiTaskAborter(t,r)}else this.__task_aborter=void 0;n&&!n.signal.aborted&&n.abort(t,e)}}};Ir.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},Ir.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};var Mr=(0,Er.createAbilityInjector)(Ir,"abort",{afterInjection:function(t,e){let n=t.prototype._asyncFeatures||0;n|=Tr.Cancelable,e&&(e.asyncFeatures&&(n|=e.asyncFeatures),e.maxTaskConcurrency>0&&(t.prototype._maxTaskConcurrency=e.maxTaskConcurrency)),t.prototype._asyncFeatures=n}});function Rr(t,e){const n=e.global?e:new RegExp(e.source,`${e.flags}g`);let r,s=0;for(;null!==(r=n.exec(t));)s++;return s}var Pr=require("lodash-es"),qr=require("util-ex");async function Vr(t,e,n){return Br(Hr(t,e,n),e,n)}async function Br(t,e,n){if(t.length){const r=await Promise.all(t.map(((t,r)=>Gr(t,r,e,n)))),s=n?.returnArrayOnly;let i;if(r?.length){const t=`{${r.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(",")}}`;i=On(t,e)}if(i&&!s){const t=Object.entries(i),e=Object.keys(i);1===t.length&&void 0!==i[0]?i=i[0]:e.every((t=>!isNaN(parseInt(t))))?i=e.sort(((t,e)=>parseInt(t)-parseInt(e))).map((t=>i[t])):2===t.length&&"0"===t[0][0]&&t[0][1]===t[1][1]&&(i=i[0])}return i}}function Ur(t,e,n,r){const[s,i]=t;if(!s&&"|"===i[0])return"choice: {"+function(t,e,n){const r=Hr(t,e,{...n,delimiter:":"}),s={},i=r.map((([t,e],n)=>{if(t){const t=e.indexOf(":"),n=e.slice(0,t).trim();if(s[n])throw new Error("Only one "+n+" is allowed");return s[n]=!0,e}{if("|"===e[0]){if(s.items)throw new Error("Only one items is allowed");return s.items=!0,"items:["+function(t,e='"'){return t.map((t=>zr(t)?t:e+t+e))}(e.split("|").filter(Boolean))+"]"}const t=parseInt(e.trim());if(!isNaN(t)){if(s.maxPick)throw new Error("Only one maxPick is allowed");return s.maxPick=!0,"maxPick:"+t}if("random"===e||"ai"===e)return s.type=!0,'type:"'+e+'"';if(zr(e)){if(s.separator)throw new Error("Only one separator is allowed");return s.separator=!0,"separator:"+e}}}));return i}(i,n,r)+"}"}async function _r([t,e],n,r,s){if(!r)return;let i,o;if(t){const t=e.split(":");i=t[0].trim(),o=t[1].trim()}else o=e,i=n+"";const a={template:o,data:{...r,...s?.templateData}};s?.templateFormat&&(a.templateFormat=s.templateFormat);const c=await z.formatIf(a);return c?(o=c,i+":"+Jr(o)):void 0}async function Lr(t,e,n,r){let s=Ur(t,0,n,r);return s||(s=await _r(t,e,n,r)),s}function zr(t){const e=t[0];return('"'===e||"'"===e)&&t[t.length-1]===e}function Jr(t){return'"'+t.replace(/(?<!\\)"(?!\\)/g,'\\"')+'"'}var Dr=["true","false","null","undefined","NaN","Infinity"];function Wr(t){return function(t,e=['""',"''","{}"]){return e.some((e=>t[0]===e[0]&&t[t.length-1]===e[1]))}(t)||!Number.isNaN(parseFloat(t))||Dr.includes(t)||Yr(t)}async function Kr(t,e){const n=(0,qr.newFunction)("async expression",[],`return ${t};`,Cn(e));let r=await n.call(this);switch(typeof r){case"number":case"boolean":case"undefined":return r;case"function":return n.toString();default:return JSON.stringify(r)}}async function Gr(t,e,n,r){const[s,i]=t,o=r?.argProcessor;if("function"==typeof o){const s=await o(t,e,n,r);if(s)return s}if(s){const t=i.indexOf(":"),e=i.slice(0,t).trim(),r=i.slice(t+1).trim();if(!(Wr(r)||n&&void 0!==(0,Pr.get)(n,r)))return e+":"+Jr(r);if(!Yr(i))try{return e+":"+await Kr.call(this,r,n)}catch(t){}return i}{const t=i.trim();if(n&&void 0!==(0,Pr.get)(n,t))return e+":"+t+', "'+t+'":'+t;if(Wr(t))return e+":"+t;if(!Yr(i))try{return e+":"+await Kr.call(this,t,n)}catch(t){}return e+":"+Jr(t)}}function Hr(t,e,n){const r=n?.delimiter??",";let s=[],i=!1,o="",a="",c=!1,u="";for(let e=0;e<t.length;e++){const n=t[e];if(n!==r||i||u)if("\\"===n)a+=n,e++,a+=t[e];else if("("!==n&&"["!==n||i)if(u&&n===u)u="",a+=n;else if("{"!==n||i)'"'===n||"'"===n?(i&&n===o?i=!1:i||(i=!0,o=n),a+=n):"="!==n||i||c||!/^[\p{L}\p{N}_ ]+$/u.test(a)?a+=n:(a+=":",c=!0);else{let r,s=e,i=!1,o="",c=-1;for(;s<t.length&&("}"!==(r=t[s])||i||c>0);)"\\"===r?s++:"{"!==r||i?"}"!==r||i?'"'!==r&&"'"!==r||(i&&n===o?i=!1:i||(i=!0,o=n)):c--:c++,s++;s<t.length&&(a+=t.substring(e,s+1),e=s)}else u="("===n?")":"]",a+=n;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 Zr(t,e,n){const r=t.match(/^([^(]+)(?:\((.*)\))?$/);if(!r)throw new Error("Invalid command format");const[,s,i]=r;let o;return i&&(o=await Vr(i,e,n)),{command:s.trim(),args:o}}var Xr=/^\s*\(\)|[a-zA-Z_$][\w\d$]*|\(([a-zA-Z_$][\w\d$]*)(\s*,\s*([a-zA-Z_$][\w\d$]*))*\)\s*=>/;function Yr(t){return Xr.test(t)}var Qr=c(require("memoizee")),ts=require("json-canonicalize");function es(t,e){var n;void 0!==e?.promise||!function(t){return"function"==typeof t&&"AsyncFunction"===t.constructor.name}(t)&&(!(n=t)||"object"!=typeof n&&"function"!=typeof n||"function"!=typeof n.then)||(e={promise:!0,...e}),void 0===e?.length&&(e={length:!1,...e});const r=e?.normalizer;return(0,Qr.default)(t,{...e,normalizer:t=>{if(r){const e=r(t);if("string"===e)return e;e&&(t=e)}return on((0,ts.canonicalize)(t))}})}var ns=class t extends jr{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 T("missing apiRoot to load tools","ClientTools")}static loadFromSync(e){for(const n in e){const r=this.get(n),s=e[n];r?r instanceof t?r.assign(s):T(`${n} already registered as ${r.constructor.name}`,"ClientTools"):this.register(s)}}static async fetch(t,e){const n=this.get(t);if(n&&n.fetch)return n.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,n){const r={...this.fetchOptions};let s;r.headers&&r.headers["Content-Type"]||(r.headers={"Content-Type":"application/json",...r.headers}),t?.stream&&!r.headers.Connection&&(r.headers.Connection="keep-alive"),e||(e=this.action||"post"),"res"===e&&(e="get"),n?("string"!=typeof n&&(n=JSON.stringify(n)),n=this.name+"/"+n):n=this.name,r.method=e.toUpperCase(),"get"===e||"delete"===e?s=n+this.getUrlParams(t):(r.body=JSON.stringify(t),s=n);const i=await fetch(`${this.apiRoot}/${s}`,r);if(!i.ok){throw await this.errorFrom(i)}return i}async errorFrom(t){let e,n=t.status,r=t.statusText,s=this.name;if(t.body){const n=await t.text();try{const t=JSON.parse(n);t&&(t.error&&(r=t.error),t.name&&(s=t.name),t.data&&(e=t.data,e.name=s,e.what&&(e.msg=r,r=e.what)),t.message&&(r=r+":"+t.message))}catch(t){console.warn("🚀 ~ parse error body to json:",t)}}return O(r,s,n)}async func(t){const e=await this.fetch(t);if(t?.stream)return e;return await e.json()}},rs={...p};ns.defineProperties(ns,rs);var ss=class t extends jr{static get apiRoot(){return this._apiRoot}static setApiRoot(t){this._apiRoot=t}static toJSON(){const e={};for(const n in this.items){let r=this.items[n];(r instanceof t||r.isApi)&&(r.allowExportFunc||(r=r.toJSON(),delete r.func),e[n]=r)}return e}func({}){}},is={...p};ss.defineProperties(ss,is);var os=require("events-ex"),as=class extends jr{constructor(){super(...arguments),this._emitter=new os.EventEmitter,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},cs=new as(Ae),us=require("secondary-cache");function ls({key:t,value:e,options:n}={}){return void 0!==t?null===e?this.cache.del(t):void 0!==e?this.cache.set(t,e,n):this.cache.get(t):(n&&this.cache.setDefaultOptions(n),this.cache)}function fs(t,e){let n=jr.get(t);return n||(n=new jr(t,{func:ls,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"}),n.cache=new us.Cache(e)),n}var hs=fs("lrucache"),ps=class extends ns{async _func(t,e){const n=await this.fetch(e,t);if(e?.stream)return n;return await n.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))}}},ws={methods:{type:"array",assign(t,e,n,r,s){s?.isExported||e.assignMethods(t)}}};ps.defineProperties(ps,ws);var ds=class extends ps{async fetch(t,e){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let n=t.id;return n||T("id is required"),"string"==typeof n&&(n=encodeURIComponent(n)),delete t.id,super.fetch(t,e,n)}"list"===e?e="get":e.startsWith("$")&&(t.act=e,e="post")}return await super.fetch(t,e)}},ms=class extends ds{constructor(){super(...arguments),this._sseEvents={},this._forwardEvents=new Set,this.name=ke,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}):"",n=`${this.apiRoot}/${this.name}${e}`,r=this._es=new EventSource(n);return Object.entries(this._sseEvents).forEach((([t,e])=>{r.addEventListener(t,e)})),this._esEvents=t,r}esListener(t){const e=t.data?JSON.parse(t.data):void 0,n=t.type;if(!this._forwardEvents.has(n)){const t=this.emitter;t&&e&&n&&(Array.isArray(e)?t.emit(n,...e):t.emit(n,e))}}async subscribe(t){const e=await this.sub({event:t});"string"==typeof t&&(t=[t]);const n=this.evtSource;for(const e of t)if(!this._sseEvents[e]){const t=this._sseEvents[e]=this.esListener.bind(this);n.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)}},ys=new ms(ke),bs=require("util-ex"),gs=class extends ss{constructor(t,e={}){super(t,e),this.params={act:{type:"string"}};const n=this.methods=[];this.initRpcMethods(n)}get SpecialRpcMethodNames(){return this.constructor.SpecialRpcMethodNames}initRpcMethods(t=this.methods){const e=this.SpecialRpcMethodNames;if(Array.isArray(e))for(const n of e)"function"==typeof this[n]&&t.push(n);(0,bs.getAllNames)(Object.getPrototypeOf(this)).filter((t=>t.startsWith("$")&&"function"==typeof this[t])).forEach((e=>{t.push(e);const n=e.slice(1);void 0===this[n]&&(this[n]=this[e])}))}cast(t,e){let n=this.params[t];return n&&("string"!=typeof n&&(n=n.type),"number"===n&&(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)}};gs.defineProperties(gs,{methods:{type:"array"}});var vs=class extends gs{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}}}static{this.SpecialRpcMethodNames=h}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}},Es=cs.runSync(),xs=class t extends vs{constructor(){super(...arguments),this.name=ke,this.description="subscribe server sent event",this.result="event",this.depends={[Ae]:cs}}static get sse(){return this._sse||(this._sse=new Ce),this._sse}get sse(){return this.constructor.sse}static publish(e,n){return t.sse.publish(e,n)}static{this.ebListener=function(...e){t.sse.publish(e,this.type)}}static subscribe(e,n,r){return t.sse.subscribe(e,n,r)}static alreadyForward(e){const n=Es.listeners(e);for(const e of n)if(e===t.ebListener)return!0}publishSSE(t,e){return this.constructor.publish(t,e)}subscribeSSE(t,e,n){return"string"==typeof n&&(n=[n]),this.constructor.subscribe(t,e,n)}forward(e){Array.isArray(e)||(e=[e]);for(const n of e)t.alreadyForward(n)||Es.on(n,t.ebListener)}unforward(e){"string"==typeof e&&(e=[e]);for(const n of e)Es.off(n,t.ebListener)}list({_req:t,_res:e,event:n}){t&&e&&this.subscribeSSE(t,e,n)}$sub({event:t}){if(t)return this.forward(t),{event:t};T("event is required","sub",400)}$unsub({event:t}){if(t)return this.unforward(t),{event:t};T("event is required","unsub",400)}$publish({event:t,data:e}){if(t&&e){"string"==typeof t&&(t=[t]);for(const n of t)this.publishSSE(e,n);return{event:t}}T("event or data is required","pub",400)}isStream(t){return"list"===this.getMethodFromParams(t)}},$s=new xs(ke);function Ss(){cs.register(),hs.register()}
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{AIArgProcessor as e,AIChatRoles as r,AIMessageTypes as t,AIStream as a,AITextGenerationFinishReasons as o,AbortError as s,AbortErrorCode as n,ActionNames as i,AlreadyExistsError as l,AlreadyExistsErrorCode as m,AsyncFeatureBits as u,AsyncFeatures as c,BaseError as d,CancelableAbility as p,ChoiceArgProcessor as S,ClientToolFuncSchema as T,ClientTools as h,CommonError as F,ConfigFile as E,DefaultAsyncSemaphoreCapacity as g,EnvironmentEx as C,ErrorCode as v,EventBusName as A,EventClient as f,EventName as x,EventServer as y,EventToolFunc as R,FStringPromptTemplate as b,FewShotPromptTemplate as I,FilenameReservedRegex as P,GolangPromptTemplate as N,HfPromptTemplate as H,IntSet as j,InternalErrorCode as k,Interpreter as D,NIL as O,NotFoundError as V,NotFoundErrorCode as B,NotImplementationError as L,NotImplementedErrorCode as M,PASSING_SCORE as z,PromptExampleSelector as w,PromptTemplate as G,PromptTemplateTypes as U,PromptTypes as Y,RStreamErrCode as W,RateLimit as J,ReadableStreamError as K,RemoteToolFuncSchema as X,ResClientTools as _,ResServerTools as q,ResponseRStreamErrCode as Q,SSEChannel as Z,SSEChannelAlreadyClosedErrCode as $,Semaphore as ee,ServerToolFuncSchema as re,ServerTools as te,TaskAbortController as ae,Template as oe,TemplateArgProcessor as se,ToolAsyncCancelableBit as ne,ToolAsyncMultiTaskBit as ie,ToolAsyncPriorityBit as le,ToolFunc as me,ToolFuncSchema as ue,WindowsReservedNameRegex as ce,XXHashAlgorithm as de,_lrucache as pe,backendEventable as Se,base32768 as Te,builtins as he,countRegexMatches as Fe,createAbilityInjector as Ee,createCallbacksTransformer as ge,createEmptyReadableStream as Ce,createEndWithRepetitionDetector as ve,createError as Ae,createEventStreamTransformer as fe,createHfValueFunc as xe,createLRUCache as ye,dateToText as Re,defaultTemplateFormat as be,event as Ie,eventClient as Pe,eventServer as Ne,expandEnv as He,expandObjEnv as je,extNameLevel as ke,fileIsExists as De,filenameReservedRegex as Oe,filterValidFnScope as Ve,formatISO as Be,getAllEnumKeys as Le,getConfigFileNames as Me,getConfigs as ze,getKeysPath as we,getMultiLevelExtname as Ge,getRealFilepath as Ue,getResponseErrorReadableStream as Ye,interpolateEnv as We,interpolateFString as Je,interpolateGolangTemplate as Ke,isModelNameMatched as Xe,isValidFilename as _e,isValidFilepath as qe,isWebStream as Qe,jsonFilterToWhere as Ze,jsonToMarkdownStr as $e,loadFileFromPaths as er,loadTextFromPaths as rr,lrucache as tr,makeToolFuncCancelable as ar,matchUrlProtocol as or,messagesToText as sr,mimeType as nr,paramsSizeToScaleStr as ir,parse as lr,parse2 as mr,parseCommand as ur,parseDateFormat as cr,parseFString as dr,parseISO as pr,parseJsJson as Sr,parseObjectArgInfo as Tr,parseObjectArgumentInfos as hr,parseObjectArguments as Fr,parseObjectArgumentsAsArgInfos as Er,parseYaml as gr,quoteStr as Cr,reControlCharsRegex as vr,readFilenamesRecursiveSync as Ar,readableFromAsyncIterable as fr,registerCoreTools as xr,registerYamlTag as yr,sanitizeFilename as Rr,sanitizeFilepath as br,saveConfigFile as Ir,scaleStrToParamsSize as Pr,sortedValues as Nr,splitSentence as Hr,stringify as jr,stringify2 as kr,textToDate as Dr,throwError as Or,toDate as Vr,toDateTime as Br,tokenize as Lr,trimStartOfStreamHelper as Mr,truncTo as zr,utils_exports as wr,uuid as Gr,v1 as Ur,v4 as Yr,v5 as Wr,validate as Jr,version as Kr,wait as Xr,xxhash as _r,xxhash32 as qr,xxhash64 as Qr,xxhashAsStr as Zr}from"./chunk-4LD7IUUG.mjs";import{__export as $r,__reExport as et}from"./chunk-U5DDQYSF.mjs";var rt={};$r(rt,{AIArgProcessor:()=>e,AIChatRoles:()=>r,AIMessageTypes:()=>t,AIStream:()=>a,AITextGenerationFinishReasons:()=>o,AbortError:()=>s,AbortErrorCode:()=>n,ActionNames:()=>i,AlreadyExistsError:()=>l,AlreadyExistsErrorCode:()=>m,AsyncFeatureBits:()=>u,AsyncFeatures:()=>c,BaseError:()=>d,CancelableAbility:()=>p,ChoiceArgProcessor:()=>S,ClientToolFuncSchema:()=>T,ClientTools:()=>h,CommonError:()=>F,ConfigFile:()=>E,DefaultAsyncSemaphoreCapacity:()=>g,ErrorCode:()=>v,EventBusName:()=>A,EventClient:()=>f,EventName:()=>x,EventServer:()=>y,EventToolFunc:()=>R,FStringPromptTemplate:()=>b,FewShotPromptTemplate:()=>I,FilenameReservedRegex:()=>P,GolangPromptTemplate:()=>N,HFBuiltins:()=>he,HFEnvironment:()=>C,HFInterpreter:()=>D,HFTemplate:()=>oe,HfPromptTemplate:()=>H,IntSet:()=>j,InternalErrorCode:()=>k,NotFoundError:()=>V,NotFoundErrorCode:()=>B,NotImplementationError:()=>L,NotImplementedErrorCode:()=>M,PASSING_SCORE:()=>z,PromptExampleSelector:()=>w,PromptTemplate:()=>G,PromptTemplateTypes:()=>U,PromptTypes:()=>Y,RStreamErrCode:()=>W,RateLimit:()=>J,ReadableStreamError:()=>K,RemoteToolFuncSchema:()=>X,ResClientTools:()=>_,ResServerTools:()=>q,ResponseRStreamErrCode:()=>Q,SSEChannel:()=>Z,SSEChannelAlreadyClosedErrCode:()=>$,Semaphore:()=>ee,ServerToolFuncSchema:()=>re,ServerTools:()=>te,TaskAbortController:()=>ae,TemplateArgProcessor:()=>se,ToolAsyncCancelableBit:()=>ne,ToolAsyncMultiTaskBit:()=>ie,ToolAsyncPriorityBit:()=>le,ToolFunc:()=>me,ToolFuncSchema:()=>ue,WindowsReservedNameRegex:()=>ce,XXHashAlgorithm:()=>de,_lrucache:()=>pe,backendEventable:()=>Se,base32768:()=>Te,countRegexMatches:()=>Fe,createAbilityInjector:()=>Ee,createCallbacksTransformer:()=>ge,createEmptyReadableStream:()=>Ce,createEndWithRepetitionDetector:()=>ve,createError:()=>Ae,createEventStreamTransformer:()=>fe,createHfValueFunc:()=>xe,createLRUCache:()=>ye,dateToText:()=>Re,defaultTemplateFormat:()=>be,event:()=>Ie,eventClient:()=>Pe,eventServer:()=>Ne,expandEnv:()=>He,expandObjEnv:()=>je,extNameLevel:()=>ke,fileIsExists:()=>De,filenameReservedRegex:()=>Oe,filterValidFnScope:()=>Ve,formatISO:()=>Be,getAllEnumKeys:()=>Le,getConfigFileNames:()=>Me,getConfigs:()=>ze,getKeysPath:()=>we,getMultiLevelExtname:()=>Ge,getRealFilepath:()=>Ue,getResponseErrorReadableStream:()=>Ye,hfParse:()=>lr,hfTokenize:()=>Lr,interpolateEnv:()=>We,interpolateFString:()=>Je,interpolateGolangTemplate:()=>Ke,isModelNameMatched:()=>Xe,isValidFilename:()=>_e,isValidFilepath:()=>qe,isWebStream:()=>Qe,jsonFilterToWhere:()=>Ze,jsonToMarkdownStr:()=>$e,loadFileFromPaths:()=>er,loadTextFromPaths:()=>rr,lrucache:()=>tr,makeToolFuncCancelable:()=>ar,matchUrlProtocol:()=>or,messagesToText:()=>sr,mimeType:()=>nr,paramsSizeToScaleStr:()=>ir,parseCommand:()=>ur,parseDateFormat:()=>cr,parseFString:()=>dr,parseISO:()=>pr,parseJsJson:()=>Sr,parseObjectArgInfo:()=>Tr,parseObjectArgumentInfos:()=>hr,parseObjectArguments:()=>Fr,parseObjectArgumentsAsArgInfos:()=>Er,parseYaml:()=>gr,quoteStr:()=>Cr,reControlCharsRegex:()=>vr,readFilenamesRecursiveSync:()=>Ar,readableFromAsyncIterable:()=>fr,registerCoreTools:()=>xr,registerYamlTag:()=>yr,sanitizeFilename:()=>Rr,sanitizeFilepath:()=>br,saveConfigFile:()=>Ir,scaleStrToParamsSize:()=>Pr,sortedValues:()=>Nr,splitSentence:()=>Hr,stringifyYaml:()=>kr,textToDate:()=>Dr,throwError:()=>Or,toDate:()=>Vr,toDateTime:()=>Br,trimStartOfStreamHelper:()=>Mr,truncTo:()=>zr,uuid:()=>Gr,uuidNIL:()=>O,uuidParse:()=>mr,uuidStringify:()=>jr,uuidValidate:()=>Jr,uuidVersion:()=>Kr,uuidv1:()=>Ur,uuidv4:()=>Yr,uuidv5:()=>Wr,wait:()=>Xr,xxhash:()=>_r,xxhash32:()=>qr,xxhash64:()=>Qr,xxhashAsStr:()=>Zr}),et(rt,wr);export{e as AIArgProcessor,r as AIChatRoles,t as AIMessageTypes,a as AIStream,o as AITextGenerationFinishReasons,s as AbortError,n as AbortErrorCode,i as ActionNames,l as AlreadyExistsError,m as AlreadyExistsErrorCode,u as AsyncFeatureBits,c as AsyncFeatures,d as BaseError,p as CancelableAbility,S as ChoiceArgProcessor,T as ClientToolFuncSchema,h as ClientTools,F as CommonError,E as ConfigFile,g as DefaultAsyncSemaphoreCapacity,v as ErrorCode,A as EventBusName,f as EventClient,x as EventName,y as EventServer,R as EventToolFunc,b as FStringPromptTemplate,I as FewShotPromptTemplate,P as FilenameReservedRegex,N as GolangPromptTemplate,he as HFBuiltins,C as HFEnvironment,D as HFInterpreter,oe as HFTemplate,H as HfPromptTemplate,j as IntSet,k as InternalErrorCode,V as NotFoundError,B as NotFoundErrorCode,L as NotImplementationError,M as NotImplementedErrorCode,z as PASSING_SCORE,w as PromptExampleSelector,G as PromptTemplate,U as PromptTemplateTypes,Y as PromptTypes,W as RStreamErrCode,J as RateLimit,K as ReadableStreamError,X as RemoteToolFuncSchema,_ as ResClientTools,q as ResServerTools,Q as ResponseRStreamErrCode,Z as SSEChannel,$ as SSEChannelAlreadyClosedErrCode,ee as Semaphore,re as ServerToolFuncSchema,te as ServerTools,ae as TaskAbortController,se as TemplateArgProcessor,ne as ToolAsyncCancelableBit,ie as ToolAsyncMultiTaskBit,le as ToolAsyncPriorityBit,me as ToolFunc,ue as ToolFuncSchema,ce as WindowsReservedNameRegex,de as XXHashAlgorithm,pe as _lrucache,Se as backendEventable,Te as base32768,Fe as countRegexMatches,Ee as createAbilityInjector,ge as createCallbacksTransformer,Ce as createEmptyReadableStream,ve as createEndWithRepetitionDetector,Ae as createError,fe as createEventStreamTransformer,xe as createHfValueFunc,ye as createLRUCache,Re as dateToText,be as defaultTemplateFormat,Ie as event,Pe as eventClient,Ne as eventServer,He as expandEnv,je as expandObjEnv,ke as extNameLevel,De as fileIsExists,Oe as filenameReservedRegex,Ve as filterValidFnScope,Be as formatISO,Le as getAllEnumKeys,Me as getConfigFileNames,ze as getConfigs,we as getKeysPath,Ge as getMultiLevelExtname,Ue as getRealFilepath,Ye as getResponseErrorReadableStream,lr as hfParse,Lr as hfTokenize,We as interpolateEnv,Je as interpolateFString,Ke as interpolateGolangTemplate,Xe as isModelNameMatched,_e as isValidFilename,qe as isValidFilepath,Qe as isWebStream,Ze as jsonFilterToWhere,$e as jsonToMarkdownStr,er as loadFileFromPaths,rr as loadTextFromPaths,tr as lrucache,ar as makeToolFuncCancelable,or as matchUrlProtocol,sr as messagesToText,nr as mimeType,ir as paramsSizeToScaleStr,ur as parseCommand,cr as parseDateFormat,dr as parseFString,pr as parseISO,Sr as parseJsJson,Tr as parseObjectArgInfo,hr as parseObjectArgumentInfos,Fr as parseObjectArguments,Er as parseObjectArgumentsAsArgInfos,gr as parseYaml,Cr as quoteStr,vr as reControlCharsRegex,Ar as readFilenamesRecursiveSync,fr as readableFromAsyncIterable,xr as registerCoreTools,yr as registerYamlTag,Rr as sanitizeFilename,br as sanitizeFilepath,Ir as saveConfigFile,Pr as scaleStrToParamsSize,Nr as sortedValues,Hr as splitSentence,kr as stringifyYaml,Dr as textToDate,Or as throwError,Vr as toDate,Br as toDateTime,Mr as trimStartOfStreamHelper,zr as truncTo,Gr as uuid,O as uuidNIL,mr as uuidParse,jr as uuidStringify,Jr as uuidValidate,Kr as uuidVersion,Ur as uuidv1,Yr as uuidv4,Wr as uuidv5,Xr as wait,_r as xxhash,qr as xxhash32,Qr as xxhash64,Zr as xxhashAsStr};
1
+ import{AIArgProcessor as a,AIChatRoles as s,AIMessageTypes as i,AIStream as u,AITextGenerationFinishReasons as e,AbortError as r,AbortErrorCode as n,ActionNames as t,AlreadyExistsError as d,AlreadyExistsErrorCode as m,AsyncFeatureBits as o,AsyncFeatures as f,BaseError as l,CancelableAbility as p,ChoiceArgProcessor as v,ClientToolFuncSchema as F,ClientTools as H,CommonError as h,ConfigFile as I,DefaultAsyncSemaphoreCapacity as g,EnvironmentEx as k,ErrorCode as y,EventBusName as P,EventClient as T,EventName as V,EventServer as c,EventToolFunc as j,FStringPromptTemplate as x,FewShotPromptTemplate as z,FilenameReservedRegex as B,GolangPromptTemplate as C,HfPromptTemplate as E,IntSet as L,InternalErrorCode as N,Interpreter as O,NIL as Q,NotFoundError as S,NotFoundErrorCode as U,NotImplementationError as X,NotImplementedErrorCode as Y,PASSING_SCORE as b,PromptExampleSelector as q,PromptTemplate as w,PromptTemplateTypes as A,PromptTypes as D,RStreamErrCode as G,RateLimit as J,ReadableStreamError as K,RemoteToolFuncSchema as M,ResClientTools as R,ResServerTools as W,ResponseRStreamErrCode as Z,SSEChannel as $,SSEChannelAlreadyClosedErrCode as _,Semaphore as aa,ServerToolFuncSchema as sa,ServerTools as ia,TaskAbortController as ua,Template as ea,TemplateArgProcessor as ra,ToolAsyncCancelableBit as na,ToolAsyncMultiTaskBit as ta,ToolAsyncPriorityBit as da,ToolFunc as ma,ToolFuncSchema as oa,WindowsReservedNameRegex as fa,XXHashAlgorithm as la,_lrucache as pa,backendEventable as va,base32768 as Fa,builtins as Ha,canonicalize as ha,countRegexMatches as Ia,createAbilityInjector as ga,createCallbacksTransformer as ka,createEmptyReadableStream as ya,createEndWithRepetitionDetector as Pa,createError as Ta,createEventStreamTransformer as Va,createHfValueFunc as ca,createLRUCache as ja,dateToText as xa,defaultTemplateFormat as za,event as Ba,eventClient as Ca,eventServer as Ea,expandEnv as La,expandObjEnv as Na,extNameLevel as Oa,fileIsExists as Qa,filenameReservedRegex as Sa,filterValidFnScope as Ua,formatISO as Xa,getAllEnumKeys as Ya,getConfigFileNames as ba,getConfigs as qa,getKeysPath as wa,getMultiLevelExtname as Aa,getRealFilepath as Da,getResponseErrorReadableStream as Ga,interpolateEnv as Ja,interpolateFString as Ka,interpolateGolangTemplate as Ma,isModelNameMatched as Ra,isValidFilename as Wa,isValidFilepath as Za,isWebStream as $a,jsonFilterToWhere as _a,jsonToMarkdownStr as as,loadFileFromPaths as ss,loadTextFromPaths as is,lrucache as us,makeToolFuncCancelable as es,matchUrlProtocol as rs,memoize as ns,messagesToText as ts,mimeType as ds,paramsSizeToScaleStr as ms,parse as os,parse2 as fs,parseCommand as ls,parseDateFormat as ps,parseFString as vs,parseISO as Fs,parseJsJson as Hs,parseObjectArgInfo as hs,parseObjectArgumentInfos as Is,parseObjectArguments as gs,parseObjectArgumentsAsArgInfos as ks,parseYaml as ys,quoteStr as Ps,reControlCharsRegex as Ts,readFilenamesRecursiveSync as Vs,readableFromAsyncIterable as cs,registerCoreTools as js,registerYamlTag as xs,sanitizeFilename as zs,sanitizeFilepath as Bs,saveConfigFile as Cs,scaleStrToParamsSize as Es,sortedValues as Ls,splitSentence as Ns,stringify as Os,stringify2 as Qs,textToDate as Ss,throwError as Us,toDate as Xs,toDateTime as Ys,tokenize as bs,trimStartOfStreamHelper as qs,truncTo as ws,uuid as As,v1 as Ds,v4 as Gs,v5 as Js,validate as Ks,version as Ms,wait as Rs,xxhash as Ws,xxhash32 as Zs,xxhash64 as $s,xxhashAsStr as _s}from"./chunk-COXUI4Q3.mjs";export{a as AIArgProcessor,s as AIChatRoles,i as AIMessageTypes,u as AIStream,e as AITextGenerationFinishReasons,r as AbortError,n as AbortErrorCode,t as ActionNames,d as AlreadyExistsError,m as AlreadyExistsErrorCode,o as AsyncFeatureBits,f as AsyncFeatures,l as BaseError,p as CancelableAbility,v as ChoiceArgProcessor,F as ClientToolFuncSchema,H as ClientTools,h as CommonError,I as ConfigFile,g as DefaultAsyncSemaphoreCapacity,y as ErrorCode,P as EventBusName,T as EventClient,V as EventName,c as EventServer,j as EventToolFunc,x as FStringPromptTemplate,z as FewShotPromptTemplate,B as FilenameReservedRegex,C as GolangPromptTemplate,Ha as HFBuiltins,k as HFEnvironment,O as HFInterpreter,ea as HFTemplate,E as HfPromptTemplate,L as IntSet,N as InternalErrorCode,S as NotFoundError,U as NotFoundErrorCode,X as NotImplementationError,Y as NotImplementedErrorCode,b as PASSING_SCORE,q as PromptExampleSelector,w as PromptTemplate,A as PromptTemplateTypes,D as PromptTypes,G as RStreamErrCode,J as RateLimit,K as ReadableStreamError,M as RemoteToolFuncSchema,R as ResClientTools,W as ResServerTools,Z as ResponseRStreamErrCode,$ as SSEChannel,_ as SSEChannelAlreadyClosedErrCode,aa as Semaphore,sa as ServerToolFuncSchema,ia as ServerTools,ua as TaskAbortController,ra as TemplateArgProcessor,na as ToolAsyncCancelableBit,ta as ToolAsyncMultiTaskBit,da as ToolAsyncPriorityBit,ma as ToolFunc,oa as ToolFuncSchema,fa as WindowsReservedNameRegex,la as XXHashAlgorithm,pa as _lrucache,va as backendEventable,Fa as base32768,ha as canonicalize,Ia as countRegexMatches,ga as createAbilityInjector,ka as createCallbacksTransformer,ya as createEmptyReadableStream,Pa as createEndWithRepetitionDetector,Ta as createError,Va as createEventStreamTransformer,ca as createHfValueFunc,ja as createLRUCache,xa as dateToText,za as defaultTemplateFormat,Ba as event,Ca as eventClient,Ea as eventServer,La as expandEnv,Na as expandObjEnv,Oa as extNameLevel,Qa as fileIsExists,Sa as filenameReservedRegex,Ua as filterValidFnScope,Xa as formatISO,Ya as getAllEnumKeys,ba as getConfigFileNames,qa as getConfigs,wa as getKeysPath,Aa as getMultiLevelExtname,Da as getRealFilepath,Ga as getResponseErrorReadableStream,os as hfParse,bs as hfTokenize,Ja as interpolateEnv,Ka as interpolateFString,Ma as interpolateGolangTemplate,Ra as isModelNameMatched,Wa as isValidFilename,Za as isValidFilepath,$a as isWebStream,_a as jsonFilterToWhere,as as jsonToMarkdownStr,ss as loadFileFromPaths,is as loadTextFromPaths,us as lrucache,es as makeToolFuncCancelable,rs as matchUrlProtocol,ns as memoize,ts as messagesToText,ds as mimeType,ms as paramsSizeToScaleStr,ls as parseCommand,ps as parseDateFormat,vs as parseFString,Fs as parseISO,Hs as parseJsJson,hs as parseObjectArgInfo,Is as parseObjectArgumentInfos,gs as parseObjectArguments,ks as parseObjectArgumentsAsArgInfos,ys as parseYaml,Ps as quoteStr,Ts as reControlCharsRegex,Vs as readFilenamesRecursiveSync,cs as readableFromAsyncIterable,js as registerCoreTools,xs as registerYamlTag,zs as sanitizeFilename,Bs as sanitizeFilepath,Cs as saveConfigFile,Es as scaleStrToParamsSize,Ls as sortedValues,Ns as splitSentence,Qs as stringifyYaml,Ss as textToDate,Us as throwError,Xs as toDate,Ys as toDateTime,qs as trimStartOfStreamHelper,ws as truncTo,As as uuid,Q as uuidNIL,fs as uuidParse,Os as uuidStringify,Ks as uuidValidate,Ms as uuidVersion,Ds as uuidv1,Gs as uuidv4,Js as uuidv5,Rs as wait,Ws as xxhash,Zs as xxhash32,$s as xxhash64,_s as xxhashAsStr};
@@ -1 +1 @@
1
- import"../chunk-U5DDQYSF.mjs";function r(r,e){expect(r.length).toBeGreaterThanOrEqual(e.length);for(let n=0;n<e.length;n++)if(r[n]!==e[n])return!1;return!0}import e from"net";async function n(r,n=10){return new Promise(((t,o)=>{void 0===r?r=0:(r=parseInt(r))>=0||(r=0);const i=e.createServer();i.on("error",(e=>{"EADDRINUSE"===e.code&&(r++,--n>0)?i.listen(r):o(e)})),i.on("listening",(async()=>{const r=i.address().port;i.close(),t(r)})),i.listen(r)}))}import{existsSync as t,rmSync as o}from"fs";function i(r){t(r)&&o(r,{recursive:!0}),t(r+".temp")&&o(r+".temp",{recursive:!0})}export{r as compareStr,n as findPort,i as rmFile};
1
+ function r(r,e){expect(r.length).toBeGreaterThanOrEqual(e.length);for(let n=0;n<e.length;n++)if(r[n]!==e[n])return!1;return!0}import e from"net";async function n(r,n=10){return new Promise(((t,o)=>{void 0===r?r=0:(r=parseInt(r))>=0||(r=0);const i=e.createServer();i.on("error",(e=>{"EADDRINUSE"===e.code&&(r++,--n>0)?i.listen(r):o(e)})),i.on("listening",(async()=>{const r=i.address().port;i.close(),t(r)})),i.listen(r)}))}import{existsSync as t,rmSync as o}from"fs";function i(r){t(r)&&o(r,{recursive:!0}),t(r+".temp")&&o(r+".temp",{recursive:!0})}export{r as compareStr,n as findPort,i as rmFile};