@isdk/ai-tool 0.1.2 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-COXUI4Q3.mjs → chunk-O367BMRE.mjs} +1 -1
- package/dist/funcs.mjs +1 -1
- package/dist/index.d.mts +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/docs/classes/AbortError.md +8 -8
- package/docs/classes/AlreadyExistsError.md +8 -8
- package/docs/classes/BaseError.md +8 -8
- package/docs/classes/CancelableAbility.md +20 -20
- package/docs/classes/ClientTools.md +55 -55
- package/docs/classes/CommonError.md +8 -8
- package/docs/classes/EventClient.md +77 -77
- package/docs/classes/EventServer.md +78 -78
- package/docs/classes/EventToolFunc.md +46 -46
- package/docs/classes/FStringPromptTemplate.md +18 -18
- package/docs/classes/FewShotPromptTemplate.md +22 -22
- package/docs/classes/GolangPromptTemplate.md +18 -18
- package/docs/classes/HFEnvironment.md +9 -9
- package/docs/classes/HFInterpreter.md +19 -19
- package/docs/classes/HFTemplate.md +4 -4
- package/docs/classes/HfPromptTemplate.md +18 -18
- package/docs/classes/IntSet.md +12 -12
- package/docs/classes/NotFoundError.md +8 -8
- package/docs/classes/NotImplementationError.md +8 -8
- package/docs/classes/PromptExampleSelector.md +8 -8
- package/docs/classes/PromptTemplate.md +17 -17
- package/docs/classes/ReadableStreamError.md +8 -8
- package/docs/classes/ResClientTools.md +61 -61
- package/docs/classes/ResServerTools.md +62 -62
- package/docs/classes/SSEChannel.md +15 -15
- package/docs/classes/Semaphore.md +14 -14
- package/docs/classes/ServerTools.md +51 -51
- package/docs/classes/TaskAbortController.md +7 -7
- package/docs/classes/ToolFunc.md +43 -43
- package/docs/enums/AsyncFeatureBits.md +3 -3
- package/docs/enums/AsyncFeatures.md +3 -3
- package/docs/enums/ErrorCode.md +21 -21
- package/docs/enums/XXHashAlgorithm.md +2 -2
- package/docs/interfaces/AIChatAssistantMessageParam.md +6 -6
- package/docs/interfaces/AIChatContentPartImage.md +2 -2
- package/docs/interfaces/AIChatContentPartText.md +2 -2
- package/docs/interfaces/AIChatMessageParamBase.md +1 -1
- package/docs/interfaces/AIChatMessageToolCall.md +3 -3
- package/docs/interfaces/AIChatSystemMessageParam.md +3 -3
- package/docs/interfaces/AIChatToolMessageParam.md +4 -4
- package/docs/interfaces/AIChatUserMessageParam.md +7 -7
- package/docs/interfaces/AIChoiceConfig.md +7 -7
- package/docs/interfaces/AIResult.md +5 -5
- package/docs/interfaces/AIStreamParser.md +1 -1
- package/docs/interfaces/AIStreamParserOptions.md +1 -1
- package/docs/interfaces/BaseFunc.md +9 -9
- package/docs/interfaces/BaseFuncItem.md +8 -8
- package/docs/interfaces/CancelableAbilityOptions.md +2 -2
- package/docs/interfaces/ClientFuncItem.md +11 -11
- package/docs/interfaces/DotenvExpandOptions.md +3 -3
- package/docs/interfaces/DotenvExpandOutput.md +2 -2
- package/docs/interfaces/EventClientFuncParams.md +4 -4
- package/docs/interfaces/EventServerFuncParams.md +5 -5
- package/docs/interfaces/FewShotPromptTemplateOptions.md +11 -11
- package/docs/interfaces/FuncItem.md +9 -9
- package/docs/interfaces/FuncParam.md +6 -6
- package/docs/interfaces/ParseObjectArgumentOptions.md +5 -5
- package/docs/interfaces/PromptExampleSelectorOptions.md +2 -2
- package/docs/interfaces/PromptTemplateOptions.md +6 -6
- package/docs/interfaces/RemoteFuncItem.md +11 -11
- package/docs/interfaces/ResClientFuncParams.md +2 -2
- package/docs/interfaces/ResServerFuncParams.md +5 -5
- package/docs/interfaces/SanitizeFilenameOptions.md +2 -2
- package/docs/interfaces/ServerFuncItem.md +12 -12
- package/docs/interfaces/ServerFuncParams.md +2 -2
- package/docs/interfaces/StreamCallbacksAndOptions.md +4 -4
- package/docs/interfaces/TaskPromise.md +1 -1
- package/docs/interfaces/ToolFuncPackage.md +3 -3
- package/docs/modules.md +152 -131
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EventEmitter as t}from"events-ex";import{AdvancePropertyManager as e}from"property-manager";import{_createFunction as n}from"util-ex";import{AbstractError as r,createErrorClass as s}from"abstract-error";var i=(t=>(t[t.OK=200]="OK",t[t.Accepted=202]="Accepted",t[t.BadRequest=400]="BadRequest",t[t.InvalidArgument=400]="InvalidArgument",t[t.Unauthorized=401]="Unauthorized",t[t.PaymentRequired=402]="PaymentRequired",t[t.Forbidden=403]="Forbidden",t[t.NotFound=404]="NotFound",t[t.MethodNotAllowed=405]="MethodNotAllowed",t[t.NotAcceptable=406]="NotAcceptable",t[t.RequestTimeout=408]="RequestTimeout",t[t.Conflict=409]="Conflict",t[t.Corruption=409]="Corruption",t[t.TooManyRequests=429]="TooManyRequests",t[t.Aborted=499]="Aborted",t[t.InternalError=500]="InternalError",t[t.NotImplemented=501]="NotImplemented",t[t.NotSupported=501]="NotSupported",t[t.BadGateway=502]="BadGateway",t[t.ServiceUnavailable=503]="ServiceUnavailable",t[t.GatewayTimeout=504]="GatewayTimeout",t))(i||{}),o=500,a=501,c=404,u=409,f=499,h=class t extends r{static createErrorClass(e,n,r=t){return s(e,n,r)}constructor(t,e,n){super(t,e);const r=this.constructor;null!=e?this.code=e:r.code?this.code=r.code:this.code=r.name,n?"string"==typeof n?this.name=n:Object.assign(this,n):"string"==typeof this.code?this.name=this.code:this.name=r.name}toJSON(){const t={name:this.name,code:this.code,data:this.data,caller:this.caller,error:this.message,stack:this.stack};return Object.keys(t).forEach((e=>void 0===t[e]&&delete t[e])),t}fromJSON(e){const n=new t(e.message);return n.code=e.code,n.data=e.data,n.caller=e.caller,n.message=e.error,n.stack=e.stack,n}},l=class extends h{constructor(t,e,n=o){super(t,n,e)}},p=class extends l{constructor(t,e){t||(t="Not Implementation."),super(t,e,501)}};l[501]=p;var w=class extends l{static{this.code=c}constructor(t,e){super(`Could not find ${t}.`,e,c),this.data={what:t}}};l[404]=w;var d=class extends l{static{this.code=u}constructor(t,e){super(`The ${t} already exists.`,e,u),this.data={what:t}}};l[409]=d;var m=class extends l{static{this.code=f}constructor(t,e){e||(e="AbortError"),super(t?`The operation was aborted for ${t}.`:"The operation was aborted.",e,f),t&&(this.data={what:t})}};function y(t,e,n=o){const r=new(l[n]||l)(t,e,n);return"number"!=typeof r.code&&(r.code=n),r}function b(t,e,n=o){throw y(t,e,n)}l[499]=m;import{createAbilityInjector as g}from"custom-ability";var v=.618,x=["get","post","put","delete","patch","list","res"],E={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"}};import{format as $,parse as k,parseISO as S}from"date-fns";import{formatISO as O,parseISO as j,toDate as A}from"date-fns";var N="MMMM d, y 'at' h:m:s b 'GMT'x";function C(t){let e;try{"string"==typeof t?e=S(t):"number"==typeof t?e=new Date(t):t instanceof Date&&(e=t)}catch(t){console.error(t)}return e}function T(t,e=N){return k(t,e,new Date)}function M(t,e=N){return $(t,e)}var I=["stop","length","content-filter","tool-calls","abort","error","other",null],F=["human","ai","generic","system","tool"],P=["user","assistant","system","tool","tool_calls"];function U(t){let e="";for(const n of t)if(n.content){e+=n.role.toLowerCase()+":";let t=n.createdAt;if(t){const n=C(t);n&&(e+=" ["+M(n)+"]")}e+=" "+n.content+"\n"}return e}var V=["chat","char","plan"],B=["internal","hf","fill"];import{BaseFactory as R}from"custom-factory";var _="default",L=class t extends R{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||_,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||_);if(e)return Reflect.construct(e,arguments);throw new l(`Prompt template type ${r} not found`,"PromptTemplate",400)}}_initialize(t){throw new p("Not implemented","PromptTemplate")}initialize(e){this.constructor!==t&&(Object.assign(this,this.toJSON(e)),e?.ignoreInitialize||this._initialize(e))}_format(t){throw new p("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 z(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 q=!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=>{q=t}));var J=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,q?r:z(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()}},D=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"}),W=Object.freeze({set:D.Set,for:D.For,in:D.In,is:D.Is,if:D.If,else:D.Else,endif:D.EndIf,elif:D.ElseIf,endfor:D.EndFor,and:D.And,or:D.Or,not:D.Not,"not in":D.NotIn,macro:D.Macro,endmacro:D.EndMacro,true:D.BooleanLiteral,false:D.BooleanLiteral,True:D.BooleanLiteral,False:D.BooleanLiteral}),K=class{constructor(t,e){this.value=t,this.type=e}};function Z(t){return/\w/.test(t)}function G(t){return/[0-9]/.test(t)}var H=[["{%",D.OpenStatement],["%}",D.CloseStatement],["{{",D.OpenExpression],["}}",D.CloseExpression],["(",D.OpenParen],[")",D.CloseParen],["{",D.OpenCurlyBracket],["}",D.CloseCurlyBracket],["[",D.OpenSquareBracket],["]",D.CloseSquareBracket],[",",D.Comma],[".",D.Dot],[":",D.Colon],["|",D.Pipe],["<=",D.ComparisonBinaryOperator],[">=",D.ComparisonBinaryOperator],["==",D.ComparisonBinaryOperator],["!=",D.ComparisonBinaryOperator],["<",D.ComparisonBinaryOperator],[">",D.ComparisonBinaryOperator],["+",D.AdditiveBinaryOperator],["-",D.AdditiveBinaryOperator],["*",D.MultiplicativeBinaryOperator],["/",D.MultiplicativeBinaryOperator],["%",D.MultiplicativeBinaryOperator],["=",D.Equals]],X=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function Q(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=X.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===D.CloseStatement||t===D.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 K(t,D.Text));continue}}i((t=>/\s/.test(t)));const e=r[s];if("-"===e||"+"===e){const t=n.at(-1)?.type;if(t===D.Text||void 0===t)throw new SyntaxError(`Unexpected character: ${e}`);switch(t){case D.Identifier:case D.NumericLiteral:case D.BooleanLiteral:case D.StringLiteral:case D.CloseParen:case D.CloseSquareBracket:break;default:{++s;const t=i(G);n.push(new K(`${e}${t}`,t.length>0?D.NumericLiteral:D.UnaryOperator));continue}}}for(const[t,e]of H){if(r.slice(s,s+t.length)===t){n.push(new K(t,e)),s+=t.length;continue t}}if("'"!==e&&'"'!==e)if(G(e)){const t=i(G);n.push(new K(t,D.NumericLiteral))}else{if(!Z(e))throw new SyntaxError(`Unexpected character: ${e}`);{const t=i(Z),e=Object.hasOwn(W,t)?W[t]:D.Identifier;e===D.In&&n.at(-1)?.type===D.Not?(n.pop(),n.push(new K("not in",D.NotIn))):n.push(new K(t,e))}}else{++s;const t=i((t=>t!==e));n.push(new K(t,D.StringLiteral)),++s}}return n}var Y=class{constructor(){this.type="Statement"}},tt=class extends Y{constructor(t){super(),this.body=t,this.type="Program"}},et=class extends Y{constructor(t,e,n){super(),this.test=t,this.body=e,this.alternate=n,this.type="If"}},nt=class extends Y{constructor(t,e,n,r){super(),this.loopvar=t,this.iterable=e,this.body=n,this.defaultBlock=r,this.type="For"}},rt=class extends Y{constructor(t,e){super(),this.assignee=t,this.value=e,this.type="Set"}},st=class extends Y{constructor(t,e,n){super(),this.name=t,this.args=e,this.body=n,this.type="Macro"}},it=class extends Y{constructor(){super(...arguments),this.type="Expression"}},ot=class extends it{constructor(t,e,n){super(),this.object=t,this.property=e,this.computed=n,this.type="MemberExpression"}},at=class extends it{constructor(t,e){super(),this.callee=t,this.args=e,this.type="CallExpression"}},ct=class extends it{constructor(t){super(),this.value=t,this.type="Identifier"}},ut=class extends it{constructor(t){super(),this.value=t,this.type="Literal"}},ft=class extends ut{constructor(){super(...arguments),this.type="NumericLiteral"}},ht=class extends ut{constructor(){super(...arguments),this.type="StringLiteral"}},lt=class extends ut{constructor(){super(...arguments),this.type="BooleanLiteral"}},pt=class extends ut{constructor(){super(...arguments),this.type="ArrayLiteral"}},wt=class extends ut{constructor(){super(...arguments),this.type="TupleLiteral"}},dt=class extends ut{constructor(){super(...arguments),this.type="ObjectLiteral"}},mt=class extends it{constructor(t,e,n){super(),this.operator=t,this.left=e,this.right=n,this.type="BinaryExpression"}},yt=class extends it{constructor(t,e){super(),this.operand=t,this.filter=e,this.type="FilterExpression"}},bt=class extends it{constructor(t,e){super(),this.iterable=t,this.test=e,this.type="SelectExpression"}},gt=class extends it{constructor(t,e,n){super(),this.operand=t,this.negate=e,this.test=n,this.type="TestExpression"}},vt=class extends it{constructor(t,e){super(),this.operator=t,this.argument=e,this.type="UnaryExpression"}},xt=class extends it{constructor(t=void 0,e=void 0,n=void 0){super(),this.start=t,this.stop=e,this.step=n,this.type="SliceExpression"}},Et=class extends it{constructor(t,e){super(),this.key=t,this.value=e,this.type="KeywordArgumentExpression"}};function $t(t){const e=new tt([]);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 D.Text:e=new ht(r(D.Text,"Expected text token").value);break;case D.OpenStatement:e=function(){let e;switch(r(D.OpenStatement,"Expected opening statement token"),t[n].type){case D.Set:++n,e=a(),r(D.CloseStatement,"Expected closing statement token");break;case D.If:++n,e=c(),r(D.OpenStatement,"Expected {% token"),r(D.EndIf,"Expected endif token"),r(D.CloseStatement,"Expected %} token");break;case D.Macro:++n,e=function(){const t=x();if("Identifier"!==t.type)throw new SyntaxError("Expected identifier following macro statement");const e=y();r(D.CloseStatement,"Expected closing statement token");const n=[];for(;i(D.OpenStatement,D.EndMacro);)n.push(s());return new st(t,e,n)}(),r(D.OpenStatement,"Expected {% token"),r(D.EndMacro,"Expected endmacro token"),r(D.CloseStatement,"Expected %} token");break;case D.For:++n,e=function(){const t=u(!0);if(!(t instanceof ct||t instanceof wt))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${t.type} instead`);r(D.In,"Expected `in` keyword following loop variable");const e=f();r(D.CloseStatement,"Expected closing statement token");const a=[];for(;i(D.OpenStatement,D.EndFor)&&i(D.OpenStatement,D.Else);)a.push(s());const c=[];if(o(D.OpenStatement,D.Else))for(++n,++n,r(D.CloseStatement,"Expected closing statement token");i(D.OpenStatement,D.EndFor);)c.push(s());return new nt(t,e,a,c)}(),r(D.OpenStatement,"Expected {% token"),r(D.EndFor,"Expected endfor token"),r(D.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${t[n].type} ${t[n].value}`)}return e}(),e.isStatement=!0;break;case D.OpenExpression:e=function(){r(D.OpenExpression,"Expected opening expression token");const t=f();return r(D.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=f();if(o(D.Equals)){++n;const e=a();return new rt(t,e)}return t}function c(){const e=f();r(D.CloseStatement,"Expected closing statement token");const i=[],a=[];for(;t[n]?.type!==D.OpenStatement||t[n+1]?.type!==D.ElseIf&&t[n+1]?.type!==D.Else&&t[n+1]?.type!==D.EndIf;)i.push(s());if(t[n]?.type===D.OpenStatement&&t[n+1]?.type!==D.EndIf)if(++n,o(D.ElseIf))r(D.ElseIf,"Expected elseif token"),a.push(c());else for(r(D.Else,"Expected else token"),r(D.CloseStatement,"Expected closing statement token");t[n]?.type!==D.OpenStatement||t[n+1]?.type!==D.EndIf;)a.push(s());return new et(e,i,a)}function u(t=!1){const e=t?x:f,r=[e()],s=o(D.Comma);for(;s&&(++n,r.push(e()),o(D.Comma)););return s?new wt(r):r[0]}function f(){return function(){const t=h();if(o(D.If)){++n;const e=h();if(o(D.Else)){++n;const r=h();return new et(e,[t],[r])}return new bt(t,e)}return t}()}function h(){let e=l();for(;o(D.Or);){const r=t[n];++n;const s=l();e=new mt(r,e,s)}return e}function l(){let e=p();for(;o(D.And);){const r=t[n];++n;const s=p();e=new mt(r,e,s)}return e}function p(){let e;for(;o(D.Not);){const r=t[n];++n;const s=p();e=new vt(r,s)}return e??function(){let e=w();for(;o(D.ComparisonBinaryOperator)||o(D.In)||o(D.NotIn);){const r=t[n];++n;const s=w();e=new mt(r,e,s)}return e}()}function w(){let e=g();for(;o(D.AdditiveBinaryOperator);){const r=t[n];++n;const s=g();e=new mt(r,e,s)}return e}function d(){const e=function(){let e=x();for(;o(D.Dot)||o(D.OpenSquareBracket);){const s=t[n];let i;++n;const o=s.type!==D.Dot;if(o)i=b(),r(D.CloseSquareBracket,"Expected closing square bracket");else if(i=x(),"Identifier"!==i.type)throw new SyntaxError("Expected identifier following dot operator");e=new ot(e,i,o)}return e}();return o(D.OpenParen)?m(e):e}function m(t){let e=new at(t,y());return o(D.OpenParen)&&(e=m(e)),e}function y(){r(D.OpenParen,"Expected opening parenthesis for arguments list");const t=function(){const t=[];for(;!o(D.CloseParen);){let e=f();if(o(D.Equals)){if(++n,!(e instanceof ct))throw new SyntaxError("Expected identifier for keyword argument");const t=f();e=new Et(e,t)}t.push(e),o(D.Comma)&&++n}return t}();return r(D.CloseParen,"Expected closing parenthesis for arguments list"),t}function b(){const t=[];let e=!1;for(;!o(D.CloseSquareBracket);)o(D.Colon)?(t.push(void 0),++n,e=!0):(t.push(f()),o(D.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 xt(...t)}return t[0]}function g(){let e=v();for(;o(D.MultiplicativeBinaryOperator);){const r=t[n];++n;const s=v();e=new mt(r,e,s)}return e}function v(){let t=function(){let t=d();for(;o(D.Pipe);){++n;let e=x();if(!(e instanceof ct))throw new SyntaxError("Expected identifier for the filter");o(D.OpenParen)&&(e=m(e)),t=new yt(t,e)}return t}();for(;o(D.Is);){++n;const e=o(D.Not);e&&++n;let r=x();if(r instanceof lt&&(r=new ct(r.value.toString())),!(r instanceof ct))throw new SyntaxError("Expected identifier for the test");t=new gt(t,e,r)}return t}function x(){const e=t[n];switch(e.type){case D.NumericLiteral:return++n,new ft(Number(e.value));case D.StringLiteral:return++n,new ht(e.value);case D.BooleanLiteral:return++n,new lt("true"===e.value.toLowerCase());case D.Identifier:return++n,new ct(e.value);case D.OpenParen:{++n;const e=u();if(t[n].type!==D.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${t[n].type} instead`);return++n,e}case D.OpenSquareBracket:{++n;const t=[];for(;!o(D.CloseSquareBracket);)t.push(f()),o(D.Comma)&&++n;return++n,new pt(t)}case D.OpenCurlyBracket:{++n;const t=new Map;for(;!o(D.CloseCurlyBracket);){const e=f();r(D.Colon,"Expected colon between key and value in object literal");const s=f();t.set(e,s),o(D.Comma)&&++n}return++n,new dt(t)}default:throw new SyntaxError(`Unexpected token: ${e.type}`)}}for(;n<t.length;)e.body.push(s());return e}function kt(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 St(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 Ot(t){return t.replace(/\b\w/g,(t=>t.toUpperCase()))}var jt=class{constructor(t=void 0){this.type="RuntimeValue",this.builtins=new Map,this.value=t}__bool__(){return new Ct(!!this.value)}toString(){return""+this.value}toJSON(){return this.value}},At=class extends jt{constructor(){super(...arguments),this.type="NumericValue"}},Nt=class t extends jt{constructor(){super(...arguments),this.type="StringValue",this.builtins=new Map([["upper",new Pt((()=>new t(this.value.toUpperCase())))],["lower",new Pt((()=>new t(this.value.toLowerCase())))],["strip",new Pt((()=>new t(this.value.trim())))],["title",new Pt((()=>new t(Ot(this.value))))],["length",new At(this.value.length)],["rstrip",new Pt((()=>new t(this.value.trimEnd())))],["lstrip",new Pt((()=>new t(this.value.trimStart())))]])}},Ct=class extends jt{constructor(){super(...arguments),this.type="BooleanValue"}},Tt=class extends jt{constructor(t,e){super(t),this.orgValue=e,this.type="ObjectValue",this.builtins=new Map([["get",new Pt((([t,e])=>{if(!(t instanceof Nt))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new Ut}))],["items",new Pt((()=>new It(Array.from(this.value.entries()).map((([t,e])=>new It([new Nt(t),e]))))))]])}toString(){let t;return t=this.orgValue&&this.orgValue.toString!==Object.prototype.toString?this.orgValue.toString():JSON.stringify(Object.fromEntries(this.value.entries())),t}toJSON(){return this.orgValue?this.orgValue:Object.fromEntries(this.value.entries())}__bool__(){return new Ct(this.value.size>0)}},Mt=class extends Tt{constructor(){super(...arguments),this.type="KeywordArgumentsValue"}},It=class extends jt{constructor(){super(...arguments),this.type="ArrayValue",this.builtins=new Map([["length",new At(this.value.length)]])}__bool__(){return new Ct(this.value.length>0)}},Ft=class extends It{constructor(){super(...arguments),this.type="TupleValue"}},Pt=class extends jt{constructor(){super(...arguments),this.type="FunctionValue"}},Ut=class extends jt{constructor(){super(...arguments),this.type="NullValue"}},Vt=class extends jt{constructor(){super(...arguments),this.type="UndefinedValue"}},Bt=class{constructor(t){this.parent=t,this.variables=new Map([["namespace",new Pt((t=>{if(0===t.length)return new Tt(new Map);if(1!==t.length||!(t[0]instanceof Tt))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 Pt],["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 It||t instanceof Nt],["lower",t=>{const e=t.value;return"StringValue"===t.type&&e===e.toLowerCase()}],["upper",t=>{const e=t.value;return"StringValue"===t.type&&e===e.toUpperCase()}],["none",t=>"NullValue"===t.type],["defined",t=>"UndefinedValue"!==t.type],["undefined",t=>"UndefinedValue"===t.type],["equalto",(t,e)=>t.value===e.value],["eq",(t,e)=>t.value===e.value]])}set(t,e){return this.declareVariable(t,_t(e))}declareVariable(t,e){if(this.variables.has(t))throw new SyntaxError(`Variable already declared: ${t}`);return this.variables.set(t,e),e}setVariable(t,e){return this.variables.set(t,e),e}resolve(t){if(this.variables.has(t))return this;if(this.parent)return this.parent.resolve(t);throw new Error(`Unknown variable: ${t}`)}lookupVariable(t){try{return this.resolve(t).variables.get(t)??new Vt}catch{return new Vt}}},Rt=class{constructor(t){this.global=t??new Bt}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 Ct(n.value==r.value);case"!=":return new Ct(n.value!=r.value)}if(n instanceof Vt||r instanceof Vt)throw new Error("Cannot perform operation on undefined values");if(n instanceof Ut||r instanceof Ut)throw new Error("Cannot perform operation on null values");if(n instanceof At&&r instanceof At)switch(t.operator.value){case"+":return new At(n.value+r.value);case"-":return new At(n.value-r.value);case"*":return new At(n.value*r.value);case"/":return new At(n.value/r.value);case"%":return new At(n.value%r.value);case"<":return new Ct(n.value<r.value);case">":return new Ct(n.value>r.value);case">=":return new Ct(n.value>=r.value);case"<=":return new Ct(n.value<=r.value)}else if(n instanceof It&&r instanceof It){if("+"===t.operator.value)return new It(n.value.concat(r.value))}else if(r instanceof It){const e=void 0!==r.value.find((t=>t.value===n.value));switch(t.operator.value){case"in":return new Ct(e);case"not in":return new Ct(!e)}}if((n instanceof Nt||r instanceof Nt)&&"+"===t.operator.value)return new Nt(n.toString()+r.toString());if(n instanceof Nt&&r instanceof Nt)switch(t.operator.value){case"in":return new Ct(r.value.includes(n.value));case"not in":return new Ct(!r.value.includes(n.value))}if(n instanceof Nt&&r instanceof Tt)switch(t.operator.value){case"in":return new Ct(r.value.has(n.value));case"not in":return new Ct(!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 Pt)return s.value([n],e);if(n instanceof It)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 At(n.value.length);case"reverse":return new It(n.value.reverse());case"sort":return new It(n.value.sort(((t,e)=>{if(t.type!==e.type)throw new Error(`Cannot compare different types: ${t.type} and ${e.type}`);switch(t.type){case"NumericValue":return t.value-e.value;case"StringValue":return t.value.localeCompare(e.value);default:throw new Error(`Cannot compare type: ${t.type}`)}})));default:throw new Error(`Unknown ArrayValue filter: ${r.value}`)}else if(n instanceof Nt)switch(r.value){case"length":return new At(n.value.length);case"upper":return new Nt(n.value.toUpperCase());case"lower":return new Nt(n.value.toLowerCase());case"title":return new Nt(Ot(n.value));case"capitalize":return new Nt(n.value.charAt(0).toUpperCase()+n.value.slice(1));case"trim":return new Nt(n.value.trim());case"trimStart":return new Nt(n.value.trimStart());case"trimEnd":return new Nt(n.value.trimEnd());case"indent":return new Nt(n.value.split("\n").map(((t,e)=>0===e||0===t.length?t:" "+t)).join("\n"));case"string":return n;default:throw new Error(`Unknown StringValue filter: ${r.value}`)}else{if(n instanceof At){if("abs"===r.value)return new At(Math.abs(n.value));throw new Error(`Unknown NumericValue filter: ${r.value}`)}if(n instanceof Tt)switch(r.value){case"items":return new It(Array.from(n.value.entries()).map((([t,e])=>new It([new Nt(t),e]))));case"length":return new At(n.value.size);case"string":return new Nt(n.toString());default:throw new Error(`Unknown ObjectValue filter: ${r.value}`)}}throw new Error(`Cannot apply filter "${r.value}" to type: ${n.type}`)}if("CallExpression"===t.filter.type){const r=t.filter;if("Identifier"!==r.callee.type)throw new Error(`Unknown filter: ${r.callee.type}`);const s=r.callee.value,i=e.lookupVariable(s);if(i instanceof Pt){const[t,s]=this.evaluateArguments(r.args,e);return s.size>0&&t.push(new Mt(s)),i.value([n,...t],e)}if(n instanceof It){switch(s){case"selectattr":{if(n.value.some((t=>!(t instanceof Tt))))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 It(a)}case"map":{const[,t]=this.evaluateArguments(r.args,e);if(t.has("attribute")){const e=t.get("attribute");if(!(e instanceof Nt))throw new Error("attribute must be a string");const r=t.get("default"),s=n.value.map((t=>{if(!(t instanceof Tt))throw new Error("items in map must be an object");return t.value.get(e.value)??r??new Vt}));return new It(s)}throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${s}`)}if(n instanceof Nt){if("indent"===s){const[t,s]=this.evaluateArguments(r.args,e),i=t.at(0)??s.get("width")??new At(4);if(!(i instanceof At))throw new Error("width must be a number");const o=t.at(1)??s.get("first")??new Ct(!1),a=t.at(2)??s.get("blank")??new Ct(!1),c=n.value.split("\n"),u=" ".repeat(i.value),f=c.map(((t,e)=>!o.value&&0===e||!a.value&&0===t.length?t:u+t));return new Nt(f.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 Ct(t.negate?!s:s)}evaluateUnaryExpression(t,e){const n=this.evaluate(t.argument,e);if("not"===t.operator.value)return new Ct(!n.value);throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let n="";for(const r of t){const t=this.evaluate(r,e);"NullValue"!==t.type&&"UndefinedValue"!==t.type&&(n+=t)}return new Nt(n)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){const[n,r]=this.evaluateArguments(t.args,e);r.size>0&&n.push(new Mt(r));const s=this.evaluate(t.callee,e);if("FunctionValue"!==s.type)throw new Error(`Cannot call something that is not a function: got ${s.type}`);return s.value(n,e)}evaluateSliceExpression(t,e,n){if(!(t instanceof It||t instanceof Nt))throw new Error("Slice object must be an array or string");const r=this.evaluate(e.start,n),s=this.evaluate(e.stop,n),i=this.evaluate(e.step,n);if(!(r instanceof At||r instanceof Vt))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof At||s instanceof Vt))throw new Error("Slice stop must be numeric or undefined");if(!(i instanceof At||i instanceof Vt))throw new Error("Slice step must be numeric or undefined");return t instanceof It?new It(St(t.value,r.value,s.value,i.value)):new Nt(St(Array.from(t.value),r.value,s.value,i.value).join(""))}evaluateMemberExpression(t,e){const n=this.evaluate(t.object,e);let r,s;if(t.computed){if("SliceExpression"===t.property.type)return this.evaluateSliceExpression(n,t.property,e);r=this.evaluate(t.property,e)}else r=new Nt(t.property.value);if(n instanceof Tt){if(!(r instanceof Nt))throw new Error(`Cannot access property with non-string: got ${r.type}`);s=n.value.get(r.value)??n.builtins.get(r.value)}else if(n instanceof It||n instanceof Nt)if(r instanceof At)s=n.value.at(r.value),n instanceof Nt&&(s=new Nt(n.value.at(r.value)));else{if(!(r instanceof Nt))throw new Error(`Cannot access property with non-string/non-number: got ${r.type}`);s=n.builtins.get(r.value)}else{if(!(r instanceof Nt))throw new Error(`Cannot access property with non-string: got ${r.type}`);s=n.builtins.get(r.value)}return s instanceof jt?s:new Vt}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 Tt))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 Ut}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 Bt(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 It))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 Bt(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 At(e+1)],["index0",new At(e)],["revindex",new At(i.length-e)],["revindex0",new At(i.length-e-1)],["first",new Ct(0===e)],["last",new Ct(e===i.length-1)],["length",new At(i.length)],["previtem",e>0?i[e-1]:new Vt],["nextitem",e<i.length-1?i[e+1]:new Vt]]);n.setVariable("loop",new Tt(r)),o[e](n);a+=this.evaluateBlock(t.body,n).value,c=!1}if(c){a+=this.evaluateBlock(t.defaultBlock,n).value}return new Nt(a)}evaluateMacro(t,e){return e.setVariable(t.name.value,new Pt(((e,n)=>{const r=new Bt(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 Ut}evaluate(t,e){if(void 0===t)return new Vt;switch(t.type){case"Program":return this.evalProgram(t,e);case"Set":return this.evaluateSet(t,e);case"If":return this.evaluateIf(t,e);case"For":return this.evaluateFor(t,e);case"Macro":return this.evaluateMacro(t,e);case"NumericLiteral":return new At(Number(t.value));case"StringLiteral":return new Nt(t.value);case"BooleanLiteral":return new Ct(t.value);case"ArrayLiteral":return new It(t.value.map((t=>this.evaluate(t,e))));case"TupleLiteral":return new Ft(t.value.map((t=>this.evaluate(t,e))));case"ObjectLiteral":{const n=new Map;for(const[r,s]of t.value){const t=this.evaluate(r,e);if(!(t instanceof Nt))throw new Error(`Object keys must be strings: got ${t.type}`);n.set(t.value,this.evaluate(s,e))}return new Tt(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 _t(t){switch(typeof t){case"number":return new At(t);case"string":return new Nt(t);case"boolean":return new Ct(t);case"undefined":return new Vt;case"object":return null===t?new Ut:Array.isArray(t)?new It(t.map(_t)):new Tt(new Map(Object.entries(t).map((([t,e])=>[t,_t(e)]))),t);case"function":return new Pt(((e,n)=>{const r=e.map((t=>Lt(t)));return _t(t(...r)??null)}));default:throw new Error(`Cannot convert to runtime value: ${t}`)}}function Lt(t){let e=t;if(Array.isArray(t))e=t.map((t=>Lt(t)));else if(t instanceof Map)e={},t.forEach(((t,n)=>{e[n]=Lt(t)}));else switch(t.type){case"NullValue":e=null;break;case"UndefinedValue":e=void 0;break;case"ArrayValue":e=t.value.map((t=>Lt(t)));break;case"KeywordArgumentsValue":case"ObjectValue":e=t.orgValue?t.orgValue:Lt(t.value),"KeywordArgumentsValue"===t.type&&Object.setPrototypeOf(e,{jinja_kargs:!0});break;default:t.type&&(e=t.value)}return e}function zt(t,e=0){return Math.floor(Math.random()*(t-e+1))+e}var qt={randomInt:zt,select:function(t,e){if(Array.isArray(t)||"string"==typeof t)return void 0===e?e=zt(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[zt(n.length-1)]}return t[e]}},tojson:function(t,e,n){return e&&"object"==typeof e&&(e.depth&&(n=e.depth),e=e.indent),Jt(t,e,n)}};function Jt(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=>Jt(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}": ${Jt(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 Dt=class extends Bt{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()}},Wt=class t{static{this.global=new Dt}constructor(t,e={}){const n=Q(t,e={lstrip_blocks:!0,trim_blocks:!0,...e});this.parsed=$t(n)}render(e){const n=new Bt(t.global);n.set("false",!1),n.set("true",!0),n.set("raise_exception",(t=>{throw new Error(t)})),n.set("range",kt);for(const[t,r]of Object.entries(e))n.set(t,r);return new Rt(n).run(this.parsed).toString()}};function Kt(t,e){let n;switch(t.type){case"Identifier":n=t.value;break;case"MemberExpression":n=Kt(t.object,e);break;case"FilterExpression":n=Kt(t.operand,e);break;case"Set":{e||(e=[]);const r=Kt(t.assignee);r&&e.push(r),n=Kt(t.value,e);break}}return n&&e?.includes(n)&&(n=void 0),n}function Zt(t){let e;if("Program"===t.type)e=t.body.some((t=>Zt(t)));else e=t.isStatement;return e}function Gt(t,e){let n=[];if(Array.isArray(t))n=t.map((t=>Gt(t,e))).filter(Boolean).flat();else switch(t.type){case"Program":n=t.body.map((t=>Gt(t,e))).filter(Boolean).flat();break;case"If":n=[Kt(t.test,e),...Gt(t.body,e),...Gt(t.alternate,e)].filter(Boolean);break;case"BinaryExpression":n=[Kt(t.left,e),Kt(t.right,e)].filter(Boolean);break;case"For":{const r=Kt(t.loopvar);r&&(e||(e=[]),e.push(r)),n=[Kt(t.iterable,e),...Gt(t.body,e)].filter(Boolean);break}case"CallExpression":n=[Kt(t.callee,e),...Gt(t.args,e)].filter(Boolean);break;default:n=[Kt(t,e)].filter(Boolean)}return n}Wt.global.assign(qt);var Ht=class extends L{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 Wt(n)}catch(t){}return e&&(r=Zt(e.parsed)),r}getVariables(t=this.compiledTemplate){return Gt(t.parsed,[]).filter(((t,e,n)=>n.indexOf(t)===e))}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new l("Prompt template must be a string","PromptTemplate",400);this.compiledTemplate=new Wt(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return this.compiledTemplate.render(t)}};function Xt(t){return function(e){return t}}function Qt(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 Yt(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 te(t){const e=new Set;return t.forEach((t=>{"variable"===t.type&&e.add(t.name)})),[...e]}L.register(Ht,{name:"hf",aliases:["huggingface","internal","default"]});var ee=class extends L{static isTemplate(t){let e,n,r=!1;if("object"==typeof t?(n=t.template,e=t.compiledTemplate):n=t,!e&&n)try{e=Qt(n)}catch(t){}if(e){r=te(e).length>0}return r}getVariables(t=this.compiledTemplate){return te(t)}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new l("Prompt template must be a string","PromptTemplate",400);this.compiledTemplate=Qt(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return Yt(this.compiledTemplate,t)}};function ne(t,e){return"string"==typeof e&&(e=e.split(".").filter((t=>t.length))),e.reduce(((t,e)=>t?.[e]),t)}function re(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 ne(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):ne(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=ne(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=ne(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):ne(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=ne(e,r);let o;return o=isNaN(s)?i[s.substring(1,s.length-1)]:i[parseInt(s,10)],o||""}))}(r,e,n),r}L.register(ee,{name:"fstring",aliases:["python","f-string","langchain"]});var se=class extends L{static isTemplate(t){const e="string"==typeof t?t:t.template;return e?.includes("{{")&&e.includes("}}")}getVariables(t){const e={};return re(t,e,!0),[...Object.keys(e)]}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new l("Prompt template must be a string","PromptTemplate",400);this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables(e)}_format(t){return re(this.template,t)}};function ie(t){return Object.keys(t).sort().map((e=>t[e]))}L.register(se,{name:"golang",aliases:["localai","ollama"]});var oe=class extends L{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 L?t.examplePrompt:L.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=ie(t);n.length>0&&e.push(...n)}const n=[this.prefix,...e,this.suffix].join(this.exampleSeparator),r=this.templateFormat;return await L.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}};L.register(oe,{name:"fewshot",aliases:["few_shot"]});var ae=/(\\)?(\$)(?!\()(\{?)([\w.]+)(?::?-((?:\$\{(?:\$\{(?:\$\{[^}]*\}|[^}])*}|[^}])*}|[^}])+))?(\}?)/gi;function ce(t){return t.replace(/\\\$/g,"$")}function ue(t,e,n){return t.replace(ae,((r,s,i,o,a,c,u)=>"\\"===s?r.slice(1):e[a]?e[a]===n[a]?e[a]:ue(e[a],e,n):n[a]?n[a]===t?n[a]:ue(n[a],e,n):c?c.startsWith("$")?ue(c,e,n):c:""))}function fe(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]?ue(r,e,t.parsed):e[n]:ue(r,e,t.parsed),t.parsed[n]=r?ce(r):r}for(const n in t.parsed)e[n]=t.parsed[n];return t}function he(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=ue(t,e.processEnv,e.parsed);break;case"object":if(n.has(t))return t;if(n.add(t),Array.isArray(t))for(let r=0;r<t.length;r++){const s=t[r];"string"!=typeof s&&"object"!=typeof s||(t[r]=he(t[r],e,n))}else for(const[r,s]of Object.entries(t))"string"!=typeof s&&"object"!=typeof s||(t[r]=he(s,e,n))}return t}var le=/(\S.+?[.!?])(?=\s+|$)|(\S.+?)(?=[\n]|$)/g,pe=/([A-Z][a-z]{1,2}\.)\s(\w)/g,we=/(\.[a-zA-Z]\.)\s(\w)/g,de=new RegExp("([A-Z][a-z]{1,2}\\.)@(\\w)","g"),me=new RegExp("(\\.[a-zA-Z]\\.)@(\\w)","g");function ye(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 be(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=ye(s,"@",[pe,we]),o=Array.from(i.matchAll(le));if(o.length)for(let t=0;t<o.length;t++){let e=ye(o[t][0]," ",[de,me]);r.push(e)}else r.push(s)}return r}function ge(t,e=2,n=.5){const r=10**e;return Math.trunc((t+Number.EPSILON+n/r)*r)/r}async function ve(t){return new Promise((e=>setTimeout(e,t)))}import{createAbilityInjector as xe}from"custom-ability";var Ee="event",$e="event-bus";var ke=xe((function(t){return class{static get emitter(){if(!this._emitter){const t=this.get($e)?.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 Se(t,e){return!t||t.some((t=>t instanceof RegExp?t.test(e):t===e))}var Oe=498,je=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||b("Channel closed","SSEChannel",498);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||Se(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||b("Channel closed","SSEChannel",498);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=>Se(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 Ae(t){return t instanceof ReadableStream||t instanceof WritableStream}var Ne=600,Ce=601,Te=class extends h{constructor(t,e=600){super(t,500)}};function Me(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 Te(`Response error: ${e}`,Ce))}}})}return new ReadableStream({start(t){t.error(new Te("Response error: No response body",Ce))}})}function Ie(){return new ReadableStream({start(t){t.close()}})}import{createParser as Fe}from"eventsource-parser";function Pe(t){const e=new TextDecoder;let n;return new TransformStream({async start(e){n=Fe((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 Ue(){let t=!0;return e=>(t&&(e=e.trimStart())&&(t=!1),e)}function Ve(t,e){if(!t.ok)return Me(t.body);let n=t.body||new ReadableStream({start(t){t.close()}});return n instanceof ReadableStream||(n=ReadableStream.from(n)),n.pipeThrough(Pe(e))}function Be(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 Re(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()}})}import{v1 as _e,v5 as Le,v4 as ze}from"uuid";import*as qe from"base32768";import{v1 as Je,v4 as De,v5 as We,stringify as Ke,parse as Ze,validate as Ge,version as He,NIL as Xe}from"uuid";var Qe={1:_e,4:ze,5:Le};function Ye(t=1,e){const n=Qe[t];return e?qe.encode(n(null,[])):n()}import tn from"xxhashjs";import*as en from"base32768";import{canonicalize as nn}from"json-canonicalize";var rn=en,{h32:sn,h64:on}=tn,an=588213;function cn(t,e=16){return"object"==typeof t&&(t=nn(t)),sn(t,an).toString(e)}function un(t,e=16){return"object"==typeof t&&(t=nn(t)),on(t,an).toString(e)}var fn=(t=>(t[t.xxhash64=111]="xxhash64",t[t.xxhash32=112]="xxhash32",t))(fn||{});function hn(t,e=111,n=an){let r;return t.buffer&&(t=t.buffer),112!==e?(r=on(t,n),r=new Uint16Array([r._a00,r._a16,r._a32,r._a48]),r=new Uint8Array(r.buffer)):(r=sn(t,n),r=new Uint16Array([r._low,r._high]),r=new Uint8Array(r.buffer)),r}function ln(t,e=111,n=an){return en.encode(hn(t,e,n))}import pn from"path";var wn=/[<>:"/\\|?*\u0000-\u001F]/,dn=/^(con|prn|aux|nul|com\d|lpt\d)$/i,mn=100,yn=/^\.+(\\|\/)|^\.+$/,bn=/\.+$/,gn=/[\u0000-\u001F\u0080-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069]/;function vn(){return new RegExp(wn.source,"g")}function xn(){return new RegExp(gn.source,"g")}function En(t){return t&&!(wn.test(t)||xn().test(t)||yn.test(t)||bn.test(t))}function $n(t){const e=t.split(pn.sep);return("/"===t[0]||e[0]&&pn.dirname(e[0])===e[0])&&e.shift(),e.every(En)}function kn(t,e={}){const n=e.replacement||"!";if((wn.test(n)||gn.test(n))&&b("Replacement string cannot contain reserved filename characters","sanitizeFilename",400),n.length>0){const e=/([<>:"/\\|?*\u0000-\u001F]){2,}/;t=t.replace(e,"$1")}if(t=(t=(t=(t=(t=t.normalize("NFD")).replace(yn,n)).replace(vn(),n)).replace(xn(),n)).replace(bn,""),n.length>0){"."===t[0]||"."!==t[0]||(t=n+t),"."===t[t.length-1]&&(t+=n)}t=dn.test(t)?t+n:t;const r="number"==typeof e.maxLength?e.maxLength:mn;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(pn.sep);let r;("/"===t[0]||n[0]&&pn.dirname(n[0])===n[0])&&(r=n.shift());const s=n.map((t=>kn(t,e)));return void 0!==r&&s.unshift(r),s.join(pn.sep)}function On(t,e=1){let n="";for(;e--;){const e=pn.extname(t);if(!e)break;n=e+n,t=pn.basename(t,e)}return n}function jn(t){return t.split(".").length-1}import{isRegExpStr as An,toRegExp as Nn}from"util-ex";function Cn(t,e){if("string"!=typeof t)throw new l("modelName must be a string","isModelNameMatched",400);switch(typeof e){case"string":if(An(e)){const n=(e=Nn(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(An(n)){const r=(e=Nn(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 Tn(t){return Object.keys(t).filter((t=>Number.isNaN(Number(t))))}import{pick as Mn}from"lodash-es";import{newFunction as In}from"util-ex";function Fn(t,e){if(e&&(e=Vn(e)),e){const n=Object.keys(e);if(n.length){const r=Object.values(e);return In("expression",n,`return ${t}`)(...r)}}return In("expression",[],`return ${t}`)()}var Pn=/^[a-zA-Z_$][0-9a-zA-Z_$]*$/,Un=t=>Pn.test(t);function Vn(t){if(t){const e=Object.keys(t),n=e.length,r=e.filter((e=>Un(e)&&null!==t[e]));if(n===r.length)return t;if(r.length)return t=Mn(t,r)}}function Bn(t){return t?Rn(t,[],""):[]}function Rn(t,e,n="."){return Array.isArray(t)?t.flatMap(((t,n)=>Rn(t,[...e,`[${n}]`]))):(r=t)&&r.constructor===Object?Object.entries(t).flatMap((([t,r])=>Rn(r,[...e,n+t]))):[e.join("")];var r}function _n(t){if(t<2)throw new l("repetitionThreshold must be greater than 1","createEndWithRepetitionDetector",400);const e=new RegExp(`([\\S\\s]+)(\\1{${t-1},})$`);return function(t){return e.exec(t)}}import Ln from"path";import*as zn from"fs";function qn(t){const e=zn.statSync(t,{throwIfNoEntry:!1});return e?.isFile()}function Jn(t,e,n,r){const s=r?.signal,i=r?.exclude;let o;if(Ln.isAbsolute(t)?o=qn(t)?t:Dn(Ln.basename(t),[Ln.dirname(t)],{extNames:n,exclude:i,signal:s}):(e||(e=["."]),o=Dn(t,e,{extNames:n,exclude:i,signal:s})),!o)throw new w(t,"loadFileFromPaths");{const t=o;o=zn.readFileSync(o),r&&(r.filepath=t)}return o}function Dn(t,e,{extNames:n,signal:r,exclude:s=[]}){let i;const o=n?n.map((e=>On(t,jn(e)))):void 0;"string"==typeof s&&(s=[s]);for(const a of e){if(r?.aborted)throw r.reason;const e=Ln.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)&&qn(r)){i=r;break}}else if(!s.includes(e)&&qn(e)){i=e;break}}return i}function Wn(t,e,n,r,s){let i;"string"==typeof r?(i=r,r=void 0):i=r?.encoding??"utf8";return Jn(t,e,n,r).toString(i)}function Kn(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=Zn(r.pop()),e=Ln.resolve(t);if(s.has(e))continue;s.add(e);const u=zn.statSync(t,{throwIfNoEntry:!1});if(u?.isDirectory()){const e=zn.readdirSync(t,{withFileTypes:!0});for(let s=0;s<e.length;s++){const i=e[s],a=Ln.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 Zn(t){const e=zn.lstatSync(t,{throwIfNoEntry:!1});return e?.isSymbolicLink()&&(t=zn.readlinkSync(t)),t}import{existsSync as Gn,mkdirSync as Hn,readdirSync as Xn,statSync as Qn,writeFileSync as Yn}from"fs";import tr from"path";import{Config as er}from"load-config-file";import{parse as nr,stringify as rr}from"yaml";import{regexp as sr}from"yaml-types";import{mimeType as ir}from"mime-type/with-db";import{stringify as or}from"yaml";var ar=[sr];function cr(t){Array.isArray(t)||(t=[t]);for(const e of t){-1===ar.indexOf(e)&&ar.push(e)}}function ur(t){return nr(t,{customTags:ar})}function fr(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=Xn(t,{withFileTypes:!0,recursive:!0});for(const r of n){const n=tr.join(t,r.name);r.isFile()&&e(n,r)}}(t,((t,e)=>{if(s?.includes(t))return;const o=tr.extname(t),a=Qn(t);if(i.includes(o)){if(r?.hasOwnProperty(t)&&a.mtimeMs<=r[t])return;n.push(t)}})),n}function hr(t,e){return fr(t,e).map((t=>er.loadSync(t))).filter((t=>void 0!==t))}function lr(t,e,n=1){"."===t[0]&&n++;const r=On(t,n);(!r||r.split(".").length<=1)&&(t+=".yaml");const s=ir.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=rr(e)}const i=tr.dirname(t);return Gn(i)||Hn(i,{recursive:!0}),Yn(t,e,{encoding:"utf8"}),t}function pr(t){t instanceof Date&&(t=t.toISOString());return function(t,e){return t?`'${e}'`:String(e)}("string"==typeof t,t)}function wr(t,e){return t.map((t=>yr(t,e))).join(" AND ")}function dr(t,e){return t.map((t=>yr(t,e))).join(" OR ")}function mr(t,e){const n=[];return Object.keys(e).forEach((r=>{const s=e[r];switch(r){case"$lt":case"<":n.push(`${t} < ${pr(s)}`);break;case"<=":case"$lte":n.push(`${t} <= ${pr(s)}`);break;case"$gt":case">":n.push(`${t} > ${pr(s)}`);break;case"$gte":case">=":n.push(`${t} >= ${pr(s)}`);break;case"$ne":case"!=":n.push(`${t} != ${pr(s)}`);break;case"=":case"$eq":n.push(`${t} = ${pr(s)}`);break;case"$in":n.push(`${t} IN (${s.map((t=>pr(t))).join(", ")})`);break;case"$nin":n.push(`${t} NOT IN (${s.map((t=>pr(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 yr(t,e){const n=[];if("function"!=typeof e&&(e=t=>t),Array.isArray(t))n.push(wr(t,e));else for(const[r,s]of Object.entries(t))if("$and"===r)n.push(`(${wr(t[r],e)})`);else if("$or"===r)n.push(`(${dr(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(mr(e(r),s))}return n.length>1?n.join(" AND "):n[0]}function br(t){const e=t.indexOf("://");if(e>0)return t.substring(0,e)}function gr(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 vr(t){const e=t.match(/^\s*[+]?(\d+(?:[.]\d+)?)\s*([TBMK])?\s*$/i);if(!e)throw new l("Invalid formatted parameter size string.","scaleToSize",400);const n=parseFloat(e[1]),r=e[2]?.toLowerCase();switch(r){case"t":return 1e12*n;case"b":return 1e9*n;case"m":return 1e6*n;case"k":return 1e3*n;default:return n}}function xr(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":" ")+xr(t,{level:n+1,visiting:r})}}er.register([".yml",".yaml"],ur),er.register([".json"],(function(t){return JSON.parse(t)}));var Er=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}};import{EventEmitter as $r}from"events-ex";var kr=32;function Sr(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 Or=class{constructor(t){this._capacity=Sr(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(Sr(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)}}},jr=class extends $r{};function Ar(t){return"function"==typeof t}function Nr(){return"1"}var Cr=class{constructor(t,{initFn:e=Nr,pauseFn:n,resumeFn:r,capacity:s=32}={}){if(Ar(n)!==Ar(r))throw new Error("pauseFn and resumeFn must be both set for pausing");this.maxConcurrency=t,this.free=new Or(t),this.waiting=new Or(s),this.releaseEmitter=new jr,this.useDefaultTokens=e===Nr,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 Tr(t,{timeUnit:e=1e3,uniformDistribution:n=!1}={}){const r=new Cr(n?1:t),s=n?e/t:e;return async function(){await r.acquire(),setTimeout((()=>r.release()),s)}}import{createAbilityInjector as Mr}from"custom-ability";import{defineProperty as Ir}from"util-ex";var Fr=class extends AbortController{constructor(t){super(),Ir(this,"parent",t)}abort(t,e){this.signal.aborted||("string"==typeof t&&(t=new m(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 m(e.reason||"aborted")}}},Pr=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 Cr(t-1)),e}isAborted(t){const e=this.hasAsyncFeature(is);let n=this.__task_aborter;if(n&&e){if(null==t)throw new l("Missing taskId",this.name+".isAborted",400);n=n[t]}return!n||n.signal.aborted}getRunningTask(t){const e=this.hasAsyncFeature(is);let n=this.__task_aborter;if(n&&e){if(null==t)throw new l("Missing taskId",this.name+".getRunningTask",400);n=n[t]}return n?.signal.aborted&&(e?this.__task_aborter[t]=void 0:this.__task_aborter=void 0,n=void 0),n}getRunningTaskCount(){let t;if(this.hasAsyncFeature(is)){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(is);if(!r&&n&&this.getRunningTask())throw new l("The task is running",this.name,429);const s=t?.aborter||new Fr(this);if(!(s instanceof Fr)){if(!(s instanceof AbortController))throw new l("aborter should be an AbortController",this.name,400);Object.setPrototypeOf(s,new Fr(this))}if(r){null==this.__task_aborter&&(this.__task_aborter={});const t=this.__task_aborter;null==e&&(e=this.generateAsyncTaskId(e,t)),s.id=e,t[e]=s}else this.__task_aborter=s;const i=t?.timeout;return i>0&&(s.timeoutId=setTimeout((()=>{s.timeoutId=void 0,this.abort("timeout",{timeout:i})}),i)),s.signal.addEventListener("abort",(()=>{const t=s.timeoutId;t&&(s.timeoutId=void 0,clearTimeout(t));const e=s.signal;try{this.emit&&this.emit("aborting",e.reason,e.reason?.data)}finally{s.streamController?.error(e.reason)}})),s}$cleanMultiTaskAborter(t,e){const n=this.super,r=this.self||this;n?n.call(r,t,e):r._cleanMultiTaskAborter(t,e)}cleanTaskAborter(t){if(this.hasAsyncFeature(is)){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=Re({onStart:t=>{Ir(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(is)){const t=e?.taskId;if(null==t)throw new l("Missing data.taskId",this.name+".abort",400);n=n[t],this.cleanMultiTaskAborter(t,r)}else this.__task_aborter=void 0;n&&!n.signal.aborted&&n.abort(t,e)}}};Pr.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},Pr.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};var Ur=Mr(Pr,"abort",{afterInjection:function(t,e){let n=t.prototype._asyncFeatures||0;n|=us.Cancelable,e&&(e.asyncFeatures&&(n|=e.asyncFeatures),e.maxTaskConcurrency>0&&(t.prototype._maxTaskConcurrency=e.maxTaskConcurrency)),t.prototype._asyncFeatures=n}});function Vr(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}import{get as Br}from"lodash-es";import{newFunction as Rr}from"util-ex";async function _r(t,e,n){return Lr(Xr(t,e,n),e,n)}async function Lr(t,e,n){if(t.length){const r=await Promise.all(t.map(((t,r)=>Hr(t,r,e,n)))),s=n?.returnArrayOnly;let i;if(r?.length){const t=`{${r.map((t=>function(t){const e={"\n":"\\n","\r":"\\r","\t":"\\t","\b":"\\b","\f":"\\f","\\":"\\\\"};return t.replace(/\\?[\n\r\t\b\f\\]/g,(t=>t.startsWith("\\")?t:e[t]))}(t))).join(",")}}`;i=Fn(t,e)}if(i&&!s){const t=Object.entries(i),e=Object.keys(i);1===t.length&&void 0!==i[0]?i=i[0]:e.every((t=>!isNaN(parseInt(t))))?i=e.sort(((t,e)=>parseInt(t)-parseInt(e))).map((t=>i[t])):2===t.length&&"0"===t[0][0]&&t[0][1]===t[1][1]&&(i=i[0])}return i}}function zr(t,e,n,r){const[s,i]=t;if(!s&&"|"===i[0])return"choice: {"+function(t,e,n){const r=Xr(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=>Dr(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(Dr(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 qr([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 L.formatIf(a);return c?(o=c,i+":"+Wr(o)):void 0}async function Jr(t,e,n,r){let s=zr(t,0,n,r);return s||(s=await qr(t,e,n,r)),s}function Dr(t){const e=t[0];return('"'===e||"'"===e)&&t[t.length-1]===e}function Wr(t){return'"'+t.replace(/(?<!\\)"(?!\\)/g,'\\"')+'"'}var Kr=["true","false","null","undefined","NaN","Infinity"];function Zr(t){return function(t,e=['""',"''","{}"]){return e.some((e=>t[0]===e[0]&&t[t.length-1]===e[1]))}(t)||!Number.isNaN(parseFloat(t))||Kr.includes(t)||ts(t)}async function Gr(t,e){const n=Rr("async expression",[],`return ${t};`,Vn(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 Hr(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(!(Zr(r)||n&&void 0!==Br(n,r)))return e+":"+Wr(r);if(!ts(i))try{return e+":"+await Gr.call(this,r,n)}catch(t){}return i}{const t=i.trim();if(n&&void 0!==Br(n,t))return e+":"+t+', "'+t+'":'+t;if(Zr(t))return e+":"+t;if(!ts(i))try{return e+":"+await Gr.call(this,t,n)}catch(t){}return e+":"+Wr(t)}}function Xr(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 _r(i,e,n)),{command:s.trim(),args:o}}var Yr=/^\s*\(\)|[a-zA-Z_$][\w\d$]*|\(([a-zA-Z_$][\w\d$]*)(\s*,\s*([a-zA-Z_$][\w\d$]*))*\)\s*=>/;function ts(t){return Yr.test(t)}import es from"memoizee";import{canonicalize as ns}from"json-canonicalize";function rs(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 es(t,{...e,normalizer:t=>{if(r){const e=r(t);if("string"===e)return e;e&&(t=e)}return ln(ns(t))}})}var ss,is=0,os=1,as=2,cs=(t=>(t[t.MultiTask=is]="MultiTask",t[t.Cancelable=1]="Cancelable",t[t.Priority=2]="Priority",t))(cs||{}),us=((ss=us||{})[ss.MultiTask=1<<is]="MultiTask",ss[ss.Cancelable=2]="Cancelable",ss[ss.Priority=4]="Priority",ss),fs=class t extends e{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),Er.has(n,t)}static run(t,e){const n=this.get(t);if(n)return n.run(e);throw new w(`${t} to run`,this.name)}static runSync(t,e){const n=this.get(t);if(n)return n.runSync(e);throw new w(`${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(`${t} to run`,this.name)}static runWithPosSync(t,...e){const n=this.get(t);if(n)return n.runWithPosSync(...e);throw new w(`${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);b("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),Er.has(e,t)}isStream(t){return this.stream}},hs={name:{type:"string"},description:{type:"string"},func:{type:"function",assign(t,e,r,s,i){let o=t;const a=typeof t;return i.isExported?o="function"===a?t.toString():t:t&&("string"!==a&&(t=t.toString()),o=n(t,e.scope)),o}},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"}};fs.defineProperties(fs,hs);var ls=class extends fs{constructor(){super(...arguments),this._emitter=new t,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},ps=new ls($e);import{Cache as ws}from"secondary-cache";function ds({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 ms(t,e){let n=fs.get(t);return n||(n=new fs(t,{func:ds,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 ws(e)),n}var ys=ms("lrucache"),bs=class t extends fs{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 b("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):b(`${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 y(r,s,n)}async func(t){const e=await this.fetch(t);if(t?.stream)return e;return await e.json()}},gs={...E};bs.defineProperties(bs,gs);var vs=class extends bs{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))}}},xs={methods:{type:"array",assign(t,e,n,r,s){s?.isExported||e.assignMethods(t)}}};vs.defineProperties(vs,xs);var Es=class extends vs{async fetch(t,e){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let n=t.id;return n||b("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)}},$s=class extends Es{constructor(){super(...arguments),this._sseEvents={},this._forwardEvents=new Set,this.name=Ee,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)}},ks=new $s(Ee);import{getAllNames as Ss}from"util-ex";var Os=class t extends fs{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({}){}},js={...E};Os.defineProperties(Os,js);var As=class extends Os{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);Ss(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(e,this.name)}};As.defineProperties(As,{methods:{type:"array"}});var Ns=class extends As{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}}}static{this.SpecialRpcMethodNames=x}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}},Cs=ps.runSync(),Ts=class t extends Ns{constructor(){super(...arguments),this.name=Ee,this.description="subscribe server sent event",this.result="event",this.depends={[$e]:ps}}static get sse(){return this._sse||(this._sse=new je),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=Cs.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)||Cs.on(n,t.ebListener)}unforward(e){"string"==typeof e&&(e=[e]);for(const n of e)Cs.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};b("event is required","sub",400)}$unsub({event:t}){if(t)return this.unforward(t),{event:t};b("event is required","unsub",400)}$publish({event:t,data:e}){if(t&&e){"string"==typeof t&&(t=[t]);for(const n of t)this.publishSSE(e,n);return{event:t}}b("event or data is required","pub",400)}isStream(t){return"list"===this.getMethodFromParams(t)}},Ms=new Ts(Ee);function Is(){ps.register(),ys.register()}export{v as PASSING_SCORE,x as ActionNames,E as RemoteToolFuncSchema,i as ErrorCode,o as InternalErrorCode,a as NotImplementedErrorCode,c as NotFoundErrorCode,u as AlreadyExistsErrorCode,f as AbortErrorCode,h as BaseError,l as CommonError,p as NotImplementationError,w as NotFoundError,d as AlreadyExistsError,m as AbortError,y as createError,b as throwError,k as parseDateFormat,C as toDateTime,T as textToDate,M as dateToText,O as formatISO,j as parseISO,A as toDate,I as AITextGenerationFinishReasons,F as AIMessageTypes,P as AIChatRoles,U as messagesToText,V as PromptTypes,B as PromptTemplateTypes,_ as defaultTemplateFormat,L as PromptTemplate,J as PromptExampleSelector,Q as tokenize,$t as parse,Rt as Interpreter,qt as builtins,Dt as EnvironmentEx,Wt as Template,Ht as HfPromptTemplate,Xt as createHfValueFunc,Qt as parseFString,Yt as interpolateFString,ee as FStringPromptTemplate,re as interpolateGolangTemplate,se as GolangPromptTemplate,ie as sortedValues,oe as FewShotPromptTemplate,ue as interpolateEnv,fe as expandEnv,he as expandObjEnv,be as splitSentence,ge as truncTo,ve as wait,Ee as EventName,$e as EventBusName,ke as backendEventable,Oe as SSEChannelAlreadyClosedErrCode,je as SSEChannel,Ae as isWebStream,Ne as RStreamErrCode,Ce as ResponseRStreamErrCode,Te as ReadableStreamError,Me as getResponseErrorReadableStream,Ie as createEmptyReadableStream,Pe as createEventStreamTransformer,Ue as trimStartOfStreamHelper,Ve as AIStream,Be as readableFromAsyncIterable,Re as createCallbacksTransformer,Ye as uuid,Je as v1,De as v4,We as v5,Ke as stringify,Ze as parse2,Ge as validate,He as version,Xe as NIL,nn as canonicalize,rn as base32768,cn as xxhash32,un as xxhash64,fn as XXHashAlgorithm,hn as xxhash,ln as xxhashAsStr,wn as FilenameReservedRegex,dn as WindowsReservedNameRegex,vn as filenameReservedRegex,xn as reControlCharsRegex,En as isValidFilename,$n as isValidFilepath,kn as sanitizeFilename,Sn as sanitizeFilepath,On as getMultiLevelExtname,jn as extNameLevel,Cn as isModelNameMatched,Tn as getAllEnumKeys,Fn as parseJsJson,Vn as filterValidFnScope,Bn as getKeysPath,_n as createEndWithRepetitionDetector,qn as fileIsExists,Jn as loadFileFromPaths,Wn as loadTextFromPaths,Kn as readFilenamesRecursiveSync,Zn as getRealFilepath,er as ConfigFile,ir as mimeType,cr as registerYamlTag,ur as parseYaml,fr as getConfigFileNames,hr as getConfigs,lr as saveConfigFile,or as stringify2,yr as jsonFilterToWhere,br as matchUrlProtocol,gr as paramsSizeToScaleStr,vr as scaleStrToParamsSize,xr as jsonToMarkdownStr,Er as IntSet,kr as DefaultAsyncSemaphoreCapacity,Cr as Semaphore,Tr as RateLimit,is as ToolAsyncMultiTaskBit,os as ToolAsyncCancelableBit,as as ToolAsyncPriorityBit,cs as AsyncFeatureBits,us as AsyncFeatures,fs as ToolFunc,hs as ToolFuncSchema,Fr as TaskAbortController,Pr as CancelableAbility,Ur as makeToolFuncCancelable,Vr as countRegexMatches,_r as parseObjectArguments,Lr as parseObjectArgumentInfos,zr as ChoiceArgProcessor,qr as TemplateArgProcessor,Jr as AIArgProcessor,Wr as quoteStr,Hr as parseObjectArgInfo,Xr as parseObjectArgumentsAsArgInfos,Qr as parseCommand,rs as memoize,g as createAbilityInjector,bs as ClientTools,gs as ClientToolFuncSchema,Os as ServerTools,js as ServerToolFuncSchema,ls as EventToolFunc,ps as event,ds as _lrucache,ms as createLRUCache,ys as lrucache,Es as ResClientTools,$s as EventClient,ks as eventClient,Ns as ResServerTools,Ts as EventServer,Ms as eventServer,Is as registerCoreTools};
|
|
1
|
+
import{EventEmitter as t}from"events-ex";import{AdvancePropertyManager as e}from"property-manager";import{_createFunction as n}from"util-ex";import{AbstractError as r,createErrorClass as s}from"abstract-error";var i=(t=>(t[t.OK=200]="OK",t[t.Accepted=202]="Accepted",t[t.BadRequest=400]="BadRequest",t[t.InvalidArgument=400]="InvalidArgument",t[t.Unauthorized=401]="Unauthorized",t[t.PaymentRequired=402]="PaymentRequired",t[t.Forbidden=403]="Forbidden",t[t.NotFound=404]="NotFound",t[t.MethodNotAllowed=405]="MethodNotAllowed",t[t.NotAcceptable=406]="NotAcceptable",t[t.RequestTimeout=408]="RequestTimeout",t[t.Conflict=409]="Conflict",t[t.Corruption=409]="Corruption",t[t.TooManyRequests=429]="TooManyRequests",t[t.Aborted=499]="Aborted",t[t.InternalError=500]="InternalError",t[t.NotImplemented=501]="NotImplemented",t[t.NotSupported=501]="NotSupported",t[t.BadGateway=502]="BadGateway",t[t.ServiceUnavailable=503]="ServiceUnavailable",t[t.GatewayTimeout=504]="GatewayTimeout",t))(i||{}),o=500,a=501,c=404,u=409,f=499,h=class t extends r{static createErrorClass(e,n,r=t){return s(e,n,r)}constructor(t,e,n){super(t,e);const r=this.constructor;null!=e?this.code=e:r.code?this.code=r.code:this.code=r.name,n?"string"==typeof n?this.name=n:Object.assign(this,n):"string"==typeof this.code?this.name=this.code:this.name=r.name}toJSON(){const t={name:this.name,code:this.code,data:this.data,caller:this.caller,error:this.message,stack:this.stack};return Object.keys(t).forEach((e=>void 0===t[e]&&delete t[e])),t}fromJSON(e){const n=new t(e.message);return n.code=e.code,n.data=e.data,n.caller=e.caller,n.message=e.error,n.stack=e.stack,n}},l=class extends h{constructor(t,e,n=o){super(t,n,e)}},p=class extends l{constructor(t,e){t||(t="Not Implementation."),super(t,e,501)}};l[501]=p;var w=class extends l{static{this.code=c}constructor(t,e){super(`Could not find ${t}.`,e,c),this.data={what:t}}};l[404]=w;var d=class extends l{static{this.code=u}constructor(t,e){super(`The ${t} already exists.`,e,u),this.data={what:t}}};l[409]=d;var m=class extends l{static{this.code=f}constructor(t,e){e||(e="AbortError"),super(t?`The operation was aborted for ${t}.`:"The operation was aborted.",e,f),t&&(this.data={what:t})}};function y(t,e,n=o){const r=new(l[n]||l)(t,e,n);return"number"!=typeof r.code&&(r.code=n),r}function b(t,e,n=o){throw y(t,e,n)}l[499]=m;import{createAbilityInjector as g}from"custom-ability";var v=.618,x=["get","post","put","delete","patch","list","res"],E={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"}};import{format as $,parse as k,parseISO as S}from"date-fns";import{formatISO as O,parseISO as j,toDate as A}from"date-fns";var N="MMMM d, y 'at' h:m:s b 'GMT'x";function C(t){let e;try{"string"==typeof t?e=S(t):"number"==typeof t?e=new Date(t):t instanceof Date&&(e=t)}catch(t){console.error(t)}return e}function T(t,e=N){return k(t,e,new Date)}function I(t,e=N){return $(t,e)}var M=["stop","length","content-filter","tool-calls","abort","error","other",null],F=["human","ai","generic","system","tool"],P=["user","assistant","system","tool","tool_calls"];function U(t){let e="";for(const n of t)if(n.content){e+=n.role.toLowerCase()+":";let t=n.createdAt;if(t){const n=C(t);n&&(e+=" ["+I(n)+"]")}e+=" "+n.content+"\n"}return e}var V=["chat","char","plan"],B=["internal","hf","fill"];import{BaseFactory as R}from"custom-factory";var _="default",L=class t extends R{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||_,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||_);if(e)return Reflect.construct(e,arguments);throw new l(`Prompt template type ${r} not found`,"PromptTemplate",400)}}_initialize(t){throw new p("Not implemented","PromptTemplate")}initialize(e){this.constructor!==t&&(Object.assign(this,this.toJSON(e)),e?.ignoreInitialize||this._initialize(e))}_format(t){throw new p("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 z(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 q=!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=>{q=t}));var J=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,q?r:z(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()}},D=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"}),W=Object.freeze({set:D.Set,for:D.For,in:D.In,is:D.Is,if:D.If,else:D.Else,endif:D.EndIf,elif:D.ElseIf,endfor:D.EndFor,and:D.And,or:D.Or,not:D.Not,"not in":D.NotIn,macro:D.Macro,endmacro:D.EndMacro,true:D.BooleanLiteral,false:D.BooleanLiteral,True:D.BooleanLiteral,False:D.BooleanLiteral}),K=class{constructor(t,e){this.value=t,this.type=e}};function Z(t){return/\w/.test(t)}function G(t){return/[0-9]/.test(t)}var H=[["{%",D.OpenStatement],["%}",D.CloseStatement],["{{",D.OpenExpression],["}}",D.CloseExpression],["(",D.OpenParen],[")",D.CloseParen],["{",D.OpenCurlyBracket],["}",D.CloseCurlyBracket],["[",D.OpenSquareBracket],["]",D.CloseSquareBracket],[",",D.Comma],[".",D.Dot],[":",D.Colon],["|",D.Pipe],["<=",D.ComparisonBinaryOperator],[">=",D.ComparisonBinaryOperator],["==",D.ComparisonBinaryOperator],["!=",D.ComparisonBinaryOperator],["<",D.ComparisonBinaryOperator],[">",D.ComparisonBinaryOperator],["+",D.AdditiveBinaryOperator],["-",D.AdditiveBinaryOperator],["*",D.MultiplicativeBinaryOperator],["/",D.MultiplicativeBinaryOperator],["%",D.MultiplicativeBinaryOperator],["=",D.Equals]],X=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function Q(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=X.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===D.CloseStatement||t===D.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 K(t,D.Text));continue}}i((t=>/\s/.test(t)));const e=r[s];if("-"===e||"+"===e){const t=n.at(-1)?.type;if(t===D.Text||void 0===t)throw new SyntaxError(`Unexpected character: ${e}`);switch(t){case D.Identifier:case D.NumericLiteral:case D.BooleanLiteral:case D.StringLiteral:case D.CloseParen:case D.CloseSquareBracket:break;default:{++s;const t=i(G);n.push(new K(`${e}${t}`,t.length>0?D.NumericLiteral:D.UnaryOperator));continue}}}for(const[t,e]of H){if(r.slice(s,s+t.length)===t){n.push(new K(t,e)),s+=t.length;continue t}}if("'"!==e&&'"'!==e)if(G(e)){const t=i(G);n.push(new K(t,D.NumericLiteral))}else{if(!Z(e))throw new SyntaxError(`Unexpected character: ${e}`);{const t=i(Z),e=Object.hasOwn(W,t)?W[t]:D.Identifier;e===D.In&&n.at(-1)?.type===D.Not?(n.pop(),n.push(new K("not in",D.NotIn))):n.push(new K(t,e))}}else{++s;const t=i((t=>t!==e));n.push(new K(t,D.StringLiteral)),++s}}return n}var Y=class{constructor(){this.type="Statement"}},tt=class extends Y{constructor(t){super(),this.body=t,this.type="Program"}},et=class extends Y{constructor(t,e,n){super(),this.test=t,this.body=e,this.alternate=n,this.type="If"}},nt=class extends Y{constructor(t,e,n,r){super(),this.loopvar=t,this.iterable=e,this.body=n,this.defaultBlock=r,this.type="For"}},rt=class extends Y{constructor(t,e){super(),this.assignee=t,this.value=e,this.type="Set"}},st=class extends Y{constructor(t,e,n){super(),this.name=t,this.args=e,this.body=n,this.type="Macro"}},it=class extends Y{constructor(){super(...arguments),this.type="Expression"}},ot=class extends it{constructor(t,e,n){super(),this.object=t,this.property=e,this.computed=n,this.type="MemberExpression"}},at=class extends it{constructor(t,e){super(),this.callee=t,this.args=e,this.type="CallExpression"}},ct=class extends it{constructor(t){super(),this.value=t,this.type="Identifier"}},ut=class extends it{constructor(t){super(),this.value=t,this.type="Literal"}},ft=class extends ut{constructor(){super(...arguments),this.type="NumericLiteral"}},ht=class extends ut{constructor(){super(...arguments),this.type="StringLiteral"}},lt=class extends ut{constructor(){super(...arguments),this.type="BooleanLiteral"}},pt=class extends ut{constructor(){super(...arguments),this.type="ArrayLiteral"}},wt=class extends ut{constructor(){super(...arguments),this.type="TupleLiteral"}},dt=class extends ut{constructor(){super(...arguments),this.type="ObjectLiteral"}},mt=class extends it{constructor(t,e,n){super(),this.operator=t,this.left=e,this.right=n,this.type="BinaryExpression"}},yt=class extends it{constructor(t,e){super(),this.operand=t,this.filter=e,this.type="FilterExpression"}},bt=class extends it{constructor(t,e){super(),this.iterable=t,this.test=e,this.type="SelectExpression"}},gt=class extends it{constructor(t,e,n){super(),this.operand=t,this.negate=e,this.test=n,this.type="TestExpression"}},vt=class extends it{constructor(t,e){super(),this.operator=t,this.argument=e,this.type="UnaryExpression"}},xt=class extends it{constructor(t=void 0,e=void 0,n=void 0){super(),this.start=t,this.stop=e,this.step=n,this.type="SliceExpression"}},Et=class extends it{constructor(t,e){super(),this.key=t,this.value=e,this.type="KeywordArgumentExpression"}};function $t(t){const e=new tt([]);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 D.Text:e=new ht(r(D.Text,"Expected text token").value);break;case D.OpenStatement:e=function(){let e;switch(r(D.OpenStatement,"Expected opening statement token"),t[n].type){case D.Set:++n,e=a(),r(D.CloseStatement,"Expected closing statement token");break;case D.If:++n,e=c(),r(D.OpenStatement,"Expected {% token"),r(D.EndIf,"Expected endif token"),r(D.CloseStatement,"Expected %} token");break;case D.Macro:++n,e=function(){const t=x();if("Identifier"!==t.type)throw new SyntaxError("Expected identifier following macro statement");const e=y();r(D.CloseStatement,"Expected closing statement token");const n=[];for(;i(D.OpenStatement,D.EndMacro);)n.push(s());return new st(t,e,n)}(),r(D.OpenStatement,"Expected {% token"),r(D.EndMacro,"Expected endmacro token"),r(D.CloseStatement,"Expected %} token");break;case D.For:++n,e=function(){const t=u(!0);if(!(t instanceof ct||t instanceof wt))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${t.type} instead`);r(D.In,"Expected `in` keyword following loop variable");const e=f();r(D.CloseStatement,"Expected closing statement token");const a=[];for(;i(D.OpenStatement,D.EndFor)&&i(D.OpenStatement,D.Else);)a.push(s());const c=[];if(o(D.OpenStatement,D.Else))for(++n,++n,r(D.CloseStatement,"Expected closing statement token");i(D.OpenStatement,D.EndFor);)c.push(s());return new nt(t,e,a,c)}(),r(D.OpenStatement,"Expected {% token"),r(D.EndFor,"Expected endfor token"),r(D.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${t[n].type} ${t[n].value}`)}return e}(),e.isStatement=!0;break;case D.OpenExpression:e=function(){r(D.OpenExpression,"Expected opening expression token");const t=f();return r(D.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=f();if(o(D.Equals)){++n;const e=a();return new rt(t,e)}return t}function c(){const e=f();r(D.CloseStatement,"Expected closing statement token");const i=[],a=[];for(;t[n]?.type!==D.OpenStatement||t[n+1]?.type!==D.ElseIf&&t[n+1]?.type!==D.Else&&t[n+1]?.type!==D.EndIf;)i.push(s());if(t[n]?.type===D.OpenStatement&&t[n+1]?.type!==D.EndIf)if(++n,o(D.ElseIf))r(D.ElseIf,"Expected elseif token"),a.push(c());else for(r(D.Else,"Expected else token"),r(D.CloseStatement,"Expected closing statement token");t[n]?.type!==D.OpenStatement||t[n+1]?.type!==D.EndIf;)a.push(s());return new et(e,i,a)}function u(t=!1){const e=t?x:f,r=[e()],s=o(D.Comma);for(;s&&(++n,r.push(e()),o(D.Comma)););return s?new wt(r):r[0]}function f(){return function(){const t=h();if(o(D.If)){++n;const e=h();if(o(D.Else)){++n;const r=h();return new et(e,[t],[r])}return new bt(t,e)}return t}()}function h(){let e=l();for(;o(D.Or);){const r=t[n];++n;const s=l();e=new mt(r,e,s)}return e}function l(){let e=p();for(;o(D.And);){const r=t[n];++n;const s=p();e=new mt(r,e,s)}return e}function p(){let e;for(;o(D.Not);){const r=t[n];++n;const s=p();e=new vt(r,s)}return e??function(){let e=w();for(;o(D.ComparisonBinaryOperator)||o(D.In)||o(D.NotIn);){const r=t[n];++n;const s=w();e=new mt(r,e,s)}return e}()}function w(){let e=g();for(;o(D.AdditiveBinaryOperator);){const r=t[n];++n;const s=g();e=new mt(r,e,s)}return e}function d(){const e=function(){let e=x();for(;o(D.Dot)||o(D.OpenSquareBracket);){const s=t[n];let i;++n;const o=s.type!==D.Dot;if(o)i=b(),r(D.CloseSquareBracket,"Expected closing square bracket");else if(i=x(),"Identifier"!==i.type)throw new SyntaxError("Expected identifier following dot operator");e=new ot(e,i,o)}return e}();return o(D.OpenParen)?m(e):e}function m(t){let e=new at(t,y());return o(D.OpenParen)&&(e=m(e)),e}function y(){r(D.OpenParen,"Expected opening parenthesis for arguments list");const t=function(){const t=[];for(;!o(D.CloseParen);){let e=f();if(o(D.Equals)){if(++n,!(e instanceof ct))throw new SyntaxError("Expected identifier for keyword argument");const t=f();e=new Et(e,t)}t.push(e),o(D.Comma)&&++n}return t}();return r(D.CloseParen,"Expected closing parenthesis for arguments list"),t}function b(){const t=[];let e=!1;for(;!o(D.CloseSquareBracket);)o(D.Colon)?(t.push(void 0),++n,e=!0):(t.push(f()),o(D.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 xt(...t)}return t[0]}function g(){let e=v();for(;o(D.MultiplicativeBinaryOperator);){const r=t[n];++n;const s=v();e=new mt(r,e,s)}return e}function v(){let t=function(){let t=d();for(;o(D.Pipe);){++n;let e=x();if(!(e instanceof ct))throw new SyntaxError("Expected identifier for the filter");o(D.OpenParen)&&(e=m(e)),t=new yt(t,e)}return t}();for(;o(D.Is);){++n;const e=o(D.Not);e&&++n;let r=x();if(r instanceof lt&&(r=new ct(r.value.toString())),!(r instanceof ct))throw new SyntaxError("Expected identifier for the test");t=new gt(t,e,r)}return t}function x(){const e=t[n];switch(e.type){case D.NumericLiteral:return++n,new ft(Number(e.value));case D.StringLiteral:return++n,new ht(e.value);case D.BooleanLiteral:return++n,new lt("true"===e.value.toLowerCase());case D.Identifier:return++n,new ct(e.value);case D.OpenParen:{++n;const e=u();if(t[n].type!==D.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${t[n].type} instead`);return++n,e}case D.OpenSquareBracket:{++n;const t=[];for(;!o(D.CloseSquareBracket);)t.push(f()),o(D.Comma)&&++n;return++n,new pt(t)}case D.OpenCurlyBracket:{++n;const t=new Map;for(;!o(D.CloseCurlyBracket);){const e=f();r(D.Colon,"Expected colon between key and value in object literal");const s=f();t.set(e,s),o(D.Comma)&&++n}return++n,new dt(t)}default:throw new SyntaxError(`Unexpected token: ${e.type}`)}}for(;n<t.length;)e.body.push(s());return e}function kt(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 St(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 Ot(t){return t.replace(/\b\w/g,(t=>t.toUpperCase()))}var jt=class{constructor(t=void 0){this.type="RuntimeValue",this.builtins=new Map,this.value=t}__bool__(){return new Ct(!!this.value)}toString(){return""+this.value}toJSON(){return this.value}},At=class extends jt{constructor(){super(...arguments),this.type="NumericValue"}},Nt=class t extends jt{constructor(){super(...arguments),this.type="StringValue",this.builtins=new Map([["upper",new Pt((()=>new t(this.value.toUpperCase())))],["lower",new Pt((()=>new t(this.value.toLowerCase())))],["strip",new Pt((()=>new t(this.value.trim())))],["title",new Pt((()=>new t(Ot(this.value))))],["length",new At(this.value.length)],["rstrip",new Pt((()=>new t(this.value.trimEnd())))],["lstrip",new Pt((()=>new t(this.value.trimStart())))]])}},Ct=class extends jt{constructor(){super(...arguments),this.type="BooleanValue"}},Tt=class extends jt{constructor(t,e){super(t),this.orgValue=e,this.type="ObjectValue",this.builtins=new Map([["get",new Pt((([t,e])=>{if(!(t instanceof Nt))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new Ut}))],["items",new Pt((()=>new Mt(Array.from(this.value.entries()).map((([t,e])=>new Mt([new Nt(t),e]))))))]])}toString(){let t;return t=this.orgValue&&this.orgValue.toString!==Object.prototype.toString?this.orgValue.toString():JSON.stringify(Object.fromEntries(this.value.entries())),t}toJSON(){return this.orgValue?this.orgValue:Object.fromEntries(this.value.entries())}__bool__(){return new Ct(this.value.size>0)}},It=class extends Tt{constructor(){super(...arguments),this.type="KeywordArgumentsValue"}},Mt=class extends jt{constructor(){super(...arguments),this.type="ArrayValue",this.builtins=new Map([["length",new At(this.value.length)]])}__bool__(){return new Ct(this.value.length>0)}},Ft=class extends Mt{constructor(){super(...arguments),this.type="TupleValue"}},Pt=class extends jt{constructor(){super(...arguments),this.type="FunctionValue"}},Ut=class extends jt{constructor(){super(...arguments),this.type="NullValue"}},Vt=class extends jt{constructor(){super(...arguments),this.type="UndefinedValue"}},Bt=class{constructor(t){this.parent=t,this.variables=new Map([["namespace",new Pt((t=>{if(0===t.length)return new Tt(new Map);if(1!==t.length||!(t[0]instanceof Tt))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 Pt],["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 Mt||t instanceof Nt],["lower",t=>{const e=t.value;return"StringValue"===t.type&&e===e.toLowerCase()}],["upper",t=>{const e=t.value;return"StringValue"===t.type&&e===e.toUpperCase()}],["none",t=>"NullValue"===t.type],["defined",t=>"UndefinedValue"!==t.type],["undefined",t=>"UndefinedValue"===t.type],["equalto",(t,e)=>t.value===e.value],["eq",(t,e)=>t.value===e.value]])}set(t,e){return this.declareVariable(t,_t(e))}declareVariable(t,e){if(this.variables.has(t))throw new SyntaxError(`Variable already declared: ${t}`);return this.variables.set(t,e),e}setVariable(t,e){return this.variables.set(t,e),e}resolve(t){if(this.variables.has(t))return this;if(this.parent)return this.parent.resolve(t);throw new Error(`Unknown variable: ${t}`)}lookupVariable(t){try{return this.resolve(t).variables.get(t)??new Vt}catch{return new Vt}}},Rt=class{constructor(t){this.global=t??new Bt}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 Ct(n.value==r.value);case"!=":return new Ct(n.value!=r.value)}if(n instanceof Vt||r instanceof Vt)throw new Error("Cannot perform operation on undefined values");if(n instanceof Ut||r instanceof Ut)throw new Error("Cannot perform operation on null values");if(n instanceof At&&r instanceof At)switch(t.operator.value){case"+":return new At(n.value+r.value);case"-":return new At(n.value-r.value);case"*":return new At(n.value*r.value);case"/":return new At(n.value/r.value);case"%":return new At(n.value%r.value);case"<":return new Ct(n.value<r.value);case">":return new Ct(n.value>r.value);case">=":return new Ct(n.value>=r.value);case"<=":return new Ct(n.value<=r.value)}else if(n instanceof Mt&&r instanceof Mt){if("+"===t.operator.value)return new Mt(n.value.concat(r.value))}else if(r instanceof Mt){const e=void 0!==r.value.find((t=>t.value===n.value));switch(t.operator.value){case"in":return new Ct(e);case"not in":return new Ct(!e)}}if((n instanceof Nt||r instanceof Nt)&&"+"===t.operator.value)return new Nt(n.toString()+r.toString());if(n instanceof Nt&&r instanceof Nt)switch(t.operator.value){case"in":return new Ct(r.value.includes(n.value));case"not in":return new Ct(!r.value.includes(n.value))}if(n instanceof Nt&&r instanceof Tt)switch(t.operator.value){case"in":return new Ct(r.value.has(n.value));case"not in":return new Ct(!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 Pt)return s.value([n],e);if(n instanceof Mt)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 At(n.value.length);case"reverse":return new Mt(n.value.reverse());case"sort":return new Mt(n.value.sort(((t,e)=>{if(t.type!==e.type)throw new Error(`Cannot compare different types: ${t.type} and ${e.type}`);switch(t.type){case"NumericValue":return t.value-e.value;case"StringValue":return t.value.localeCompare(e.value);default:throw new Error(`Cannot compare type: ${t.type}`)}})));default:throw new Error(`Unknown ArrayValue filter: ${r.value}`)}else if(n instanceof Nt)switch(r.value){case"length":return new At(n.value.length);case"upper":return new Nt(n.value.toUpperCase());case"lower":return new Nt(n.value.toLowerCase());case"title":return new Nt(Ot(n.value));case"capitalize":return new Nt(n.value.charAt(0).toUpperCase()+n.value.slice(1));case"trim":return new Nt(n.value.trim());case"trimStart":return new Nt(n.value.trimStart());case"trimEnd":return new Nt(n.value.trimEnd());case"indent":return new Nt(n.value.split("\n").map(((t,e)=>0===e||0===t.length?t:" "+t)).join("\n"));case"string":return n;default:throw new Error(`Unknown StringValue filter: ${r.value}`)}else{if(n instanceof At){if("abs"===r.value)return new At(Math.abs(n.value));throw new Error(`Unknown NumericValue filter: ${r.value}`)}if(n instanceof Tt)switch(r.value){case"items":return new Mt(Array.from(n.value.entries()).map((([t,e])=>new Mt([new Nt(t),e]))));case"length":return new At(n.value.size);case"string":return new Nt(n.toString());default:throw new Error(`Unknown ObjectValue filter: ${r.value}`)}}throw new Error(`Cannot apply filter "${r.value}" to type: ${n.type}`)}if("CallExpression"===t.filter.type){const r=t.filter;if("Identifier"!==r.callee.type)throw new Error(`Unknown filter: ${r.callee.type}`);const s=r.callee.value,i=e.lookupVariable(s);if(i instanceof Pt){const[t,s]=this.evaluateArguments(r.args,e);return s.size>0&&t.push(new It(s)),i.value([n,...t],e)}if(n instanceof Mt){switch(s){case"selectattr":{if(n.value.some((t=>!(t instanceof Tt))))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 Mt(a)}case"map":{const[,t]=this.evaluateArguments(r.args,e);if(t.has("attribute")){const e=t.get("attribute");if(!(e instanceof Nt))throw new Error("attribute must be a string");const r=t.get("default"),s=n.value.map((t=>{if(!(t instanceof Tt))throw new Error("items in map must be an object");return t.value.get(e.value)??r??new Vt}));return new Mt(s)}throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${s}`)}if(n instanceof Nt){if("indent"===s){const[t,s]=this.evaluateArguments(r.args,e),i=t.at(0)??s.get("width")??new At(4);if(!(i instanceof At))throw new Error("width must be a number");const o=t.at(1)??s.get("first")??new Ct(!1),a=t.at(2)??s.get("blank")??new Ct(!1),c=n.value.split("\n"),u=" ".repeat(i.value),f=c.map(((t,e)=>!o.value&&0===e||!a.value&&0===t.length?t:u+t));return new Nt(f.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 Ct(t.negate?!s:s)}evaluateUnaryExpression(t,e){const n=this.evaluate(t.argument,e);if("not"===t.operator.value)return new Ct(!n.value);throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let n="";for(const r of t){const t=this.evaluate(r,e);"NullValue"!==t.type&&"UndefinedValue"!==t.type&&(n+=t)}return new Nt(n)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){const[n,r]=this.evaluateArguments(t.args,e);r.size>0&&n.push(new It(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 Mt||t instanceof Nt))throw new Error("Slice object must be an array or string");const r=this.evaluate(e.start,n),s=this.evaluate(e.stop,n),i=this.evaluate(e.step,n);if(!(r instanceof At||r instanceof Vt))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof At||s instanceof Vt))throw new Error("Slice stop must be numeric or undefined");if(!(i instanceof At||i instanceof Vt))throw new Error("Slice step must be numeric or undefined");return t instanceof Mt?new Mt(St(t.value,r.value,s.value,i.value)):new Nt(St(Array.from(t.value),r.value,s.value,i.value).join(""))}evaluateMemberExpression(t,e){const n=this.evaluate(t.object,e);let r,s;if(t.computed){if("SliceExpression"===t.property.type)return this.evaluateSliceExpression(n,t.property,e);r=this.evaluate(t.property,e)}else r=new Nt(t.property.value);if(n instanceof Tt){if(!(r instanceof Nt))throw new Error(`Cannot access property with non-string: got ${r.type}`);s=n.value.get(r.value)??n.builtins.get(r.value)}else if(n instanceof Mt||n instanceof Nt)if(r instanceof At)s=n.value.at(r.value),n instanceof Nt&&(s=new Nt(n.value.at(r.value)));else{if(!(r instanceof Nt))throw new Error(`Cannot access property with non-string/non-number: got ${r.type}`);s=n.builtins.get(r.value)}else{if(!(r instanceof Nt))throw new Error(`Cannot access property with non-string: got ${r.type}`);s=n.builtins.get(r.value)}return s instanceof jt?s:new Vt}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 Tt))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 Ut}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 Bt(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 Mt))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 Bt(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 At(e+1)],["index0",new At(e)],["revindex",new At(i.length-e)],["revindex0",new At(i.length-e-1)],["first",new Ct(0===e)],["last",new Ct(e===i.length-1)],["length",new At(i.length)],["previtem",e>0?i[e-1]:new Vt],["nextitem",e<i.length-1?i[e+1]:new Vt]]);n.setVariable("loop",new Tt(r)),o[e](n);a+=this.evaluateBlock(t.body,n).value,c=!1}if(c){a+=this.evaluateBlock(t.defaultBlock,n).value}return new Nt(a)}evaluateMacro(t,e){return e.setVariable(t.name.value,new Pt(((e,n)=>{const r=new Bt(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 Ut}evaluate(t,e){if(void 0===t)return new Vt;switch(t.type){case"Program":return this.evalProgram(t,e);case"Set":return this.evaluateSet(t,e);case"If":return this.evaluateIf(t,e);case"For":return this.evaluateFor(t,e);case"Macro":return this.evaluateMacro(t,e);case"NumericLiteral":return new At(Number(t.value));case"StringLiteral":return new Nt(t.value);case"BooleanLiteral":return new Ct(t.value);case"ArrayLiteral":return new Mt(t.value.map((t=>this.evaluate(t,e))));case"TupleLiteral":return new Ft(t.value.map((t=>this.evaluate(t,e))));case"ObjectLiteral":{const n=new Map;for(const[r,s]of t.value){const t=this.evaluate(r,e);if(!(t instanceof Nt))throw new Error(`Object keys must be strings: got ${t.type}`);n.set(t.value,this.evaluate(s,e))}return new Tt(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 _t(t){switch(typeof t){case"number":return new At(t);case"string":return new Nt(t);case"boolean":return new Ct(t);case"undefined":return new Vt;case"object":return null===t?new Ut:Array.isArray(t)?new Mt(t.map(_t)):new Tt(new Map(Object.entries(t).map((([t,e])=>[t,_t(e)]))),t);case"function":return new Pt(((e,n)=>{const r=e.map((t=>Lt(t)));return _t(t(...r)??null)}));default:throw new Error(`Cannot convert to runtime value: ${t}`)}}function Lt(t){let e=t;if(Array.isArray(t))e=t.map((t=>Lt(t)));else if(t instanceof Map)e={},t.forEach(((t,n)=>{e[n]=Lt(t)}));else switch(t.type){case"NullValue":e=null;break;case"UndefinedValue":e=void 0;break;case"ArrayValue":e=t.value.map((t=>Lt(t)));break;case"KeywordArgumentsValue":case"ObjectValue":e=t.orgValue?t.orgValue:Lt(t.value),"KeywordArgumentsValue"===t.type&&Object.setPrototypeOf(e,{jinja_kargs:!0});break;default:t.type&&(e=t.value)}return e}function zt(t,e=0){return Math.floor(Math.random()*(t-e+1))+e}var qt={randomInt:zt,select:function(t,e){if(Array.isArray(t)||"string"==typeof t)return void 0===e?e=zt(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[zt(n.length-1)]}return t[e]}},tojson:function(t,e,n){return e&&"object"==typeof e&&(e.depth&&(n=e.depth),e=e.indent),Jt(t,e,n)}};function Jt(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=>Jt(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}": ${Jt(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 Dt=class extends Bt{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()}},Wt=class t{static{this.global=new Dt}constructor(t,e={}){const n=Q(t,e={lstrip_blocks:!0,trim_blocks:!0,...e});this.parsed=$t(n)}render(e){const n=new Bt(t.global);n.set("false",!1),n.set("true",!0),n.set("raise_exception",(t=>{throw new Error(t)})),n.set("range",kt);for(const[t,r]of Object.entries(e))n.set(t,r);return new Rt(n).run(this.parsed).toString()}};function Kt(t,e){let n;switch(t.type){case"Identifier":n=t.value;break;case"MemberExpression":n=Kt(t.object,e);break;case"FilterExpression":n=Kt(t.operand,e);break;case"Set":{e||(e=[]);const r=Kt(t.assignee);r&&e.push(r),n=Kt(t.value,e);break}}return n&&e?.includes(n)&&(n=void 0),n}function Zt(t){let e;if("Program"===t.type)e=t.body.some((t=>Zt(t)));else e=t.isStatement;return e}function Gt(t,e){let n=[];if(Array.isArray(t))n=t.map((t=>Gt(t,e))).filter(Boolean).flat();else switch(t.type){case"Program":n=t.body.map((t=>Gt(t,e))).filter(Boolean).flat();break;case"If":n=[Kt(t.test,e),...Gt(t.body,e),...Gt(t.alternate,e)].filter(Boolean);break;case"BinaryExpression":n=[Kt(t.left,e),Kt(t.right,e)].filter(Boolean);break;case"For":{const r=Kt(t.loopvar);r&&(e||(e=[]),e.push(r)),n=[Kt(t.iterable,e),...Gt(t.body,e)].filter(Boolean);break}case"CallExpression":n=[Kt(t.callee,e),...Gt(t.args,e)].filter(Boolean);break;default:n=[Kt(t,e)].filter(Boolean)}return n}Wt.global.assign(qt);var Ht=class extends L{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 Wt(n)}catch(t){}return e&&(r=Zt(e.parsed)),r}getVariables(t=this.compiledTemplate){return Gt(t.parsed,[]).filter(((t,e,n)=>n.indexOf(t)===e))}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new l("Prompt template must be a string","PromptTemplate",400);this.compiledTemplate=new Wt(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return this.compiledTemplate.render(t)}};function Xt(t){return function(e){return t}}function Qt(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 Yt(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 te(t){const e=new Set;return t.forEach((t=>{"variable"===t.type&&e.add(t.name)})),[...e]}L.register(Ht,{name:"hf",aliases:["huggingface","internal","default"]});var ee=class extends L{static isTemplate(t){let e,n,r=!1;if("object"==typeof t?(n=t.template,e=t.compiledTemplate):n=t,!e&&n)try{e=Qt(n)}catch(t){}if(e){r=te(e).length>0}return r}getVariables(t=this.compiledTemplate){return te(t)}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new l("Prompt template must be a string","PromptTemplate",400);this.compiledTemplate=Qt(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return Yt(this.compiledTemplate,t)}};function ne(t,e){return"string"==typeof e&&(e=e.split(".").filter((t=>t.length))),e.reduce(((t,e)=>t?.[e]),t)}function re(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 ne(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):ne(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=ne(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=ne(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):ne(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=ne(e,r);let o;return o=isNaN(s)?i[s.substring(1,s.length-1)]:i[parseInt(s,10)],o||""}))}(r,e,n),r}L.register(ee,{name:"fstring",aliases:["python","f-string","langchain"]});var se=class extends L{static isTemplate(t){const e="string"==typeof t?t:t.template;return e?.includes("{{")&&e.includes("}}")}getVariables(t){const e={};return re(t,e,!0),[...Object.keys(e)]}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new l("Prompt template must be a string","PromptTemplate",400);this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables(e)}_format(t){return re(this.template,t)}};function ie(t){return Object.keys(t).sort().map((e=>t[e]))}L.register(se,{name:"golang",aliases:["localai","ollama"]});var oe=class extends L{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 L?t.examplePrompt:L.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=ie(t);n.length>0&&e.push(...n)}const n=[this.prefix,...e,this.suffix].join(this.exampleSeparator),r=this.templateFormat;return await L.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}};L.register(oe,{name:"fewshot",aliases:["few_shot"]});var ae=/(\\)?(\$)(?!\()(\{?)([\w.]+)(?::?-((?:\$\{(?:\$\{(?:\$\{[^}]*\}|[^}])*}|[^}])*}|[^}])+))?(\}?)/gi;function ce(t){return t.replace(/\\\$/g,"$")}function ue(t,e,n){return t.replace(ae,((r,s,i,o,a,c,u)=>"\\"===s?r.slice(1):e[a]?e[a]===n[a]?e[a]:ue(e[a],e,n):n[a]?n[a]===t?n[a]:ue(n[a],e,n):c?c.startsWith("$")?ue(c,e,n):c:""))}function fe(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]?ue(r,e,t.parsed):e[n]:ue(r,e,t.parsed),t.parsed[n]=r?ce(r):r}for(const n in t.parsed)e[n]=t.parsed[n];return t}function he(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=ue(t,e.processEnv,e.parsed);break;case"object":if(n.has(t))return t;if(n.add(t),Array.isArray(t))for(let r=0;r<t.length;r++){const s=t[r];"string"!=typeof s&&"object"!=typeof s||(t[r]=he(t[r],e,n))}else for(const[r,s]of Object.entries(t))"string"!=typeof s&&"object"!=typeof s||(t[r]=he(s,e,n))}return t}var le=/(\S.+?[.!?])(?=\s+|$)|(\S.+?)(?=[\n]|$)/g,pe=/([A-Z][a-z]{1,2}\.)\s(\w)/g,we=/(\.[a-zA-Z]\.)\s(\w)/g,de=new RegExp("([A-Z][a-z]{1,2}\\.)@(\\w)","g"),me=new RegExp("(\\.[a-zA-Z]\\.)@(\\w)","g");function ye(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 be(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=ye(s,"@",[pe,we]),o=Array.from(i.matchAll(le));if(o.length)for(let t=0;t<o.length;t++){let e=ye(o[t][0]," ",[de,me]);r.push(e)}else r.push(s)}return r}function ge(t,e=2,n=.5){const r=10**e;return Math.trunc((t+Number.EPSILON+n/r)*r)/r}async function ve(t){return new Promise((e=>setTimeout(e,t)))}import{createAbilityInjector as xe}from"custom-ability";var Ee="event",$e="event-bus";var ke=xe((function(t){return class{static get emitter(){if(!this._emitter){const t=this.get($e)?.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 Se(t,e){return!t||t.some((t=>t instanceof RegExp?t.test(e):t===e))}var Oe=498,je=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||b("Channel closed","SSEChannel",498);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||Se(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||b("Channel closed","SSEChannel",498);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=>Se(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 Ae(t){return t instanceof ReadableStream||t instanceof WritableStream}var Ne=600,Ce=601,Te=class extends h{constructor(t,e=600){super(t,500)}};function Ie(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 Te(`Response error: ${e}`,Ce))}}})}return new ReadableStream({start(t){t.error(new Te("Response error: No response body",Ce))}})}function Me(){return new ReadableStream({start(t){t.close()}})}import{createParser as Fe}from"eventsource-parser";function Pe(t){const e=new TextDecoder;let n;return new TransformStream({async start(e){n=Fe((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 Ue(){let t=!0;return e=>(t&&(e=e.trimStart())&&(t=!1),e)}function Ve(t,e){if(!t.ok)return Ie(t.body);let n=t.body||new ReadableStream({start(t){t.close()}});return n instanceof ReadableStream||(n=ReadableStream.from(n)),n.pipeThrough(Pe(e))}function Be(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 Re(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()}})}import{v1 as _e,v5 as Le,v4 as ze}from"uuid";import*as qe from"base32768";import{v1 as Je,v4 as De,v5 as We,stringify as Ke,parse as Ze,validate as Ge,version as He,NIL as Xe}from"uuid";var Qe={1:_e,4:ze,5:Le};function Ye(t=1,e){const n=Qe[t];return e?qe.encode(n(null,[])):n()}import tn from"xxhashjs";import*as en from"base32768";import{canonicalize as nn}from"json-canonicalize";var rn=en,{h32:sn,h64:on}=tn,an=588213;function cn(t,e=16){return"object"==typeof t&&(t=nn(t)),sn(t,an).toString(e)}function un(t,e=16){return"object"==typeof t&&(t=nn(t)),on(t,an).toString(e)}var fn=(t=>(t[t.xxhash64=111]="xxhash64",t[t.xxhash32=112]="xxhash32",t))(fn||{});function hn(t,e=111,n=an){let r;return t.buffer&&(t=t.buffer),112!==e?(r=on(t,n),r=new Uint16Array([r._a00,r._a16,r._a32,r._a48]),r=new Uint8Array(r.buffer)):(r=sn(t,n),r=new Uint16Array([r._low,r._high]),r=new Uint8Array(r.buffer)),r}function ln(t,e=111,n=an){return en.encode(hn(t,e,n))}import pn from"path";var wn=/[<>:"/\\|?*\u0000-\u001F]/,dn=/^(con|prn|aux|nul|com\d|lpt\d)$/i,mn=100,yn=/^\.+(\\|\/)|^\.+$/,bn=/\.+$/,gn=/[\u0000-\u001F\u0080-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069]/;function vn(){return new RegExp(wn.source,"g")}function xn(){return new RegExp(gn.source,"g")}function En(t){return t&&!(wn.test(t)||xn().test(t)||yn.test(t)||bn.test(t))}function $n(t){const e=t.split(pn.sep);return("/"===t[0]||e[0]&&pn.dirname(e[0])===e[0])&&e.shift(),e.every(En)}function kn(t,e={}){const n=e.replacement||"!";if((wn.test(n)||gn.test(n))&&b("Replacement string cannot contain reserved filename characters","sanitizeFilename",400),n.length>0){const e=/([<>:"/\\|?*\u0000-\u001F]){2,}/;t=t.replace(e,"$1")}if(t=(t=(t=(t=(t=t.normalize("NFD")).replace(yn,n)).replace(vn(),n)).replace(xn(),n)).replace(bn,""),n.length>0){"."===t[0]||"."!==t[0]||(t=n+t),"."===t[t.length-1]&&(t+=n)}t=dn.test(t)?t+n:t;const r="number"==typeof e.maxLength?e.maxLength:mn;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(pn.sep);let r;("/"===t[0]||n[0]&&pn.dirname(n[0])===n[0])&&(r=n.shift());const s=n.map((t=>kn(t,e)));return void 0!==r&&s.unshift(r),s.join(pn.sep)}function On(t,e=1){let n="";for(;e--;){const e=pn.extname(t);if(!e)break;n=e+n,t=pn.basename(t,e)}return n}function jn(t){return t.split(".").length-1}import{isRegExpStr as An,toRegExp as Nn}from"util-ex";function Cn(t,e){if("string"!=typeof t)throw new l("modelName must be a string","isModelNameMatched",400);switch(typeof e){case"string":if(An(e)){const n=(e=Nn(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(An(n)){const r=(e=Nn(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 Tn(t){return Object.keys(t).filter((t=>Number.isNaN(Number(t))))}import{pick as In}from"lodash-es";import{newFunction as Mn}from"util-ex";function Fn(t,e){if(e&&(e=Vn(e)),e){const n=Object.keys(e);if(n.length){const r=Object.values(e);return Mn("expression",n,`return ${t}`)(...r)}}return Mn("expression",[],`return ${t}`)()}var Pn=/^[a-zA-Z_$][0-9a-zA-Z_$]*$/,Un=t=>Pn.test(t);function Vn(t){if(t){const e=Object.keys(t),n=e.length,r=e.filter((e=>Un(e)&&null!==t[e]));if(n===r.length)return t;if(r.length)return t=In(t,r)}}function Bn(t){return t?Rn(t,[],""):[]}function Rn(t,e,n="."){return Array.isArray(t)?t.flatMap(((t,n)=>Rn(t,[...e,`[${n}]`]))):(r=t)&&r.constructor===Object?Object.entries(t).flatMap((([t,r])=>Rn(r,[...e,n+t]))):[e.join("")];var r}function _n(t){if(t<2)throw new l("repetitionThreshold must be greater than 1","createEndWithRepetitionDetector",400);const e=new RegExp(`([\\S\\s]+)(\\1{${t-1},})$`);return function(t){return e.exec(t)}}import Ln from"path";import*as zn from"fs";function qn(t){const e=zn.statSync(t,{throwIfNoEntry:!1});return e?.isFile()}function Jn(t,e,n,r){const s=r?.signal,i=r?.exclude;let o;if(Ln.isAbsolute(t)?o=qn(t)?t:Dn(Ln.basename(t),[Ln.dirname(t)],{extNames:n,exclude:i,signal:s}):(e||(e=["."]),o=Dn(t,e,{extNames:n,exclude:i,signal:s})),!o)throw new w(t,"loadFileFromPaths");{const t=o;o=zn.readFileSync(o),r&&(r.filepath=t)}return o}function Dn(t,e,{extNames:n,signal:r,exclude:s=[]}){let i;const o=n?n.map((e=>On(t,jn(e)))):void 0;"string"==typeof s&&(s=[s]);for(const a of e){if(r?.aborted)throw r.reason;const e=Ln.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)&&qn(r)){i=r;break}}else if(!s.includes(e)&&qn(e)){i=e;break}}return i}function Wn(t,e,n,r,s){let i;"string"==typeof r?(i=r,r=void 0):i=r?.encoding??"utf8";return Jn(t,e,n,r).toString(i)}function Kn(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=Zn(r.pop()),e=Ln.resolve(t);if(s.has(e))continue;s.add(e);const u=zn.statSync(t,{throwIfNoEntry:!1});if(u?.isDirectory()){const e=zn.readdirSync(t,{withFileTypes:!0});for(let s=0;s<e.length;s++){const i=e[s],a=Ln.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 Zn(t){const e=zn.lstatSync(t,{throwIfNoEntry:!1});return e?.isSymbolicLink()&&(t=zn.readlinkSync(t)),t}import{existsSync as Gn,mkdirSync as Hn,readdirSync as Xn,statSync as Qn,writeFileSync as Yn}from"fs";import tr from"path";import{Config as er}from"load-config-file";import{parse as nr,stringify as rr}from"yaml";import{regexp as sr}from"yaml-types";import{mimeType as ir}from"mime-type/with-db";import{stringify as or}from"yaml";var ar=[sr];function cr(t){Array.isArray(t)||(t=[t]);for(const e of t){-1===ar.indexOf(e)&&ar.push(e)}}function ur(t){return nr(t,{customTags:ar})}function fr(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=Xn(t,{withFileTypes:!0,recursive:!0});for(const r of n){const n=tr.join(t,r.name);r.isFile()&&e(n,r)}}(t,((t,e)=>{if(s?.includes(t))return;const o=tr.extname(t),a=Qn(t);if(i.includes(o)){if(r?.hasOwnProperty(t)&&a.mtimeMs<=r[t])return;n.push(t)}})),n}function hr(t,e){return fr(t,e).map((t=>er.loadSync(t))).filter((t=>void 0!==t))}function lr(t,e,n=1){"."===t[0]&&n++;const r=On(t,n);(!r||r.split(".").length<=1)&&(t+=".yaml");const s=ir.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=rr(e)}const i=tr.dirname(t);return Gn(i)||Hn(i,{recursive:!0}),Yn(t,e,{encoding:"utf8"}),t}function pr(t){t instanceof Date&&(t=t.toISOString());return function(t,e){return t?`'${e}'`:String(e)}("string"==typeof t,t)}function wr(t,e){return t.map((t=>yr(t,e))).join(" AND ")}function dr(t,e){return t.map((t=>yr(t,e))).join(" OR ")}function mr(t,e){const n=[];return Object.keys(e).forEach((r=>{const s=e[r];switch(r){case"$lt":case"<":n.push(`${t} < ${pr(s)}`);break;case"<=":case"$lte":n.push(`${t} <= ${pr(s)}`);break;case"$gt":case">":n.push(`${t} > ${pr(s)}`);break;case"$gte":case">=":n.push(`${t} >= ${pr(s)}`);break;case"$ne":case"!=":n.push(`${t} != ${pr(s)}`);break;case"=":case"$eq":n.push(`${t} = ${pr(s)}`);break;case"$in":n.push(`${t} IN (${s.map((t=>pr(t))).join(", ")})`);break;case"$nin":n.push(`${t} NOT IN (${s.map((t=>pr(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 yr(t,e){const n=[];if("function"!=typeof e&&(e=t=>t),Array.isArray(t))n.push(wr(t,e));else for(const[r,s]of Object.entries(t))if("$and"===r)n.push(`(${wr(t[r],e)})`);else if("$or"===r)n.push(`(${dr(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(mr(e(r),s))}return n.length>1?n.join(" AND "):n[0]}function br(t){const e=t.indexOf("://");if(e>0)return t.substring(0,e)}function gr(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 vr(t){const e=t.match(/^\s*[+]?(\d+(?:[.]\d+)?)\s*([TBMK])?\s*$/i);if(!e)throw new l("Invalid formatted parameter size string.","scaleToSize",400);const n=parseFloat(e[1]),r=e[2]?.toLowerCase();switch(r){case"t":return 1e12*n;case"b":return 1e9*n;case"m":return 1e6*n;case"k":return 1e3*n;default:return n}}function xr(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":" ")+xr(t,{level:n+1,visiting:r})}}er.register([".yml",".yaml"],ur),er.register([".json"],(function(t){return JSON.parse(t)}));var Er=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}};import{EventEmitter as $r}from"events-ex";var kr=32;function Sr(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 Or=class{constructor(t){this._capacity=Sr(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(Sr(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)}}},jr=class extends $r{};function Ar(t){return"function"==typeof t}function Nr(){return"1"}var Cr=class{constructor(t,{initFn:e=Nr,pauseFn:n,resumeFn:r,capacity:s=32}={}){if(Ar(n)!==Ar(r))throw new Error("pauseFn and resumeFn must be both set for pausing");this.maxConcurrency=t,this.free=new Or(t),this.waiting=new Or(s),this.releaseEmitter=new jr,this.useDefaultTokens=e===Nr,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 Tr(t,{timeUnit:e=1e3,uniformDistribution:n=!1}={}){const r=new Cr(n?1:t),s=n?e/t:e;return async function(){await r.acquire(),setTimeout((()=>r.release()),s)}}import{createAbilityInjector as Ir}from"custom-ability";import{defineProperty as Mr}from"util-ex";var Fr=class extends AbortController{constructor(t){super(),Mr(this,"parent",t)}abort(t,e){this.signal.aborted||("string"==typeof t&&(t=new m(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 m(e.reason||"aborted")}}},Pr=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 Cr(t-1)),e}isAborted(t){const e=this.hasAsyncFeature(os);let n=this.__task_aborter;if(n&&e){if(null==t)throw new l("Missing taskId",this.name+".isAborted",400);n=n[t]}return!n||n.signal.aborted}getRunningTask(t){const e=this.hasAsyncFeature(os);let n=this.__task_aborter;if(n&&e){if(null==t)throw new l("Missing taskId",this.name+".getRunningTask",400);n=n[t]}return n?.signal.aborted&&(e?this.__task_aborter[t]=void 0:this.__task_aborter=void 0,n=void 0),n}getRunningTaskCount(){let t;if(this.hasAsyncFeature(os)){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(os);if(!r&&n&&this.getRunningTask())throw new l("The task is running",this.name,429);const s=t?.aborter||new Fr(this);if(!(s instanceof Fr)){if(!(s instanceof AbortController))throw new l("aborter should be an AbortController",this.name,400);Object.setPrototypeOf(s,new Fr(this))}if(r){null==this.__task_aborter&&(this.__task_aborter={});const t=this.__task_aborter;null==e&&(e=this.generateAsyncTaskId(e,t)),s.id=e,t[e]=s}else this.__task_aborter=s;const i=t?.timeout;return i>0&&(s.timeoutId=setTimeout((()=>{s.timeoutId=void 0,this.abort("timeout",{timeout:i})}),i)),s.signal.addEventListener("abort",(()=>{const t=s.timeoutId;t&&(s.timeoutId=void 0,clearTimeout(t));const e=s.signal;try{this.emit&&this.emit("aborting",e.reason,e.reason?.data)}finally{s.streamController?.error(e.reason)}})),s}$cleanMultiTaskAborter(t,e){const n=this.super,r=this.self||this;n?n.call(r,t,e):r._cleanMultiTaskAborter(t,e)}cleanTaskAborter(t){if(this.hasAsyncFeature(os)){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=Re({onStart:t=>{Mr(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(os)){const t=e?.taskId;if(null==t)throw new l("Missing data.taskId",this.name+".abort",400);n=n[t],this.cleanMultiTaskAborter(t,r)}else this.__task_aborter=void 0;n&&!n.signal.aborted&&n.abort(t,e)}}};Pr.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},Pr.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};var Ur=Ir(Pr,"abort",{afterInjection:function(t,e){let n=t.prototype._asyncFeatures||0;n|=fs.Cancelable,e&&(e.asyncFeatures&&(n|=e.asyncFeatures),e.maxTaskConcurrency>0&&(t.prototype._maxTaskConcurrency=e.maxTaskConcurrency)),t.prototype._asyncFeatures=n}});function Vr(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}import{get as Br}from"lodash-es";import{newFunction as Rr}from"util-ex";async function _r(t,e,n){return zr(Qr(t,e,n),e,n)}function Lr(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 zr(t,e,n){if(t.length){const r=await Promise.all(t.map(((t,r)=>Xr(t,r,e,n))));console.log("🚀 ~ parseObjectArgumentInfos ~ _args:",r);const s=n?.returnArrayOnly;let i;if(r?.length){const t=`{${r.map((t=>t)).join(",")}}`;console.log("🚀 ~ parseObjectArgumentInfos ~ jsonStr:",t),i=Fn(t,e)}return i&&!s&&(i=Lr(i)),i}}function qr(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=>Wr(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(Wr(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 L.formatIf(a);return c?(o=c,i+":"+JSON.stringify(o)):void 0}async function Dr(t,e,n,r){let s=qr(t,0,n,r);return s||(s=await Jr(t,e,n,r)),s}function Wr(t){const e=t[0];return('"'===e||"'"===e)&&t[t.length-1]===e}function Kr(t){return'"'+t.replace(/(?<!\\)"(?!\\)/g,'\\"')+'"'}var Zr=["true","false","null","undefined","NaN","Infinity"];function Gr(t){return function(t,e=['""',"''","{}"]){return e.some((e=>t[0]===e[0]&&t[t.length-1]===e[1]))}(t)||!Number.isNaN(parseFloat(t))||Zr.includes(t)||es(t)}async function Hr(t,e){const n=Rr("async expression",[],`return ${t};`,Vn(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 Xr(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(!(Gr(r)||n&&void 0!==Br(n,r)))return e+":"+Kr(r);if(!es(i))try{return e+":"+await Hr.call(this,r,n)}catch(t){}return i}{const t=i.trim();if(n&&void 0!==Br(n,t))return e+":"+t+', "'+t+'":'+t;if(Gr(t))return e+":"+t;if(!es(i))try{return e+":"+await Hr.call(this,t,n)}catch(t){}return e+":"+Kr(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 Yr(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 _r(i,e,n)),{command:s.trim(),args:o}}var ts=/^\s*\(\)|[a-zA-Z_$][\w\d$]*|\(([a-zA-Z_$][\w\d$]*)(\s*,\s*([a-zA-Z_$][\w\d$]*))*\)\s*=>/;function es(t){return ts.test(t)}import ns from"memoizee";import{canonicalize as rs}from"json-canonicalize";function ss(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 ns(t,{...e,normalizer:t=>{if(r){const e=r(t);if("string"===e)return e;e&&(t=e)}return ln(rs(t))}})}var is,os=0,as=1,cs=2,us=(t=>(t[t.MultiTask=os]="MultiTask",t[t.Cancelable=1]="Cancelable",t[t.Priority=2]="Priority",t))(us||{}),fs=((is=fs||{})[is.MultiTask=1<<os]="MultiTask",is[is.Cancelable=2]="Cancelable",is[is.Priority=4]="Priority",is),hs=class t extends e{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),Er.has(n,t)}static run(t,e){const n=this.get(t);if(n)return n.run(e);throw new w(`${t} to run`,this.name)}static runSync(t,e){const n=this.get(t);if(n)return n.runSync(e);throw new w(`${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(`${t} to run`,this.name)}static runWithPosSync(t,...e){const n=this.get(t);if(n)return n.runWithPosSync(...e);throw new w(`${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);b("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),Er.has(e,t)}isStream(t){return this.stream}},ls={name:{type:"string"},description:{type:"string"},func:{type:"function",assign(t,e,r,s,i){let o=t;const a=typeof t;return i.isExported?o="function"===a?t.toString():t:t&&("string"!==a&&(t=t.toString()),o=n(t,e.scope)),o}},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"}};hs.defineProperties(hs,ls);var ps=class extends hs{constructor(){super(...arguments),this._emitter=new t,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},ws=new ps($e);import{Cache as ds}from"secondary-cache";function ms({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 ys(t,e){let n=hs.get(t);return n||(n=new hs(t,{func:ms,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 ds(e)),n}var bs=ys("lrucache"),gs=class t extends hs{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 b("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):b(`${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 y(r,s,n)}async func(t){const e=await this.fetch(t);if(t?.stream)return e;return await e.json()}},vs={...E};gs.defineProperties(gs,vs);var xs=class extends gs{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))}}},Es={methods:{type:"array",assign(t,e,n,r,s){s?.isExported||e.assignMethods(t)}}};xs.defineProperties(xs,Es);var $s=class extends xs{async fetch(t,e){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let n=t.id;return n||b("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)}},ks=class extends $s{constructor(){super(...arguments),this._sseEvents={},this._forwardEvents=new Set,this.name=Ee,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)}},Ss=new ks(Ee);import{getAllNames as Os}from"util-ex";var js=class t extends hs{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({}){}},As={...E};js.defineProperties(js,As);var Ns=class extends js{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);Os(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(e,this.name)}};Ns.defineProperties(Ns,{methods:{type:"array"}});var Cs=class extends Ns{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}}}static{this.SpecialRpcMethodNames=x}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}},Ts=ws.runSync(),Is=class t extends Cs{constructor(){super(...arguments),this.name=Ee,this.description="subscribe server sent event",this.result="event",this.depends={[$e]:ws}}static get sse(){return this._sse||(this._sse=new je),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=Ts.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)||Ts.on(n,t.ebListener)}unforward(e){"string"==typeof e&&(e=[e]);for(const n of e)Ts.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};b("event is required","sub",400)}$unsub({event:t}){if(t)return this.unforward(t),{event:t};b("event is required","unsub",400)}$publish({event:t,data:e}){if(t&&e){"string"==typeof t&&(t=[t]);for(const n of t)this.publishSSE(e,n);return{event:t}}b("event or data is required","pub",400)}isStream(t){return"list"===this.getMethodFromParams(t)}},Ms=new Is(Ee);function Fs(){ws.register(),bs.register()}export{v as PASSING_SCORE,x as ActionNames,E as RemoteToolFuncSchema,i as ErrorCode,o as InternalErrorCode,a as NotImplementedErrorCode,c as NotFoundErrorCode,u as AlreadyExistsErrorCode,f as AbortErrorCode,h as BaseError,l as CommonError,p as NotImplementationError,w as NotFoundError,d as AlreadyExistsError,m as AbortError,y as createError,b as throwError,k as parseDateFormat,C as toDateTime,T as textToDate,I as dateToText,O as formatISO,j as parseISO,A as toDate,M as AITextGenerationFinishReasons,F as AIMessageTypes,P as AIChatRoles,U as messagesToText,V as PromptTypes,B as PromptTemplateTypes,_ as defaultTemplateFormat,L as PromptTemplate,J as PromptExampleSelector,Q as tokenize,$t as parse,Rt as Interpreter,qt as builtins,Dt as EnvironmentEx,Wt as Template,Ht as HfPromptTemplate,Xt as createHfValueFunc,Qt as parseFString,Yt as interpolateFString,ee as FStringPromptTemplate,re as interpolateGolangTemplate,se as GolangPromptTemplate,ie as sortedValues,oe as FewShotPromptTemplate,ue as interpolateEnv,fe as expandEnv,he as expandObjEnv,be as splitSentence,ge as truncTo,ve as wait,Ee as EventName,$e as EventBusName,ke as backendEventable,Oe as SSEChannelAlreadyClosedErrCode,je as SSEChannel,Ae as isWebStream,Ne as RStreamErrCode,Ce as ResponseRStreamErrCode,Te as ReadableStreamError,Ie as getResponseErrorReadableStream,Me as createEmptyReadableStream,Pe as createEventStreamTransformer,Ue as trimStartOfStreamHelper,Ve as AIStream,Be as readableFromAsyncIterable,Re as createCallbacksTransformer,Ye as uuid,Je as v1,De as v4,We as v5,Ke as stringify,Ze as parse2,Ge as validate,He as version,Xe as NIL,nn as canonicalize,rn as base32768,cn as xxhash32,un as xxhash64,fn as XXHashAlgorithm,hn as xxhash,ln as xxhashAsStr,wn as FilenameReservedRegex,dn as WindowsReservedNameRegex,vn as filenameReservedRegex,xn as reControlCharsRegex,En as isValidFilename,$n as isValidFilepath,kn as sanitizeFilename,Sn as sanitizeFilepath,On as getMultiLevelExtname,jn as extNameLevel,Cn as isModelNameMatched,Tn as getAllEnumKeys,Fn as parseJsJson,Vn as filterValidFnScope,Bn as getKeysPath,_n as createEndWithRepetitionDetector,qn as fileIsExists,Jn as loadFileFromPaths,Wn as loadTextFromPaths,Kn as readFilenamesRecursiveSync,Zn as getRealFilepath,er as ConfigFile,ir as mimeType,cr as registerYamlTag,ur as parseYaml,fr as getConfigFileNames,hr as getConfigs,lr as saveConfigFile,or as stringify2,yr as jsonFilterToWhere,br as matchUrlProtocol,gr as paramsSizeToScaleStr,vr as scaleStrToParamsSize,xr as jsonToMarkdownStr,Er as IntSet,kr as DefaultAsyncSemaphoreCapacity,Cr as Semaphore,Tr as RateLimit,os as ToolAsyncMultiTaskBit,as as ToolAsyncCancelableBit,cs as ToolAsyncPriorityBit,us as AsyncFeatureBits,fs as AsyncFeatures,hs as ToolFunc,ls as ToolFuncSchema,Fr as TaskAbortController,Pr as CancelableAbility,Ur as makeToolFuncCancelable,Vr as countRegexMatches,_r as parseObjectArguments,Lr as simplifyObjectArguments,zr as parseObjectArgumentInfos,qr as ChoiceArgProcessor,Jr as TemplateArgProcessor,Dr as AIArgProcessor,Kr as quoteStr,Xr as parseObjectArgInfo,Qr as parseObjectArgumentsAsArgInfos,Yr as parseCommand,ss as memoize,g as createAbilityInjector,gs as ClientTools,vs as ClientToolFuncSchema,js as ServerTools,As as ServerToolFuncSchema,ps as EventToolFunc,ws as event,ms as _lrucache,ys as createLRUCache,bs as lrucache,$s as ResClientTools,ks as EventClient,Ss as eventClient,Cs as ResServerTools,Is as EventServer,Ms as eventServer,Fs as registerCoreTools};
|
package/dist/funcs.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EventClient as m,EventServer as o,EventToolFunc as r,_lrucache as p,createLRUCache as t,event as c,eventClient as e,eventServer as f,lrucache as h,registerCoreTools as i}from"./chunk-
|
|
1
|
+
import{EventClient as m,EventServer as o,EventToolFunc as r,_lrucache as p,createLRUCache as t,event as c,eventClient as e,eventServer as f,lrucache as h,registerCoreTools as i}from"./chunk-O367BMRE.mjs";export{m as EventClient,o as EventServer,r as EventToolFunc,p as _lrucache,t as createLRUCache,c as event,e as eventClient,f as eventServer,h as lrucache,i as registerCoreTools};
|
package/dist/index.d.mts
CHANGED
|
@@ -1542,6 +1542,7 @@ interface ParseObjectArgumentOptions {
|
|
|
1542
1542
|
* ```
|
|
1543
1543
|
*/
|
|
1544
1544
|
declare function parseObjectArguments(argsStr: string, scope?: Record<string, any>, options?: ParseObjectArgumentOptions): Promise<any>;
|
|
1545
|
+
declare function simplifyObjectArguments(args: any): any;
|
|
1545
1546
|
declare function parseObjectArgumentInfos(args: ArgInfo[], scope?: Record<string, any>, options?: ParseObjectArgumentOptions): Promise<any>;
|
|
1546
1547
|
declare function ChoiceArgProcessor(argInfo: ArgInfo, _ix: number, scope?: Record<string, any>, options?: ParseObjectArgumentOptions): string | undefined;
|
|
1547
1548
|
declare function TemplateArgProcessor([isNamedArg, arg]: ArgInfo, ix: number, scope?: Record<string, any>, options?: ParseObjectArgumentOptions): Promise<string | undefined>;
|
|
@@ -1571,4 +1572,4 @@ declare function parseCommand(commandStr: string, scope?: Record<string, any>, o
|
|
|
1571
1572
|
|
|
1572
1573
|
declare function memoize<F extends (...args: any[]) => any>(fn: any, options?: Options<F>): F & _memoize.Memoized<F>;
|
|
1573
1574
|
|
|
1574
|
-
export { AIArgProcessor, type AIChatAssistantMessageParam, type AIChatContentPart, type AIChatContentPartImage, type AIChatContentPartText, type AIChatMessageParam, type AIChatMessageParamBase, type AIChatMessageToolCall, type AIChatRole, AIChatRoles, type AIChatSystemMessageParam, type AIChatToolMessageParam, type AIChatUserMessageParam, type AIChoiceConfig, type AIMessageType, AIMessageTypes, AIModelNameRules, type AIResult, AIStream, type AIStreamParser, type AIStreamParserOptions, type AITextGenerationFinishReason, AITextGenerationFinishReasons, AsyncFeatures, type AsyncTaskId, BaseError, CancelableAbility, type CancelableAbilityOptions, ChoiceArgProcessor, CommonError, DefaultAsyncSemaphoreCapacity, type DotenvExpandOptions, type DotenvExpandOutput, type DotenvParseInput, type DotenvParseOutput, type DotenvPopulateInput, EventBusName, type EventErrorListenerFn, type EventListenerFn, EventName, FStringPromptTemplate, type FStringPromptTemplateNode, FewShotPromptTemplate, type FewShotPromptTemplateOptions, FilenameReservedRegex, GolangPromptTemplate, builtins as HFBuiltins, EnvironmentEx as HFEnvironment, Interpreter as HFInterpreter, Template as HFTemplate, HfPromptTemplate, IntSet, type JsonFilter, type ParseObjectArgumentOptions, PromptExampleSelector, type PromptExampleSelectorOptions, type PromptExamples, PromptTemplate, type PromptTemplateOptions, type PromptTemplateType, PromptTemplateTypes, type PromptType, PromptTypes, RStreamErrCode, RateLimit, ReadableStreamError, ResponseRStreamErrCode, type SanitizeFilenameOptions, Semaphore, type StreamCallbacksAndOptions, TaskAbortController, type TaskAbortControllers, type TaskPromise, TemplateArgProcessor, ToolFunc, WindowsReservedNameRegex, XXHashAlgorithm, backendEventable, base32768, countRegexMatches, createCallbacksTransformer, createEmptyReadableStream, createEndWithRepetitionDetector, createEventStreamTransformer, createHfValueFunc, dateToText, defaultTemplateFormat, expandEnv, expandObjEnv, extNameLevel, fileIsExists, filenameReservedRegex, filterValidFnScope, getAllEnumKeys, getConfigFileNames, getConfigs, getKeysPath, getMultiLevelExtname, getRealFilepath, getResponseErrorReadableStream, parse as hfParse, tokenize as hfTokenize, interpolateEnv, interpolateFString, interpolateGolangTemplate, isModelNameMatched, isValidFilename, isValidFilepath, isWebStream, jsonFilterToWhere, jsonToMarkdownStr, loadFileFromPaths, loadTextFromPaths, makeToolFuncCancelable, matchUrlProtocol, memoize, messagesToText, paramsSizeToScaleStr, parseCommand, parseFString, parseJsJson, parseObjectArgInfo, parseObjectArgumentInfos, parseObjectArguments, parseObjectArgumentsAsArgInfos, parseYaml, quoteStr, reControlCharsRegex, readFilenamesRecursiveSync, readableFromAsyncIterable, registerYamlTag, sanitizeFilename, sanitizeFilepath, saveConfigFile, scaleStrToParamsSize, sortedValues, splitSentence, textToDate, toDateTime, trimStartOfStreamHelper, truncTo, uuid, wait, xxhash, xxhash32, xxhash64, xxhashAsStr };
|
|
1575
|
+
export { AIArgProcessor, type AIChatAssistantMessageParam, type AIChatContentPart, type AIChatContentPartImage, type AIChatContentPartText, type AIChatMessageParam, type AIChatMessageParamBase, type AIChatMessageToolCall, type AIChatRole, AIChatRoles, type AIChatSystemMessageParam, type AIChatToolMessageParam, type AIChatUserMessageParam, type AIChoiceConfig, type AIMessageType, AIMessageTypes, AIModelNameRules, type AIResult, AIStream, type AIStreamParser, type AIStreamParserOptions, type AITextGenerationFinishReason, AITextGenerationFinishReasons, AsyncFeatures, type AsyncTaskId, BaseError, CancelableAbility, type CancelableAbilityOptions, ChoiceArgProcessor, CommonError, DefaultAsyncSemaphoreCapacity, type DotenvExpandOptions, type DotenvExpandOutput, type DotenvParseInput, type DotenvParseOutput, type DotenvPopulateInput, EventBusName, type EventErrorListenerFn, type EventListenerFn, EventName, FStringPromptTemplate, type FStringPromptTemplateNode, FewShotPromptTemplate, type FewShotPromptTemplateOptions, FilenameReservedRegex, GolangPromptTemplate, builtins as HFBuiltins, EnvironmentEx as HFEnvironment, Interpreter as HFInterpreter, Template as HFTemplate, HfPromptTemplate, IntSet, type JsonFilter, type ParseObjectArgumentOptions, PromptExampleSelector, type PromptExampleSelectorOptions, type PromptExamples, PromptTemplate, type PromptTemplateOptions, type PromptTemplateType, PromptTemplateTypes, type PromptType, PromptTypes, RStreamErrCode, RateLimit, ReadableStreamError, ResponseRStreamErrCode, type SanitizeFilenameOptions, Semaphore, type StreamCallbacksAndOptions, TaskAbortController, type TaskAbortControllers, type TaskPromise, TemplateArgProcessor, ToolFunc, WindowsReservedNameRegex, XXHashAlgorithm, backendEventable, base32768, countRegexMatches, createCallbacksTransformer, createEmptyReadableStream, createEndWithRepetitionDetector, createEventStreamTransformer, createHfValueFunc, dateToText, defaultTemplateFormat, expandEnv, expandObjEnv, extNameLevel, fileIsExists, filenameReservedRegex, filterValidFnScope, getAllEnumKeys, getConfigFileNames, getConfigs, getKeysPath, getMultiLevelExtname, getRealFilepath, getResponseErrorReadableStream, parse as hfParse, tokenize as hfTokenize, interpolateEnv, interpolateFString, interpolateGolangTemplate, isModelNameMatched, isValidFilename, isValidFilepath, isWebStream, jsonFilterToWhere, jsonToMarkdownStr, loadFileFromPaths, loadTextFromPaths, makeToolFuncCancelable, matchUrlProtocol, memoize, messagesToText, paramsSizeToScaleStr, parseCommand, parseFString, parseJsJson, parseObjectArgInfo, parseObjectArgumentInfos, parseObjectArguments, parseObjectArgumentsAsArgInfos, parseYaml, quoteStr, reControlCharsRegex, readFilenamesRecursiveSync, readableFromAsyncIterable, registerYamlTag, sanitizeFilename, sanitizeFilepath, saveConfigFile, scaleStrToParamsSize, simplifyObjectArguments, sortedValues, splitSentence, textToDate, toDateTime, trimStartOfStreamHelper, truncTo, uuid, wait, xxhash, xxhash32, xxhash64, xxhashAsStr };
|
package/dist/index.d.ts
CHANGED
|
@@ -1542,6 +1542,7 @@ interface ParseObjectArgumentOptions {
|
|
|
1542
1542
|
* ```
|
|
1543
1543
|
*/
|
|
1544
1544
|
declare function parseObjectArguments(argsStr: string, scope?: Record<string, any>, options?: ParseObjectArgumentOptions): Promise<any>;
|
|
1545
|
+
declare function simplifyObjectArguments(args: any): any;
|
|
1545
1546
|
declare function parseObjectArgumentInfos(args: ArgInfo[], scope?: Record<string, any>, options?: ParseObjectArgumentOptions): Promise<any>;
|
|
1546
1547
|
declare function ChoiceArgProcessor(argInfo: ArgInfo, _ix: number, scope?: Record<string, any>, options?: ParseObjectArgumentOptions): string | undefined;
|
|
1547
1548
|
declare function TemplateArgProcessor([isNamedArg, arg]: ArgInfo, ix: number, scope?: Record<string, any>, options?: ParseObjectArgumentOptions): Promise<string | undefined>;
|
|
@@ -1571,4 +1572,4 @@ declare function parseCommand(commandStr: string, scope?: Record<string, any>, o
|
|
|
1571
1572
|
|
|
1572
1573
|
declare function memoize<F extends (...args: any[]) => any>(fn: any, options?: Options<F>): F & _memoize.Memoized<F>;
|
|
1573
1574
|
|
|
1574
|
-
export { AIArgProcessor, type AIChatAssistantMessageParam, type AIChatContentPart, type AIChatContentPartImage, type AIChatContentPartText, type AIChatMessageParam, type AIChatMessageParamBase, type AIChatMessageToolCall, type AIChatRole, AIChatRoles, type AIChatSystemMessageParam, type AIChatToolMessageParam, type AIChatUserMessageParam, type AIChoiceConfig, type AIMessageType, AIMessageTypes, AIModelNameRules, type AIResult, AIStream, type AIStreamParser, type AIStreamParserOptions, type AITextGenerationFinishReason, AITextGenerationFinishReasons, AsyncFeatures, type AsyncTaskId, BaseError, CancelableAbility, type CancelableAbilityOptions, ChoiceArgProcessor, CommonError, DefaultAsyncSemaphoreCapacity, type DotenvExpandOptions, type DotenvExpandOutput, type DotenvParseInput, type DotenvParseOutput, type DotenvPopulateInput, EventBusName, type EventErrorListenerFn, type EventListenerFn, EventName, FStringPromptTemplate, type FStringPromptTemplateNode, FewShotPromptTemplate, type FewShotPromptTemplateOptions, FilenameReservedRegex, GolangPromptTemplate, builtins as HFBuiltins, EnvironmentEx as HFEnvironment, Interpreter as HFInterpreter, Template as HFTemplate, HfPromptTemplate, IntSet, type JsonFilter, type ParseObjectArgumentOptions, PromptExampleSelector, type PromptExampleSelectorOptions, type PromptExamples, PromptTemplate, type PromptTemplateOptions, type PromptTemplateType, PromptTemplateTypes, type PromptType, PromptTypes, RStreamErrCode, RateLimit, ReadableStreamError, ResponseRStreamErrCode, type SanitizeFilenameOptions, Semaphore, type StreamCallbacksAndOptions, TaskAbortController, type TaskAbortControllers, type TaskPromise, TemplateArgProcessor, ToolFunc, WindowsReservedNameRegex, XXHashAlgorithm, backendEventable, base32768, countRegexMatches, createCallbacksTransformer, createEmptyReadableStream, createEndWithRepetitionDetector, createEventStreamTransformer, createHfValueFunc, dateToText, defaultTemplateFormat, expandEnv, expandObjEnv, extNameLevel, fileIsExists, filenameReservedRegex, filterValidFnScope, getAllEnumKeys, getConfigFileNames, getConfigs, getKeysPath, getMultiLevelExtname, getRealFilepath, getResponseErrorReadableStream, parse as hfParse, tokenize as hfTokenize, interpolateEnv, interpolateFString, interpolateGolangTemplate, isModelNameMatched, isValidFilename, isValidFilepath, isWebStream, jsonFilterToWhere, jsonToMarkdownStr, loadFileFromPaths, loadTextFromPaths, makeToolFuncCancelable, matchUrlProtocol, memoize, messagesToText, paramsSizeToScaleStr, parseCommand, parseFString, parseJsJson, parseObjectArgInfo, parseObjectArgumentInfos, parseObjectArguments, parseObjectArgumentsAsArgInfos, parseYaml, quoteStr, reControlCharsRegex, readFilenamesRecursiveSync, readableFromAsyncIterable, registerYamlTag, sanitizeFilename, sanitizeFilepath, saveConfigFile, scaleStrToParamsSize, sortedValues, splitSentence, textToDate, toDateTime, trimStartOfStreamHelper, truncTo, uuid, wait, xxhash, xxhash32, xxhash64, xxhashAsStr };
|
|
1575
|
+
export { AIArgProcessor, type AIChatAssistantMessageParam, type AIChatContentPart, type AIChatContentPartImage, type AIChatContentPartText, type AIChatMessageParam, type AIChatMessageParamBase, type AIChatMessageToolCall, type AIChatRole, AIChatRoles, type AIChatSystemMessageParam, type AIChatToolMessageParam, type AIChatUserMessageParam, type AIChoiceConfig, type AIMessageType, AIMessageTypes, AIModelNameRules, type AIResult, AIStream, type AIStreamParser, type AIStreamParserOptions, type AITextGenerationFinishReason, AITextGenerationFinishReasons, AsyncFeatures, type AsyncTaskId, BaseError, CancelableAbility, type CancelableAbilityOptions, ChoiceArgProcessor, CommonError, DefaultAsyncSemaphoreCapacity, type DotenvExpandOptions, type DotenvExpandOutput, type DotenvParseInput, type DotenvParseOutput, type DotenvPopulateInput, EventBusName, type EventErrorListenerFn, type EventListenerFn, EventName, FStringPromptTemplate, type FStringPromptTemplateNode, FewShotPromptTemplate, type FewShotPromptTemplateOptions, FilenameReservedRegex, GolangPromptTemplate, builtins as HFBuiltins, EnvironmentEx as HFEnvironment, Interpreter as HFInterpreter, Template as HFTemplate, HfPromptTemplate, IntSet, type JsonFilter, type ParseObjectArgumentOptions, PromptExampleSelector, type PromptExampleSelectorOptions, type PromptExamples, PromptTemplate, type PromptTemplateOptions, type PromptTemplateType, PromptTemplateTypes, type PromptType, PromptTypes, RStreamErrCode, RateLimit, ReadableStreamError, ResponseRStreamErrCode, type SanitizeFilenameOptions, Semaphore, type StreamCallbacksAndOptions, TaskAbortController, type TaskAbortControllers, type TaskPromise, TemplateArgProcessor, ToolFunc, WindowsReservedNameRegex, XXHashAlgorithm, backendEventable, base32768, countRegexMatches, createCallbacksTransformer, createEmptyReadableStream, createEndWithRepetitionDetector, createEventStreamTransformer, createHfValueFunc, dateToText, defaultTemplateFormat, expandEnv, expandObjEnv, extNameLevel, fileIsExists, filenameReservedRegex, filterValidFnScope, getAllEnumKeys, getConfigFileNames, getConfigs, getKeysPath, getMultiLevelExtname, getRealFilepath, getResponseErrorReadableStream, parse as hfParse, tokenize as hfTokenize, interpolateEnv, interpolateFString, interpolateGolangTemplate, isModelNameMatched, isValidFilename, isValidFilepath, isWebStream, jsonFilterToWhere, jsonToMarkdownStr, loadFileFromPaths, loadTextFromPaths, makeToolFuncCancelable, matchUrlProtocol, memoize, messagesToText, paramsSizeToScaleStr, parseCommand, parseFString, parseJsJson, parseObjectArgInfo, parseObjectArgumentInfos, parseObjectArguments, parseObjectArgumentsAsArgInfos, parseYaml, quoteStr, reControlCharsRegex, readFilenamesRecursiveSync, readableFromAsyncIterable, registerYamlTag, sanitizeFilename, sanitizeFilepath, saveConfigFile, scaleStrToParamsSize, simplifyObjectArguments, sortedValues, splitSentence, textToDate, toDateTime, trimStartOfStreamHelper, truncTo, uuid, wait, xxhash, xxhash32, xxhash64, xxhashAsStr };
|