New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@koishijs/core

Package Overview
Dependencies
Maintainers
1
Versions
167
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@koishijs/core - npm Package Compare versions

Comparing version 4.7.3 to 4.7.4

2

lib/browser.js

@@ -1,2 +0,2 @@

var Be=Object.defineProperty;var f=(m,e)=>Be(m,"name",{value:e,configurable:!0});var G=(m,e)=>()=>(e||m((e={exports:{}}).exports,e),e.exports);var he=G((Ct,Re)=>{Re.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 fe=G((vt,Ke)=>{Ke.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 ge=G((wt,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 xe=G((St,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 be=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 je=G((Fn,bt)=>{bt.exports={name:"@koishijs/core",description:"Core Features for Koishi",version:"4.7.3",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.3.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.3.2","fastest-levenshtein":"^1.0.12",minato:"^1.1.0"}}});import{defineProperty as Z,Schema as _,Time as me}from"@koishijs/utils";import{App as R}from"cordis";export*from"@koishijs/utils";export*from"cordis";export*from"minato";import{isNullable as ye,Logger as Ne,Random as ze,Time as ee}from"@koishijs/utils";import{Context as Ce}from"cordis";var ve=new Ne("i18n"),we=Symbol("template"),te=class{constructor(e){this._data={};this._formatters={};this._presets={};this.define("",{"":""}),this.define("zh",he()),this.define("en",fe()),this.define("ja",ge()),this.define("fr",xe()),this.define("zh-tw",be()),this.registerBuiltins()}set(e,t,n){if(t.includes("@")||typeof n=="string"){let i=this._data[e],[r,c]=t.slice(0,-1).split("@");c&&(n[we]=c),!ye(i[r])&&!e.startsWith("$")&&ve.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[we],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[c,...l]=r.split("|"),o=c.trim().split("."),d=t;for(let h of o)if(d=d[h],ye(d))return"";for(let h of l){let x=h.trim().match(/(\w+)(?:\((.+)\))?/),y=this._formatters[x[1]];if(!y)throw new Error(`Formatter "${x[1]}" not found`);let U=x[2]?x[2].split(",").map(v=>v.trim()):[];d=y(d,U,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 c of i)for(let l of["$"+c,c]){let o=this._data[l]?.[r];if(o!==void 0)return this.render(o,n,c)}return ve.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 c=ee[e[r]],l=ee[e[r+1]];if(t>=c-l/2){t+=l/2;let o=Math.floor(t/c)+" "+this.text([i],["general."+e[r]],{});return t%c>l&&(o+=` ${Math.floor(t%c/l)} `+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(([c,l])=>this.render(t.item,{key:c,value:l},i));return r.unshift(this.render(t.header,n,i)),r.push(this.render(t.footer,n,i)),r.join(`
var Be=Object.defineProperty;var f=(m,e)=>Be(m,"name",{value:e,configurable:!0});var G=(m,e)=>()=>(e||m((e={exports:{}}).exports,e),e.exports);var he=G((Ct,Re)=>{Re.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 fe=G((vt,Ke)=>{Ke.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 ge=G((wt,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 xe=G((St,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 be=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 je=G((Fn,bt)=>{bt.exports={name:"@koishijs/core",description:"Core Features for Koishi",version:"4.7.4",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.3.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.3.3","fastest-levenshtein":"^1.0.12",minato:"^1.1.0"}}});import{defineProperty as Z,Schema as _,Time as me}from"@koishijs/utils";import{App as R}from"cordis";export*from"@koishijs/utils";export*from"cordis";export*from"minato";import{isNullable as ye,Logger as Ne,Random as ze,Time as ee}from"@koishijs/utils";import{Context as Ce}from"cordis";var ve=new Ne("i18n"),we=Symbol("template"),te=class{constructor(e){this._data={};this._formatters={};this._presets={};this.define("",{"":""}),this.define("zh",he()),this.define("en",fe()),this.define("ja",ge()),this.define("fr",xe()),this.define("zh-tw",be()),this.registerBuiltins()}set(e,t,n){if(t.includes("@")||typeof n=="string"){let i=this._data[e],[r,c]=t.slice(0,-1).split("@");c&&(n[we]=c),!ye(i[r])&&!e.startsWith("$")&&ve.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[we],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[c,...l]=r.split("|"),o=c.trim().split("."),d=t;for(let h of o)if(d=d[h],ye(d))return"";for(let h of l){let x=h.trim().match(/(\w+)(?:\((.+)\))?/),y=this._formatters[x[1]];if(!y)throw new Error(`Formatter "${x[1]}" not found`);let U=x[2]?x[2].split(",").map(v=>v.trim()):[];d=y(d,U,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 c of i)for(let l of["$"+c,c]){let o=this._data[l]?.[r];if(o!==void 0)return this.render(o,n,c)}return ve.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 c=ee[e[r]],l=ee[e[r+1]];if(t>=c-l/2){t+=l/2;let o=Math.floor(t/c)+" "+this.text([i],["general."+e[r]],{});return t%c>l&&(o+=` ${Math.floor(t%c/l)} `+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(([c,l])=>this.render(t.item,{key:c,value:l},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 Se}from"minato";import{Context as ke}from"cordis";var Q;(function(t){let m;(function(i){i[i.ignore=1]="ignore"})(m=t.Flag||(t.Flag={})),t.fields=[]})(Q||(Q={}));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 Se{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"]})}setDriver(e,t){super.setDriver(e,t),Object.keys(this.drivers).length?this.ctx.database=this:this.ctx.database=null}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){Se.prototype.extend.call(this,e,t,n),this.ctx.emit("model",e)},"extend");ke.service("database");ke.service("model",{constructor:X});import{coerce as lt,defineProperty as dt,escapeRegExp as ut,makeArray as pt}from"@koishijs/utils";import{Context as Pe}from"cordis";import{Logger as st,paramCase as ot,remove as at,Schema as P}from"@koishijs/utils";import{Context as Fe}from"cordis";import{Logger as De,makeArray as nt,Random as it,sleep as rt}from"@koishijs/utils";import{Context as $e}from"cordis";import{coerce as He,Logger as Ve,remove as K,Schema as H}from"@koishijs/utils";import{camelCase as _e,escapeRegExp as Ae,paramCase as Te,segment as ne,Time as We}from"@koishijs/utils";var ie=`"'“‘`,re=`"'”’`,j;(function(C){let m={};function e(s,a,u){m[s]={terminator:a,parse:u}}C.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=ie.indexOf(a[0]),S=re[g],A="";S&&(a=a.slice(1),u=`${S}(?=${u})|$`),u+=`|${Object.keys({...this.bracs,...m}).map(Ae).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:E,terminator:O}=this.bracs[w[0]],$=E?.(a)||this.parse(a,O);a=$.rest,p.inters.push({...$,pos:A.length,initiator:w[0]})}else{let E=w[0]===S,O=a.slice(w.index+ +E);return p.rest=O.trimStart(),p.quoted=E,p.terminator=w[0],E?p.terminator+=O.slice(0,-p.rest.length):S&&(A=ie[g]+A,p.inters.forEach($=>$.pos+=1)),p.content=A,S==="'"&&C.revert(p),p}}}parse(a,u=""){let p=[],g=a,S="",A=`\\s+|[${Ae(u)}]|$`;for(;g&&!(u&&g.startsWith(u));){let b=this.parseToken(g,A);p.push(b),g=b.rest,S=b.terminator,delete b.rest}return g.startsWith(u)&&(g=g.slice(1)),a=a.slice(0,-(g+S).length),{tokens:p,rest:g,source:a}}stringify(a){let u=a.tokens.reduce((p,g)=>(g.quoted&&(p+=ie[re.indexOf(g.terminator[0])]||""),p+g.content+g.terminator),"");return a.rest&&!re.includes(u[u.length-1])||a.initiator?u.slice(0,-1):u}}f(t,"Tokenizer"),C.Tokenizer=t;let n=new t;function i(s,a=""){return n.parse(s,a)}C.parse=i,f(i,"parse");function r(s){return n.stringify(s)}C.stringify=r,f(r,"stringify");function c(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)}}C.revert=c,f(c,"revert");function l(s){return typeof s=="string"?d[s]||{}:{}}f(l,"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}}C.createDomain=h,f(h,"createDomain"),h("rawtext",s=>s),h("string",s=>s),h("text",s=>s,{greedy:!0}),h("rawtext",s=>ne.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=We.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=ne.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=ne.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[S,A]=p.split(":"),b=A?A.trim():void 0;u.push({name:S,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 U(s,a,u,p,g={}){let{name:S,type:A,fallback:b}=g,w=s===""&&!a;if(w&&b!==void 0)return b;let E=o(A);if(E)try{return E(s,p.session)}catch($){if(!p.session)p.error=`internal.invalid-${u}`;else{let I=p.session.text($.message||"internal.check-syntax");p.error=p.session.text(`internal.invalid-${u}`,[S,I])}return}if(w)return!0;if(a)return s;let O=+s;return O*0==0?O:s}C.parseValue=U,f(U,"parseValue");class v{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=Te(a),S=u.replace(/(?<=^|\s)[\w\x80-\uffff].*/,""),A=u.slice(S.length),b=S.replace(/(?<=^|\s)(<[^<]+>|\[[^[]+\]).*/,""),w=S.slice(b.length);b=b.trim()||"--"+g;let E=[],O=[];for(let T of b.trim().split(",")){T=T.trimStart();let W=T.replace(/^-+/,"");!W||!T.startsWith("-")?O.push(T):E.push(W)}!("value"in p)&&!E.includes(g)&&(b+=", --"+g);let $=y(w);$.stripped&&(b+=" "+$.stripped);let I=this._options[a]||={...F.defaultOptionConfig,...$[0],...p,name:a,values:{},valuesSyntax:{},syntax:b},k=`commands.${this.name}.options.${a}`,D=typeof I.fallback;"value"in p?(k+="."+p.value,I.valuesSyntax[p.value]=b,E.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("",k,A),this._assignOption(I,E,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=C.parse(a,u));let S=this.name+" "+C.stringify(a);for(;!a.error&&a.tokens.length;){let A=a.tokens[0],{content:b,quoted:w}=A,E=this._arguments[p.length];if(b[0]!=="-"&&l(E?.type).greedy){p.push(C.parseValue(C.stringify(a),!0,"argument",a,E));break}a.tokens.shift();let O,$,I;if(!w&&(O=this._symbolicOptions[b]))$=[Te(O.name)];else{if(b[0]!=="-"||w){p.push(C.parseValue(b,w,"argument",a,E||{type:"string"}));continue}let k=0,D;for(;k<b.length&&b.charCodeAt(k)===45;++k);if(b.slice(k,k+3)==="no-"&&!this._namedOptions[b.slice(k)]){D=b.slice(k+3),g[_e(D)]=!1;continue}let T=k+1;for(;T<b.length&&b.charCodeAt(T)!==61;T++);D=b.slice(k,T),$=k>1?[D]:D,I=b.slice(++T),O=this._namedOptions[$[$.length-1]]}if(w=!1,!I){let{type:k}=O||{};if(l(k).greedy)I=C.stringify(a),w=!0,a.tokens=[];else if(k!=="boolean"&&a.tokens.length&&(k||a.tokens[0]?.content!=="-")){let D=a.tokens.shift();I=D.content,w=D.quoted}}for(let k=0;k<$.length;k++){let D=$[k],T=this._namedOptions[D],W=T?T.name:_e(D);if(T&&D in T.values)g[W]=T.values[D];else{let Me=k+1<$.length?"":I;g[W]=C.parseValue(Me,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:S,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 S=u[g];S===!0?p+=` --${g}`:S===!1?p+=` --no-${g}`:p+=` --${g} ${this.stringifyArg(S)}`}for(let g of a)p+=" "+this.stringifyArg(g);return p}}f(v,"CommandBase"),C.CommandBase=v})(j||(j={}));var se=new Ve("command"),oe=class extends j.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={...oe.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&&(K(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(()=>{K(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(()=>K(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.match(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(()=>K(this._checkers,e)),this}action(e,t=!1){return t?this._actions.unshift(e):this._actions.push(e),this._disposables?.push(()=>K(this._actions,e)),this}use(e,...t){return e(this,...t)}async execute(e,t=M.compose){e.command??=this,e.args??=[],e.options??={};let{args:n,options:i,error:r}=e;if(r)return r;se.level>=3&&se.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 c=0,l=this._actions.map(d=>async()=>await d.call(this,e,...n));l.push(t);let o=l.length;e.next=async d=>{if(d!==void 0&&(l.push(h=>M.compose(d,h)),l.length>M.MAX_DEPTH))throw new Error(`middleware stack exceeded ${M.MAX_DEPTH}`);return l[c++]?.(e.next)};try{let d=await e.next();if(typeof d=="string")return d}catch(d){if(c===o)throw d;let h=He(d);se.warn(`${e.source||=this.stringify(n,i)}

@@ -3,0 +3,0 @@ ${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)),K(this.ctx.$commander._commandList,this),this.parent&&K(this.parent.children,this)}},F=oe;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 Qe,valueMap as Xe}from"@koishijs/utils";function ae(m){m.before("parse",(t,n)=>{let i=j.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 c of m.$commander._shortcuts){let{name:l,fuzzy:o,command:d,prefix:h,options:x={},args:y=[]}=c;if(!(h&&!i.appel||!d.ctx.match(n)))if(typeof l=="string"){if(!o&&t!==l||!t.startsWith(l))continue;let U=t.slice(l.length);if(o&&!i.appel&&U.match(/^\S/))continue;let v=j.parse(U.trim());return v.session=n,v=d.parse(v,"",[...y],{...x}),v.command=d,v}else{let v=function(C){return typeof C!="string"?C:(C=C.replace(/\$\$/g,"@@__PLACEHOLDER__@@"),U.forEach((s,a)=>{!a||a>9||(C=C.replace(new RegExp(`\\$${a}`,"g"),(s||"").replace(/\$/g,"@@__PLACEHOLDER__@@")))}),C.replace(/@@__PLACEHOLDER__@@/g,"$"))};f(v,"escape");let U=l.exec(t);if(!U)continue;return{command:d,args:y.map(v),options:Xe(x,v)}}}}),m.before("attach",t=>{Qe(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:c}=t;if(r.help&&i._options.help)return e(c,i.name);if(i._actions.length)return;let l=n.shift()||"",o=m.$commander.getCommand(i.name+"."+l);if(o){let d=c.__redirected_commands||=[`(${i.name}${i._aliases.length!==0?"|"+i._aliases.join("|"):""})`];d.push(l);let h=new RegExp(`^${d.join("[. ]")}( |$)`);return t=j.parse(c.parsed.content.replace(h,"")),t.session=c,t=o.parse(t),c.execute({...t,command:o})}else return e(c,i.name)})}f(ae,"runtime");function ce(m){m.on("command-added",e=>{e.userFields(({tokens:t,command:n,options:i={}},r)=>{if(!n)return;let{authority:c}=n.config,l=c>0;for(let{name:o,authority:d}of Object.values(n._options))o in i?d>0&&(l=!0):t&&d>0&&(l=!0);l&&r.add("authority")})}),m.before("command/execute",e=>{let{session:t,options:n,command:i}=e;if(!t.user)return;function r(c,...l){return i.config.showWarning?t.text(c,l):""}if(f(r,"sendHint"),t.user.authority&&i.getConfig("authority",t)>t.user.authority)return r("internal.low-authority");for(let c of Object.values(i._options))if(c.name in n&&c.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 c(l,...o){return i.config.showWarning?r.text(l,o):""}if(f(c,"sendHint"),i.config.checkArgCount){if((i._arguments[t.length]||{}).required)return c("internal.insufficient-arguments");let o=i._arguments[i._arguments.length-1]||{};if(t.length>i._arguments.length&&o.type!=="text"&&!o.variadic)return c("internal.redunant-arguments")}if(i.config.checkUnknown){let l=Object.keys(n).filter(o=>!i._options[o]);if(l.length)return c("internal.unknown-option",l.join(", "))}})}f(ce,"validate");var V=class{constructor(e,t={}){this.ctx=e;this.config=t;this._commandList=[];this._commands=new Map;this._shortcuts=[];e.plugin(ae),e.plugin(ce)}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(),c=e.slice(r.length),l=r.split(/(?=[./])/g),o,d,h=[];if(l.forEach((y,U)=>{let v=y.charCodeAt(0),C=v===46?o.name+y:v===47?y.slice(1):y,s=this.getCommand(C);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(C,c,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(V,"Commander"),V.key="$commander";$e.service(V.key,{constructor:V,methods:["command"]});import{defineProperty as q,isNullable as Je,Logger as Ye,makeArray as Ze,observe as le,Random as et,segment as tt}from"@koishijs/utils";var de=new Ye("session"),J=class{constructor(e,t){Object.assign(this,t),this.platform=e.platform,q(this,"app",e.ctx.app),q(this,"bot",e),q(this,"user",null),q(this,"channel",null),q(this,"id",et.id()),q(this,"_queuedTasks",[]),q(this,"_queuedTimeout",null)}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=tt.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=>{de.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=>(de.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(Je(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 c=await n.database.getChannel(i,e,t);if(c)return c;let l=await this.resolveValue(n.options.autoAssign)?this.selfId:"";if(l)return n.database.createChannel(i,e,{assignee:l,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}`,c=this.app.$internal._channelCache.get(this.id,r);if(c){for(let o in c)n.delete(o);if(!n.size)return c}let l=await this.getChannel(e,[...n]);return c=this.app.$internal._channelCache.get(this.id,r),c?c.$merge(l):(c=le(l,o=>this.app.database.setChannel(i,e,o),`channel ${r}`),this.app.$internal._channelCache.set(this.id,r,c)),c}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 c=await this.resolveValue(n.options.autoAuthorize);if(c)return n.database.createUser(i,e,{authority:c});{let l=n.model.tables.user.create();return Object.assign(l,{[i]:e,authority:c}),l}}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 l in r)t.delete(l);if(!t.size)return this.user=r}if(this.author?.anonymous){let l=this.app.model.tables.user.create();l[i]=n,l.authority=await this.resolveValue(this.app.options.autoAuthorize);let o=le(l,()=>Promise.resolve());return this.user=o}let c=await this.getUser(n,[...t]);return r=this.app.$internal._userCache.get(this.id,this.uid),r?r.$merge(c):(r=le(c,l=>this.app.database.setUser(this.platform,n,l),`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=Ze(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:c}of r.tokens)c.forEach(i);!this.resolve(r)||(this.app.emit(r.session,`command/before-attach-${e}`,r,n),Ie(r,F[`_${e}Fields`],n),Ie(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=j.parse(e)),e.session=this,e.tokens){for(let r of e.tokens){let{inters:c}=r,l=[];for(let o=0;o<c.length;++o)l.push(await this.execute(c[o],!0));for(let o=c.length-1;o>=0;--o){let{pos:d}=c[o];r.content=r.content.slice(0,d)+l[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 de.warn(new Error(`cannot find command ${e.name}`)),"";let{command:n}=e;if(!n.ctx.match(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=Ee(this);return this.app.middleware(async(n,i)=>t&&Ee(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 Ee(m){return""+m.userId+m.channelId}f(Ee,"getSessionId");function Ie(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(Ie,"collectFields");var Oe=new De("bot"),B=class{constructor(e,t){this.adapter=e;this.config=t;this.id=it.id();this.ctx=e.ctx,this.app=this.ctx.app,this.platform=t.platform||e.platform,this.logger=new De(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",Oe.success("logged in to %s as %c (%s)",this.platform,this.username,this.selfId)}reject(e){this.error=e,this.status="offline",Oe.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 rt(n);try{let[c,l]=nt(e[r]);i.push(...await this.sendMessage(c,t,l))}catch(c){this.ctx.logger("bot").warn(c)}}return i}};f(B,"Bot");(function(e){e.library={}})(B||(B={}));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,ot(n),e)}};f(z,"Adapter");var ct=new st("app");(function(c){c.redirect=Symbol("koishi.adapter.redirect"),c.library={},c.configMap={};function n(l,o){return o?`${l}.${o}`:l}c.join=n,f(n,"join");function i(l,o,...d){let h=l+"-adapter";l=l.toLowerCase(),B.library[l]=o;let x;if(typeof d[0]=="function")c.library[l]=d[0],x=d[0].schema;else{let C=function(s){if(s.type==="union"||s.type==="intersect")s.list.forEach(C);else if(s.type==="object")for(let a in s.dict)v.dict[a]=new P(s.dict[a]),v.dict[a].meta={...s.dict[a].meta,required:!1};else throw new Error("cannot flatten bot schema")};f(C,"flatten"),c.library[l]={[c.redirect]:d[1]},x=c.library[l].schema=P.union([]).description("机器人要使用的协议。");let v=P.object({protocol:P.string()});for(let s in d[0])c.library[n(l,s)]=d[0][s],C(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(v,s=>{if(s.protocol)throw new Error(`unknown protocol "${s.protocol}"`);return s.protocol=d[1](s),ct.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,v=>({bots:[v]}))])]);function U(v,C={}){v.emit("adapter",l),c.configMap[l]=C;for(let s of C.bots)v.bots.create(l,s,o)}return f(U,"apply"),{name:h,Config:y,apply:U}}c.define=i,f(i,"define");class r extends Array{constructor(o){super();this.ctx=o;this.adapters={}}get caller(){return this[Fe.current]||this.ctx}get(o){return this.find(d=>d.sid===o)}create(o,d,h){h||=B.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=at(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=c.library[h];if(!x)throw new Error(`unsupported protocol "${h}"`);if(x[c.redirect])return d.protocol=x[c.redirect](d),this.resolve(o,d);let y=new x(this.caller,c.configMap[o]);return y.platform=o,this.caller.on("dispose",()=>{delete this.adapters[h]}),this.adapters[h]=y}}f(r,"BotList"),c.BotList=r})(z||(z={}));Fe.service("bots",{constructor:z.BotList});function mt(m,e="",t=""){return m.length?new RegExp(`^${e}(${m.map(ut).join("|")})${t}`):/$^/}f(mt,"createLeadingRE");var M;(function(t){t.MAX_DEPTH=64;async function e(n,i){return typeof n=="function"?n(i):n}t.compose=e,f(e,"compose")})(M||(M={}));var ue=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[Pe.current]||this.ctx}middleware(e,t=!1){return this.caller.lifecycle.register("middleware",this._hooks,e,t)}prepare(){this._nameRE=mt(pt(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,c=null,l=/^\[CQ:(\w+)((,\w+=[^,\]]*)*)\]/,o=await e.preprocess();e.subtype!=="private"&&(n=o.match(l))&&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)||(c=d,o=o.slice(d.length));if(dt(e,"parsed",{content:o,appel:r,prefix:c}),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&Q.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.match(e)).map(([,o])=>o.bind(null,e)),n=0,i="",r="",{prettyErrors:c}=this.ctx.app.options,l=f(async o=>{if(c&&(r=new Error().stack.split(`

@@ -955,5 +955,5 @@ import * as utils from '@koishijs/utils';

protected stop(): Awaitable<void>;
protected fork(ctx: Context, config: any): void;
protected fork?(ctx: Context, config: any): void;
constructor(ctx: Context, name: string, immediate?: boolean);
get caller(): Context;
}
{
"name": "@koishijs/core",
"description": "Core Features for Koishi",
"version": "4.7.3",
"version": "4.7.4",
"main": "lib/node.js",

@@ -39,3 +39,3 @@ "module": "lib/browser.js",

"@koishijs/utils": "^5.4.5",
"cordis": "^1.3.2",
"cordis": "^1.3.3",
"fastest-levenshtein": "^1.0.12",

@@ -42,0 +42,0 @@ "minato": "^1.1.0"

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc