@isdk/ai-tool 0.0.7 → 0.0.9

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