@isdk/ai-tool 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/dist/chunk-FLVJ4R53.mjs +1 -0
  2. package/dist/funcs.js +1 -1
  3. package/dist/funcs.mjs +1 -1
  4. package/dist/index.d.mts +35 -3
  5. package/dist/index.d.ts +35 -3
  6. package/dist/index.js +1 -1
  7. package/dist/index.mjs +1 -1
  8. package/docs/classes/CancelableAbility.md +20 -20
  9. package/docs/classes/ClientTools.md +54 -54
  10. package/docs/classes/EventClient.md +76 -76
  11. package/docs/classes/EventServer.md +78 -78
  12. package/docs/classes/EventToolFunc.md +46 -46
  13. package/docs/classes/FStringPromptTemplate.md +18 -18
  14. package/docs/classes/FewShotPromptTemplate.md +22 -22
  15. package/docs/classes/GolangPromptTemplate.md +18 -18
  16. package/docs/classes/HFEnvironment.md +9 -9
  17. package/docs/classes/HFInterpreter.md +4 -4
  18. package/docs/classes/HFTemplate.md +4 -4
  19. package/docs/classes/HfPromptTemplate.md +18 -18
  20. package/docs/classes/IntSet.md +11 -11
  21. package/docs/classes/PromptExampleSelector.md +8 -8
  22. package/docs/classes/PromptTemplate.md +17 -17
  23. package/docs/classes/ReadableStreamError.md +1 -1
  24. package/docs/classes/ResClientTools.md +61 -61
  25. package/docs/classes/ResServerTools.md +62 -62
  26. package/docs/classes/SSEChannel.md +14 -14
  27. package/docs/classes/Semaphore.md +8 -8
  28. package/docs/classes/ServerTools.md +50 -50
  29. package/docs/classes/TaskAbortController.md +7 -7
  30. package/docs/classes/ToolFunc.md +43 -43
  31. package/docs/enumerations/AsyncFeatureBits.md +3 -3
  32. package/docs/enumerations/AsyncFeatures.md +3 -3
  33. package/docs/enumerations/XXHashAlgorithm.md +2 -2
  34. package/docs/functions/AIArgProcessor.md +1 -1
  35. package/docs/functions/AIStream.md +1 -1
  36. package/docs/functions/ChoiceArgProcessor.md +1 -1
  37. package/docs/functions/RateLimit.md +1 -1
  38. package/docs/functions/TemplateArgProcessor.md +1 -1
  39. package/docs/functions/backendEventable.md +1 -1
  40. package/docs/functions/countRegexMatches.md +1 -1
  41. package/docs/functions/createCallbacksTransformer.md +1 -1
  42. package/docs/functions/createEmptyReadableStream.md +1 -1
  43. package/docs/functions/createEndWithRepetitionDetector.md +1 -1
  44. package/docs/functions/createEventStreamTransformer.md +1 -1
  45. package/docs/functions/createHfValueFunc.md +1 -1
  46. package/docs/functions/createLRUCache.md +1 -1
  47. package/docs/functions/dateToText.md +1 -1
  48. package/docs/functions/expandEnv.md +1 -1
  49. package/docs/functions/expandObjEnv.md +1 -1
  50. package/docs/functions/extNameLevel.md +1 -1
  51. package/docs/functions/fileIsExists.md +1 -1
  52. package/docs/functions/filenameReservedRegex.md +1 -1
  53. package/docs/functions/filterValidFnScope.md +1 -1
  54. package/docs/functions/findPort.md +1 -1
  55. package/docs/functions/getAllEnumKeys.md +1 -1
  56. package/docs/functions/getConfigFileNames.md +1 -1
  57. package/docs/functions/getConfigs.md +1 -1
  58. package/docs/functions/getKeysPath.md +1 -1
  59. package/docs/functions/getMultiLevelExtname.md +1 -1
  60. package/docs/functions/getPackageDir.md +1 -1
  61. package/docs/functions/getRealFilepath.md +1 -1
  62. package/docs/functions/getResponseErrorReadableStream.md +1 -1
  63. package/docs/functions/hasDirectoryIn.md +38 -0
  64. package/docs/functions/hfParse.md +1 -1
  65. package/docs/functions/hfTokenize.md +1 -1
  66. package/docs/functions/interpolateEnv.md +1 -1
  67. package/docs/functions/interpolateFString.md +1 -1
  68. package/docs/functions/interpolateGolangTemplate.md +1 -1
  69. package/docs/functions/isModelNameMatched.md +1 -1
  70. package/docs/functions/isRegExp.md +21 -0
  71. package/docs/functions/isSubdirectory.md +39 -0
  72. package/docs/functions/isValidFilename.md +1 -1
  73. package/docs/functions/isValidFilepath.md +1 -1
  74. package/docs/functions/isWebStream.md +1 -1
  75. package/docs/functions/jsonFilterToWhere.md +1 -1
  76. package/docs/functions/jsonToMarkdownStr.md +1 -1
  77. package/docs/functions/loadFileFromPaths.md +1 -1
  78. package/docs/functions/loadTextFromPaths.md +1 -1
  79. package/docs/functions/lrucache.md +1 -1
  80. package/docs/functions/makeToolFuncCancelable.md +1 -1
  81. package/docs/functions/matchUrlProtocol.md +1 -1
  82. package/docs/functions/memoize.md +1 -1
  83. package/docs/functions/messagesToText.md +1 -1
  84. package/docs/functions/paramsSizeToScaleStr.md +1 -1
  85. package/docs/functions/parseCommand.md +1 -1
  86. package/docs/functions/parseFString.md +1 -1
  87. package/docs/functions/parseJsJson.md +1 -1
  88. package/docs/functions/parseObjectArgInfo.md +1 -1
  89. package/docs/functions/parseObjectArgumentInfos.md +1 -1
  90. package/docs/functions/parseObjectArguments.md +1 -1
  91. package/docs/functions/parseObjectArgumentsAsArgInfos.md +1 -1
  92. package/docs/functions/parseYaml.md +1 -1
  93. package/docs/functions/quoteStr.md +1 -1
  94. package/docs/functions/reControlCharsRegex.md +1 -1
  95. package/docs/functions/readFilenamesRecursiveSync.md +1 -1
  96. package/docs/functions/readableFromAsyncIterable.md +1 -1
  97. package/docs/functions/registerCoreTools.md +1 -1
  98. package/docs/functions/registerYamlTag.md +1 -1
  99. package/docs/functions/sanitizeFilename.md +1 -1
  100. package/docs/functions/sanitizeFilepath.md +1 -1
  101. package/docs/functions/saveConfigFile.md +1 -1
  102. package/docs/functions/scaleStrToParamsSize.md +1 -1
  103. package/docs/functions/simplifyObjectArguments.md +1 -1
  104. package/docs/functions/sortedValues.md +1 -1
  105. package/docs/functions/splitSentence.md +1 -1
  106. package/docs/functions/stringifyYaml.md +6 -34
  107. package/docs/functions/textToDate.md +1 -1
  108. package/docs/functions/toDateTime.md +1 -1
  109. package/docs/functions/toRegExp.md +34 -0
  110. package/docs/functions/trimStartOfStreamHelper.md +1 -1
  111. package/docs/functions/truncTo.md +1 -1
  112. package/docs/functions/uuid.md +1 -1
  113. package/docs/functions/wait.md +1 -1
  114. package/docs/functions/xxhash.md +1 -1
  115. package/docs/functions/xxhash32.md +1 -1
  116. package/docs/functions/xxhash64.md +1 -1
  117. package/docs/functions/xxhashAsStr.md +1 -1
  118. package/docs/globals.md +4 -0
  119. package/docs/interfaces/AIChatAssistantMessageParam.md +6 -6
  120. package/docs/interfaces/AIChatContentPartImage.md +2 -2
  121. package/docs/interfaces/AIChatContentPartText.md +2 -2
  122. package/docs/interfaces/AIChatMessageParamBase.md +1 -1
  123. package/docs/interfaces/AIChatMessageToolCall.md +3 -3
  124. package/docs/interfaces/AIChatSystemMessageParam.md +3 -3
  125. package/docs/interfaces/AIChatToolMessageParam.md +4 -4
  126. package/docs/interfaces/AIChatUserMessageParam.md +7 -7
  127. package/docs/interfaces/AIChoiceConfig.md +7 -7
  128. package/docs/interfaces/AIResult.md +10 -6
  129. package/docs/interfaces/AIStreamParser.md +1 -1
  130. package/docs/interfaces/AIStreamParserOptions.md +1 -1
  131. package/docs/interfaces/BaseFunc.md +9 -9
  132. package/docs/interfaces/BaseFuncItem.md +8 -8
  133. package/docs/interfaces/CancelableAbilityOptions.md +2 -2
  134. package/docs/interfaces/ClientFuncItem.md +11 -11
  135. package/docs/interfaces/DotenvExpandOptions.md +3 -3
  136. package/docs/interfaces/DotenvExpandOutput.md +2 -2
  137. package/docs/interfaces/EventClientFuncParams.md +4 -4
  138. package/docs/interfaces/EventServerFuncParams.md +5 -5
  139. package/docs/interfaces/FewShotPromptTemplateOptions.md +11 -11
  140. package/docs/interfaces/FuncItem.md +9 -9
  141. package/docs/interfaces/FuncParam.md +6 -6
  142. package/docs/interfaces/ParseObjectArgumentOptions.md +5 -5
  143. package/docs/interfaces/PromptExampleSelectorOptions.md +2 -2
  144. package/docs/interfaces/PromptTemplateOptions.md +6 -6
  145. package/docs/interfaces/RemoteFuncItem.md +11 -11
  146. package/docs/interfaces/ResClientFuncParams.md +2 -2
  147. package/docs/interfaces/ResServerFuncParams.md +5 -5
  148. package/docs/interfaces/SanitizeFilenameOptions.md +2 -2
  149. package/docs/interfaces/ServerFuncItem.md +12 -12
  150. package/docs/interfaces/ServerFuncParams.md +2 -2
  151. package/docs/interfaces/StreamCallbacksAndOptions.md +4 -4
  152. package/docs/interfaces/TaskPromise.md +1 -1
  153. package/docs/interfaces/ToolFuncPackage.md +3 -3
  154. package/docs/type-aliases/AIChatContentPart.md +1 -1
  155. package/docs/type-aliases/AIChatMessageParam.md +1 -1
  156. package/docs/type-aliases/AIChatRole.md +1 -1
  157. package/docs/type-aliases/AIMessageType.md +1 -1
  158. package/docs/type-aliases/AIModelNameRule.md +1 -1
  159. package/docs/type-aliases/AIModelNameRuleFn.md +1 -1
  160. package/docs/type-aliases/AIModelNameRules.md +1 -1
  161. package/docs/type-aliases/AITextGenerationFinishReason.md +1 -1
  162. package/docs/type-aliases/ActionName.md +1 -1
  163. package/docs/type-aliases/AsyncTaskId.md +1 -1
  164. package/docs/type-aliases/EventErrorListenerFn.md +1 -1
  165. package/docs/type-aliases/EventListenerFn.md +1 -1
  166. package/docs/type-aliases/FStringPromptTemplateNode.md +1 -1
  167. package/docs/type-aliases/FuncParamType.md +1 -1
  168. package/docs/type-aliases/PromptExamples.md +1 -1
  169. package/docs/type-aliases/PromptTemplateType.md +1 -1
  170. package/docs/type-aliases/PromptType.md +1 -1
  171. package/docs/type-aliases/TFunc.md +1 -1
  172. package/docs/variables/AIChatRoles.md +1 -1
  173. package/docs/variables/AIMessageTypes.md +1 -1
  174. package/docs/variables/AITextGenerationFinishReasons.md +2 -2
  175. package/docs/variables/ActionNames.md +1 -1
  176. package/docs/variables/ClientToolFuncSchema.md +1 -1
  177. package/docs/variables/DefaultAsyncSemaphoreCapacity.md +1 -1
  178. package/docs/variables/EventBusName.md +1 -1
  179. package/docs/variables/EventName.md +1 -1
  180. package/docs/variables/FilenameReservedRegex.md +1 -1
  181. package/docs/variables/HFBuiltins.md +1 -1
  182. package/docs/variables/PASSING_SCORE.md +1 -1
  183. package/docs/variables/PromptTemplateTypes.md +1 -1
  184. package/docs/variables/PromptTypes.md +1 -1
  185. package/docs/variables/RStreamErrCode.md +1 -1
  186. package/docs/variables/RemoteToolFuncSchema.md +1 -1
  187. package/docs/variables/ResponseRStreamErrCode.md +1 -1
  188. package/docs/variables/SSEChannelAlreadyClosedErrCode.md +1 -1
  189. package/docs/variables/ServerToolFuncSchema.md +1 -1
  190. package/docs/variables/ToolAsyncCancelableBit.md +1 -1
  191. package/docs/variables/ToolAsyncMultiTaskBit.md +1 -1
  192. package/docs/variables/ToolAsyncPriorityBit.md +1 -1
  193. package/docs/variables/ToolFuncSchema.md +1 -1
  194. package/docs/variables/WindowsReservedNameRegex.md +1 -1
  195. package/docs/variables/base32768.md +1 -1
  196. package/docs/variables/defaultTemplateFormat.md +1 -1
  197. package/docs/variables/event.md +1 -1
  198. package/docs/variables/eventClient.md +1 -1
  199. package/docs/variables/eventServer.md +1 -1
  200. package/docs/variables/lrucache.md +1 -1
  201. package/package.json +1 -1
  202. package/dist/chunk-TOUPOZHH.mjs +0 -1
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var t,e=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,i=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,a=(t,e,i,a)=>{if(e&&"object"==typeof e||"function"==typeof e)for(let c of s(e))o.call(t,c)||c===i||n(t,c,{get:()=>e[c],enumerable:!(a=r(e,c))||a.enumerable});return t},c=(t,r,s)=>(s=null!=t?e(i(t)):{},a(!r&&t&&t.__esModule?s:n(s,"default",{value:t,enumerable:!0}),t)),u={};((t,e)=>{for(var r in e)n(t,r,{get:e[r],enumerable:!0})})(u,{AIArgProcessor:()=>jr,AIChatRoles:()=>$,AIMessageTypes:()=>x,AIStream:()=>Ae,AITextGenerationFinishReasons:()=>E,AbortError:()=>w.AbortError,AbortErrorCode:()=>w.AbortErrorCode,ActionNames:()=>h,AlreadyExistsError:()=>w.AlreadyExistsError,AlreadyExistsErrorCode:()=>w.AlreadyExistsErrorCode,AsyncFeatureBits:()=>pr,AsyncFeatures:()=>wr,BaseError:()=>w.BaseError,CancelableAbility:()=>gr,ChoiceArgProcessor:()=>Or,ClientToolFuncSchema:()=>Zr,ClientTools:()=>Hr,CommonError:()=>w.CommonError,ConfigFile:()=>Cn.Config,DefaultAsyncSemaphoreCapacity:()=>Yn,ErrorCode:()=>w.ErrorCode,EventBusName:()=>he,EventClient:()=>cs,EventName:()=>fe,EventServer:()=>ws,EventToolFunc:()=>Qr,FStringPromptTemplate:()=>zt,FewShotPromptTemplate:()=>Ht,FilenameReservedRegex:()=>Ke,GolangPromptTemplate:()=>Wt,HFBuiltins:()=>Nt,HFEnvironment:()=>It,HFInterpreter:()=>Ot,HFTemplate:()=>Mt,HfPromptTemplate:()=>Vt,IntSet:()=>Gn,InternalErrorCode:()=>w.InternalErrorCode,NotFoundError:()=>w.NotFoundError,NotFoundErrorCode:()=>w.NotFoundErrorCode,NotImplementationError:()=>w.NotImplementationError,NotImplementedErrorCode:()=>w.NotImplementedErrorCode,PASSING_SCORE:()=>f,PromptExampleSelector:()=>F,PromptTemplate:()=>j,PromptTemplateTypes:()=>A,PromptTypes:()=>k,RStreamErrCode:()=>be,RateLimit:()=>ir,ReadableStreamError:()=>ve,RemoteToolFuncSchema:()=>p,ResClientTools:()=>as,ResServerTools:()=>hs,ResponseRStreamErrCode:()=>ge,SSEChannel:()=>me,SSEChannelAlreadyClosedErrCode:()=>de,Semaphore:()=>sr,ServerToolFuncSchema:()=>Xr,ServerTools:()=>Gr,TaskAbortController:()=>br,TemplateArgProcessor:()=>Tr,ToolAsyncCancelableBit:()=>fr,ToolAsyncMultiTaskBit:()=>lr,ToolAsyncPriorityBit:()=>hr,ToolFunc:()=>dr,ToolFuncSchema:()=>mr,WindowsReservedNameRegex:()=>He,XXHashAlgorithm:()=>ze,_lrucache:()=>ns,backendEventable:()=>pe,base32768:()=>qe,canonicalize:()=>Re.canonicalize,countRegexMatches:()=>Er,createAbilityInjector:()=>l.createAbilityInjector,createCallbacksTransformer:()=>Te,createEmptyReadableStream:()=>xe,createEndWithRepetitionDetector:()=>gn,createError:()=>w.createError,createEventStreamTransformer:()=>Se,createHfValueFunc:()=>Bt,createLRUCache:()=>rs,dateToText:()=>v,defaultTemplateFormat:()=>T,event:()=>ts,eventClient:()=>us,eventServer:()=>ds,expandEnv:()=>Yt,expandObjEnv:()=>Qt,extNameLevel:()=>an,fileIsExists:()=>xn,filenameReservedRegex:()=>Qe,filterValidFnScope:()=>mn,findPort:()=>Dr,formatISO:()=>m.formatISO,getAllEnumKeys:()=>ln,getConfigFileNames:()=>Vn,getConfigs:()=>Bn,getKeysPath:()=>yn,getMultiLevelExtname:()=>on,getPackageDir:()=>Kr,getRealFilepath:()=>On,getResponseErrorReadableStream:()=>Ee,hfParse:()=>ft,hfTokenize:()=>U,interpolateEnv:()=>Xt,interpolateFString:()=>_t,interpolateGolangTemplate:()=>Jt,isModelNameMatched:()=>un,isValidFilename:()=>en,isValidFilepath:()=>nn,isWebStream:()=>ye,jsonFilterToWhere:()=>Jn,jsonToMarkdownStr:()=>Zn,loadFileFromPaths:()=>$n,loadTextFromPaths:()=>kn,lrucache:()=>ss,makeToolFuncCancelable:()=>vr,matchUrlProtocol:()=>Wn,memoize:()=>Lr,messagesToText:()=>S,mimeType:()=>In.mimeType,paramsSizeToScaleStr:()=>Kn,parseCommand:()=>qr,parseDateFormat:()=>d.parse,parseFString:()=>Ut,parseISO:()=>m.parseISO,parseJsJson:()=>pn,parseObjectArgInfo:()=>Pr,parseObjectArgumentInfos:()=>Ar,parseObjectArguments:()=>Sr,parseObjectArgumentsAsArgInfos:()=>Rr,parseYaml:()=>qn,quoteStr:()=>Nr,reControlCharsRegex:()=>tn,readFilenamesRecursiveSync:()=>An,readableFromAsyncIterable:()=>Oe,registerCoreTools:()=>ms,registerYamlTag:()=>Rn,sanitizeFilename:()=>rn,sanitizeFilepath:()=>sn,saveConfigFile:()=>Un,scaleStrToParamsSize:()=>Hn,simplifyObjectArguments:()=>kr,sortedValues:()=>Kt,splitSentence:()=>ae,stringifyYaml:()=>Mn.stringify,textToDate:()=>g,throwError:()=>w.throwError,toDate:()=>m.toDate,toDateTime:()=>b,trimStartOfStreamHelper:()=>ke,truncTo:()=>ce,uuid:()=>Ie,uuidNIL:()=>Ne.NIL,uuidParse:()=>Ne.parse,uuidStringify:()=>Ne.stringify,uuidValidate:()=>Ne.validate,uuidVersion:()=>Ne.version,uuidv1:()=>Ne.v1,uuidv4:()=>Ne.v4,uuidv5:()=>Ne.v5,wait:()=>ue,xxhash:()=>De,xxhash32:()=>_e,xxhash64:()=>Le,xxhashAsStr:()=>Je}),module.exports=(t=u,a(n({},"__esModule",{value:!0}),t));var l=require("custom-ability"),f=.618,h=["get","post","put","delete","patch","list","res"],p={apiRoot:{type:"string",get(){return this._apiRoot??this.constructor.apiRoot},set(t){this._apiRoot=t}},action:{type:"string",assign:(t,e,n,r,s)=>t||"post"},fetchOptions:{type:"object"},allowExportFunc:{type:"boolean"}},w=require("@isdk/common-error"),d=require("date-fns"),m=require("date-fns"),y="MMMM d, y 'at' h:m:s b 'GMT'x";function b(t){let e;try{"string"==typeof t?e=(0,d.parseISO)(t):"number"==typeof t?e=new Date(t):t instanceof Date&&(e=t)}catch(t){console.error(t)}return e}function g(t,e=y){return(0,d.parse)(t,e,new Date)}function v(t,e=y){return(0,d.format)(t,e)}var E=["stop","length","content-filter","tool-calls","abort","error","other",null],x=["human","ai","generic","system","tool"],$=["user","assistant","system","tool","tool_calls"];function S(t){let e="";for(const n of t)if(n.content){e+=n.role.toLowerCase()+":";let t=n.createdAt;if(t){const n=b(t);n&&(e+=" ["+v(n)+"]")}e+=" "+n.content+"\n"}return e}var k=["chat","char","plan"],A=["internal","hf","fill"],O=require("custom-factory");var T="default",j=class t extends O.BaseFactory{static from(t,e){return new this(t,e)}static async format(t){return new this(t).format()}static async formatIf(t){if(this.isTemplate(t)){return new this(t).format()}}static isTemplate(e){if(e?.template){const n=e.templateFormat||T,r=t.get(n);return r.isTemplate!==t.isTemplate&&r.isTemplate(e)}}filterData(t){return Array.isArray(this.inputVariables)&&(t=Object.fromEntries(Object.entries(t).filter((([t])=>this.inputVariables.includes(t))))),t}constructor(e,n){"string"==typeof e?(n||(n={}),n.template=e):e&&(e=(n=e).template);const{templateFormat:r}=n||{};if(super(n),this.constructor===t){const e=t.get(r||T);if(e)return Reflect.construct(e,arguments);throw new w.CommonError(`Prompt template type ${r} 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 n=this.data;if(e={...n,...e},n)for(const[t,r]of Object.entries(n))e[t]===r&&"function"==typeof r&&(delete e[t],e[t]=await r(e));for(const[n,r]of Object.entries(e))r instanceof t&&(delete e[n],e[n]=await r.format(e));return this._format(e)}partial(t){t={...this.data,...t};const e=this.toJSON();return e.data=t,e.ignoreInitialize=!0,new this.constructor(e)}toJSON(e=this){let n={template:e.template,data:e.data,inputVariables:e.inputVariables,compiledTemplate:e.compiledTemplate};var r;return e.templateFormat&&t.get(e.templateFormat)!==this.constructor&&(n.templateFormat=e.templateFormat),r=n,n=Object.keys(r).reduce(((t,e)=>{const n=r[e];return null!=n&&(t[e]=n),t}),{}),n}};function C(t){return(e=t)&&"function"==typeof e[Symbol.iterator]?async function*(t){const e=t[Symbol.iterator]();let n;try{for(;;){n=!1;const t=e.next();if(n=!0,t.done)return n=!1,await t.value;yield await t.value}}finally{n&&await(e.return?.().value)}}(t):t;var e}var N=!1;(async function(){let t=!1,e=!1;try{for await(const e of function*(){try{yield Promise.reject()}finally{t=!0}}())throw new Error("impossible")}catch{e=!0}return e&&t})().then((t=>{N=t}));var F=class{constructor(t,e){this.initialize(t,e)}initialize(t,e){const n=e?.maxLength;var r;n>0&&(this.maxLength=n),void 0!==e?.threshold&&(!0===e.threshold?this.threshold=.5:!1!==e.threshold&&(this.threshold=e.threshold)),this.examples=(r=t,N?r:C(r))}selectExample(t,e){if(void 0===e||e<=this.threshold)return t}async*selectExamples(t=this.examples){let e=this.maxLength||1/0;for await(const n of t){const t="number"==typeof this.threshold?Math.random():void 0;if(this.selectExample(n,t)){if(--e<0)break;yield n}}}async*[Symbol.asyncIterator](){yield*this.selectExamples()}},I=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"}),M=Object.freeze({set:I.Set,for:I.For,in:I.In,is:I.Is,if:I.If,else:I.Else,endif:I.EndIf,elif:I.ElseIf,endfor:I.EndFor,and:I.And,or:I.Or,not:I.Not,"not in":I.NotIn,macro:I.Macro,endmacro:I.EndMacro,true:I.BooleanLiteral,false:I.BooleanLiteral,True:I.BooleanLiteral,False:I.BooleanLiteral}),P=class{constructor(t,e){this.value=t,this.type=e}};function R(t){return/\w/.test(t)}function q(t){return/[0-9]/.test(t)}var V=[["{%",I.OpenStatement],["%}",I.CloseStatement],["{{",I.OpenExpression],["}}",I.CloseExpression],["(",I.OpenParen],[")",I.CloseParen],["{",I.OpenCurlyBracket],["}",I.CloseCurlyBracket],["[",I.OpenSquareBracket],["]",I.CloseSquareBracket],[",",I.Comma],[".",I.Dot],[":",I.Colon],["|",I.Pipe],["<=",I.ComparisonBinaryOperator],[">=",I.ComparisonBinaryOperator],["==",I.ComparisonBinaryOperator],["!=",I.ComparisonBinaryOperator],["<",I.ComparisonBinaryOperator],[">",I.ComparisonBinaryOperator],["+",I.AdditiveBinaryOperator],["-",I.AdditiveBinaryOperator],["*",I.MultiplicativeBinaryOperator],["/",I.MultiplicativeBinaryOperator],["%",I.MultiplicativeBinaryOperator],["=",I.Equals]],B=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function U(t,e={}){const n=[],r=function(t,e={}){return t.endsWith("\n")&&(t=t.slice(0,-1)),t=t.replace(/{#.*?#}/gs,"{##}"),e.lstrip_blocks&&(t=t.replace(/^[ \t]*({[#%])/gm,"$1")),e.trim_blocks&&(t=t.replace(/([#%]})\n/g,"$1")),t.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}(t,e);let s=0;const i=t=>{let e="";for(;t(r[s]);)if("\\"!==r[s]){if(e+=r[s++],s>=r.length)throw new SyntaxError("Unexpected end of input")}else{if(++s,s>=r.length)throw new SyntaxError("Unexpected end of input");const t=r[s++],n=B.get(t);if(void 0===n)throw new SyntaxError(`Unexpected escaped character: ${t}`);e+=n}return e};t:for(;s<r.length;){const t=n.at(-1)?.type;if(void 0===t||t===I.CloseStatement||t===I.CloseExpression){let t="";for(;s<r.length&&("{"!==r[s]||"%"!==r[s+1]&&"{"!==r[s+1]);)t+=r[s++];if(t.length>0){n.push(new P(t,I.Text));continue}}i((t=>/\s/.test(t)));const e=r[s];if("-"===e||"+"===e){const t=n.at(-1)?.type;if(t===I.Text||void 0===t)throw new SyntaxError(`Unexpected character: ${e}`);switch(t){case I.Identifier:case I.NumericLiteral:case I.BooleanLiteral:case I.StringLiteral:case I.CloseParen:case I.CloseSquareBracket:break;default:{++s;const t=i(q);n.push(new P(`${e}${t}`,t.length>0?I.NumericLiteral:I.UnaryOperator));continue}}}for(const[t,e]of V){if(r.slice(s,s+t.length)===t){n.push(new P(t,e)),s+=t.length;continue t}}if("'"!==e&&'"'!==e)if(q(e)){const t=i(q);n.push(new P(t,I.NumericLiteral))}else{if(!R(e))throw new SyntaxError(`Unexpected character: ${e}`);{const t=i(R),e=Object.hasOwn(M,t)?M[t]:I.Identifier;e===I.In&&n.at(-1)?.type===I.Not?(n.pop(),n.push(new P("not in",I.NotIn))):n.push(new P(t,e))}}else{++s;const t=i((t=>t!==e));n.push(new P(t,I.StringLiteral)),++s}}return n}var _=class{constructor(){this.type="Statement"}},L=class extends _{constructor(t){super(),this.body=t,this.type="Program"}},z=class extends _{constructor(t,e,n){super(),this.test=t,this.body=e,this.alternate=n,this.type="If"}},D=class extends _{constructor(t,e,n,r){super(),this.loopvar=t,this.iterable=e,this.body=n,this.defaultBlock=r,this.type="For"}},J=class extends _{constructor(t,e){super(),this.assignee=t,this.value=e,this.type="Set"}},W=class extends _{constructor(t,e,n){super(),this.name=t,this.args=e,this.body=n,this.type="Macro"}},K=class extends _{constructor(){super(...arguments),this.type="Expression"}},H=class extends K{constructor(t,e,n){super(),this.object=t,this.property=e,this.computed=n,this.type="MemberExpression"}},Z=class extends K{constructor(t,e){super(),this.callee=t,this.args=e,this.type="CallExpression"}},G=class extends K{constructor(t){super(),this.value=t,this.type="Identifier"}},X=class extends K{constructor(t){super(),this.value=t,this.type="Literal"}},Y=class extends X{constructor(){super(...arguments),this.type="NumericLiteral"}},Q=class extends X{constructor(){super(...arguments),this.type="StringLiteral"}},tt=class extends X{constructor(){super(...arguments),this.type="BooleanLiteral"}},et=class extends X{constructor(){super(...arguments),this.type="ArrayLiteral"}},nt=class extends X{constructor(){super(...arguments),this.type="TupleLiteral"}},rt=class extends X{constructor(){super(...arguments),this.type="ObjectLiteral"}},st=class extends K{constructor(t,e,n){super(),this.operator=t,this.left=e,this.right=n,this.type="BinaryExpression"}},it=class extends K{constructor(t,e){super(),this.operand=t,this.filter=e,this.type="FilterExpression"}},ot=class extends K{constructor(t,e){super(),this.iterable=t,this.test=e,this.type="SelectExpression"}},at=class extends K{constructor(t,e,n){super(),this.operand=t,this.negate=e,this.test=n,this.type="TestExpression"}},ct=class extends K{constructor(t,e){super(),this.operator=t,this.argument=e,this.type="UnaryExpression"}},ut=class extends K{constructor(t=void 0,e=void 0,n=void 0){super(),this.start=t,this.stop=e,this.step=n,this.type="SliceExpression"}},lt=class extends K{constructor(t,e){super(),this.key=t,this.value=e,this.type="KeywordArgumentExpression"}};function ft(t){const e=new L([]);let n=0;function r(e,r){const s=t[n++];if(!s||s.type!==e)throw new Error(`Parser Error: ${r}. ${s.type} !== ${e}.`);return s}function s(){let e;switch(t[n].type){case I.Text:e=new Q(r(I.Text,"Expected text token").value);break;case I.OpenStatement:e=function(){let e;switch(r(I.OpenStatement,"Expected opening statement token"),t[n].type){case I.Set:++n,e=a(),r(I.CloseStatement,"Expected closing statement token");break;case I.If:++n,e=c(),r(I.OpenStatement,"Expected {% token"),r(I.EndIf,"Expected endif token"),r(I.CloseStatement,"Expected %} token");break;case I.Macro:++n,e=function(){const t=E();if("Identifier"!==t.type)throw new SyntaxError("Expected identifier following macro statement");const e=y();r(I.CloseStatement,"Expected closing statement token");const n=[];for(;i(I.OpenStatement,I.EndMacro);)n.push(s());return new W(t,e,n)}(),r(I.OpenStatement,"Expected {% token"),r(I.EndMacro,"Expected endmacro token"),r(I.CloseStatement,"Expected %} token");break;case I.For:++n,e=function(){const t=u(!0);if(!(t instanceof G||t instanceof nt))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${t.type} instead`);r(I.In,"Expected `in` keyword following loop variable");const e=l();r(I.CloseStatement,"Expected closing statement token");const a=[];for(;i(I.OpenStatement,I.EndFor)&&i(I.OpenStatement,I.Else);)a.push(s());const c=[];if(o(I.OpenStatement,I.Else))for(++n,++n,r(I.CloseStatement,"Expected closing statement token");i(I.OpenStatement,I.EndFor);)c.push(s());return new D(t,e,a,c)}(),r(I.OpenStatement,"Expected {% token"),r(I.EndFor,"Expected endfor token"),r(I.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${t[n].type} ${t[n].value}`)}return e}(),e.isStatement=!0;break;case I.OpenExpression:e=function(){r(I.OpenExpression,"Expected opening expression token");const t=l();return r(I.CloseExpression,"Expected closing expression token"),t}(),e.isStatement=!0;break;default:throw new SyntaxError(`Unexpected token type: ${t[n].type}`)}return e}function i(...e){return n+e.length<=t.length&&e.some(((e,r)=>e!==t[n+r].type))}function o(...e){return n+e.length<=t.length&&e.every(((e,r)=>e===t[n+r].type))}function a(){const t=l();if(o(I.Equals)){++n;const e=a();return new J(t,e)}return t}function c(){const e=l();r(I.CloseStatement,"Expected closing statement token");const i=[],a=[];for(;t[n]?.type!==I.OpenStatement||t[n+1]?.type!==I.ElseIf&&t[n+1]?.type!==I.Else&&t[n+1]?.type!==I.EndIf;)i.push(s());if(t[n]?.type===I.OpenStatement&&t[n+1]?.type!==I.EndIf)if(++n,o(I.ElseIf))r(I.ElseIf,"Expected elseif token"),a.push(c());else for(r(I.Else,"Expected else token"),r(I.CloseStatement,"Expected closing statement token");t[n]?.type!==I.OpenStatement||t[n+1]?.type!==I.EndIf;)a.push(s());return new z(e,i,a)}function u(t=!1){const e=t?E:l,r=[e()],s=o(I.Comma);for(;s&&(++n,r.push(e()),o(I.Comma)););return s?new nt(r):r[0]}function l(){return function(){const t=f();if(o(I.If)){++n;const e=f();if(o(I.Else)){++n;const r=f();return new z(e,[t],[r])}return new ot(t,e)}return t}()}function f(){let e=h();for(;o(I.Or);){const r=t[n];++n;const s=h();e=new st(r,e,s)}return e}function h(){let e=p();for(;o(I.And);){const r=t[n];++n;const s=p();e=new st(r,e,s)}return e}function p(){let e;for(;o(I.Not);){const r=t[n];++n;const s=p();e=new ct(r,s)}return e??function(){let e=w();for(;o(I.ComparisonBinaryOperator)||o(I.In)||o(I.NotIn);){const r=t[n];++n;const s=w();e=new st(r,e,s)}return e}()}function w(){let e=g();for(;o(I.AdditiveBinaryOperator);){const r=t[n];++n;const s=g();e=new st(r,e,s)}return e}function d(){const e=function(){let e=E();for(;o(I.Dot)||o(I.OpenSquareBracket);){const s=t[n];let i;++n;const o=s.type!==I.Dot;if(o)i=b(),r(I.CloseSquareBracket,"Expected closing square bracket");else if(i=E(),"Identifier"!==i.type)throw new SyntaxError("Expected identifier following dot operator");e=new H(e,i,o)}return e}();return o(I.OpenParen)?m(e):e}function m(t){let e=new Z(t,y());return o(I.OpenParen)&&(e=m(e)),e}function y(){r(I.OpenParen,"Expected opening parenthesis for arguments list");const t=function(){const t=[];for(;!o(I.CloseParen);){let e=l();if(o(I.Equals)){if(++n,!(e instanceof G))throw new SyntaxError("Expected identifier for keyword argument");const t=l();e=new lt(e,t)}t.push(e),o(I.Comma)&&++n}return t}();return r(I.CloseParen,"Expected closing parenthesis for arguments list"),t}function b(){const t=[];let e=!1;for(;!o(I.CloseSquareBracket);)o(I.Colon)?(t.push(void 0),++n,e=!0):(t.push(l()),o(I.Colon)&&(++n,e=!0));if(0===t.length)throw new SyntaxError("Expected at least one argument for member/slice expression");if(e){if(t.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new ut(...t)}return t[0]}function g(){let e=v();for(;o(I.MultiplicativeBinaryOperator);){const r=t[n];++n;const s=v();e=new st(r,e,s)}return e}function v(){let t=function(){let t=d();for(;o(I.Pipe);){++n;let e=E();if(!(e instanceof G))throw new SyntaxError("Expected identifier for the filter");o(I.OpenParen)&&(e=m(e)),t=new it(t,e)}return t}();for(;o(I.Is);){++n;const e=o(I.Not);e&&++n;let r=E();if(r instanceof tt&&(r=new G(r.value.toString())),!(r instanceof G))throw new SyntaxError("Expected identifier for the test");t=new at(t,e,r)}return t}function E(){const e=t[n];switch(e.type){case I.NumericLiteral:return++n,new Y(Number(e.value));case I.StringLiteral:return++n,new Q(e.value);case I.BooleanLiteral:return++n,new tt("true"===e.value.toLowerCase());case I.Identifier:return++n,new G(e.value);case I.OpenParen:{++n;const e=u();if(t[n].type!==I.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${t[n].type} instead`);return++n,e}case I.OpenSquareBracket:{++n;const t=[];for(;!o(I.CloseSquareBracket);)t.push(l()),o(I.Comma)&&++n;return++n,new et(t)}case I.OpenCurlyBracket:{++n;const t=new Map;for(;!o(I.CloseCurlyBracket);){const e=l();r(I.Colon,"Expected colon between key and value in object literal");const s=l();t.set(e,s),o(I.Comma)&&++n}return++n,new rt(t)}default:throw new SyntaxError(`Unexpected token: ${e.type}`)}}for(;n<t.length;)e.body.push(s());return e}function ht(t,e,n=1){void 0===e&&(e=t,t=0);const r=[];for(let s=t;s<e;s+=n)r.push(s);return r}function pt(t,e,n,r=1){const s=Math.sign(r);s>=0?(e=(e??=0)<0?Math.max(t.length+e,0):Math.min(e,t.length),n=(n??=t.length)<0?Math.max(t.length+n,0):Math.min(n,t.length)):(e=(e??=t.length-1)<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),n=(n??=-1)<-1?Math.max(t.length+n,-1):Math.min(n,t.length-1));const i=[];for(let o=e;s*o<s*n;o+=r)i.push(t[o]);return i}function wt(t){return t.replace(/\b\w/g,(t=>t.toUpperCase()))}var dt=class{constructor(t=void 0){this.type="RuntimeValue",this.builtins=new Map,this.value=t}__bool__(){return new bt(!!this.value)}toString(){return""+this.value}toJSON(){return this.value}},mt=class extends dt{constructor(){super(...arguments),this.type="NumericValue"}},yt=class t extends dt{constructor(){super(...arguments),this.type="StringValue",this.builtins=new Map([["upper",new $t((()=>new t(this.value.toUpperCase())))],["lower",new $t((()=>new t(this.value.toLowerCase())))],["strip",new $t((()=>new t(this.value.trim())))],["title",new $t((()=>new t(wt(this.value))))],["length",new mt(this.value.length)],["rstrip",new $t((()=>new t(this.value.trimEnd())))],["lstrip",new $t((()=>new t(this.value.trimStart())))]])}},bt=class extends dt{constructor(){super(...arguments),this.type="BooleanValue"}},gt=class extends dt{constructor(t,e){super(t),this.orgValue=e,this.type="ObjectValue",this.builtins=new Map([["get",new $t((([t,e])=>{if(!(t instanceof yt))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new St}))],["items",new $t((()=>new Et(Array.from(this.value.entries()).map((([t,e])=>new Et([new yt(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 bt(this.value.size>0)}},vt=class extends gt{constructor(){super(...arguments),this.type="KeywordArgumentsValue"}},Et=class extends dt{constructor(){super(...arguments),this.type="ArrayValue",this.builtins=new Map([["length",new mt(this.value.length)]])}__bool__(){return new bt(this.value.length>0)}},xt=class extends Et{constructor(){super(...arguments),this.type="TupleValue"}},$t=class extends dt{constructor(){super(...arguments),this.type="FunctionValue"}},St=class extends dt{constructor(){super(...arguments),this.type="NullValue"}},kt=class extends dt{constructor(){super(...arguments),this.type="UndefinedValue"}},At=class{constructor(t){this.parent=t,this.variables=new Map([["namespace",new $t((t=>{if(0===t.length)return new gt(new Map);if(1!==t.length||!(t[0]instanceof gt))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 $t],["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 Et||t instanceof yt],["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,Tt(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 kt}catch{return new kt}}},Ot=class{constructor(t){this.global=t??new At}run(t){return this.evaluate(t,this.global)}evaluateBinaryExpression(t,e){const n=this.evaluate(t.left,e);switch(t.operator.value){case"and":return n.__bool__().value?this.evaluate(t.right,e):n;case"or":return n.__bool__().value?n:this.evaluate(t.right,e)}const r=this.evaluate(t.right,e);switch(t.operator.value){case"==":return new bt(n.value==r.value);case"!=":return new bt(n.value!=r.value)}if(n instanceof kt||r instanceof kt)throw new Error("Cannot perform operation on undefined values");if(n instanceof St||r instanceof St)throw new Error("Cannot perform operation on null values");if(n instanceof mt&&r instanceof mt)switch(t.operator.value){case"+":return new mt(n.value+r.value);case"-":return new mt(n.value-r.value);case"*":return new mt(n.value*r.value);case"/":return new mt(n.value/r.value);case"%":return new mt(n.value%r.value);case"<":return new bt(n.value<r.value);case">":return new bt(n.value>r.value);case">=":return new bt(n.value>=r.value);case"<=":return new bt(n.value<=r.value)}else if(n instanceof Et&&r instanceof Et){if("+"===t.operator.value)return new Et(n.value.concat(r.value))}else if(r instanceof Et){const e=void 0!==r.value.find((t=>t.value===n.value));switch(t.operator.value){case"in":return new bt(e);case"not in":return new bt(!e)}}if((n instanceof yt||r instanceof yt)&&"+"===t.operator.value)return new yt(n.toString()+r.toString());if(n instanceof yt&&r instanceof yt)switch(t.operator.value){case"in":return new bt(r.value.includes(n.value));case"not in":return new bt(!r.value.includes(n.value))}if(n instanceof yt&&r instanceof gt)switch(t.operator.value){case"in":return new bt(r.value.has(n.value));case"not in":return new bt(!r.value.has(n.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${n.type} and ${r.type}`)}evaluateArguments(t,e){const n=[],r=new Map;for(const s of t)if("KeywordArgumentExpression"===s.type){const t=s;r.set(t.key.value,this.evaluate(t.value,e))}else{if(r.size>0)throw new Error("Positional arguments must come before keyword arguments");n.push(this.evaluate(s,e))}return[n,r]}evaluateFilterExpression(t,e){const n=this.evaluate(t.operand,e);if("Identifier"===t.filter.type){const r=t.filter,s=e.lookupVariable(r.value);if(s instanceof $t)return s.value([n],e);if(n instanceof Et)switch(r.value){case"list":return n;case"first":return n.value[0];case"last":return n.value[n.value.length-1];case"length":return new mt(n.value.length);case"reverse":return new Et(n.value.reverse());case"sort":return new Et(n.value.sort(((t,e)=>{if(t.type!==e.type)throw new Error(`Cannot compare different types: ${t.type} and ${e.type}`);switch(t.type){case"NumericValue":return t.value-e.value;case"StringValue":return t.value.localeCompare(e.value);default:throw new Error(`Cannot compare type: ${t.type}`)}})));default:throw new Error(`Unknown ArrayValue filter: ${r.value}`)}else if(n instanceof yt)switch(r.value){case"length":return new mt(n.value.length);case"upper":return new yt(n.value.toUpperCase());case"lower":return new yt(n.value.toLowerCase());case"title":return new yt(wt(n.value));case"capitalize":return new yt(n.value.charAt(0).toUpperCase()+n.value.slice(1));case"trim":return new yt(n.value.trim());case"trimStart":return new yt(n.value.trimStart());case"trimEnd":return new yt(n.value.trimEnd());case"indent":return new yt(n.value.split("\n").map(((t,e)=>0===e||0===t.length?t:" "+t)).join("\n"));case"string":return n;default:throw new Error(`Unknown StringValue filter: ${r.value}`)}else{if(n instanceof mt){if("abs"===r.value)return new mt(Math.abs(n.value));throw new Error(`Unknown NumericValue filter: ${r.value}`)}if(n instanceof gt)switch(r.value){case"items":return new Et(Array.from(n.value.entries()).map((([t,e])=>new Et([new yt(t),e]))));case"length":return new mt(n.value.size);case"string":return new yt(n.toString());default:throw new Error(`Unknown ObjectValue filter: ${r.value}`)}}throw new Error(`Cannot apply filter "${r.value}" to type: ${n.type}`)}if("CallExpression"===t.filter.type){const r=t.filter;if("Identifier"!==r.callee.type)throw new Error(`Unknown filter: ${r.callee.type}`);const s=r.callee.value,i=e.lookupVariable(s);if(i instanceof $t){const[t,s]=this.evaluateArguments(r.args,e);return s.size>0&&t.push(new vt(s)),i.value([n,...t],e)}if(n instanceof Et){switch(s){case"selectattr":{if(n.value.some((t=>!(t instanceof gt))))throw new Error("`selectattr` can only be applied to array of objects");if(r.args.some((t=>"StringLiteral"!==t.type)))throw new Error("arguments of `selectattr` must be strings");const[t,s,i]=r.args.map((t=>this.evaluate(t,e)));let o;if(s){const t=e.tests.get(s.value);if(!t)throw new Error(`Unknown test: ${s.value}`);o=t}else o=(...t)=>t[0].__bool__().value;const a=n.value.filter((e=>{const n=e.value.get(t.value);return!!n&&o(n,i)}));return new Et(a)}case"map":{const[,t]=this.evaluateArguments(r.args,e);if(t.has("attribute")){const e=t.get("attribute");if(!(e instanceof yt))throw new Error("attribute must be a string");const r=t.get("default"),s=n.value.map((t=>{if(!(t instanceof gt))throw new Error("items in map must be an object");return t.value.get(e.value)??r??new kt}));return new Et(s)}throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${s}`)}if(n instanceof yt){if("indent"===s){const[t,s]=this.evaluateArguments(r.args,e),i=t.at(0)??s.get("width")??new mt(4);if(!(i instanceof mt))throw new Error("width must be a number");const o=t.at(1)??s.get("first")??new bt(!1),a=t.at(2)??s.get("blank")??new bt(!1),c=n.value.split("\n"),u=" ".repeat(i.value),l=c.map(((t,e)=>!o.value&&0===e||!a.value&&0===t.length?t:u+t));return new yt(l.join("\n"))}throw new Error(`Unknown StringValue filter: ${s}`)}throw new Error(`Cannot apply filter "${s}" to type: ${n.type}`)}throw new Error(`Unknown filter: ${t.filter.type}`)}evaluateTestExpression(t,e){const n=this.evaluate(t.operand,e),r=e.tests.get(t.test.value);if(!r)throw new Error(`Unknown test: ${t.test.value}`);const s=r(n);return new bt(t.negate?!s:s)}evaluateUnaryExpression(t,e){const n=this.evaluate(t.argument,e);if("not"===t.operator.value)return new bt(!n.value);throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let n="";for(const r of t){const t=this.evaluate(r,e);"NullValue"!==t.type&&"UndefinedValue"!==t.type&&(n+=t)}return new yt(n)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){const[n,r]=this.evaluateArguments(t.args,e);r.size>0&&n.push(new vt(r));const s=this.evaluate(t.callee,e);if("FunctionValue"!==s.type)throw new Error(`Cannot call something that is not a function: got ${s.type}`);return s.value(n,e)}evaluateSliceExpression(t,e,n){if(!(t instanceof Et||t instanceof yt))throw new Error("Slice object must be an array or string");const r=this.evaluate(e.start,n),s=this.evaluate(e.stop,n),i=this.evaluate(e.step,n);if(!(r instanceof mt||r instanceof kt))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof mt||s instanceof kt))throw new Error("Slice stop must be numeric or undefined");if(!(i instanceof mt||i instanceof kt))throw new Error("Slice step must be numeric or undefined");return t instanceof Et?new Et(pt(t.value,r.value,s.value,i.value)):new yt(pt(Array.from(t.value),r.value,s.value,i.value).join(""))}evaluateMemberExpression(t,e){const n=this.evaluate(t.object,e);let r,s;if(t.computed){if("SliceExpression"===t.property.type)return this.evaluateSliceExpression(n,t.property,e);r=this.evaluate(t.property,e)}else r=new yt(t.property.value);if(n instanceof gt){if(!(r instanceof yt))throw new Error(`Cannot access property with non-string: got ${r.type}`);s=n.value.get(r.value)??n.builtins.get(r.value)}else if(n instanceof Et||n instanceof yt)if(r instanceof mt)s=n.value.at(r.value),n instanceof yt&&(s=new yt(n.value.at(r.value)));else{if(!(r instanceof yt))throw new Error(`Cannot access property with non-string/non-number: got ${r.type}`);s=n.builtins.get(r.value)}else{if(!(r instanceof yt))throw new Error(`Cannot access property with non-string: got ${r.type}`);s=n.builtins.get(r.value)}return s instanceof dt?s:new kt}evaluateSet(t,e){const n=this.evaluate(t.value,e);if("Identifier"===t.assignee.type){const r=t.assignee.value;e.setVariable(r,n)}else{if("MemberExpression"!==t.assignee.type)throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(t.assignee)}`);{const r=t.assignee,s=this.evaluate(r.object,e);if(!(s instanceof gt))throw new Error("Cannot assign to member of non-object");if("Identifier"!==r.property.type)throw new Error("Cannot assign to member with non-identifier property");s.value.set(r.property.value,n)}}return new St}evaluateIf(t,e){const n=this.evaluate(t.test,e);return this.evaluateBlock(n.__bool__().value?t.body:t.alternate,e)}evaluateFor(t,e){const n=new At(e);let r,s;if("SelectExpression"===t.iterable.type){const e=t.iterable;s=this.evaluate(e.iterable,n),r=e.test}else s=this.evaluate(t.iterable,n);if(!(s instanceof Et))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 At(n),c=s.value[e];let u;if("Identifier"===t.loopvar.type)u=e=>e.setVariable(t.loopvar.value,c);else{if("TupleLiteral"!==t.loopvar.type)throw new Error(`Invalid loop variable(s): ${t.loopvar.type}`);{const e=t.loopvar;if("ArrayValue"!==c.type)throw new Error(`Cannot unpack non-iterable type: ${c.type}`);const n=c;if(e.value.length!==n.value.length)throw new Error(`Too ${e.value.length>n.value.length?"few":"many"} items to unpack`);u=t=>{for(let r=0;r<e.value.length;++r){if("Identifier"!==e.value[r].type)throw new Error(`Cannot unpack non-identifier type: ${e.value[r].type}`);t.setVariable(e.value[r].value,n.value[r])}}}}if(r){u(a);if(!this.evaluate(r,a).__bool__().value)continue}i.push(c),o.push(u)}let a="",c=!0;for(let e=0;e<i.length;++e){const r=new Map([["index",new mt(e+1)],["index0",new mt(e)],["revindex",new mt(i.length-e)],["revindex0",new mt(i.length-e-1)],["first",new bt(0===e)],["last",new bt(e===i.length-1)],["length",new mt(i.length)],["previtem",e>0?i[e-1]:new kt],["nextitem",e<i.length-1?i[e+1]:new kt]]);n.setVariable("loop",new gt(r)),o[e](n);a+=this.evaluateBlock(t.body,n).value,c=!1}if(c){a+=this.evaluateBlock(t.defaultBlock,n).value}return new yt(a)}evaluateMacro(t,e){return e.setVariable(t.name.value,new $t(((e,n)=>{const r=new At(n);let s;e=e.slice(),"KeywordArgumentsValue"===e.at(-1)?.type&&(s=e.pop());for(let n=0;n<t.args.length;++n){const i=t.args[n],o=e[n];if("Identifier"===i.type){const t=i;if(!o)throw new Error(`Missing positional argument: ${t.value}`);r.setVariable(t.value,o)}else{if("KeywordArgumentExpression"!==i.type)throw new Error(`Unknown argument type: ${i.type}`);{const t=i,e=o??s?.value.get(t.key.value)??this.evaluate(t.value,r);r.setVariable(t.key.value,e)}}}return this.evaluateBlock(t.body,r)}))),new St}evaluate(t,e){if(void 0===t)return new kt;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 mt(Number(t.value));case"StringLiteral":return new yt(t.value);case"BooleanLiteral":return new bt(t.value);case"ArrayLiteral":return new Et(t.value.map((t=>this.evaluate(t,e))));case"TupleLiteral":return new xt(t.value.map((t=>this.evaluate(t,e))));case"ObjectLiteral":{const n=new Map;for(const[r,s]of t.value){const t=this.evaluate(r,e);if(!(t instanceof yt))throw new Error(`Object keys must be strings: got ${t.type}`);n.set(t.value,this.evaluate(s,e))}return new gt(n,t.value)}case"Identifier":return this.evaluateIdentifier(t,e);case"CallExpression":return this.evaluateCallExpression(t,e);case"MemberExpression":return this.evaluateMemberExpression(t,e);case"UnaryExpression":return this.evaluateUnaryExpression(t,e);case"BinaryExpression":return this.evaluateBinaryExpression(t,e);case"FilterExpression":return this.evaluateFilterExpression(t,e);case"TestExpression":return this.evaluateTestExpression(t,e);default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function Tt(t){switch(typeof t){case"number":return new mt(t);case"string":return new yt(t);case"boolean":return new bt(t);case"undefined":return new kt;case"object":return null===t?new St:Array.isArray(t)?new Et(t.map(Tt)):new gt(new Map(Object.entries(t).map((([t,e])=>[t,Tt(e)]))),t);case"function":return new $t(((e,n)=>{const r=e.map((t=>jt(t)));return Tt(t(...r)??null)}));default:throw new Error(`Cannot convert to runtime value: ${t}`)}}function jt(t){let e=t;if(Array.isArray(t))e=t.map((t=>jt(t)));else if(t instanceof Map)e={},t.forEach(((t,n)=>{e[n]=jt(t)}));else switch(t.type){case"NullValue":e=null;break;case"UndefinedValue":e=void 0;break;case"ArrayValue":e=t.value.map((t=>jt(t)));break;case"KeywordArgumentsValue":case"ObjectValue":e=t.orgValue?t.orgValue:jt(t.value),"KeywordArgumentsValue"===t.type&&Object.setPrototypeOf(e,{jinja_kargs:!0});break;default:t.type&&(e=t.value)}return e}function Ct(t,e=0){return Math.floor(Math.random()*(t-e+1))+e}var Nt={randomInt:Ct,select:function(t,e){if(Array.isArray(t)||"string"==typeof t)return void 0===e?e=Ct(t.length-1):"string"==typeof e&&(e=parseInt(e)),e<0&&(e=t.length+e),t[e];if(t&&"object"==typeof t){if(void 0===e){const n=Object.keys(t);e=n[Ct(n.length-1)]}return t[e]}},tojson:function(t,e,n){return e&&"object"==typeof e&&(e.depth&&(n=e.depth),e=e.indent),Ft(t,e,n)}};function Ft(t,e,n){let r="";const s=n??0;if(null===t)r="null";else{const n=typeof t;switch(n){case"undefined":r="null";case"number":case"string":case"boolean":return JSON.stringify(t);case"object":{const n=e?" ".repeat(e):"",r="\n"+n.repeat(s),i=r+n;if(Array.isArray(t)){const n=t.map((t=>Ft(t,e,s+1)));return e?`[${i}${n.join(`,${i}`)}${r}]`:`[${n.join(", ")}]`}{const n=Array.from(Object.entries(t)).map((([t,n])=>{const r=`"${t}": ${Ft(n,e,s+1)}`;return e?`${i}${r}`:r}));return e?`{${n.join(",")}${r}}`:`{${n.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${n}`)}}return r}var It=class extends At{constructor(t){super(t),this.parent=t}assign(t){for(const[e,n]of Object.entries(t))this.set(e,n)}clear(){this.variables.clear()}},Mt=class t{static{this.global=new It}constructor(t,e={}){const n=U(t,e={lstrip_blocks:!0,trim_blocks:!0,...e});this.parsed=ft(n)}render(e){const n=new At(t.global);n.set("false",!1),n.set("true",!0),n.set("raise_exception",(t=>{throw new Error(t)})),n.set("range",ht);for(const[t,r]of Object.entries(e))n.set(t,r);return new Ot(n).run(this.parsed).toString()}};function Pt(t,e){let n;switch(t.type){case"Identifier":n=t.value;break;case"MemberExpression":n=Pt(t.object,e);break;case"FilterExpression":n=Pt(t.operand,e);break;case"Set":{e||(e=[]);const r=Pt(t.assignee);r&&e.push(r),n=Pt(t.value,e);break}}return n&&e?.includes(n)&&(n=void 0),n}function Rt(t){let e;if("Program"===t.type)e=t.body.some((t=>Rt(t)));else e=t.isStatement;return e}function qt(t,e){let n=[];if(Array.isArray(t))n=t.map((t=>qt(t,e))).filter(Boolean).flat();else switch(t.type){case"Program":n=t.body.map((t=>qt(t,e))).filter(Boolean).flat();break;case"If":n=[Pt(t.test,e),...qt(t.body,e),...qt(t.alternate,e)].filter(Boolean);break;case"BinaryExpression":n=[Pt(t.left,e),Pt(t.right,e)].filter(Boolean);break;case"For":{const r=Pt(t.loopvar);r&&(e||(e=[]),e.push(r)),n=[Pt(t.iterable,e),...qt(t.body,e)].filter(Boolean);break}case"CallExpression":n=[Pt(t.callee,e),...qt(t.args,e)].filter(Boolean);break;default:n=[Pt(t,e)].filter(Boolean)}return n}Mt.global.assign(Nt);var Vt=class extends j{static isTemplate(t){let e,n,r=!1;if("object"==typeof t?(n=t.template,e=t.compiledTemplate):n=t,!e&&n)try{e=new Mt(n)}catch(t){}return e&&(r=Rt(e.parsed)),r}getVariables(t=this.compiledTemplate){return qt(t.parsed,[]).filter(((t,e,n)=>n.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 Mt(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return this.compiledTemplate.render(t)}};function Bt(t){return function(e){return t}}function Ut(t){const e=t.split(""),n=[],r=(t,n)=>{for(let r=n;r<e.length;r+=1)if(t.includes(e[r]))return r;return-1};let s=0;for(;s<e.length;)if("{"===e[s]&&s+1<e.length&&"{"===e[s+1])n.push({type:"literal",text:"{"}),s+=2;else if("}"===e[s]&&s+1<e.length&&"}"===e[s+1])n.push({type:"literal",text:"}"}),s+=2;else if("{"===e[s]){const t=r("}",s);if(t<0)throw new Error("Unclosed '{' in template.");n.push({type:"variable",name:e.slice(s+1,t).join("")}),s=t+1}else{if("}"===e[s])throw new Error("Single '}' in template.");{const t=r("{}",s),i=(t<0?e.slice(s):e.slice(s,t)).join("");n.push({type:"literal",text:i}),s=t<0?e.length:t}}return n}function _t(t,e){return t.reduce(((t,n)=>{let r;return r="variable"===n.type?n.name in e?t+e[n.name]:t:t+n.text,r}),"")}function Lt(t){const e=new Set;return t.forEach((t=>{"variable"===t.type&&e.add(t.name)})),[...e]}j.register(Vt,{name:"hf",aliases:["huggingface","internal","default"]});var zt=class extends j{static isTemplate(t){let e,n,r=!1;if("object"==typeof t?(n=t.template,e=t.compiledTemplate):n=t,!e&&n)try{e=Ut(n)}catch(t){}if(e){r=Lt(e).length>0}return r}getVariables(t=this.compiledTemplate){return Lt(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=Ut(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return _t(this.compiledTemplate,t)}};function Dt(t,e){return"string"==typeof e&&(e=e.split(".").filter((t=>t.length))),e.reduce(((t,e)=>t?.[e]),t)}function Jt(t,e,n){let r=function(t,e,n){return t.replace(/{{\s*re_replace\s+\.(.+?)\s+(["'])((?:(?!\2).)*?)\2\s+(["'])((?:(?!\4).)*?)\4\s*}}/g,((t,r,s,i,o,a)=>{if(n)return e[r]=null,t;const c=new RegExp(i,"g");return Dt(e,r).replace(c,a)}))}(t,e,n);return r=function(t,e,n){return t.replace(/{{\s*join\s+\.(.+?)\s+(["'])((?:(?!\2).)*?)\2\s*}}/g,((t,r,s,i)=>n?(e[r]=null,t):Dt(e,r).join(i)))}(r,e,n),r=function(t,e,n){return t.replace(/{{\s*if\s*(\S+?)\s*}}([^{]*)({{\s*else\s*}}([^{]*))?{{\s*end\s*}}/g,((t,r,s,i,o)=>{if(n)return r.startsWith(".")&&(r=r.substring(1)),e[r]=null,t;let a;if(!r.startsWith("."))throw new Error("Functionality not implemented");{const t=Dt(e,r.substring(1));if(null==t)a=o??"";else if("string"==typeof t)a=t.length>0?s:o??"";else if(Array.isArray(t))a=t.length>0?s:o??"";else{if("boolean"!=typeof t)throw new Error(`Unexpected type for variable ${r}: ${typeof t}`);a=t?s:o??""}}return a}))}(r,e,n),r=function(t,e,n){return t.replace(/{{\s*range\s*[.$]([^{}\s]+?)\s*}}([^{]*?){{\.}}([^{]*?){{\s*end\s*}}/g,((t,r,s,i)=>{if(n)return e[r]=null,t;const o=Dt(e,r);if(Array.isArray(o)){let t="";for(const e of o)t+=`${s}${e}${i}`;return t}return t}))}(r,e,n),r=function(t,e,n){return t.replace(/{{\s*\.([^{}\s]+?)\s*}}/g,((t,r)=>n?(e[r]=null,t):Dt(e,r)||""))}(r,e,n),r=function(t,e,n){return t.replace(/{{\s*index\s*\.(.+?)\s+(.+?)\s*}}/g,((t,r,s)=>{if(n)return e[r]=null,t;const i=Dt(e,r);let o;return o=isNaN(s)?i[s.substring(1,s.length-1)]:i[parseInt(s,10)],o||""}))}(r,e,n),r}j.register(zt,{name:"fstring",aliases:["python","f-string","langchain"]});var Wt=class extends j{static isTemplate(t){const e="string"==typeof t?t:t.template;return e?.includes("{{")&&e.includes("}}")}getVariables(t){const e={};return Jt(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 Jt(this.template,t)}};function Kt(t){return Object.keys(t).sort().map((e=>t[e]))}j.register(Wt,{name:"golang",aliases:["localai","ollama"]});var Ht=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 n=await this.examplePrompt.format(t);e.push(n)}else if("string"==typeof t)e.push(t);else if(t){const n=Kt(t);n.length>0&&e.push(...n)}const n=[this.prefix,...e,this.suffix].join(this.exampleSeparator),r=this.templateFormat;return await j.format({template:n,data:t,templateFormat:r})}toJSON(t=this){const e=super.toJSON(t);return t.suffix&&(e.suffix=t.suffix),t.exampleSeparator&&(e.exampleSeparator=t.exampleSeparator),t.prefix&&(e.prefix=t.prefix),t.examplePrompt&&(e.examplePrompt=t.examplePrompt),t.examples&&(e.examples=t.examples),e}};j.register(Ht,{name:"fewshot",aliases:["few_shot"]});var Zt=/(\\)?(\$)(?!\()(\{?)([\w.]+)(?::?-((?:\$\{(?:\$\{(?:\$\{[^}]*\}|[^}])*}|[^}])*}|[^}])+))?(\}?)/gi;function Gt(t){return t.replace(/\\\$/g,"$")}function Xt(t,e,n){return t.replace(Zt,((r,s,i,o,a,c,u)=>"\\"===s?r.slice(1):e[a]?e[a]===n[a]?e[a]:Xt(e[a],e,n):n[a]?n[a]===t?n[a]:Xt(n[a],e,n):c?c.startsWith("$")?Xt(c,e,n):c:""))}function Yt(t){let e=process.env;t&&null!=t.processEnv&&(e=t.processEnv);for(const n in t.parsed){let r=t.parsed[n];if(!r)continue;r=Object.prototype.hasOwnProperty.call(e,n)?e[n]===t.parsed[n]?Xt(r,e,t.parsed):e[n]:Xt(r,e,t.parsed),t.parsed[n]=r?Gt(r):r}for(const n in t.parsed)e[n]=t.parsed[n];return t}function Qt(t,e={},n){switch(n||(n=new WeakSet),e.processEnv||(e.processEnv={...process.env}),e.parsed||(e.parsed=e.processEnv),typeof t){case"string":t=Xt(t,e.processEnv,e.parsed);break;case"object":if(n.has(t)||null===t)return t;if(n.add(t),Array.isArray(t))for(let r=0;r<t.length;r++){const s=t[r];"string"!=typeof s&&"object"!=typeof s||(t[r]=Qt(t[r],e,n))}else for(const[r,s]of Object.entries(t))"string"!=typeof s&&"object"!=typeof s||(t[r]=Qt(s,e,n))}return t}var te="@",ee=/(\S.+?[.!?])(?=\s+|$)|(\S.+?)(?=[\n]|$)/g,ne=/([A-Z][a-z]{1,2}\.)\s(\w)/g,re=/(\.[a-zA-Z]\.)\s(\w)/g,se=new RegExp("([A-Z][a-z]{1,2}\\.)"+te+"(\\w)","g"),ie=new RegExp("(\\.[a-zA-Z]\\.)"+te+"(\\w)","g");function oe(t,e,n){const r="$1"+e+"$2";let s=t;for(let t=0;t<n.length;t++)s=s.replace(n[t],r);return s}function ae(t,e=!0){const n=(t=(t=(t=(t=(t=t.replace(/([。!??])\1+/g,"$1")).replace(/([。!??])([^”’])/g,"$1\n$2")).replace(/(\.{6})([^”’])/g,"$1\n$2")).replace(/(…{2})([^”’])/g,"$1\n$2")).replace(/([。!??][”’])([^,。!??])/g,"$1\n$2")).split("\n");let r=[];for(let t=0;t<n.length;t++){let s=n[t].trim();if(!s)continue;if(!e){r.push(s);continue}let i=oe(s,te,[ne,re]),o=Array.from(i.matchAll(ee));if(o.length)for(let t=0;t<o.length;t++){let e=oe(o[t][0]," ",[se,ie]);r.push(e)}else r.push(s)}return r}function ce(t,e=2,n=.5){const r=10**e;return Math.trunc((t+Number.EPSILON+n/r)*r)/r}async function ue(t){return new Promise((e=>setTimeout(e,t)))}var le=require("custom-ability"),fe="event",he="event-bus";var pe=(0,le.createAbilityInjector)((function(t){return class{static get emitter(){if(!this._emitter){const t=this.get(he)?.emitter;t&&(this._emitter=t,this.prototype._events=t._events)}return this._emitter}get emitter(){return this.constructor._emitter}on(e,n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.on(e,n)}once(e,n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.once(e,n)}off(e,n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.off(e,n)}emit(e,...n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return"error"===e?this.emitError.apply(this,n):r.emit.call(this,e,this.name,...n)}emitError(e,...n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.emit.call(this,"error",e,this.name,...n)}async emitAsync(e,...n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.emitAsync.call(this,e,this.name,...n)}}}),!0);function we(t,e){return!t||t.some((t=>t instanceof RegExp?t.test(e):t===e))}var de=498,me=class{get active(){return this._active}set active(t){t!==this._active&&(t?(this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0),this.options.pingInterval>0&&(this.pingTimer=setInterval((()=>this.publish()),this.options.pingInterval))):(this.clients.size&&this.clearClients(),this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0)),this._active=t)}constructor(t){this.options=Object.assign({},{pingInterval:3e3,maxStreamDuration:3e4,clientRetryInterval:1e3,startId:1,historySize:100,rewind:0,cors:!1},t),this.nextID=this.options.startId,this.clients=new Set,this.messages=[],this.active=!0}publish(t,e){let n,r;this.active||(0,w.throwError)("Channel closed","SSEChannel",de);let s=e;if(t||e)r=this.nextID++,"object"==typeof t&&(t.event?(s=t.event,void 0!==t.data&&(t=JSON.stringify(t.data))):t=JSON.stringify(t)),t=t?t.split(/[\r\n]+/).map((t=>"data: "+t)).join("\n"):"",n="id: "+r+"\n"+(e?"event: "+e+"\n":"")+(t||"data: ")+"\n\n",this.messages.push({id:r,_eventName:s,output:n});else{if(!this.clients.size)return;n="data: \n\n"}for([...this.clients].filter((t=>!s||we(t.events,s))).forEach(((t,e)=>{t.res.write(n)}));this.messages.length>this.options.historySize;)this.messages.shift();return r}subscribe(t,e,n){this.active||(0,w.throwError)("Channel closed","SSEChannel",de);const r={req:t,res:e,events:n},s=this.options.maxStreamDuration;let i="max-age=0, stale-while-revalidate=0, stale-if-error=0, no-transform";s>0&&(i+=", s-maxage="+(Math.floor(s/1e3)-1));const o={"Content-Type":"text/event-stream","Cache-Control":i,Connection:"keep-alive"};this.options.cors&&(o["access-control-allow-origin"]="*"),r.req.socket.setNoDelay(!0),r.res.writeHead(200,o);let a="retry: "+this.options.clientRetryInterval+"\n\n";const c=Number.parseInt(t.headers["last-event-id"],10),u=Number.isNaN(c)?this.options.rewind:this.nextID-1-c;return u&&this.messages.filter((t=>we(r.events,t.eventName))).slice(0-u).forEach((t=>{a+=t.output})),r.res.write(a),this.clients.add(r),s>0&&setTimeout((()=>{r.res.writableEnded||this.unsubscribe(r)}),s),r.res.on("close",(()=>this.unsubscribe(r))),r}unsubscribe(t){t.res.end(),this.clients.delete(t)}clearClients(){this.clients.forEach((t=>t.res.end())),this.clients.clear()}listClients(){const t={};return this.clients.forEach((e=>{const n=e.req.socket.remoteAddress??"";n in t||(t[n]=0),t[n]++})),t}getSubscriberCount(){return this.clients.size}};function ye(t){return t instanceof ReadableStream||t instanceof WritableStream}var be=600,ge=601,ve=class extends w.BaseError{constructor(t,e=be){super(t,500)}};function Ee(t){if(t){const e=t.getReader();return new ReadableStream({async start(t){const{done:n,value:r}=await e.read();if(!n){const e=(new TextDecoder).decode(r);t.error(new ve(`Response error: ${e}`,ge))}}})}return new ReadableStream({start(t){t.error(new ve("Response error: No response body",ge))}})}function xe(){return new ReadableStream({start(t){t.close()}})}var $e=require("eventsource-parser");function Se(t){const e=new TextDecoder;let n;return new TransformStream({async start(e){n=(0,$e.createParser)((n=>{if("data"in n&&"event"===n.type&&"[DONE]"===n.data||"done"===n.event)e.terminate();else if("data"in n){const r=t?t(n.data,{event:n.event}):n.data;r&&e.enqueue(r)}}))},transform(t){n.feed(e.decode(t))}})}function ke(){let t=!0;return e=>(t&&(e=e.trimStart())&&(t=!1),e)}function Ae(t,e){if(!t.ok)return Ee(t.body);let n=t.body||new ReadableStream({start(t){t.close()}});return n instanceof ReadableStream||(n=ReadableStream.from(n)),n.pipeThrough(Se(e))}function Oe(t){let e=t[Symbol.asyncIterator]();return new ReadableStream({async pull(t){const{done:n,value:r}=await e.next();n?t.close():t.enqueue(r)},async cancel(t){await(e.return?.(t))}})}function Te(t){const e=t||{};return new TransformStream({async start(t){const n=t.error;if(t.error=r=>{n.call(t,r),e.onError&&e.onError(r)},e.onStart)try{await e.onStart(t)}catch(e){t.error(e)}},async transform(t,n){try{let r;e.onTransform&&(r=await e.onTransform(t,n)),r||(r=t),n.enqueue(r)}catch(t){n.error(t)}},async flush(t){if(e.onFinal)try{await e.onFinal(t)}catch(e){return t.error(e)}t.terminate()}})}var je=require("uuid"),Ce=c(require("base32768")),Ne=require("uuid"),Fe={1:je.v1,4:je.v4,5:je.v5};function Ie(t=1,e){const n=Fe[t];return e?Ce.encode(n(null,[])):n()}var Me=c(require("xxhashjs")),Pe=c(require("base32768")),Re=require("json-canonicalize"),qe=Pe,{h32:Ve,h64:Be}=Me.default,Ue=588213;function _e(t,e=16){return"object"==typeof t&&(t=(0,Re.canonicalize)(t)),Ve(t,Ue).toString(e)}function Le(t,e=16){return"object"==typeof t&&(t=(0,Re.canonicalize)(t)),Be(t,Ue).toString(e)}var ze=(t=>(t[t.xxhash64=111]="xxhash64",t[t.xxhash32=112]="xxhash32",t))(ze||{});function De(t,e=111,n=Ue){let r;return t.buffer&&(t=t.buffer),112!==e?(r=Be(t,n),r=new Uint16Array([r._a00,r._a16,r._a32,r._a48]),r=new Uint8Array(r.buffer)):(r=Ve(t,n),r=new Uint16Array([r._low,r._high]),r=new Uint8Array(r.buffer)),r}function Je(t,e=111,n=Ue){return Pe.encode(De(t,e,n))}var We=c(require("path")),Ke=/[<>:"/\\|?*\u0000-\u001F]/,He=/^(con|prn|aux|nul|com\d|lpt\d)$/i,Ze=100,Ge=/^\.+(\\|\/)|^\.+$/,Xe=/\.+$/,Ye=/[\u0000-\u001F\u0080-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069]/;function Qe(){return new RegExp(Ke.source,"g")}function tn(){return new RegExp(Ye.source,"g")}function en(t){return t&&!(Ke.test(t)||tn().test(t)||Ge.test(t)||Xe.test(t))}function nn(t){const e=t.split(We.default.sep);return("/"===t[0]||e[0]&&We.default.dirname(e[0])===e[0])&&e.shift(),e.every(en)}function rn(t,e={}){const n=e.replacement||"!";if((Ke.test(n)||Ye.test(n))&&(0,w.throwError)("Replacement string cannot contain reserved filename characters","sanitizeFilename",w.ErrorCode.InvalidArgument),n.length>0){const e=/([<>:"/\\|?*\u0000-\u001F]){2,}/;t=t.replace(e,"$1")}if(t=(t=(t=(t=(t=t.normalize("NFD")).replace(Ge,n)).replace(Qe(),n)).replace(tn(),n)).replace(Xe,""),n.length>0){"."===t[0]||"."!==t[0]||(t=n+t),"."===t[t.length-1]&&(t+=n)}t=He.test(t)?t+n:t;const r="number"==typeof e.maxLength?e.maxLength:Ze;if(t.length>r){const e=t.lastIndexOf(".");if(-1===e)t=t.slice(0,r);else{const n=t.slice(0,e),s=t.slice(e);t=n.slice(0,Math.max(1,r-s.length))+s}}return t}function sn(t,e={}){const n=t.split(We.default.sep);let r;("/"===t[0]||n[0]&&We.default.dirname(n[0])===n[0])&&(r=n.shift());const s=n.map((t=>rn(t,e)));return void 0!==r&&s.unshift(r),s.join(We.default.sep)}function on(t,e=1){let n="";for(;e--;){const e=We.default.extname(t);if(!e)break;n=e+n,t=We.default.basename(t,e)}return n}function an(t){return t.split(".").length-1}var cn=require("util-ex");function un(t,e){if("string"!=typeof t)throw new w.CommonError("modelName must be a string","isModelNameMatched",w.ErrorCode.InvalidArgument);switch(typeof e){case"string":if((0,cn.isRegExpStr)(e)){const n=(e=(0,cn.toRegExp)(e)).exec(t);if(n)return n}else if(t.toLowerCase()===e.toLowerCase())return e;break;case"object":if(Array.isArray(e)){for(const n of e)if("string"==typeof n){if((0,cn.isRegExpStr)(n)){const r=(e=(0,cn.toRegExp)(n)).exec(t);if(r)return r}else if(t.toLowerCase()===n.toLowerCase())return n}else if(n instanceof RegExp){const e=n.exec(t);if(e)return e}else if("function"==typeof n){const e=n.call(this,t);if(e)return e}}else if(e instanceof RegExp){const n=e.exec(t);if(n)return n}break;case"function":const n=e.call(this,t);if(n)return n}}function ln(t){return Object.keys(t).filter((t=>Number.isNaN(Number(t))))}var fn=require("lodash-es"),hn=require("util-ex");function pn(t,e){if(e&&(e=mn(e)),e){const n=Object.keys(e);if(n.length){const r=Object.values(e);return(0,hn.newFunction)("expression",n,`return ${t}`)(...r)}}return(0,hn.newFunction)("expression",[],`return ${t}`)()}var wn=/^[a-zA-Z_$][0-9a-zA-Z_$]*$/,dn=t=>wn.test(t);function mn(t){if(t){const e=Object.keys(t),n=e.length,r=e.filter((e=>dn(e)&&null!==t[e]));if(n===r.length)return t;if(r.length)return t=(0,fn.pick)(t,r)}}function yn(t){return t?bn(t,[],""):[]}function bn(t,e,n="."){return Array.isArray(t)?t.flatMap(((t,n)=>bn(t,[...e,`[${n}]`]))):(r=t)&&r.constructor===Object?Object.entries(t).flatMap((([t,r])=>bn(r,[...e,n+t]))):[e.join("")];var r}function gn(t){if(t<2)throw new w.CommonError("repetitionThreshold must be greater than 1","createEndWithRepetitionDetector",w.ErrorCode.InvalidArgument);const e=new RegExp(`([\\S\\s]+)(\\1{${t-1},})$`);return function(t){return e.exec(t)}}var vn=c(require("path")),En=c(require("fs"));function xn(t){const e=En.statSync(t,{throwIfNoEntry:!1});return e?.isFile()}function $n(t,e,n,r){const s=r?.signal,i=r?.exclude;let o;if(vn.default.isAbsolute(t)?o=xn(t)?t:Sn(vn.default.basename(t),[vn.default.dirname(t)],{extNames:n,exclude:i,signal:s}):(e||(e=["."]),o=Sn(t,e,{extNames:n,exclude:i,signal:s})),!o)throw new w.NotFoundError(t,"loadFileFromPaths");{const t=o;o=En.readFileSync(o),r&&(r.filepath=t)}return o}function Sn(t,e,{extNames:n,signal:r,exclude:s=[]}){let i;const o=n?n.map((e=>on(t,an(e)))):void 0;"string"==typeof s&&(s=[s]);for(const a of e){if(r?.aborted)throw r.reason;const e=vn.default.resolve(a,t);if(o)for(let t=0;t<o.length;t++){const r=e+(o[t]!==n[t]?n[t]:"");if(!s.includes(r)&&xn(r)){i=r;break}}else if(!s.includes(e)&&xn(e)){i=e;break}}return i}function kn(t,e,n,r,s){let i;"string"==typeof r?(i=r,r=void 0):i=r?.encoding??"utf8";return $n(t,e,n,r).toString(i)}function An(t,e){const n=[],r="string"==typeof t?[t]:[...t],s=new Set,i=e?.signal,o=e?.isFileMatched,a=e?.level;let c=0;for(;r.length>0;){if(i?.aborted)throw i.reason;const t=On(r.pop()),e=vn.default.resolve(t);if(s.has(e))continue;s.add(e);const u=En.statSync(t,{throwIfNoEntry:!1});if(u?.isDirectory()){const e=En.readdirSync(t,{withFileTypes:!0});for(let s=0;s<e.length;s++){const i=e[s],a=vn.default.join(t,i.name);i.isDirectory()?r.push(a):!i.isFile()||o&&!o(a)||n.push(a)}if(c++,a&&c>=a)break}}return n}function On(t){const e=En.lstatSync(t,{throwIfNoEntry:!1});return e?.isSymbolicLink()&&(t=En.readlinkSync(t)),t}var Tn=require("fs"),jn=c(require("path")),Cn=require("load-config-file"),Nn=require("yaml"),Fn=require("yaml-types"),In=require("mime-type/with-db"),Mn=require("yaml"),Pn=[Fn.regexp];function Rn(t){Array.isArray(t)||(t=[t]);for(const e of t){-1===Pn.indexOf(e)&&Pn.push(e)}}function qn(t){return(0,Nn.parse)(t,{customTags:Pn})}function Vn(t,e){const n=[],r=e?.after,s=e?.exclude?"string"==typeof e.exclude?[e.exclude]:e.exclude:void 0,i=e?.extensions?"string"==typeof e.extensions?[e.extensions]:e.extensions.map((t=>t.startsWith(".")?t:"."+t)):[".yml",".yaml",".json"];return function(t,e){const n=(0,Tn.readdirSync)(t,{withFileTypes:!0,recursive:!0});for(const r of n){const n=jn.default.join(t,r.name);r.isFile()&&e(n,r)}}(t,((t,e)=>{if(s?.includes(t))return;const o=jn.default.extname(t),a=(0,Tn.statSync)(t);if(i.includes(o)){if(r?.hasOwnProperty(t)&&a.mtimeMs<=r[t])return;n.push(t)}})),n}function Bn(t,e){return Vn(t,e).map((t=>Cn.Config.loadSync(t))).filter((t=>void 0!==t))}function Un(t,e,n=1){"."===t[0]&&n++;const r=on(t,n);(!r||r.split(".").length<=1)&&(t+=".yaml");const s=In.mimeType.lookup(t);if("application/json"===s)e=JSON.stringify(e,null,2);else{if("text/yaml"!==s)throw new Error(`${t} unsupported mime type: ${s}`);e=(0,Nn.stringify)(e)}const i=jn.default.dirname(t);return(0,Tn.existsSync)(i)||(0,Tn.mkdirSync)(i,{recursive:!0}),(0,Tn.writeFileSync)(t,e,{encoding:"utf8"}),t}function _n(t){t instanceof Date&&(t=t.toISOString());return function(t,e){return t?`'${e}'`:String(e)}("string"==typeof t,t)}function Ln(t,e){return t.map((t=>Jn(t,e))).join(" AND ")}function zn(t,e){return t.map((t=>Jn(t,e))).join(" OR ")}function Dn(t,e){const n=[];return Object.keys(e).forEach((r=>{const s=e[r];switch(r){case"$lt":case"<":n.push(`${t} < ${_n(s)}`);break;case"<=":case"$lte":n.push(`${t} <= ${_n(s)}`);break;case"$gt":case">":n.push(`${t} > ${_n(s)}`);break;case"$gte":case">=":n.push(`${t} >= ${_n(s)}`);break;case"$ne":case"!=":n.push(`${t} != ${_n(s)}`);break;case"=":case"$eq":n.push(`${t} = ${_n(s)}`);break;case"$in":n.push(`${t} IN (${s.map((t=>_n(t))).join(", ")})`);break;case"$nin":n.push(`${t} NOT IN (${s.map((t=>_n(t))).join(", ")})`);break;case"$regex":n.push(`${t} REGEXP '${s.source}'`);break;case"$like":n.push(`${t} LIKE '${s}'`);break;case"$nlike":n.push(`${t} NOT LIKE '${s}'`);break;case"$glob":n.push(`${t} GLOB '${s}'`);break;case"$nglob":n.push(`${t} NOT GLOB '${s}'`);break;default:throw new Error(`Unsupported condition operator: ${r}`)}})),n.join(" AND ")}function Jn(t,e){const n=[];if("function"!=typeof e&&(e=t=>t),Array.isArray(t))n.push(Ln(t,e));else for(const[r,s]of Object.entries(t))if("$and"===r)n.push(`(${Ln(t[r],e)})`);else if("$or"===r)n.push(`(${zn(t[r],e)})`);else{const t=typeof s;if(null==s)n.push(`${e(r)} IS NULL`);else if(s instanceof Date)n.push(`${e(r)}='${s.toISOString()}'`);else if("object"!==t||Array.isArray(s))if("string"===t)n.push(`${e(r)}='${s}'`);else{if("number"!==t&&"boolean"!==t)throw new Error(`Unsupported value type for key ${r}`);n.push(`${e(r)}=${s}`)}else n.push(Dn(e(r),s))}return n.length>1?n.join(" AND "):n[0]}function Wn(t){const e=t.indexOf("://");if(e>0)return t.substring(0,e)}function Kn(t,e=0){let n,r=t*10**e;return t>=1e12?(r=Math.round(r/1e12),n="T"):t>=1e9?(r=Math.round(r/1e9),n="B"):t>=1e6?(r=Math.round(r/1e6),n="M"):t>=1e3?(r=Math.round(r/1e3),n="K"):(r=Math.round(r),n=""),r/=10**e,r.toFixed(e)+n}function Hn(t){const e=t.match(/^\s*[+]?(\d+(?:[.]\d+)?)\s*([TBMK])?\s*$/i);if(!e)throw new w.CommonError("Invalid formatted parameter size string.","scaleToSize",w.ErrorCode.InvalidArgument);const n=parseFloat(e[1]),r=e[2]?.toLowerCase();switch(r){case"t":return 1e12*n;case"b":return 1e9*n;case"m":return 1e6*n;case"k":return 1e3*n;default:return n}}function Zn(t,e){const n=e?.level||0,r=e?.visiting||new Set,s=e?.objectTag||"*",i=e?.arrayTag||"-";let o=[];const a=" ".repeat(2*n);if(null!=t)switch(typeof t){case"object":r.has(t)?o=["[Circular]"]:(r.add(t),o=Array.isArray(t)?t.map((t=>i+c(t))):Object.entries(t).map((([t,e])=>s+" `"+t+"`:"+c(e))));break;case"string":return t;default:return JSON.stringify(t)}else o=["null"];return o.length?a+o.join("\n"+a):"";function c(t){return(null!=t&&"object"==typeof t?"\n":" ")+Zn(t,{level:n+1,visiting:r})}}Cn.Config.register([".yml",".yaml"],qn),Cn.Config.register([".json"],(function(t){return JSON.parse(t)}));var Gn=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}},Xn=require("events-ex"),Yn=32;function Qn(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 tr=class{constructor(t){this._capacity=Qn(t),this._length=0,this._front=0,this.arr=[]}push(t){const e=this._length;this.checkCapacity(e+1);const n=this._front+e&this._capacity-1;return this.arr[n]=t,this._length=e+1,n}pop(){const t=this._length;if(0===t)return;const e=this._front+t-1&this._capacity-1,n=this.arr[e];return this.arr[e]=void 0,this._length=t-1,n}shift(){const t=this._length;if(0===t)return;const e=this._front,n=this.arr[e];return this.arr[e]=void 0,this._front=e+1&this._capacity-1,this._length=t-1,n}get length(){return this._length}checkCapacity(t){this._capacity<t&&this.resizeTo(Qn(1.5*this._capacity+16))}resizeTo(t){const e=this._capacity;this._capacity=t;const n=this._front,r=this._length;if(n+r>e){const t=n+r&e-1;!function(t,e,n,r,s){for(let i=0;i<s;++i)n[i+r]=t[i+e],t[i+e]=void 0}(this.arr,0,this.arr,e,t)}}},er=class extends Xn.EventEmitter{};function nr(t){return"function"==typeof t}function rr(){return"1"}var sr=class{constructor(t,{initFn:e=rr,pauseFn:n,resumeFn:r,capacity:s=Yn}={}){if(nr(n)!==nr(r))throw new Error("pauseFn and resumeFn must be both set for pausing");this.maxConcurrency=t,this.free=new tr(t),this.waiting=new tr(s),this.releaseEmitter=new er,this.useDefaultTokens=e===rr,this.pauseFn=n,this.resumeFn=r,this.paused=!1,this.releaseEmitter.on("release",(t=>{const e=this.waiting.shift();e?e.resolve(t):(this.resumeFn&&this.paused&&(this.paused=!1,this.resumeFn()),this.free.push(t))}));for(let n=0;n<t;n++)this.free.push(e())}tryAcquire(){return this.free.pop()}acquire(t){let e=this.tryAcquire();return void 0!==e?Promise.resolve(e):new Promise(((e,n)=>{this.pauseFn&&!this.paused&&(this.paused=!0,this.pauseFn());const r=this.waiting.push({resolve:e,reject:n});return t&&t.addEventListener("abort",(()=>{this.waiting[r]=void 0;const e=t.reason instanceof Error?t.reason:new Error(t.reason||"aborted");t.alreadyRejected=!0,n(e)})),r}))}release(t){this.releaseEmitter.emit("release",this.useDefaultTokens?"1":t)}drain(){const t=new Array(this.maxConcurrency);for(let e=0;e<this.maxConcurrency;e++)t[e]=this.acquire();return Promise.all(t)}pendingCount(){return this.waiting.length}};function ir(t,{timeUnit:e=1e3,uniformDistribution:n=!1}={}){const r=new sr(n?1:t),s=n?e/t:e;return async function(){await r.acquire(),setTimeout((()=>r.release()),s)}}var or,ar=require("custom-ability"),cr=require("property-manager"),ur=require("util-ex"),lr=0,fr=1,hr=2,pr=(t=>(t[t.MultiTask=lr]="MultiTask",t[t.Cancelable=fr]="Cancelable",t[t.Priority=hr]="Priority",t))(pr||{}),wr=((or=wr||{})[or.MultiTask=1<<lr]="MultiTask",or[or.Cancelable=1<<fr]="Cancelable",or[or.Priority=1<<hr]="Priority",or),dr=class t extends cr.AdvancePropertyManager{static{this.items={}}static get(t){return this.items[t]}static list(){return this.items}static getByTag(t){let e;for(const n in this.list()){const r=this.get(n);let s=r.tags;if("string"==typeof s){if(s===t){e=r;break}}else if(Array.isArray(s)&&s.indexOf(t)>=0){e=r;break}}return e}static getAllByTag(t){let e=[];for(const n in this.list()){const r=this.get(n);let s=r.tags;"string"==typeof s?s===t&&e.push(r):Array.isArray(s)&&s.indexOf(t)>=0&&e.push(r)}return e}static hasAsyncFeature(t){const e=this.prototype;let n=e.asyncFeatures;return e._asyncFeatures&&(n|=e._asyncFeatures),Gn.has(n,t)}static run(t,e){const n=this.get(t);if(n)return n.run(e);throw new w.NotFoundError(`${t} to run`,this.name)}static runSync(t,e){const n=this.get(t);if(n)return n.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 n=this.get(t);if(n)return n.runWithPos(...e);throw new w.NotFoundError(`${t} to run`,this.name)}static runWithPosSync(t,...e){const n=this.get(t);if(n)return n.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,n={}){switch(typeof e){case"string":n.name=e;break;case"function":n.func=e;break;case"object":n=e}e=n.name;let r=!!this.get(e);if(r)r=!1;else{if(!(n instanceof t))return r=new this(n),r.register();this.items[e]=n,r=n}return r}static unregister(t){const e=this.items[t];return e&&delete this.items[t],e}constructor(t,e={}){switch(super(),typeof t){case"string":e.name=t;break;case"function":e.func=t;break;case"object":e=t}this.name=t=e.name,e.scope&&(this.scope=e.scope),"function"==typeof e.setup&&e.setup.call(this,e),this.initialize(e)}register(){const e=this.constructor,n=this.depends;if(n){const e=Object.keys(n);for(const r of e){const e=n[r];e instanceof t&&e.register()}}return e.register(this)}unregister(){return this.constructor.unregister(this.name)}arr2ObjParams(t){if(this.params&&(t.length>1||Array.isArray(t[0])||t[0]&&"object"!=typeof t[0])){const e={},n=Object.keys(this.params);let r=Math.min(n.length,t.length);for(let s=0;s<r;s++)e[n[s]]=t[s];t=[e]}return t}obj2ArrParams(t){const e=[];if(t&&this.params&&Array.isArray(this.params)){const n=Object.keys(t);let r=Math.min(n.length,this.params.length);for(let s=0;s<r;s++)e.push(t[n[s]])}return e}runSync(t){const e=this.params&&Array.isArray(this.params);if(Array.isArray(t)){if(e)return this.func(...t);(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),Gn.has(e,t)}isStream(t){return this.stream}},mr={name:{type:"string"},description:{type:"string"},func:{type:"function",assign(t,e,n,r,s){let i=t;const o=typeof t;return s.isExported?i="function"===o?t.toString():t:t&&("string"!==o&&(t=t.toString()),i=(0,ur._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"}};dr.defineProperties(dr,mr);var yr=require("util-ex"),br=class extends AbortController{constructor(t){super(),(0,yr.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")}}},gr=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 sr(t-1)),e}isAborted(t){const e=this.hasAsyncFeature(lr);let n=this.__task_aborter;if(n&&e){if(null==t)throw new w.CommonError("Missing taskId",this.name+".isAborted",w.ErrorCode.InvalidArgument);n=n[t]}return!n||n.signal.aborted}getRunningTask(t){const e=this.hasAsyncFeature(lr);let n=this.__task_aborter;if(n&&e){if(null==t)throw new w.CommonError("Missing taskId",this.name+".getRunningTask",w.ErrorCode.InvalidArgument);n=n[t]}return n?.signal.aborted&&(e?this.__task_aborter[t]=void 0:this.__task_aborter=void 0,n=void 0),n}getRunningTaskCount(){let t;if(this.hasAsyncFeature(lr)){const e=this.__task_aborter;t=e&&Object.entries(e).filter((([t,n])=>{if(!n?.signal.aborted)return!0;e[t]=void 0})).length}else{const e=this.__task_aborter;t=e?.signal.aborted?0:1}return t}_generateAsyncTaskId(t,e){if(e||(e=this.__task_aborter),null==t&&(t=0,e))for(;e[t];)t++;return t}$generateAsyncTaskId(t,e){const n=this.super,r=this.self||this;return t=n?n.call(r,t):this._generateAsyncTaskId(t,e)}createAborter(t,e,n=!0){const r=this.hasAsyncFeature(lr);if(!r&&n&&this.getRunningTask())throw new w.CommonError("The task is running",this.name,w.ErrorCode.TooManyRequests);const s=t?.aborter||new br(this);if(!(s instanceof br)){if(!(s instanceof AbortController))throw new w.CommonError("aborter should be an AbortController",this.name,w.ErrorCode.InvalidArgument);Object.setPrototypeOf(s,new br(this))}if(r){null==this.__task_aborter&&(this.__task_aborter={});const t=this.__task_aborter;null==e&&(e=this.generateAsyncTaskId(e,t)),s.id=e,t[e]=s}else this.__task_aborter=s;const i=t?.timeout;return i>0&&(s.timeoutId=setTimeout((()=>{s.timeoutId=void 0,this.abort("timeout",{timeout:i})}),i)),s.signal.addEventListener("abort",(()=>{const t=s.timeoutId;t&&(s.timeoutId=void 0,clearTimeout(t));const e=s.signal;try{this.emit&&this.emit("aborting",e.reason,e.reason?.data)}finally{s.streamController?.error(e.reason)}})),s}$cleanMultiTaskAborter(t,e){const n=this.super,r=this.self||this;n?n.call(r,t,e):r._cleanMultiTaskAborter(t,e)}cleanTaskAborter(t){if(this.hasAsyncFeature(lr)){const e=this.__task_aborter;this.cleanMultiTaskAborter(t.id,e)}else this.__task_aborter=void 0}_cleanMultiTaskAborter(t,e){"number"==typeof t?e[t]=void 0:delete e[t]}createTaskPromise(t,e,n){const r=this.createAborter(e,n?.taskId,n?.raiseError);void 0===e&&(e={}),"object"==typeof e&&(e.aborter=r);let s=t(e,r).then((t=>{if(t&&t instanceof ReadableStream){const e=()=>{this.cleanTaskAborter(r)},n=Te({onStart:t=>{(0,yr.defineProperty)(r,"streamController",t)},onFinal:e,onError:e,onTransform:(t,e)=>(t&&"object"==typeof t&&(t.taskId=r.id),t)});t=t.pipeThrough(n)}else this.cleanTaskAborter(r);return t})).catch((t=>{throw this.cleanTaskAborter(r),t})).finally((()=>{r.timeoutId&&(clearTimeout(r.timeoutId),r.timeoutId=void 0)}));return s.task=r,s}runAsyncCancelableTask(t={},e,n){let r=this.createTaskPromise(e,t,n);const s=this.semaphore;if(s){const t=r,e=t.task;r=s.acquire(e.signal).then((()=>t)).finally((()=>{s.release()})),r.task=e}return r}abort(t,e){let n=this.__task_aborter;if(n){const r=n;if(this.hasAsyncFeature(lr)){const t=e?.taskId;if(null==t)throw new w.CommonError("Missing data.taskId",this.name+".abort",w.ErrorCode.InvalidArgument);n=n[t],this.cleanMultiTaskAborter(t,r)}else this.__task_aborter=void 0;n&&!n.signal.aborted&&n.abort(t,e)}}};gr.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},gr.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};var vr=(0,ar.createAbilityInjector)(gr,"abort",{afterInjection:function(t,e){let n=t.prototype._asyncFeatures||0;n|=wr.Cancelable,e&&(e.asyncFeatures&&(n|=e.asyncFeatures),e.maxTaskConcurrency>0&&(t.prototype._maxTaskConcurrency=e.maxTaskConcurrency)),t.prototype._asyncFeatures=n}});function Er(t,e){const n=e.global?e:new RegExp(e.source,`${e.flags}g`);let r,s=0;for(;null!==(r=n.exec(t));)s++;return s}var xr=require("lodash-es"),$r=require("util-ex");async function Sr(t,e,n){return Ar(Rr(t,e,n),e,n)}function kr(t){if(t&&!Array.isArray(t)&&"object"==typeof t){const e=Object.entries(t),n=Object.keys(t);1===e.length&&void 0!==t[0]?t=t[0]:n.every((t=>!isNaN(parseInt(t))))?t=n.sort(((t,e)=>parseInt(t)-parseInt(e))).map((e=>t[e])):2===e.length&&"0"===e[0][0]&&e[0][1]===e[1][1]&&(t=t[0])}return t}async function Ar(t,e,n){if(t.length){const r=await Promise.all(t.map(((t,r)=>Pr(t,r,e,n)))),s=n?.returnArrayOnly;let i;if(r?.length){i=pn(`{${r.map((t=>t)).join(",")}}`,e)}return i&&!s&&(i=kr(i)),i}}function Or(t,e,n,r){const[s,i]=t;if(!s&&"|"===i[0])return"choice: {"+function(t,e,n){const r=Rr(t,e,{...n,delimiter:":"}),s={},i=r.map((([t,e],n)=>{if(t){const t=e.indexOf(":"),n=e.slice(0,t).trim();if(s[n])throw new Error("Only one "+n+" is allowed");return s[n]=!0,e}{if("|"===e[0]){if(s.items)throw new Error("Only one items is allowed");return s.items=!0,"items:["+function(t,e='"'){return t.map((t=>Cr(t)?t:e+t+e))}(e.split("|").filter(Boolean))+"]"}const t=parseInt(e.trim());if(!isNaN(t)){if(s.maxPick)throw new Error("Only one maxPick is allowed");return s.maxPick=!0,"maxPick:"+t}if("random"===e||"ai"===e)return s.type=!0,'type:"'+e+'"';if(Cr(e)){if(s.separator)throw new Error("Only one separator is allowed");return s.separator=!0,"separator:"+e}}}));return i}(i,n,r)+"}"}async function Tr([t,e],n,r,s){if(!r)return;let i,o;if(t){const t=e.split(":");i=t[0].trim(),o=t[1].trim()}else o=e,i=n+"";const a={template:o,data:{...r,...s?.templateData}};s?.templateFormat&&(a.templateFormat=s.templateFormat);const c=await j.formatIf(a);return c?(o=c,i+":"+JSON.stringify(o)):void 0}async function jr(t,e,n,r){let s=Or(t,0,n,r);return s||(s=await Tr(t,e,n,r)),s}function Cr(t){const e=t[0];return('"'===e||"'"===e)&&t[t.length-1]===e}function Nr(t){return'"'+t.replace(/(?<!\\)"(?!\\)/g,'\\"')+'"'}var Fr=["true","false","null","undefined","NaN","Infinity"];function Ir(t){return function(t,e=['""',"''","{}"]){return e.some((e=>t[0]===e[0]&&t[t.length-1]===e[1]))}(t)||!Number.isNaN(parseFloat(t))||Fr.includes(t)||Br(t)}async function Mr(t,e){const n=(0,$r.newFunction)("async expression",[],`return ${t};`,mn(e));let r=await n.call(this);switch(typeof r){case"number":case"boolean":case"undefined":return r;case"function":return n.toString();default:return JSON.stringify(r)}}async function Pr(t,e,n,r){const[s,i]=t,o=r?.argProcessor;if("function"==typeof o){const s=await o(t,e,n,r);if(s)return s}if(s){const t=i.indexOf(":"),e=i.slice(0,t).trim(),r=i.slice(t+1).trim();if(!(Ir(r)||n&&void 0!==(0,xr.get)(n,r)))return e+":"+Nr(r);if(!Br(i))try{return e+":"+await Mr.call(this,r,n)}catch(t){}return i}{const t=i.trim();if(n&&void 0!==(0,xr.get)(n,t))return e+":"+t+', "'+t+'":'+t;if(Ir(t))return e+":"+t;if(!Br(i))try{return e+":"+await Mr.call(this,t,n)}catch(t){}return e+":"+Nr(t)}}function Rr(t,e,n){const r=n?.delimiter??",";let s=[],i=!1,o="",a="",c=!1,u="";for(let e=0;e<t.length;e++){const n=t[e];if(n!==r||i||u)if("\\"===n)a+=n,e++,a+=t[e];else if("("!==n&&"["!==n||i)if(u&&n===u)u="",a+=n;else if("{"!==n||i)'"'===n||"'"===n?(i&&n===o?i=!1:i||(i=!0,o=n),a+=n):"="!==n||i||c||!/^[\p{L}\p{N}_ ]+$/u.test(a)?a+=n:(a+=":",c=!0);else{let r,s=e,i=!1,o="",c=-1;for(;s<t.length&&("}"!==(r=t[s])||i||c>0);)"\\"===r?s++:"{"!==r||i?"}"!==r||i?'"'!==r&&"'"!==r||(i&&n===o?i=!1:i||(i=!0,o=n)):c--:c++,s++;s<t.length&&(a+=t.substring(e,s+1),e=s)}else u="("===n?")":"]",a+=n;else a=a.trim(),a.endsWith(":")&&(a+="undefined"),s.push([c,a]),a="",c=!1}return a&&(a=a.trim(),a.endsWith(":")&&(a+="undefined"),s.push([c,a])),s}async function qr(t,e,n){const r=t.match(/^([^(]+)(?:\((.*)\))?$/);if(!r)throw new Error("Invalid command format");const[,s,i]=r;let o;return i&&(o=await Sr(i,e,n)),{command:s.trim(),args:o}}var Vr=/^\s*\(\)|[a-zA-Z_$][\w\d$]*|\(([a-zA-Z_$][\w\d$]*)(\s*,\s*([a-zA-Z_$][\w\d$]*))*\)\s*=>/;function Br(t){return Vr.test(t)}var Ur=c(require("memoizee")),_r=require("json-canonicalize");function Lr(t,e){var n;void 0!==e?.promise||!function(t){return"function"==typeof t&&"AsyncFunction"===t.constructor.name}(t)&&(!(n=t)||"object"!=typeof n&&"function"!=typeof n||"function"!=typeof n.then)||(e={promise:!0,...e}),void 0===e?.length&&(e={length:!1,...e});const r=e?.normalizer;return(0,Ur.default)(t,{...e,normalizer:t=>{if(r){const e=r(t);if("string"===e)return e;e&&(t=e)}return Je((0,_r.canonicalize)(t))}})}var zr=c(require("net"));async function Dr(t,e=10){return new Promise(((n,r)=>{void 0===t?t=0:("string"==typeof t&&(t=parseInt(t)),t>=0||(t=0));const s=zr.default.createServer();s.on("error",(n=>{"EADDRINUSE"===n.code&&(t++,--e>0)?s.listen(t):r(n)})),s.on("listening",(async()=>{const t=s.address().port;s.close(),n(t)})),s.listen(t)}))}var Jr=c(require("path")),Wr=require("pkg-dir");function Kr(t){const e=(0,Wr.packageDirectorySync)({cwd:t});if(e)return e;const n=t.split(Jr.default.sep);let r=n.lastIndexOf("dist");if(r>0)return n.slice(0,r).join(Jr.default.sep);if(r=n.lastIndexOf("src"),r>0)return n.slice(0,r).join(Jr.default.sep);throw new Error("can not find package directory")}var Hr=class t extends dr{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 n in e){const r=this.get(n),s=e[n];r?r instanceof t?r.assign(s):(0,w.throwError)(`${n} already registered as ${r.constructor.name}`,"ClientTools"):this.register(s)}}static async fetch(t,e){const n=this.get(t);if(n&&n.fetch)return n.fetch(e)}getUrlParams(t){if(void 0!==t){const e=JSON.stringify(t);if("{}"!==e&&"[]"!==e&&'""'!==e)return"?p="+encodeURIComponent(e)}return""}async fetch(t,e,n){const r={...this.fetchOptions};let s;r.headers&&r.headers["Content-Type"]||(r.headers={"Content-Type":"application/json",...r.headers}),t?.stream&&!r.headers.Connection&&(r.headers.Connection="keep-alive"),e||(e=this.action||"post"),"res"===e&&(e="get"),n?("string"!=typeof n&&(n=JSON.stringify(n)),n=this.name+"/"+n):n=this.name,r.method=e.toUpperCase(),"get"===e||"delete"===e?s=n+this.getUrlParams(t):(r.body=JSON.stringify(t),s=n);const i=await fetch(`${this.apiRoot}/${s}`,r);if(!i.ok){throw await this.errorFrom(i)}return i}async errorFrom(t){let e,n=t.status,r=t.statusText,s=this.name;if(t.body){const n=await t.text();try{const t=JSON.parse(n);t&&(t.error&&(r=t.error),t.name&&(s=t.name),t.data&&(e=t.data,e.name=s,e.what&&(e.msg=r,r=e.what)),t.message&&(r=r+":"+t.message))}catch(t){console.warn("🚀 ~ parse error body to json:",t)}}return(0,w.createError)(r,s,n)}async func(t){const e=await this.fetch(t);if(t?.stream)return e;return await e.json()}},Zr={...p};Hr.defineProperties(Hr,Zr);var Gr=class t extends dr{static get apiRoot(){return this._apiRoot}static setApiRoot(t){this._apiRoot=t}static toJSON(){const e={};for(const n in this.items){let r=this.items[n];(r instanceof t||r.isApi)&&(r.allowExportFunc||(r=r.toJSON(),delete r.func),e[n]=r)}return e}func({}){}},Xr={...p};Gr.defineProperties(Gr,Xr);var Yr=require("events-ex"),Qr=class extends dr{constructor(){super(...arguments),this._emitter=new Yr.EventEmitter,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},ts=new Qr(he),es=require("secondary-cache");function ns({key:t,value:e,options:n}={}){return void 0!==t?null===e?this.cache.del(t):void 0!==e?this.cache.set(t,e,n):this.cache.get(t):(n&&this.cache.setDefaultOptions(n),this.cache)}function rs(t,e){let n=dr.get(t);return n||(n=new dr(t,{func:ns,description:"get/set LRU cache or return the LRUCache object",params:{key:{name:"key",type:"string",description:"the key is undefined means change the default cache options"},value:{name:"value",type:"any",description:"the value to store, if value is null means remove the key"},options:{name:"options",type:"object|number",description:"the optional cache options:{capacity,expires,cleanInterval} or expires"}},result:"any"}),n.cache=new es.Cache(e)),n}var ss=rs("lrucache"),is=class extends Hr{async _func(t,e){const n=await this.fetch(e,t);if(e?.stream)return n;return await n.json()}async func(t){const e=t.action;return e&&delete t.action,this._func(e,t)}assignMethods(t){if(Array.isArray(t))for(const e of t){const t=e.startsWith("$")?e.slice(1):e;this[t]||(this[t]=(t=>this._func.bind(this,t))(e))}}},os={methods:{type:"array",assign(t,e,n,r,s){s?.isExported||e.assignMethods(t)}}};is.defineProperties(is,os);var as=class extends is{async fetch(t,e){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let n=t.id;return n||(0,w.throwError)("id is required"),"string"==typeof n&&(n=encodeURIComponent(n)),delete t.id,super.fetch(t,e,n)}"list"===e?e="get":e.startsWith("$")&&(t.act=e,e="post")}return await super.fetch(t,e)}},cs=class extends as{constructor(){super(...arguments),this._sseEvents={},this._forwardEvents=new Set,this.name=fe,this.description="subscribe server sent event",this.ebListener=async function(...t){const e=this.type;this.target.publish&&await this.target.publish({data:t,event:e})}}get evtSource(){let t=this._es;return t&&t.readyState!==EventSource.CLOSED||(t=this.initEventSource(this._esEvents)),t}get active(){return!!this._es&&this._es.readyState!==EventSource.CLOSED}set active(t){t!==this.active&&(t?this.initEventSource(this._esEvents):this._es&&(this._es.close(),this._es=void 0))}initEventSource(t){if("string"==typeof t&&(t=[t]),this._es&&this._es.readyState!==EventSource.CLOSED){if(!this._esEvents||t&&t.every((t=>this._esEvents.includes(t))))return this._es;this._es.close()}const e=t?this.getUrlParams({event:t}):"",n=`${this.apiRoot}/${this.name}${e}`,r=this._es=new EventSource(n);return Object.entries(this._sseEvents).forEach((([t,e])=>{r.addEventListener(t,e)})),this._esEvents=t,r}esListener(t){const e=t.data?JSON.parse(t.data):void 0,n=t.type;if(!this._forwardEvents.has(n)){const t=this.emitter;t&&e&&n&&(Array.isArray(e)?t.emit(n,...e):t.emit(n,e))}}async subscribe(t){const e=await this.sub({event:t});"string"==typeof t&&(t=[t]);const n=this.evtSource;for(const e of t)if(!this._sseEvents[e]){const t=this._sseEvents[e]=this.esListener.bind(this);n.addEventListener(e,t)}return e}async unsubscribe(t){const e=await this.unsub({event:t});"string"==typeof t&&(t=[t]);for(const e of t){const t=this._sseEvents[e];t&&(delete this._sseEvents[e],this.evtSource.removeEventListener(e,t))}return e}forwardEvent(t){"string"==typeof t&&(t=[t]);for(const e of t)this._forwardEvents.has(e)||(this._forwardEvents.add(e),this.on&&this.on(e,this.ebListener))}unforwardEvent(t){"string"==typeof t&&(t=[t]);for(const e of t)this._forwardEvents.has(e)&&(this._forwardEvents.delete(e),this.off&&this.off(e,this.ebListener))}async init(t){if(this.active=!1,this.initEventSource(t),t)return await this.subscribe(t)}},us=new cs(fe),ls=require("util-ex"),fs=class extends Gr{constructor(t,e={}){super(t,e),this.params={act:{type:"string"}};const n=this.methods=[];this.initRpcMethods(n)}get SpecialRpcMethodNames(){return this.constructor.SpecialRpcMethodNames}initRpcMethods(t=this.methods){const e=this.SpecialRpcMethodNames;if(Array.isArray(e))for(const n of e)"function"==typeof this[n]&&t.push(n);(0,ls.getAllNames)(Object.getPrototypeOf(this)).filter((t=>t.startsWith("$")&&"function"==typeof this[t])).forEach((e=>{t.push(e);const n=e.slice(1);void 0===this[n]&&(this[n]=this[e])}))}cast(t,e){let n=this.params[t];return n&&("string"!=typeof n&&(n=n.type),"number"===n&&(e=Number(e))),e}getMethodFromParams(t){const e=t?.act;return e}castParams(t){return t}func(t){const e=this.getMethodFromParams(t);if(e&&"function"==typeof this[e])return t=this.castParams(t),this[e](t);throw new w.NotFoundError(e,this.name)}};fs.defineProperties(fs,{methods:{type:"array"}});var hs=class extends fs{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}}}static{this.SpecialRpcMethodNames=h}getMethodFromParams(t){let e=t?._req?.method?.toLowerCase();return"get"===e&&void 0===t.id&&(e="list"),"post"===e&&t.act&&(e=t.act),e}castParams(t){return void 0!==t.id&&(t.id=this.cast("id",t.id)),t}},ps=ts.runSync(),ws=class t extends hs{constructor(){super(...arguments),this.name=fe,this.description="subscribe server sent event",this.result="event",this.depends={[he]:ts}}static get sse(){return this._sse||(this._sse=new me),this._sse}get sse(){return this.constructor.sse}static publish(e,n){return t.sse.publish(e,n)}static{this.ebListener=function(...e){t.sse.publish(e,this.type)}}static subscribe(e,n,r){return t.sse.subscribe(e,n,r)}static alreadyForward(e){const n=ps.listeners(e);for(const e of n)if(e===t.ebListener)return!0}publishSSE(t,e){return this.constructor.publish(t,e)}subscribeSSE(t,e,n){return"string"==typeof n&&(n=[n]),this.constructor.subscribe(t,e,n)}forward(e){Array.isArray(e)||(e=[e]);for(const n of e)t.alreadyForward(n)||ps.on(n,t.ebListener)}unforward(e){"string"==typeof e&&(e=[e]);for(const n of e)ps.off(n,t.ebListener)}list({_req:t,_res:e,event:n}){t&&e&&this.subscribeSSE(t,e,n)}$sub({event:t}){if(t)return this.forward(t),{event:t};(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 n of t)this.publishSSE(e,n);return{event:t}}(0,w.throwError)("event or data is required","pub",w.ErrorCode.InvalidArgument)}isStream(t){return"list"===this.getMethodFromParams(t)}},ds=new ws(fe);function ms(){ts.register(),ss.register()}
1
+ "use strict";var t,e=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,i=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,a=(t,e,i,a)=>{if(e&&"object"==typeof e||"function"==typeof e)for(let c of s(e))o.call(t,c)||c===i||n(t,c,{get:()=>e[c],enumerable:!(a=r(e,c))||a.enumerable});return t},c=(t,r,s)=>(s=null!=t?e(i(t)):{},a(!r&&t&&t.__esModule?s:n(s,"default",{value:t,enumerable:!0}),t)),u={};((t,e)=>{for(var r in e)n(t,r,{get:e[r],enumerable:!0})})(u,{AIArgProcessor:()=>Cr,AIChatRoles:()=>S,AIMessageTypes:()=>$,AIStream:()=>Oe,AITextGenerationFinishReasons:()=>x,AbortError:()=>d.AbortError,AbortErrorCode:()=>d.AbortErrorCode,ActionNames:()=>p,AlreadyExistsError:()=>d.AlreadyExistsError,AlreadyExistsErrorCode:()=>d.AlreadyExistsErrorCode,AsyncFeatureBits:()=>wr,AsyncFeatures:()=>dr,BaseError:()=>d.BaseError,CancelableAbility:()=>vr,ChoiceArgProcessor:()=>Tr,ClientToolFuncSchema:()=>es,ClientTools:()=>ts,CommonError:()=>d.CommonError,ConfigFile:()=>Nn.Config,DefaultAsyncSemaphoreCapacity:()=>Qn,ErrorCode:()=>d.ErrorCode,EventBusName:()=>pe,EventClient:()=>ws,EventName:()=>he,EventServer:()=>vs,EventToolFunc:()=>is,FStringPromptTemplate:()=>Dt,FewShotPromptTemplate:()=>Zt,FilenameReservedRegex:()=>He,GolangPromptTemplate:()=>Kt,HFBuiltins:()=>Ft,HFEnvironment:()=>Mt,HFInterpreter:()=>Tt,HFTemplate:()=>Pt,HfPromptTemplate:()=>Bt,IntSet:()=>Xn,InternalErrorCode:()=>d.InternalErrorCode,NotFoundError:()=>d.NotFoundError,NotFoundErrorCode:()=>d.NotFoundErrorCode,NotImplementationError:()=>d.NotImplementationError,NotImplementedErrorCode:()=>d.NotImplementedErrorCode,PASSING_SCORE:()=>h,PromptExampleSelector:()=>I,PromptTemplate:()=>C,PromptTemplateTypes:()=>O,PromptTypes:()=>A,RStreamErrCode:()=>ge,RateLimit:()=>or,ReadableStreamError:()=>Ee,RemoteToolFuncSchema:()=>w,ResClientTools:()=>ps,ResServerTools:()=>bs,ResponseRStreamErrCode:()=>ve,SSEChannel:()=>ye,SSEChannelAlreadyClosedErrCode:()=>me,Semaphore:()=>ir,ServerToolFuncSchema:()=>rs,ServerTools:()=>ns,TaskAbortController:()=>gr,TemplateArgProcessor:()=>jr,ToolAsyncCancelableBit:()=>hr,ToolAsyncMultiTaskBit:()=>fr,ToolAsyncPriorityBit:()=>pr,ToolFunc:()=>mr,ToolFuncSchema:()=>yr,WindowsReservedNameRegex:()=>Ze,XXHashAlgorithm:()=>De,_lrucache:()=>cs,backendEventable:()=>we,base32768:()=>Ve,canonicalize:()=>qe.canonicalize,countRegexMatches:()=>xr,createAbilityInjector:()=>l.createAbilityInjector,createCallbacksTransformer:()=>je,createEmptyReadableStream:()=>$e,createEndWithRepetitionDetector:()=>vn,createError:()=>d.createError,createEventStreamTransformer:()=>ke,createHfValueFunc:()=>Ut,createLRUCache:()=>us,dateToText:()=>E,defaultTemplateFormat:()=>j,event:()=>os,eventClient:()=>ds,eventServer:()=>Es,expandEnv:()=>Qt,expandObjEnv:()=>te,extNameLevel:()=>cn,fileIsExists:()=>$n,filenameReservedRegex:()=>tn,filterValidFnScope:()=>yn,findPort:()=>Jr,formatISO:()=>y.formatISO,getAllEnumKeys:()=>fn,getConfigFileNames:()=>Bn,getConfigs:()=>Un,getKeysPath:()=>bn,getMultiLevelExtname:()=>an,getPackageDir:()=>Hr,getRealFilepath:()=>Tn,getResponseErrorReadableStream:()=>xe,hasDirectoryIn:()=>Xr,hfParse:()=>ht,hfTokenize:()=>_,interpolateEnv:()=>Yt,interpolateFString:()=>Lt,interpolateGolangTemplate:()=>Wt,isModelNameMatched:()=>ln,isRegExp:()=>Qr,isSubdirectory:()=>Gr,isValidFilename:()=>nn,isValidFilepath:()=>rn,isWebStream:()=>be,jsonFilterToWhere:()=>Wn,jsonToMarkdownStr:()=>Gn,loadFileFromPaths:()=>Sn,loadTextFromPaths:()=>An,lrucache:()=>ls,makeToolFuncCancelable:()=>Er,matchUrlProtocol:()=>Kn,memoize:()=>zr,messagesToText:()=>k,mimeType:()=>Mn.mimeType,paramsSizeToScaleStr:()=>Hn,parseCommand:()=>Vr,parseDateFormat:()=>m.parse,parseFString:()=>_t,parseISO:()=>y.parseISO,parseJsJson:()=>wn,parseObjectArgInfo:()=>Rr,parseObjectArgumentInfos:()=>Or,parseObjectArguments:()=>kr,parseObjectArgumentsAsArgInfos:()=>qr,parseYaml:()=>qn,quoteStr:()=>Fr,reControlCharsRegex:()=>en,readFilenamesRecursiveSync:()=>On,readableFromAsyncIterable:()=>Te,registerCoreTools:()=>xs,registerYamlTag:()=>Rn,sanitizeFilename:()=>sn,sanitizeFilepath:()=>on,saveConfigFile:()=>_n,scaleStrToParamsSize:()=>Zn,simplifyObjectArguments:()=>Ar,sortedValues:()=>Ht,splitSentence:()=>ce,stringifyYaml:()=>Vn,textToDate:()=>v,throwError:()=>d.throwError,toDate:()=>y.toDate,toDateTime:()=>g,toRegExp:()=>f.toRegExp,trimStartOfStreamHelper:()=>Ae,truncTo:()=>ue,uuid:()=>Me,uuidNIL:()=>Fe.NIL,uuidParse:()=>Fe.parse,uuidStringify:()=>Fe.stringify,uuidValidate:()=>Fe.validate,uuidVersion:()=>Fe.version,uuidv1:()=>Fe.v1,uuidv4:()=>Fe.v4,uuidv5:()=>Fe.v5,wait:()=>le,xxhash:()=>Je,xxhash32:()=>Le,xxhash64:()=>ze,xxhashAsStr:()=>We}),module.exports=(t=u,a(n({},"__esModule",{value:!0}),t));var l=require("custom-ability"),f=require("util-ex"),h=.618,p=["get","post","put","delete","patch","list","res"],w={apiRoot:{type:"string",get(){return this._apiRoot??this.constructor.apiRoot},set(t){this._apiRoot=t}},action:{type:"string",assign:(t,e,n,r,s)=>t||"post"},fetchOptions:{type:"object"},allowExportFunc:{type:"boolean"}},d=require("@isdk/common-error"),m=require("date-fns"),y=require("date-fns"),b="MMMM d, y 'at' h:m:s b 'GMT'x";function g(t){let e;try{"string"==typeof t?e=(0,m.parseISO)(t):"number"==typeof t?e=new Date(t):t instanceof Date&&(e=t)}catch(t){console.error(t)}return e}function v(t,e=b){return(0,m.parse)(t,e,new Date)}function E(t,e=b){return(0,m.format)(t,e)}var x=["stop","length","content_filter","tool_calls","function_call","abort","error","other",null],$=["human","ai","generic","system","tool"],S=["user","assistant","system","tool","tool_calls"];function k(t){let e="";for(const n of t)if(n.content){e+=n.role.toLowerCase()+":";let t=n.createdAt;if(t){const n=g(t);n&&(e+=" ["+E(n)+"]")}e+=" "+n.content+"\n"}return e}var A=["chat","char","plan"],O=["internal","hf","fill"],T=require("custom-factory");var j="default",C=class t extends T.BaseFactory{static from(t,e){return new this(t,e)}static async format(t){return new this(t).format()}static async formatIf(t){if(this.isTemplate(t)){return new this(t).format()}}static isTemplate(e){if(e?.template){const n=e.templateFormat||j,r=t.get(n);return r.isTemplate!==t.isTemplate&&r.isTemplate(e)}}filterData(t){return Array.isArray(this.inputVariables)&&(t=Object.fromEntries(Object.entries(t).filter((([t])=>this.inputVariables.includes(t))))),t}constructor(e,n){"string"==typeof e?(n||(n={}),n.template=e):e&&(e=(n=e).template);const{templateFormat:r}=n||{};if(super(n),this.constructor===t){const e=t.get(r||j);if(e)return Reflect.construct(e,arguments);throw new d.CommonError(`Prompt template type ${r} not found`,"PromptTemplate",d.ErrorCode.InvalidArgument)}}_initialize(t){throw new d.NotImplementationError("Not implemented","PromptTemplate")}initialize(e){this.constructor!==t&&(Object.assign(this,this.toJSON(e)),e?.ignoreInitialize||this._initialize(e))}_format(t){throw new d.NotImplementationError("Not implemented","PromptTemplate")}async format(e){const n=this.data;if(e={...n,...e},n)for(const[t,r]of Object.entries(n))e[t]===r&&"function"==typeof r&&(delete e[t],e[t]=await r(e));for(const[n,r]of Object.entries(e))r instanceof t&&(delete e[n],e[n]=await r.format(e));return this._format(e)}partial(t){t={...this.data,...t};const e=this.toJSON();return e.data=t,e.ignoreInitialize=!0,new this.constructor(e)}toJSON(e=this){let n={template:e.template,data:e.data,inputVariables:e.inputVariables,compiledTemplate:e.compiledTemplate};var r;return e.templateFormat&&t.get(e.templateFormat)!==this.constructor&&(n.templateFormat=e.templateFormat),r=n,n=Object.keys(r).reduce(((t,e)=>{const n=r[e];return null!=n&&(t[e]=n),t}),{}),n}};function N(t){return(e=t)&&"function"==typeof e[Symbol.iterator]?async function*(t){const e=t[Symbol.iterator]();let n;try{for(;;){n=!1;const t=e.next();if(n=!0,t.done)return n=!1,await t.value;yield await t.value}}finally{n&&await(e.return?.().value)}}(t):t;var e}var F=!1;(async function(){let t=!1,e=!1;try{for await(const e of function*(){try{yield Promise.reject()}finally{t=!0}}())throw new Error("impossible")}catch{e=!0}return e&&t})().then((t=>{F=t}));var I=class{constructor(t,e){this.initialize(t,e)}initialize(t,e){const n=e?.maxLength;var r;n>0&&(this.maxLength=n),void 0!==e?.threshold&&(!0===e.threshold?this.threshold=.5:!1!==e.threshold&&(this.threshold=e.threshold)),this.examples=(r=t,F?r:N(r))}selectExample(t,e){if(void 0===e||e<=this.threshold)return t}async*selectExamples(t=this.examples){let e=this.maxLength||1/0;for await(const n of t){const t="number"==typeof this.threshold?Math.random():void 0;if(this.selectExample(n,t)){if(--e<0)break;yield n}}}async*[Symbol.asyncIterator](){yield*this.selectExamples()}},M=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"}),P=Object.freeze({set:M.Set,for:M.For,in:M.In,is:M.Is,if:M.If,else:M.Else,endif:M.EndIf,elif:M.ElseIf,endfor:M.EndFor,and:M.And,or:M.Or,not:M.Not,"not in":M.NotIn,macro:M.Macro,endmacro:M.EndMacro,true:M.BooleanLiteral,false:M.BooleanLiteral,True:M.BooleanLiteral,False:M.BooleanLiteral}),R=class{constructor(t,e){this.value=t,this.type=e}};function q(t){return/\w/.test(t)}function V(t){return/[0-9]/.test(t)}var B=[["{%",M.OpenStatement],["%}",M.CloseStatement],["{{",M.OpenExpression],["}}",M.CloseExpression],["(",M.OpenParen],[")",M.CloseParen],["{",M.OpenCurlyBracket],["}",M.CloseCurlyBracket],["[",M.OpenSquareBracket],["]",M.CloseSquareBracket],[",",M.Comma],[".",M.Dot],[":",M.Colon],["|",M.Pipe],["<=",M.ComparisonBinaryOperator],[">=",M.ComparisonBinaryOperator],["==",M.ComparisonBinaryOperator],["!=",M.ComparisonBinaryOperator],["<",M.ComparisonBinaryOperator],[">",M.ComparisonBinaryOperator],["+",M.AdditiveBinaryOperator],["-",M.AdditiveBinaryOperator],["*",M.MultiplicativeBinaryOperator],["/",M.MultiplicativeBinaryOperator],["%",M.MultiplicativeBinaryOperator],["=",M.Equals]],U=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function _(t,e={}){const n=[],r=function(t,e={}){return t.endsWith("\n")&&(t=t.slice(0,-1)),t=t.replace(/{#.*?#}/gs,"{##}"),e.lstrip_blocks&&(t=t.replace(/^[ \t]*({[#%])/gm,"$1")),e.trim_blocks&&(t=t.replace(/([#%]})\n/g,"$1")),t.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}(t,e);let s=0;const i=t=>{let e="";for(;t(r[s]);)if("\\"!==r[s]){if(e+=r[s++],s>=r.length)throw new SyntaxError("Unexpected end of input")}else{if(++s,s>=r.length)throw new SyntaxError("Unexpected end of input");const t=r[s++],n=U.get(t);if(void 0===n)throw new SyntaxError(`Unexpected escaped character: ${t}`);e+=n}return e};t:for(;s<r.length;){const t=n.at(-1)?.type;if(void 0===t||t===M.CloseStatement||t===M.CloseExpression){let t="";for(;s<r.length&&("{"!==r[s]||"%"!==r[s+1]&&"{"!==r[s+1]);)t+=r[s++];if(t.length>0){n.push(new R(t,M.Text));continue}}i((t=>/\s/.test(t)));const e=r[s];if("-"===e||"+"===e){const t=n.at(-1)?.type;if(t===M.Text||void 0===t)throw new SyntaxError(`Unexpected character: ${e}`);switch(t){case M.Identifier:case M.NumericLiteral:case M.BooleanLiteral:case M.StringLiteral:case M.CloseParen:case M.CloseSquareBracket:break;default:{++s;const t=i(V);n.push(new R(`${e}${t}`,t.length>0?M.NumericLiteral:M.UnaryOperator));continue}}}for(const[t,e]of B){if(r.slice(s,s+t.length)===t){n.push(new R(t,e)),s+=t.length;continue t}}if("'"!==e&&'"'!==e)if(V(e)){const t=i(V);n.push(new R(t,M.NumericLiteral))}else{if(!q(e))throw new SyntaxError(`Unexpected character: ${e}`);{const t=i(q),e=Object.hasOwn(P,t)?P[t]:M.Identifier;e===M.In&&n.at(-1)?.type===M.Not?(n.pop(),n.push(new R("not in",M.NotIn))):n.push(new R(t,e))}}else{++s;const t=i((t=>t!==e));n.push(new R(t,M.StringLiteral)),++s}}return n}var L=class{constructor(){this.type="Statement"}},z=class extends L{constructor(t){super(),this.body=t,this.type="Program"}},D=class extends L{constructor(t,e,n){super(),this.test=t,this.body=e,this.alternate=n,this.type="If"}},J=class extends L{constructor(t,e,n,r){super(),this.loopvar=t,this.iterable=e,this.body=n,this.defaultBlock=r,this.type="For"}},W=class extends L{constructor(t,e){super(),this.assignee=t,this.value=e,this.type="Set"}},K=class extends L{constructor(t,e,n){super(),this.name=t,this.args=e,this.body=n,this.type="Macro"}},H=class extends L{constructor(){super(...arguments),this.type="Expression"}},Z=class extends H{constructor(t,e,n){super(),this.object=t,this.property=e,this.computed=n,this.type="MemberExpression"}},G=class extends H{constructor(t,e){super(),this.callee=t,this.args=e,this.type="CallExpression"}},X=class extends H{constructor(t){super(),this.value=t,this.type="Identifier"}},Y=class extends H{constructor(t){super(),this.value=t,this.type="Literal"}},Q=class extends Y{constructor(){super(...arguments),this.type="NumericLiteral"}},tt=class extends Y{constructor(){super(...arguments),this.type="StringLiteral"}},et=class extends Y{constructor(){super(...arguments),this.type="BooleanLiteral"}},nt=class extends Y{constructor(){super(...arguments),this.type="ArrayLiteral"}},rt=class extends Y{constructor(){super(...arguments),this.type="TupleLiteral"}},st=class extends Y{constructor(){super(...arguments),this.type="ObjectLiteral"}},it=class extends H{constructor(t,e,n){super(),this.operator=t,this.left=e,this.right=n,this.type="BinaryExpression"}},ot=class extends H{constructor(t,e){super(),this.operand=t,this.filter=e,this.type="FilterExpression"}},at=class extends H{constructor(t,e){super(),this.iterable=t,this.test=e,this.type="SelectExpression"}},ct=class extends H{constructor(t,e,n){super(),this.operand=t,this.negate=e,this.test=n,this.type="TestExpression"}},ut=class extends H{constructor(t,e){super(),this.operator=t,this.argument=e,this.type="UnaryExpression"}},lt=class extends H{constructor(t=void 0,e=void 0,n=void 0){super(),this.start=t,this.stop=e,this.step=n,this.type="SliceExpression"}},ft=class extends H{constructor(t,e){super(),this.key=t,this.value=e,this.type="KeywordArgumentExpression"}};function ht(t){const e=new z([]);let n=0;function r(e,r){const s=t[n++];if(!s||s.type!==e)throw new Error(`Parser Error: ${r}. ${s.type} !== ${e}.`);return s}function s(){let e;switch(t[n].type){case M.Text:e=new tt(r(M.Text,"Expected text token").value);break;case M.OpenStatement:e=function(){let e;switch(r(M.OpenStatement,"Expected opening statement token"),t[n].type){case M.Set:++n,e=a(),r(M.CloseStatement,"Expected closing statement token");break;case M.If:++n,e=c(),r(M.OpenStatement,"Expected {% token"),r(M.EndIf,"Expected endif token"),r(M.CloseStatement,"Expected %} token");break;case M.Macro:++n,e=function(){const t=E();if("Identifier"!==t.type)throw new SyntaxError("Expected identifier following macro statement");const e=y();r(M.CloseStatement,"Expected closing statement token");const n=[];for(;i(M.OpenStatement,M.EndMacro);)n.push(s());return new K(t,e,n)}(),r(M.OpenStatement,"Expected {% token"),r(M.EndMacro,"Expected endmacro token"),r(M.CloseStatement,"Expected %} token");break;case M.For:++n,e=function(){const t=u(!0);if(!(t instanceof X||t instanceof rt))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${t.type} instead`);r(M.In,"Expected `in` keyword following loop variable");const e=l();r(M.CloseStatement,"Expected closing statement token");const a=[];for(;i(M.OpenStatement,M.EndFor)&&i(M.OpenStatement,M.Else);)a.push(s());const c=[];if(o(M.OpenStatement,M.Else))for(++n,++n,r(M.CloseStatement,"Expected closing statement token");i(M.OpenStatement,M.EndFor);)c.push(s());return new J(t,e,a,c)}(),r(M.OpenStatement,"Expected {% token"),r(M.EndFor,"Expected endfor token"),r(M.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${t[n].type} ${t[n].value}`)}return e}(),e.isStatement=!0;break;case M.OpenExpression:e=function(){r(M.OpenExpression,"Expected opening expression token");const t=l();return r(M.CloseExpression,"Expected closing expression token"),t}(),e.isStatement=!0;break;default:throw new SyntaxError(`Unexpected token type: ${t[n].type}`)}return e}function i(...e){return n+e.length<=t.length&&e.some(((e,r)=>e!==t[n+r].type))}function o(...e){return n+e.length<=t.length&&e.every(((e,r)=>e===t[n+r].type))}function a(){const t=l();if(o(M.Equals)){++n;const e=a();return new W(t,e)}return t}function c(){const e=l();r(M.CloseStatement,"Expected closing statement token");const i=[],a=[];for(;t[n]?.type!==M.OpenStatement||t[n+1]?.type!==M.ElseIf&&t[n+1]?.type!==M.Else&&t[n+1]?.type!==M.EndIf;)i.push(s());if(t[n]?.type===M.OpenStatement&&t[n+1]?.type!==M.EndIf)if(++n,o(M.ElseIf))r(M.ElseIf,"Expected elseif token"),a.push(c());else for(r(M.Else,"Expected else token"),r(M.CloseStatement,"Expected closing statement token");t[n]?.type!==M.OpenStatement||t[n+1]?.type!==M.EndIf;)a.push(s());return new D(e,i,a)}function u(t=!1){const e=t?E:l,r=[e()],s=o(M.Comma);for(;s&&(++n,r.push(e()),o(M.Comma)););return s?new rt(r):r[0]}function l(){return function(){const t=f();if(o(M.If)){++n;const e=f();if(o(M.Else)){++n;const r=f();return new D(e,[t],[r])}return new at(t,e)}return t}()}function f(){let e=h();for(;o(M.Or);){const r=t[n];++n;const s=h();e=new it(r,e,s)}return e}function h(){let e=p();for(;o(M.And);){const r=t[n];++n;const s=p();e=new it(r,e,s)}return e}function p(){let e;for(;o(M.Not);){const r=t[n];++n;const s=p();e=new ut(r,s)}return e??function(){let e=w();for(;o(M.ComparisonBinaryOperator)||o(M.In)||o(M.NotIn);){const r=t[n];++n;const s=w();e=new it(r,e,s)}return e}()}function w(){let e=g();for(;o(M.AdditiveBinaryOperator);){const r=t[n];++n;const s=g();e=new it(r,e,s)}return e}function d(){const e=function(){let e=E();for(;o(M.Dot)||o(M.OpenSquareBracket);){const s=t[n];let i;++n;const o=s.type!==M.Dot;if(o)i=b(),r(M.CloseSquareBracket,"Expected closing square bracket");else if(i=E(),"Identifier"!==i.type)throw new SyntaxError("Expected identifier following dot operator");e=new Z(e,i,o)}return e}();return o(M.OpenParen)?m(e):e}function m(t){let e=new G(t,y());return o(M.OpenParen)&&(e=m(e)),e}function y(){r(M.OpenParen,"Expected opening parenthesis for arguments list");const t=function(){const t=[];for(;!o(M.CloseParen);){let e=l();if(o(M.Equals)){if(++n,!(e instanceof X))throw new SyntaxError("Expected identifier for keyword argument");const t=l();e=new ft(e,t)}t.push(e),o(M.Comma)&&++n}return t}();return r(M.CloseParen,"Expected closing parenthesis for arguments list"),t}function b(){const t=[];let e=!1;for(;!o(M.CloseSquareBracket);)o(M.Colon)?(t.push(void 0),++n,e=!0):(t.push(l()),o(M.Colon)&&(++n,e=!0));if(0===t.length)throw new SyntaxError("Expected at least one argument for member/slice expression");if(e){if(t.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new lt(...t)}return t[0]}function g(){let e=v();for(;o(M.MultiplicativeBinaryOperator);){const r=t[n];++n;const s=v();e=new it(r,e,s)}return e}function v(){let t=function(){let t=d();for(;o(M.Pipe);){++n;let e=E();if(!(e instanceof X))throw new SyntaxError("Expected identifier for the filter");o(M.OpenParen)&&(e=m(e)),t=new ot(t,e)}return t}();for(;o(M.Is);){++n;const e=o(M.Not);e&&++n;let r=E();if(r instanceof et&&(r=new X(r.value.toString())),!(r instanceof X))throw new SyntaxError("Expected identifier for the test");t=new ct(t,e,r)}return t}function E(){const e=t[n];switch(e.type){case M.NumericLiteral:return++n,new Q(Number(e.value));case M.StringLiteral:return++n,new tt(e.value);case M.BooleanLiteral:return++n,new et("true"===e.value.toLowerCase());case M.Identifier:return++n,new X(e.value);case M.OpenParen:{++n;const e=u();if(t[n].type!==M.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${t[n].type} instead`);return++n,e}case M.OpenSquareBracket:{++n;const t=[];for(;!o(M.CloseSquareBracket);)t.push(l()),o(M.Comma)&&++n;return++n,new nt(t)}case M.OpenCurlyBracket:{++n;const t=new Map;for(;!o(M.CloseCurlyBracket);){const e=l();r(M.Colon,"Expected colon between key and value in object literal");const s=l();t.set(e,s),o(M.Comma)&&++n}return++n,new st(t)}default:throw new SyntaxError(`Unexpected token: ${e.type}`)}}for(;n<t.length;)e.body.push(s());return e}function pt(t,e,n=1){void 0===e&&(e=t,t=0);const r=[];for(let s=t;s<e;s+=n)r.push(s);return r}function wt(t,e,n,r=1){const s=Math.sign(r);s>=0?(e=(e??=0)<0?Math.max(t.length+e,0):Math.min(e,t.length),n=(n??=t.length)<0?Math.max(t.length+n,0):Math.min(n,t.length)):(e=(e??=t.length-1)<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),n=(n??=-1)<-1?Math.max(t.length+n,-1):Math.min(n,t.length-1));const i=[];for(let o=e;s*o<s*n;o+=r)i.push(t[o]);return i}function dt(t){return t.replace(/\b\w/g,(t=>t.toUpperCase()))}var mt=class{constructor(t=void 0){this.type="RuntimeValue",this.builtins=new Map,this.value=t}__bool__(){return new gt(!!this.value)}toString(){return""+this.value}toJSON(){return this.value}},yt=class extends mt{constructor(){super(...arguments),this.type="NumericValue"}},bt=class t extends mt{constructor(){super(...arguments),this.type="StringValue",this.builtins=new Map([["upper",new St((()=>new t(this.value.toUpperCase())))],["lower",new St((()=>new t(this.value.toLowerCase())))],["strip",new St((()=>new t(this.value.trim())))],["title",new St((()=>new t(dt(this.value))))],["length",new yt(this.value.length)],["rstrip",new St((()=>new t(this.value.trimEnd())))],["lstrip",new St((()=>new t(this.value.trimStart())))]])}},gt=class extends mt{constructor(){super(...arguments),this.type="BooleanValue"}},vt=class extends mt{constructor(t,e){super(t),this.orgValue=e,this.type="ObjectValue",this.builtins=new Map([["get",new St((([t,e])=>{if(!(t instanceof bt))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new kt}))],["items",new St((()=>new xt(Array.from(this.value.entries()).map((([t,e])=>new xt([new bt(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 gt(this.value.size>0)}},Et=class extends vt{constructor(){super(...arguments),this.type="KeywordArgumentsValue"}},xt=class extends mt{constructor(){super(...arguments),this.type="ArrayValue",this.builtins=new Map([["length",new yt(this.value.length)]])}__bool__(){return new gt(this.value.length>0)}},$t=class extends xt{constructor(){super(...arguments),this.type="TupleValue"}},St=class extends mt{constructor(){super(...arguments),this.type="FunctionValue"}},kt=class extends mt{constructor(){super(...arguments),this.type="NullValue"}},At=class extends mt{constructor(){super(...arguments),this.type="UndefinedValue"}},Ot=class{constructor(t){this.parent=t,this.variables=new Map([["namespace",new St((t=>{if(0===t.length)return new vt(new Map);if(1!==t.length||!(t[0]instanceof vt))throw new Error("`namespace` expects either zero arguments or a single object argument");return t[0]}))]]),this.tests=new Map([["boolean",t=>"BooleanValue"===t.type],["callable",t=>t instanceof St],["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 xt||t instanceof bt],["lower",t=>{const e=t.value;return"StringValue"===t.type&&e===e.toLowerCase()}],["upper",t=>{const e=t.value;return"StringValue"===t.type&&e===e.toUpperCase()}],["none",t=>"NullValue"===t.type],["defined",t=>"UndefinedValue"!==t.type],["undefined",t=>"UndefinedValue"===t.type],["equalto",(t,e)=>t.value===e.value],["eq",(t,e)=>t.value===e.value]])}set(t,e){return this.declareVariable(t,jt(e))}declareVariable(t,e){if(this.variables.has(t))throw new SyntaxError(`Variable already declared: ${t}`);return this.variables.set(t,e),e}setVariable(t,e){return this.variables.set(t,e),e}resolve(t){if(this.variables.has(t))return this;if(this.parent)return this.parent.resolve(t);throw new Error(`Unknown variable: ${t}`)}lookupVariable(t){try{return this.resolve(t).variables.get(t)??new At}catch{return new At}}},Tt=class{constructor(t){this.global=t??new Ot}run(t){return this.evaluate(t,this.global)}evaluateBinaryExpression(t,e){const n=this.evaluate(t.left,e);switch(t.operator.value){case"and":return n.__bool__().value?this.evaluate(t.right,e):n;case"or":return n.__bool__().value?n:this.evaluate(t.right,e)}const r=this.evaluate(t.right,e);switch(t.operator.value){case"==":return new gt(n.value==r.value);case"!=":return new gt(n.value!=r.value)}if(n instanceof At||r instanceof At)throw new Error("Cannot perform operation on undefined values");if(n instanceof kt||r instanceof kt)throw new Error("Cannot perform operation on null values");if(n instanceof yt&&r instanceof yt)switch(t.operator.value){case"+":return new yt(n.value+r.value);case"-":return new yt(n.value-r.value);case"*":return new yt(n.value*r.value);case"/":return new yt(n.value/r.value);case"%":return new yt(n.value%r.value);case"<":return new gt(n.value<r.value);case">":return new gt(n.value>r.value);case">=":return new gt(n.value>=r.value);case"<=":return new gt(n.value<=r.value)}else if(n instanceof xt&&r instanceof xt){if("+"===t.operator.value)return new xt(n.value.concat(r.value))}else if(r instanceof xt){const e=void 0!==r.value.find((t=>t.value===n.value));switch(t.operator.value){case"in":return new gt(e);case"not in":return new gt(!e)}}if((n instanceof bt||r instanceof bt)&&"+"===t.operator.value)return new bt(n.toString()+r.toString());if(n instanceof bt&&r instanceof bt)switch(t.operator.value){case"in":return new gt(r.value.includes(n.value));case"not in":return new gt(!r.value.includes(n.value))}if(n instanceof bt&&r instanceof vt)switch(t.operator.value){case"in":return new gt(r.value.has(n.value));case"not in":return new gt(!r.value.has(n.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${n.type} and ${r.type}`)}evaluateArguments(t,e){const n=[],r=new Map;for(const s of t)if("KeywordArgumentExpression"===s.type){const t=s;r.set(t.key.value,this.evaluate(t.value,e))}else{if(r.size>0)throw new Error("Positional arguments must come before keyword arguments");n.push(this.evaluate(s,e))}return[n,r]}evaluateFilterExpression(t,e){const n=this.evaluate(t.operand,e);if("Identifier"===t.filter.type){const r=t.filter,s=e.lookupVariable(r.value);if(s instanceof St)return s.value([n],e);if(n instanceof xt)switch(r.value){case"list":return n;case"first":return n.value[0];case"last":return n.value[n.value.length-1];case"length":return new yt(n.value.length);case"reverse":return new xt(n.value.reverse());case"sort":return new xt(n.value.sort(((t,e)=>{if(t.type!==e.type)throw new Error(`Cannot compare different types: ${t.type} and ${e.type}`);switch(t.type){case"NumericValue":return t.value-e.value;case"StringValue":return t.value.localeCompare(e.value);default:throw new Error(`Cannot compare type: ${t.type}`)}})));default:throw new Error(`Unknown ArrayValue filter: ${r.value}`)}else if(n instanceof bt)switch(r.value){case"length":return new yt(n.value.length);case"upper":return new bt(n.value.toUpperCase());case"lower":return new bt(n.value.toLowerCase());case"title":return new bt(dt(n.value));case"capitalize":return new bt(n.value.charAt(0).toUpperCase()+n.value.slice(1));case"trim":return new bt(n.value.trim());case"trimStart":return new bt(n.value.trimStart());case"trimEnd":return new bt(n.value.trimEnd());case"indent":return new bt(n.value.split("\n").map(((t,e)=>0===e||0===t.length?t:" "+t)).join("\n"));case"string":return n;default:throw new Error(`Unknown StringValue filter: ${r.value}`)}else{if(n instanceof yt){if("abs"===r.value)return new yt(Math.abs(n.value));throw new Error(`Unknown NumericValue filter: ${r.value}`)}if(n instanceof vt)switch(r.value){case"items":return new xt(Array.from(n.value.entries()).map((([t,e])=>new xt([new bt(t),e]))));case"length":return new yt(n.value.size);case"string":return new bt(n.toString());default:throw new Error(`Unknown ObjectValue filter: ${r.value}`)}}throw new Error(`Cannot apply filter "${r.value}" to type: ${n.type}`)}if("CallExpression"===t.filter.type){const r=t.filter;if("Identifier"!==r.callee.type)throw new Error(`Unknown filter: ${r.callee.type}`);const s=r.callee.value,i=e.lookupVariable(s);if(i instanceof St){const[t,s]=this.evaluateArguments(r.args,e);return s.size>0&&t.push(new Et(s)),i.value([n,...t],e)}if(n instanceof xt){switch(s){case"selectattr":{if(n.value.some((t=>!(t instanceof vt))))throw new Error("`selectattr` can only be applied to array of objects");if(r.args.some((t=>"StringLiteral"!==t.type)))throw new Error("arguments of `selectattr` must be strings");const[t,s,i]=r.args.map((t=>this.evaluate(t,e)));let o;if(s){const t=e.tests.get(s.value);if(!t)throw new Error(`Unknown test: ${s.value}`);o=t}else o=(...t)=>t[0].__bool__().value;const a=n.value.filter((e=>{const n=e.value.get(t.value);return!!n&&o(n,i)}));return new xt(a)}case"map":{const[,t]=this.evaluateArguments(r.args,e);if(t.has("attribute")){const e=t.get("attribute");if(!(e instanceof bt))throw new Error("attribute must be a string");const r=t.get("default"),s=n.value.map((t=>{if(!(t instanceof vt))throw new Error("items in map must be an object");return t.value.get(e.value)??r??new At}));return new xt(s)}throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${s}`)}if(n instanceof bt){if("indent"===s){const[t,s]=this.evaluateArguments(r.args,e),i=t.at(0)??s.get("width")??new yt(4);if(!(i instanceof yt))throw new Error("width must be a number");const o=t.at(1)??s.get("first")??new gt(!1),a=t.at(2)??s.get("blank")??new gt(!1),c=n.value.split("\n"),u=" ".repeat(i.value),l=c.map(((t,e)=>!o.value&&0===e||!a.value&&0===t.length?t:u+t));return new bt(l.join("\n"))}throw new Error(`Unknown StringValue filter: ${s}`)}throw new Error(`Cannot apply filter "${s}" to type: ${n.type}`)}throw new Error(`Unknown filter: ${t.filter.type}`)}evaluateTestExpression(t,e){const n=this.evaluate(t.operand,e),r=e.tests.get(t.test.value);if(!r)throw new Error(`Unknown test: ${t.test.value}`);const s=r(n);return new gt(t.negate?!s:s)}evaluateUnaryExpression(t,e){const n=this.evaluate(t.argument,e);if("not"===t.operator.value)return new gt(!n.value);throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let n="";for(const r of t){const t=this.evaluate(r,e);"NullValue"!==t.type&&"UndefinedValue"!==t.type&&(n+=t)}return new bt(n)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){const[n,r]=this.evaluateArguments(t.args,e);r.size>0&&n.push(new Et(r));const s=this.evaluate(t.callee,e);if("FunctionValue"!==s.type)throw new Error(`Cannot call something that is not a function: got ${s.type}`);return s.value(n,e)}evaluateSliceExpression(t,e,n){if(!(t instanceof xt||t instanceof bt))throw new Error("Slice object must be an array or string");const r=this.evaluate(e.start,n),s=this.evaluate(e.stop,n),i=this.evaluate(e.step,n);if(!(r instanceof yt||r instanceof At))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof yt||s instanceof At))throw new Error("Slice stop must be numeric or undefined");if(!(i instanceof yt||i instanceof At))throw new Error("Slice step must be numeric or undefined");return t instanceof xt?new xt(wt(t.value,r.value,s.value,i.value)):new bt(wt(Array.from(t.value),r.value,s.value,i.value).join(""))}evaluateMemberExpression(t,e){const n=this.evaluate(t.object,e);let r,s;if(t.computed){if("SliceExpression"===t.property.type)return this.evaluateSliceExpression(n,t.property,e);r=this.evaluate(t.property,e)}else r=new bt(t.property.value);if(n instanceof vt){if(!(r instanceof bt))throw new Error(`Cannot access property with non-string: got ${r.type}`);s=n.value.get(r.value)??n.builtins.get(r.value)}else if(n instanceof xt||n instanceof bt)if(r instanceof yt)s=n.value.at(r.value),n instanceof bt&&(s=new bt(n.value.at(r.value)));else{if(!(r instanceof bt))throw new Error(`Cannot access property with non-string/non-number: got ${r.type}`);s=n.builtins.get(r.value)}else{if(!(r instanceof bt))throw new Error(`Cannot access property with non-string: got ${r.type}`);s=n.builtins.get(r.value)}return s instanceof mt?s:new At}evaluateSet(t,e){const n=this.evaluate(t.value,e);if("Identifier"===t.assignee.type){const r=t.assignee.value;e.setVariable(r,n)}else{if("MemberExpression"!==t.assignee.type)throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(t.assignee)}`);{const r=t.assignee,s=this.evaluate(r.object,e);if(!(s instanceof vt))throw new Error("Cannot assign to member of non-object");if("Identifier"!==r.property.type)throw new Error("Cannot assign to member with non-identifier property");s.value.set(r.property.value,n)}}return new kt}evaluateIf(t,e){const n=this.evaluate(t.test,e);return this.evaluateBlock(n.__bool__().value?t.body:t.alternate,e)}evaluateFor(t,e){const n=new Ot(e);let r,s;if("SelectExpression"===t.iterable.type){const e=t.iterable;s=this.evaluate(e.iterable,n),r=e.test}else s=this.evaluate(t.iterable,n);if(!(s instanceof xt))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 Ot(n),c=s.value[e];let u;if("Identifier"===t.loopvar.type)u=e=>e.setVariable(t.loopvar.value,c);else{if("TupleLiteral"!==t.loopvar.type)throw new Error(`Invalid loop variable(s): ${t.loopvar.type}`);{const e=t.loopvar;if("ArrayValue"!==c.type)throw new Error(`Cannot unpack non-iterable type: ${c.type}`);const n=c;if(e.value.length!==n.value.length)throw new Error(`Too ${e.value.length>n.value.length?"few":"many"} items to unpack`);u=t=>{for(let r=0;r<e.value.length;++r){if("Identifier"!==e.value[r].type)throw new Error(`Cannot unpack non-identifier type: ${e.value[r].type}`);t.setVariable(e.value[r].value,n.value[r])}}}}if(r){u(a);if(!this.evaluate(r,a).__bool__().value)continue}i.push(c),o.push(u)}let a="",c=!0;for(let e=0;e<i.length;++e){const r=new Map([["index",new yt(e+1)],["index0",new yt(e)],["revindex",new yt(i.length-e)],["revindex0",new yt(i.length-e-1)],["first",new gt(0===e)],["last",new gt(e===i.length-1)],["length",new yt(i.length)],["previtem",e>0?i[e-1]:new At],["nextitem",e<i.length-1?i[e+1]:new At]]);n.setVariable("loop",new vt(r)),o[e](n);a+=this.evaluateBlock(t.body,n).value,c=!1}if(c){a+=this.evaluateBlock(t.defaultBlock,n).value}return new bt(a)}evaluateMacro(t,e){return e.setVariable(t.name.value,new St(((e,n)=>{const r=new Ot(n);let s;e=e.slice(),"KeywordArgumentsValue"===e.at(-1)?.type&&(s=e.pop());for(let n=0;n<t.args.length;++n){const i=t.args[n],o=e[n];if("Identifier"===i.type){const t=i;if(!o)throw new Error(`Missing positional argument: ${t.value}`);r.setVariable(t.value,o)}else{if("KeywordArgumentExpression"!==i.type)throw new Error(`Unknown argument type: ${i.type}`);{const t=i,e=o??s?.value.get(t.key.value)??this.evaluate(t.value,r);r.setVariable(t.key.value,e)}}}return this.evaluateBlock(t.body,r)}))),new kt}evaluate(t,e){if(void 0===t)return new At;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 yt(Number(t.value));case"StringLiteral":return new bt(t.value);case"BooleanLiteral":return new gt(t.value);case"ArrayLiteral":return new xt(t.value.map((t=>this.evaluate(t,e))));case"TupleLiteral":return new $t(t.value.map((t=>this.evaluate(t,e))));case"ObjectLiteral":{const n=new Map;for(const[r,s]of t.value){const t=this.evaluate(r,e);if(!(t instanceof bt))throw new Error(`Object keys must be strings: got ${t.type}`);n.set(t.value,this.evaluate(s,e))}return new vt(n,t.value)}case"Identifier":return this.evaluateIdentifier(t,e);case"CallExpression":return this.evaluateCallExpression(t,e);case"MemberExpression":return this.evaluateMemberExpression(t,e);case"UnaryExpression":return this.evaluateUnaryExpression(t,e);case"BinaryExpression":return this.evaluateBinaryExpression(t,e);case"FilterExpression":return this.evaluateFilterExpression(t,e);case"TestExpression":return this.evaluateTestExpression(t,e);default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function jt(t){switch(typeof t){case"number":return new yt(t);case"string":return new bt(t);case"boolean":return new gt(t);case"undefined":return new At;case"object":return null===t?new kt:Array.isArray(t)?new xt(t.map(jt)):new vt(new Map(Object.entries(t).map((([t,e])=>[t,jt(e)]))),t);case"function":return new St(((e,n)=>{const r=e.map((t=>Ct(t)));return jt(t(...r)??null)}));default:throw new Error(`Cannot convert to runtime value: ${t}`)}}function Ct(t){let e=t;if(Array.isArray(t))e=t.map((t=>Ct(t)));else if(t instanceof Map)e={},t.forEach(((t,n)=>{e[n]=Ct(t)}));else switch(t.type){case"NullValue":e=null;break;case"UndefinedValue":e=void 0;break;case"ArrayValue":e=t.value.map((t=>Ct(t)));break;case"KeywordArgumentsValue":case"ObjectValue":e=t.orgValue?t.orgValue:Ct(t.value),"KeywordArgumentsValue"===t.type&&Object.setPrototypeOf(e,{jinja_kargs:!0});break;default:t.type&&(e=t.value)}return e}function Nt(t,e=0){return Math.floor(Math.random()*(t-e+1))+e}var Ft={randomInt:Nt,select:function(t,e){if(Array.isArray(t)||"string"==typeof t)return void 0===e?e=Nt(t.length-1):"string"==typeof e&&(e=parseInt(e)),e<0&&(e=t.length+e),t[e];if(t&&"object"==typeof t){if(void 0===e){const n=Object.keys(t);e=n[Nt(n.length-1)]}return t[e]}},tojson:function(t,e,n){return e&&"object"==typeof e&&(e.depth&&(n=e.depth),e=e.indent),It(t,e,n)}};function It(t,e,n){let r="";const s=n??0;if(null===t)r="null";else{const n=typeof t;switch(n){case"undefined":r="null";case"number":case"string":case"boolean":return JSON.stringify(t);case"object":{const n=e?" ".repeat(e):"",r="\n"+n.repeat(s),i=r+n;if(Array.isArray(t)){const n=t.map((t=>It(t,e,s+1)));return e?`[${i}${n.join(`,${i}`)}${r}]`:`[${n.join(", ")}]`}{const n=Array.from(Object.entries(t)).map((([t,n])=>{const r=`"${t}": ${It(n,e,s+1)}`;return e?`${i}${r}`:r}));return e?`{${n.join(",")}${r}}`:`{${n.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${n}`)}}return r}var Mt=class extends Ot{constructor(t){super(t),this.parent=t}assign(t){for(const[e,n]of Object.entries(t))this.set(e,n)}clear(){this.variables.clear()}},Pt=class t{static{this.global=new Mt}constructor(t,e={}){const n=_(t,e={lstrip_blocks:!0,trim_blocks:!0,...e});this.parsed=ht(n)}render(e){const n=new Ot(t.global);n.set("false",!1),n.set("true",!0),n.set("raise_exception",(t=>{throw new Error(t)})),n.set("range",pt);for(const[t,r]of Object.entries(e))n.set(t,r);return new Tt(n).run(this.parsed).toString()}};function Rt(t,e){let n;switch(t.type){case"Identifier":n=t.value;break;case"MemberExpression":n=Rt(t.object,e);break;case"FilterExpression":n=Rt(t.operand,e);break;case"Set":{e||(e=[]);const r=Rt(t.assignee);r&&e.push(r),n=Rt(t.value,e);break}}return n&&e?.includes(n)&&(n=void 0),n}function qt(t){let e;if("Program"===t.type)e=t.body.some((t=>qt(t)));else e=t.isStatement;return e}function Vt(t,e){let n=[];if(Array.isArray(t))n=t.map((t=>Vt(t,e))).filter(Boolean).flat();else switch(t.type){case"Program":n=t.body.map((t=>Vt(t,e))).filter(Boolean).flat();break;case"If":n=[Rt(t.test,e),...Vt(t.body,e),...Vt(t.alternate,e)].filter(Boolean);break;case"BinaryExpression":n=[Rt(t.left,e),Rt(t.right,e)].filter(Boolean);break;case"For":{const r=Rt(t.loopvar);r&&(e||(e=[]),e.push(r)),n=[Rt(t.iterable,e),...Vt(t.body,e)].filter(Boolean);break}case"CallExpression":n=[Rt(t.callee,e),...Vt(t.args,e)].filter(Boolean);break;default:n=[Rt(t,e)].filter(Boolean)}return n}Pt.global.assign(Ft);var Bt=class extends C{static isTemplate(t){let e,n,r=!1;if("object"==typeof t?(n=t.template,e=t.compiledTemplate):n=t,!e&&n)try{e=new Pt(n)}catch(t){}return e&&(r=qt(e.parsed)),r}getVariables(t=this.compiledTemplate){return Vt(t.parsed,[]).filter(((t,e,n)=>n.indexOf(t)===e))}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new d.CommonError("Prompt template must be a string","PromptTemplate",d.ErrorCode.InvalidArgument);this.compiledTemplate=new Pt(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return this.compiledTemplate.render(t)}};function Ut(t){return function(e){return t}}function _t(t){const e=t.split(""),n=[],r=(t,n)=>{for(let r=n;r<e.length;r+=1)if(t.includes(e[r]))return r;return-1};let s=0;for(;s<e.length;)if("{"===e[s]&&s+1<e.length&&"{"===e[s+1])n.push({type:"literal",text:"{"}),s+=2;else if("}"===e[s]&&s+1<e.length&&"}"===e[s+1])n.push({type:"literal",text:"}"}),s+=2;else if("{"===e[s]){const t=r("}",s);if(t<0)throw new Error("Unclosed '{' in template.");n.push({type:"variable",name:e.slice(s+1,t).join("")}),s=t+1}else{if("}"===e[s])throw new Error("Single '}' in template.");{const t=r("{}",s),i=(t<0?e.slice(s):e.slice(s,t)).join("");n.push({type:"literal",text:i}),s=t<0?e.length:t}}return n}function Lt(t,e){return t.reduce(((t,n)=>{let r;return r="variable"===n.type?n.name in e?t+e[n.name]:t:t+n.text,r}),"")}function zt(t){const e=new Set;return t.forEach((t=>{"variable"===t.type&&e.add(t.name)})),[...e]}C.register(Bt,{name:"hf",aliases:["huggingface","internal","default"]});var Dt=class extends C{static isTemplate(t){let e,n,r=!1;if("object"==typeof t?(n=t.template,e=t.compiledTemplate):n=t,!e&&n)try{e=_t(n)}catch(t){}if(e){r=zt(e).length>0}return r}getVariables(t=this.compiledTemplate){return zt(t)}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new d.CommonError("Prompt template must be a string","PromptTemplate",d.ErrorCode.InvalidArgument);this.compiledTemplate=_t(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return Lt(this.compiledTemplate,t)}};function Jt(t,e){return"string"==typeof e&&(e=e.split(".").filter((t=>t.length))),e.reduce(((t,e)=>t?.[e]),t)}function Wt(t,e,n){let r=function(t,e,n){return t.replace(/{{\s*re_replace\s+\.(.+?)\s+(["'])((?:(?!\2).)*?)\2\s+(["'])((?:(?!\4).)*?)\4\s*}}/g,((t,r,s,i,o,a)=>{if(n)return e[r]=null,t;const c=new RegExp(i,"g");return Jt(e,r).replace(c,a)}))}(t,e,n);return r=function(t,e,n){return t.replace(/{{\s*join\s+\.(.+?)\s+(["'])((?:(?!\2).)*?)\2\s*}}/g,((t,r,s,i)=>n?(e[r]=null,t):Jt(e,r).join(i)))}(r,e,n),r=function(t,e,n){return t.replace(/{{\s*if\s*(\S+?)\s*}}([^{]*)({{\s*else\s*}}([^{]*))?{{\s*end\s*}}/g,((t,r,s,i,o)=>{if(n)return r.startsWith(".")&&(r=r.substring(1)),e[r]=null,t;let a;if(!r.startsWith("."))throw new Error("Functionality not implemented");{const t=Jt(e,r.substring(1));if(null==t)a=o??"";else if("string"==typeof t)a=t.length>0?s:o??"";else if(Array.isArray(t))a=t.length>0?s:o??"";else{if("boolean"!=typeof t)throw new Error(`Unexpected type for variable ${r}: ${typeof t}`);a=t?s:o??""}}return a}))}(r,e,n),r=function(t,e,n){return t.replace(/{{\s*range\s*[.$]([^{}\s]+?)\s*}}([^{]*?){{\.}}([^{]*?){{\s*end\s*}}/g,((t,r,s,i)=>{if(n)return e[r]=null,t;const o=Jt(e,r);if(Array.isArray(o)){let t="";for(const e of o)t+=`${s}${e}${i}`;return t}return t}))}(r,e,n),r=function(t,e,n){return t.replace(/{{\s*\.([^{}\s]+?)\s*}}/g,((t,r)=>n?(e[r]=null,t):Jt(e,r)||""))}(r,e,n),r=function(t,e,n){return t.replace(/{{\s*index\s*\.(.+?)\s+(.+?)\s*}}/g,((t,r,s)=>{if(n)return e[r]=null,t;const i=Jt(e,r);let o;return o=isNaN(s)?i[s.substring(1,s.length-1)]:i[parseInt(s,10)],o||""}))}(r,e,n),r}C.register(Dt,{name:"fstring",aliases:["python","f-string","langchain"]});var Kt=class extends C{static isTemplate(t){const e="string"==typeof t?t:t.template;return e?.includes("{{")&&e.includes("}}")}getVariables(t){const e={};return Wt(t,e,!0),[...Object.keys(e)]}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new d.CommonError("Prompt template must be a string","PromptTemplate",d.ErrorCode.InvalidArgument);this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables(e)}_format(t){return Wt(this.template,t)}};function Ht(t){return Object.keys(t).sort().map((e=>t[e]))}C.register(Kt,{name:"golang",aliases:["localai","ollama"]});var Zt=class extends C{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 C?t.examplePrompt:C.from(t.examplePrompt)),t.examples&&(this.examples=t.examples)),this.prefix||(this.prefix=""),this.exampleSeparator||(this.exampleSeparator="\n\n"),this.suffix||(this.suffix="")}async _format(t){const e=[];for await(const t of this.examples)if(this.examplePrompt){const n=await this.examplePrompt.format(t);e.push(n)}else if("string"==typeof t)e.push(t);else if(t){const n=Ht(t);n.length>0&&e.push(...n)}const n=[this.prefix,...e,this.suffix].join(this.exampleSeparator),r=this.templateFormat;return await C.format({template:n,data:t,templateFormat:r})}toJSON(t=this){const e=super.toJSON(t);return t.suffix&&(e.suffix=t.suffix),t.exampleSeparator&&(e.exampleSeparator=t.exampleSeparator),t.prefix&&(e.prefix=t.prefix),t.examplePrompt&&(e.examplePrompt=t.examplePrompt),t.examples&&(e.examples=t.examples),e}};C.register(Zt,{name:"fewshot",aliases:["few_shot"]});var Gt=/(\\)?(\$)(?!\()(\{?)([\w.]+)(?::?-((?:\$\{(?:\$\{(?:\$\{[^}]*\}|[^}])*}|[^}])*}|[^}])+))?(\}?)/gi;function Xt(t){return t.replace(/\\\$/g,"$")}function Yt(t,e,n){return t.replace(Gt,((r,s,i,o,a,c,u)=>"\\"===s?r.slice(1):e[a]?e[a]===n[a]?e[a]:Yt(e[a],e,n):n[a]?n[a]===t?n[a]:Yt(n[a],e,n):c?c.startsWith("$")?Yt(c,e,n):c:""))}function Qt(t){let e=process.env;t&&null!=t.processEnv&&(e=t.processEnv);for(const n in t.parsed){let r=t.parsed[n];if(!r)continue;r=Object.prototype.hasOwnProperty.call(e,n)?e[n]===t.parsed[n]?Yt(r,e,t.parsed):e[n]:Yt(r,e,t.parsed),t.parsed[n]=r?Xt(r):r}for(const n in t.parsed)e[n]=t.parsed[n];return t}function te(t,e={},n){switch(n||(n=new WeakSet),e.processEnv||(e.processEnv={...process.env}),e.parsed||(e.parsed=e.processEnv),typeof t){case"string":t=Yt(t,e.processEnv,e.parsed);break;case"object":if(n.has(t)||null===t)return t;if(n.add(t),Array.isArray(t))for(let r=0;r<t.length;r++){const s=t[r];"string"!=typeof s&&"object"!=typeof s||(t[r]=te(t[r],e,n))}else for(const[r,s]of Object.entries(t))"string"!=typeof s&&"object"!=typeof s||(t[r]=te(s,e,n))}return t}var ee="@",ne=/(\S.+?[.!?])(?=\s+|$)|(\S.+?)(?=[\n]|$)/g,re=/([A-Z][a-z]{1,2}\.)\s(\w)/g,se=/(\.[a-zA-Z]\.)\s(\w)/g,ie=new RegExp("([A-Z][a-z]{1,2}\\.)"+ee+"(\\w)","g"),oe=new RegExp("(\\.[a-zA-Z]\\.)"+ee+"(\\w)","g");function ae(t,e,n){const r="$1"+e+"$2";let s=t;for(let t=0;t<n.length;t++)s=s.replace(n[t],r);return s}function ce(t,e=!0){const n=(t=(t=(t=(t=(t=t.replace(/([。!??])\1+/g,"$1")).replace(/([。!??])([^”’])/g,"$1\n$2")).replace(/(\.{6})([^”’])/g,"$1\n$2")).replace(/(…{2})([^”’])/g,"$1\n$2")).replace(/([。!??][”’])([^,。!??])/g,"$1\n$2")).split("\n");let r=[];for(let t=0;t<n.length;t++){let s=n[t].trim();if(!s)continue;if(!e){r.push(s);continue}let i=ae(s,ee,[re,se]),o=Array.from(i.matchAll(ne));if(o.length)for(let t=0;t<o.length;t++){let e=ae(o[t][0]," ",[ie,oe]);r.push(e)}else r.push(s)}return r}function ue(t,e=2,n=.5){const r=10**e;return Math.trunc((t+Number.EPSILON+n/r)*r)/r}async function le(t){return new Promise((e=>setTimeout(e,t)))}var fe=require("custom-ability"),he="event",pe="event-bus";var we=(0,fe.createAbilityInjector)((function(t){return class{static get emitter(){if(!this._emitter){const t=this.get(pe)?.emitter;t&&(this._emitter=t,this.prototype._events=t._events)}return this._emitter}get emitter(){return this.constructor._emitter}on(e,n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.on(e,n)}once(e,n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.once(e,n)}off(e,n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.off(e,n)}emit(e,...n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return"error"===e?this.emitError.apply(this,n):r.emit.call(this,e,this.name,...n)}emitError(e,...n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.emit.call(this,"error",e,this.name,...n)}async emitAsync(e,...n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.emitAsync.call(this,e,this.name,...n)}}}),!0);function de(t,e){return!t||t.some((t=>t instanceof RegExp?t.test(e):t===e))}var me=498,ye=class{get active(){return this._active}set active(t){t!==this._active&&(t?(this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0),this.options.pingInterval>0&&(this.pingTimer=setInterval((()=>this.publish()),this.options.pingInterval))):(this.clients.size&&this.clearClients(),this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0)),this._active=t)}constructor(t){this.options=Object.assign({},{pingInterval:3e3,maxStreamDuration:3e4,clientRetryInterval:1e3,startId:1,historySize:100,rewind:0,cors:!1},t),this.nextID=this.options.startId,this.clients=new Set,this.messages=[],this.active=!0}publish(t,e){let n,r;this.active||(0,d.throwError)("Channel closed","SSEChannel",me);let s=e;if(t||e)r=this.nextID++,"object"==typeof t&&(t.event?(s=t.event,void 0!==t.data&&(t=JSON.stringify(t.data))):t=JSON.stringify(t)),t=t?t.split(/[\r\n]+/).map((t=>"data: "+t)).join("\n"):"",n="id: "+r+"\n"+(e?"event: "+e+"\n":"")+(t||"data: ")+"\n\n",this.messages.push({id:r,_eventName:s,output:n});else{if(!this.clients.size)return;n="data: \n\n"}for([...this.clients].filter((t=>!s||de(t.events,s))).forEach(((t,e)=>{t.res.write(n)}));this.messages.length>this.options.historySize;)this.messages.shift();return r}subscribe(t,e,n){this.active||(0,d.throwError)("Channel closed","SSEChannel",me);const r={req:t,res:e,events:n},s=this.options.maxStreamDuration;let i="max-age=0, stale-while-revalidate=0, stale-if-error=0, no-transform";s>0&&(i+=", s-maxage="+(Math.floor(s/1e3)-1));const o={"Content-Type":"text/event-stream","Cache-Control":i,Connection:"keep-alive"};this.options.cors&&(o["access-control-allow-origin"]="*"),r.req.socket.setNoDelay(!0),r.res.writeHead(200,o);let a="retry: "+this.options.clientRetryInterval+"\n\n";const c=Number.parseInt(t.headers["last-event-id"],10),u=Number.isNaN(c)?this.options.rewind:this.nextID-1-c;return u&&this.messages.filter((t=>de(r.events,t.eventName))).slice(0-u).forEach((t=>{a+=t.output})),r.res.write(a),this.clients.add(r),s>0&&setTimeout((()=>{r.res.writableEnded||this.unsubscribe(r)}),s),r.res.on("close",(()=>this.unsubscribe(r))),r}unsubscribe(t){t.res.end(),this.clients.delete(t)}clearClients(){this.clients.forEach((t=>t.res.end())),this.clients.clear()}listClients(){const t={};return this.clients.forEach((e=>{const n=e.req.socket.remoteAddress??"";n in t||(t[n]=0),t[n]++})),t}getSubscriberCount(){return this.clients.size}};function be(t){return t instanceof ReadableStream||t instanceof WritableStream}var ge=600,ve=601,Ee=class extends d.BaseError{constructor(t,e=ge){super(t,500)}};function xe(t){if(t){const e=t.getReader();return new ReadableStream({async start(t){const{done:n,value:r}=await e.read();if(!n){const e=(new TextDecoder).decode(r);t.error(new Ee(`Response error: ${e}`,ve))}}})}return new ReadableStream({start(t){t.error(new Ee("Response error: No response body",ve))}})}function $e(){return new ReadableStream({start(t){t.close()}})}var Se=require("eventsource-parser");function ke(t){const e=new TextDecoder;let n;return new TransformStream({async start(e){n=(0,Se.createParser)((n=>{if("data"in n&&"event"===n.type&&"[DONE]"===n.data||"done"===n.event)e.terminate();else if("data"in n){const r=t?t(n.data,{event:n.event}):n.data;r&&e.enqueue(r)}}))},transform(t){n.feed(e.decode(t))}})}function Ae(){let t=!0;return e=>(t&&(e=e.trimStart())&&(t=!1),e)}function Oe(t,e){if(!t.ok)return xe(t.body);let n=t.body||new ReadableStream({start(t){t.close()}});return n instanceof ReadableStream||(n=ReadableStream.from(n)),n.pipeThrough(ke(e))}function Te(t){let e=t[Symbol.asyncIterator]();return new ReadableStream({async pull(t){const{done:n,value:r}=await e.next();n?t.close():t.enqueue(r)},async cancel(t){await(e.return?.(t))}})}function je(t){const e=t||{};return new TransformStream({async start(t){const n=t.error;if(t.error=r=>{n.call(t,r),e.onError&&e.onError(r)},e.onStart)try{await e.onStart(t)}catch(e){t.error(e)}},async transform(t,n){try{let r;e.onTransform&&(r=await e.onTransform(t,n)),r||(r=t),n.enqueue(r)}catch(t){n.error(t)}},async flush(t){if(e.onFinal)try{await e.onFinal(t)}catch(e){return t.error(e)}t.terminate()}})}var Ce=require("uuid"),Ne=c(require("base32768")),Fe=require("uuid"),Ie={1:Ce.v1,4:Ce.v4,5:Ce.v5};function Me(t=1,e){const n=Ie[t];return e?Ne.encode(n(null,[])):n()}var Pe=c(require("xxhashjs")),Re=c(require("base32768")),qe=require("json-canonicalize"),Ve=Re,{h32:Be,h64:Ue}=Pe.default,_e=588213;function Le(t,e=16){return"object"==typeof t&&(t=(0,qe.canonicalize)(t)),Be(t,_e).toString(e)}function ze(t,e=16){return"object"==typeof t&&(t=(0,qe.canonicalize)(t)),Ue(t,_e).toString(e)}var De=(t=>(t[t.xxhash64=111]="xxhash64",t[t.xxhash32=112]="xxhash32",t))(De||{});function Je(t,e=111,n=_e){let r;return t.buffer&&(t=t.buffer),112!==e?(r=Ue(t,n),r=new Uint16Array([r._a00,r._a16,r._a32,r._a48]),r=new Uint8Array(r.buffer)):(r=Be(t,n),r=new Uint16Array([r._low,r._high]),r=new Uint8Array(r.buffer)),r}function We(t,e=111,n=_e){return Re.encode(Je(t,e,n))}var Ke=c(require("path")),He=/[<>:"/\\|?*\u0000-\u001F]/,Ze=/^(con|prn|aux|nul|com\d|lpt\d)$/i,Ge=100,Xe=/^\.+(\\|\/)|^\.+$/,Ye=/\.+$/,Qe=/[\u0000-\u001F\u0080-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069]/;function tn(){return new RegExp(He.source,"g")}function en(){return new RegExp(Qe.source,"g")}function nn(t){return t&&!(He.test(t)||en().test(t)||Xe.test(t)||Ye.test(t))}function rn(t){const e=t.split(Ke.default.sep);return("/"===t[0]||e[0]&&Ke.default.dirname(e[0])===e[0])&&e.shift(),e.every(nn)}function sn(t,e={}){const n=e.replacement||"!";if((He.test(n)||Qe.test(n))&&(0,d.throwError)("Replacement string cannot contain reserved filename characters","sanitizeFilename",d.ErrorCode.InvalidArgument),n.length>0){const e=/([<>:"/\\|?*\u0000-\u001F]){2,}/;t=t.replace(e,"$1")}if(t=(t=(t=(t=(t=t.normalize("NFD")).replace(Xe,n)).replace(tn(),n)).replace(en(),n)).replace(Ye,""),n.length>0){"."===t[0]||"."!==t[0]||(t=n+t),"."===t[t.length-1]&&(t+=n)}t=Ze.test(t)?t+n:t;const r="number"==typeof e.maxLength?e.maxLength:Ge;if(t.length>r){const e=t.lastIndexOf(".");if(-1===e)t=t.slice(0,r);else{const n=t.slice(0,e),s=t.slice(e);t=n.slice(0,Math.max(1,r-s.length))+s}}return t}function on(t,e={}){const n=t.split(Ke.default.sep);let r;("/"===t[0]||n[0]&&Ke.default.dirname(n[0])===n[0])&&(r=n.shift());const s=n.map((t=>sn(t,e)));return void 0!==r&&s.unshift(r),s.join(Ke.default.sep)}function an(t,e=1){let n="";for(;e--;){const e=Ke.default.extname(t);if(!e)break;n=e+n,t=Ke.default.basename(t,e)}return n}function cn(t){return t.split(".").length-1}var un=require("util-ex");function ln(t,e){if("string"!=typeof t)throw new d.CommonError("modelName must be a string","isModelNameMatched",d.ErrorCode.InvalidArgument);switch(typeof e){case"string":if((0,un.isRegExpStr)(e)){const n=(e=(0,un.toRegExp)(e)).exec(t);if(n)return n}else if(t.toLowerCase()===e.toLowerCase())return e;break;case"object":if(Array.isArray(e)){for(const n of e)if("string"==typeof n){if((0,un.isRegExpStr)(n)){const r=(e=(0,un.toRegExp)(n)).exec(t);if(r)return r}else if(t.toLowerCase()===n.toLowerCase())return n}else if(n instanceof RegExp){const e=n.exec(t);if(e)return e}else if("function"==typeof n){const e=n.call(this,t);if(e)return e}}else if(e instanceof RegExp){const n=e.exec(t);if(n)return n}break;case"function":const n=e.call(this,t);if(n)return n}}function fn(t){return Object.keys(t).filter((t=>Number.isNaN(Number(t))))}var hn=require("lodash-es"),pn=require("util-ex");function wn(t,e){if(e&&(e=yn(e)),e){const n=Object.keys(e);if(n.length){const r=Object.values(e);return(0,pn.newFunction)("expression",n,`return ${t}`)(...r)}}return(0,pn.newFunction)("expression",[],`return ${t}`)()}var dn=/^[a-zA-Z_$][0-9a-zA-Z_$]*$/,mn=t=>dn.test(t);function yn(t){if(t){const e=Object.keys(t),n=e.length,r=e.filter((e=>mn(e)&&null!==t[e]));if(n===r.length)return t;if(r.length)return t=(0,hn.pick)(t,r)}}function bn(t){return t?gn(t,[],""):[]}function gn(t,e,n="."){return Array.isArray(t)?t.flatMap(((t,n)=>gn(t,[...e,`[${n}]`]))):(r=t)&&r.constructor===Object?Object.entries(t).flatMap((([t,r])=>gn(r,[...e,n+t]))):[e.join("")];var r}function vn(t){if(t<2)throw new d.CommonError("repetitionThreshold must be greater than 1","createEndWithRepetitionDetector",d.ErrorCode.InvalidArgument);const e=new RegExp(`([\\S\\s]+)(\\1{${t-1},})$`);return function(t){return e.exec(t)}}var En=c(require("path")),xn=c(require("fs"));function $n(t){const e=xn.statSync(t,{throwIfNoEntry:!1});return e?.isFile()}function Sn(t,e,n,r){const s=r?.signal,i=r?.exclude;let o;if(En.default.isAbsolute(t)?o=$n(t)?t:kn(En.default.basename(t),[En.default.dirname(t)],{extNames:n,exclude:i,signal:s}):(e||(e=["."]),o=kn(t,e,{extNames:n,exclude:i,signal:s})),!o)throw new d.NotFoundError(t,"loadFileFromPaths");{const t=o;o=xn.readFileSync(o),r&&(r.filepath=t)}return o}function kn(t,e,{extNames:n,signal:r,exclude:s=[]}){let i;const o=n?n.map((e=>an(t,cn(e)))):void 0;"string"==typeof s&&(s=[s]);for(const a of e){if(r?.aborted)throw r.reason;const e=En.default.resolve(a,t);if(o)for(let t=0;t<o.length;t++){const r=e+(o[t]!==n[t]?n[t]:"");if(!s.includes(r)&&$n(r)){i=r;break}}else if(!s.includes(e)&&$n(e)){i=e;break}}return i}function An(t,e,n,r,s){let i;"string"==typeof r?(i=r,r=void 0):i=r?.encoding??"utf8";return Sn(t,e,n,r).toString(i)}function On(t,e){const n=[],r="string"==typeof t?[t]:[...t],s=new Set,i=e?.signal,o=e?.isFileMatched,a=e?.level;let c=0;for(;r.length>0;){if(i?.aborted)throw i.reason;const t=Tn(r.pop()),e=En.default.resolve(t);if(s.has(e))continue;s.add(e);const u=xn.statSync(t,{throwIfNoEntry:!1});if(u?.isDirectory()){const e=xn.readdirSync(t,{withFileTypes:!0});for(let s=0;s<e.length;s++){const i=e[s],a=En.default.join(t,i.name);i.isDirectory()?r.push(a):!i.isFile()||o&&!o(a)||n.push(a)}if(c++,a&&c>=a)break}}return n}function Tn(t){const e=xn.lstatSync(t,{throwIfNoEntry:!1});return e?.isSymbolicLink()&&(t=xn.readlinkSync(t)),t}var jn=require("fs"),Cn=c(require("path")),Nn=require("load-config-file"),Fn=require("yaml"),In=require("yaml-types"),Mn=require("mime-type/with-db"),Pn=[In.regexp];function Rn(t){Array.isArray(t)||(t=[t]);for(const e of t){-1===Pn.indexOf(e)&&Pn.push(e)}}function qn(t){return(0,Fn.parse)(t,{customTags:Pn})}function Vn(t){return(0,Fn.stringify)(t,{customTags:Pn})}function Bn(t,e){const n=[],r=e?.after,s=e?.exclude?"string"==typeof e.exclude?[e.exclude]:e.exclude:void 0,i=e?.extensions?"string"==typeof e.extensions?[e.extensions]:e.extensions.map((t=>t.startsWith(".")?t:"."+t)):[".yml",".yaml",".json"];return function(t,e){const n=(0,jn.readdirSync)(t,{withFileTypes:!0,recursive:!0});for(const r of n){const n=Cn.default.join(t,r.name);r.isFile()&&e(n,r)}}(t,((t,e)=>{if(s?.includes(t))return;const o=Cn.default.extname(t),a=(0,jn.statSync)(t);if(i.includes(o)){if(r?.hasOwnProperty(t)&&a.mtimeMs<=r[t])return;n.push(t)}})),n}function Un(t,e){return Bn(t,e).map((t=>Nn.Config.loadSync(t))).filter((t=>void 0!==t))}function _n(t,e,n=1){"."===t[0]&&n++;const r=an(t,n);(!r||r.split(".").length<=1)&&(t+=".yaml");const s=Mn.mimeType.lookup(t);if("application/json"===s)e=JSON.stringify(e,null,2);else{if("text/yaml"!==s)throw new Error(`${t} unsupported mime type: ${s}`);e=Vn(e)}const i=Cn.default.dirname(t);return(0,jn.existsSync)(i)||(0,jn.mkdirSync)(i,{recursive:!0}),(0,jn.writeFileSync)(t,e,{encoding:"utf8"}),t}function Ln(t){t instanceof Date&&(t=t.toISOString());return function(t,e){return t?`'${e}'`:String(e)}("string"==typeof t,t)}function zn(t,e){return t.map((t=>Wn(t,e))).join(" AND ")}function Dn(t,e){return t.map((t=>Wn(t,e))).join(" OR ")}function Jn(t,e){const n=[];return Object.keys(e).forEach((r=>{const s=e[r];switch(r){case"$lt":case"<":n.push(`${t} < ${Ln(s)}`);break;case"<=":case"$lte":n.push(`${t} <= ${Ln(s)}`);break;case"$gt":case">":n.push(`${t} > ${Ln(s)}`);break;case"$gte":case">=":n.push(`${t} >= ${Ln(s)}`);break;case"$ne":case"!=":n.push(`${t} != ${Ln(s)}`);break;case"=":case"$eq":n.push(`${t} = ${Ln(s)}`);break;case"$in":n.push(`${t} IN (${s.map((t=>Ln(t))).join(", ")})`);break;case"$nin":n.push(`${t} NOT IN (${s.map((t=>Ln(t))).join(", ")})`);break;case"$regex":n.push(`${t} REGEXP '${s.source}'`);break;case"$like":n.push(`${t} LIKE '${s}'`);break;case"$nlike":n.push(`${t} NOT LIKE '${s}'`);break;case"$glob":n.push(`${t} GLOB '${s}'`);break;case"$nglob":n.push(`${t} NOT GLOB '${s}'`);break;default:throw new Error(`Unsupported condition operator: ${r}`)}})),n.join(" AND ")}function Wn(t,e){const n=[];if("function"!=typeof e&&(e=t=>t),Array.isArray(t))n.push(zn(t,e));else for(const[r,s]of Object.entries(t))if("$and"===r)n.push(`(${zn(t[r],e)})`);else if("$or"===r)n.push(`(${Dn(t[r],e)})`);else{const t=typeof s;if(null==s)n.push(`${e(r)} IS NULL`);else if(s instanceof Date)n.push(`${e(r)}='${s.toISOString()}'`);else if("object"!==t||Array.isArray(s))if("string"===t)n.push(`${e(r)}='${s}'`);else{if("number"!==t&&"boolean"!==t)throw new Error(`Unsupported value type for key ${r}`);n.push(`${e(r)}=${s}`)}else n.push(Jn(e(r),s))}return n.length>1?n.join(" AND "):n[0]}function Kn(t){const e=t.indexOf("://");if(e>0)return t.substring(0,e)}function Hn(t,e=0){let n,r=t*10**e;return t>=1e12?(r=Math.round(r/1e12),n="T"):t>=1e9?(r=Math.round(r/1e9),n="B"):t>=1e6?(r=Math.round(r/1e6),n="M"):t>=1e3?(r=Math.round(r/1e3),n="K"):(r=Math.round(r),n=""),r/=10**e,r.toFixed(e)+n}function Zn(t){const e=t.match(/^\s*[+]?(\d+(?:[.]\d+)?)\s*([TBMK])?\s*$/i);if(!e)throw new d.CommonError("Invalid formatted parameter size string.","scaleToSize",d.ErrorCode.InvalidArgument);const n=parseFloat(e[1]),r=e[2]?.toLowerCase();switch(r){case"t":return 1e12*n;case"b":return 1e9*n;case"m":return 1e6*n;case"k":return 1e3*n;default:return n}}function Gn(t,e){const n=e?.level||0,r=e?.visiting||new Set,s=e?.objectTag||"*",i=e?.arrayTag||"-";let o=[];const a=" ".repeat(2*n);if(null!=t)switch(typeof t){case"object":r.has(t)?o=["[Circular]"]:(r.add(t),o=Array.isArray(t)?t.map((t=>i+c(t))):Object.entries(t).map((([t,e])=>s+" `"+t+"`:"+c(e))));break;case"string":return t;default:return JSON.stringify(t)}else o=["null"];return o.length?a+o.join("\n"+a):"";function c(t){return(null!=t&&"object"==typeof t?"\n":" ")+Gn(t,{level:n+1,visiting:r})}}Nn.Config.register([".yml",".yaml"],qn),Nn.Config.register([".json"],(function(t){return JSON.parse(t)}));var Xn=class t{constructor(t=0){this.bitField=t}static has(t,e){return!!(t&1<<e)}static add(t,e){return t|1<<e}static delete(t,e){return t&~(1<<e)}add(t){return this.bitField|=1<<t,this}delete(t){return this.bitField&=~(1<<t),this}has(e){return t.has(this.bitField,e)}clear(){return this.bitField=0,this}valueOf(){return this.bitField}toString(){return this.bitField.toString()}toJSON(){return this.bitField}},Yn=require("events-ex"),Qn=32;function tr(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 er=class{constructor(t){this._capacity=tr(t),this._length=0,this._front=0,this.arr=[]}push(t){const e=this._length;this.checkCapacity(e+1);const n=this._front+e&this._capacity-1;return this.arr[n]=t,this._length=e+1,n}pop(){const t=this._length;if(0===t)return;const e=this._front+t-1&this._capacity-1,n=this.arr[e];return this.arr[e]=void 0,this._length=t-1,n}shift(){const t=this._length;if(0===t)return;const e=this._front,n=this.arr[e];return this.arr[e]=void 0,this._front=e+1&this._capacity-1,this._length=t-1,n}get length(){return this._length}checkCapacity(t){this._capacity<t&&this.resizeTo(tr(1.5*this._capacity+16))}resizeTo(t){const e=this._capacity;this._capacity=t;const n=this._front,r=this._length;if(n+r>e){const t=n+r&e-1;!function(t,e,n,r,s){for(let i=0;i<s;++i)n[i+r]=t[i+e],t[i+e]=void 0}(this.arr,0,this.arr,e,t)}}},nr=class extends Yn.EventEmitter{};function rr(t){return"function"==typeof t}function sr(){return"1"}var ir=class{constructor(t,{initFn:e=sr,pauseFn:n,resumeFn:r,capacity:s=Qn}={}){if(rr(n)!==rr(r))throw new Error("pauseFn and resumeFn must be both set for pausing");this.maxConcurrency=t,this.free=new er(t),this.waiting=new er(s),this.releaseEmitter=new nr,this.useDefaultTokens=e===sr,this.pauseFn=n,this.resumeFn=r,this.paused=!1,this.releaseEmitter.on("release",(t=>{const e=this.waiting.shift();e?e.resolve(t):(this.resumeFn&&this.paused&&(this.paused=!1,this.resumeFn()),this.free.push(t))}));for(let n=0;n<t;n++)this.free.push(e())}tryAcquire(){return this.free.pop()}acquire(t){let e=this.tryAcquire();return void 0!==e?Promise.resolve(e):new Promise(((e,n)=>{this.pauseFn&&!this.paused&&(this.paused=!0,this.pauseFn());const r=this.waiting.push({resolve:e,reject:n});return t&&t.addEventListener("abort",(()=>{this.waiting[r]=void 0;const e=t.reason instanceof Error?t.reason:new Error(t.reason||"aborted");t.alreadyRejected=!0,n(e)})),r}))}release(t){this.releaseEmitter.emit("release",this.useDefaultTokens?"1":t)}drain(){const t=new Array(this.maxConcurrency);for(let e=0;e<this.maxConcurrency;e++)t[e]=this.acquire();return Promise.all(t)}pendingCount(){return this.waiting.length}};function or(t,{timeUnit:e=1e3,uniformDistribution:n=!1}={}){const r=new ir(n?1:t),s=n?e/t:e;return async function(){await r.acquire(),setTimeout((()=>r.release()),s)}}var ar,cr=require("custom-ability"),ur=require("property-manager"),lr=require("util-ex"),fr=0,hr=1,pr=2,wr=(t=>(t[t.MultiTask=fr]="MultiTask",t[t.Cancelable=hr]="Cancelable",t[t.Priority=pr]="Priority",t))(wr||{}),dr=((ar=dr||{})[ar.MultiTask=1<<fr]="MultiTask",ar[ar.Cancelable=1<<hr]="Cancelable",ar[ar.Priority=1<<pr]="Priority",ar),mr=class t extends ur.AdvancePropertyManager{static{this.items={}}static get(t){return this.items[t]}static list(){return this.items}static getByTag(t){let e;for(const n in this.list()){const r=this.get(n);let s=r.tags;if("string"==typeof s){if(s===t){e=r;break}}else if(Array.isArray(s)&&s.indexOf(t)>=0){e=r;break}}return e}static getAllByTag(t){let e=[];for(const n in this.list()){const r=this.get(n);let s=r.tags;"string"==typeof s?s===t&&e.push(r):Array.isArray(s)&&s.indexOf(t)>=0&&e.push(r)}return e}static hasAsyncFeature(t){const e=this.prototype;let n=e.asyncFeatures;return e._asyncFeatures&&(n|=e._asyncFeatures),Xn.has(n,t)}static run(t,e){const n=this.get(t);if(n)return n.run(e);throw new d.NotFoundError(`${t} to run`,this.name)}static runSync(t,e){const n=this.get(t);if(n)return n.runSync(e);throw new d.NotFoundError(`${t} to run`,this.name)}static getFunc(t){const e=this.get(t);return e?.getFunc()}static runWithPos(t,...e){const n=this.get(t);if(n)return n.runWithPos(...e);throw new d.NotFoundError(`${t} to run`,this.name)}static runWithPosSync(t,...e){const n=this.get(t);if(n)return n.runWithPosSync(...e);throw new d.NotFoundError(`${t} to run`,this.name)}static getFuncWithPos(t){const e=this.get(t);return e?.getFuncWithPos()}static register(e,n={}){switch(typeof e){case"string":n.name=e;break;case"function":n.func=e;break;case"object":n=e}e=n.name;let r=!!this.get(e);if(r)r=!1;else{if(!(n instanceof t))return r=new this(n),r.register();this.items[e]=n,r=n}return r}static unregister(t){const e=this.items[t];return e&&delete this.items[t],e}constructor(t,e={}){switch(super(),typeof t){case"string":e.name=t;break;case"function":e.func=t;break;case"object":e=t}this.name=t=e.name,e.scope&&(this.scope=e.scope),"function"==typeof e.setup&&e.setup.call(this,e),this.initialize(e)}register(){const e=this.constructor,n=this.depends;if(n){const e=Object.keys(n);for(const r of e){const e=n[r];e instanceof t&&e.register()}}return e.register(this)}unregister(){return this.constructor.unregister(this.name)}arr2ObjParams(t){if(this.params&&(t.length>1||Array.isArray(t[0])||t[0]&&"object"!=typeof t[0])){const e={},n=Object.keys(this.params);let r=Math.min(n.length,t.length);for(let s=0;s<r;s++)e[n[s]]=t[s];t=[e]}return t}obj2ArrParams(t){const e=[];if(t&&this.params&&Array.isArray(this.params)){const n=Object.keys(t);let r=Math.min(n.length,this.params.length);for(let s=0;s<r;s++)e.push(t[n[s]])}return e}runSync(t){const e=this.params&&Array.isArray(this.params);if(Array.isArray(t)){if(e)return this.func(...t);(0,d.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),Xn.has(e,t)}isStream(t){return this.stream}},yr={name:{type:"string"},description:{type:"string"},func:{type:"function",assign(t,e,n,r,s){let i=t;const o=typeof t;return s.isExported?i="function"===o?t.toString():t:t&&("string"!==o&&(t=t.toString()),i=(0,lr._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"}};mr.defineProperties(mr,yr);var br=require("util-ex"),gr=class extends AbortController{constructor(t){super(),(0,br.defineProperty)(this,"parent",t)}abort(t,e){this.signal.aborted||("string"==typeof t&&(t=new d.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 d.AbortError(e.reason||"aborted")}}},vr=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 ir(t-1)),e}isAborted(t){const e=this.hasAsyncFeature(fr);let n=this.__task_aborter;if(n&&e){if(null==t)throw new d.CommonError("Missing taskId",this.name+".isAborted",d.ErrorCode.InvalidArgument);n=n[t]}return!n||n.signal.aborted}getRunningTask(t){const e=this.hasAsyncFeature(fr);let n=this.__task_aborter;if(n&&e){if(null==t)throw new d.CommonError("Missing taskId",this.name+".getRunningTask",d.ErrorCode.InvalidArgument);n=n[t]}return n?.signal.aborted&&(e?this.__task_aborter[t]=void 0:this.__task_aborter=void 0,n=void 0),n}getRunningTaskCount(){let t;if(this.hasAsyncFeature(fr)){const e=this.__task_aborter;t=e&&Object.entries(e).filter((([t,n])=>{if(!n?.signal.aborted)return!0;e[t]=void 0})).length}else{const e=this.__task_aborter;t=e?.signal.aborted?0:1}return t}_generateAsyncTaskId(t,e){if(e||(e=this.__task_aborter),null==t&&(t=0,e))for(;e[t];)t++;return t}$generateAsyncTaskId(t,e){const n=this.super,r=this.self||this;return t=n?n.call(r,t):this._generateAsyncTaskId(t,e)}createAborter(t,e,n=!0){const r=this.hasAsyncFeature(fr);if(!r&&n&&this.getRunningTask())throw new d.CommonError("The task is running",this.name,d.ErrorCode.TooManyRequests);const s=t?.aborter||new gr(this);if(!(s instanceof gr)){if(!(s instanceof AbortController))throw new d.CommonError("aborter should be an AbortController",this.name,d.ErrorCode.InvalidArgument);Object.setPrototypeOf(s,new gr(this))}if(r){null==this.__task_aborter&&(this.__task_aborter={});const t=this.__task_aborter;null==e&&(e=this.generateAsyncTaskId(e,t)),s.id=e,t[e]=s}else this.__task_aborter=s;const i=t?.timeout;return i>0&&(s.timeoutId=setTimeout((()=>{s.timeoutId=void 0,this.abort("timeout",{timeout:i})}),i)),s.signal.addEventListener("abort",(()=>{const t=s.timeoutId;t&&(s.timeoutId=void 0,clearTimeout(t));const e=s.signal;try{this.emit&&this.emit("aborting",e.reason,e.reason?.data)}finally{s.streamController?.error(e.reason)}})),s}$cleanMultiTaskAborter(t,e){const n=this.super,r=this.self||this;n?n.call(r,t,e):r._cleanMultiTaskAborter(t,e)}cleanTaskAborter(t){if(this.hasAsyncFeature(fr)){const e=this.__task_aborter;this.cleanMultiTaskAborter(t.id,e)}else this.__task_aborter=void 0}_cleanMultiTaskAborter(t,e){"number"==typeof t?e[t]=void 0:delete e[t]}createTaskPromise(t,e,n){const r=this.createAborter(e,n?.taskId,n?.raiseError);void 0===e&&(e={}),"object"==typeof e&&(e.aborter=r);let s=t(e,r).then((t=>{if(t&&t instanceof ReadableStream){const e=()=>{this.cleanTaskAborter(r)},n=je({onStart:t=>{(0,br.defineProperty)(r,"streamController",t)},onFinal:e,onError:e,onTransform:(t,e)=>(t&&"object"==typeof t&&(t.taskId=r.id),t)});t=t.pipeThrough(n)}else this.cleanTaskAborter(r);return t})).catch((t=>{throw this.cleanTaskAborter(r),t})).finally((()=>{r.timeoutId&&(clearTimeout(r.timeoutId),r.timeoutId=void 0)}));return s.task=r,s}runAsyncCancelableTask(t={},e,n){let r=this.createTaskPromise(e,t,n);const s=this.semaphore;if(s){const t=r,e=t.task;r=s.acquire(e.signal).then((()=>t)).finally((()=>{s.release()})),r.task=e}return r}abort(t,e){let n=this.__task_aborter;if(n){const r=n;if(this.hasAsyncFeature(fr)){const t=e?.taskId;if(null==t)throw new d.CommonError("Missing data.taskId",this.name+".abort",d.ErrorCode.InvalidArgument);n=n[t],this.cleanMultiTaskAborter(t,r)}else this.__task_aborter=void 0;n&&!n.signal.aborted&&n.abort(t,e)}}};vr.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},vr.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};var Er=(0,cr.createAbilityInjector)(vr,"abort",{afterInjection:function(t,e){let n=t.prototype._asyncFeatures||0;n|=dr.Cancelable,e&&(e.asyncFeatures&&(n|=e.asyncFeatures),e.maxTaskConcurrency>0&&(t.prototype._maxTaskConcurrency=e.maxTaskConcurrency)),t.prototype._asyncFeatures=n}});function xr(t,e){const n=e.global?e:new RegExp(e.source,`${e.flags}g`);let r,s=0;for(;null!==(r=n.exec(t));)s++;return s}var $r=require("lodash-es"),Sr=require("util-ex");async function kr(t,e,n){return Or(qr(t,e,n),e,n)}function Ar(t){if(t&&!Array.isArray(t)&&"object"==typeof t){const e=Object.entries(t),n=Object.keys(t);1===e.length&&void 0!==t[0]?t=t[0]:n.every((t=>!isNaN(parseInt(t))))?t=n.sort(((t,e)=>parseInt(t)-parseInt(e))).map((e=>t[e])):2===e.length&&"0"===e[0][0]&&e[0][1]===e[1][1]&&(t=t[0])}return t}async function Or(t,e,n){if(t.length){const r=await Promise.all(t.map(((t,r)=>Rr(t,r,e,n)))),s=n?.returnArrayOnly;let i;if(r?.length){i=wn(`{${r.map((t=>t)).join(",")}}`,e)}return i&&!s&&(i=Ar(i)),i}}function Tr(t,e,n,r){const[s,i]=t;if(!s&&"|"===i[0])return"choice: {"+function(t,e,n){const r=qr(t,e,{...n,delimiter:":"}),s={},i=r.map((([t,e],n)=>{if(t){const t=e.indexOf(":"),n=e.slice(0,t).trim();if(s[n])throw new Error("Only one "+n+" is allowed");return s[n]=!0,e}{if("|"===e[0]){if(s.items)throw new Error("Only one items is allowed");return s.items=!0,"items:["+function(t,e='"'){return t.map((t=>Nr(t)?t:e+t+e))}(e.split("|").filter(Boolean))+"]"}const t=parseInt(e.trim());if(!isNaN(t)){if(s.maxPick)throw new Error("Only one maxPick is allowed");return s.maxPick=!0,"maxPick:"+t}if("random"===e||"ai"===e)return s.type=!0,'type:"'+e+'"';if(Nr(e)){if(s.separator)throw new Error("Only one separator is allowed");return s.separator=!0,"separator:"+e}}}));return i}(i,n,r)+"}"}async function jr([t,e],n,r,s){if(!r)return;let i,o;if(t){const t=e.split(":");i=t[0].trim(),o=t[1].trim()}else o=e,i=n+"";const a={template:o,data:{...r,...s?.templateData}};s?.templateFormat&&(a.templateFormat=s.templateFormat);const c=await C.formatIf(a);return c?(o=c,i+":"+JSON.stringify(o)):void 0}async function Cr(t,e,n,r){let s=Tr(t,0,n,r);return s||(s=await jr(t,e,n,r)),s}function Nr(t){const e=t[0];return('"'===e||"'"===e)&&t[t.length-1]===e}function Fr(t){return'"'+t.replace(/(?<!\\)"(?!\\)/g,'\\"')+'"'}var Ir=["true","false","null","undefined","NaN","Infinity"];function Mr(t){return function(t,e=['""',"''","{}"]){return e.some((e=>t[0]===e[0]&&t[t.length-1]===e[1]))}(t)||!Number.isNaN(parseFloat(t))||Ir.includes(t)||Ur(t)}async function Pr(t,e){const n=(0,Sr.newFunction)("async expression",[],`return ${t};`,yn(e));let r=await n.call(this);switch(typeof r){case"number":case"boolean":case"undefined":return r;case"function":return n.toString();default:return JSON.stringify(r)}}async function Rr(t,e,n,r){const[s,i]=t,o=r?.argProcessor;if("function"==typeof o){const s=await o(t,e,n,r);if(s)return s}if(s){const t=i.indexOf(":"),e=i.slice(0,t).trim(),r=i.slice(t+1).trim();if(!(Mr(r)||n&&void 0!==(0,$r.get)(n,r)))return e+":"+Fr(r);if(!Ur(i))try{return e+":"+await Pr.call(this,r,n)}catch(t){}return i}{const t=i.trim();if(n&&void 0!==(0,$r.get)(n,t))return e+":"+t+', "'+t+'":'+t;if(Mr(t))return e+":"+t;if(!Ur(i))try{return e+":"+await Pr.call(this,t,n)}catch(t){}return e+":"+Fr(t)}}function qr(t,e,n){const r=n?.delimiter??",";let s=[],i=!1,o="",a="",c=!1,u="";for(let e=0;e<t.length;e++){const n=t[e];if(n!==r||i||u)if("\\"===n)a+=n,e++,a+=t[e];else if("("!==n&&"["!==n||i)if(u&&n===u)u="",a+=n;else if("{"!==n||i)'"'===n||"'"===n?(i&&n===o?i=!1:i||(i=!0,o=n),a+=n):"="!==n||i||c||!/^[\p{L}\p{N}_ ]+$/u.test(a)?a+=n:(a+=":",c=!0);else{let r,s=e,i=!1,o="",c=-1;for(;s<t.length&&("}"!==(r=t[s])||i||c>0);)"\\"===r?s++:"{"!==r||i?"}"!==r||i?'"'!==r&&"'"!==r||(i&&n===o?i=!1:i||(i=!0,o=n)):c--:c++,s++;s<t.length&&(a+=t.substring(e,s+1),e=s)}else u="("===n?")":"]",a+=n;else a=a.trim(),a.endsWith(":")&&(a+="undefined"),s.push([c,a]),a="",c=!1}return a&&(a=a.trim(),a.endsWith(":")&&(a+="undefined"),s.push([c,a])),s}async function Vr(t,e,n){const r=t.match(/^([^(]+)(?:\((.*)\))?$/);if(!r)throw new Error("Invalid command format");const[,s,i]=r;let o;return i&&(o=await kr(i,e,n)),{command:s.trim(),args:o}}var Br=/^\s*\(\)|[a-zA-Z_$][\w\d$]*|\(([a-zA-Z_$][\w\d$]*)(\s*,\s*([a-zA-Z_$][\w\d$]*))*\)\s*=>/;function Ur(t){return Br.test(t)}var _r=c(require("memoizee")),Lr=require("json-canonicalize");function zr(t,e){var n;void 0!==e?.promise||!function(t){return"function"==typeof t&&"AsyncFunction"===t.constructor.name}(t)&&(!(n=t)||"object"!=typeof n&&"function"!=typeof n||"function"!=typeof n.then)||(e={promise:!0,...e}),void 0===e?.length&&(e={length:!1,...e});const r=e?.normalizer;return(0,_r.default)(t,{...e,normalizer:t=>{if(r){const e=r(t);if("string"===e)return e;e&&(t=e)}return We((0,Lr.canonicalize)(t))}})}var Dr=c(require("net"));async function Jr(t,e=10){return new Promise(((n,r)=>{void 0===t?t=0:("string"==typeof t&&(t=parseInt(t)),t>=0||(t=0));const s=Dr.default.createServer();s.on("error",(n=>{"EADDRINUSE"===n.code&&(t++,--e>0)?s.listen(t):r(n)})),s.on("listening",(async()=>{const t=s.address().port;s.close(),n(t)})),s.listen(t)}))}var Wr=c(require("path")),Kr=require("pkg-dir");function Hr(t){const e=(0,Kr.packageDirectorySync)({cwd:t});if(e)return e;const n=t.split(Wr.default.sep);let r=n.lastIndexOf("dist");if(r>0)return n.slice(0,r).join(Wr.default.sep);if(r=n.lastIndexOf("src"),r>0)return n.slice(0,r).join(Wr.default.sep);throw new Error("can not find package directory")}var Zr=c(require("path"));function Gr(t,e){try{const n=Zr.default.relative(Zr.default.resolve(t),Zr.default.resolve(e));return!n.startsWith("..")&&!Zr.default.isAbsolute(n)}catch{return!1}}function Xr(t,e){return e?.some((e=>Gr(e,t)))}var Yr=require("util-ex");function Qr(t){return(0,Yr.isRegExpStr)(t)||(0,Yr.isRegExp)(t)}var ts=class t extends mr{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,d.throwError)("missing apiRoot to load tools","ClientTools")}static loadFromSync(e){for(const n in e){const r=this.get(n),s=e[n];r?r instanceof t?r.assign(s):(0,d.throwError)(`${n} already registered as ${r.constructor.name}`,"ClientTools"):this.register(s)}}static async fetch(t,e){const n=this.get(t);if(n&&n.fetch)return n.fetch(e)}getUrlParams(t){if(void 0!==t){const e=JSON.stringify(t);if("{}"!==e&&"[]"!==e&&'""'!==e)return"?p="+encodeURIComponent(e)}return""}async fetch(t,e,n){const r={...this.fetchOptions};let s;r.headers&&r.headers["Content-Type"]||(r.headers={"Content-Type":"application/json",...r.headers}),t?.stream&&!r.headers.Connection&&(r.headers.Connection="keep-alive"),e||(e=this.action||"post"),"res"===e&&(e="get"),n?("string"!=typeof n&&(n=JSON.stringify(n)),n=this.name+"/"+n):n=this.name,r.method=e.toUpperCase(),"get"===e||"delete"===e?s=n+this.getUrlParams(t):(r.body=JSON.stringify(t),s=n);const i=await fetch(`${this.apiRoot}/${s}`,r);if(!i.ok){throw await this.errorFrom(i)}return i}async errorFrom(t){let e,n=t.status,r=t.statusText,s=this.name;if(t.body){const n=await t.text();try{const t=JSON.parse(n);t&&(t.error&&(r=t.error),t.name&&(s=t.name),t.data&&(e=t.data,e.name=s,e.what&&(e.msg=r,r=e.what)),t.message&&(r=r+":"+t.message))}catch(t){console.warn("🚀 ~ parse error body to json:",t)}}return(0,d.createError)(r,s,n)}async func(t){const e=await this.fetch(t);if(t?.stream)return e;return await e.json()}},es={...w};ts.defineProperties(ts,es);var ns=class t extends mr{static get apiRoot(){return this._apiRoot}static setApiRoot(t){this._apiRoot=t}static toJSON(){const e={};for(const n in this.items){let r=this.items[n];(r instanceof t||r.isApi)&&(r.allowExportFunc||(r=r.toJSON(),delete r.func),e[n]=r)}return e}func({}){}},rs={...w};ns.defineProperties(ns,rs);var ss=require("events-ex"),is=class extends mr{constructor(){super(...arguments),this._emitter=new ss.EventEmitter,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},os=new is(pe),as=require("secondary-cache");function cs({key:t,value:e,options:n}={}){return void 0!==t?null===e?this.cache.del(t):void 0!==e?this.cache.set(t,e,n):this.cache.get(t):(n&&this.cache.setDefaultOptions(n),this.cache)}function us(t,e){let n=mr.get(t);return n||(n=new mr(t,{func:cs,description:"get/set LRU cache or return the LRUCache object",params:{key:{name:"key",type:"string",description:"the key is undefined means change the default cache options"},value:{name:"value",type:"any",description:"the value to store, if value is null means remove the key"},options:{name:"options",type:"object|number",description:"the optional cache options:{capacity,expires,cleanInterval} or expires"}},result:"any"}),n.cache=new as.Cache(e)),n}var ls=us("lrucache"),fs=class extends ts{async _func(t,e){const n=await this.fetch(e,t);if(e?.stream)return n;return await n.json()}async func(t){const e=t.action;return e&&delete t.action,this._func(e,t)}assignMethods(t){if(Array.isArray(t))for(const e of t){const t=e.startsWith("$")?e.slice(1):e;this[t]||(this[t]=(t=>this._func.bind(this,t))(e))}}},hs={methods:{type:"array",assign(t,e,n,r,s){s?.isExported||e.assignMethods(t)}}};fs.defineProperties(fs,hs);var ps=class extends fs{async fetch(t,e){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let n=t.id;return n||(0,d.throwError)("id is required"),"string"==typeof n&&(n=encodeURIComponent(n)),delete t.id,super.fetch(t,e,n)}"list"===e?e="get":e.startsWith("$")&&(t.act=e,e="post")}return await super.fetch(t,e)}},ws=class extends ps{constructor(){super(...arguments),this._sseEvents={},this._forwardEvents=new Set,this.name=he,this.description="subscribe server sent event",this.ebListener=async function(...t){const e=this.type;this.target.publish&&await this.target.publish({data:t,event:e})}}get evtSource(){let t=this._es;return t&&t.readyState!==EventSource.CLOSED||(t=this.initEventSource(this._esEvents)),t}get active(){return!!this._es&&this._es.readyState!==EventSource.CLOSED}set active(t){t!==this.active&&(t?this.initEventSource(this._esEvents):this._es&&(this._es.close(),this._es=void 0))}initEventSource(t){if("string"==typeof t&&(t=[t]),this._es&&this._es.readyState!==EventSource.CLOSED){if(!this._esEvents||t&&t.every((t=>this._esEvents.includes(t))))return this._es;this._es.close()}const e=t?this.getUrlParams({event:t}):"",n=`${this.apiRoot}/${this.name}${e}`,r=this._es=new EventSource(n);return Object.entries(this._sseEvents).forEach((([t,e])=>{r.addEventListener(t,e)})),this._esEvents=t,r}esListener(t){const e=t.data?JSON.parse(t.data):void 0,n=t.type;if(!this._forwardEvents.has(n)){const t=this.emitter;t&&e&&n&&(Array.isArray(e)?t.emit(n,...e):t.emit(n,e))}}async subscribe(t){const e=await this.sub({event:t});"string"==typeof t&&(t=[t]);const n=this.evtSource;for(const e of t)if(!this._sseEvents[e]){const t=this._sseEvents[e]=this.esListener.bind(this);n.addEventListener(e,t)}return e}async unsubscribe(t){const e=await this.unsub({event:t});"string"==typeof t&&(t=[t]);for(const e of t){const t=this._sseEvents[e];t&&(delete this._sseEvents[e],this.evtSource.removeEventListener(e,t))}return e}forwardEvent(t){"string"==typeof t&&(t=[t]);for(const e of t)this._forwardEvents.has(e)||(this._forwardEvents.add(e),this.on&&this.on(e,this.ebListener))}unforwardEvent(t){"string"==typeof t&&(t=[t]);for(const e of t)this._forwardEvents.has(e)&&(this._forwardEvents.delete(e),this.off&&this.off(e,this.ebListener))}async init(t){if(this.active=!1,this.initEventSource(t),t)return await this.subscribe(t)}},ds=new ws(he),ms=require("util-ex"),ys=class extends ns{constructor(t,e={}){super(t,e),this.params={act:{type:"string"}};const n=this.methods=[];this.initRpcMethods(n)}get SpecialRpcMethodNames(){return this.constructor.SpecialRpcMethodNames}initRpcMethods(t=this.methods){const e=this.SpecialRpcMethodNames;if(Array.isArray(e))for(const n of e)"function"==typeof this[n]&&t.push(n);(0,ms.getAllNames)(Object.getPrototypeOf(this)).filter((t=>t.startsWith("$")&&"function"==typeof this[t])).forEach((e=>{t.push(e);const n=e.slice(1);void 0===this[n]&&(this[n]=this[e])}))}cast(t,e){let n=this.params[t];return n&&("string"!=typeof n&&(n=n.type),"number"===n&&(e=Number(e))),e}getMethodFromParams(t){const e=t?.act;return e}castParams(t){return t}func(t){const e=this.getMethodFromParams(t);if(e&&"function"==typeof this[e])return t=this.castParams(t),this[e](t);throw new d.NotFoundError(e,this.name)}};ys.defineProperties(ys,{methods:{type:"array"}});var bs=class extends ys{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}},gs=os.runSync(),vs=class t extends bs{constructor(){super(...arguments),this.name=he,this.description="subscribe server sent event",this.result="event",this.depends={[pe]:os}}static get sse(){return this._sse||(this._sse=new ye),this._sse}get sse(){return this.constructor.sse}static publish(e,n){return t.sse.publish(e,n)}static{this.ebListener=function(...e){t.sse.publish(e,this.type)}}static subscribe(e,n,r){return t.sse.subscribe(e,n,r)}static alreadyForward(e){const n=gs.listeners(e);for(const e of n)if(e===t.ebListener)return!0}publishSSE(t,e){return this.constructor.publish(t,e)}subscribeSSE(t,e,n){return"string"==typeof n&&(n=[n]),this.constructor.subscribe(t,e,n)}forward(e){Array.isArray(e)||(e=[e]);for(const n of e)t.alreadyForward(n)||gs.on(n,t.ebListener)}unforward(e){"string"==typeof e&&(e=[e]);for(const n of e)gs.off(n,t.ebListener)}list({_req:t,_res:e,event:n}){t&&e&&this.subscribeSSE(t,e,n)}$sub({event:t}){if(t)return this.forward(t),{event:t};(0,d.throwError)("event is required","sub",d.ErrorCode.InvalidArgument)}$unsub({event:t}){if(t)return this.unforward(t),{event:t};(0,d.throwError)("event is required","unsub",d.ErrorCode.InvalidArgument)}$publish({event:t,data:e}){if(t&&e){"string"==typeof t&&(t=[t]);for(const n of t)this.publishSSE(e,n);return{event:t}}(0,d.throwError)("event or data is required","pub",d.ErrorCode.InvalidArgument)}isStream(t){return"list"===this.getMethodFromParams(t)}},Es=new vs(he);function xs(){os.register(),ls.register()}
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{AIArgProcessor as s,AIChatRoles as a,AIMessageTypes as i,AIStream as u,AITextGenerationFinishReasons as r,AbortError as e,AbortErrorCode as n,ActionNames as t,AlreadyExistsError as d,AlreadyExistsErrorCode as m,AsyncFeatureBits as o,AsyncFeatures as f,BaseError as H,CancelableAbility as p,ChoiceArgProcessor as P,ClientToolFuncSchema as h,ClientTools as l,CommonError as v,ConfigFile as F,DefaultAsyncSemaphoreCapacity as k,EnvironmentEx as L,ErrorCode as T,EventBusName as c,EventClient as g,EventName as j,EventServer as y,EventToolFunc as I,FStringPromptTemplate as O,FewShotPromptTemplate as V,FilenameReservedRegex as x,GolangPromptTemplate as z,HfPromptTemplate as B,IntSet as E,InternalErrorCode as N,Interpreter as Q,NIL as S,NotFoundError as U,NotFoundErrorCode as X,NotImplementationError as Y,NotImplementedErrorCode as Z,PASSING_SCORE as b,PromptExampleSelector as q,PromptTemplate as w,PromptTemplateTypes as A,PromptTypes as C,RStreamErrCode as D,RateLimit as G,ReadableStreamError as J,RemoteToolFuncSchema as K,ResClientTools as M,ResServerTools as R,ResponseRStreamErrCode as W,SSEChannel as $,SSEChannelAlreadyClosedErrCode as _,Semaphore as ss,ServerToolFuncSchema as as,ServerTools as is,TaskAbortController as us,Template as rs,TemplateArgProcessor as es,ToolAsyncCancelableBit as ns,ToolAsyncMultiTaskBit as ts,ToolAsyncPriorityBit as ds,ToolFunc as ms,ToolFuncSchema as os,WindowsReservedNameRegex as fs,XXHashAlgorithm as Hs,_lrucache as ps,backendEventable as Ps,base32768 as hs,builtins as ls,canonicalize as vs,countRegexMatches as Fs,createAbilityInjector as ks,createCallbacksTransformer as Ls,createEmptyReadableStream as Ts,createEndWithRepetitionDetector as cs,createError as gs,createEventStreamTransformer as js,createHfValueFunc as ys,createLRUCache as Is,dateToText as Os,defaultTemplateFormat as Vs,event as xs,eventClient as zs,eventServer as Bs,expandEnv as Es,expandObjEnv as Ns,extNameLevel as Qs,fileIsExists as Ss,filenameReservedRegex as Us,filterValidFnScope as Xs,formatISO as Ys,getAllEnumKeys as Zs,getConfigFileNames as bs,getConfigs as qs,getKeysPath as ws,getMultiLevelExtname as As,getPackageDir as Cs,getRealFilepath as Ds,getResponseErrorReadableStream as Gs,interpolateEnv as Js,interpolateFString as Ks,interpolateGolangTemplate as Ms,isModelNameMatched as Rs,isValidFilename as Ws,isValidFilepath as $s,isWebStream as _s,jsonFilterToWhere as sa,jsonToMarkdownStr as aa,loadFileFromPaths as ia,loadTextFromPaths as ua,lrucache as ra,makeToolFuncCancelable as ea,matchUrlProtocol as na,memoize as ta,messagesToText as da,mimeType as ma,paramsSizeToScaleStr as oa,parse as fa,parse2 as Ha,parseCommand as pa,parseDateFormat as Pa,parseFString as ha,parseISO as la,parseJsJson as va,parseObjectArgInfo as Fa,parseObjectArgumentInfos as ka,parseObjectArguments as La,parseObjectArgumentsAsArgInfos as Ta,parseYaml as ca,quoteStr as ga,reControlCharsRegex as ja,readFilenamesRecursiveSync as ya,readableFromAsyncIterable as Ia,registerCoreTools as Oa,registerYamlTag as Va,sanitizeFilename as xa,sanitizeFilepath as za,saveConfigFile as Ba,scaleStrToParamsSize as Ea,simplifyObjectArguments as Na,sortedValues as Qa,splitSentence as Sa,stringify as Ua,stringify2 as Xa,textToDate as Ya,throwError as Za,toDate as ba,toDateTime as qa,tokenize as wa,trimStartOfStreamHelper as Aa,truncTo as Ca,uuid as Da,v1 as Ga,v4 as Ja,v5 as Ka,validate as Ma,version as Ra,wait as Wa,xxhash as $a,xxhash32 as _a,xxhash64 as si,xxhashAsStr as ai}from"./chunk-TOUPOZHH.mjs";import{findPort as ii}from"./chunk-PXQPLL62.mjs";export{s as AIArgProcessor,a as AIChatRoles,i as AIMessageTypes,u as AIStream,r as AITextGenerationFinishReasons,e as AbortError,n as AbortErrorCode,t as ActionNames,d as AlreadyExistsError,m as AlreadyExistsErrorCode,o as AsyncFeatureBits,f as AsyncFeatures,H as BaseError,p as CancelableAbility,P as ChoiceArgProcessor,h as ClientToolFuncSchema,l as ClientTools,v as CommonError,F as ConfigFile,k as DefaultAsyncSemaphoreCapacity,T as ErrorCode,c as EventBusName,g as EventClient,j as EventName,y as EventServer,I as EventToolFunc,O as FStringPromptTemplate,V as FewShotPromptTemplate,x as FilenameReservedRegex,z as GolangPromptTemplate,ls as HFBuiltins,L as HFEnvironment,Q as HFInterpreter,rs as HFTemplate,B as HfPromptTemplate,E as IntSet,N as InternalErrorCode,U as NotFoundError,X as NotFoundErrorCode,Y as NotImplementationError,Z as NotImplementedErrorCode,b as PASSING_SCORE,q as PromptExampleSelector,w as PromptTemplate,A as PromptTemplateTypes,C as PromptTypes,D as RStreamErrCode,G as RateLimit,J as ReadableStreamError,K as RemoteToolFuncSchema,M as ResClientTools,R as ResServerTools,W as ResponseRStreamErrCode,$ as SSEChannel,_ as SSEChannelAlreadyClosedErrCode,ss as Semaphore,as as ServerToolFuncSchema,is as ServerTools,us as TaskAbortController,es as TemplateArgProcessor,ns as ToolAsyncCancelableBit,ts as ToolAsyncMultiTaskBit,ds as ToolAsyncPriorityBit,ms as ToolFunc,os as ToolFuncSchema,fs as WindowsReservedNameRegex,Hs as XXHashAlgorithm,ps as _lrucache,Ps as backendEventable,hs as base32768,vs as canonicalize,Fs as countRegexMatches,ks as createAbilityInjector,Ls as createCallbacksTransformer,Ts as createEmptyReadableStream,cs as createEndWithRepetitionDetector,gs as createError,js as createEventStreamTransformer,ys as createHfValueFunc,Is as createLRUCache,Os as dateToText,Vs as defaultTemplateFormat,xs as event,zs as eventClient,Bs as eventServer,Es as expandEnv,Ns as expandObjEnv,Qs as extNameLevel,Ss as fileIsExists,Us as filenameReservedRegex,Xs as filterValidFnScope,ii as findPort,Ys as formatISO,Zs as getAllEnumKeys,bs as getConfigFileNames,qs as getConfigs,ws as getKeysPath,As as getMultiLevelExtname,Cs as getPackageDir,Ds as getRealFilepath,Gs as getResponseErrorReadableStream,fa as hfParse,wa as hfTokenize,Js as interpolateEnv,Ks as interpolateFString,Ms as interpolateGolangTemplate,Rs as isModelNameMatched,Ws as isValidFilename,$s as isValidFilepath,_s as isWebStream,sa as jsonFilterToWhere,aa as jsonToMarkdownStr,ia as loadFileFromPaths,ua as loadTextFromPaths,ra as lrucache,ea as makeToolFuncCancelable,na as matchUrlProtocol,ta as memoize,da as messagesToText,ma as mimeType,oa as paramsSizeToScaleStr,pa as parseCommand,Pa as parseDateFormat,ha as parseFString,la as parseISO,va as parseJsJson,Fa as parseObjectArgInfo,ka as parseObjectArgumentInfos,La as parseObjectArguments,Ta as parseObjectArgumentsAsArgInfos,ca as parseYaml,ga as quoteStr,ja as reControlCharsRegex,ya as readFilenamesRecursiveSync,Ia as readableFromAsyncIterable,Oa as registerCoreTools,Va as registerYamlTag,xa as sanitizeFilename,za as sanitizeFilepath,Ba as saveConfigFile,Ea as scaleStrToParamsSize,Na as simplifyObjectArguments,Qa as sortedValues,Sa as splitSentence,Xa as stringifyYaml,Ya as textToDate,Za as throwError,ba as toDate,qa as toDateTime,Aa as trimStartOfStreamHelper,Ca as truncTo,Da as uuid,S as uuidNIL,Ha as uuidParse,Ua as uuidStringify,Ma as uuidValidate,Ra as uuidVersion,Ga as uuidv1,Ja as uuidv4,Ka as uuidv5,Wa as wait,$a as xxhash,_a as xxhash32,si as xxhash64,ai as xxhashAsStr};
1
+ import{AIArgProcessor as s,AIChatRoles as a,AIMessageTypes as u,AIStream as i,AITextGenerationFinishReasons as e,AbortError as r,AbortErrorCode as n,ActionNames as t,AlreadyExistsError as d,AlreadyExistsErrorCode as m,AsyncFeatureBits as o,AsyncFeatures as f,BaseError as p,CancelableAbility as F,ChoiceArgProcessor as h,ClientToolFuncSchema as v,ClientTools as H,CommonError as L,ConfigFile as P,DefaultAsyncSemaphoreCapacity as k,EnvironmentEx as l,ErrorCode as V,EventBusName as c,EventClient as j,EventName as I,EventServer as T,EventToolFunc as g,FStringPromptTemplate as x,FewShotPromptTemplate as y,FilenameReservedRegex as z,GolangPromptTemplate as B,HfPromptTemplate as E,IntSet as J,InternalErrorCode as N,Interpreter as Q,NIL as R,NotFoundError as S,NotFoundErrorCode as X,NotImplementationError as b,NotImplementedErrorCode as q,PASSING_SCORE as w,PromptExampleSelector as A,PromptTemplate as C,PromptTemplateTypes as D,PromptTypes as G,RStreamErrCode as K,RateLimit as M,ReadableStreamError as O,RemoteToolFuncSchema as U,ResClientTools as W,ResServerTools as Y,ResponseRStreamErrCode as Z,SSEChannel as $,SSEChannelAlreadyClosedErrCode as _,Semaphore as ss,ServerToolFuncSchema as as,ServerTools as us,TaskAbortController as is,Template as es,TemplateArgProcessor as rs,ToolAsyncCancelableBit as ns,ToolAsyncMultiTaskBit as ts,ToolAsyncPriorityBit as ds,ToolFunc as ms,ToolFuncSchema as os,WindowsReservedNameRegex as fs,XXHashAlgorithm as ps,_lrucache as Fs,backendEventable as hs,base32768 as vs,builtins as Hs,canonicalize as Ls,countRegexMatches as Ps,createAbilityInjector as ks,createCallbacksTransformer as ls,createEmptyReadableStream as Vs,createEndWithRepetitionDetector as cs,createError as js,createEventStreamTransformer as Is,createHfValueFunc as Ts,createLRUCache as gs,dateToText as xs,defaultTemplateFormat as ys,event as zs,eventClient as Bs,eventServer as Es,expandEnv as Js,expandObjEnv as Ns,extNameLevel as Qs,fileIsExists as Rs,filenameReservedRegex as Ss,filterValidFnScope as Xs,formatISO as bs,getAllEnumKeys as qs,getConfigFileNames as ws,getConfigs as As,getKeysPath as Cs,getMultiLevelExtname as Ds,getPackageDir as Gs,getRealFilepath as Ks,getResponseErrorReadableStream as Ms,hasDirectoryIn as Os,interpolateEnv as Us,interpolateFString as Ws,interpolateGolangTemplate as Ys,isModelNameMatched as Zs,isRegExp as $s,isSubdirectory as _s,isValidFilename as sa,isValidFilepath as aa,isWebStream as ua,jsonFilterToWhere as ia,jsonToMarkdownStr as ea,loadFileFromPaths as ra,loadTextFromPaths as na,lrucache as ta,makeToolFuncCancelable as da,matchUrlProtocol as ma,memoize as oa,messagesToText as fa,mimeType as pa,paramsSizeToScaleStr as Fa,parse as ha,parse2 as va,parseCommand as Ha,parseDateFormat as La,parseFString as Pa,parseISO as ka,parseJsJson as la,parseObjectArgInfo as Va,parseObjectArgumentInfos as ca,parseObjectArguments as ja,parseObjectArgumentsAsArgInfos as Ia,parseYaml as Ta,quoteStr as ga,reControlCharsRegex as xa,readFilenamesRecursiveSync as ya,readableFromAsyncIterable as za,registerCoreTools as Ba,registerYamlTag as Ea,sanitizeFilename as Ja,sanitizeFilepath as Na,saveConfigFile as Qa,scaleStrToParamsSize as Ra,simplifyObjectArguments as Sa,sortedValues as Xa,splitSentence as ba,stringify as qa,stringifyYaml as wa,textToDate as Aa,throwError as Ca,toDate as Da,toDateTime as Ga,toRegExp as Ka,tokenize as Ma,trimStartOfStreamHelper as Oa,truncTo as Ua,uuid as Wa,v1 as Ya,v4 as Za,v5 as $a,validate as _a,version as su,wait as au,xxhash as uu,xxhash32 as iu,xxhash64 as eu,xxhashAsStr as ru}from"./chunk-FLVJ4R53.mjs";import{findPort as nu}from"./chunk-PXQPLL62.mjs";export{s as AIArgProcessor,a as AIChatRoles,u as AIMessageTypes,i as AIStream,e as AITextGenerationFinishReasons,r as AbortError,n as AbortErrorCode,t as ActionNames,d as AlreadyExistsError,m as AlreadyExistsErrorCode,o as AsyncFeatureBits,f as AsyncFeatures,p as BaseError,F as CancelableAbility,h as ChoiceArgProcessor,v as ClientToolFuncSchema,H as ClientTools,L as CommonError,P as ConfigFile,k as DefaultAsyncSemaphoreCapacity,V as ErrorCode,c as EventBusName,j as EventClient,I as EventName,T as EventServer,g as EventToolFunc,x as FStringPromptTemplate,y as FewShotPromptTemplate,z as FilenameReservedRegex,B as GolangPromptTemplate,Hs as HFBuiltins,l as HFEnvironment,Q as HFInterpreter,es as HFTemplate,E as HfPromptTemplate,J as IntSet,N as InternalErrorCode,S as NotFoundError,X as NotFoundErrorCode,b as NotImplementationError,q as NotImplementedErrorCode,w as PASSING_SCORE,A as PromptExampleSelector,C as PromptTemplate,D as PromptTemplateTypes,G as PromptTypes,K as RStreamErrCode,M as RateLimit,O as ReadableStreamError,U as RemoteToolFuncSchema,W as ResClientTools,Y as ResServerTools,Z as ResponseRStreamErrCode,$ as SSEChannel,_ as SSEChannelAlreadyClosedErrCode,ss as Semaphore,as as ServerToolFuncSchema,us as ServerTools,is as TaskAbortController,rs as TemplateArgProcessor,ns as ToolAsyncCancelableBit,ts as ToolAsyncMultiTaskBit,ds as ToolAsyncPriorityBit,ms as ToolFunc,os as ToolFuncSchema,fs as WindowsReservedNameRegex,ps as XXHashAlgorithm,Fs as _lrucache,hs as backendEventable,vs as base32768,Ls as canonicalize,Ps as countRegexMatches,ks as createAbilityInjector,ls as createCallbacksTransformer,Vs as createEmptyReadableStream,cs as createEndWithRepetitionDetector,js as createError,Is as createEventStreamTransformer,Ts as createHfValueFunc,gs as createLRUCache,xs as dateToText,ys as defaultTemplateFormat,zs as event,Bs as eventClient,Es as eventServer,Js as expandEnv,Ns as expandObjEnv,Qs as extNameLevel,Rs as fileIsExists,Ss as filenameReservedRegex,Xs as filterValidFnScope,nu as findPort,bs as formatISO,qs as getAllEnumKeys,ws as getConfigFileNames,As as getConfigs,Cs as getKeysPath,Ds as getMultiLevelExtname,Gs as getPackageDir,Ks as getRealFilepath,Ms as getResponseErrorReadableStream,Os as hasDirectoryIn,ha as hfParse,Ma as hfTokenize,Us as interpolateEnv,Ws as interpolateFString,Ys as interpolateGolangTemplate,Zs as isModelNameMatched,$s as isRegExp,_s as isSubdirectory,sa as isValidFilename,aa as isValidFilepath,ua as isWebStream,ia as jsonFilterToWhere,ea as jsonToMarkdownStr,ra as loadFileFromPaths,na as loadTextFromPaths,ta as lrucache,da as makeToolFuncCancelable,ma as matchUrlProtocol,oa as memoize,fa as messagesToText,pa as mimeType,Fa as paramsSizeToScaleStr,Ha as parseCommand,La as parseDateFormat,Pa as parseFString,ka as parseISO,la as parseJsJson,Va as parseObjectArgInfo,ca as parseObjectArgumentInfos,ja as parseObjectArguments,Ia as parseObjectArgumentsAsArgInfos,Ta as parseYaml,ga as quoteStr,xa as reControlCharsRegex,ya as readFilenamesRecursiveSync,za as readableFromAsyncIterable,Ba as registerCoreTools,Ea as registerYamlTag,Ja as sanitizeFilename,Na as sanitizeFilepath,Qa as saveConfigFile,Ra as scaleStrToParamsSize,Sa as simplifyObjectArguments,Xa as sortedValues,ba as splitSentence,wa as stringifyYaml,Aa as textToDate,Ca as throwError,Da as toDate,Ga as toDateTime,Ka as toRegExp,Oa as trimStartOfStreamHelper,Ua as truncTo,Wa as uuid,R as uuidNIL,va as uuidParse,qa as uuidStringify,_a as uuidValidate,su as uuidVersion,Ya as uuidv1,Za as uuidv4,$a as uuidv5,au as wait,uu as xxhash,iu as xxhash32,eu as xxhash64,ru as xxhashAsStr};