@isdk/ai-tool 0.1.5 → 0.2.1
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.
- package/dist/chunk-PXQPLL62.mjs +1 -0
- package/dist/chunk-TOUPOZHH.mjs +1 -0
- package/dist/find-port-qS1CZ9c-.d.mts +3 -0
- package/dist/find-port-qS1CZ9c-.d.ts +3 -0
- package/dist/funcs.d.mts +2 -2
- package/dist/funcs.d.ts +2 -2
- package/dist/funcs.js +1 -1
- package/dist/funcs.mjs +1 -1
- package/dist/{index-DvpywQaE.d.mts → index-DUEs7T8M.d.mts} +5 -153
- package/dist/{index-DvpywQaE.d.ts → index-DUEs7T8M.d.ts} +5 -153
- package/dist/index.d.mts +23 -5
- package/dist/index.d.ts +23 -5
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/test/util.d.mts +3 -3
- package/dist/test/util.d.ts +3 -3
- package/dist/test/util.js +1 -1
- package/dist/test/util.mjs +1 -1
- package/docs/README.md +5 -3
- package/docs/_media/CONTRIBUTING.md +18 -0
- package/docs/_media/LICENSE-MIT +22 -0
- package/docs/classes/AbortError.md +108 -129
- package/docs/classes/AlreadyExistsError.md +105 -126
- package/docs/classes/BaseError.md +112 -125
- package/docs/classes/CancelableAbility.md +136 -188
- package/docs/classes/ClientTools.md +1005 -1107
- package/docs/classes/CommonError.md +115 -136
- package/docs/classes/ConfigFile.md +150 -163
- package/docs/classes/EventClient.md +1128 -1282
- package/docs/classes/EventServer.md +1165 -1303
- package/docs/classes/EventToolFunc.md +958 -1028
- package/docs/classes/FStringPromptTemplate.md +352 -438
- package/docs/classes/FewShotPromptTemplate.md +364 -464
- package/docs/classes/GolangPromptTemplate.md +352 -438
- package/docs/classes/HFEnvironment.md +53 -79
- package/docs/classes/HFInterpreter.md +20 -377
- package/docs/classes/HFTemplate.md +21 -33
- package/docs/classes/HfPromptTemplate.md +352 -438
- package/docs/classes/IntSet.md +67 -100
- package/docs/classes/NotFoundError.md +105 -126
- package/docs/classes/NotImplementationError.md +105 -126
- package/docs/classes/PromptExampleSelector.md +58 -70
- package/docs/classes/PromptTemplate.md +338 -422
- package/docs/classes/ReadableStreamError.md +108 -129
- package/docs/classes/ResClientTools.md +916 -1026
- package/docs/classes/ResServerTools.md +919 -1026
- package/docs/classes/SSEChannel.md +93 -112
- package/docs/classes/Semaphore.md +44 -140
- package/docs/classes/ServerTools.md +981 -1072
- package/docs/classes/TaskAbortController.md +46 -66
- package/docs/classes/ToolFunc.md +840 -910
- package/docs/enumerations/AsyncFeatureBits.md +37 -0
- package/docs/enumerations/AsyncFeatures.md +37 -0
- package/docs/enumerations/ErrorCode.md +217 -0
- package/docs/enumerations/XXHashAlgorithm.md +27 -0
- package/docs/functions/AIArgProcessor.md +27 -0
- package/docs/functions/AIStream.md +50 -0
- package/docs/functions/ChoiceArgProcessor.md +27 -0
- package/docs/functions/RateLimit.md +33 -0
- package/docs/functions/TemplateArgProcessor.md +27 -0
- package/docs/functions/backendEventable.md +23 -0
- package/docs/functions/canonicalize.md +21 -0
- package/docs/functions/countRegexMatches.md +33 -0
- package/docs/functions/createAbilityInjector.md +87 -0
- package/docs/functions/createCallbacksTransformer.md +49 -0
- package/docs/functions/createEmptyReadableStream.md +23 -0
- package/docs/functions/createEndWithRepetitionDetector.md +29 -0
- package/docs/functions/createError.md +35 -0
- package/docs/functions/createEventStreamTransformer.md +33 -0
- package/docs/functions/createHfValueFunc.md +29 -0
- package/docs/functions/createLRUCache.md +23 -0
- package/docs/functions/dateToText.md +23 -0
- package/docs/functions/expandEnv.md +40 -0
- package/docs/functions/expandObjEnv.md +54 -0
- package/docs/functions/extNameLevel.md +43 -0
- package/docs/functions/fileIsExists.md +34 -0
- package/docs/functions/filenameReservedRegex.md +22 -0
- package/docs/functions/filterValidFnScope.md +21 -0
- package/docs/functions/findPort.md +23 -0
- package/docs/functions/formatISO.md +71 -0
- package/docs/functions/getAllEnumKeys.md +31 -0
- package/docs/functions/getConfigFileNames.md +23 -0
- package/docs/functions/getConfigs.md +23 -0
- package/docs/functions/getKeysPath.md +38 -0
- package/docs/functions/getMultiLevelExtname.md +31 -0
- package/docs/functions/getPackageDir.md +39 -0
- package/docs/functions/getRealFilepath.md +34 -0
- package/docs/functions/getResponseErrorReadableStream.md +21 -0
- package/docs/functions/hfParse.md +24 -0
- package/docs/functions/hfTokenize.md +25 -0
- package/docs/functions/interpolateEnv.md +25 -0
- package/docs/functions/interpolateFString.md +27 -0
- package/docs/functions/interpolateGolangTemplate.md +31 -0
- package/docs/functions/isModelNameMatched.md +45 -0
- package/docs/functions/isValidFilename.md +38 -0
- package/docs/functions/isValidFilepath.md +27 -0
- package/docs/functions/isWebStream.md +21 -0
- package/docs/functions/jsonFilterToWhere.md +45 -0
- package/docs/functions/jsonToMarkdownStr.md +31 -0
- package/docs/functions/loadFileFromPaths.md +54 -0
- package/docs/functions/loadTextFromPaths.md +29 -0
- package/docs/functions/lrucache.md +29 -0
- package/docs/functions/makeToolFuncCancelable.md +23 -0
- package/docs/functions/matchUrlProtocol.md +48 -0
- package/docs/functions/memoize.md +27 -0
- package/docs/functions/messagesToText.md +21 -0
- package/docs/functions/paramsSizeToScaleStr.md +32 -0
- package/docs/functions/parseCommand.md +33 -0
- package/docs/functions/parseDateFormat.md +360 -0
- package/docs/functions/parseFString.md +26 -0
- package/docs/functions/parseISO.md +72 -0
- package/docs/functions/parseJsJson.md +38 -0
- package/docs/functions/parseObjectArgInfo.md +27 -0
- package/docs/functions/parseObjectArgumentInfos.md +25 -0
- package/docs/functions/parseObjectArguments.md +68 -0
- package/docs/functions/parseObjectArgumentsAsArgInfos.md +42 -0
- package/docs/functions/parseYaml.md +21 -0
- package/docs/functions/quoteStr.md +21 -0
- package/docs/functions/reControlCharsRegex.md +21 -0
- package/docs/functions/readFilenamesRecursiveSync.md +47 -0
- package/docs/functions/readableFromAsyncIterable.md +28 -0
- package/docs/functions/registerCoreTools.md +17 -0
- package/docs/functions/registerYamlTag.md +21 -0
- package/docs/functions/sanitizeFilename.md +37 -0
- package/docs/functions/sanitizeFilepath.md +31 -0
- package/docs/functions/saveConfigFile.md +25 -0
- package/docs/functions/scaleStrToParamsSize.md +27 -0
- package/docs/functions/simplifyObjectArguments.md +21 -0
- package/docs/functions/sortedValues.md +25 -0
- package/docs/functions/splitSentence.md +37 -0
- package/docs/functions/stringifyYaml.md +49 -0
- package/docs/functions/textToDate.md +23 -0
- package/docs/functions/throwError.md +37 -0
- package/docs/functions/toDate.md +76 -0
- package/docs/functions/toDateTime.md +21 -0
- package/docs/functions/trimStartOfStreamHelper.md +41 -0
- package/docs/functions/truncTo.md +47 -0
- package/docs/functions/uuid.md +23 -0
- package/docs/functions/uuidParse.md +21 -0
- package/docs/functions/uuidStringify.md +23 -0
- package/docs/functions/uuidValidate.md +21 -0
- package/docs/functions/uuidVersion.md +21 -0
- package/docs/functions/uuidv1.md +47 -0
- package/docs/functions/uuidv4.md +47 -0
- package/docs/functions/uuidv5.md +51 -0
- package/docs/functions/wait.md +21 -0
- package/docs/functions/xxhash.md +25 -0
- package/docs/functions/xxhash32.md +23 -0
- package/docs/functions/xxhash64.md +23 -0
- package/docs/functions/xxhashAsStr.md +25 -0
- package/docs/globals.md +236 -0
- package/docs/interfaces/AIChatAssistantMessageParam.md +29 -38
- package/docs/interfaces/AIChatContentPartImage.md +11 -16
- package/docs/interfaces/AIChatContentPartText.md +9 -12
- package/docs/interfaces/AIChatMessageParamBase.md +12 -19
- package/docs/interfaces/AIChatMessageToolCall.md +18 -21
- package/docs/interfaces/AIChatSystemMessageParam.md +16 -22
- package/docs/interfaces/AIChatToolMessageParam.md +19 -26
- package/docs/interfaces/AIChatUserMessageParam.md +32 -42
- package/docs/interfaces/AIChoiceConfig.md +31 -39
- package/docs/interfaces/AIResult.md +26 -33
- package/docs/interfaces/AIStreamParser.md +24 -18
- package/docs/interfaces/AIStreamParserOptions.md +8 -10
- package/docs/interfaces/BaseFunc.md +55 -75
- package/docs/interfaces/BaseFuncItem.md +43 -61
- package/docs/interfaces/CancelableAbilityOptions.md +43 -54
- package/docs/interfaces/ClientFuncItem.md +66 -83
- package/docs/interfaces/DotenvExpandOptions.md +15 -19
- package/docs/interfaces/DotenvExpandOutput.md +11 -14
- package/docs/interfaces/DotenvParseInput.md +6 -2
- package/docs/interfaces/DotenvParseOutput.md +6 -2
- package/docs/interfaces/DotenvPopulateInput.md +6 -2
- package/docs/interfaces/EventClientFuncParams.md +22 -33
- package/docs/interfaces/EventServerFuncParams.md +27 -35
- package/docs/interfaces/FewShotPromptTemplateOptions.md +58 -74
- package/docs/interfaces/FuncItem.md +53 -70
- package/docs/interfaces/FuncParam.md +29 -36
- package/docs/interfaces/FuncParams.md +6 -2
- package/docs/interfaces/Funcs.md +6 -2
- package/docs/interfaces/JsonFilter.md +6 -2
- package/docs/interfaces/ParseObjectArgumentOptions.md +23 -29
- package/docs/interfaces/PromptExampleSelectorOptions.md +13 -16
- package/docs/interfaces/PromptTemplateOptions.md +31 -40
- package/docs/interfaces/RemoteFuncItem.md +64 -82
- package/docs/interfaces/ResClientFuncParams.md +14 -19
- package/docs/interfaces/ResServerFuncParams.md +28 -36
- package/docs/interfaces/SanitizeFilenameOptions.md +11 -14
- package/docs/interfaces/ServerFuncItem.md +70 -88
- package/docs/interfaces/ServerFuncParams.md +15 -20
- package/docs/interfaces/StreamCallbacksAndOptions.md +36 -65
- package/docs/interfaces/TaskAbortControllers.md +6 -2
- package/docs/interfaces/TaskPromise.md +48 -61
- package/docs/interfaces/ToolFuncPackage.md +18 -32
- package/docs/type-aliases/AIChatContentPart.md +13 -0
- package/docs/type-aliases/AIChatMessageParam.md +13 -0
- package/docs/type-aliases/AIChatRole.md +13 -0
- package/docs/type-aliases/AIMessageType.md +13 -0
- package/docs/type-aliases/AIModelNameRule.md +13 -0
- package/docs/type-aliases/AIModelNameRuleFn.md +21 -0
- package/docs/type-aliases/AIModelNameRules.md +13 -0
- package/docs/type-aliases/AITextGenerationFinishReason.md +13 -0
- package/docs/type-aliases/ActionName.md +13 -0
- package/docs/type-aliases/AsyncTaskId.md +13 -0
- package/docs/type-aliases/EventErrorListenerFn.md +27 -0
- package/docs/type-aliases/EventListenerFn.md +25 -0
- package/docs/type-aliases/FStringPromptTemplateNode.md +16 -0
- package/docs/type-aliases/FuncParamType.md +13 -0
- package/docs/type-aliases/PromptExamples.md +17 -0
- package/docs/type-aliases/PromptTemplateType.md +13 -0
- package/docs/type-aliases/PromptType.md +13 -0
- package/docs/type-aliases/TFunc.md +23 -0
- package/docs/variables/AIChatRoles.md +13 -0
- package/docs/variables/AIMessageTypes.md +13 -0
- package/docs/variables/AITextGenerationFinishReasons.md +13 -0
- package/docs/variables/AbortErrorCode.md +13 -0
- package/docs/variables/ActionNames.md +13 -0
- package/docs/variables/AlreadyExistsErrorCode.md +13 -0
- package/docs/variables/ClientToolFuncSchema.md +87 -0
- package/docs/variables/DefaultAsyncSemaphoreCapacity.md +13 -0
- package/docs/variables/EventBusName.md +13 -0
- package/docs/variables/EventName.md +13 -0
- package/docs/variables/FilenameReservedRegex.md +16 -0
- package/docs/variables/HFBuiltins.md +92 -0
- package/docs/variables/InternalErrorCode.md +13 -0
- package/docs/variables/NotFoundErrorCode.md +13 -0
- package/docs/variables/NotImplementedErrorCode.md +13 -0
- package/docs/variables/PASSING_SCORE.md +13 -0
- package/docs/variables/PromptTemplateTypes.md +13 -0
- package/docs/variables/PromptTypes.md +16 -0
- package/docs/variables/RStreamErrCode.md +13 -0
- package/docs/variables/RemoteToolFuncSchema.md +87 -0
- package/docs/variables/ResponseRStreamErrCode.md +13 -0
- package/docs/variables/SSEChannelAlreadyClosedErrCode.md +13 -0
- package/docs/variables/ServerToolFuncSchema.md +87 -0
- package/docs/variables/ToolAsyncCancelableBit.md +13 -0
- package/docs/variables/ToolAsyncMultiTaskBit.md +13 -0
- package/docs/variables/ToolAsyncPriorityBit.md +13 -0
- package/docs/variables/ToolFuncSchema.md +125 -0
- package/docs/variables/WindowsReservedNameRegex.md +15 -0
- package/docs/variables/base32768.md +13 -0
- package/docs/variables/defaultTemplateFormat.md +13 -0
- package/docs/variables/event.md +13 -0
- package/docs/variables/eventClient.md +13 -0
- package/docs/variables/eventServer.md +13 -0
- package/docs/variables/lrucache.md +13 -0
- package/docs/variables/mimeType.md +13 -0
- package/docs/variables/uuidNIL.md +13 -0
- package/package.json +28 -27
- package/dist/chunk-RNB2V3XB.mjs +0 -1
- package/docs/.nojekyll +0 -1
- package/docs/enums/AsyncFeatureBits.md +0 -41
- package/docs/enums/AsyncFeatures.md +0 -41
- package/docs/enums/ErrorCode.md +0 -239
- package/docs/enums/XXHashAlgorithm.md +0 -30
- package/docs/modules.md +0 -4020
package/dist/funcs.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var t,e=Object.create,r=Object.defineProperty,n=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,i=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,a=(t,e,i,a)=>{if(e&&"object"==typeof e||"function"==typeof e)for(let c of s(e))o.call(t,c)||c===i||r(t,c,{get:()=>e[c],enumerable:!(a=n(e,c))||a.enumerable});return t},c=(t,n,s)=>(s=null!=t?e(i(t)):{},a(!n&&t&&t.__esModule?s:r(s,"default",{value:t,enumerable:!0}),t)),u={};((t,e)=>{for(var n in e)r(t,n,{get:e[n],enumerable:!0})})(u,{EventClient:()=>ke,EventServer:()=>Me,EventToolFunc:()=>fe,_lrucache:()=>de,createLRUCache:()=>ye,event:()=>we,eventClient:()=>Se,eventServer:()=>qe,lrucache:()=>me,registerCoreTools:()=>Ie}),module.exports=(t=u,a(r({},"__esModule",{value:!0}),t));var h=require("events-ex"),l=require("property-manager"),f=require("util-ex"),w=require("abstract-error"),p=500,d=class t extends w.AbstractError{static createErrorClass(e,r,n=t){return(0,w.createErrorClass)(e,r,n)}constructor(t,e,r){super(t,e);const n=this.constructor;null!=e?this.code=e:n.code?this.code=n.code:this.code=n.name,r?"string"==typeof r?this.name=r:Object.assign(this,r):"string"==typeof this.code?this.name=this.code:this.name=n.name}toJSON(){const t={name:this.name,code:this.code,data:this.data,caller:this.caller,error:this.message,stack:this.stack};return Object.keys(t).forEach((e=>void 0===t[e]&&delete t[e])),t}fromJSON(e){const r=new t(e.message);return r.code=e.code,r.data=e.data,r.caller=e.caller,r.message=e.error,r.stack=e.stack,r}},y=class extends d{constructor(t,e,r=p){super(t,r,e)}},m=class extends y{constructor(t,e){t||(t="Not Implementation."),super(t,e,501)}};y[501]=m;var b=class extends y{static{this.code=404}constructor(t,e){super(`Could not find ${t}.`,e,404),this.data={what:t}}};y[404]=b;var g=class extends y{static{this.code=409}constructor(t,e){super(`The ${t} already exists.`,e,409),this.data={what:t}}};y[409]=g;var x=class extends y{static{this.code=499}constructor(t,e){e||(e="AbortError"),super(t?`The operation was aborted for ${t}.`:"The operation was aborted.",e,499),t&&(this.data={what:t})}};function E(t,e,r=p){const n=new(y[r]||y)(t,e,r);return"number"!=typeof n.code&&(n.code=r),n}function v(t,e,r=p){throw E(t,e,r)}y[499]=x;require("custom-ability");var k=["get","post","put","delete","patch","list","res"],S={apiRoot:{type:"string",get(){return this._apiRoot??this.constructor.apiRoot},set(t){this._apiRoot=t}},action:{type:"string",assign:(t,e,r,n,s)=>t||"post"},fetchOptions:{type:"object"},allowExportFunc:{type:"boolean"}},$=(require("date-fns"),require("date-fns"),require("custom-factory"));var O="default",j=class t extends $.BaseFactory{static from(t,e){return new this(t,e)}static async format(t){return new this(t).format()}static async formatIf(t){if(this.isTemplate(t)){return new this(t).format()}}static isTemplate(e){if(e?.template){const r=e.templateFormat||O,n=t.get(r);return n.isTemplate!==t.isTemplate&&n.isTemplate(e)}}filterData(t){return Array.isArray(this.inputVariables)&&(t=Object.fromEntries(Object.entries(t).filter((([t])=>this.inputVariables.includes(t))))),t}constructor(e,r){"string"==typeof e?(r||(r={}),r.template=e):e&&(e=(r=e).template);const{templateFormat:n}=r||{};if(super(r),this.constructor===t){const e=t.get(n||O);if(e)return Reflect.construct(e,arguments);throw new y(`Prompt template type ${n} not found`,"PromptTemplate",400)}}_initialize(t){throw new m("Not implemented","PromptTemplate")}initialize(e){this.constructor!==t&&(Object.assign(this,this.toJSON(e)),e?.ignoreInitialize||this._initialize(e))}_format(t){throw new m("Not implemented","PromptTemplate")}async format(e){const r=this.data;if(e={...r,...e},r)for(const[t,n]of Object.entries(r))e[t]===n&&"function"==typeof n&&(delete e[t],e[t]=await n(e));for(const[r,n]of Object.entries(e))n instanceof t&&(delete e[r],e[r]=await n.format(e));return this._format(e)}partial(t){t={...this.data,...t};const e=this.toJSON();return e.data=t,e.ignoreInitialize=!0,new this.constructor(e)}toJSON(e=this){let r={template:e.template,data:e.data,inputVariables:e.inputVariables,compiledTemplate:e.compiledTemplate};var n;return e.templateFormat&&t.get(e.templateFormat)!==this.constructor&&(r.templateFormat=e.templateFormat),n=r,r=Object.keys(n).reduce(((t,e)=>{const r=n[e];return null!=r&&(t[e]=r),t}),{}),r}};(async function(){let t=!1,e=!1;try{for await(const e of function*(){try{yield Promise.reject()}finally{t=!0}}())throw new Error("impossible")}catch{e=!0}return e&&t})().then((t=>{t}));var C=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),A=Object.freeze({set:C.Set,for:C.For,in:C.In,is:C.Is,if:C.If,else:C.Else,endif:C.EndIf,elif:C.ElseIf,endfor:C.EndFor,and:C.And,or:C.Or,not:C.Not,"not in":C.NotIn,macro:C.Macro,endmacro:C.EndMacro,true:C.BooleanLiteral,false:C.BooleanLiteral,True:C.BooleanLiteral,False:C.BooleanLiteral}),T=class{constructor(t,e){this.value=t,this.type=e}};function M(t){return/\w/.test(t)}function q(t){return/[0-9]/.test(t)}var I=[["{%",C.OpenStatement],["%}",C.CloseStatement],["{{",C.OpenExpression],["}}",C.CloseExpression],["(",C.OpenParen],[")",C.CloseParen],["{",C.OpenCurlyBracket],["}",C.CloseCurlyBracket],["[",C.OpenSquareBracket],["]",C.CloseSquareBracket],[",",C.Comma],[".",C.Dot],[":",C.Colon],["|",C.Pipe],["<=",C.ComparisonBinaryOperator],[">=",C.ComparisonBinaryOperator],["==",C.ComparisonBinaryOperator],["!=",C.ComparisonBinaryOperator],["<",C.ComparisonBinaryOperator],[">",C.ComparisonBinaryOperator],["+",C.AdditiveBinaryOperator],["-",C.AdditiveBinaryOperator],["*",C.MultiplicativeBinaryOperator],["/",C.MultiplicativeBinaryOperator],["%",C.MultiplicativeBinaryOperator],["=",C.Equals]],N=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);var V=class{constructor(){this.type="Statement"}},P=class extends V{constructor(t){super(),this.body=t,this.type="Program"}},U=class extends V{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r,this.type="If"}},B=class extends V{constructor(t,e,r,n){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=n,this.type="For"}},F=class extends V{constructor(t,e){super(),this.assignee=t,this.value=e,this.type="Set"}},_=class extends V{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r,this.type="Macro"}},L=class extends V{constructor(){super(...arguments),this.type="Expression"}},R=class extends L{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r,this.type="MemberExpression"}},J=class extends L{constructor(t,e){super(),this.callee=t,this.args=e,this.type="CallExpression"}},z=class extends L{constructor(t){super(),this.value=t,this.type="Identifier"}},W=class extends L{constructor(t){super(),this.value=t,this.type="Literal"}},K=class extends W{constructor(){super(...arguments),this.type="NumericLiteral"}},D=class extends W{constructor(){super(...arguments),this.type="StringLiteral"}},Z=class extends W{constructor(){super(...arguments),this.type="BooleanLiteral"}},H=class extends W{constructor(){super(...arguments),this.type="ArrayLiteral"}},G=class extends W{constructor(){super(...arguments),this.type="TupleLiteral"}},Q=class extends W{constructor(){super(...arguments),this.type="ObjectLiteral"}},X=class extends L{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r,this.type="BinaryExpression"}},Y=class extends L{constructor(t,e){super(),this.operand=t,this.filter=e,this.type="FilterExpression"}},tt=class extends L{constructor(t,e){super(),this.iterable=t,this.test=e,this.type="SelectExpression"}},et=class extends L{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r,this.type="TestExpression"}},rt=class extends L{constructor(t,e){super(),this.operator=t,this.argument=e,this.type="UnaryExpression"}},nt=class extends L{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r,this.type="SliceExpression"}},st=class extends L{constructor(t,e){super(),this.key=t,this.value=e,this.type="KeywordArgumentExpression"}};function it(t){const e=new P([]);let r=0;function n(e,n){const s=t[r++];if(!s||s.type!==e)throw new Error(`Parser Error: ${n}. ${s.type} !== ${e}.`);return s}function s(){let e;switch(t[r].type){case C.Text:e=new D(n(C.Text,"Expected text token").value);break;case C.OpenStatement:e=function(){let e;switch(n(C.OpenStatement,"Expected opening statement token"),t[r].type){case C.Set:++r,e=a(),n(C.CloseStatement,"Expected closing statement token");break;case C.If:++r,e=c(),n(C.OpenStatement,"Expected {% token"),n(C.EndIf,"Expected endif token"),n(C.CloseStatement,"Expected %} token");break;case C.Macro:++r,e=function(){const t=E();if("Identifier"!==t.type)throw new SyntaxError("Expected identifier following macro statement");const e=m();n(C.CloseStatement,"Expected closing statement token");const r=[];for(;i(C.OpenStatement,C.EndMacro);)r.push(s());return new _(t,e,r)}(),n(C.OpenStatement,"Expected {% token"),n(C.EndMacro,"Expected endmacro token"),n(C.CloseStatement,"Expected %} token");break;case C.For:++r,e=function(){const t=u(!0);if(!(t instanceof z||t instanceof G))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${t.type} instead`);n(C.In,"Expected `in` keyword following loop variable");const e=h();n(C.CloseStatement,"Expected closing statement token");const a=[];for(;i(C.OpenStatement,C.EndFor)&&i(C.OpenStatement,C.Else);)a.push(s());const c=[];if(o(C.OpenStatement,C.Else))for(++r,++r,n(C.CloseStatement,"Expected closing statement token");i(C.OpenStatement,C.EndFor);)c.push(s());return new B(t,e,a,c)}(),n(C.OpenStatement,"Expected {% token"),n(C.EndFor,"Expected endfor token"),n(C.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${t[r].type} ${t[r].value}`)}return e}(),e.isStatement=!0;break;case C.OpenExpression:e=function(){n(C.OpenExpression,"Expected opening expression token");const t=h();return n(C.CloseExpression,"Expected closing expression token"),t}(),e.isStatement=!0;break;default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}return e}function i(...e){return r+e.length<=t.length&&e.some(((e,n)=>e!==t[r+n].type))}function o(...e){return r+e.length<=t.length&&e.every(((e,n)=>e===t[r+n].type))}function a(){const t=h();if(o(C.Equals)){++r;const e=a();return new F(t,e)}return t}function c(){const e=h();n(C.CloseStatement,"Expected closing statement token");const i=[],a=[];for(;t[r]?.type!==C.OpenStatement||t[r+1]?.type!==C.ElseIf&&t[r+1]?.type!==C.Else&&t[r+1]?.type!==C.EndIf;)i.push(s());if(t[r]?.type===C.OpenStatement&&t[r+1]?.type!==C.EndIf)if(++r,o(C.ElseIf))n(C.ElseIf,"Expected elseif token"),a.push(c());else for(n(C.Else,"Expected else token"),n(C.CloseStatement,"Expected closing statement token");t[r]?.type!==C.OpenStatement||t[r+1]?.type!==C.EndIf;)a.push(s());return new U(e,i,a)}function u(t=!1){const e=t?E:h,n=[e()],s=o(C.Comma);for(;s&&(++r,n.push(e()),o(C.Comma)););return s?new G(n):n[0]}function h(){return function(){const t=l();if(o(C.If)){++r;const e=l();if(o(C.Else)){++r;const n=l();return new U(e,[t],[n])}return new tt(t,e)}return t}()}function l(){let e=f();for(;o(C.Or);){const n=t[r];++r;const s=f();e=new X(n,e,s)}return e}function f(){let e=w();for(;o(C.And);){const n=t[r];++r;const s=w();e=new X(n,e,s)}return e}function w(){let e;for(;o(C.Not);){const n=t[r];++r;const s=w();e=new rt(n,s)}return e??function(){let e=p();for(;o(C.ComparisonBinaryOperator)||o(C.In)||o(C.NotIn);){const n=t[r];++r;const s=p();e=new X(n,e,s)}return e}()}function p(){let e=g();for(;o(C.AdditiveBinaryOperator);){const n=t[r];++r;const s=g();e=new X(n,e,s)}return e}function d(){const e=function(){let e=E();for(;o(C.Dot)||o(C.OpenSquareBracket);){const s=t[r];let i;++r;const o=s.type!==C.Dot;if(o)i=b(),n(C.CloseSquareBracket,"Expected closing square bracket");else if(i=E(),"Identifier"!==i.type)throw new SyntaxError("Expected identifier following dot operator");e=new R(e,i,o)}return e}();return o(C.OpenParen)?y(e):e}function y(t){let e=new J(t,m());return o(C.OpenParen)&&(e=y(e)),e}function m(){n(C.OpenParen,"Expected opening parenthesis for arguments list");const t=function(){const t=[];for(;!o(C.CloseParen);){let e=h();if(o(C.Equals)){if(++r,!(e instanceof z))throw new SyntaxError("Expected identifier for keyword argument");const t=h();e=new st(e,t)}t.push(e),o(C.Comma)&&++r}return t}();return n(C.CloseParen,"Expected closing parenthesis for arguments list"),t}function b(){const t=[];let e=!1;for(;!o(C.CloseSquareBracket);)o(C.Colon)?(t.push(void 0),++r,e=!0):(t.push(h()),o(C.Colon)&&(++r,e=!0));if(0===t.length)throw new SyntaxError("Expected at least one argument for member/slice expression");if(e){if(t.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new nt(...t)}return t[0]}function g(){let e=x();for(;o(C.MultiplicativeBinaryOperator);){const n=t[r];++r;const s=x();e=new X(n,e,s)}return e}function x(){let t=function(){let t=d();for(;o(C.Pipe);){++r;let e=E();if(!(e instanceof z))throw new SyntaxError("Expected identifier for the filter");o(C.OpenParen)&&(e=y(e)),t=new Y(t,e)}return t}();for(;o(C.Is);){++r;const e=o(C.Not);e&&++r;let n=E();if(n instanceof Z&&(n=new z(n.value.toString())),!(n instanceof z))throw new SyntaxError("Expected identifier for the test");t=new et(t,e,n)}return t}function E(){const e=t[r];switch(e.type){case C.NumericLiteral:return++r,new K(Number(e.value));case C.StringLiteral:return++r,new D(e.value);case C.BooleanLiteral:return++r,new Z("true"===e.value.toLowerCase());case C.Identifier:return++r,new z(e.value);case C.OpenParen:{++r;const e=u();if(t[r].type!==C.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${t[r].type} instead`);return++r,e}case C.OpenSquareBracket:{++r;const t=[];for(;!o(C.CloseSquareBracket);)t.push(h()),o(C.Comma)&&++r;return++r,new H(t)}case C.OpenCurlyBracket:{++r;const t=new Map;for(;!o(C.CloseCurlyBracket);){const e=h();n(C.Colon,"Expected colon between key and value in object literal");const s=h();t.set(e,s),o(C.Comma)&&++r}return++r,new Q(t)}default:throw new SyntaxError(`Unexpected token: ${e.type}`)}}for(;r<t.length;)e.body.push(s());return e}function ot(t,e,r=1){void 0===e&&(e=t,t=0);const n=[];for(let s=t;s<e;s+=r)n.push(s);return n}function at(t,e,r,n=1){const s=Math.sign(n);s>=0?(e=(e??=0)<0?Math.max(t.length+e,0):Math.min(e,t.length),r=(r??=t.length)<0?Math.max(t.length+r,0):Math.min(r,t.length)):(e=(e??=t.length-1)<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),r=(r??=-1)<-1?Math.max(t.length+r,-1):Math.min(r,t.length-1));const i=[];for(let o=e;s*o<s*r;o+=n)i.push(t[o]);return i}function ct(t){return t.replace(/\b\w/g,(t=>t.toUpperCase()))}var ut=class{constructor(t=void 0){this.type="RuntimeValue",this.builtins=new Map,this.value=t}__bool__(){return new ft(!!this.value)}toString(){return""+this.value}toJSON(){return this.value}},ht=class extends ut{constructor(){super(...arguments),this.type="NumericValue"}},lt=class t extends ut{constructor(){super(...arguments),this.type="StringValue",this.builtins=new Map([["upper",new mt((()=>new t(this.value.toUpperCase())))],["lower",new mt((()=>new t(this.value.toLowerCase())))],["strip",new mt((()=>new t(this.value.trim())))],["title",new mt((()=>new t(ct(this.value))))],["length",new ht(this.value.length)],["rstrip",new mt((()=>new t(this.value.trimEnd())))],["lstrip",new mt((()=>new t(this.value.trimStart())))]])}},ft=class extends ut{constructor(){super(...arguments),this.type="BooleanValue"}},wt=class extends ut{constructor(t,e){super(t),this.orgValue=e,this.type="ObjectValue",this.builtins=new Map([["get",new mt((([t,e])=>{if(!(t instanceof lt))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new bt}))],["items",new mt((()=>new dt(Array.from(this.value.entries()).map((([t,e])=>new dt([new lt(t),e]))))))]])}toString(){let t;return t=this.orgValue&&this.orgValue.toString!==Object.prototype.toString?this.orgValue.toString():JSON.stringify(Object.fromEntries(this.value.entries())),t}toJSON(){return this.orgValue?this.orgValue:Object.fromEntries(this.value.entries())}__bool__(){return new ft(this.value.size>0)}},pt=class extends wt{constructor(){super(...arguments),this.type="KeywordArgumentsValue"}},dt=class extends ut{constructor(){super(...arguments),this.type="ArrayValue",this.builtins=new Map([["length",new ht(this.value.length)]])}__bool__(){return new ft(this.value.length>0)}},yt=class extends dt{constructor(){super(...arguments),this.type="TupleValue"}},mt=class extends ut{constructor(){super(...arguments),this.type="FunctionValue"}},bt=class extends ut{constructor(){super(...arguments),this.type="NullValue"}},gt=class extends ut{constructor(){super(...arguments),this.type="UndefinedValue"}},xt=class{constructor(t){this.parent=t,this.variables=new Map([["namespace",new mt((t=>{if(0===t.length)return new wt(new Map);if(1!==t.length||!(t[0]instanceof wt))throw new Error("`namespace` expects either zero arguments or a single object argument");return t[0]}))]]),this.tests=new Map([["boolean",t=>"BooleanValue"===t.type],["callable",t=>t instanceof mt],["odd",t=>{if("NumericValue"!==t.type)throw new Error(`Cannot apply test "odd" to type: ${t.type}`);return t.value%2!=0}],["even",t=>{if("NumericValue"!==t.type)throw new Error(`Cannot apply test "even" to type: ${t.type}`);return t.value%2==0}],["false",t=>"BooleanValue"===t.type&&!t.value],["true",t=>"BooleanValue"===t.type&&t.value],["string",t=>"StringValue"===t.type],["number",t=>"NumericValue"===t.type],["integer",t=>"NumericValue"===t.type&&Number.isInteger(t.value)],["iterable",t=>t instanceof dt||t instanceof lt],["lower",t=>{const e=t.value;return"StringValue"===t.type&&e===e.toLowerCase()}],["upper",t=>{const e=t.value;return"StringValue"===t.type&&e===e.toUpperCase()}],["none",t=>"NullValue"===t.type],["defined",t=>"UndefinedValue"!==t.type],["undefined",t=>"UndefinedValue"===t.type],["equalto",(t,e)=>t.value===e.value],["eq",(t,e)=>t.value===e.value]])}set(t,e){return this.declareVariable(t,vt(e))}declareVariable(t,e){if(this.variables.has(t))throw new SyntaxError(`Variable already declared: ${t}`);return this.variables.set(t,e),e}setVariable(t,e){return this.variables.set(t,e),e}resolve(t){if(this.variables.has(t))return this;if(this.parent)return this.parent.resolve(t);throw new Error(`Unknown variable: ${t}`)}lookupVariable(t){try{return this.resolve(t).variables.get(t)??new gt}catch{return new gt}}},Et=class{constructor(t){this.global=t??new xt}run(t){return this.evaluate(t,this.global)}evaluateBinaryExpression(t,e){const r=this.evaluate(t.left,e);switch(t.operator.value){case"and":return r.__bool__().value?this.evaluate(t.right,e):r;case"or":return r.__bool__().value?r:this.evaluate(t.right,e)}const n=this.evaluate(t.right,e);switch(t.operator.value){case"==":return new ft(r.value==n.value);case"!=":return new ft(r.value!=n.value)}if(r instanceof gt||n instanceof gt)throw new Error("Cannot perform operation on undefined values");if(r instanceof bt||n instanceof bt)throw new Error("Cannot perform operation on null values");if(r instanceof ht&&n instanceof ht)switch(t.operator.value){case"+":return new ht(r.value+n.value);case"-":return new ht(r.value-n.value);case"*":return new ht(r.value*n.value);case"/":return new ht(r.value/n.value);case"%":return new ht(r.value%n.value);case"<":return new ft(r.value<n.value);case">":return new ft(r.value>n.value);case">=":return new ft(r.value>=n.value);case"<=":return new ft(r.value<=n.value)}else if(r instanceof dt&&n instanceof dt){if("+"===t.operator.value)return new dt(r.value.concat(n.value))}else if(n instanceof dt){const e=void 0!==n.value.find((t=>t.value===r.value));switch(t.operator.value){case"in":return new ft(e);case"not in":return new ft(!e)}}if((r instanceof lt||n instanceof lt)&&"+"===t.operator.value)return new lt(r.toString()+n.toString());if(r instanceof lt&&n instanceof lt)switch(t.operator.value){case"in":return new ft(n.value.includes(r.value));case"not in":return new ft(!n.value.includes(r.value))}if(r instanceof lt&&n instanceof wt)switch(t.operator.value){case"in":return new ft(n.value.has(r.value));case"not in":return new ft(!n.value.has(r.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${r.type} and ${n.type}`)}evaluateArguments(t,e){const r=[],n=new Map;for(const s of t)if("KeywordArgumentExpression"===s.type){const t=s;n.set(t.key.value,this.evaluate(t.value,e))}else{if(n.size>0)throw new Error("Positional arguments must come before keyword arguments");r.push(this.evaluate(s,e))}return[r,n]}evaluateFilterExpression(t,e){const r=this.evaluate(t.operand,e);if("Identifier"===t.filter.type){const n=t.filter,s=e.lookupVariable(n.value);if(s instanceof mt)return s.value([r],e);if(r instanceof dt)switch(n.value){case"list":return r;case"first":return r.value[0];case"last":return r.value[r.value.length-1];case"length":return new ht(r.value.length);case"reverse":return new dt(r.value.reverse());case"sort":return new dt(r.value.sort(((t,e)=>{if(t.type!==e.type)throw new Error(`Cannot compare different types: ${t.type} and ${e.type}`);switch(t.type){case"NumericValue":return t.value-e.value;case"StringValue":return t.value.localeCompare(e.value);default:throw new Error(`Cannot compare type: ${t.type}`)}})));default:throw new Error(`Unknown ArrayValue filter: ${n.value}`)}else if(r instanceof lt)switch(n.value){case"length":return new ht(r.value.length);case"upper":return new lt(r.value.toUpperCase());case"lower":return new lt(r.value.toLowerCase());case"title":return new lt(ct(r.value));case"capitalize":return new lt(r.value.charAt(0).toUpperCase()+r.value.slice(1));case"trim":return new lt(r.value.trim());case"trimStart":return new lt(r.value.trimStart());case"trimEnd":return new lt(r.value.trimEnd());case"indent":return new lt(r.value.split("\n").map(((t,e)=>0===e||0===t.length?t:" "+t)).join("\n"));case"string":return r;default:throw new Error(`Unknown StringValue filter: ${n.value}`)}else{if(r instanceof ht){if("abs"===n.value)return new ht(Math.abs(r.value));throw new Error(`Unknown NumericValue filter: ${n.value}`)}if(r instanceof wt)switch(n.value){case"items":return new dt(Array.from(r.value.entries()).map((([t,e])=>new dt([new lt(t),e]))));case"length":return new ht(r.value.size);case"string":return new lt(r.toString());default:throw new Error(`Unknown ObjectValue filter: ${n.value}`)}}throw new Error(`Cannot apply filter "${n.value}" to type: ${r.type}`)}if("CallExpression"===t.filter.type){const n=t.filter;if("Identifier"!==n.callee.type)throw new Error(`Unknown filter: ${n.callee.type}`);const s=n.callee.value,i=e.lookupVariable(s);if(i instanceof mt){const[t,s]=this.evaluateArguments(n.args,e);return s.size>0&&t.push(new pt(s)),i.value([r,...t],e)}if(r instanceof dt){switch(s){case"selectattr":{if(r.value.some((t=>!(t instanceof wt))))throw new Error("`selectattr` can only be applied to array of objects");if(n.args.some((t=>"StringLiteral"!==t.type)))throw new Error("arguments of `selectattr` must be strings");const[t,s,i]=n.args.map((t=>this.evaluate(t,e)));let o;if(s){const t=e.tests.get(s.value);if(!t)throw new Error(`Unknown test: ${s.value}`);o=t}else o=(...t)=>t[0].__bool__().value;const a=r.value.filter((e=>{const r=e.value.get(t.value);return!!r&&o(r,i)}));return new dt(a)}case"map":{const[,t]=this.evaluateArguments(n.args,e);if(t.has("attribute")){const e=t.get("attribute");if(!(e instanceof lt))throw new Error("attribute must be a string");const n=t.get("default"),s=r.value.map((t=>{if(!(t instanceof wt))throw new Error("items in map must be an object");return t.value.get(e.value)??n??new gt}));return new dt(s)}throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${s}`)}if(r instanceof lt){if("indent"===s){const[t,s]=this.evaluateArguments(n.args,e),i=t.at(0)??s.get("width")??new ht(4);if(!(i instanceof ht))throw new Error("width must be a number");const o=t.at(1)??s.get("first")??new ft(!1),a=t.at(2)??s.get("blank")??new ft(!1),c=r.value.split("\n"),u=" ".repeat(i.value),h=c.map(((t,e)=>!o.value&&0===e||!a.value&&0===t.length?t:u+t));return new lt(h.join("\n"))}throw new Error(`Unknown StringValue filter: ${s}`)}throw new Error(`Cannot apply filter "${s}" to type: ${r.type}`)}throw new Error(`Unknown filter: ${t.filter.type}`)}evaluateTestExpression(t,e){const r=this.evaluate(t.operand,e),n=e.tests.get(t.test.value);if(!n)throw new Error(`Unknown test: ${t.test.value}`);const s=n(r);return new ft(t.negate?!s:s)}evaluateUnaryExpression(t,e){const r=this.evaluate(t.argument,e);if("not"===t.operator.value)return new ft(!r.value);throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let r="";for(const n of t){const t=this.evaluate(n,e);"NullValue"!==t.type&&"UndefinedValue"!==t.type&&(r+=t)}return new lt(r)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){const[r,n]=this.evaluateArguments(t.args,e);n.size>0&&r.push(new pt(n));const s=this.evaluate(t.callee,e);if("FunctionValue"!==s.type)throw new Error(`Cannot call something that is not a function: got ${s.type}`);return s.value(r,e)}evaluateSliceExpression(t,e,r){if(!(t instanceof dt||t instanceof lt))throw new Error("Slice object must be an array or string");const n=this.evaluate(e.start,r),s=this.evaluate(e.stop,r),i=this.evaluate(e.step,r);if(!(n instanceof ht||n instanceof gt))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof ht||s instanceof gt))throw new Error("Slice stop must be numeric or undefined");if(!(i instanceof ht||i instanceof gt))throw new Error("Slice step must be numeric or undefined");return t instanceof dt?new dt(at(t.value,n.value,s.value,i.value)):new lt(at(Array.from(t.value),n.value,s.value,i.value).join(""))}evaluateMemberExpression(t,e){const r=this.evaluate(t.object,e);let n,s;if(t.computed){if("SliceExpression"===t.property.type)return this.evaluateSliceExpression(r,t.property,e);n=this.evaluate(t.property,e)}else n=new lt(t.property.value);if(r instanceof wt){if(!(n instanceof lt))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.value.get(n.value)??r.builtins.get(n.value)}else if(r instanceof dt||r instanceof lt)if(n instanceof ht)s=r.value.at(n.value),r instanceof lt&&(s=new lt(r.value.at(n.value)));else{if(!(n instanceof lt))throw new Error(`Cannot access property with non-string/non-number: got ${n.type}`);s=r.builtins.get(n.value)}else{if(!(n instanceof lt))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.builtins.get(n.value)}return s instanceof ut?s:new gt}evaluateSet(t,e){const r=this.evaluate(t.value,e);if("Identifier"===t.assignee.type){const n=t.assignee.value;e.setVariable(n,r)}else{if("MemberExpression"!==t.assignee.type)throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(t.assignee)}`);{const n=t.assignee,s=this.evaluate(n.object,e);if(!(s instanceof wt))throw new Error("Cannot assign to member of non-object");if("Identifier"!==n.property.type)throw new Error("Cannot assign to member with non-identifier property");s.value.set(n.property.value,r)}}return new bt}evaluateIf(t,e){const r=this.evaluate(t.test,e);return this.evaluateBlock(r.__bool__().value?t.body:t.alternate,e)}evaluateFor(t,e){const r=new xt(e);let n,s;if("SelectExpression"===t.iterable.type){const e=t.iterable;s=this.evaluate(e.iterable,r),n=e.test}else s=this.evaluate(t.iterable,r);if(!(s instanceof dt))throw new Error(`Expected iterable type in for loop: got ${s.type}`);const i=[],o=[];for(let e=0;e<s.value.length;++e){const a=new xt(r),c=s.value[e];let u;if("Identifier"===t.loopvar.type)u=e=>e.setVariable(t.loopvar.value,c);else{if("TupleLiteral"!==t.loopvar.type)throw new Error(`Invalid loop variable(s): ${t.loopvar.type}`);{const e=t.loopvar;if("ArrayValue"!==c.type)throw new Error(`Cannot unpack non-iterable type: ${c.type}`);const r=c;if(e.value.length!==r.value.length)throw new Error(`Too ${e.value.length>r.value.length?"few":"many"} items to unpack`);u=t=>{for(let n=0;n<e.value.length;++n){if("Identifier"!==e.value[n].type)throw new Error(`Cannot unpack non-identifier type: ${e.value[n].type}`);t.setVariable(e.value[n].value,r.value[n])}}}}if(n){u(a);if(!this.evaluate(n,a).__bool__().value)continue}i.push(c),o.push(u)}let a="",c=!0;for(let e=0;e<i.length;++e){const n=new Map([["index",new ht(e+1)],["index0",new ht(e)],["revindex",new ht(i.length-e)],["revindex0",new ht(i.length-e-1)],["first",new ft(0===e)],["last",new ft(e===i.length-1)],["length",new ht(i.length)],["previtem",e>0?i[e-1]:new gt],["nextitem",e<i.length-1?i[e+1]:new gt]]);r.setVariable("loop",new wt(n)),o[e](r);a+=this.evaluateBlock(t.body,r).value,c=!1}if(c){a+=this.evaluateBlock(t.defaultBlock,r).value}return new lt(a)}evaluateMacro(t,e){return e.setVariable(t.name.value,new mt(((e,r)=>{const n=new xt(r);let s;e=e.slice(),"KeywordArgumentsValue"===e.at(-1)?.type&&(s=e.pop());for(let r=0;r<t.args.length;++r){const i=t.args[r],o=e[r];if("Identifier"===i.type){const t=i;if(!o)throw new Error(`Missing positional argument: ${t.value}`);n.setVariable(t.value,o)}else{if("KeywordArgumentExpression"!==i.type)throw new Error(`Unknown argument type: ${i.type}`);{const t=i,e=o??s?.value.get(t.key.value)??this.evaluate(t.value,n);n.setVariable(t.key.value,e)}}}return this.evaluateBlock(t.body,n)}))),new bt}evaluate(t,e){if(void 0===t)return new gt;switch(t.type){case"Program":return this.evalProgram(t,e);case"Set":return this.evaluateSet(t,e);case"If":return this.evaluateIf(t,e);case"For":return this.evaluateFor(t,e);case"Macro":return this.evaluateMacro(t,e);case"NumericLiteral":return new ht(Number(t.value));case"StringLiteral":return new lt(t.value);case"BooleanLiteral":return new ft(t.value);case"ArrayLiteral":return new dt(t.value.map((t=>this.evaluate(t,e))));case"TupleLiteral":return new yt(t.value.map((t=>this.evaluate(t,e))));case"ObjectLiteral":{const r=new Map;for(const[n,s]of t.value){const t=this.evaluate(n,e);if(!(t instanceof lt))throw new Error(`Object keys must be strings: got ${t.type}`);r.set(t.value,this.evaluate(s,e))}return new wt(r,t.value)}case"Identifier":return this.evaluateIdentifier(t,e);case"CallExpression":return this.evaluateCallExpression(t,e);case"MemberExpression":return this.evaluateMemberExpression(t,e);case"UnaryExpression":return this.evaluateUnaryExpression(t,e);case"BinaryExpression":return this.evaluateBinaryExpression(t,e);case"FilterExpression":return this.evaluateFilterExpression(t,e);case"TestExpression":return this.evaluateTestExpression(t,e);default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function vt(t){switch(typeof t){case"number":return new ht(t);case"string":return new lt(t);case"boolean":return new ft(t);case"undefined":return new gt;case"object":return null===t?new bt:Array.isArray(t)?new dt(t.map(vt)):new wt(new Map(Object.entries(t).map((([t,e])=>[t,vt(e)]))),t);case"function":return new mt(((e,r)=>{const n=e.map((t=>kt(t)));return vt(t(...n)??null)}));default:throw new Error(`Cannot convert to runtime value: ${t}`)}}function kt(t){let e=t;if(Array.isArray(t))e=t.map((t=>kt(t)));else if(t instanceof Map)e={},t.forEach(((t,r)=>{e[r]=kt(t)}));else switch(t.type){case"NullValue":e=null;break;case"UndefinedValue":e=void 0;break;case"ArrayValue":e=t.value.map((t=>kt(t)));break;case"KeywordArgumentsValue":case"ObjectValue":e=t.orgValue?t.orgValue:kt(t.value),"KeywordArgumentsValue"===t.type&&Object.setPrototypeOf(e,{jinja_kargs:!0});break;default:t.type&&(e=t.value)}return e}function St(t,e=0){return Math.floor(Math.random()*(t-e+1))+e}var $t={randomInt:St,select:function(t,e){if(Array.isArray(t)||"string"==typeof t)return void 0===e?e=St(t.length-1):"string"==typeof e&&(e=parseInt(e)),e<0&&(e=t.length+e),t[e];if(t&&"object"==typeof t){if(void 0===e){const r=Object.keys(t);e=r[St(r.length-1)]}return t[e]}},tojson:function(t,e,r){return e&&"object"==typeof e&&(e.depth&&(r=e.depth),e=e.indent),Ot(t,e,r)}};function Ot(t,e,r){let n="";const s=r??0;if(null===t)n="null";else{const r=typeof t;switch(r){case"undefined":n="null";case"number":case"string":case"boolean":return JSON.stringify(t);case"object":{const r=e?" ".repeat(e):"",n="\n"+r.repeat(s),i=n+r;if(Array.isArray(t)){const r=t.map((t=>Ot(t,e,s+1)));return e?`[${i}${r.join(`,${i}`)}${n}]`:`[${r.join(", ")}]`}{const r=Array.from(Object.entries(t)).map((([t,r])=>{const n=`"${t}": ${Ot(r,e,s+1)}`;return e?`${i}${n}`:n}));return e?`{${r.join(",")}${n}}`:`{${r.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${r}`)}}return n}var jt=class extends xt{constructor(t){super(t),this.parent=t}assign(t){for(const[e,r]of Object.entries(t))this.set(e,r)}clear(){this.variables.clear()}},Ct=class t{static{this.global=new jt}constructor(t,e={}){const r=function(t,e={}){const r=[],n=function(t,e={}){return t.endsWith("\n")&&(t=t.slice(0,-1)),t=t.replace(/{#.*?#}/gs,"{##}"),e.lstrip_blocks&&(t=t.replace(/^[ \t]*({[#%])/gm,"$1")),e.trim_blocks&&(t=t.replace(/([#%]})\n/g,"$1")),t.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}(t,e);let s=0;const i=t=>{let e="";for(;t(n[s]);)if("\\"!==n[s]){if(e+=n[s++],s>=n.length)throw new SyntaxError("Unexpected end of input")}else{if(++s,s>=n.length)throw new SyntaxError("Unexpected end of input");const t=n[s++],r=N.get(t);if(void 0===r)throw new SyntaxError(`Unexpected escaped character: ${t}`);e+=r}return e};t:for(;s<n.length;){const t=r.at(-1)?.type;if(void 0===t||t===C.CloseStatement||t===C.CloseExpression){let t="";for(;s<n.length&&("{"!==n[s]||"%"!==n[s+1]&&"{"!==n[s+1]);)t+=n[s++];if(t.length>0){r.push(new T(t,C.Text));continue}}i((t=>/\s/.test(t)));const e=n[s];if("-"===e||"+"===e){const t=r.at(-1)?.type;if(t===C.Text||void 0===t)throw new SyntaxError(`Unexpected character: ${e}`);switch(t){case C.Identifier:case C.NumericLiteral:case C.BooleanLiteral:case C.StringLiteral:case C.CloseParen:case C.CloseSquareBracket:break;default:{++s;const t=i(q);r.push(new T(`${e}${t}`,t.length>0?C.NumericLiteral:C.UnaryOperator));continue}}}for(const[t,e]of I)if(n.slice(s,s+t.length)===t){r.push(new T(t,e)),s+=t.length;continue t}if("'"!==e&&'"'!==e)if(q(e)){const t=i(q);r.push(new T(t,C.NumericLiteral))}else{if(!M(e))throw new SyntaxError(`Unexpected character: ${e}`);{const t=i(M),e=Object.hasOwn(A,t)?A[t]:C.Identifier;e===C.In&&r.at(-1)?.type===C.Not?(r.pop(),r.push(new T("not in",C.NotIn))):r.push(new T(t,e))}}else{++s;const t=i((t=>t!==e));r.push(new T(t,C.StringLiteral)),++s}}return r}(t,e={lstrip_blocks:!0,trim_blocks:!0,...e});this.parsed=it(r)}render(e){const r=new xt(t.global);r.set("false",!1),r.set("true",!0),r.set("raise_exception",(t=>{throw new Error(t)})),r.set("range",ot);for(const[t,n]of Object.entries(e))r.set(t,n);return new Et(r).run(this.parsed).toString()}};function At(t,e){let r;switch(t.type){case"Identifier":r=t.value;break;case"MemberExpression":r=At(t.object,e);break;case"FilterExpression":r=At(t.operand,e);break;case"Set":{e||(e=[]);const n=At(t.assignee);n&&e.push(n),r=At(t.value,e);break}}return r&&e?.includes(r)&&(r=void 0),r}function Tt(t){let e;if("Program"===t.type)e=t.body.some((t=>Tt(t)));else e=t.isStatement;return e}function Mt(t,e){let r=[];if(Array.isArray(t))r=t.map((t=>Mt(t,e))).filter(Boolean).flat();else switch(t.type){case"Program":r=t.body.map((t=>Mt(t,e))).filter(Boolean).flat();break;case"If":r=[At(t.test,e),...Mt(t.body,e),...Mt(t.alternate,e)].filter(Boolean);break;case"BinaryExpression":r=[At(t.left,e),At(t.right,e)].filter(Boolean);break;case"For":{const n=At(t.loopvar);n&&(e||(e=[]),e.push(n)),r=[At(t.iterable,e),...Mt(t.body,e)].filter(Boolean);break}case"CallExpression":r=[At(t.callee,e),...Mt(t.args,e)].filter(Boolean);break;default:r=[At(t,e)].filter(Boolean)}return r}Ct.global.assign($t);function qt(t){const e=t.split(""),r=[],n=(t,r)=>{for(let n=r;n<e.length;n+=1)if(t.includes(e[n]))return n;return-1};let s=0;for(;s<e.length;)if("{"===e[s]&&s+1<e.length&&"{"===e[s+1])r.push({type:"literal",text:"{"}),s+=2;else if("}"===e[s]&&s+1<e.length&&"}"===e[s+1])r.push({type:"literal",text:"}"}),s+=2;else if("{"===e[s]){const t=n("}",s);if(t<0)throw new Error("Unclosed '{' in template.");r.push({type:"variable",name:e.slice(s+1,t).join("")}),s=t+1}else{if("}"===e[s])throw new Error("Single '}' in template.");{const t=n("{}",s),i=(t<0?e.slice(s):e.slice(s,t)).join("");r.push({type:"literal",text:i}),s=t<0?e.length:t}}return r}function It(t){const e=new Set;return t.forEach((t=>{"variable"===t.type&&e.add(t.name)})),[...e]}j.register(class extends j{static isTemplate(t){let e,r,n=!1;if("object"==typeof t?(r=t.template,e=t.compiledTemplate):r=t,!e&&r)try{e=new Ct(r)}catch(t){}return e&&(n=Tt(e.parsed)),n}getVariables(t=this.compiledTemplate){return Mt(t.parsed,[]).filter(((t,e,r)=>r.indexOf(t)===e))}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new y("Prompt template must be a string","PromptTemplate",400);this.compiledTemplate=new Ct(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return this.compiledTemplate.render(t)}},{name:"hf",aliases:["huggingface","internal","default"]});function Nt(t,e){return"string"==typeof e&&(e=e.split(".").filter((t=>t.length))),e.reduce(((t,e)=>t?.[e]),t)}function Vt(t,e,r){let n=function(t,e,r){return t.replace(/{{\s*re_replace\s+\.(.+?)\s+(["'])([^\2]*?)\2\s+(["'])([^\4]*?)\4\s*}}/g,((t,n,s,i,o,a)=>{if(r)return e[n]=null,t;const c=new RegExp(i,"g");return Nt(e,n).replace(c,a)}))}(t,e,r);return n=function(t,e,r){return t.replace(/{{\s*join\s+\.(.+?)\s+(["'])([^\2]*?)\2\s*}}/g,((t,n,s,i)=>r?(e[n]=null,t):Nt(e,n).join(i)))}(n,e,r),n=function(t,e,r){return t.replace(/{{\s*if\s*(\S+?)\s*}}([^{]*)({{\s*else\s*}}([^{]*))?{{\s*end\s*}}/g,((t,n,s,i,o)=>{if(r)return n.startsWith(".")&&(n=n.substring(1)),e[n]=null,t;let a;if(!n.startsWith("."))throw new Error("Functionality not implemented");{const t=Nt(e,n.substring(1));if(null==t)a=o??"";else if("string"==typeof t)a=t.length>0?s:o??"";else if(Array.isArray(t))a=t.length>0?s:o??"";else{if("boolean"!=typeof t)throw new Error(`Unexpected type for variable ${n}: ${typeof t}`);a=t?s:o??""}}return a}))}(n,e,r),n=function(t,e,r){return t.replace(/{{\s*range\s*[.$]([^{}\s]+?)\s*}}([^{]*?){{\.}}([^{]*?){{\s*end\s*}}/g,((t,n,s,i)=>{if(r)return e[n]=null,t;const o=Nt(e,n);if(Array.isArray(o)){let t="";for(const e of o)t+=`${s}${e}${i}`;return t}return t}))}(n,e,r),n=function(t,e,r){return t.replace(/{{\s*\.([^{}\s]+?)\s*}}/g,((t,n)=>r?(e[n]=null,t):Nt(e,n)||""))}(n,e,r),n=function(t,e,r){return t.replace(/{{\s*index\s*\.(.+?)\s+(.+?)\s*}}/g,((t,n,s)=>{if(r)return e[n]=null,t;const i=Nt(e,n);let o;return o=isNaN(s)?i[s.substring(1,s.length-1)]:i[parseInt(s,10)],o||""}))}(n,e,r),n}j.register(class extends j{static isTemplate(t){let e,r,n=!1;if("object"==typeof t?(r=t.template,e=t.compiledTemplate):r=t,!e&&r)try{e=qt(r)}catch(t){}if(e){n=It(e).length>0}return n}getVariables(t=this.compiledTemplate){return It(t)}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new y("Prompt template must be a string","PromptTemplate",400);this.compiledTemplate=qt(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return e=this.compiledTemplate,r=t,e.reduce(((t,e)=>{let n;return n="variable"===e.type?e.name in r?t+r[e.name]:t:t+e.text,n}),"");var e,r}},{name:"fstring",aliases:["python","f-string","langchain"]});function Pt(t){return Object.keys(t).sort().map((e=>t[e]))}j.register(class extends j{static isTemplate(t){const e="string"==typeof t?t:t.template;return e?.includes("{{")&&e.includes("}}")}getVariables(t){const e={};return Vt(t,e,!0),[...Object.keys(e)]}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new y("Prompt template must be a string","PromptTemplate",400);this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables(e)}_format(t){return Vt(this.template,t)}},{name:"golang",aliases:["localai","ollama"]});j.register(class extends j{static from(t){return new this(t)}constructor(t){super(t)}_initialize(t){t&&(t.suffix&&(this.suffix=t.suffix),t.exampleSeparator&&(this.exampleSeparator=t.exampleSeparator),t.prefix&&(this.prefix=t.prefix),t.examplePrompt&&(this.examplePrompt=t.examplePrompt instanceof j?t.examplePrompt:j.from(t.examplePrompt)),t.examples&&(this.examples=t.examples)),this.prefix||(this.prefix=""),this.exampleSeparator||(this.exampleSeparator="\n\n"),this.suffix||(this.suffix="")}async _format(t){const e=[];for await(const t of this.examples)if(this.examplePrompt){const r=await this.examplePrompt.format(t);e.push(r)}else if("string"==typeof t)e.push(t);else if(t){const r=Pt(t);r.length>0&&e.push(...r)}const r=[this.prefix,...e,this.suffix].join(this.exampleSeparator),n=this.templateFormat;return await j.format({template:r,data:t,templateFormat:n})}toJSON(t=this){const e=super.toJSON(t);return t.suffix&&(e.suffix=t.suffix),t.exampleSeparator&&(e.exampleSeparator=t.exampleSeparator),t.prefix&&(e.prefix=t.prefix),t.examplePrompt&&(e.examplePrompt=t.examplePrompt),t.examples&&(e.examples=t.examples),e}},{name:"fewshot",aliases:["few_shot"]});new RegExp("([A-Z][a-z]{1,2}\\.)@(\\w)","g"),new RegExp("(\\.[a-zA-Z]\\.)@(\\w)","g");var Ut=require("custom-ability"),Bt="event",Ft="event-bus";(0,Ut.createAbilityInjector)((function(t){return class{static get emitter(){if(!this._emitter){const t=this.get(Ft)?.emitter;t&&(this._emitter=t,this.prototype._events=t._events)}return this._emitter}get emitter(){return this.constructor._emitter}on(e,r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return n.on(e,r)}once(e,r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return n.once(e,r)}off(e,r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return n.off(e,r)}emit(e,...r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return"error"===e?this.emitError.apply(this,r):n.emit.call(this,e,this.name,...r)}emitError(e,...r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return n.emit.call(this,"error",e,this.name,...r)}async emitAsync(e,...r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return n.emitAsync.call(this,e,this.name,...r)}}}),!0);function _t(t,e){return!t||t.some((t=>t instanceof RegExp?t.test(e):t===e))}var Lt=class{get active(){return this._active}set active(t){t!==this._active&&(t?(this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0),this.options.pingInterval>0&&(this.pingTimer=setInterval((()=>this.publish()),this.options.pingInterval))):(this.clients.size&&this.clearClients(),this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0)),this._active=t)}constructor(t){this.options=Object.assign({},{pingInterval:3e3,maxStreamDuration:3e4,clientRetryInterval:1e3,startId:1,historySize:100,rewind:0,cors:!1},t),this.nextID=this.options.startId,this.clients=new Set,this.messages=[],this.active=!0}publish(t,e){let r,n;this.active||v("Channel closed","SSEChannel",498);let s=e;if(t||e)n=this.nextID++,"object"==typeof t&&(t.event?(s=t.event,void 0!==t.data&&(t=JSON.stringify(t.data))):t=JSON.stringify(t)),t=t?t.split(/[\r\n]+/).map((t=>"data: "+t)).join("\n"):"",r="id: "+n+"\n"+(e?"event: "+e+"\n":"")+(t||"data: ")+"\n\n",this.messages.push({id:n,_eventName:s,output:r});else{if(!this.clients.size)return;r="data: \n\n"}for([...this.clients].filter((t=>!s||_t(t.events,s))).forEach(((t,e)=>{t.res.write(r)}));this.messages.length>this.options.historySize;)this.messages.shift();return n}subscribe(t,e,r){this.active||v("Channel closed","SSEChannel",498);const n={req:t,res:e,events:r},s=this.options.maxStreamDuration;let i="max-age=0, stale-while-revalidate=0, stale-if-error=0, no-transform";s>0&&(i+=", s-maxage="+(Math.floor(s/1e3)-1));const o={"Content-Type":"text/event-stream","Cache-Control":i,Connection:"keep-alive"};this.options.cors&&(o["access-control-allow-origin"]="*"),n.req.socket.setNoDelay(!0),n.res.writeHead(200,o);let a="retry: "+this.options.clientRetryInterval+"\n\n";const c=Number.parseInt(t.headers["last-event-id"],10),u=Number.isNaN(c)?this.options.rewind:this.nextID-1-c;return u&&this.messages.filter((t=>_t(n.events,t.eventName))).slice(0-u).forEach((t=>{a+=t.output})),n.res.write(a),this.clients.add(n),s>0&&setTimeout((()=>{n.res.writableEnded||this.unsubscribe(n)}),s),n.res.on("close",(()=>this.unsubscribe(n))),n}unsubscribe(t){t.res.end(),this.clients.delete(t)}clearClients(){this.clients.forEach((t=>t.res.end())),this.clients.clear()}listClients(){const t={};return this.clients.forEach((e=>{const r=e.req.socket.remoteAddress??"";r in t||(t[r]=0),t[r]++})),t}getSubscriberCount(){return this.clients.size}};require("eventsource-parser");require("uuid"),c(require("base32768")),require("uuid");var Rt=c(require("xxhashjs")),{h32:Jt,h64:zt}=(c(require("base32768")),require("json-canonicalize"),Rt.default),Wt=(require("util-ex"),require("lodash-es"),require("util-ex"),require("load-config-file")),Kt=require("yaml"),Dt=require("yaml-types"),Zt=(require("mime-type/with-db"),require("yaml"),[Dt.regexp]);Wt.Config.register([".yml",".yaml"],(function(t){return(0,Kt.parse)(t,{customTags:Zt})})),Wt.Config.register([".json"],(function(t){return JSON.parse(t)}));var Ht=class t{constructor(t=0){this.bitField=t}static has(t,e){return!!(t&1<<e)}static add(t,e){return t|1<<e}static delete(t,e){return t&~(1<<e)}add(t){return this.bitField|=1<<t,this}delete(t){return this.bitField&=~(1<<t),this}has(e){return t.has(this.bitField,e)}clear(){return this.bitField=0,this}valueOf(){return this.bitField}toString(){return this.bitField.toString()}toJSON(){return this.bitField}},Gt=require("events-ex");function Qt(t){return e=Math.min(Math.max(16,t),1073741824),e>>>=0,e-=1,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,1+(e|=e>>16);var e}var Xt=class{constructor(t){this._capacity=Qt(t),this._length=0,this._front=0,this.arr=[]}push(t){const e=this._length;this.checkCapacity(e+1);const r=this._front+e&this._capacity-1;return this.arr[r]=t,this._length=e+1,r}pop(){const t=this._length;if(0===t)return;const e=this._front+t-1&this._capacity-1,r=this.arr[e];return this.arr[e]=void 0,this._length=t-1,r}shift(){const t=this._length;if(0===t)return;const e=this._front,r=this.arr[e];return this.arr[e]=void 0,this._front=e+1&this._capacity-1,this._length=t-1,r}get length(){return this._length}checkCapacity(t){this._capacity<t&&this.resizeTo(Qt(1.5*this._capacity+16))}resizeTo(t){const e=this._capacity;this._capacity=t;const r=this._front,n=this._length;if(r+n>e){const t=r+n&e-1;!function(t,e,r,n,s){for(let i=0;i<s;++i)r[i+n]=t[i+e],t[i+e]=void 0}(this.arr,0,this.arr,e,t)}}},Yt=class extends Gt.EventEmitter{};function te(t){return"function"==typeof t}function ee(){return"1"}var re=class{constructor(t,{initFn:e=ee,pauseFn:r,resumeFn:n,capacity:s=32}={}){if(te(r)!==te(n))throw new Error("pauseFn and resumeFn must be both set for pausing");this.maxConcurrency=t,this.free=new Xt(t),this.waiting=new Xt(s),this.releaseEmitter=new Yt,this.useDefaultTokens=e===ee,this.pauseFn=r,this.resumeFn=n,this.paused=!1,this.releaseEmitter.on("release",(t=>{const e=this.waiting.shift();e?e.resolve(t):(this.resumeFn&&this.paused&&(this.paused=!1,this.resumeFn()),this.free.push(t))}));for(let r=0;r<t;r++)this.free.push(e())}tryAcquire(){return this.free.pop()}acquire(t){let e=this.tryAcquire();return void 0!==e?Promise.resolve(e):new Promise(((e,r)=>{this.pauseFn&&!this.paused&&(this.paused=!0,this.pauseFn());const n=this.waiting.push({resolve:e,reject:r});return t&&t.addEventListener("abort",(()=>{this.waiting[n]=void 0;const e=t.reason instanceof Error?t.reason:new Error(t.reason||"aborted");t.alreadyRejected=!0,r(e)})),n}))}release(t){this.releaseEmitter.emit("release",this.useDefaultTokens?"1":t)}drain(){const t=new Array(this.maxConcurrency);for(let e=0;e<this.maxConcurrency;e++)t[e]=this.acquire();return Promise.all(t)}pendingCount(){return this.waiting.length}},ne=require("custom-ability"),se=require("util-ex"),ie=class extends AbortController{constructor(t){super(),(0,se.defineProperty)(this,"parent",t)}abort(t,e){this.signal.aborted||("string"==typeof t&&(t=new x(t)),t&&e&&"object"==typeof t&&Object.assign(t.data,e),super.abort(t))}throwRejected(t){const e=this.signal;if(e.aborted){if(void 0===t&&(t=e.alreadyRejected),t)return!0;throw e.reason instanceof Error?e.reason:new x(e.reason||"aborted")}}},oe=class{get maxTaskConcurrency(){return this._maxTaskConcurrency}get semaphore(){const t=this._maxTaskConcurrency;let e=this.__task_semaphore;return t>0&&!e&&(e=this.__task_semaphore=new re(t-1)),e}isAborted(t){const e=this.hasAsyncFeature(ce);let r=this.__task_aborter;if(r&&e){if(null==t)throw new y("Missing taskId",this.name+".isAborted",400);r=r[t]}return!r||r.signal.aborted}getRunningTask(t){const e=this.hasAsyncFeature(ce);let r=this.__task_aborter;if(r&&e){if(null==t)throw new y("Missing taskId",this.name+".getRunningTask",400);r=r[t]}return r?.signal.aborted&&(e?this.__task_aborter[t]=void 0:this.__task_aborter=void 0,r=void 0),r}getRunningTaskCount(){let t;if(this.hasAsyncFeature(ce)){const e=this.__task_aborter;t=e&&Object.entries(e).filter((([t,r])=>{if(!r?.signal.aborted)return!0;e[t]=void 0})).length}else{const e=this.__task_aborter;t=e?.signal.aborted?0:1}return t}_generateAsyncTaskId(t,e){if(e||(e=this.__task_aborter),null==t&&(t=0,e))for(;e[t];)t++;return t}$generateAsyncTaskId(t,e){const r=this.super,n=this.self||this;return t=r?r.call(n,t):this._generateAsyncTaskId(t,e)}createAborter(t,e,r=!0){const n=this.hasAsyncFeature(ce);if(!n&&r&&this.getRunningTask())throw new y("The task is running",this.name,429);const s=t?.aborter||new ie(this);if(!(s instanceof ie)){if(!(s instanceof AbortController))throw new y("aborter should be an AbortController",this.name,400);Object.setPrototypeOf(s,new ie(this))}if(n){null==this.__task_aborter&&(this.__task_aborter={});const t=this.__task_aborter;null==e&&(e=this.generateAsyncTaskId(e,t)),s.id=e,t[e]=s}else this.__task_aborter=s;const i=t?.timeout;return i>0&&(s.timeoutId=setTimeout((()=>{s.timeoutId=void 0,this.abort("timeout",{timeout:i})}),i)),s.signal.addEventListener("abort",(()=>{const t=s.timeoutId;t&&(s.timeoutId=void 0,clearTimeout(t));const e=s.signal;try{this.emit&&this.emit("aborting",e.reason,e.reason?.data)}finally{s.streamController?.error(e.reason)}})),s}$cleanMultiTaskAborter(t,e){const r=this.super,n=this.self||this;r?r.call(n,t,e):n._cleanMultiTaskAborter(t,e)}cleanTaskAborter(t){if(this.hasAsyncFeature(ce)){const e=this.__task_aborter;this.cleanMultiTaskAborter(t.id,e)}else this.__task_aborter=void 0}_cleanMultiTaskAborter(t,e){"number"==typeof t?e[t]=void 0:delete e[t]}createTaskPromise(t,e,r){const n=this.createAborter(e,r?.taskId,r?.raiseError);void 0===e&&(e={}),"object"==typeof e&&(e.aborter=n);let s=t(e,n).then((t=>{if(t&&t instanceof ReadableStream){const e=()=>{this.cleanTaskAborter(n)},r=function(t){const e=t||{};return new TransformStream({async start(t){const r=t.error;if(t.error=n=>{r.call(t,n),e.onError&&e.onError(n)},e.onStart)try{await e.onStart(t)}catch(e){t.error(e)}},async transform(t,r){try{let n;e.onTransform&&(n=await e.onTransform(t,r)),n||(n=t),r.enqueue(n)}catch(t){r.error(t)}},async flush(t){if(e.onFinal)try{await e.onFinal(t)}catch(e){return t.error(e)}t.terminate()}})}({onStart:t=>{(0,se.defineProperty)(n,"streamController",t)},onFinal:e,onError:e,onTransform:(t,e)=>(t&&"object"==typeof t&&(t.taskId=n.id),t)});t=t.pipeThrough(r)}else this.cleanTaskAborter(n);return t})).catch((t=>{throw this.cleanTaskAborter(n),t})).finally((()=>{n.timeoutId&&(clearTimeout(n.timeoutId),n.timeoutId=void 0)}));return s.task=n,s}runAsyncCancelableTask(t={},e,r){let n=this.createTaskPromise(e,t,r);const s=this.semaphore;if(s){const t=n,e=t.task;n=s.acquire(e.signal).then((()=>t)).finally((()=>{s.release()})),n.task=e}return n}abort(t,e){let r=this.__task_aborter;if(r){const n=r;if(this.hasAsyncFeature(ce)){const t=e?.taskId;if(null==t)throw new y("Missing data.taskId",this.name+".abort",400);r=r[t],this.cleanMultiTaskAborter(t,n)}else this.__task_aborter=void 0;r&&!r.signal.aborted&&r.abort(t,e)}}};oe.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},oe.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};(0,ne.createAbilityInjector)(oe,"abort",{afterInjection:function(t,e){let r=t.prototype._asyncFeatures||0;r|=ue.Cancelable,e&&(e.asyncFeatures&&(r|=e.asyncFeatures),e.maxTaskConcurrency>0&&(t.prototype._maxTaskConcurrency=e.maxTaskConcurrency)),t.prototype._asyncFeatures=r}}),require("lodash-es"),require("util-ex"),c(require("memoizee")),require("json-canonicalize");var ae,ce=0,ue=((ae=ue||{})[ae.MultiTask=1<<ce]="MultiTask",ae[ae.Cancelable=2]="Cancelable",ae[ae.Priority=4]="Priority",ae),he=class t extends l.AdvancePropertyManager{static{this.items={}}static get(t){return this.items[t]}static list(){return this.items}static getByTag(t){let e;for(const r in this.list()){const n=this.get(r);let s=n.tags;if("string"==typeof s){if(s===t){e=n;break}}else if(Array.isArray(s)&&s.indexOf(t)>=0){e=n;break}}return e}static getAllByTag(t){let e=[];for(const r in this.list()){const n=this.get(r);let s=n.tags;"string"==typeof s?s===t&&e.push(n):Array.isArray(s)&&s.indexOf(t)>=0&&e.push(n)}return e}static hasAsyncFeature(t){const e=this.prototype;let r=e.asyncFeatures;return e._asyncFeatures&&(r|=e._asyncFeatures),Ht.has(r,t)}static run(t,e){const r=this.get(t);if(r)return r.run(e);throw new b(`${t} to run`,this.name)}static runSync(t,e){const r=this.get(t);if(r)return r.runSync(e);throw new b(`${t} to run`,this.name)}static getFunc(t){const e=this.get(t);return e?.getFunc()}static runWithPos(t,...e){const r=this.get(t);if(r)return r.runWithPos(...e);throw new b(`${t} to run`,this.name)}static runWithPosSync(t,...e){const r=this.get(t);if(r)return r.runWithPosSync(...e);throw new b(`${t} to run`,this.name)}static getFuncWithPos(t){const e=this.get(t);return e?.getFuncWithPos()}static register(e,r={}){switch(typeof e){case"string":r.name=e;break;case"function":r.func=e;break;case"object":r=e}e=r.name;let n=!!this.get(e);if(n)n=!1;else{if(!(r instanceof t))return n=new this(r),n.register();this.items[e]=r,n=r}return n}static unregister(t){const e=this.items[t];return e&&delete this.items[t],e}constructor(t,e={}){switch(super(),typeof t){case"string":e.name=t;break;case"function":e.func=t;break;case"object":e=t}this.name=t=e.name,e.scope&&(this.scope=e.scope),"function"==typeof e.setup&&e.setup.call(this,e),this.initialize(e)}register(){const e=this.constructor,r=this.depends;if(r){const e=Object.keys(r);for(const n of e){const e=r[n];e instanceof t&&e.register()}}return e.register(this)}unregister(){return this.constructor.unregister(this.name)}arr2ObjParams(t){if(this.params&&(t.length>1||Array.isArray(t[0])||t[0]&&"object"!=typeof t[0])){const e={},r=Object.keys(this.params);let n=Math.min(r.length,t.length);for(let s=0;s<n;s++)e[r[s]]=t[s];t=[e]}return t}obj2ArrParams(t){const e=[];if(t&&this.params&&Array.isArray(this.params)){const r=Object.keys(t);let n=Math.min(r.length,this.params.length);for(let s=0;s<n;s++)e.push(t[r[s]])}return e}runSync(t){const e=this.params&&Array.isArray(this.params);if(Array.isArray(t)){if(e)return this.func(...t);v("the function is not support array params, the params must be object!",this.name)}return e?(t=this.obj2ArrParams(t),console.warn('Warning:Use runWithPos() instead of run() for the "'+this.name+'" is function with position params'),this.func(...t)):this.func(t)}run(t){return this.runSync(t)}runAs(t,e){return this.runAsSync(t,e)}runAsSync(t,e){return this.constructor.runSync(t,e)}getFunc(t){return t?this.constructor.getFunc(t):this.runSync.bind(this)}runWithPosSync(...t){return this.params&&!Array.isArray(this.params)&&(t=this.arr2ObjParams(t)),this.func(...t)}runWithPosAsSync(t,...e){return this.constructor.runWithPosSync(t,...e)}runWithPos(...t){return this.runWithPosSync(...t)}runWithPosAs(t,...e){return this.runWithPosAsSync(t,...e)}getFuncWithPos(t){return t?this.constructor.getFuncWithPos(t):this.runWithPosSync.bind(this)}hasAsyncFeature(t){let e=this.asyncFeatures;return this._asyncFeatures&&(e|=this._asyncFeatures),Ht.has(e,t)}isStream(t){return this.stream}},le={name:{type:"string"},description:{type:"string"},func:{type:"function",assign(t,e,r,n,s){let i=t;const o=typeof t;return s.isExported?i="function"===o?t.toString():t:t&&("string"!==o&&(t=t.toString()),i=(0,f._createFunction)(t,e.scope)),i}},params:{type:"object"},result:{type:"any"},setup:{type:"function"},depends:{type:"object",exported:!1},tags:{type:["array","string"]},isApi:{type:"boolean"},stream:{type:"boolean"},asyncFeatures:{type:"number"}};he.defineProperties(he,le);var fe=class extends he{constructor(){super(...arguments),this._emitter=new h.EventEmitter,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},we=new fe(Ft),pe=require("secondary-cache");function de({key:t,value:e,options:r}={}){return void 0!==t?null===e?this.cache.del(t):void 0!==e?this.cache.set(t,e,r):this.cache.get(t):(r&&this.cache.setDefaultOptions(r),this.cache)}function ye(t,e){let r=he.get(t);return r||(r=new he(t,{func:de,description:"get/set LRU cache or return the LRUCache object",params:{key:{name:"key",type:"string",description:"the key is undefined means change the default cache options"},value:{name:"value",type:"any",description:"the value to store, if value is null means remove the key"},options:{name:"options",type:"object|number",description:"the optional cache options:{capacity,expires,cleanInterval} or expires"}},result:"any"}),r.cache=new pe.Cache(e)),r}var me=ye("lrucache"),be=class t extends he{static get apiRoot(){return t._apiRoot}static setApiRoot(e){t._apiRoot=e}static async loadFrom(){if(this._apiRoot){const t=await fetch(this._apiRoot,{headers:{"Content-Type":"application/json"}}),e=await t.json();e&&this.loadFromSync(e)}else v("missing apiRoot to load tools","ClientTools")}static loadFromSync(e){for(const r in e){const n=this.get(r),s=e[r];n?n instanceof t?n.assign(s):v(`${r} already registered as ${n.constructor.name}`,"ClientTools"):this.register(s)}}static async fetch(t,e){const r=this.get(t);if(r&&r.fetch)return r.fetch(e)}getUrlParams(t){if(void 0!==t){const e=JSON.stringify(t);if("{}"!==e&&"[]"!==e&&'""'!==e)return"?p="+encodeURIComponent(e)}return""}async fetch(t,e,r){const n={...this.fetchOptions};let s;n.headers&&n.headers["Content-Type"]||(n.headers={"Content-Type":"application/json",...n.headers}),t?.stream&&!n.headers.Connection&&(n.headers.Connection="keep-alive"),e||(e=this.action||"post"),"res"===e&&(e="get"),r?("string"!=typeof r&&(r=JSON.stringify(r)),r=this.name+"/"+r):r=this.name,n.method=e.toUpperCase(),"get"===e||"delete"===e?s=r+this.getUrlParams(t):(n.body=JSON.stringify(t),s=r);const i=await fetch(`${this.apiRoot}/${s}`,n);if(!i.ok){throw await this.errorFrom(i)}return i}async errorFrom(t){let e,r=t.status,n=t.statusText,s=this.name;if(t.body){const r=await t.text();try{const t=JSON.parse(r);t&&(t.error&&(n=t.error),t.name&&(s=t.name),t.data&&(e=t.data,e.name=s,e.what&&(e.msg=n,n=e.what)),t.message&&(n=n+":"+t.message))}catch(t){console.warn("🚀 ~ parse error body to json:",t)}}return E(n,s,r)}async func(t){const e=await this.fetch(t);if(t?.stream)return e;return await e.json()}},ge={...S};be.defineProperties(be,ge);var xe=class extends be{async _func(t,e){const r=await this.fetch(e,t);if(e?.stream)return r;return await r.json()}async func(t){const e=t.action;return e&&delete t.action,this._func(e,t)}assignMethods(t){if(Array.isArray(t))for(const e of t){const t=e.startsWith("$")?e.slice(1):e;this[t]||(this[t]=(t=>this._func.bind(this,t))(e))}}},Ee={methods:{type:"array",assign(t,e,r,n,s){s?.isExported||e.assignMethods(t)}}};xe.defineProperties(xe,Ee);var ve=class extends xe{async fetch(t,e){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let r=t.id;return r||v("id is required"),"string"==typeof r&&(r=encodeURIComponent(r)),delete t.id,super.fetch(t,e,r)}"list"===e?e="get":e.startsWith("$")&&(t.act=e,e="post")}return await super.fetch(t,e)}},ke=class extends ve{constructor(){super(...arguments),this._sseEvents={},this._forwardEvents=new Set,this.name=Bt,this.description="subscribe server sent event",this.ebListener=async function(...t){const e=this.type;this.target.publish&&await this.target.publish({data:t,event:e})}}get evtSource(){let t=this._es;return t&&t.readyState!==EventSource.CLOSED||(t=this.initEventSource(this._esEvents)),t}get active(){return!!this._es&&this._es.readyState!==EventSource.CLOSED}set active(t){t!==this.active&&(t?this.initEventSource(this._esEvents):this._es&&(this._es.close(),this._es=void 0))}initEventSource(t){if("string"==typeof t&&(t=[t]),this._es&&this._es.readyState!==EventSource.CLOSED){if(!this._esEvents||t&&t.every((t=>this._esEvents.includes(t))))return this._es;this._es.close()}const e=t?this.getUrlParams({event:t}):"",r=`${this.apiRoot}/${this.name}${e}`,n=this._es=new EventSource(r);return Object.entries(this._sseEvents).forEach((([t,e])=>{n.addEventListener(t,e)})),this._esEvents=t,n}esListener(t){const e=t.data?JSON.parse(t.data):void 0,r=t.type;if(!this._forwardEvents.has(r)){const t=this.emitter;t&&e&&r&&(Array.isArray(e)?t.emit(r,...e):t.emit(r,e))}}async subscribe(t){const e=await this.sub({event:t});"string"==typeof t&&(t=[t]);const r=this.evtSource;for(const e of t)if(!this._sseEvents[e]){const t=this._sseEvents[e]=this.esListener.bind(this);r.addEventListener(e,t)}return e}async unsubscribe(t){const e=await this.unsub({event:t});"string"==typeof t&&(t=[t]);for(const e of t){const t=this._sseEvents[e];t&&(delete this._sseEvents[e],this.evtSource.removeEventListener(e,t))}return e}forwardEvent(t){"string"==typeof t&&(t=[t]);for(const e of t)this._forwardEvents.has(e)||(this._forwardEvents.add(e),this.on&&this.on(e,this.ebListener))}unforwardEvent(t){"string"==typeof t&&(t=[t]);for(const e of t)this._forwardEvents.has(e)&&(this._forwardEvents.delete(e),this.off&&this.off(e,this.ebListener))}async init(t){if(this.active=!1,this.initEventSource(t),t)return await this.subscribe(t)}},Se=new ke(Bt),$e=require("util-ex"),Oe=class t extends he{static get apiRoot(){return this._apiRoot}static setApiRoot(t){this._apiRoot=t}static toJSON(){const e={};for(const r in this.items){let n=this.items[r];(n instanceof t||n.isApi)&&(n.allowExportFunc||(n=n.toJSON(),delete n.func),e[r]=n)}return e}func({}){}},je={...S};Oe.defineProperties(Oe,je);var Ce=class extends Oe{constructor(t,e={}){super(t,e),this.params={act:{type:"string"}};const r=this.methods=[];this.initRpcMethods(r)}get SpecialRpcMethodNames(){return this.constructor.SpecialRpcMethodNames}initRpcMethods(t=this.methods){const e=this.SpecialRpcMethodNames;if(Array.isArray(e))for(const r of e)"function"==typeof this[r]&&t.push(r);(0,$e.getAllNames)(Object.getPrototypeOf(this)).filter((t=>t.startsWith("$")&&"function"==typeof this[t])).forEach((e=>{t.push(e);const r=e.slice(1);void 0===this[r]&&(this[r]=this[e])}))}cast(t,e){let r=this.params[t];return r&&("string"!=typeof r&&(r=r.type),"number"===r&&(e=Number(e))),e}getMethodFromParams(t){const e=t?.act;return e}castParams(t){return t}func(t){const e=this.getMethodFromParams(t);if(e&&"function"==typeof this[e])return t=this.castParams(t),this[e](t);throw new b(e,this.name)}};Ce.defineProperties(Ce,{methods:{type:"array"}});var Ae=class extends Ce{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}}}static{this.SpecialRpcMethodNames=k}getMethodFromParams(t){let e=t?._req?.method?.toLowerCase();return"get"===e&&void 0===t.id&&(e="list"),"post"===e&&t.act&&(e=t.act),e}castParams(t){return void 0!==t.id&&(t.id=this.cast("id",t.id)),t}},Te=we.runSync(),Me=class t extends Ae{constructor(){super(...arguments),this.name=Bt,this.description="subscribe server sent event",this.result="event",this.depends={[Ft]:we}}static get sse(){return this._sse||(this._sse=new Lt),this._sse}get sse(){return this.constructor.sse}static publish(e,r){return t.sse.publish(e,r)}static{this.ebListener=function(...e){t.sse.publish(e,this.type)}}static subscribe(e,r,n){return t.sse.subscribe(e,r,n)}static alreadyForward(e){const r=Te.listeners(e);for(const e of r)if(e===t.ebListener)return!0}publishSSE(t,e){return this.constructor.publish(t,e)}subscribeSSE(t,e,r){return"string"==typeof r&&(r=[r]),this.constructor.subscribe(t,e,r)}forward(e){Array.isArray(e)||(e=[e]);for(const r of e)t.alreadyForward(r)||Te.on(r,t.ebListener)}unforward(e){"string"==typeof e&&(e=[e]);for(const r of e)Te.off(r,t.ebListener)}list({_req:t,_res:e,event:r}){t&&e&&this.subscribeSSE(t,e,r)}$sub({event:t}){if(t)return this.forward(t),{event:t};v("event is required","sub",400)}$unsub({event:t}){if(t)return this.unforward(t),{event:t};v("event is required","unsub",400)}$publish({event:t,data:e}){if(t&&e){"string"==typeof t&&(t=[t]);for(const r of t)this.publishSSE(e,r);return{event:t}}v("event or data is required","pub",400)}isStream(t){return"list"===this.getMethodFromParams(t)}},qe=new Me(Bt);function Ie(){we.register(),me.register()}
|
|
1
|
+
"use strict";var t,e=Object.create,r=Object.defineProperty,n=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,i=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,a=(t,e,i,a)=>{if(e&&"object"==typeof e||"function"==typeof e)for(let c of s(e))o.call(t,c)||c===i||r(t,c,{get:()=>e[c],enumerable:!(a=n(e,c))||a.enumerable});return t},c=(t,n,s)=>(s=null!=t?e(i(t)):{},a(!n&&t&&t.__esModule?s:r(s,"default",{value:t,enumerable:!0}),t)),u={};((t,e)=>{for(var n in e)r(t,n,{get:e[n],enumerable:!0})})(u,{EventClient:()=>pe,EventServer:()=>ve,EventToolFunc:()=>ne,_lrucache:()=>oe,createLRUCache:()=>ae,event:()=>se,eventClient:()=>de,eventServer:()=>ke,lrucache:()=>ce,registerCoreTools:()=>Se}),module.exports=(t=u,a(r({},"__esModule",{value:!0}),t));var h=require("events-ex"),l=require("property-manager"),f=require("util-ex"),w=require("@isdk/common-error"),p=(require("custom-ability"),["get","post","put","delete","patch","list","res"]),d={apiRoot:{type:"string",get(){return this._apiRoot??this.constructor.apiRoot},set(t){this._apiRoot=t}},action:{type:"string",assign:(t,e,r,n,s)=>t||"post"},fetchOptions:{type:"object"},allowExportFunc:{type:"boolean"}},y=(require("date-fns"),require("date-fns"),require("custom-factory"));var m="default",b=class t extends y.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||m,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||m);if(e)return Reflect.construct(e,arguments);throw new w.CommonError(`Prompt template type ${n} not found`,"PromptTemplate",w.ErrorCode.InvalidArgument)}}_initialize(t){throw new w.NotImplementationError("Not implemented","PromptTemplate")}initialize(e){this.constructor!==t&&(Object.assign(this,this.toJSON(e)),e?.ignoreInitialize||this._initialize(e))}_format(t){throw new w.NotImplementationError("Not implemented","PromptTemplate")}async format(e){const r=this.data;if(e={...r,...e},r)for(const[t,n]of Object.entries(r))e[t]===n&&"function"==typeof n&&(delete e[t],e[t]=await n(e));for(const[r,n]of Object.entries(e))n instanceof t&&(delete e[r],e[r]=await n.format(e));return this._format(e)}partial(t){t={...this.data,...t};const e=this.toJSON();return e.data=t,e.ignoreInitialize=!0,new this.constructor(e)}toJSON(e=this){let r={template:e.template,data:e.data,inputVariables:e.inputVariables,compiledTemplate:e.compiledTemplate};var n;return e.templateFormat&&t.get(e.templateFormat)!==this.constructor&&(r.templateFormat=e.templateFormat),n=r,r=Object.keys(n).reduce(((t,e)=>{const r=n[e];return null!=r&&(t[e]=r),t}),{}),r}};(async function(){let t=!1,e=!1;try{for await(const e of function*(){try{yield Promise.reject()}finally{t=!0}}())throw new Error("impossible")}catch{e=!0}return e&&t})().then((t=>{t}));var g=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),E=Object.freeze({set:g.Set,for:g.For,in:g.In,is:g.Is,if:g.If,else:g.Else,endif:g.EndIf,elif:g.ElseIf,endfor:g.EndFor,and:g.And,or:g.Or,not:g.Not,"not in":g.NotIn,macro:g.Macro,endmacro:g.EndMacro,true:g.BooleanLiteral,false:g.BooleanLiteral,True:g.BooleanLiteral,False:g.BooleanLiteral}),x=class{constructor(t,e){this.value=t,this.type=e}};function v(t){return/\w/.test(t)}function k(t){return/[0-9]/.test(t)}var S=[["{%",g.OpenStatement],["%}",g.CloseStatement],["{{",g.OpenExpression],["}}",g.CloseExpression],["(",g.OpenParen],[")",g.CloseParen],["{",g.OpenCurlyBracket],["}",g.CloseCurlyBracket],["[",g.OpenSquareBracket],["]",g.CloseSquareBracket],[",",g.Comma],[".",g.Dot],[":",g.Colon],["|",g.Pipe],["<=",g.ComparisonBinaryOperator],[">=",g.ComparisonBinaryOperator],["==",g.ComparisonBinaryOperator],["!=",g.ComparisonBinaryOperator],["<",g.ComparisonBinaryOperator],[">",g.ComparisonBinaryOperator],["+",g.AdditiveBinaryOperator],["-",g.AdditiveBinaryOperator],["*",g.MultiplicativeBinaryOperator],["/",g.MultiplicativeBinaryOperator],["%",g.MultiplicativeBinaryOperator],["=",g.Equals]],$=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);var O=class{constructor(){this.type="Statement"}},j=class extends O{constructor(t){super(),this.body=t,this.type="Program"}},C=class extends O{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r,this.type="If"}},A=class extends O{constructor(t,e,r,n){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=n,this.type="For"}},M=class extends O{constructor(t,e){super(),this.assignee=t,this.value=e,this.type="Set"}},T=class extends O{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r,this.type="Macro"}},q=class extends O{constructor(){super(...arguments),this.type="Expression"}},I=class extends q{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r,this.type="MemberExpression"}},V=class extends q{constructor(t,e){super(),this.callee=t,this.args=e,this.type="CallExpression"}},N=class extends q{constructor(t){super(),this.value=t,this.type="Identifier"}},P=class extends q{constructor(t){super(),this.value=t,this.type="Literal"}},U=class extends P{constructor(){super(...arguments),this.type="NumericLiteral"}},B=class extends P{constructor(){super(...arguments),this.type="StringLiteral"}},F=class extends P{constructor(){super(...arguments),this.type="BooleanLiteral"}},_=class extends P{constructor(){super(...arguments),this.type="ArrayLiteral"}},L=class extends P{constructor(){super(...arguments),this.type="TupleLiteral"}},R=class extends P{constructor(){super(...arguments),this.type="ObjectLiteral"}},J=class extends q{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r,this.type="BinaryExpression"}},z=class extends q{constructor(t,e){super(),this.operand=t,this.filter=e,this.type="FilterExpression"}},W=class extends q{constructor(t,e){super(),this.iterable=t,this.test=e,this.type="SelectExpression"}},K=class extends q{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r,this.type="TestExpression"}},D=class extends q{constructor(t,e){super(),this.operator=t,this.argument=e,this.type="UnaryExpression"}},Z=class extends q{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r,this.type="SliceExpression"}},H=class extends q{constructor(t,e){super(),this.key=t,this.value=e,this.type="KeywordArgumentExpression"}};function G(t){const e=new j([]);let r=0;function n(e,n){const s=t[r++];if(!s||s.type!==e)throw new Error(`Parser Error: ${n}. ${s.type} !== ${e}.`);return s}function s(){let e;switch(t[r].type){case g.Text:e=new B(n(g.Text,"Expected text token").value);break;case g.OpenStatement:e=function(){let e;switch(n(g.OpenStatement,"Expected opening statement token"),t[r].type){case g.Set:++r,e=a(),n(g.CloseStatement,"Expected closing statement token");break;case g.If:++r,e=c(),n(g.OpenStatement,"Expected {% token"),n(g.EndIf,"Expected endif token"),n(g.CloseStatement,"Expected %} token");break;case g.Macro:++r,e=function(){const t=v();if("Identifier"!==t.type)throw new SyntaxError("Expected identifier following macro statement");const e=m();n(g.CloseStatement,"Expected closing statement token");const r=[];for(;i(g.OpenStatement,g.EndMacro);)r.push(s());return new T(t,e,r)}(),n(g.OpenStatement,"Expected {% token"),n(g.EndMacro,"Expected endmacro token"),n(g.CloseStatement,"Expected %} token");break;case g.For:++r,e=function(){const t=u(!0);if(!(t instanceof N||t instanceof L))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${t.type} instead`);n(g.In,"Expected `in` keyword following loop variable");const e=h();n(g.CloseStatement,"Expected closing statement token");const a=[];for(;i(g.OpenStatement,g.EndFor)&&i(g.OpenStatement,g.Else);)a.push(s());const c=[];if(o(g.OpenStatement,g.Else))for(++r,++r,n(g.CloseStatement,"Expected closing statement token");i(g.OpenStatement,g.EndFor);)c.push(s());return new A(t,e,a,c)}(),n(g.OpenStatement,"Expected {% token"),n(g.EndFor,"Expected endfor token"),n(g.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${t[r].type} ${t[r].value}`)}return e}(),e.isStatement=!0;break;case g.OpenExpression:e=function(){n(g.OpenExpression,"Expected opening expression token");const t=h();return n(g.CloseExpression,"Expected closing expression token"),t}(),e.isStatement=!0;break;default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}return e}function i(...e){return r+e.length<=t.length&&e.some(((e,n)=>e!==t[r+n].type))}function o(...e){return r+e.length<=t.length&&e.every(((e,n)=>e===t[r+n].type))}function a(){const t=h();if(o(g.Equals)){++r;const e=a();return new M(t,e)}return t}function c(){const e=h();n(g.CloseStatement,"Expected closing statement token");const i=[],a=[];for(;t[r]?.type!==g.OpenStatement||t[r+1]?.type!==g.ElseIf&&t[r+1]?.type!==g.Else&&t[r+1]?.type!==g.EndIf;)i.push(s());if(t[r]?.type===g.OpenStatement&&t[r+1]?.type!==g.EndIf)if(++r,o(g.ElseIf))n(g.ElseIf,"Expected elseif token"),a.push(c());else for(n(g.Else,"Expected else token"),n(g.CloseStatement,"Expected closing statement token");t[r]?.type!==g.OpenStatement||t[r+1]?.type!==g.EndIf;)a.push(s());return new C(e,i,a)}function u(t=!1){const e=t?v:h,n=[e()],s=o(g.Comma);for(;s&&(++r,n.push(e()),o(g.Comma)););return s?new L(n):n[0]}function h(){return function(){const t=l();if(o(g.If)){++r;const e=l();if(o(g.Else)){++r;const n=l();return new C(e,[t],[n])}return new W(t,e)}return t}()}function l(){let e=f();for(;o(g.Or);){const n=t[r];++r;const s=f();e=new J(n,e,s)}return e}function f(){let e=w();for(;o(g.And);){const n=t[r];++r;const s=w();e=new J(n,e,s)}return e}function w(){let e;for(;o(g.Not);){const n=t[r];++r;const s=w();e=new D(n,s)}return e??function(){let e=p();for(;o(g.ComparisonBinaryOperator)||o(g.In)||o(g.NotIn);){const n=t[r];++r;const s=p();e=new J(n,e,s)}return e}()}function p(){let e=E();for(;o(g.AdditiveBinaryOperator);){const n=t[r];++r;const s=E();e=new J(n,e,s)}return e}function d(){const e=function(){let e=v();for(;o(g.Dot)||o(g.OpenSquareBracket);){const s=t[r];let i;++r;const o=s.type!==g.Dot;if(o)i=b(),n(g.CloseSquareBracket,"Expected closing square bracket");else if(i=v(),"Identifier"!==i.type)throw new SyntaxError("Expected identifier following dot operator");e=new I(e,i,o)}return e}();return o(g.OpenParen)?y(e):e}function y(t){let e=new V(t,m());return o(g.OpenParen)&&(e=y(e)),e}function m(){n(g.OpenParen,"Expected opening parenthesis for arguments list");const t=function(){const t=[];for(;!o(g.CloseParen);){let e=h();if(o(g.Equals)){if(++r,!(e instanceof N))throw new SyntaxError("Expected identifier for keyword argument");const t=h();e=new H(e,t)}t.push(e),o(g.Comma)&&++r}return t}();return n(g.CloseParen,"Expected closing parenthesis for arguments list"),t}function b(){const t=[];let e=!1;for(;!o(g.CloseSquareBracket);)o(g.Colon)?(t.push(void 0),++r,e=!0):(t.push(h()),o(g.Colon)&&(++r,e=!0));if(0===t.length)throw new SyntaxError("Expected at least one argument for member/slice expression");if(e){if(t.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new Z(...t)}return t[0]}function E(){let e=x();for(;o(g.MultiplicativeBinaryOperator);){const n=t[r];++r;const s=x();e=new J(n,e,s)}return e}function x(){let t=function(){let t=d();for(;o(g.Pipe);){++r;let e=v();if(!(e instanceof N))throw new SyntaxError("Expected identifier for the filter");o(g.OpenParen)&&(e=y(e)),t=new z(t,e)}return t}();for(;o(g.Is);){++r;const e=o(g.Not);e&&++r;let n=v();if(n instanceof F&&(n=new N(n.value.toString())),!(n instanceof N))throw new SyntaxError("Expected identifier for the test");t=new K(t,e,n)}return t}function v(){const e=t[r];switch(e.type){case g.NumericLiteral:return++r,new U(Number(e.value));case g.StringLiteral:return++r,new B(e.value);case g.BooleanLiteral:return++r,new F("true"===e.value.toLowerCase());case g.Identifier:return++r,new N(e.value);case g.OpenParen:{++r;const e=u();if(t[r].type!==g.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${t[r].type} instead`);return++r,e}case g.OpenSquareBracket:{++r;const t=[];for(;!o(g.CloseSquareBracket);)t.push(h()),o(g.Comma)&&++r;return++r,new _(t)}case g.OpenCurlyBracket:{++r;const t=new Map;for(;!o(g.CloseCurlyBracket);){const e=h();n(g.Colon,"Expected colon between key and value in object literal");const s=h();t.set(e,s),o(g.Comma)&&++r}return++r,new R(t)}default:throw new SyntaxError(`Unexpected token: ${e.type}`)}}for(;r<t.length;)e.body.push(s());return e}function Q(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 X(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 Y(t){return t.replace(/\b\w/g,(t=>t.toUpperCase()))}var tt=class{constructor(t=void 0){this.type="RuntimeValue",this.builtins=new Map,this.value=t}__bool__(){return new nt(!!this.value)}toString(){return""+this.value}toJSON(){return this.value}},et=class extends tt{constructor(){super(...arguments),this.type="NumericValue"}},rt=class t extends tt{constructor(){super(...arguments),this.type="StringValue",this.builtins=new Map([["upper",new ct((()=>new t(this.value.toUpperCase())))],["lower",new ct((()=>new t(this.value.toLowerCase())))],["strip",new ct((()=>new t(this.value.trim())))],["title",new ct((()=>new t(Y(this.value))))],["length",new et(this.value.length)],["rstrip",new ct((()=>new t(this.value.trimEnd())))],["lstrip",new ct((()=>new t(this.value.trimStart())))]])}},nt=class extends tt{constructor(){super(...arguments),this.type="BooleanValue"}},st=class extends tt{constructor(t,e){super(t),this.orgValue=e,this.type="ObjectValue",this.builtins=new Map([["get",new ct((([t,e])=>{if(!(t instanceof rt))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new ut}))],["items",new ct((()=>new ot(Array.from(this.value.entries()).map((([t,e])=>new ot([new rt(t),e]))))))]])}toString(){let t;return t=this.orgValue&&this.orgValue.toString!==Object.prototype.toString?this.orgValue.toString():JSON.stringify(Object.fromEntries(this.value.entries())),t}toJSON(){return this.orgValue?this.orgValue:Object.fromEntries(this.value.entries())}__bool__(){return new nt(this.value.size>0)}},it=class extends st{constructor(){super(...arguments),this.type="KeywordArgumentsValue"}},ot=class extends tt{constructor(){super(...arguments),this.type="ArrayValue",this.builtins=new Map([["length",new et(this.value.length)]])}__bool__(){return new nt(this.value.length>0)}},at=class extends ot{constructor(){super(...arguments),this.type="TupleValue"}},ct=class extends tt{constructor(){super(...arguments),this.type="FunctionValue"}},ut=class extends tt{constructor(){super(...arguments),this.type="NullValue"}},ht=class extends tt{constructor(){super(...arguments),this.type="UndefinedValue"}},lt=class{constructor(t){this.parent=t,this.variables=new Map([["namespace",new ct((t=>{if(0===t.length)return new st(new Map);if(1!==t.length||!(t[0]instanceof st))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 ct],["odd",t=>{if("NumericValue"!==t.type)throw new Error(`Cannot apply test "odd" to type: ${t.type}`);return t.value%2!=0}],["even",t=>{if("NumericValue"!==t.type)throw new Error(`Cannot apply test "even" to type: ${t.type}`);return t.value%2==0}],["false",t=>"BooleanValue"===t.type&&!t.value],["true",t=>"BooleanValue"===t.type&&t.value],["string",t=>"StringValue"===t.type],["number",t=>"NumericValue"===t.type],["integer",t=>"NumericValue"===t.type&&Number.isInteger(t.value)],["iterable",t=>t instanceof ot||t instanceof rt],["lower",t=>{const e=t.value;return"StringValue"===t.type&&e===e.toLowerCase()}],["upper",t=>{const e=t.value;return"StringValue"===t.type&&e===e.toUpperCase()}],["none",t=>"NullValue"===t.type],["defined",t=>"UndefinedValue"!==t.type],["undefined",t=>"UndefinedValue"===t.type],["equalto",(t,e)=>t.value===e.value],["eq",(t,e)=>t.value===e.value]])}set(t,e){return this.declareVariable(t,wt(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 ht}catch{return new ht}}},ft=class{constructor(t){this.global=t??new lt}run(t){return this.evaluate(t,this.global)}evaluateBinaryExpression(t,e){const r=this.evaluate(t.left,e);switch(t.operator.value){case"and":return r.__bool__().value?this.evaluate(t.right,e):r;case"or":return r.__bool__().value?r:this.evaluate(t.right,e)}const n=this.evaluate(t.right,e);switch(t.operator.value){case"==":return new nt(r.value==n.value);case"!=":return new nt(r.value!=n.value)}if(r instanceof ht||n instanceof ht)throw new Error("Cannot perform operation on undefined values");if(r instanceof ut||n instanceof ut)throw new Error("Cannot perform operation on null values");if(r instanceof et&&n instanceof et)switch(t.operator.value){case"+":return new et(r.value+n.value);case"-":return new et(r.value-n.value);case"*":return new et(r.value*n.value);case"/":return new et(r.value/n.value);case"%":return new et(r.value%n.value);case"<":return new nt(r.value<n.value);case">":return new nt(r.value>n.value);case">=":return new nt(r.value>=n.value);case"<=":return new nt(r.value<=n.value)}else if(r instanceof ot&&n instanceof ot){if("+"===t.operator.value)return new ot(r.value.concat(n.value))}else if(n instanceof ot){const e=void 0!==n.value.find((t=>t.value===r.value));switch(t.operator.value){case"in":return new nt(e);case"not in":return new nt(!e)}}if((r instanceof rt||n instanceof rt)&&"+"===t.operator.value)return new rt(r.toString()+n.toString());if(r instanceof rt&&n instanceof rt)switch(t.operator.value){case"in":return new nt(n.value.includes(r.value));case"not in":return new nt(!n.value.includes(r.value))}if(r instanceof rt&&n instanceof st)switch(t.operator.value){case"in":return new nt(n.value.has(r.value));case"not in":return new nt(!n.value.has(r.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${r.type} and ${n.type}`)}evaluateArguments(t,e){const r=[],n=new Map;for(const s of t)if("KeywordArgumentExpression"===s.type){const t=s;n.set(t.key.value,this.evaluate(t.value,e))}else{if(n.size>0)throw new Error("Positional arguments must come before keyword arguments");r.push(this.evaluate(s,e))}return[r,n]}evaluateFilterExpression(t,e){const r=this.evaluate(t.operand,e);if("Identifier"===t.filter.type){const n=t.filter,s=e.lookupVariable(n.value);if(s instanceof ct)return s.value([r],e);if(r instanceof ot)switch(n.value){case"list":return r;case"first":return r.value[0];case"last":return r.value[r.value.length-1];case"length":return new et(r.value.length);case"reverse":return new ot(r.value.reverse());case"sort":return new ot(r.value.sort(((t,e)=>{if(t.type!==e.type)throw new Error(`Cannot compare different types: ${t.type} and ${e.type}`);switch(t.type){case"NumericValue":return t.value-e.value;case"StringValue":return t.value.localeCompare(e.value);default:throw new Error(`Cannot compare type: ${t.type}`)}})));default:throw new Error(`Unknown ArrayValue filter: ${n.value}`)}else if(r instanceof rt)switch(n.value){case"length":return new et(r.value.length);case"upper":return new rt(r.value.toUpperCase());case"lower":return new rt(r.value.toLowerCase());case"title":return new rt(Y(r.value));case"capitalize":return new rt(r.value.charAt(0).toUpperCase()+r.value.slice(1));case"trim":return new rt(r.value.trim());case"trimStart":return new rt(r.value.trimStart());case"trimEnd":return new rt(r.value.trimEnd());case"indent":return new rt(r.value.split("\n").map(((t,e)=>0===e||0===t.length?t:" "+t)).join("\n"));case"string":return r;default:throw new Error(`Unknown StringValue filter: ${n.value}`)}else{if(r instanceof et){if("abs"===n.value)return new et(Math.abs(r.value));throw new Error(`Unknown NumericValue filter: ${n.value}`)}if(r instanceof st)switch(n.value){case"items":return new ot(Array.from(r.value.entries()).map((([t,e])=>new ot([new rt(t),e]))));case"length":return new et(r.value.size);case"string":return new rt(r.toString());default:throw new Error(`Unknown ObjectValue filter: ${n.value}`)}}throw new Error(`Cannot apply filter "${n.value}" to type: ${r.type}`)}if("CallExpression"===t.filter.type){const n=t.filter;if("Identifier"!==n.callee.type)throw new Error(`Unknown filter: ${n.callee.type}`);const s=n.callee.value,i=e.lookupVariable(s);if(i instanceof ct){const[t,s]=this.evaluateArguments(n.args,e);return s.size>0&&t.push(new it(s)),i.value([r,...t],e)}if(r instanceof ot){switch(s){case"selectattr":{if(r.value.some((t=>!(t instanceof st))))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 ot(a)}case"map":{const[,t]=this.evaluateArguments(n.args,e);if(t.has("attribute")){const e=t.get("attribute");if(!(e instanceof rt))throw new Error("attribute must be a string");const n=t.get("default"),s=r.value.map((t=>{if(!(t instanceof st))throw new Error("items in map must be an object");return t.value.get(e.value)??n??new ht}));return new ot(s)}throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${s}`)}if(r instanceof rt){if("indent"===s){const[t,s]=this.evaluateArguments(n.args,e),i=t.at(0)??s.get("width")??new et(4);if(!(i instanceof et))throw new Error("width must be a number");const o=t.at(1)??s.get("first")??new nt(!1),a=t.at(2)??s.get("blank")??new nt(!1),c=r.value.split("\n"),u=" ".repeat(i.value),h=c.map(((t,e)=>!o.value&&0===e||!a.value&&0===t.length?t:u+t));return new rt(h.join("\n"))}throw new Error(`Unknown StringValue filter: ${s}`)}throw new Error(`Cannot apply filter "${s}" to type: ${r.type}`)}throw new Error(`Unknown filter: ${t.filter.type}`)}evaluateTestExpression(t,e){const r=this.evaluate(t.operand,e),n=e.tests.get(t.test.value);if(!n)throw new Error(`Unknown test: ${t.test.value}`);const s=n(r);return new nt(t.negate?!s:s)}evaluateUnaryExpression(t,e){const r=this.evaluate(t.argument,e);if("not"===t.operator.value)return new nt(!r.value);throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let r="";for(const n of t){const t=this.evaluate(n,e);"NullValue"!==t.type&&"UndefinedValue"!==t.type&&(r+=t)}return new rt(r)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){const[r,n]=this.evaluateArguments(t.args,e);n.size>0&&r.push(new it(n));const s=this.evaluate(t.callee,e);if("FunctionValue"!==s.type)throw new Error(`Cannot call something that is not a function: got ${s.type}`);return s.value(r,e)}evaluateSliceExpression(t,e,r){if(!(t instanceof ot||t instanceof rt))throw new Error("Slice object must be an array or string");const n=this.evaluate(e.start,r),s=this.evaluate(e.stop,r),i=this.evaluate(e.step,r);if(!(n instanceof et||n instanceof ht))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof et||s instanceof ht))throw new Error("Slice stop must be numeric or undefined");if(!(i instanceof et||i instanceof ht))throw new Error("Slice step must be numeric or undefined");return t instanceof ot?new ot(X(t.value,n.value,s.value,i.value)):new rt(X(Array.from(t.value),n.value,s.value,i.value).join(""))}evaluateMemberExpression(t,e){const r=this.evaluate(t.object,e);let n,s;if(t.computed){if("SliceExpression"===t.property.type)return this.evaluateSliceExpression(r,t.property,e);n=this.evaluate(t.property,e)}else n=new rt(t.property.value);if(r instanceof st){if(!(n instanceof rt))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.value.get(n.value)??r.builtins.get(n.value)}else if(r instanceof ot||r instanceof rt)if(n instanceof et)s=r.value.at(n.value),r instanceof rt&&(s=new rt(r.value.at(n.value)));else{if(!(n instanceof rt))throw new Error(`Cannot access property with non-string/non-number: got ${n.type}`);s=r.builtins.get(n.value)}else{if(!(n instanceof rt))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.builtins.get(n.value)}return s instanceof tt?s:new ht}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 st))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 ut}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 lt(e);let n,s;if("SelectExpression"===t.iterable.type){const e=t.iterable;s=this.evaluate(e.iterable,r),n=e.test}else s=this.evaluate(t.iterable,r);if(!(s instanceof ot))throw new Error(`Expected iterable type in for loop: got ${s.type}`);const i=[],o=[];for(let e=0;e<s.value.length;++e){const a=new lt(r),c=s.value[e];let u;if("Identifier"===t.loopvar.type)u=e=>e.setVariable(t.loopvar.value,c);else{if("TupleLiteral"!==t.loopvar.type)throw new Error(`Invalid loop variable(s): ${t.loopvar.type}`);{const e=t.loopvar;if("ArrayValue"!==c.type)throw new Error(`Cannot unpack non-iterable type: ${c.type}`);const r=c;if(e.value.length!==r.value.length)throw new Error(`Too ${e.value.length>r.value.length?"few":"many"} items to unpack`);u=t=>{for(let n=0;n<e.value.length;++n){if("Identifier"!==e.value[n].type)throw new Error(`Cannot unpack non-identifier type: ${e.value[n].type}`);t.setVariable(e.value[n].value,r.value[n])}}}}if(n){u(a);if(!this.evaluate(n,a).__bool__().value)continue}i.push(c),o.push(u)}let a="",c=!0;for(let e=0;e<i.length;++e){const n=new Map([["index",new et(e+1)],["index0",new et(e)],["revindex",new et(i.length-e)],["revindex0",new et(i.length-e-1)],["first",new nt(0===e)],["last",new nt(e===i.length-1)],["length",new et(i.length)],["previtem",e>0?i[e-1]:new ht],["nextitem",e<i.length-1?i[e+1]:new ht]]);r.setVariable("loop",new st(n)),o[e](r);a+=this.evaluateBlock(t.body,r).value,c=!1}if(c){a+=this.evaluateBlock(t.defaultBlock,r).value}return new rt(a)}evaluateMacro(t,e){return e.setVariable(t.name.value,new ct(((e,r)=>{const n=new lt(r);let s;e=e.slice(),"KeywordArgumentsValue"===e.at(-1)?.type&&(s=e.pop());for(let r=0;r<t.args.length;++r){const i=t.args[r],o=e[r];if("Identifier"===i.type){const t=i;if(!o)throw new Error(`Missing positional argument: ${t.value}`);n.setVariable(t.value,o)}else{if("KeywordArgumentExpression"!==i.type)throw new Error(`Unknown argument type: ${i.type}`);{const t=i,e=o??s?.value.get(t.key.value)??this.evaluate(t.value,n);n.setVariable(t.key.value,e)}}}return this.evaluateBlock(t.body,n)}))),new ut}evaluate(t,e){if(void 0===t)return new ht;switch(t.type){case"Program":return this.evalProgram(t,e);case"Set":return this.evaluateSet(t,e);case"If":return this.evaluateIf(t,e);case"For":return this.evaluateFor(t,e);case"Macro":return this.evaluateMacro(t,e);case"NumericLiteral":return new et(Number(t.value));case"StringLiteral":return new rt(t.value);case"BooleanLiteral":return new nt(t.value);case"ArrayLiteral":return new ot(t.value.map((t=>this.evaluate(t,e))));case"TupleLiteral":return new at(t.value.map((t=>this.evaluate(t,e))));case"ObjectLiteral":{const r=new Map;for(const[n,s]of t.value){const t=this.evaluate(n,e);if(!(t instanceof rt))throw new Error(`Object keys must be strings: got ${t.type}`);r.set(t.value,this.evaluate(s,e))}return new st(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 wt(t){switch(typeof t){case"number":return new et(t);case"string":return new rt(t);case"boolean":return new nt(t);case"undefined":return new ht;case"object":return null===t?new ut:Array.isArray(t)?new ot(t.map(wt)):new st(new Map(Object.entries(t).map((([t,e])=>[t,wt(e)]))),t);case"function":return new ct(((e,r)=>{const n=e.map((t=>pt(t)));return wt(t(...n)??null)}));default:throw new Error(`Cannot convert to runtime value: ${t}`)}}function pt(t){let e=t;if(Array.isArray(t))e=t.map((t=>pt(t)));else if(t instanceof Map)e={},t.forEach(((t,r)=>{e[r]=pt(t)}));else switch(t.type){case"NullValue":e=null;break;case"UndefinedValue":e=void 0;break;case"ArrayValue":e=t.value.map((t=>pt(t)));break;case"KeywordArgumentsValue":case"ObjectValue":e=t.orgValue?t.orgValue:pt(t.value),"KeywordArgumentsValue"===t.type&&Object.setPrototypeOf(e,{jinja_kargs:!0});break;default:t.type&&(e=t.value)}return e}function dt(t,e=0){return Math.floor(Math.random()*(t-e+1))+e}var yt={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,r){return e&&"object"==typeof e&&(e.depth&&(r=e.depth),e=e.indent),mt(t,e,r)}};function mt(t,e,r){let n="";const s=r??0;if(null===t)n="null";else{const r=typeof t;switch(r){case"undefined":n="null";case"number":case"string":case"boolean":return JSON.stringify(t);case"object":{const r=e?" ".repeat(e):"",n="\n"+r.repeat(s),i=n+r;if(Array.isArray(t)){const r=t.map((t=>mt(t,e,s+1)));return e?`[${i}${r.join(`,${i}`)}${n}]`:`[${r.join(", ")}]`}{const r=Array.from(Object.entries(t)).map((([t,r])=>{const n=`"${t}": ${mt(r,e,s+1)}`;return e?`${i}${n}`:n}));return e?`{${r.join(",")}${n}}`:`{${r.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${r}`)}}return n}var bt=class extends lt{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()}},gt=class t{static{this.global=new bt}constructor(t,e={}){const r=function(t,e={}){const r=[],n=function(t,e={}){return t.endsWith("\n")&&(t=t.slice(0,-1)),t=t.replace(/{#.*?#}/gs,"{##}"),e.lstrip_blocks&&(t=t.replace(/^[ \t]*({[#%])/gm,"$1")),e.trim_blocks&&(t=t.replace(/([#%]})\n/g,"$1")),t.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}(t,e);let s=0;const i=t=>{let e="";for(;t(n[s]);)if("\\"!==n[s]){if(e+=n[s++],s>=n.length)throw new SyntaxError("Unexpected end of input")}else{if(++s,s>=n.length)throw new SyntaxError("Unexpected end of input");const t=n[s++],r=$.get(t);if(void 0===r)throw new SyntaxError(`Unexpected escaped character: ${t}`);e+=r}return e};t:for(;s<n.length;){const t=r.at(-1)?.type;if(void 0===t||t===g.CloseStatement||t===g.CloseExpression){let t="";for(;s<n.length&&("{"!==n[s]||"%"!==n[s+1]&&"{"!==n[s+1]);)t+=n[s++];if(t.length>0){r.push(new x(t,g.Text));continue}}i((t=>/\s/.test(t)));const e=n[s];if("-"===e||"+"===e){const t=r.at(-1)?.type;if(t===g.Text||void 0===t)throw new SyntaxError(`Unexpected character: ${e}`);switch(t){case g.Identifier:case g.NumericLiteral:case g.BooleanLiteral:case g.StringLiteral:case g.CloseParen:case g.CloseSquareBracket:break;default:{++s;const t=i(k);r.push(new x(`${e}${t}`,t.length>0?g.NumericLiteral:g.UnaryOperator));continue}}}for(const[t,e]of S)if(n.slice(s,s+t.length)===t){r.push(new x(t,e)),s+=t.length;continue t}if("'"!==e&&'"'!==e)if(k(e)){const t=i(k);r.push(new x(t,g.NumericLiteral))}else{if(!v(e))throw new SyntaxError(`Unexpected character: ${e}`);{const t=i(v),e=Object.hasOwn(E,t)?E[t]:g.Identifier;e===g.In&&r.at(-1)?.type===g.Not?(r.pop(),r.push(new x("not in",g.NotIn))):r.push(new x(t,e))}}else{++s;const t=i((t=>t!==e));r.push(new x(t,g.StringLiteral)),++s}}return r}(t,e={lstrip_blocks:!0,trim_blocks:!0,...e});this.parsed=G(r)}render(e){const r=new lt(t.global);r.set("false",!1),r.set("true",!0),r.set("raise_exception",(t=>{throw new Error(t)})),r.set("range",Q);for(const[t,n]of Object.entries(e))r.set(t,n);return new ft(r).run(this.parsed).toString()}};function Et(t,e){let r;switch(t.type){case"Identifier":r=t.value;break;case"MemberExpression":r=Et(t.object,e);break;case"FilterExpression":r=Et(t.operand,e);break;case"Set":{e||(e=[]);const n=Et(t.assignee);n&&e.push(n),r=Et(t.value,e);break}}return r&&e?.includes(r)&&(r=void 0),r}function xt(t){let e;if("Program"===t.type)e=t.body.some((t=>xt(t)));else e=t.isStatement;return e}function vt(t,e){let r=[];if(Array.isArray(t))r=t.map((t=>vt(t,e))).filter(Boolean).flat();else switch(t.type){case"Program":r=t.body.map((t=>vt(t,e))).filter(Boolean).flat();break;case"If":r=[Et(t.test,e),...vt(t.body,e),...vt(t.alternate,e)].filter(Boolean);break;case"BinaryExpression":r=[Et(t.left,e),Et(t.right,e)].filter(Boolean);break;case"For":{const n=Et(t.loopvar);n&&(e||(e=[]),e.push(n)),r=[Et(t.iterable,e),...vt(t.body,e)].filter(Boolean);break}case"CallExpression":r=[Et(t.callee,e),...vt(t.args,e)].filter(Boolean);break;default:r=[Et(t,e)].filter(Boolean)}return r}gt.global.assign(yt);function kt(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 St(t){const e=new Set;return t.forEach((t=>{"variable"===t.type&&e.add(t.name)})),[...e]}b.register(class extends b{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 gt(r)}catch(t){}return e&&(n=xt(e.parsed)),n}getVariables(t=this.compiledTemplate){return vt(t.parsed,[]).filter(((t,e,r)=>r.indexOf(t)===e))}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new w.CommonError("Prompt template must be a string","PromptTemplate",w.ErrorCode.InvalidArgument);this.compiledTemplate=new gt(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return this.compiledTemplate.render(t)}},{name:"hf",aliases:["huggingface","internal","default"]});function $t(t,e){return"string"==typeof e&&(e=e.split(".").filter((t=>t.length))),e.reduce(((t,e)=>t?.[e]),t)}function Ot(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 $t(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):$t(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=$t(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=$t(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):$t(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=$t(e,n);let o;return o=isNaN(s)?i[s.substring(1,s.length-1)]:i[parseInt(s,10)],o||""}))}(n,e,r),n}b.register(class extends b{static isTemplate(t){let e,r,n=!1;if("object"==typeof t?(r=t.template,e=t.compiledTemplate):r=t,!e&&r)try{e=kt(r)}catch(t){}if(e){n=St(e).length>0}return n}getVariables(t=this.compiledTemplate){return St(t)}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new w.CommonError("Prompt template must be a string","PromptTemplate",w.ErrorCode.InvalidArgument);this.compiledTemplate=kt(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return e=this.compiledTemplate,r=t,e.reduce(((t,e)=>{let n;return n="variable"===e.type?e.name in r?t+r[e.name]:t:t+e.text,n}),"");var e,r}},{name:"fstring",aliases:["python","f-string","langchain"]});function jt(t){return Object.keys(t).sort().map((e=>t[e]))}b.register(class extends b{static isTemplate(t){const e="string"==typeof t?t:t.template;return e?.includes("{{")&&e.includes("}}")}getVariables(t){const e={};return Ot(t,e,!0),[...Object.keys(e)]}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new w.CommonError("Prompt template must be a string","PromptTemplate",w.ErrorCode.InvalidArgument);this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables(e)}_format(t){return Ot(this.template,t)}},{name:"golang",aliases:["localai","ollama"]});b.register(class extends b{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 b?t.examplePrompt:b.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=jt(t);r.length>0&&e.push(...r)}const r=[this.prefix,...e,this.suffix].join(this.exampleSeparator),n=this.templateFormat;return await b.format({template:r,data:t,templateFormat:n})}toJSON(t=this){const e=super.toJSON(t);return t.suffix&&(e.suffix=t.suffix),t.exampleSeparator&&(e.exampleSeparator=t.exampleSeparator),t.prefix&&(e.prefix=t.prefix),t.examplePrompt&&(e.examplePrompt=t.examplePrompt),t.examples&&(e.examples=t.examples),e}},{name:"fewshot",aliases:["few_shot"]});new RegExp("([A-Z][a-z]{1,2}\\.)@(\\w)","g"),new RegExp("(\\.[a-zA-Z]\\.)@(\\w)","g");var Ct=require("custom-ability"),At="event",Mt="event-bus";(0,Ct.createAbilityInjector)((function(t){return class{static get emitter(){if(!this._emitter){const t=this.get(Mt)?.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 Tt(t,e){return!t||t.some((t=>t instanceof RegExp?t.test(e):t===e))}var qt=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||(0,w.throwError)("Channel closed","SSEChannel",498);let s=e;if(t||e)n=this.nextID++,"object"==typeof t&&(t.event?(s=t.event,void 0!==t.data&&(t=JSON.stringify(t.data))):t=JSON.stringify(t)),t=t?t.split(/[\r\n]+/).map((t=>"data: "+t)).join("\n"):"",r="id: "+n+"\n"+(e?"event: "+e+"\n":"")+(t||"data: ")+"\n\n",this.messages.push({id:n,_eventName:s,output:r});else{if(!this.clients.size)return;r="data: \n\n"}for([...this.clients].filter((t=>!s||Tt(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||(0,w.throwError)("Channel closed","SSEChannel",498);const n={req:t,res:e,events:r},s=this.options.maxStreamDuration;let i="max-age=0, stale-while-revalidate=0, stale-if-error=0, no-transform";s>0&&(i+=", s-maxage="+(Math.floor(s/1e3)-1));const o={"Content-Type":"text/event-stream","Cache-Control":i,Connection:"keep-alive"};this.options.cors&&(o["access-control-allow-origin"]="*"),n.req.socket.setNoDelay(!0),n.res.writeHead(200,o);let a="retry: "+this.options.clientRetryInterval+"\n\n";const c=Number.parseInt(t.headers["last-event-id"],10),u=Number.isNaN(c)?this.options.rewind:this.nextID-1-c;return u&&this.messages.filter((t=>Tt(n.events,t.eventName))).slice(0-u).forEach((t=>{a+=t.output})),n.res.write(a),this.clients.add(n),s>0&&setTimeout((()=>{n.res.writableEnded||this.unsubscribe(n)}),s),n.res.on("close",(()=>this.unsubscribe(n))),n}unsubscribe(t){t.res.end(),this.clients.delete(t)}clearClients(){this.clients.forEach((t=>t.res.end())),this.clients.clear()}listClients(){const t={};return this.clients.forEach((e=>{const r=e.req.socket.remoteAddress??"";r in t||(t[r]=0),t[r]++})),t}getSubscriberCount(){return this.clients.size}};require("eventsource-parser");require("uuid"),c(require("base32768")),require("uuid");var It=c(require("xxhashjs")),{h32:Vt,h64:Nt}=(c(require("base32768")),require("json-canonicalize"),It.default),Pt=(require("util-ex"),require("lodash-es"),require("util-ex"),require("load-config-file")),Ut=require("yaml"),Bt=require("yaml-types"),Ft=(require("mime-type/with-db"),require("yaml"),[Bt.regexp]);Pt.Config.register([".yml",".yaml"],(function(t){return(0,Ut.parse)(t,{customTags:Ft})})),Pt.Config.register([".json"],(function(t){return JSON.parse(t)}));var _t=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}},Lt=require("events-ex");function Rt(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 Jt=class{constructor(t){this._capacity=Rt(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(Rt(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)}}},zt=class extends Lt.EventEmitter{};function Wt(t){return"function"==typeof t}function Kt(){return"1"}var Dt=class{constructor(t,{initFn:e=Kt,pauseFn:r,resumeFn:n,capacity:s=32}={}){if(Wt(r)!==Wt(n))throw new Error("pauseFn and resumeFn must be both set for pausing");this.maxConcurrency=t,this.free=new Jt(t),this.waiting=new Jt(s),this.releaseEmitter=new zt,this.useDefaultTokens=e===Kt,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}},Zt=require("custom-ability"),Ht=require("util-ex"),Gt=class extends AbortController{constructor(t){super(),(0,Ht.defineProperty)(this,"parent",t)}abort(t,e){this.signal.aborted||("string"==typeof t&&(t=new w.AbortError(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 w.AbortError(e.reason||"aborted")}}},Qt=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 Dt(t-1)),e}isAborted(t){const e=this.hasAsyncFeature(Yt);let r=this.__task_aborter;if(r&&e){if(null==t)throw new w.CommonError("Missing taskId",this.name+".isAborted",w.ErrorCode.InvalidArgument);r=r[t]}return!r||r.signal.aborted}getRunningTask(t){const e=this.hasAsyncFeature(Yt);let r=this.__task_aborter;if(r&&e){if(null==t)throw new w.CommonError("Missing taskId",this.name+".getRunningTask",w.ErrorCode.InvalidArgument);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(Yt)){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(Yt);if(!n&&r&&this.getRunningTask())throw new w.CommonError("The task is running",this.name,w.ErrorCode.TooManyRequests);const s=t?.aborter||new Gt(this);if(!(s instanceof Gt)){if(!(s instanceof AbortController))throw new w.CommonError("aborter should be an AbortController",this.name,w.ErrorCode.InvalidArgument);Object.setPrototypeOf(s,new Gt(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(Yt)){const e=this.__task_aborter;this.cleanMultiTaskAborter(t.id,e)}else this.__task_aborter=void 0}_cleanMultiTaskAborter(t,e){"number"==typeof t?e[t]=void 0:delete e[t]}createTaskPromise(t,e,r){const n=this.createAborter(e,r?.taskId,r?.raiseError);void 0===e&&(e={}),"object"==typeof e&&(e.aborter=n);let s=t(e,n).then((t=>{if(t&&t instanceof ReadableStream){const e=()=>{this.cleanTaskAborter(n)},r=function(t){const e=t||{};return new TransformStream({async start(t){const r=t.error;if(t.error=n=>{r.call(t,n),e.onError&&e.onError(n)},e.onStart)try{await e.onStart(t)}catch(e){t.error(e)}},async transform(t,r){try{let n;e.onTransform&&(n=await e.onTransform(t,r)),n||(n=t),r.enqueue(n)}catch(t){r.error(t)}},async flush(t){if(e.onFinal)try{await e.onFinal(t)}catch(e){return t.error(e)}t.terminate()}})}({onStart:t=>{(0,Ht.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(Yt)){const t=e?.taskId;if(null==t)throw new w.CommonError("Missing data.taskId",this.name+".abort",w.ErrorCode.InvalidArgument);r=r[t],this.cleanMultiTaskAborter(t,n)}else this.__task_aborter=void 0;r&&!r.signal.aborted&&r.abort(t,e)}}};Qt.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},Qt.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};(0,Zt.createAbilityInjector)(Qt,"abort",{afterInjection:function(t,e){let r=t.prototype._asyncFeatures||0;r|=te.Cancelable,e&&(e.asyncFeatures&&(r|=e.asyncFeatures),e.maxTaskConcurrency>0&&(t.prototype._maxTaskConcurrency=e.maxTaskConcurrency)),t.prototype._asyncFeatures=r}}),require("lodash-es"),require("util-ex"),c(require("memoizee")),require("json-canonicalize"),require("pkg-dir");var Xt,Yt=0,te=((Xt=te||{})[Xt.MultiTask=1<<Yt]="MultiTask",Xt[Xt.Cancelable=2]="Cancelable",Xt[Xt.Priority=4]="Priority",Xt),ee=class t extends l.AdvancePropertyManager{static{this.items={}}static get(t){return this.items[t]}static list(){return this.items}static getByTag(t){let e;for(const r in this.list()){const n=this.get(r);let s=n.tags;if("string"==typeof s){if(s===t){e=n;break}}else if(Array.isArray(s)&&s.indexOf(t)>=0){e=n;break}}return e}static getAllByTag(t){let e=[];for(const r in this.list()){const n=this.get(r);let s=n.tags;"string"==typeof s?s===t&&e.push(n):Array.isArray(s)&&s.indexOf(t)>=0&&e.push(n)}return e}static hasAsyncFeature(t){const e=this.prototype;let r=e.asyncFeatures;return e._asyncFeatures&&(r|=e._asyncFeatures),_t.has(r,t)}static run(t,e){const r=this.get(t);if(r)return r.run(e);throw new w.NotFoundError(`${t} to run`,this.name)}static runSync(t,e){const r=this.get(t);if(r)return r.runSync(e);throw new w.NotFoundError(`${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 w.NotFoundError(`${t} to run`,this.name)}static runWithPosSync(t,...e){const r=this.get(t);if(r)return r.runWithPosSync(...e);throw new w.NotFoundError(`${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);(0,w.throwError)("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),_t.has(e,t)}isStream(t){return this.stream}},re={name:{type:"string"},description:{type:"string"},func:{type:"function",assign(t,e,r,n,s){let i=t;const o=typeof t;return s.isExported?i="function"===o?t.toString():t:t&&("string"!==o&&(t=t.toString()),i=(0,f._createFunction)(t,e.scope)),i}},params:{type:"object"},result:{type:"any"},setup:{type:"function"},depends:{type:"object",exported:!1},tags:{type:["array","string"]},isApi:{type:"boolean"},stream:{type:"boolean"},asyncFeatures:{type:"number"}};ee.defineProperties(ee,re);var ne=class extends ee{constructor(){super(...arguments),this._emitter=new h.EventEmitter,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},se=new ne(Mt),ie=require("secondary-cache");function oe({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 ae(t,e){let r=ee.get(t);return r||(r=new ee(t,{func:oe,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 ie.Cache(e)),r}var ce=ae("lrucache"),ue=class t extends ee{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(0,w.throwError)("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):(0,w.throwError)(`${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(0,w.createError)(n,s,r)}async func(t){const e=await this.fetch(t);if(t?.stream)return e;return await e.json()}},he={...d};ue.defineProperties(ue,he);var le=class extends ue{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))}}},fe={methods:{type:"array",assign(t,e,r,n,s){s?.isExported||e.assignMethods(t)}}};le.defineProperties(le,fe);var we=class extends le{async fetch(t,e){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let r=t.id;return r||(0,w.throwError)("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)}},pe=class extends we{constructor(){super(...arguments),this._sseEvents={},this._forwardEvents=new Set,this.name=At,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)}},de=new pe(At),ye=require("util-ex"),me=class t extends ee{static get apiRoot(){return this._apiRoot}static setApiRoot(t){this._apiRoot=t}static toJSON(){const e={};for(const r in this.items){let n=this.items[r];(n instanceof t||n.isApi)&&(n.allowExportFunc||(n=n.toJSON(),delete n.func),e[r]=n)}return e}func({}){}},be={...d};me.defineProperties(me,be);var ge=class extends me{constructor(t,e={}){super(t,e),this.params={act:{type:"string"}};const r=this.methods=[];this.initRpcMethods(r)}get SpecialRpcMethodNames(){return this.constructor.SpecialRpcMethodNames}initRpcMethods(t=this.methods){const e=this.SpecialRpcMethodNames;if(Array.isArray(e))for(const r of e)"function"==typeof this[r]&&t.push(r);(0,ye.getAllNames)(Object.getPrototypeOf(this)).filter((t=>t.startsWith("$")&&"function"==typeof this[t])).forEach((e=>{t.push(e);const r=e.slice(1);void 0===this[r]&&(this[r]=this[e])}))}cast(t,e){let r=this.params[t];return r&&("string"!=typeof r&&(r=r.type),"number"===r&&(e=Number(e))),e}getMethodFromParams(t){const e=t?.act;return e}castParams(t){return t}func(t){const e=this.getMethodFromParams(t);if(e&&"function"==typeof this[e])return t=this.castParams(t),this[e](t);throw new w.NotFoundError(e,this.name)}};ge.defineProperties(ge,{methods:{type:"array"}});var Ee=class extends ge{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}}}static{this.SpecialRpcMethodNames=p}getMethodFromParams(t){let e=t?._req?.method?.toLowerCase();return"get"===e&&void 0===t.id&&(e="list"),"post"===e&&t.act&&(e=t.act),e}castParams(t){return void 0!==t.id&&(t.id=this.cast("id",t.id)),t}},xe=se.runSync(),ve=class t extends Ee{constructor(){super(...arguments),this.name=At,this.description="subscribe server sent event",this.result="event",this.depends={[Mt]:se}}static get sse(){return this._sse||(this._sse=new qt),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=xe.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)||xe.on(r,t.ebListener)}unforward(e){"string"==typeof e&&(e=[e]);for(const r of e)xe.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};(0,w.throwError)("event is required","sub",w.ErrorCode.InvalidArgument)}$unsub({event:t}){if(t)return this.unforward(t),{event:t};(0,w.throwError)("event is required","unsub",w.ErrorCode.InvalidArgument)}$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}}(0,w.throwError)("event or data is required","pub",w.ErrorCode.InvalidArgument)}isStream(t){return"list"===this.getMethodFromParams(t)}},ke=new ve(At);function Se(){se.register(),ce.register()}
|
package/dist/funcs.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EventClient as m,EventServer as o,EventToolFunc as r,_lrucache as p,createLRUCache as t,event as
|
|
1
|
+
import{EventClient as m,EventServer as o,EventToolFunc as r,_lrucache as p,createLRUCache as t,event as P,eventClient as c,eventServer as h,lrucache as i,registerCoreTools as j}from"./chunk-TOUPOZHH.mjs";import"./chunk-PXQPLL62.mjs";export{m as EventClient,o as EventServer,r as EventToolFunc,p as _lrucache,t as createLRUCache,P as event,c as eventClient,h as eventServer,i as lrucache,j as registerCoreTools};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { EventEmitter, Event } from 'events-ex';
|
|
2
2
|
import { AdvancePropertyManager } from 'property-manager';
|
|
3
3
|
import { ICacheOptions, Cache } from 'secondary-cache';
|
|
4
|
-
import
|
|
4
|
+
import * as _isdk_common_error from '@isdk/common-error';
|
|
5
5
|
import { IncomingMessage, ServerResponse } from 'http';
|
|
6
6
|
|
|
7
7
|
declare const ToolAsyncMultiTaskBit = 0;
|
|
@@ -162,154 +162,6 @@ interface RemoteFuncItem extends BaseFuncItem {
|
|
|
162
162
|
fetchOptions?: any;
|
|
163
163
|
}
|
|
164
164
|
|
|
165
|
-
type ErrorCodeType = number | string;
|
|
166
|
-
declare enum ErrorCode {
|
|
167
|
-
OK = 200,
|
|
168
|
-
Accepted = 202,
|
|
169
|
-
BadRequest = 400,
|
|
170
|
-
InvalidArgument = 400,
|
|
171
|
-
Unauthorized = 401,
|
|
172
|
-
PaymentRequired = 402,
|
|
173
|
-
Forbidden = 403,
|
|
174
|
-
NotFound = 404,
|
|
175
|
-
MethodNotAllowed = 405,
|
|
176
|
-
NotAcceptable = 406,
|
|
177
|
-
RequestTimeout = 408,
|
|
178
|
-
Conflict = 409,
|
|
179
|
-
Corruption = 409,
|
|
180
|
-
TooManyRequests = 429,
|
|
181
|
-
Aborted = 499,
|
|
182
|
-
InternalError = 500,
|
|
183
|
-
NotImplemented = 501,
|
|
184
|
-
NotSupported = 501,
|
|
185
|
-
BadGateway = 502,
|
|
186
|
-
ServiceUnavailable = 503,// task is processing and Retry-After
|
|
187
|
-
GatewayTimeout = 504
|
|
188
|
-
}
|
|
189
|
-
declare const InternalErrorCode = ErrorCode.InternalError;
|
|
190
|
-
declare const NotImplementedErrorCode = ErrorCode.NotImplemented;
|
|
191
|
-
declare const NotFoundErrorCode = ErrorCode.NotFound;
|
|
192
|
-
declare const AlreadyExistsErrorCode = ErrorCode.Conflict;
|
|
193
|
-
declare const AbortErrorCode = ErrorCode.Aborted;
|
|
194
|
-
/**
|
|
195
|
-
* BaseError class that extends the Error class.
|
|
196
|
-
*
|
|
197
|
-
* @example
|
|
198
|
-
* // Create a custom error
|
|
199
|
-
* class CustomError extends BaseError {
|
|
200
|
-
* static code = 'customError';
|
|
201
|
-
* constructor(message: string) {
|
|
202
|
-
* super(message);
|
|
203
|
-
* }
|
|
204
|
-
* }
|
|
205
|
-
*
|
|
206
|
-
* // Throw the custom error
|
|
207
|
-
* throw new CustomError('This is a custom error');
|
|
208
|
-
*
|
|
209
|
-
* @description
|
|
210
|
-
* This class is used to create custom errors that extend the built-in Error class. It provides a way to define custom error codes and additional data associated with the error.
|
|
211
|
-
*
|
|
212
|
-
* @property {ErrorCodeType} code - The error code associated with the error.
|
|
213
|
-
* @property {string} caller - The name of the function that threw the error.
|
|
214
|
-
* @property {ErrorCodeType} code - The error code associated with the error.
|
|
215
|
-
* @property {any} data - Additional data associated with the error.
|
|
216
|
-
*
|
|
217
|
-
* @method toJSON - Returns a JSON representation of the error.
|
|
218
|
-
* @method fromJSON - Creates a new BaseError instance from a JSON representation.
|
|
219
|
-
*/
|
|
220
|
-
declare class BaseError extends AbstractError {
|
|
221
|
-
/**
|
|
222
|
-
* The error code associated with the error.
|
|
223
|
-
*/
|
|
224
|
-
static code: ErrorCodeType;
|
|
225
|
-
caller: string;
|
|
226
|
-
code: ErrorCodeType;
|
|
227
|
-
data?: any;
|
|
228
|
-
static createErrorClass(aType: string, aErrorCode?: number | string | typeof AbstractError, ParentErrorClass?: typeof BaseError): typeof BaseError;
|
|
229
|
-
/**
|
|
230
|
-
* Constructs a new BaseError instance.
|
|
231
|
-
*
|
|
232
|
-
* @param {string} message - The error message.
|
|
233
|
-
* @param {ErrorCodeType} [code] - The error code.
|
|
234
|
-
* @param {string|object} [name] - The error name or additional properties.
|
|
235
|
-
*/
|
|
236
|
-
constructor(message: string, code?: ErrorCodeType, name?: string | object);
|
|
237
|
-
/**
|
|
238
|
-
* Returns a JSON representation of the error.
|
|
239
|
-
*
|
|
240
|
-
* @returns {object} A JSON representation of the error.
|
|
241
|
-
*/
|
|
242
|
-
toJSON(): any;
|
|
243
|
-
/**
|
|
244
|
-
* Creates a new BaseError instance from a JSON representation.
|
|
245
|
-
*
|
|
246
|
-
* @param {object} json - A JSON representation of the error.
|
|
247
|
-
* @returns {BaseError} A new BaseError instance.
|
|
248
|
-
*/
|
|
249
|
-
fromJSON(json: any): BaseError;
|
|
250
|
-
}
|
|
251
|
-
declare class CommonError extends BaseError {
|
|
252
|
-
constructor(message: string, name?: string | Record<string, any>, status?: ErrorCodeType);
|
|
253
|
-
}
|
|
254
|
-
/**
|
|
255
|
-
* Represents an error when a function or method is not implemented.
|
|
256
|
-
* Inherits from BaseError.
|
|
257
|
-
*
|
|
258
|
-
* @example
|
|
259
|
-
* throw new NotImplementationError()
|
|
260
|
-
*
|
|
261
|
-
* @extends CommonError
|
|
262
|
-
*/
|
|
263
|
-
declare class NotImplementationError extends CommonError {
|
|
264
|
-
constructor(msg?: string, name?: string | Record<string, any>);
|
|
265
|
-
}
|
|
266
|
-
/**
|
|
267
|
-
* Represents an error when a requested resource is not found.
|
|
268
|
-
* Inherits from BaseError.
|
|
269
|
-
*
|
|
270
|
-
* @example
|
|
271
|
-
* throw new NotFoundError('user', { id: 123 })
|
|
272
|
-
*
|
|
273
|
-
* @extends CommonError
|
|
274
|
-
*/
|
|
275
|
-
declare class NotFoundError extends CommonError {
|
|
276
|
-
static code: ErrorCode;
|
|
277
|
-
constructor(what: string | number, name?: string | Record<string, any>);
|
|
278
|
-
}
|
|
279
|
-
/**
|
|
280
|
-
* Represents an error when a requested resource already exists.
|
|
281
|
-
* Inherits from BaseError.
|
|
282
|
-
*
|
|
283
|
-
* @example
|
|
284
|
-
* throw new AlreadyExistsError('user', { id: 123 })
|
|
285
|
-
*
|
|
286
|
-
* @extends CommonError
|
|
287
|
-
*/
|
|
288
|
-
declare class AlreadyExistsError extends CommonError {
|
|
289
|
-
static code: ErrorCode;
|
|
290
|
-
constructor(what: string | number, name?: string | Record<string, any>);
|
|
291
|
-
}
|
|
292
|
-
declare class AbortError extends CommonError {
|
|
293
|
-
static code: ErrorCode;
|
|
294
|
-
constructor(what?: string, name?: string | Record<string, any>);
|
|
295
|
-
}
|
|
296
|
-
/**
|
|
297
|
-
* Create an error object
|
|
298
|
-
* @param message - Error message
|
|
299
|
-
* @param name - Error name, optional
|
|
300
|
-
* @param status - Error status code, default to 500
|
|
301
|
-
* @returns Error object
|
|
302
|
-
*/
|
|
303
|
-
declare function createError(message: string, name?: string | Record<string, any>, status?: ErrorCode | ErrorCodeType): CommonError;
|
|
304
|
-
/**
|
|
305
|
-
* Throw an error
|
|
306
|
-
* @param message - Error message
|
|
307
|
-
* @param name - Error name, optional
|
|
308
|
-
* @param status - Error status code, default to 500
|
|
309
|
-
* @throws {BaseError} Throws a BaseError object
|
|
310
|
-
*/
|
|
311
|
-
declare function throwError(message: string, name?: string | Record<string, any>, status?: ErrorCode | ErrorCodeType): void;
|
|
312
|
-
|
|
313
165
|
type Events = (string | RegExp)[];
|
|
314
166
|
type Client = {
|
|
315
167
|
req: IncomingMessage;
|
|
@@ -391,7 +243,7 @@ declare class ClientTools extends ToolFunc {
|
|
|
391
243
|
static fetch(name: string, objParam?: any): Promise<any>;
|
|
392
244
|
getUrlParams(objParam: any): string;
|
|
393
245
|
fetch(objParam?: any, act?: ActionName, subName?: any): Promise<Response>;
|
|
394
|
-
errorFrom(res: Response): Promise<CommonError>;
|
|
246
|
+
errorFrom(res: Response): Promise<_isdk_common_error.CommonError>;
|
|
395
247
|
func(objParam: any): Promise<any>;
|
|
396
248
|
}
|
|
397
249
|
declare const ClientToolFuncSchema: {
|
|
@@ -402,7 +254,7 @@ declare const ClientToolFuncSchema: {
|
|
|
402
254
|
};
|
|
403
255
|
action: {
|
|
404
256
|
type: string;
|
|
405
|
-
assign(value:
|
|
257
|
+
assign(value: ActionName, dest: any, src?: any, name?: string, options?: any): "get" | "post" | "put" | "delete" | "patch" | "list" | "res";
|
|
406
258
|
};
|
|
407
259
|
fetchOptions: {
|
|
408
260
|
type: string;
|
|
@@ -443,7 +295,7 @@ declare const ServerToolFuncSchema: {
|
|
|
443
295
|
};
|
|
444
296
|
action: {
|
|
445
297
|
type: string;
|
|
446
|
-
assign(value:
|
|
298
|
+
assign(value: ActionName, dest: any, src?: any, name?: string, options?: any): "get" | "post" | "put" | "delete" | "patch" | "list" | "res";
|
|
447
299
|
};
|
|
448
300
|
fetchOptions: {
|
|
449
301
|
type: string;
|
|
@@ -626,4 +478,4 @@ declare const eventServer: EventServer;
|
|
|
626
478
|
|
|
627
479
|
declare function registerCoreTools(): void;
|
|
628
480
|
|
|
629
|
-
export {
|
|
481
|
+
export { AsyncFeatures as A, type BaseFuncItem as B, type ClientFuncItem as C, event as D, EventToolFunc as E, type FuncParamType as F, createLRUCache as G, lrucache as H, type EventClientFuncParams as I, EventClient as J, eventClient as K, type EventServerFuncParams as L, EventServer as M, eventServer as N, type ResClientFuncParams as O, PASSING_SCORE as P, ResClientTools as Q, RemoteToolFuncSchema as R, SSEChannelAlreadyClosedErrCode as S, ToolFunc as T, type ResServerFuncParams as U, ResServerTools as V, _lrucache as _, type AIModelNameRules as a, ActionNames as b, type ActionName as c, type AIModelNameRuleFn as d, type AIModelNameRule as e, type RemoteFuncItem as f, SSEChannel as g, ToolAsyncMultiTaskBit as h, ToolAsyncCancelableBit as i, ToolAsyncPriorityBit as j, AsyncFeatureBits as k, type FuncParam as l, type FuncParams as m, type TFunc as n, type FuncItem as o, type BaseFunc as p, type Funcs as q, type ToolFuncPackage as r, ToolFuncSchema as s, ClientTools as t, ClientToolFuncSchema as u, type ServerFuncParams as v, type ServerFuncItem as w, ServerTools as x, ServerToolFuncSchema as y, registerCoreTools as z };
|