Skip to content

Commit

Permalink
feat(core): update minato to v3 alpha
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Feb 8, 2024
1 parent 64e13d0 commit 61c7d2c
Show file tree
Hide file tree
Showing 10 changed files with 57 additions and 81 deletions.
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -39,6 +39,7 @@
"license": "MIT",
"devDependencies": {
"@cordisjs/eslint-config": "^1.0.4",
"@koishijs/plugin-database-memory": "npm:@minatojs/driver-memory@^3.0.0-alpha.0",
"@octokit/webhooks-types": "^7.3.1",
"@sinonjs/fake-timers": "^6.0.1",
"@types/chai": "^4.3.11",
Expand Down
8 changes: 4 additions & 4 deletions packages/core/package.json
Expand Up @@ -33,10 +33,10 @@
"dependencies": {
"@koishijs/i18n-utils": "^1.0.1",
"@koishijs/utils": "^7.1.2",
"@minatojs/core": "^2.9.0",
"@satorijs/core": "^3.5.0",
"cordis": "^3.7.1",
"@satorijs/core": "^3.5.3",
"cordis": "^3.9.1",
"cosmokit": "^1.5.2",
"fastest-levenshtein": "^1.0.16"
"fastest-levenshtein": "^1.0.16",
"minato": "^3.0.0-alpha.0"
}
}
11 changes: 6 additions & 5 deletions packages/core/src/context.ts
Expand Up @@ -16,9 +16,6 @@ export type EffectScope = cordis.EffectScope<Context>
export type ForkScope = cordis.ForkScope<Context>
export type MainScope = cordis.MainScope<Context>

export interface Service extends Context.Associate<'service'> {}
export class Service<C extends Context = Context> extends satori.Service<C> {}

export { Adapter, Bot, Element, h, Logger, MessageEncoder, Messenger, Quester, Satori, Schema, segment, Universal, z } from '@satorijs/core'
export type { Component, Fragment, Render } from '@satorijs/core'

Expand All @@ -43,7 +40,6 @@ type BeforeEventMap = { [E in keyof Events & string as OmitSubstring<E, 'before-
export interface Events<C extends Context = Context> extends satori.Events<C> {}

export interface Context {
[Context.config]: Context.Config
[Context.events]: Events<this>
[Context.session]: Session<never, never, this>
}
Expand All @@ -66,8 +62,9 @@ export class Context extends satori.Context {
this.provide('schema', new SchemaService(this), true)
this.provide('permissions', new Permissions(this), true)
this.provide('database', undefined, true)
this.provide('model', new DatabaseService(this), true)
this.provide('model', undefined, true)
this.provide('$commander', new Commander(this, this.config), true)
this.plugin(DatabaseService)
}

/** @deprecated use `ctx.root` instead */
Expand Down Expand Up @@ -193,6 +190,10 @@ Context.Config.list.push(Schema.object({
request: Quester.Config,
}))

export class Service<C extends Context = Context> extends satori.Service<C> {
static Context = Context
}

// for backward compatibility
export { Context as App }

Expand Down
58 changes: 10 additions & 48 deletions packages/core/src/database.ts
@@ -1,8 +1,8 @@
import * as utils from '@koishijs/utils'
import { defineProperty, Dict, MaybeArray } from 'cosmokit'
import { Database, Driver, Update } from '@minatojs/core'
import { Fragment, Schema, Universal } from '@satorijs/core'
import { Context, Plugin } from './context'
import { Dict, MaybeArray } from 'cosmokit'
import { Database, Driver, Update } from 'minato'
import { Fragment, Universal } from '@satorijs/core'
import { Context } from './context'

declare module './context' {
interface Events {
Expand Down Expand Up @@ -72,10 +72,9 @@ export interface Tables {
channel: Channel
}

export class DatabaseService extends Database<Tables> {
constructor(protected app: Context) {
super()
defineProperty(this, Context.current, app)
export class DatabaseService extends Database<Tables, Context> {
constructor(ctx: Context) {
super(ctx)

this.extend('user', {
id: 'unsigned(8)',
Expand Down Expand Up @@ -111,7 +110,7 @@ export class DatabaseService extends Database<Tables> {
primary: ['id', 'platform'],
})

app.on('login-added', ({ platform }) => {
ctx.on('login-added', ({ platform }) => {
if (platform in this.tables.user.fields) return
this.migrate('user', { [platform]: 'string(255)' }, async (db) => {
const users = await db.get('user', { [platform]: { $exists: true } }, ['id', platform as never])
Expand Down Expand Up @@ -155,7 +154,7 @@ export class DatabaseService extends Database<Tables> {

getSelfIds(platforms?: string[]): Dict<string[]> {
const selfIdMap: Dict<string[]> = Object.create(null)
for (const bot of this.app.bots) {
for (const bot of this.ctx.bots) {
if (platforms && !platforms.includes(bot.platform)) continue
(selfIdMap[bot.platform] ||= []).push(bot.selfId)
}
Expand Down Expand Up @@ -204,7 +203,7 @@ export class DatabaseService extends Database<Tables> {
this[Context.current].logger('app').warn('broadcast', 'channel not found: ', channels.join(', '))
}

return (await Promise.all(this.app.bots.map((bot) => {
return (await Promise.all(this.ctx.bots.map((bot) => {
const targets = assignMap[bot.platform]?.[bot.selfId]
if (!targets) return Promise.resolve([])
const sessions = targets.map(({ id, guildId, locales }) => {
Expand All @@ -220,40 +219,3 @@ export class DatabaseService extends Database<Tables> {
}))).flat(1)
}
}

// workaround typings
DatabaseService.prototype.extend = function extend(this: DatabaseService, name, fields, config) {
Database.prototype.extend.call(this, name, fields, {
...config,
// driver: this[Context.current].mapping.database,
})
this.app.emit('model', name)
}

// https://github.com/microsoft/TypeScript/issues/15713#issuecomment-499474386
export const defineDriver = <T, >(constructor: Driver.Constructor<T>, schema?: Schema, prepare?: Plugin.Function<Context, T>): Plugin.Object<Context, T> => ({
name: constructor.name,
reusable: true,
Config: schema,
filter: false,
async apply(ctx, config) {
config = { ...config }
await prepare?.(ctx, config)
const driver = new constructor(ctx.model, config)
const key = 'default'

ctx.on('ready', async () => {
await driver.start()
ctx.model.drivers[key] = driver
ctx.model.refresh()
const database = Object.create(ctx.model)
ctx.database = database
})

ctx.on('dispose', async () => {
ctx.database = null
delete ctx.model.drivers[key]
await driver.stop()
})
},
})
2 changes: 1 addition & 1 deletion packages/core/src/filter.ts
@@ -1,5 +1,5 @@
import { defineProperty } from 'cosmokit'
import { Eval } from '@minatojs/core'
import { Eval } from 'minato'
import { Channel, User } from './database'
import { Context } from './context'
import { Session } from './session'
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/index.ts
Expand Up @@ -2,7 +2,7 @@
import { version } from '../package.json'

export * from '@koishijs/utils'
export * from '@minatojs/core'
export * from 'minato'
export * from './bot'
export * from './context'
export * from './database'
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/session.ts
@@ -1,7 +1,7 @@
import { observe } from '@koishijs/utils'
import { Awaitable, isNullable, makeArray } from 'cosmokit'
import { Fragment, h, Logger, Universal } from '@satorijs/core'
import { Eval, executeEval, isEvalExpr } from '@minatojs/core'
import { Eval, executeEval, isEvalExpr } from 'minato'
import * as satori from '@satorijs/core'
import { Argv } from './command'
import { Context } from './context'
Expand Down Expand Up @@ -339,7 +339,7 @@ export class Session<U extends User.Field = never, G extends Channel.Field = nev
}
}
if (!this.app.$commander.resolveCommand(argv)) return
this.app.emit(argv.session, `command/before-attach-${key}` as any, argv, fields)
;(this.app as Context).emit(argv.session, `command/before-attach-${key}` as any, argv, fields)
collectFields(argv, argv.command[`_${key}Fields` as any], fields)
}
if (argv) collect(argv)
Expand Down
6 changes: 3 additions & 3 deletions packages/koishi/package.json
Expand Up @@ -45,11 +45,11 @@
"framework"
],
"dependencies": {
"@koishijs/core": "4.16.8",
"@koishijs/loader": "4.4.4",
"@koishijs/core": "4.17.0-alpha.0",
"@koishijs/loader": "4.5.0-alpha.0",
"@koishijs/plugin-server": "^3.1.7",
"@koishijs/utils": "^7.1.2",
"@satorijs/satori": "^3.5.0",
"@satorijs/satori": "^3.5.3",
"cac": "^6.7.14",
"kleur": "^4.1.5"
},
Expand Down
14 changes: 13 additions & 1 deletion packages/loader/src/index.ts
@@ -1,4 +1,4 @@
import { Logger } from '@koishijs/core'
import { Dict, Logger } from '@koishijs/core'
import { promises as fs } from 'fs'
import * as dotenv from 'dotenv'
import ns from 'ns-require'
Expand Down Expand Up @@ -29,6 +29,18 @@ export default class NodeLoader extends Loader {
})
}

migrateEntry(name: string, config: Dict) {
config ??= {}
if (['database-mysql', 'database-mongo', 'database-postgres'].includes(name)) {
config.database ??= 'koishi'
} else if (name === 'database-sqlite') {
config.path ??= 'data/koishi.db'
} else {
return super.migrateEntry(name, config)
}
return config
}

async migrate() {
if (this.config['port']) {
const { port, host, maxPort, selfUrl } = this.config as any
Expand Down
32 changes: 16 additions & 16 deletions packages/loader/src/shared.ts
Expand Up @@ -205,30 +205,30 @@ export abstract class Loader {
throw new Error('config file not found')
}

private migrateGroup(plugins: Dict) {
const backup = { ...plugins }
for (const key in backup) delete plugins[key]
for (const key in backup) {
protected migrateEntry(name: string, config: any): any {
if (name !== 'group') return
const backup = { ...config }
for (const key in backup) delete config[key]
for (let key in backup) {
if (key.startsWith('$')) {
plugins[key] = backup[key]
config[key] = backup[key]
continue
}
const [name] = key.split(':', 1)
const isGroup = name === 'group' || name === '~group'
if (isGroup) this.migrateGroup(backup[key])
let ident = key.slice(name.length + 1)
if (ident && !this.names.has(ident)) {
this.names.add(ident)
plugins[key] = backup[key]
continue
const [prefix] = key.split(':', 1)
const name = prefix.replace(/^~/, '')
const value = this.migrateEntry(name, backup[key]) ?? backup[key]
let ident = key.slice(prefix.length + 1)
if (!ident || this.names.has(ident)) {
ident = Math.random().toString(36).slice(2, 8)
key = `${prefix}:${ident}`
}
ident = Math.random().toString(36).slice(2, 8)
plugins[`${name}:${ident}`] = backup[key]
this.names.add(ident)
config[key] = value
}
}

async migrate() {
this.migrateGroup(this.config.plugins)
this.migrateEntry('group', this.config.plugins)
}

async readConfig(initial = false) {
Expand Down

0 comments on commit 61c7d2c

Please sign in to comment.