@koishijs/core
Advanced tools
Comparing version 4.7.5 to 4.7.6
@@ -1,7 +0,7 @@ | ||
var Me=Object.defineProperty;var f=(m,e)=>Me(m,"name",{value:e,configurable:!0});var G=(m,e)=>()=>(e||m((e={exports:{}}).exports,e),e.exports);var fe=G((yt,Be)=>{Be.exports={general:{name:"中文",paren:"({0})",quote:"“{0}”",comma:",",and:"和",or:"或",day:"天",hour:"小时",minute:"分钟",second:"秒"},internal:{"low-authority":"权限不足。","insufficient-arguments":"缺少参数,输入帮助以查看用法。","redunant-arguments":"存在多余参数,输入帮助以查看用法。","invalid-argument":"参数 {0} 输入无效,{1}","unknown-option":"存在未知选项 {0},输入帮助以查看用法。","invalid-option":"选项 {0} 输入无效,{1}","check-syntax":"输入帮助以查看用法。","invalid-number":"请提供一个数字。","invalid-integer":"请提供一个整数。","invalid-posint":"请提供一个正整数。","invalid-natural":"请提供一个非负整数。","invalid-date":"请输入合法的时间。","invalid-user":"请指定正确的用户。","invalid-channel":"请指定正确的频道。"}}});var ge=G((vt,Re)=>{Re.exports={general:{name:"English",paren:" ({0}) ",quote:'"{0}"',comma:", ",and:"and",or:"or",day:"day",hour:"hour",minute:"minute",second:"second"},internal:{"low-authority":"Low authority.","insufficient-arguments":"Insufficient arguments, type help to see usage.","redunant-arguments":"Redunant arguments, type help to see usage.","invalid-argument":"Invalid argument {0}, {1}","unknown-option":"Unknown option {0}, type help to see usage.","invalid-option":"Invalid option {0}, {1}","check-syntax":"Type help to see usage.","invalid-number":"Expect a number.","invalid-integer":"Expect an integer.","invalid-posint":"Expect a positive integer.","invalid-natural":"Expect a non-negative integer.","invalid-date":"Expect a valid date.","invalid-user":"Expect a valid user.","invalid-channel":"Expect a valid channel."}}});var xe=G((Ct,qe)=>{qe.exports={general:{name:"日本語",paren:"({0})",quote:"「{0}」",comma:"、",and:"と",or:"や",day:"日",hour:"時間",minute:"分",second:"秒"},internal:{"low-authority":"実行できる権限が付与されていません","insufficient-arguments":"パラメータが不足しています、「help」を送信して使い方を確認してください。","redunant-arguments":"パラメータ数が多すぎます、「help」を送信して使い方を確認してください。","invalid-argument":"無効なパラメータ「{0}」、{1}","unknown-option":"未知なオプション「{0}」、「help」を送信して使い方を確認してください。","invalid-option":"無効なオプション「{0}」、{1}","check-syntax":"「help」を送信して使い方を検索してください。","invalid-number":"数字を指定してください。","invalid-integer":"整数を指定してください。","invalid-posint":"正の整数を指定してください。","invalid-natural":"自然数を指定してください。","invalid-date":"日付を指定してください。","invalid-user":"ユーザー名を指定してください。","invalid-channel":"チャンネル名を指定してください。"}}});var be=G((wt,Le)=>{Le.exports={general:{name:"francais",paren:" ({0}) ",quote:'"{0}"',comma:", ",and:"et",or:"ou",day:"jour",hour:"heure",minute:"minute",second:"seconde"},internal:{"low-authority":"Droits insuffisants.","insufficient-arguments":`Arguments insuffisants, tapez "help" pour afficher l'aide`,"redunant-arguments":`Arguments redondants, tapez "help" pour afficher l'aide`,"invalid-argument":"Arguments {0} invalides, {1}","unknown-option":`Option {0} inconnue, tapez "help" pour afficher l'aide`,"invalid-option":"Option {0} invalide, {1}","check-syntax":`Tapez "help" pour afficher l'aide`,"invalid-number":"Entrez un nombre.","invalid-integer":"Entrez un entier.","invalid-posint":"Entrez un entier positif.","invalid-natural":"Entrez un entier non négatif.","invalid-date":"Entrez une date valide.","invalid-user":"Entrez un nom d'utilisateur valide.","invalid-channel":"Entrez un nom de canal valide."}}});var ye=G((kt,Ge)=>{Ge.exports={general:{name:"中文",paren:"({0})",quote:"「{0}」",comma:",",and:"和",or:"或",day:"天",hour:"小時",minute:"分鐘",second:"秒"},internal:{"low-authority":"權限不足。","insufficient-arguments":"參數個數不足,輸入「help」檢視用法。","redunant-arguments":"參數個數冗餘,輸入「help」檢視用法。","invalid-argument":"參數 {0} 無效,{1}","unknown-option":"存在未知選項 {0},輸入「help」檢視用法。","invalid-option":"選項 {0} 無效,{1}","check-syntax":"輸入「help」檢視用法。","invalid-number":"請輸入有效數字。","invalid-integer":"請輸入有效整數。","invalid-posint":"請輸入有效正整數。","invalid-natural":"請輸入有效非負整數。","invalid-date":"請輸入有效時間。","invalid-user":"請指定有效用戶。","invalid-channel":"請指定有效頻道。"}}});var Ue=G((jn,xt)=>{xt.exports={name:"@koishijs/core",description:"Core Features for Koishi",version:"4.7.5",main:"lib/node.js",module:"lib/browser.js",typings:"lib/index.d.ts",engines:{node:">=12.0.0"},files:["lib"],author:"Shigma <shigma10826@gmail.com>",license:"MIT",repository:{type:"git",url:"git+https://github.com/koishijs/koishi.git",directory:"packages/core"},bugs:{url:"https://github.com/koishijs/koishi/issues"},homepage:"https://koishi.js.org",keywords:["bot","chatbot","koishi"],devDependencies:{"@koishijs/plugin-database-memory":"^1.4.0","@koishijs/plugin-mock":"^1.0.6",chai:"^4.3.6","chai-as-promised":"^7.1.1","chai-shape":"^1.0.0"},dependencies:{"@koishijs/utils":"^5.4.5",cordis:"^1.5.5","fastest-levenshtein":"^1.0.12",minato:"^1.2.0"}}});import{defineProperty as Z,Schema as S,Time as he}from"@koishijs/utils";import{App as B}from"cordis";export*from"@koishijs/utils";export*from"cordis";export*from"minato";import{isNullable as ve,Logger as Ne,Random as ze,Time as ee}from"@koishijs/utils";import{Context as Ce}from"cordis";var we=new Ne("i18n"),ke=Symbol("template"),te=class{constructor(e){this._data={};this._formatters={};this._presets={};this.define("",{"":""}),this.define("zh",fe()),this.define("en",ge()),this.define("ja",xe()),this.define("fr",be()),this.define("zh-tw",ye()),this.registerBuiltins()}set(e,t,n){if(t.includes("@")||typeof n=="string"){let i=this._data[e],[r,l]=t.slice(0,-1).split("@");l&&(n[ke]=l),!ve(i[r])&&!e.startsWith("$")&&we.warn("override",e,r),i[r]=n,this[Ce.current]?.on("dispose",()=>{delete i[r]})}else for(let i in n)this.set(e,t+i+".",n[i])}define(e,...t){this._data[e]||={},typeof t[0]=="string"?this.set(e,t[0]+".",t[1]):this.set(e,"",t[0])}formatter(e,t){this._formatters[e]=t}preset(e,t){this._presets[e]=t}render(e,t,n){if(e!==void 0){if(typeof e!="string"){let i=e[ke],r=this._presets[i];if(!r)throw new Error(`Preset "${i}" not found`);return r(e,t,n)}return e.replace(/\{(.+?)\}/g,(i,r)=>{let[l,...c]=r.split("|"),o=l.trim().split("."),d=t;for(let h of o)if(d=d[h],ve(d))return"";for(let h of c){let x=h.trim().match(/(\w+)(?:\((.+)\))?/),y=this._formatters[x[1]];if(!y)throw new Error(`Formatter "${x[1]}" not found`);let K=x[2]?x[2].split(",").map(C=>C.trim()):[];d=y(d,K,n)}return d.toString()})}}text(e,t,n){let i=new Set;for(let r of e)!r||i.add(r);for(let r in this._data)r.startsWith("$")||i.add(r);for(let r of t)for(let l of i)for(let c of["$"+l,l]){let o=this._data[c]?.[r];if(o!==void 0)return this.render(o,n,l)}return we.warn("missing",t[0]),t[0]}registerBuiltins(){let e=["day","hour","minute","second"];this.formatter("time",(t,n,i)=>{for(let r=0;r<3;r++){let l=ee[e[r]],c=ee[e[r+1]];if(t>=l-c/2){t+=c/2;let o=Math.floor(t/l)+" "+this.text([i],["general."+e[r]],{});return t%l>c&&(o+=` ${Math.floor(t%l/c)} `+this.text([i],["general."+e[r+1]],{})),o}}return Math.round(t/ee.second)+" "+this.text([i],["general.second"],{})}),this.preset("plural",(t,n,i)=>{let r=n.length in t?n.length:t.length-1;return this.render(t[r],n,i)}),this.preset("random",(t,n,i)=>this.render(ze.pick(t),n,i)),this.preset("list",(t,n,i)=>{let r=Object.entries(n).map(([l,c])=>this.render(t.item,{key:l,value:c},i));return r.unshift(this.render(t.header,n,i)),r.push(this.render(t.footer,n,i)),r.join(` | ||
`).trim()})}};f(te,"I18n");Ce.service("i18n",{constructor:te});import{Database as _e}from"minato";import{Context as ne}from"cordis";var V;(function(t){let m;(function(i){i[i.ignore=1]="ignore"})(m=t.Flag||(t.Flag={})),t.fields=[]})(V||(V={}));var N;(function(t){let m;(function(r){r[r.ignore=1]="ignore",r[r.silent=4]="silent"})(m=t.Flag||(t.Flag={})),t.fields=[]})(N||(N={}));var X=class extends _e{constructor(e){super();this.ctx=e;this.extend("user",{id:"string(63)",name:{type:"string",length:63},flag:"unsigned(20)",authority:"unsigned(4)",locale:"string(63)"},{autoInc:!0}),this.extend("channel",{id:"string(63)",platform:"string(63)",flag:"unsigned(20)",assignee:"string(63)",guildId:"string(63)",locale:"string(63)"},{primary:["id","platform"]})}get caller(){return this[ne.current]||this.ctx}async getUser(e,t,n){let i=await this.get("user",{[e]:t},n);return Array.isArray(t)?i:(i[0]&&Object.assign(i[0],{[e]:t}),i[0])}setUser(e,t,n){return this.set("user",{[e]:t},n)}createUser(e,t,n){return this.create("user",{[e]:t,...n})}async getChannel(e,t,n){let i=await this.get("channel",{platform:e,id:t},n);return Array.isArray(t)?i:(i[0]&&Object.assign(i[0],{platform:e,id:t}),i[0])}getSelfIds(e,t){if(e)return t||=this.ctx.bots.filter(i=>i.platform===e).map(i=>i.selfId),{[e]:t};let n={};for(let i of this.ctx.bots)(n[i.platform]||=[]).push(i.selfId);return n}async getAssignedChannels(e,t=this.getSelfIds()){return this.get("channel",{$or:Object.entries(t).map(([n,i])=>({platform:n,assignee:i}))},e)}setChannel(e,t,n){return this.set("channel",{platform:e,id:t},n)}createChannel(e,t,n){return this.create("channel",{platform:e,id:t,...n})}};f(X,"DatabaseService");X.prototype.extend=f(function(e,t,n){_e.prototype.extend.call(this,e,t,{...n,driver:this.caller.mapping.database}),this.ctx.emit("model",e)},"extend");ne.service("database");ne.service("model",{constructor:X});var Pt=f((m,e,t)=>({name:m.name,reusable:!0,Config:e,apply(n,i){t?.(n,i);let r=new m(n.model,i),l=n.state.uid;n.on("ready",async()=>{await r.start(),n.model.drivers[l]=r;let c=Object.create(n.model);n.database=c}),n.on("dispose",async()=>{n.database=null,delete n.model.drivers[l],await r.stop()})}}),"defineDriver");import{Logger as We,remove as He}from"@koishijs/utils";import{Context as Se}from"cordis";function R(m,e,...t){return m.intersect(n=>t.length?t.includes(n[e]):!!n[e])}f(R,"property");var ie=class{constructor(e){this.app=e;e.filter=()=>!0,e.on("internal/warning",(t,...n)=>{this.logger("app").warn(t,...n)}),e.on("internal/runtime",t=>{!t.uid||(t.context.filter=n=>t.children.some(i=>i.context.filter(n)))})}get caller(){return this[Se.current]||this.app}any(){return this.caller.extend({filter:()=>!0})}never(){return this.caller.extend({filter:()=>!1})}union(e){let t=this.caller,n=typeof e=="function"?e:e.filter;return this.caller.extend({filter:i=>t.filter(i)||n(i)})}intersect(e){let t=this.caller,n=typeof e=="function"?e:e.filter;return this.caller.extend({filter:i=>t.filter(i)&&n(i)})}exclude(e){let t=this.caller,n=typeof e=="function"?e:e.filter;return this.caller.extend({filter:i=>t.filter(i)&&!n(i)})}logger(e){return new We(e)}user(...e){return R(this.caller,"userId",...e)}self(...e){return R(this.caller,"selfId",...e)}guild(...e){return R(this.caller,"guildId",...e)}channel(...e){return R(this.caller,"channelId",...e)}platform(...e){return R(this.caller,"platform",...e)}private(...e){return R(this.caller.exclude(R(this.caller,"guildId")),"userId",...e)}async waterfall(...e){let t=typeof e[0]=="object"?e.shift():null,n=e.shift();for(let i of this.app.lifecycle.getHooks(n,t)){let r=await i.apply(t,e);e[0]=r}return e[0]}chain(...e){let t=typeof e[0]=="object"?e.shift():null,n=e.shift();for(let i of this.app.lifecycle.getHooks(n,t)){let r=i.apply(t,e);e[0]=r}return e[0]}before(e,t,n=!1){let i=e.split("/");return i[i.length-1]="before-"+i[i.length-1],this.caller.on(i.join("/"),t,!n)}createTimerDispose(e){let t=f(()=>{if(clearTimeout(e),!!this.caller.state)return He(this.caller.state.disposables,t)},"dispose");return this.caller.state.disposables.push(t),t}setTimeout(e,t,...n){let i=this.createTimerDispose(setTimeout(()=>{i(),e()},t,...n));return i}setInterval(e,t,...n){return this.createTimerDispose(setInterval(e,t,...n))}async broadcast(...e){let t;Array.isArray(e[0])&&(t=e.shift());let[n,i]=e;if(!n)return[];let r=await this.caller.database.getAssignedChannels(["id","assignee","flag","platform","guildId"]),l={};for(let{id:c,assignee:o,flag:d,platform:h,guildId:x}of r)t&&!t.includes(`${h}:${c}`)||!i&&d&N.Flag.silent||((l[h]||={})[o]||=[]).push([c,x]);return(await Promise.all(Object.entries(l).flatMap(([c,o])=>this.caller.bots.map(d=>d.platform!==c?Promise.resolve([]):d.broadcast(o[d.selfId]||[],n))))).flat(1)}};f(ie,"SelectorService");Se.service("$selector",{constructor:ie,methods:["any","never","union","intersect","exclude","select","user","self","guild","channel","platform","private","chain","waterfall","before","logger","setTimeout","setInterval","broadcast"]});import{coerce as pt,defineProperty as mt,escapeRegExp as ht,makeArray as ft}from"@koishijs/utils";import{Context as Ke}from"cordis";import{Logger as lt,paramCase as ct,remove as dt,Schema as P}from"@koishijs/utils";import{Context as Pe}from"cordis";import{Logger as Oe,makeArray as st,Random as ot,sleep as at}from"@koishijs/utils";import{Context as $e}from"cordis";import{coerce as Ve,Logger as Xe,remove as q,Schema as H}from"@koishijs/utils";import{camelCase as Ae,escapeRegExp as Te,paramCase as Ee,segment as re,Time as Qe}from"@koishijs/utils";var se=`"'“‘`,oe=`"'”’`,U;(function(v){let m={};function e(s,a,u){m[s]={terminator:a,parse:u}}v.interpolate=e,f(e,"interpolate"),e("$(",")");class t{constructor(){this.bracs=Object.create(m)}interpolate(a,u,p){this.bracs[a]={terminator:u,parse:p}}parseToken(a,u="$"){let p={inters:[]},g=se.indexOf(a[0]),k=oe[g],A="";k&&(a=a.slice(1),u=`${k}(?=${u})|$`),u+=`|${Object.keys({...this.bracs,...m}).map(Te).join("|")}`;let b=new RegExp(u);for(;;){let w=b.exec(a);if(A+=a.slice(0,w.index),w[0]in this.bracs){a=a.slice(w.index+w[0].length).trimStart();let{parse:$,terminator:O}=this.bracs[w[0]],E=$?.(a)||this.parse(a,O);a=E.rest,p.inters.push({...E,pos:A.length,initiator:w[0]})}else{let $=w[0]===k,O=a.slice(w.index+ +$);return p.rest=O.trimStart(),p.quoted=$,p.terminator=w[0],$?p.terminator+=O.slice(0,-p.rest.length):k&&(A=se[g]+A,p.inters.forEach(E=>E.pos+=1)),p.content=A,k==="'"&&v.revert(p),p}}}parse(a,u=""){let p=[],g=a,k="",A=`\\s+|[${Te(u)}]|$`;for(;g&&!(u&&g.startsWith(u));){let b=this.parseToken(g,A);p.push(b),g=b.rest,k=b.terminator,delete b.rest}return g.startsWith(u)&&(g=g.slice(1)),a=a.slice(0,-(g+k).length),{tokens:p,rest:g,source:a}}stringify(a){let u=a.tokens.reduce((p,g)=>(g.quoted&&(p+=se[oe.indexOf(g.terminator[0])]||""),p+g.content+g.terminator),"");return a.rest&&!oe.includes(u[u.length-1])||a.initiator?u.slice(0,-1):u}}f(t,"Tokenizer"),v.Tokenizer=t;let n=new t;function i(s,a=""){return n.parse(s,a)}v.parse=i,f(i,"parse");function r(s){return n.stringify(s)}v.stringify=r,f(r,"stringify");function l(s){for(;s.inters.length;){let{pos:a,source:u,initiator:p}=s.inters.pop();s.content=s.content.slice(0,a)+p+u+m[p].terminator+s.content.slice(a)}}v.revert=l,f(l,"revert");function c(s){return typeof s=="string"?d[s]||{}:{}}f(c,"resolveConfig");function o(s){return typeof s=="function"?s:s instanceof RegExp?a=>{if(s.test(a))return a;throw new Error}:Array.isArray(s)?a=>{if(s.includes(a))return a;throw new Error}:d[s]?.transform}f(o,"resolveType");let d={};function h(s,a,u){d[s]={...u,transform:a}}v.createDomain=h,f(h,"createDomain"),h("rawtext",s=>s),h("string",s=>s),h("text",s=>s,{greedy:!0}),h("rawtext",s=>re.unescape(s),{greedy:!0}),h("boolean",()=>!0),h("number",(s,a)=>{let u=+s;if(Number.isFinite(u))return u;throw new Error("internal.invalid-number")}),h("integer",(s,a)=>{let u=+s;if(u*0==0&&Math.floor(u)===u)return u;throw new Error("internal.invalid-integer")}),h("posint",(s,a)=>{let u=+s;if(u*0==0&&Math.floor(u)===u&&u>0)return u;throw new Error("internal.invalid-posint")}),h("natural",(s,a)=>{let u=+s;if(u*0==0&&Math.floor(u)===u&&u>=0)return u;throw new Error("internal.invalid-natural")}),h("date",(s,a)=>{let u=Qe.parseDate(s);if(+u)return u;throw new Error("internal.invalid-date")}),h("user",(s,a)=>{if(s.startsWith("@"))return s=s.slice(1),s.includes(":")?s:`${a.platform}:${s}`;let u=re.from(s);if(u&&u.type==="at")return`${a.platform}:${u.data.id}`;throw new Error("internal.invalid-user")}),h("channel",(s,a)=>{if(s.startsWith("#"))return s=s.slice(1),s.includes(":")?s:`${a.platform}:${s}`;let u=re.from(s);if(u&&u.type==="sharp")return`${a.platform}:${u.data.id}`;throw new Error("internal.invalid-channel")});let x=/<[^>]+>|\[[^\]]+\]/g;function y(s){let a,u=[];for(;a=x.exec(s);){let p=a[0].slice(1,-1),g=!1;p.startsWith("...")&&(p=p.slice(3),g=!0);let[k,A]=p.split(":"),b=A?A.trim():void 0;u.push({name:k,variadic:g,type:b,required:a[0][0]==="<"})}return u.stripped=s.replace(/:[\w-]+[>\]]/g,p=>p.slice(-1)).trimEnd(),u}f(y,"parseDecl");function K(s,a,u,p,g={}){let{name:k,type:A,fallback:b}=g,w=s===""&&!a;if(w&&b!==void 0)return b;let $=o(A);if($)try{return $(s,p.session)}catch(E){if(!p.session)p.error=`internal.invalid-${u}`;else{let I=p.session.text(E.message||"internal.check-syntax");p.error=p.session.text(`internal.invalid-${u}`,[k,I])}return}if(w)return!0;if(a)return s;let O=+s;return O*0==0?O:s}v.parseValue=K,f(K,"parseValue");class C{constructor(a,u,p){this.name=a;this.ctx=p;this._options={};this._namedOptions={};this._symbolicOptions={};if(!a)throw new Error("expect a command name");let g=this._arguments=y(u);this.declaration=g.stripped}_createOption(a,u,p){let g=Ee(a),k=u.replace(/(?<=^|\s)[\w\x80-\uffff].*/,""),A=u.slice(k.length),b=k.replace(/(?<=^|\s)(<[^<]+>|\[[^[]+\]).*/,""),w=k.slice(b.length);b=b.trim()||"--"+g;let $=[],O=[];for(let T of b.trim().split(",")){T=T.trimStart();let W=T.replace(/^-+/,"");!W||!T.startsWith("-")?O.push(T):$.push(W)}!("value"in p)&&!$.includes(g)&&(b+=", --"+g);let E=y(w);E.stripped&&(b+=" "+E.stripped);let I=this._options[a]||={...F.defaultOptionConfig,...E[0],...p,name:a,values:{},valuesSyntax:{},syntax:b},_=`commands.${this.name}.options.${a}`,D=typeof I.fallback;"value"in p?(_+="."+p.value,I.valuesSyntax[p.value]=b,$.forEach(T=>I.values[T]=p.value)):w.trim()?!I.type&&(D==="string"||D==="number")&&(I.type=D):I.type="boolean",A&&this.ctx.i18n.define("",_,A),this._assignOption(I,$,this._namedOptions),this._assignOption(I,O,this._symbolicOptions),this._namedOptions[g]||(this._namedOptions[g]=I)}_assignOption(a,u,p){for(let g of u){if(g in p)throw new Error(`duplicate option name "${g}" for command "${this.name}"`);p[g]=a}}removeOption(a){if(!this._options[a])return!1;let u=this._options[a];delete this._options[a];for(let p in this._namedOptions)this._namedOptions[p]===u&&delete this._namedOptions[p];for(let p in this._symbolicOptions)this._symbolicOptions[p]===u&&delete this._symbolicOptions[p];return!0}parse(a,u,p=[],g={}){typeof a=="string"&&(a=v.parse(a,u));let k=this.name+" "+v.stringify(a);for(;!a.error&&a.tokens.length;){let A=a.tokens[0],{content:b,quoted:w}=A,$=this._arguments[p.length];if(b[0]!=="-"&&c($?.type).greedy){p.push(v.parseValue(v.stringify(a),!0,"argument",a,$));break}a.tokens.shift();let O,E,I;if(!w&&(O=this._symbolicOptions[b]))E=[Ee(O.name)];else{if(b[0]!=="-"||w){p.push(v.parseValue(b,w,"argument",a,$||{type:"string"}));continue}let _=0,D;for(;_<b.length&&b.charCodeAt(_)===45;++_);if(b.slice(_,_+3)==="no-"&&!this._namedOptions[b.slice(_)]){D=b.slice(_+3),g[Ae(D)]=!1;continue}let T=_+1;for(;T<b.length&&b.charCodeAt(T)!==61;T++);D=b.slice(_,T),E=_>1?[D]:D,I=b.slice(++T),O=this._namedOptions[E[E.length-1]]}if(w=!1,!I){let{type:_}=O||{};if(c(_).greedy)I=v.stringify(a),w=!0,a.tokens=[];else if(_!=="boolean"&&a.tokens.length&&(_||a.tokens[0]?.content!=="-")){let D=a.tokens.shift();I=D.content,w=D.quoted}}for(let _=0;_<E.length;_++){let D=E[_],T=this._namedOptions[D],W=T?T.name:Ae(D);if(T&&D in T.values)g[W]=T.values[D];else{let je=_+1<E.length?"":I;g[W]=v.parseValue(je,w,"option",a,T)}if(a.error)break}}for(let{name:A,fallback:b}of Object.values(this._options))b!==void 0&&!(A in g)&&(g[A]=b);return delete a.tokens,{options:g,args:p,source:k,rest:a.rest,error:a.error||""}}stringifyArg(a){return a=""+a,a.includes(" ")?`"${a}"`:a}stringify(a,u){let p=this.name;for(let g in u){let k=u[g];k===!0?p+=` --${g}`:k===!1?p+=` --no-${g}`:p+=` --${g} ${this.stringifyArg(k)}`}for(let g of a)p+=" "+this.stringifyArg(g);return p}}f(C,"CommandBase"),v.CommandBase=C})(U||(U={}));var ae=new Xe("command"),le=class extends U.CommandBase{constructor(e,t,n){super(e,t,n);this.children=[];this.parent=null;this._aliases=[];this._examples=[];this._userFields=[["locale"]];this._channelFields=[["locale"]];this._actions=[];this._checkers=[async e=>this.ctx.serial(e.session,"command/before-execute",e)];this.config={...le.defaultConfig},this._registerAlias(e),n.$commander._commandList.push(this)}static userFields(e){return this._userFields.push(e),this}static channelFields(e){return this._channelFields.push(e),this}get displayName(){return this._aliases[0]}set displayName(e){this._registerAlias(e,!0)}_registerAlias(e,t=!1){if(e=e.toLowerCase(),this._aliases.includes(e)){t&&(q(this._aliases,e),this._aliases.unshift(e));return}else t?this._aliases.unshift(e):this._aliases.push(e);let i=this.ctx.$commander.getCommand(e);if(!i)this.ctx.$commander._commands.set(e,this);else if(i!==this)throw new Error(`duplicate command names: "${e}"`);this._disposables?.push(()=>{q(this._aliases,e),this.ctx.$commander._commands.delete(e)})}[Symbol.for("nodejs.util.inspect.custom")](){return`Command <${this.name}>`}userFields(e){return this._userFields.push(e),this}channelFields(e){return this._channelFields.push(e),this}alias(...e){if(this._disposed)return this;for(let t of e)this._registerAlias(t);return this}shortcut(e,t={}){return this._disposed?this:(t.name=e,t.command=this,this.ctx.$commander._shortcuts.push(t),this._disposables?.push(()=>q(this.ctx.$commander._shortcuts,t)),this)}subcommand(e,...t){e=this.name+(e.charCodeAt(0)===46?"":"/")+e;let n=typeof t[0]=="string"?t.shift():"",i=t[0]||{};return this._disposed&&(i.patch=!0),this.ctx.command(e,n,i)}usage(e){return this._usage=e,this}example(e){return this._examples.push(e),this}option(e,...t){let n="";typeof t[0]=="string"&&(n=t.shift());let i=t[0];return this._createOption(e,n,i||{}),this._disposables?.push(()=>this.removeOption(e)),this}match(e){let{authority:t=1/0}=e.user||{};return this.ctx.filter(e)&&this.config.authority<=t}getConfig(e,t){let n=this.config[e];return typeof n=="function"?n(t):n}check(e,t=!1){return this.before(e,t)}before(e,t=!1){return t?this._checkers.push(e):this._checkers.unshift(e),this._disposables?.push(()=>q(this._checkers,e)),this}action(e,t=!1){return t?this._actions.unshift(e):this._actions.push(e),this._disposables?.push(()=>q(this._actions,e)),this}use(e,...t){return e(this,...t)}async execute(e,t=j.compose){e.command??=this,e.args??=[],e.options??={};let{args:n,options:i,error:r}=e;if(r)return r;ae.level>=3&&ae.debug(e.source||=this.stringify(n,i));for(let d of this._checkers){let h=await d.call(this,e,...n);if(typeof h=="string")return h}if(!this._actions.length)return"";let l=0,c=this._actions.map(d=>async()=>await d.call(this,e,...n));c.push(t);let o=c.length;e.next=async d=>{if(d!==void 0&&(c.push(h=>j.compose(d,h)),c.length>j.MAX_DEPTH))throw new Error(`middleware stack exceeded ${j.MAX_DEPTH}`);return c[l++]?.(e.next)};try{let d=await e.next();if(typeof d=="string")return d}catch(d){if(l===o)throw d;let h=Ve(d);ae.warn(`${e.source||=this.stringify(n,i)} | ||
${h}`),this.ctx.emit(e.session,"command-error",e,d)}return""}dispose(){this._disposed=!0,this.ctx.emit("command-removed",this);for(let e of this.children.slice())e.dispose();this.ctx.$commander._shortcuts=this.ctx.$commander._shortcuts.filter(e=>e.command!==this),this._aliases.forEach(e=>this.ctx.$commander._commands.delete(e)),q(this.ctx.$commander._commandList,this),this.parent&&q(this.parent.children,this)}},F=le;f(F,"Command"),F.defaultConfig={authority:1,showWarning:!0},F.defaultOptionConfig={authority:0},F._userFields=[],F._channelFields=[];(function(e){e.Config=H.object({authority:H.natural().default(1),hidden:H.boolean().default(!1),checkArgCount:H.boolean().default(!1),checkUnknown:H.boolean().default(!1)})})(F||(F={}));import{defineProperty as Je,valueMap as Ye}from"@koishijs/utils";function ce(m){m.before("parse",(t,n)=>{let i=U.parse(t);return n.quote&&i.tokens.push({content:n.quote.content,quoted:!0,inters:[],terminator:""}),i}),m.before("parse",(t,n)=>{let{parsed:i,quote:r}=n;if(!(i.prefix||r))for(let l of m.$commander._shortcuts){let{name:c,fuzzy:o,command:d,prefix:h,options:x={},args:y=[]}=l;if(!(h&&!i.appel||!d.ctx.filter(n)))if(typeof c=="string"){if(!o&&t!==c||!t.startsWith(c))continue;let K=t.slice(c.length);if(o&&!i.appel&&K.match(/^\S/))continue;let C=U.parse(K.trim());return C.session=n,C=d.parse(C,"",[...y],{...x}),C.command=d,C}else{let C=function(v){return typeof v!="string"?v:(v=v.replace(/\$\$/g,"@@__PLACEHOLDER__@@"),K.forEach((s,a)=>{!a||a>9||(v=v.replace(new RegExp(`\\$${a}`,"g"),(s||"").replace(/\$/g,"@@__PLACEHOLDER__@@")))}),v.replace(/@@__PLACEHOLDER__@@/g,"$"))};f(C,"escape");let K=c.exec(t);if(!K)continue;return{command:d,args:y.map(C),options:Ye(x,C)}}}}),m.before("attach",t=>{Je(t,"argv",m.bail("before-parse",t.parsed.content,t)),t.argv.root=!0,t.argv.session=t});function e(t,n){if(!!m.$commander.getCommand("help"))return t.execute({name:"help",args:[n]})}f(e,"executeHelp"),m.before("command/execute",t=>{let{args:n,command:i,options:r,session:l}=t;if(r.help&&i._options.help)return e(l,i.name);if(i._actions.length)return;let c=n.shift()||"",o=m.$commander.getCommand(i.name+"."+c);if(o){let d=l.__redirected_commands||=[`(${i.name}${i._aliases.length!==0?"|"+i._aliases.join("|"):""})`];d.push(c);let h=new RegExp(`^${d.join("[. ]")}( |$)`);return t=U.parse(l.parsed.content.replace(h,"")),t.session=l,t=o.parse(t),l.execute({...t,command:o})}else return e(l,i.name)})}f(ce,"runtime");function de(m){m.on("command-added",e=>{e.userFields(({tokens:t,command:n,options:i={}},r)=>{if(!n)return;let{authority:l}=n.config,c=l>0;for(let{name:o,authority:d}of Object.values(n._options))o in i?d>0&&(c=!0):t&&d>0&&(c=!0);c&&r.add("authority")})}),m.before("command/execute",e=>{let{session:t,options:n,command:i}=e;if(!t.user)return;function r(l,...c){return i.config.showWarning?t.text(l,c):""}if(f(r,"sendHint"),t.user.authority&&i.getConfig("authority",t)>t.user.authority)return r("internal.low-authority");for(let l of Object.values(i._options))if(l.name in n&&l.authority>t.user.authority)return r("internal.low-authority")}),m.before("command/execute",e=>{let{args:t,options:n,command:i,session:r}=e;function l(c,...o){return i.config.showWarning?r.text(c,o):""}if(f(l,"sendHint"),i.config.checkArgCount){if((i._arguments[t.length]||{}).required)return l("internal.insufficient-arguments");let o=i._arguments[i._arguments.length-1]||{};if(t.length>i._arguments.length&&o.type!=="text"&&!o.variadic)return l("internal.redunant-arguments")}if(i.config.checkUnknown){let c=Object.keys(n).filter(o=>!i._options[o]);if(c.length)return l("internal.unknown-option",c.join(", "))}})}f(de,"validate");var Q=class{constructor(e,t={}){this.ctx=e;this.config=t;this._commandList=[];this._commands=new Map;this._shortcuts=[];e.plugin(ce),e.plugin(de)}get caller(){return this[$e.current]||this.ctx}resolve(e){if(!e)return;let t=e.split("."),n=1,i=t[0],r;for(;(r=this.getCommand(i))&&n<t.length;)i=r.name+"."+t[n++];return r}getCommand(e){return this._commands.get(e)}command(e,...t){let n=typeof t[0]=="string"?t.shift():"",i=t[0],r=e.split(" ",1)[0].toLowerCase(),l=e.slice(r.length),c=r.split(/(?=[./])/g),o,d,h=[];if(c.forEach((y,K)=>{let C=y.charCodeAt(0),v=C===46?o.name+y:C===47?y.slice(1):y,s=this.getCommand(v);if(s){if(o){if(s===o)throw new Error(`cannot set a command (${s.name}) as its own subcommand`);if(s.parent){if(s.parent!==o)throw new Error(`cannot create subcommand ${r}: ${s.parent.name}/${s.name} already exists`)}else s.parent=o,o.children.push(s)}return o=s}s=new F(v,l,this.caller),h.push(s),d||(d=s),o&&(s.parent=o,s.config.authority=o.config.authority,o.children.push(s)),o=s}),n&&this.caller.i18n.define("",`commands.${o.name}.description`,n),Object.assign(o.config,i),h.forEach(y=>this.caller.emit("command-added",y)),!i?.patch)return d&&this.caller.state.disposables.unshift(()=>d.dispose()),o;d&&d.dispose();let x=Object.create(o);return x._disposables=this.caller.state.disposables,x}};f(Q,"Commander"),Q.key="$commander";$e.service(Q.key,{constructor:Q,methods:["command"]});import{defineProperty as L,isNullable as Ze,Logger as et,makeArray as tt,observe as ue,Random as nt,segment as it}from"@koishijs/utils";import{Context as rt}from"cordis";var pe=new et("session"),J=class{constructor(e,t){Object.assign(this,t),this.platform=e.platform,L(this,"app",e.ctx.app),L(this,"bot",e),L(this,"user",null),L(this,"channel",null),L(this,"id",nt.id()),L(this,"_queuedTasks",[]),L(this,"_queuedTimeout",null)}[rt.filter](e){return e.filter(this)}get uid(){return`${this.platform}:${this.userId}`}get gid(){return`${this.platform}:${this.guildId}`}get cid(){return`${this.platform}:${this.channelId}`}get sid(){return`${this.platform}:${this.selfId}`}toJSON(){return Object.fromEntries(Object.entries(this).filter(([e])=>!e.startsWith("_")&&!e.startsWith("$")))}async _preprocess(){let e,t=this.content.trim();return(e=it.from(t,{type:"quote",caret:!0}))&&(t=t.slice(e.capture[0].length).trimStart(),this.quote=await this.bot.getMessage(e.data.channelId||this.channelId,e.data.id).catch(n=>{pe.warn(n)})),t}async preprocess(){return this._promise||=this._preprocess()}get username(){let e=this.user&&this.user.name?this.user.name:this.author?this.author.nickname||this.author.username:this.userId;return this.app.chain("appellation",e,this)}async send(e){if(!!e)return this.bot.sendMessage(this.channelId,e,this.guildId).catch(t=>(pe.warn(t),[]))}cancelQueued(e=this.app.options.delay.cancel){clearTimeout(this._queuedTimeout),this._queuedTasks=[],this._queuedTimeout=setTimeout(()=>this._next(),e)}_next(){let e=this._queuedTasks.shift();if(!e){this._queuedTimeout=null;return}this.send(e.content).then(e.resolve,e.reject),this._queuedTimeout=setTimeout(()=>this._next(),e.delay)}async sendQueued(e,t){if(!!e){if(Ze(t)){let{message:n,character:i}=this.app.options.delay;t=Math.max(n,i*e.length)}return new Promise((n,i)=>{this._queuedTasks.push({content:e,delay:t,resolve:n,reject:i}),this._queuedTimeout||this._next()})}}resolveValue(e){return typeof e=="function"?Reflect.apply(e,null,[this]):e}async getChannel(e=this.channelId,t=[]){let{app:n,platform:i,guildId:r}=this;if(!t.length)return{platform:i,id:e,guildId:r};let l=await n.database.getChannel(i,e,t);if(l)return l;let c=await this.resolveValue(n.options.autoAssign)?this.selfId:"";if(c)return n.database.createChannel(i,e,{assignee:c,guildId:r});{let o=n.model.tables.channel.create();return Object.assign(o,{platform:i,id:e,guildId:r}),o}}async _observeChannelLike(e,t=[]){let n=new Set(t),{platform:i}=this,r=`${i}:${e}`,l=this.app.$internal._channelCache.get(this.id,r);if(l){for(let o in l)n.delete(o);if(!n.size)return l}let c=await this.getChannel(e,[...n]);return l=this.app.$internal._channelCache.get(this.id,r),l?l.$merge(c):(l=ue(c,o=>this.app.database.setChannel(i,e,o),`channel ${r}`),this.app.$internal._channelCache.set(this.id,r,l)),l}async observeChannel(e=[]){let t=[this._observeChannelLike(this.channelId,e)];this.channelId!==this.guildId&&t.push(this._observeChannelLike(this.guildId,e));let[n,i=n]=await Promise.all(t);return this.guild=i,this.channel=n,n}async getUser(e=this.userId,t=[]){let{app:n,platform:i}=this;if(!t.length)return{[i]:e};let r=await n.database.getUser(i,e,t);if(r)return r;let l=await this.resolveValue(n.options.autoAuthorize);if(l)return n.database.createUser(i,e,{authority:l});{let c=n.model.tables.user.create();return Object.assign(c,{[i]:e,authority:l}),c}}async observeUser(e=[]){let t=new Set(e),{userId:n,platform:i}=this,r=this.app.$internal._userCache.get(this.id,this.uid);if(r){for(let c in r)t.delete(c);if(!t.size)return this.user=r}if(this.author?.anonymous){let c=this.app.model.tables.user.create();c[i]=n,c.authority=await this.resolveValue(this.app.options.autoAuthorize);let o=ue(c,()=>Promise.resolve());return this.user=o}let l=await this.getUser(n,[...t]);return r=this.app.$internal._userCache.get(this.id,this.uid),r?r.$merge(l):(r=ue(l,c=>this.app.database.setUser(this.platform,n,c),`user ${this.uid}`),this.app.$internal._userCache.set(this.id,this.uid,r)),this.user=r}async withScope(e,t){let n=this.scope;try{return this.scope=e,await t()}finally{this.scope=n}}text(e,t={}){let n=[this.app.options.locale];n.unshift(this.user?.locale),this.subtype==="group"&&(n.unshift(this.guild?.locale),n.unshift(this.channel?.locale));let i=tt(e).map(r=>r.startsWith(".")?this.scope?this.scope+r:(this.app.logger("i18n").warn(new Error("missing scope")),""):r);return this.app.i18n.text(n,i,t)}collect(e,t,n=new Set){let i=f(r=>{if(r.session=this,r.tokens)for(let{inters:l}of r.tokens)l.forEach(i);!this.resolve(r)||(this.app.emit(r.session,`command/before-attach-${e}`,r,n),De(r,F[`_${e}Fields`],n),De(r,r.command[`_${e}Fields`],n))},"collect");return i(t),n}inferCommand(e){if(e.command)return e.command;if(e.name)return e.command=this.app.$commander.resolve(e.name);let{parsed:t,subtype:n}=this;if(e.root&&n!=="private"&&t.prefix===null&&!t.appel||!e.tokens.length)return;let i=this.app.$commander.resolve(e.tokens[0].content);if(i)return e.tokens.shift(),e.command=i}resolve(e){if(!!this.inferCommand(e)){if(e.tokens?.every(t=>!t.inters.length)){let{options:t,args:n,error:i}=e.command.parse(e);e.options={...e.options,...t},e.args=[...e.args||[],...n],e.error=i}return e.command}}async execute(e,t){if(typeof e=="string"&&(e=U.parse(e)),e.session=this,e.tokens){for(let r of e.tokens){let{inters:l}=r,c=[];for(let o=0;o<l.length;++o)c.push(await this.execute(l[o],!0));for(let o=l.length-1;o>=0;--o){let{pos:d}=l[o];r.content=r.content.slice(0,d)+c[o]+r.content.slice(d)}r.inters=[]}if(!this.resolve(e))return""}else if(e.command||=this.app.$commander.getCommand(e.name),!e.command)return pe.warn(new Error(`cannot find command ${e.name}`)),"";let{command:n}=e;if(!n.ctx.filter(this))return"";this.app.database&&(this.subtype==="group"&&await this.observeChannel(this.collect("channel",e)),await this.observeUser(this.collect("user",e)));let i=!0;return t===!0&&(i=!1,t=void 0),this.withScope(`commands.${n.name}.messages`,async()=>{let r=await n.execute(e,t);return i?(await this.send(r),""):r})}middleware(e){let t=Ie(this);return this.app.middleware(async(n,i)=>t&&Ie(n)!==t?i():e(n,i),!0)}prompt(e=this.app.options.delay.prompt){return new Promise(t=>{let n=this.middleware(r=>{clearTimeout(i),n(),t(r.content)}),i=setTimeout(()=>{n(),t("")},e)})}};f(J,"Session");function Ie(m){return""+m.userId+m.channelId}f(Ie,"getSessionId");function De(m,e,t){for(let n of e){if(typeof n=="function"){n(m,t);continue}for(let i of n)t.add(i)}return t}f(De,"collectFields");var Fe=new Oe("bot"),M=class{constructor(e,t){this.adapter=e;this.config=t;this.id=ot.id();this.ctx=e.ctx,this.app=this.ctx.app,this.platform=t.platform||e.platform,this.logger=new Oe(e.platform),this._status="offline",this.extendModel(),e.ctx.on("ready",()=>this.start()),e.ctx.on("dispose",()=>this.stop())}extendModel(){this.platform in this.ctx.model.tables.user.fields||this.ctx.model.extend("user",{[this.platform]:{type:"string",length:63}},{unique:[this.platform]})}get status(){return this._status}set status(e){this._status=e,this.ctx.bots.includes(this)&&this.ctx.emit("bot-status-updated",this)}resolve(){this.status="online",Fe.success("logged in to %s as %c (%s)",this.platform,this.username,this.selfId)}reject(e){this.error=e,this.status="offline",Fe.error(e)}async start(){if(!this.config.disabled&&!["connect","reconnect","online"].includes(this.status)){this.status="connect";try{await this.ctx.parallel("bot-connect",this),await this.adapter.connect(this)}catch(e){this.reject(e)}}}async stop(){if(!["disconnect","offline"].includes(this.status)){this.status="disconnect";try{await this.ctx.parallel("bot-disconnect",this),await this.adapter.disconnect(this)}catch(e){this.logger.warn(e)}this.status="offline"}}get sid(){return`${this.platform}:${this.selfId}`}createSession(e){return new J(this,{...e,type:"send",selfId:this.selfId,platform:this.platform,timestamp:Date.now(),author:{userId:this.selfId,username:this.username,avatar:this.avatar,discriminator:this.discriminator,isBot:!0}})}async session(e){let t=this.createSession(e);if(!await this.ctx.serial(t,"before-send",t))return t}async getGuildMemberMap(e){let t=await this.getGuildMemberList(e);return Object.fromEntries(t.map(n=>[n.userId,n.nickname||n.username]))}async broadcast(e,t,n=this.ctx.app.options.delay.broadcast){let i=[];for(let r=0;r<e.length;r++){r&&n&&await at(n);try{let[l,c]=st(e[r]);i.push(...await this.sendMessage(l,t,c))}catch(l){this.ctx.logger("bot").warn(l)}}return i}};f(M,"Bot");(function(e){e.library={}})(M||(M={}));var z=class{constructor(e,t){this.ctx=e;this.config=t;this.bots=[];e.on("ready",()=>this.start()),e.on("dispose",()=>this.stop())}connect(e){}disconnect(e){}dispatch(e){if(!this.ctx.lifecycle.isActive)return;let t=[e.type];e.subtype&&(t.unshift(t[0]+"/"+e.subtype),e.subsubtype&&t.unshift(t[0]+"/"+e.subsubtype));for(let n of t)this.ctx.emit(e,ct(n),e)}};f(z,"Adapter");var ut=new lt("app");(function(l){l.redirect=Symbol("koishi.adapter.redirect"),l.library={},l.configMap={};function n(c,o){return o?`${c}.${o}`:c}l.join=n,f(n,"join");function i(c,o,...d){let h=c+"-adapter";c=c.toLowerCase(),M.library[c]=o;let x;if(typeof d[0]=="function")l.library[c]=d[0],x=d[0].schema;else{let v=function(s){if(s.type==="union"||s.type==="intersect")s.list.forEach(v);else if(s.type==="object")for(let a in s.dict)C.dict[a]=new P(s.dict[a]),C.dict[a].meta={...s.dict[a].meta,required:!1};else throw new Error("cannot flatten bot schema")};f(v,"flatten"),l.library[c]={[l.redirect]:d[1]},x=l.library[c].schema=P.union([]).description("机器人要使用的协议。");let C=P.object({protocol:P.string()});for(let s in d[0])l.library[n(c,s)]=d[0][s],v(d[0][s].schema),x.list.push(P.intersect([P.object({protocol:P.const(s).required()}),d[0][s].schema]).description(s));x.list.push(P.transform(C,s=>{if(s.protocol)throw new Error(`unknown protocol "${s.protocol}"`);return s.protocol=d[1](s),ut.debug("infer type as %s",s.protocol),s}))}let y=P.intersect([o.schema,P.union([P.object({bots:P.array(x).required().hidden()}),P.transform(x,C=>({bots:[C]}))])]);function K(C,v={}){C.emit("adapter",c),l.configMap[c]=v;for(let s of v.bots)C.bots.create(c,s,o)}return f(K,"apply"),{name:h,Config:y,apply:K}}l.define=i,f(i,"define");class r extends Array{constructor(o){super();this.ctx=o;this.adapters={}}get caller(){return this[Pe.current]||this.ctx}get(o){return this.find(d=>d.sid===o)}create(o,d,h){h||=M.library[o];let x=this.resolve(o,d),y=new h(x,d);return x.bots.push(y),this.push(y),this.caller.emit("bot-added",y),this.caller.on("dispose",()=>{this.remove(y.id)}),y}remove(o){let d=this.findIndex(y=>y.id===o);if(d<0)return;let[h]=this.splice(d,1),x=dt(h.adapter.bots,h);return this.caller.emit("bot-removed",h),x}resolve(o,d){let h=n(o,d.protocol);if(this.adapters[h])return this.adapters[h];let x=l.library[h];if(!x)throw new Error(`unsupported protocol "${h}"`);if(x[l.redirect])return d.protocol=x[l.redirect](d),this.resolve(o,d);let y=new x(this.caller,l.configMap[o]);return y.platform=o,this.caller.on("dispose",()=>{delete this.adapters[h]}),this.adapters[h]=y}}f(r,"BotList"),l.BotList=r})(z||(z={}));Pe.service("bots",{constructor:z.BotList});function gt(m,e="",t=""){return m.length?new RegExp(`^${e}(${m.map(ht).join("|")})${t}`):/$^/}f(gt,"createLeadingRE");var j;(function(t){t.MAX_DEPTH=64;async function e(n,i){return typeof n=="function"?n(i):n}t.compose=e,f(e,"compose")})(j||(j={}));var me=class{constructor(e,t){this.ctx=e;this.config=t;this._hooks=[];this._sessions=Object.create(null);this._userCache=new Y;this._channelCache=new Y;this.prepare(),this.middleware(this._process.bind(this)),e.on("message",this._handleMessage.bind(this)),e.before("attach-user",(n,i)=>{n.collect("user",n.argv,i)}),e.before("attach-channel",(n,i)=>{n.collect("channel",n.argv,i)}),this.middleware((n,i)=>n.resolve(n.argv)?n.execute(n.argv,i):i())}get caller(){return this[Ke.current]||this.ctx}middleware(e,t=!1){return this.caller.lifecycle.register("middleware",this._hooks,e,t)}prepare(){this._nameRE=gt(ft(this.config.nickname),"@?","([,,]\\s*|\\s+)")}_resolvePrefixes(e){let t=e.resolveValue(this.config.prefix);return Array.isArray(t)?t:[t||""]}async _process(e,t){let n,i=!1,r=!1,l=null,c=/^\[CQ:(\w+)((,\w+=[^,\]]*)*)\]/,o=await e.preprocess();e.subtype!=="private"&&(n=o.match(c))&&n[1]==="at"&&n[2].includes("id="+e.selfId)?(i=r=!0,o=o.slice(n[0].length).trimStart()):(n=o.match(this._nameRE))&&(r=!0,o=o.slice(n[0].length));for(let d of this._resolvePrefixes(e))!o.startsWith(d)||(l=d,o=o.slice(d.length));if(mt(e,"parsed",{content:o,appel:r,prefix:l}),this.ctx.emit(e,"before-attach",e),this.ctx.database){if(e.subtype==="group"){let x=new Set(["flag","assignee","guildId","locale"]);this.ctx.emit("before-attach-channel",e,x);let y=await e.observeChannel(x);if(y.guildId=e.guildId,await this.ctx.serial(e,"attach-channel",e)||y.flag&N.Flag.ignore||y.assignee!==e.selfId&&!i)return}let d=new Set(["flag","authority","locale"]);this.ctx.emit("before-attach-user",e,d);let h=await e.observeUser(d);if(await this.ctx.serial(e,"attach-user",e)||h.flag&V.Flag.ignore)return}return this.ctx.emit(e,"attach",e),t()}async _handleMessage(e){if(e.selfId===e.userId)return;this._sessions[e.id]=e;let t=this._hooks.filter(([o])=>o.filter(e)).map(([,o])=>o.bind(null,e)),n=0,i="",r="",{prettyErrors:l}=this.ctx.app.options,c=f(async o=>{if(l&&(r=new Error().stack.split(` | ||
var je=Object.defineProperty;var f=(m,e)=>je(m,"name",{value:e,configurable:!0});var G=(m,e)=>()=>(e||m((e={exports:{}}).exports,e),e.exports);var ye=G((yt,Be)=>{Be.exports={general:{name:"中文",paren:"({0})",quote:"“{0}”",comma:",",and:"和",or:"或",day:"天",hour:"小时",minute:"分钟",second:"秒"},internal:{"low-authority":"权限不足。","insufficient-arguments":"缺少参数,输入帮助以查看用法。","redunant-arguments":"存在多余参数,输入帮助以查看用法。","invalid-argument":"参数 {0} 输入无效,{1}","unknown-option":"存在未知选项 {0},输入帮助以查看用法。","invalid-option":"选项 {0} 输入无效,{1}","check-syntax":"输入帮助以查看用法。","invalid-number":"请提供一个数字。","invalid-integer":"请提供一个整数。","invalid-posint":"请提供一个正整数。","invalid-natural":"请提供一个非负整数。","invalid-date":"请输入合法的时间。","invalid-user":"请指定正确的用户。","invalid-channel":"请指定正确的频道。"}}});var ve=G((vt,Re)=>{Re.exports={general:{name:"English",paren:" ({0}) ",quote:'"{0}"',comma:", ",and:"and",or:"or",day:"day",hour:"hour",minute:"minute",second:"second"},internal:{"low-authority":"Low authority.","insufficient-arguments":"Insufficient arguments, type help to see usage.","redunant-arguments":"Redunant arguments, type help to see usage.","invalid-argument":"Invalid argument {0}, {1}","unknown-option":"Unknown option {0}, type help to see usage.","invalid-option":"Invalid option {0}, {1}","check-syntax":"Type help to see usage.","invalid-number":"Expect a number.","invalid-integer":"Expect an integer.","invalid-posint":"Expect a positive integer.","invalid-natural":"Expect a non-negative integer.","invalid-date":"Expect a valid date.","invalid-user":"Expect a valid user.","invalid-channel":"Expect a valid channel."}}});var Ce=G((Ct,qe)=>{qe.exports={general:{name:"日本語",paren:"({0})",quote:"「{0}」",comma:"、",and:"と",or:"や",day:"日",hour:"時間",minute:"分",second:"秒"},internal:{"low-authority":"実行できる権限が付与されていません","insufficient-arguments":"パラメータが不足しています、「help」を送信して使い方を確認してください。","redunant-arguments":"パラメータ数が多すぎます、「help」を送信して使い方を確認してください。","invalid-argument":"無効なパラメータ「{0}」、{1}","unknown-option":"未知なオプション「{0}」、「help」を送信して使い方を確認してください。","invalid-option":"無効なオプション「{0}」、{1}","check-syntax":"「help」を送信して使い方を検索してください。","invalid-number":"数字を指定してください。","invalid-integer":"整数を指定してください。","invalid-posint":"正の整数を指定してください。","invalid-natural":"自然数を指定してください。","invalid-date":"日付を指定してください。","invalid-user":"ユーザー名を指定してください。","invalid-channel":"チャンネル名を指定してください。"}}});var we=G((wt,Le)=>{Le.exports={general:{name:"francais",paren:" ({0}) ",quote:'"{0}"',comma:", ",and:"et",or:"ou",day:"jour",hour:"heure",minute:"minute",second:"seconde"},internal:{"low-authority":"Droits insuffisants.","insufficient-arguments":`Arguments insuffisants, tapez "help" pour afficher l'aide`,"redunant-arguments":`Arguments redondants, tapez "help" pour afficher l'aide`,"invalid-argument":"Arguments {0} invalides, {1}","unknown-option":`Option {0} inconnue, tapez "help" pour afficher l'aide`,"invalid-option":"Option {0} invalide, {1}","check-syntax":`Tapez "help" pour afficher l'aide`,"invalid-number":"Entrez un nombre.","invalid-integer":"Entrez un entier.","invalid-posint":"Entrez un entier positif.","invalid-natural":"Entrez un entier non négatif.","invalid-date":"Entrez une date valide.","invalid-user":"Entrez un nom d'utilisateur valide.","invalid-channel":"Entrez un nom de canal valide."}}});var ke=G((kt,Ge)=>{Ge.exports={general:{name:"中文",paren:"({0})",quote:"「{0}」",comma:",",and:"和",or:"或",day:"天",hour:"小時",minute:"分鐘",second:"秒"},internal:{"low-authority":"權限不足。","insufficient-arguments":"參數個數不足,輸入「help」檢視用法。","redunant-arguments":"參數個數冗餘,輸入「help」檢視用法。","invalid-argument":"參數 {0} 無效,{1}","unknown-option":"存在未知選項 {0},輸入「help」檢視用法。","invalid-option":"選項 {0} 無效,{1}","check-syntax":"輸入「help」檢視用法。","invalid-number":"請輸入有效數字。","invalid-integer":"請輸入有效整數。","invalid-posint":"請輸入有效正整數。","invalid-natural":"請輸入有效非負整數。","invalid-date":"請輸入有效時間。","invalid-user":"請指定有效用戶。","invalid-channel":"請指定有效頻道。"}}});var Ke=G((Mn,xt)=>{xt.exports={name:"@koishijs/core",description:"Core Features for Koishi",version:"4.7.6",main:"lib/node.js",module:"lib/browser.js",typings:"lib/index.d.ts",files:["lib"],author:"Shigma <shigma10826@gmail.com>",license:"MIT",repository:{type:"git",url:"git+https://github.com/koishijs/koishi.git",directory:"packages/core"},bugs:{url:"https://github.com/koishijs/koishi/issues"},homepage:"https://koishi.js.org",keywords:["bot","chatbot","koishi"],devDependencies:{"@koishijs/plugin-database-memory":"^1.4.0","@koishijs/plugin-mock":"^1.0.6",chai:"^4.3.6","chai-as-promised":"^7.1.1","chai-shape":"^1.0.0"},dependencies:{"@koishijs/utils":"^5.4.5",cordis:"^1.6.0","fastest-levenshtein":"^1.0.12",minato:"^1.2.1"}}});import{defineProperty as ee,Schema as _,Time as be}from"@koishijs/utils";import{App as B}from"cordis";export*from"@koishijs/utils";export*from"cordis";export*from"minato";import{isNullable as Se,Logger as Ne,Random as ze,Time as te}from"@koishijs/utils";import{Context as _e}from"cordis";var Ae=new Ne("i18n"),Te=Symbol("template"),ne=class{constructor(e){this._data={};this._formatters={};this._presets={};this.define("",{"":""}),this.define("zh",ye()),this.define("en",ve()),this.define("ja",Ce()),this.define("fr",we()),this.define("zh-tw",ke()),this.registerBuiltins()}set(e,t,n){if(t.includes("@")||typeof n=="string"){let i=this._data[e],[r,l]=t.slice(0,-1).split("@");l&&(n[Te]=l),!Se(i[r])&&!e.startsWith("$")&&Ae.warn("override",e,r),i[r]=n,this[_e.current]?.on("dispose",()=>{delete i[r]})}else for(let i in n)this.set(e,t+i+".",n[i])}define(e,...t){this._data[e]||={},typeof t[0]=="string"?this.set(e,t[0]+".",t[1]):this.set(e,"",t[0])}formatter(e,t){this._formatters[e]=t}preset(e,t){this._presets[e]=t}render(e,t,n){if(e!==void 0){if(typeof e!="string"){let i=e[Te],r=this._presets[i];if(!r)throw new Error(`Preset "${i}" not found`);return r(e,t,n)}return e.replace(/\{(.+?)\}/g,(i,r)=>{let[l,...c]=r.split("|"),o=l.trim().split("."),d=t;for(let h of o)if(d=d[h],Se(d))return"";for(let h of c){let x=h.trim().match(/(\w+)(?:\((.+)\))?/),y=this._formatters[x[1]];if(!y)throw new Error(`Formatter "${x[1]}" not found`);let M=x[2]?x[2].split(",").map(C=>C.trim()):[];d=y(d,M,n)}return d.toString()})}}text(e,t,n){let i=new Set;for(let r of e)!r||i.add(r);for(let r in this._data)r.startsWith("$")||i.add(r);for(let r of t)for(let l of i)for(let c of["$"+l,l]){let o=this._data[c]?.[r];if(o!==void 0)return this.render(o,n,l)}return Ae.warn("missing",t[0]),t[0]}registerBuiltins(){let e=["day","hour","minute","second"];this.formatter("time",(t,n,i)=>{for(let r=0;r<3;r++){let l=te[e[r]],c=te[e[r+1]];if(t>=l-c/2){t+=c/2;let o=Math.floor(t/l)+" "+this.text([i],["general."+e[r]],{});return t%l>c&&(o+=` ${Math.floor(t%l/c)} `+this.text([i],["general."+e[r+1]],{})),o}}return Math.round(t/te.second)+" "+this.text([i],["general.second"],{})}),this.preset("plural",(t,n,i)=>{let r=n.length in t?n.length:t.length-1;return this.render(t[r],n,i)}),this.preset("random",(t,n,i)=>this.render(ze.pick(t),n,i)),this.preset("list",(t,n,i)=>{let r=Object.entries(n).map(([l,c])=>this.render(t.item,{key:l,value:c},i));return r.unshift(this.render(t.header,n,i)),r.push(this.render(t.footer,n,i)),r.join(` | ||
`).trim()})}};f(ne,"I18n");_e.service("i18n",{constructor:ne});import{Database as Ee}from"minato";import{Context as V}from"cordis";var X;(function(t){let m;(function(i){i[i.ignore=1]="ignore"})(m=t.Flag||(t.Flag={})),t.fields=[]})(X||(X={}));var W;(function(t){let m;(function(r){r[r.ignore=1]="ignore",r[r.silent=4]="silent"})(m=t.Flag||(t.Flag={})),t.fields=[]})(W||(W={}));var J=class extends Ee{constructor(e){super();this.app=e;this[V.current]=e,this.extend("user",{id:"string(63)",name:{type:"string",length:63},flag:"unsigned(20)",authority:"unsigned(4)",locale:"string(63)"},{autoInc:!0}),this.extend("channel",{id:"string(63)",platform:"string(63)",flag:"unsigned(20)",assignee:"string(63)",guildId:"string(63)",locale:"string(63)"},{primary:["id","platform"]})}async getUser(e,t,n){let i=await this.get("user",{[e]:t},n);return Array.isArray(t)?i:(i[0]&&Object.assign(i[0],{[e]:t}),i[0])}setUser(e,t,n){return this.set("user",{[e]:t},n)}createUser(e,t,n){return this.create("user",{[e]:t,...n})}async getChannel(e,t,n){let i=await this.get("channel",{platform:e,id:t},n);return Array.isArray(t)?i:(i[0]&&Object.assign(i[0],{platform:e,id:t}),i[0])}getSelfIds(e,t){if(e)return t||=this.app.bots.filter(i=>i.platform===e).map(i=>i.selfId),{[e]:t};let n={};for(let i of this.app.bots)(n[i.platform]||=[]).push(i.selfId);return n}async getAssignedChannels(e,t=this.getSelfIds()){return this.get("channel",{$or:Object.entries(t).map(([n,i])=>({platform:n,assignee:i}))},e)}setChannel(e,t,n){return this.set("channel",{platform:e,id:t},n)}createChannel(e,t,n){return this.create("channel",{platform:e,id:t,...n})}async broadcast(...e){let t;Array.isArray(e[0])&&(t=e.shift());let[n,i]=e;if(!n)return[];let r=await this.getAssignedChannels(["id","assignee","flag","platform","guildId"]),l={};for(let{id:c,assignee:o,flag:d,platform:h,guildId:x}of r)t&&!t.includes(`${h}:${c}`)||!i&&d&W.Flag.silent||((l[h]||={})[o]||=[]).push([c,x]);return(await Promise.all(Object.entries(l).flatMap(([c,o])=>this.app.bots.map(d=>d.platform!==c?Promise.resolve([]):d.broadcast(o[d.selfId]||[],n))))).flat(1)}};f(J,"DatabaseService");J.prototype.extend=f(function(e,t,n){Ee.prototype.extend.call(this,e,t,{...n,driver:this[V.current].mapping.database}),this.app.emit("model",e)},"extend");V.service("database");V.service("model",{constructor:J,methods:["getSelfIds","broadcast"]});var Pt=f((m,e,t)=>({name:m.name,reusable:!0,Config:e,apply(n,i){t?.(n,i);let r=new m(n.model,i),l=n.mapping.database||"default";n.on("ready",async()=>{await r.start(),n.model.drivers[l]=r;let c=Object.create(n.model);n.database=c}),n.on("dispose",async()=>{n.database=null,delete n.model.drivers[l],await r.stop()})}}),"defineDriver");import{Logger as We,remove as He}from"@koishijs/utils";import{Context as ie}from"cordis";function R(m,e,...t){return m.intersect(n=>t.length?t.includes(n[e]):!!n[e])}f(R,"property");var re=class{constructor(e){this.app=e;this[ie.current]=e,e.filter=()=>!0,e.on("internal/warning",(t,...n)=>{this.logger("app").warn(t,...n)}),e.on("internal/runtime",t=>{!t.uid||(t.context.filter=n=>t.children.some(i=>i.context.filter(n)))})}get caller(){return this[ie.current]}any(){return this.caller.extend({filter:()=>!0})}never(){return this.caller.extend({filter:()=>!1})}union(e){let t=this.caller,n=typeof e=="function"?e:e.filter;return this.caller.extend({filter:i=>t.filter(i)||n(i)})}intersect(e){let t=this.caller,n=typeof e=="function"?e:e.filter;return this.caller.extend({filter:i=>t.filter(i)&&n(i)})}exclude(e){let t=this.caller,n=typeof e=="function"?e:e.filter;return this.caller.extend({filter:i=>t.filter(i)&&!n(i)})}logger(e){return new We(e)}user(...e){return R(this.caller,"userId",...e)}self(...e){return R(this.caller,"selfId",...e)}guild(...e){return R(this.caller,"guildId",...e)}channel(...e){return R(this.caller,"channelId",...e)}platform(...e){return R(this.caller,"platform",...e)}private(...e){return R(this.caller.exclude(R(this.caller,"guildId")),"userId",...e)}async waterfall(...e){let t=typeof e[0]=="object"?e.shift():null,n=e.shift();for(let i of this.app.lifecycle.getHooks(n,t)){let r=await i.apply(t,e);e[0]=r}return e[0]}chain(...e){let t=typeof e[0]=="object"?e.shift():null,n=e.shift();for(let i of this.app.lifecycle.getHooks(n,t)){let r=i.apply(t,e);e[0]=r}return e[0]}before(e,t,n=!1){let i=e.split("/");return i[i.length-1]="before-"+i[i.length-1],this.caller.on(i.join("/"),t,!n)}createTimerDispose(e){let t=f(()=>{if(clearTimeout(e),!!this.caller.state)return He(this.caller.state.disposables,t)},"dispose");return this.caller.state.disposables.push(t),t}setTimeout(e,t,...n){let i=this.createTimerDispose(setTimeout(()=>{i(),e()},t,...n));return i}setInterval(e,t,...n){return this.createTimerDispose(setInterval(e,t,...n))}};f(re,"SelectorService");ie.service("selector",{constructor:re,methods:["any","never","union","intersect","exclude","select","user","self","guild","channel","platform","private","chain","waterfall","before","logger","setTimeout","setInterval"]});import{coerce as pt,defineProperty as mt,escapeRegExp as ht,makeArray as ft}from"@koishijs/utils";import{Context as ge}from"cordis";import{Logger as lt,paramCase as ct,remove as dt,Schema as P}from"@koishijs/utils";import{Context as fe}from"cordis";import{Logger as Pe,makeArray as st,Random as ot,sleep as at}from"@koishijs/utils";import{Context as pe}from"cordis";import{coerce as Ve,Logger as Xe,remove as q,Schema as H}from"@koishijs/utils";import{camelCase as $e,escapeRegExp as Ie,paramCase as Oe,segment as se,Time as Qe}from"@koishijs/utils";var oe=`"'“‘`,ae=`"'”’`,K;(function(v){let m={};function e(s,a,u){m[s]={terminator:a,parse:u}}v.interpolate=e,f(e,"interpolate"),e("$(",")");class t{constructor(){this.bracs=Object.create(m)}interpolate(a,u,p){this.bracs[a]={terminator:u,parse:p}}parseToken(a,u="$"){let p={inters:[]},g=oe.indexOf(a[0]),k=ae[g],A="";k&&(a=a.slice(1),u=`${k}(?=${u})|$`),u+=`|${Object.keys({...this.bracs,...m}).map(Ie).join("|")}`;let b=new RegExp(u);for(;;){let w=b.exec(a);if(A+=a.slice(0,w.index),w[0]in this.bracs){a=a.slice(w.index+w[0].length).trimStart();let{parse:$,terminator:D}=this.bracs[w[0]],E=$?.(a)||this.parse(a,D);a=E.rest,p.inters.push({...E,pos:A.length,initiator:w[0]})}else{let $=w[0]===k,D=a.slice(w.index+ +$);return p.rest=D.trimStart(),p.quoted=$,p.terminator=w[0],$?p.terminator+=D.slice(0,-p.rest.length):k&&(A=oe[g]+A,p.inters.forEach(E=>E.pos+=1)),p.content=A,k==="'"&&v.revert(p),p}}}parse(a,u=""){let p=[],g=a,k="",A=`\\s+|[${Ie(u)}]|$`;for(;g&&!(u&&g.startsWith(u));){let b=this.parseToken(g,A);p.push(b),g=b.rest,k=b.terminator,delete b.rest}return g.startsWith(u)&&(g=g.slice(1)),a=a.slice(0,-(g+k).length),{tokens:p,rest:g,source:a}}stringify(a){let u=a.tokens.reduce((p,g)=>(g.quoted&&(p+=oe[ae.indexOf(g.terminator[0])]||""),p+g.content+g.terminator),"");return a.rest&&!ae.includes(u[u.length-1])||a.initiator?u.slice(0,-1):u}}f(t,"Tokenizer"),v.Tokenizer=t;let n=new t;function i(s,a=""){return n.parse(s,a)}v.parse=i,f(i,"parse");function r(s){return n.stringify(s)}v.stringify=r,f(r,"stringify");function l(s){for(;s.inters.length;){let{pos:a,source:u,initiator:p}=s.inters.pop();s.content=s.content.slice(0,a)+p+u+m[p].terminator+s.content.slice(a)}}v.revert=l,f(l,"revert");function c(s){return typeof s=="string"?d[s]||{}:{}}f(c,"resolveConfig");function o(s){return typeof s=="function"?s:s instanceof RegExp?a=>{if(s.test(a))return a;throw new Error}:Array.isArray(s)?a=>{if(s.includes(a))return a;throw new Error}:d[s]?.transform}f(o,"resolveType");let d={};function h(s,a,u){d[s]={...u,transform:a}}v.createDomain=h,f(h,"createDomain"),h("rawtext",s=>s),h("string",s=>s),h("text",s=>s,{greedy:!0}),h("rawtext",s=>se.unescape(s),{greedy:!0}),h("boolean",()=>!0),h("number",(s,a)=>{let u=+s;if(Number.isFinite(u))return u;throw new Error("internal.invalid-number")}),h("integer",(s,a)=>{let u=+s;if(u*0==0&&Math.floor(u)===u)return u;throw new Error("internal.invalid-integer")}),h("posint",(s,a)=>{let u=+s;if(u*0==0&&Math.floor(u)===u&&u>0)return u;throw new Error("internal.invalid-posint")}),h("natural",(s,a)=>{let u=+s;if(u*0==0&&Math.floor(u)===u&&u>=0)return u;throw new Error("internal.invalid-natural")}),h("date",(s,a)=>{let u=Qe.parseDate(s);if(+u)return u;throw new Error("internal.invalid-date")}),h("user",(s,a)=>{if(s.startsWith("@"))return s=s.slice(1),s.includes(":")?s:`${a.platform}:${s}`;let u=se.from(s);if(u&&u.type==="at")return`${a.platform}:${u.data.id}`;throw new Error("internal.invalid-user")}),h("channel",(s,a)=>{if(s.startsWith("#"))return s=s.slice(1),s.includes(":")?s:`${a.platform}:${s}`;let u=se.from(s);if(u&&u.type==="sharp")return`${a.platform}:${u.data.id}`;throw new Error("internal.invalid-channel")});let x=/<[^>]+>|\[[^\]]+\]/g;function y(s){let a,u=[];for(;a=x.exec(s);){let p=a[0].slice(1,-1),g=!1;p.startsWith("...")&&(p=p.slice(3),g=!0);let[k,A]=p.split(":"),b=A?A.trim():void 0;u.push({name:k,variadic:g,type:b,required:a[0][0]==="<"})}return u.stripped=s.replace(/:[\w-]+[>\]]/g,p=>p.slice(-1)).trimEnd(),u}f(y,"parseDecl");function M(s,a,u,p,g={}){let{name:k,type:A,fallback:b}=g,w=s===""&&!a;if(w&&b!==void 0)return b;let $=o(A);if($)try{return $(s,p.session)}catch(E){if(!p.session)p.error=`internal.invalid-${u}`;else{let I=p.session.text(E.message||"internal.check-syntax");p.error=p.session.text(`internal.invalid-${u}`,[k,I])}return}if(w)return!0;if(a)return s;let D=+s;return D*0==0?D:s}v.parseValue=M,f(M,"parseValue");class C{constructor(a,u,p){this.name=a;this.ctx=p;this._options={};this._namedOptions={};this._symbolicOptions={};if(!a)throw new Error("expect a command name");let g=this._arguments=y(u);this.declaration=g.stripped}_createOption(a,u,p){let g=Oe(a),k=u.replace(/(?<=^|\s)[\w\x80-\uffff].*/,""),A=u.slice(k.length),b=k.replace(/(?<=^|\s)(<[^<]+>|\[[^[]+\]).*/,""),w=k.slice(b.length);b=b.trim()||"--"+g;let $=[],D=[];for(let T of b.trim().split(",")){T=T.trimStart();let z=T.replace(/^-+/,"");!z||!T.startsWith("-")?D.push(T):$.push(z)}!("value"in p)&&!$.includes(g)&&(b+=", --"+g);let E=y(w);E.stripped&&(b+=" "+E.stripped);let I=this._options[a]||={...F.defaultOptionConfig,...E[0],...p,name:a,values:{},valuesSyntax:{},syntax:b},S=`commands.${this.name}.options.${a}`,O=typeof I.fallback;"value"in p?(S+="."+p.value,I.valuesSyntax[p.value]=b,$.forEach(T=>I.values[T]=p.value)):w.trim()?!I.type&&(O==="string"||O==="number")&&(I.type=O):I.type="boolean",A&&this.ctx.i18n.define("",S,A),this._assignOption(I,$,this._namedOptions),this._assignOption(I,D,this._symbolicOptions),this._namedOptions[g]||(this._namedOptions[g]=I)}_assignOption(a,u,p){for(let g of u){if(g in p)throw new Error(`duplicate option name "${g}" for command "${this.name}"`);p[g]=a}}removeOption(a){if(!this._options[a])return!1;let u=this._options[a];delete this._options[a];for(let p in this._namedOptions)this._namedOptions[p]===u&&delete this._namedOptions[p];for(let p in this._symbolicOptions)this._symbolicOptions[p]===u&&delete this._symbolicOptions[p];return!0}parse(a,u,p=[],g={}){typeof a=="string"&&(a=v.parse(a,u));let k=this.name+" "+v.stringify(a);for(;!a.error&&a.tokens.length;){let A=a.tokens[0],{content:b,quoted:w}=A,$=this._arguments[p.length];if(b[0]!=="-"&&c($?.type).greedy){p.push(v.parseValue(v.stringify(a),!0,"argument",a,$));break}a.tokens.shift();let D,E,I;if(!w&&(D=this._symbolicOptions[b]))E=[Oe(D.name)];else{if(b[0]!=="-"||w){p.push(v.parseValue(b,w,"argument",a,$||{type:"string"}));continue}let S=0,O;for(;S<b.length&&b.charCodeAt(S)===45;++S);if(b.slice(S,S+3)==="no-"&&!this._namedOptions[b.slice(S)]){O=b.slice(S+3),g[$e(O)]=!1;continue}let T=S+1;for(;T<b.length&&b.charCodeAt(T)!==61;T++);O=b.slice(S,T),E=S>1?[O]:O,I=b.slice(++T),D=this._namedOptions[E[E.length-1]]}if(w=!1,!I){let{type:S}=D||{};if(c(S).greedy)I=v.stringify(a),w=!0,a.tokens=[];else if(S!=="boolean"&&a.tokens.length&&(S||a.tokens[0]?.content!=="-")){let O=a.tokens.shift();I=O.content,w=O.quoted}}for(let S=0;S<E.length;S++){let O=E[S],T=this._namedOptions[O],z=T?T.name:$e(O);if(T&&O in T.values)g[z]=T.values[O];else{let Ue=S+1<E.length?"":I;g[z]=v.parseValue(Ue,w,"option",a,T)}if(a.error)break}}for(let{name:A,fallback:b}of Object.values(this._options))b!==void 0&&!(A in g)&&(g[A]=b);return delete a.tokens,{options:g,args:p,source:k,rest:a.rest,error:a.error||""}}stringifyArg(a){return a=""+a,a.includes(" ")?`"${a}"`:a}stringify(a,u){let p=this.name;for(let g in u){let k=u[g];k===!0?p+=` --${g}`:k===!1?p+=` --no-${g}`:p+=` --${g} ${this.stringifyArg(k)}`}for(let g of a)p+=" "+this.stringifyArg(g);return p}}f(C,"CommandBase"),v.CommandBase=C})(K||(K={}));var le=new Xe("command"),ce=class extends K.CommandBase{constructor(e,t,n){super(e,t,n);this.children=[];this.parent=null;this._aliases=[];this._examples=[];this._userFields=[["locale"]];this._channelFields=[["locale"]];this._actions=[];this._checkers=[async e=>this.ctx.serial(e.session,"command/before-execute",e)];this.config={...ce.defaultConfig},this._registerAlias(e),n.$commander._commandList.push(this)}static userFields(e){return this._userFields.push(e),this}static channelFields(e){return this._channelFields.push(e),this}get displayName(){return this._aliases[0]}set displayName(e){this._registerAlias(e,!0)}_registerAlias(e,t=!1){if(e=e.toLowerCase(),this._aliases.includes(e)){t&&(q(this._aliases,e),this._aliases.unshift(e));return}else t?this._aliases.unshift(e):this._aliases.push(e);let i=this.ctx.$commander.getCommand(e);if(!i)this.ctx.$commander._commands.set(e,this);else if(i!==this)throw new Error(`duplicate command names: "${e}"`);this._disposables?.push(()=>{q(this._aliases,e),this.ctx.$commander._commands.delete(e)})}[Symbol.for("nodejs.util.inspect.custom")](){return`Command <${this.name}>`}userFields(e){return this._userFields.push(e),this}channelFields(e){return this._channelFields.push(e),this}alias(...e){if(this._disposed)return this;for(let t of e)this._registerAlias(t);return this}shortcut(e,t={}){return this._disposed?this:(t.name=e,t.command=this,this.ctx.$commander._shortcuts.push(t),this._disposables?.push(()=>q(this.ctx.$commander._shortcuts,t)),this)}subcommand(e,...t){e=this.name+(e.charCodeAt(0)===46?"":"/")+e;let n=typeof t[0]=="string"?t.shift():"",i=t[0]||{};return this._disposed&&(i.patch=!0),this.ctx.command(e,n,i)}usage(e){return this._usage=e,this}example(e){return this._examples.push(e),this}option(e,...t){let n="";typeof t[0]=="string"&&(n=t.shift());let i=t[0];return this._createOption(e,n,i||{}),this._disposables?.push(()=>this.removeOption(e)),this}match(e){let{authority:t=1/0}=e.user||{};return this.ctx.filter(e)&&this.config.authority<=t}getConfig(e,t){let n=this.config[e];return typeof n=="function"?n(t):n}check(e,t=!1){return this.before(e,t)}before(e,t=!1){return t?this._checkers.push(e):this._checkers.unshift(e),this._disposables?.push(()=>q(this._checkers,e)),this}action(e,t=!1){return t?this._actions.unshift(e):this._actions.push(e),this._disposables?.push(()=>q(this._actions,e)),this}use(e,...t){return e(this,...t)}async execute(e,t=U.compose){e.command??=this,e.args??=[],e.options??={};let{args:n,options:i,error:r}=e;if(r)return r;le.level>=3&&le.debug(e.source||=this.stringify(n,i));for(let d of this._checkers){let h=await d.call(this,e,...n);if(typeof h=="string")return h}if(!this._actions.length)return"";let l=0,c=this._actions.map(d=>async()=>await d.call(this,e,...n));c.push(t);let o=c.length;e.next=async d=>{if(d!==void 0&&(c.push(h=>U.compose(d,h)),c.length>U.MAX_DEPTH))throw new Error(`middleware stack exceeded ${U.MAX_DEPTH}`);return c[l++]?.(e.next)};try{let d=await e.next();if(typeof d=="string")return d}catch(d){if(l===o)throw d;let h=Ve(d);le.warn(`${e.source||=this.stringify(n,i)} | ||
${h}`),this.ctx.emit(e.session,"command-error",e,d)}return""}dispose(){this._disposed=!0,this.ctx.emit("command-removed",this);for(let e of this.children.slice())e.dispose();this.ctx.$commander._shortcuts=this.ctx.$commander._shortcuts.filter(e=>e.command!==this),this._aliases.forEach(e=>this.ctx.$commander._commands.delete(e)),q(this.ctx.$commander._commandList,this),this.parent&&q(this.parent.children,this)}},F=ce;f(F,"Command"),F.defaultConfig={authority:1,showWarning:!0},F.defaultOptionConfig={authority:0},F._userFields=[],F._channelFields=[];(function(e){e.Config=H.object({authority:H.natural().default(1),hidden:H.boolean().default(!1),checkArgCount:H.boolean().default(!1),checkUnknown:H.boolean().default(!1)})})(F||(F={}));import{defineProperty as Je,valueMap as Ye}from"@koishijs/utils";function de(m){m.before("parse",(t,n)=>{let i=K.parse(t);return n.quote&&i.tokens.push({content:n.quote.content,quoted:!0,inters:[],terminator:""}),i}),m.before("parse",(t,n)=>{let{parsed:i,quote:r}=n;if(!(i.prefix||r))for(let l of m.$commander._shortcuts){let{name:c,fuzzy:o,command:d,prefix:h,options:x={},args:y=[]}=l;if(!(h&&!i.appel||!d.ctx.filter(n)))if(typeof c=="string"){if(!o&&t!==c||!t.startsWith(c))continue;let M=t.slice(c.length);if(o&&!i.appel&&M.match(/^\S/))continue;let C=K.parse(M.trim());return C.session=n,C=d.parse(C,"",[...y],{...x}),C.command=d,C}else{let C=function(v){return typeof v!="string"?v:(v=v.replace(/\$\$/g,"@@__PLACEHOLDER__@@"),M.forEach((s,a)=>{!a||a>9||(v=v.replace(new RegExp(`\\$${a}`,"g"),(s||"").replace(/\$/g,"@@__PLACEHOLDER__@@")))}),v.replace(/@@__PLACEHOLDER__@@/g,"$"))};f(C,"escape");let M=c.exec(t);if(!M)continue;return{command:d,args:y.map(C),options:Ye(x,C)}}}}),m.before("attach",t=>{Je(t,"argv",m.bail("before-parse",t.parsed.content,t)),t.argv.root=!0,t.argv.session=t});function e(t,n){if(!!m.$commander.getCommand("help"))return t.execute({name:"help",args:[n]})}f(e,"executeHelp"),m.before("command/execute",t=>{let{args:n,command:i,options:r,session:l}=t;if(r.help&&i._options.help)return e(l,i.name);if(i._actions.length)return;let c=n.shift()||"",o=m.$commander.getCommand(i.name+"."+c);if(o){let d=l.__redirected_commands||=[`(${i.name}${i._aliases.length!==0?"|"+i._aliases.join("|"):""})`];d.push(c);let h=new RegExp(`^${d.join("[. ]")}( |$)`);return t=K.parse(l.parsed.content.replace(h,"")),t.session=l,t=o.parse(t),l.execute({...t,command:o})}else return e(l,i.name)})}f(de,"runtime");function ue(m){m.on("command-added",e=>{e.userFields(({tokens:t,command:n,options:i={}},r)=>{if(!n)return;let{authority:l}=n.config,c=l>0;for(let{name:o,authority:d}of Object.values(n._options))o in i?d>0&&(c=!0):t&&d>0&&(c=!0);c&&r.add("authority")})}),m.before("command/execute",e=>{let{session:t,options:n,command:i}=e;if(!t.user)return;function r(l,...c){return i.config.showWarning?t.text(l,c):""}if(f(r,"sendHint"),t.user.authority&&i.getConfig("authority",t)>t.user.authority)return r("internal.low-authority");for(let l of Object.values(i._options))if(l.name in n&&l.authority>t.user.authority)return r("internal.low-authority")}),m.before("command/execute",e=>{let{args:t,options:n,command:i,session:r}=e;function l(c,...o){return i.config.showWarning?r.text(c,o):""}if(f(l,"sendHint"),i.config.checkArgCount){if((i._arguments[t.length]||{}).required)return l("internal.insufficient-arguments");let o=i._arguments[i._arguments.length-1]||{};if(t.length>i._arguments.length&&o.type!=="text"&&!o.variadic)return l("internal.redunant-arguments")}if(i.config.checkUnknown){let c=Object.keys(n).filter(o=>!i._options[o]);if(c.length)return l("internal.unknown-option",c.join(", "))}})}f(ue,"validate");var Q=class{constructor(e,t={}){this.ctx=e;this.config=t;this._commandList=[];this._commands=new Map;this._shortcuts=[];this[pe.current]=e,e.plugin(de),e.plugin(ue)}get caller(){return this[pe.current]}resolve(e){if(!e)return;let t=e.split("."),n=1,i=t[0],r;for(;(r=this.getCommand(i))&&n<t.length;)i=r.name+"."+t[n++];return r}getCommand(e){return this._commands.get(e)}command(e,...t){let n=typeof t[0]=="string"?t.shift():"",i=t[0],r=e.split(" ",1)[0].toLowerCase(),l=e.slice(r.length),c=r.split(/(?=[./])/g),o,d,h=[];if(c.forEach((y,M)=>{let C=y.charCodeAt(0),v=C===46?o.name+y:C===47?y.slice(1):y,s=this.getCommand(v);if(s){if(o){if(s===o)throw new Error(`cannot set a command (${s.name}) as its own subcommand`);if(s.parent){if(s.parent!==o)throw new Error(`cannot create subcommand ${r}: ${s.parent.name}/${s.name} already exists`)}else s.parent=o,o.children.push(s)}return o=s}s=new F(v,l,this.caller),h.push(s),d||(d=s),o&&(s.parent=o,s.config.authority=o.config.authority,o.children.push(s)),o=s}),n&&this.caller.i18n.define("",`commands.${o.name}.description`,n),Object.assign(o.config,i),h.forEach(y=>this.caller.emit("command-added",y)),!i?.patch)return d&&this.caller.state.disposables.unshift(()=>d.dispose()),o;d&&d.dispose();let x=Object.create(o);return x._disposables=this.caller.state.disposables,x}};f(Q,"Commander"),Q.key="$commander";pe.service(Q.key,{constructor:Q,methods:["command"]});import{defineProperty as L,isNullable as Ze,Logger as et,makeArray as tt,observe as me,Random as nt,segment as it}from"@koishijs/utils";import{Context as rt}from"cordis";var he=new et("session"),Y=class{constructor(e,t){Object.assign(this,t),this.platform=e.platform,L(this,"app",e.ctx.app),L(this,"bot",e),L(this,"user",null),L(this,"channel",null),L(this,"id",nt.id()),L(this,"_queuedTasks",[]),L(this,"_queuedTimeout",null)}[rt.filter](e){return e.filter(this)}get uid(){return`${this.platform}:${this.userId}`}get gid(){return`${this.platform}:${this.guildId}`}get cid(){return`${this.platform}:${this.channelId}`}get sid(){return`${this.platform}:${this.selfId}`}toJSON(){return Object.fromEntries(Object.entries(this).filter(([e])=>!e.startsWith("_")&&!e.startsWith("$")))}async _preprocess(){let e,t=this.content.trim();return(e=it.from(t,{type:"quote",caret:!0}))&&(t=t.slice(e.capture[0].length).trimStart(),this.quote=await this.bot.getMessage(e.data.channelId||this.channelId,e.data.id).catch(n=>{he.warn(n)})),t}async preprocess(){return this._promise||=this._preprocess()}get username(){let e=this.user&&this.user.name?this.user.name:this.author?this.author.nickname||this.author.username:this.userId;return this.app.chain("appellation",e,this)}async send(e){if(!!e)return this.bot.sendMessage(this.channelId,e,this.guildId).catch(t=>(he.warn(t),[]))}cancelQueued(e=this.app.options.delay.cancel){clearTimeout(this._queuedTimeout),this._queuedTasks=[],this._queuedTimeout=setTimeout(()=>this._next(),e)}_next(){let e=this._queuedTasks.shift();if(!e){this._queuedTimeout=null;return}this.send(e.content).then(e.resolve,e.reject),this._queuedTimeout=setTimeout(()=>this._next(),e.delay)}async sendQueued(e,t){if(!!e){if(Ze(t)){let{message:n,character:i}=this.app.options.delay;t=Math.max(n,i*e.length)}return new Promise((n,i)=>{this._queuedTasks.push({content:e,delay:t,resolve:n,reject:i}),this._queuedTimeout||this._next()})}}resolveValue(e){return typeof e=="function"?Reflect.apply(e,null,[this]):e}async getChannel(e=this.channelId,t=[]){let{app:n,platform:i,guildId:r}=this;if(!t.length)return{platform:i,id:e,guildId:r};let l=await n.database.getChannel(i,e,t);if(l)return l;let c=await this.resolveValue(n.options.autoAssign)?this.selfId:"";if(c)return n.database.createChannel(i,e,{assignee:c,guildId:r});{let o=n.model.tables.channel.create();return Object.assign(o,{platform:i,id:e,guildId:r,$detached:!0}),o}}async _observeChannelLike(e,t=[]){let n=new Set(t),{platform:i}=this,r=`${i}:${e}`,l=this.app.$internal._channelCache.get(this.id,r);if(l){for(let o in l)n.delete(o);if(!n.size)return l}let c=await this.getChannel(e,[...n]);return l=this.app.$internal._channelCache.get(this.id,r),l?l.$merge(c):(l=me(c,o=>this.app.database.setChannel(i,e,o),`channel ${r}`),this.app.$internal._channelCache.set(this.id,r,l)),l}async observeChannel(e=[]){let t=[this._observeChannelLike(this.channelId,e)];this.channelId!==this.guildId&&t.push(this._observeChannelLike(this.guildId,e));let[n,i=n]=await Promise.all(t);return this.guild=i,this.channel=n,n}async getUser(e=this.userId,t=[]){let{app:n,platform:i}=this;if(!t.length)return{[i]:e};let r=await n.database.getUser(i,e,t);if(r)return r;let l=await this.resolveValue(n.options.autoAuthorize);if(l)return n.database.createUser(i,e,{authority:l});{let c=n.model.tables.user.create();return Object.assign(c,{[i]:e,authority:l,$detached:!0}),c}}async observeUser(e=[]){let t=new Set(e),{userId:n,platform:i}=this,r=this.app.$internal._userCache.get(this.id,this.uid);if(r){for(let c in r)t.delete(c);if(!t.size)return this.user=r}if(this.author?.anonymous){let c=this.app.model.tables.user.create();c[i]=n,c.authority=await this.resolveValue(this.app.options.autoAuthorize);let o=me(c,()=>Promise.resolve());return this.user=o}let l=await this.getUser(n,[...t]);return r=this.app.$internal._userCache.get(this.id,this.uid),r?r.$merge(l):(r=me(l,c=>this.app.database.setUser(this.platform,n,c),`user ${this.uid}`),this.app.$internal._userCache.set(this.id,this.uid,r)),this.user=r}async withScope(e,t){let n=this.scope;try{return this.scope=e,await t()}finally{this.scope=n}}text(e,t={}){let n=[this.app.options.locale];n.unshift(this.user?.locale),this.subtype==="group"&&(n.unshift(this.guild?.locale),n.unshift(this.channel?.locale));let i=tt(e).map(r=>r.startsWith(".")?this.scope?this.scope+r:(this.app.logger("i18n").warn(new Error("missing scope")),""):r);return this.app.i18n.text(n,i,t)}collect(e,t,n=new Set){let i=f(r=>{if(r.session=this,r.tokens)for(let{inters:l}of r.tokens)l.forEach(i);!this.resolve(r)||(this.app.emit(r.session,`command/before-attach-${e}`,r,n),Fe(r,F[`_${e}Fields`],n),Fe(r,r.command[`_${e}Fields`],n))},"collect");return i(t),n}inferCommand(e){if(e.command)return e.command;if(e.name)return e.command=this.app.$commander.resolve(e.name);let{parsed:t,subtype:n}=this;if(e.root&&n!=="private"&&t.prefix===null&&!t.appel||!e.tokens.length)return;let i=this.app.$commander.resolve(e.tokens[0].content);if(i)return e.tokens.shift(),e.command=i}resolve(e){if(!!this.inferCommand(e)){if(e.tokens?.every(t=>!t.inters.length)){let{options:t,args:n,error:i}=e.command.parse(e);e.options={...e.options,...t},e.args=[...e.args||[],...n],e.error=i}return e.command}}async execute(e,t){if(typeof e=="string"&&(e=K.parse(e)),e.session=this,e.tokens){for(let r of e.tokens){let{inters:l}=r,c=[];for(let o=0;o<l.length;++o)c.push(await this.execute(l[o],!0));for(let o=l.length-1;o>=0;--o){let{pos:d}=l[o];r.content=r.content.slice(0,d)+c[o]+r.content.slice(d)}r.inters=[]}if(!this.resolve(e))return""}else if(e.command||=this.app.$commander.getCommand(e.name),!e.command)return he.warn(new Error(`cannot find command ${e.name}`)),"";let{command:n}=e;if(!n.ctx.filter(this))return"";this.app.database&&(this.subtype==="group"&&await this.observeChannel(this.collect("channel",e)),await this.observeUser(this.collect("user",e)));let i=!0;return t===!0&&(i=!1,t=void 0),this.withScope(`commands.${n.name}.messages`,async()=>{let r=await n.execute(e,t);return i?(await this.send(r),""):r})}middleware(e){let t=De(this);return this.app.middleware(async(n,i)=>t&&De(n)!==t?i():e(n,i),!0)}prompt(e=this.app.options.delay.prompt){return new Promise(t=>{let n=this.middleware(r=>{clearTimeout(i),n(),t(r.content)}),i=setTimeout(()=>{n(),t("")},e)})}};f(Y,"Session");function De(m){return""+m.userId+m.channelId}f(De,"getSessionId");function Fe(m,e,t){for(let n of e){if(typeof n=="function"){n(m,t);continue}for(let i of n)t.add(i)}return t}f(Fe,"collectFields");var Me=new Pe("bot"),j=class{constructor(e,t){this.adapter=e;this.config=t;this.id=ot.id();this.ctx=e.ctx,this.app=this.ctx.app,this.platform=t.platform||e.platform,this.logger=new Pe(e.platform),this._status="offline",this.extendModel(),e.ctx.on("ready",()=>this.start()),e.ctx.on("dispose",()=>this.stop())}extendModel(){this.platform in this.ctx.model.tables.user.fields||this.ctx.model.extend("user",{[this.platform]:{type:"string",length:63}},{unique:[this.platform]})}get status(){return this._status}set status(e){this._status=e,this.ctx.bots.includes(this)&&this.ctx.emit("bot-status-updated",this)}resolve(){this.status="online",Me.success("logged in to %s as %c (%s)",this.platform,this.username,this.selfId)}reject(e){this.error=e,this.status="offline",Me.error(e)}async start(){if(!this.config.disabled&&!["connect","reconnect","online"].includes(this.status)){this.status="connect";try{await this.ctx.parallel("bot-connect",this),await this.adapter.connect(this)}catch(e){this.reject(e)}}}async stop(){if(!["disconnect","offline"].includes(this.status)){this.status="disconnect";try{await this.ctx.parallel("bot-disconnect",this),await this.adapter.disconnect(this)}catch(e){this.logger.warn(e)}this.status="offline"}}get sid(){return`${this.platform}:${this.selfId}`}createSession(e){return new Y(this,{...e,type:"send",selfId:this.selfId,platform:this.platform,timestamp:Date.now(),author:{userId:this.selfId,username:this.username,avatar:this.avatar,discriminator:this.discriminator,isBot:!0}})}async session(e){let t=this.createSession(e);if(!await this.ctx.serial(t,"before-send",t))return t}async getGuildMemberMap(e){let t=await this.getGuildMemberList(e);return Object.fromEntries(t.map(n=>[n.userId,n.nickname||n.username]))}async broadcast(e,t,n=this.ctx.app.options.delay.broadcast){let i=[];for(let r=0;r<e.length;r++){r&&n&&await at(n);try{let[l,c]=st(e[r]);i.push(...await this.sendMessage(l,t,c))}catch(l){this.ctx.logger("bot").warn(l)}}return i}};f(j,"Bot");(function(e){e.library={}})(j||(j={}));var N=class{constructor(e,t){this.ctx=e;this.config=t;this.bots=[];e.on("ready",()=>this.start()),e.on("dispose",()=>this.stop())}connect(e){}disconnect(e){}dispatch(e){if(!this.ctx.lifecycle.isActive)return;let t=[e.type];e.subtype&&(t.unshift(t[0]+"/"+e.subtype),e.subsubtype&&t.unshift(t[0]+"/"+e.subsubtype));for(let n of t)this.ctx.emit(e,ct(n),e)}};f(N,"Adapter");var ut=new lt("app");(function(l){l.redirect=Symbol("koishi.adapter.redirect"),l.library={},l.configMap={};function n(c,o){return o?`${c}.${o}`:c}l.join=n,f(n,"join");function i(c,o,...d){let h=c+"-adapter";c=c.toLowerCase(),j.library[c]=o;let x;if(typeof d[0]=="function")l.library[c]=d[0],x=d[0].schema;else{let v=function(s){if(s.type==="union"||s.type==="intersect")s.list.forEach(v);else if(s.type==="object")for(let a in s.dict)C.dict[a]=new P(s.dict[a]),C.dict[a].meta={...s.dict[a].meta,required:!1};else throw new Error("cannot flatten bot schema")};f(v,"flatten"),l.library[c]={[l.redirect]:d[1]},x=l.library[c].schema=P.union([]).description("机器人要使用的协议。");let C=P.object({protocol:P.string()});for(let s in d[0])l.library[n(c,s)]=d[0][s],v(d[0][s].schema),x.list.push(P.intersect([P.object({protocol:P.const(s).required()}),d[0][s].schema]).description(s));x.list.push(P.transform(C,s=>{if(s.protocol)throw new Error(`unknown protocol "${s.protocol}"`);return s.protocol=d[1](s),ut.debug("infer type as %s",s.protocol),s}))}let y=P.intersect([o.schema,P.union([P.object({bots:P.array(x).required().hidden()}),P.transform(x,C=>({bots:[C]}))])]);function M(C,v={}){C.emit("adapter",c),l.configMap[c]=v;for(let s of v.bots)C.bots.create(c,s,o)}return f(M,"apply"),{name:h,Config:y,apply:M}}l.define=i,f(i,"define");class r extends Array{constructor(o){super();this.app=o;this.adapters={};this[fe.current]=o}get caller(){return this[fe.current]}get(o){return this.find(d=>d.sid===o)}create(o,d,h){h||=j.library[o];let x=this.resolve(o,d),y=new h(x,d);return x.bots.push(y),this.push(y),this.caller.emit("bot-added",y),this.caller.on("dispose",()=>{this.remove(y.id)}),y}remove(o){let d=this.findIndex(y=>y.id===o);if(d<0)return;let[h]=this.splice(d,1),x=dt(h.adapter.bots,h);return this.caller.emit("bot-removed",h),x}resolve(o,d){let h=n(o,d.protocol);if(this.adapters[h])return this.adapters[h];let x=l.library[h];if(!x)throw new Error(`unsupported protocol "${h}"`);if(x[l.redirect])return d.protocol=x[l.redirect](d),this.resolve(o,d);let y=new x(this.caller,l.configMap[o]);return y.platform=o,this.caller.on("dispose",()=>{delete this.adapters[h]}),this.adapters[h]=y}}f(r,"BotList"),l.BotList=r})(N||(N={}));fe.service("bots",{constructor:N.BotList});function gt(m,e="",t=""){return m.length?new RegExp(`^${e}(${m.map(ht).join("|")})${t}`):/$^/}f(gt,"createLeadingRE");var U;(function(t){t.MAX_DEPTH=64;async function e(n,i){return typeof n=="function"?n(i):n}t.compose=e,f(e,"compose")})(U||(U={}));var xe=class{constructor(e,t){this.ctx=e;this.config=t;this._hooks=[];this._sessions=Object.create(null);this._userCache=new Z;this._channelCache=new Z;this[ge.current]=e,this.prepare(),this.middleware(this._process.bind(this)),e.on("message",this._handleMessage.bind(this)),e.before("attach-user",(n,i)=>{n.collect("user",n.argv,i)}),e.before("attach-channel",(n,i)=>{n.collect("channel",n.argv,i)}),this.middleware((n,i)=>n.resolve(n.argv)?n.execute(n.argv,i):i())}get caller(){return this[ge.current]}middleware(e,t=!1){return this.caller.lifecycle.register("middleware",this._hooks,e,t)}prepare(){this._nameRE=gt(ft(this.config.nickname),"@?","([,,]\\s*|\\s+)")}_resolvePrefixes(e){let t=e.resolveValue(this.config.prefix);return Array.isArray(t)?t:[t||""]}async _process(e,t){let n,i=!1,r=!1,l=null,c=/^\[CQ:(\w+)((,\w+=[^,\]]*)*)\]/,o=await e.preprocess();e.subtype!=="private"&&(n=o.match(c))&&n[1]==="at"&&n[2].includes("id="+e.selfId)?(i=r=!0,o=o.slice(n[0].length).trimStart()):(n=o.match(this._nameRE))&&(r=!0,o=o.slice(n[0].length));for(let d of this._resolvePrefixes(e))!o.startsWith(d)||(l=d,o=o.slice(d.length));if(mt(e,"parsed",{content:o,appel:r,prefix:l}),this.ctx.emit(e,"before-attach",e),this.ctx.database){if(e.subtype==="group"){let x=new Set(["flag","assignee","guildId","locale"]);this.ctx.emit("before-attach-channel",e,x);let y=await e.observeChannel(x);if(y.guildId=e.guildId,await this.ctx.serial(e,"attach-channel",e)||y.flag&W.Flag.ignore||y.assignee!==e.selfId&&!i)return}let d=new Set(["flag","authority","locale"]);this.ctx.emit("before-attach-user",e,d);let h=await e.observeUser(d);if(await this.ctx.serial(e,"attach-user",e)||h.flag&X.Flag.ignore)return}return this.ctx.emit(e,"attach",e),t()}async _handleMessage(e){if(e.selfId===e.userId)return;this._sessions[e.id]=e;let t=this._hooks.filter(([o])=>o.filter(e)).map(([,o])=>o.bind(null,e)),n=0,i="",r="",{prettyErrors:l}=this.ctx.app.options,c=f(async o=>{if(l&&(r=new Error().stack.split(` | ||
`,3)[2],n)){let d=r.match(/\((.+)\)/);i=` | ||
- ${d?d[1]:r.slice(7)}${i}`}try{if(!this._sessions[e.id])throw new Error("isolated next function detected");if(o!==void 0&&(t.push(d=>j.compose(o,d)),t.length>j.MAX_DEPTH))throw new Error(`middleware stack exceeded ${j.MAX_DEPTH}`);return await t[n++]?.(c)}catch(d){let h=pt(d);if(l){let x=h.indexOf(r);x>=0?h=h.slice(0,x):h+=` | ||
- ${d?d[1]:r.slice(7)}${i}`}try{if(!this._sessions[e.id])throw new Error("isolated next function detected");if(o!==void 0&&(t.push(d=>U.compose(o,d)),t.length>U.MAX_DEPTH))throw new Error(`middleware stack exceeded ${U.MAX_DEPTH}`);return await t[n++]?.(c)}catch(d){let h=pt(d);if(l){let x=h.indexOf(r);x>=0?h=h.slice(0,x):h+=` | ||
`,h+=`Middleware stack:${i}`}this.ctx.logger("session").warn(`${e.content} | ||
${h}`)}},"next");try{let o=await c();o&&await e.send(o)}finally{delete this._sessions[e.id],this.ctx.emit(e,"middleware",e),this._userCache.delete(e.id),this._channelCache.delete(e.id),await e.user?.$update(),await e.channel?.$update(),await e.guild?.$update()}}};f(me,"Internal");Ke.service("$internal",{constructor:me,methods:["middleware"]});var Y=class{#e=Object.create(null);get(e,t){let n=this.#e[t];if(!!n)return n.refs.add(e),n.value}set(e,t,n){let i=this.#e[t];i?i.value=n:i=this.#e[t]={value:n,key:t,refs:new Set},i.refs.add(e)}delete(e){for(let t in this.#e){let{refs:n}=this.#e[t];n.delete(e),n.size||delete this.#e[t]}}};f(Y,"SharedCache");var Rn=Ue().version;Z(B,"Config",S.intersect([]));Z(B.Config,"Basic",S.object({locale:S.string().default("zh").description("默认使用的语言。"),prefix:S.union([S.array(String),S.transform(String,m=>[m])]).default([""]).description("指令前缀字符,可以是字符串或字符串数组。将用于指令前缀的匹配。"),nickname:S.union([S.array(String),S.transform(String,m=>[m])]).description("机器人的昵称,可以是字符串或字符串数组。将用于指令前缀的匹配。"),autoAssign:S.union([Boolean,Function]).default(!0).description("当获取不到频道数据时,是否使用接受者作为代理者。"),autoAuthorize:S.union([S.natural(),Function]).default(1).description("当获取不到用户数据时默认使用的权限等级。")}).description("基础设置"));Z(B.Config,"Features",S.object({delay:S.object({character:S.natural().role("ms").default(0).description("调用 `session.sendQueued()` 时消息间发送的最小延迟,按前一条消息的字数计算。"),message:S.natural().role("ms").default(.1*he.second).description("调用 `session.sendQueued()` 时消息间发送的最小延迟,按固定值计算。"),cancel:S.natural().role("ms").default(0).description("调用 `session.cancelQueued()` 时默认的延迟。"),broadcast:S.natural().role("ms").default(.5*he.second).description("调用 `bot.broadcast()` 时默认的延迟。"),prompt:S.natural().role("ms").default(he.minute).description("调用 `session.prompt()` 时默认的等待时间。")})}).description("消息设置"));Z(B.Config,"Advanced",S.object({prettyErrors:S.boolean().default(!0).description("启用报错优化模式。在此模式下 Koishi 会对程序抛出的异常进行整理,过滤掉框架内部的调用记录,输出更易读的提示信息。"),maxListeners:S.natural().default(64).description("每种监听器的最大数量。如果超过这个数量,Koishi 会认定为发生了内存泄漏,将产生一个警告。")}).description("高级设置"));B.Config.list.push(B.Config.Basic,B.Config.Features,B.Config.Advanced);function qn(m){return m}f(qn,"defineConfig");export{z as Adapter,U as Argv,M as Bot,N as Channel,F as Command,Q as Commander,X as DatabaseService,te as I18n,me as Internal,j as Next,ie as SelectorService,J as Session,Y as SharedCache,V as User,qn as defineConfig,Pt as defineDriver,Ie as getSessionId,Rn as version}; | ||
${h}`)}},"next");try{let o=await c();o&&await e.send(o)}finally{delete this._sessions[e.id],this.ctx.emit(e,"middleware",e),this._userCache.delete(e.id),this._channelCache.delete(e.id),await e.user?.$update(),await e.channel?.$update(),await e.guild?.$update()}}};f(xe,"Internal");ge.service("$internal",{constructor:xe,methods:["middleware"]});var Z=class{#e=Object.create(null);get(e,t){let n=this.#e[t];if(!!n)return n.refs.add(e),n.value}set(e,t,n){let i=this.#e[t];i?i.value=n:i=this.#e[t]={value:n,key:t,refs:new Set},i.refs.add(e)}delete(e){for(let t in this.#e){let{refs:n}=this.#e[t];n.delete(e),n.size||delete this.#e[t]}}};f(Z,"SharedCache");var jn=Ke().version;ee(B,"Config",_.intersect([]));ee(B.Config,"Basic",_.object({locale:_.string().default("zh").description("默认使用的语言。"),prefix:_.union([_.array(String),_.transform(String,m=>[m])]).default([""]).description("指令前缀字符,可以是字符串或字符串数组。将用于指令前缀的匹配。"),nickname:_.union([_.array(String),_.transform(String,m=>[m])]).description("机器人的昵称,可以是字符串或字符串数组。将用于指令前缀的匹配。"),autoAssign:_.union([Boolean,Function]).default(!0).description("当获取不到频道数据时,是否使用接受者作为代理者。"),autoAuthorize:_.union([_.natural(),Function]).default(1).description("当获取不到用户数据时默认使用的权限等级。")}).description("基础设置"));ee(B.Config,"Features",_.object({delay:_.object({character:_.natural().role("ms").default(0).description("调用 `session.sendQueued()` 时消息间发送的最小延迟,按前一条消息的字数计算。"),message:_.natural().role("ms").default(.1*be.second).description("调用 `session.sendQueued()` 时消息间发送的最小延迟,按固定值计算。"),cancel:_.natural().role("ms").default(0).description("调用 `session.cancelQueued()` 时默认的延迟。"),broadcast:_.natural().role("ms").default(.5*be.second).description("调用 `bot.broadcast()` 时默认的延迟。"),prompt:_.natural().role("ms").default(be.minute).description("调用 `session.prompt()` 时默认的等待时间。")})}).description("消息设置"));ee(B.Config,"Advanced",_.object({prettyErrors:_.boolean().default(!0).description("启用报错优化模式。在此模式下 Koishi 会对程序抛出的异常进行整理,过滤掉框架内部的调用记录,输出更易读的提示信息。"),maxListeners:_.natural().default(64).description("每种监听器的最大数量。如果超过这个数量,Koishi 会认定为发生了内存泄漏,将产生一个警告。")}).description("高级设置"));B.Config.list.push(B.Config.Basic,B.Config.Features,B.Config.Advanced);function Bn(m){return m}f(Bn,"defineConfig");export{N as Adapter,K as Argv,j as Bot,W as Channel,F as Command,Q as Commander,J as DatabaseService,ne as I18n,xe as Internal,U as Next,re as SelectorService,Y as Session,Z as SharedCache,X as User,Bn as defineConfig,Pt as defineDriver,De as getSessionId,jn as version}; |
@@ -8,3 +8,3 @@ import * as utils from '@koishijs/utils'; | ||
} | ||
export interface Context { | ||
export interface Context extends DatabaseService.Mixin { | ||
database: DatabaseService; | ||
@@ -50,10 +50,11 @@ model: DatabaseService; | ||
export namespace DatabaseService { | ||
interface Delegates { | ||
interface Mixin { | ||
getSelfIds(type?: string, assignees?: string[]): Dict<string[]>; | ||
broadcast(content: string, forced?: boolean): Promise<string[]>; | ||
broadcast(channels: readonly string[], content: string, forced?: boolean): Promise<string[]>; | ||
} | ||
} | ||
export class DatabaseService extends Database<Tables> { | ||
protected ctx: Context; | ||
constructor(ctx: Context); | ||
get caller(): Context; | ||
protected app: Context; | ||
constructor(app: Context); | ||
getUser<T extends string, K extends User.Field>(platform: T, id: string, modifier?: Driver.Cursor<K>): Promise<Result<User, K> & Record<T, string>>; | ||
@@ -69,2 +70,3 @@ getUser<T extends string, K extends User.Field>(platform: T, ids: string[], modifier?: Driver.Cursor<K>): Promise<Result<User, K>[]>; | ||
createChannel(platform: string, id: string, data: Partial<Channel>): Promise<Channel>; | ||
broadcast(...args: [string, boolean?] | [readonly string[], string, boolean?]): Promise<any[]>; | ||
} | ||
@@ -295,3 +297,3 @@ export const defineDriver: <T>(constructor: Driver.Constructor<T>, schema?: utils.Schema<T, T>, prepare?: Plugin.Function<T>) => Plugin.Object<T, any>; | ||
} | ||
export interface Context extends Commander.Delegates { | ||
export interface Context extends Commander.Mixin { | ||
$commander: Commander; | ||
@@ -311,3 +313,3 @@ } | ||
} | ||
interface Delegates { | ||
interface Mixin { | ||
command<D extends string>(def: D, config?: Command.Config): Command<never, never, Argv.ArgumentType<D>>; | ||
@@ -362,6 +364,6 @@ command<D extends string>(def: D, desc: string, config?: Command.Config): Command<never, never, Argv.ArgumentType<D>>; | ||
class BotList extends Array<Bot> { | ||
private ctx; | ||
private app; | ||
adapters: Dict<Adapter>; | ||
get caller(): Context; | ||
constructor(ctx: Context); | ||
constructor(app: Context); | ||
protected get caller(): Context; | ||
get(sid: string): Bot<Bot.BaseConfig>; | ||
@@ -610,3 +612,3 @@ create<T extends Bot>(platform: string, options: any, constructor?: new (adapter: Adapter, config: any) => T): T; | ||
} | ||
export interface Context extends Internal.Delegates { | ||
export interface Context extends Internal.Mixin { | ||
$internal: Internal; | ||
@@ -636,3 +638,3 @@ } | ||
} | ||
interface Delegates { | ||
interface Mixin { | ||
middleware(middleware: Middleware, prepend?: boolean): () => boolean; | ||
@@ -670,4 +672,4 @@ } | ||
} | ||
export interface Context extends SelectorService.Delegates { | ||
$selector: SelectorService; | ||
export interface Context extends SelectorService.Mixin { | ||
selector: SelectorService; | ||
} | ||
@@ -681,3 +683,3 @@ export namespace Context { | ||
export namespace SelectorService { | ||
interface Delegates { | ||
interface Mixin { | ||
logger(name: string): Logger; | ||
@@ -695,3 +697,2 @@ any(): Context; | ||
private(...values: string[]): Context; | ||
select(options: Selection): Context; | ||
waterfall<K extends keyof Events>(name: K, ...args: Parameters<Events[K]>): Promisify<ReturnType<Events[K]>>; | ||
@@ -704,4 +705,2 @@ waterfall<K extends keyof Events>(thisArg: ThisParameterType<Events[K]>, name: K, ...args: Parameters<Events[K]>): Promisify<ReturnType<Events[K]>>; | ||
setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): () => boolean; | ||
broadcast(content: string, forced?: boolean): Promise<string[]>; | ||
broadcast(channels: readonly string[], content: string, forced?: boolean): Promise<string[]>; | ||
} | ||
@@ -736,3 +735,2 @@ } | ||
setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): () => boolean; | ||
broadcast(...args: [string, boolean?] | [readonly string[], string, boolean?]): Promise<any[]>; | ||
} | ||
@@ -801,3 +799,3 @@ export * from '@koishijs/utils'; | ||
} | ||
interface Delegates { | ||
interface Mixin { | ||
using(using: readonly string[], callback: Plugin.Function<void>): Fork; | ||
@@ -869,3 +867,3 @@ plugin<T extends Plugin>(plugin: T, config?: boolean | Plugin.Config<T>): Fork; | ||
} | ||
interface Delegates { | ||
interface Mixin { | ||
parallel<K extends keyof Events>(name: K, ...args: Parameters<Events[K]>): Promise<void>; | ||
@@ -913,7 +911,7 @@ parallel<K extends keyof Events>(thisArg: ThisParameterType<Events[K]>, name: K, ...args: Parameters<Events[K]>): Promise<void>; | ||
'internal/warning'(format: any, ...param: any[]): void; | ||
'internal/service'(this: Context, name: string): void; | ||
'internal/service'(name: string): void; | ||
'internal/update'(fork: Fork, config: any): void; | ||
'internal/hook'(this: Lifecycle, name: string, listener: Function, prepend: boolean): () => boolean; | ||
} | ||
export interface Context extends Context.Services, Context.Meta, Lifecycle.Delegates, Registry.Delegates { | ||
export interface Context extends Context.Services, Context.Meta, Lifecycle.Mixin, Registry.Mixin { | ||
} | ||
@@ -944,6 +942,9 @@ declare global { | ||
const Services: string[]; | ||
interface ServiceOptions { | ||
constructor?: any; | ||
interface MixinOptions { | ||
methods?: string[]; | ||
} | ||
function mixin(name: keyof any, options: MixinOptions): void; | ||
interface ServiceOptions extends MixinOptions { | ||
constructor?: any; | ||
} | ||
interface Meta { | ||
@@ -950,0 +951,0 @@ app: App; |
{ | ||
"name": "@koishijs/core", | ||
"description": "Core Features for Koishi", | ||
"version": "4.7.5", | ||
"version": "4.7.6", | ||
"main": "lib/node.js", | ||
"module": "lib/browser.js", | ||
"typings": "lib/index.d.ts", | ||
"engines": { | ||
"node": ">=12.0.0" | ||
}, | ||
"files": [ | ||
@@ -39,3 +36,3 @@ "lib" | ||
"@koishijs/utils": "^5.4.5", | ||
"cordis": "^1.5.5", | ||
"cordis": "^1.6.0", | ||
"fastest-levenshtein": "^1.0.12", | ||
@@ -42,0 +39,0 @@ "minato": "^1.2.1" |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
326960
Updatedcordis@^1.6.0