Skip to content

Commit

Permalink
refa(satori): introduce strict typings
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Jan 12, 2025
1 parent b5c351e commit 3d336e2
Show file tree
Hide file tree
Showing 7 changed files with 31 additions and 29 deletions.
14 changes: 7 additions & 7 deletions packages/core/src/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ export abstract class Adapter<C extends Context = Context, B extends Bot<C> = Bo

export namespace Adapter {
export interface WsClientConfig {
retryLazy?: number
retryTimes?: number
retryInterval?: number
retryLazy: number
retryTimes: number
retryInterval: number
}

export const WsClientConfig: z<WsClientConfig> = z.object({
Expand All @@ -35,7 +35,7 @@ export namespace Adapter {
}).description('连接设置')

export abstract class WsClientBase<C extends Context, B extends Bot<C>> extends Adapter<C, B> {
protected socket: WebSocket
protected socket?: WebSocket
protected connectionId = 0

protected abstract prepare(): Awaitable<WebSocket>
Expand Down Expand Up @@ -79,7 +79,7 @@ export namespace Adapter {
let socket: WebSocket
try {
socket = await this.prepare()
} catch (error) {
} catch (error: any) {
reconnect(initial, error.toString() || `failed to prepare websocket`)
return
}
Expand All @@ -92,7 +92,7 @@ export namespace Adapter {
})

socket.addEventListener('close', ({ code, reason }) => {
if (this.socket === socket) this.socket = null
if (this.socket === socket) this.socket = undefined
logger.debug(`websocket closed with ${code}`)
reconnect(initial, reason.toString() || `failed to connect to ${url}, code: ${code}`)
})
Expand Down Expand Up @@ -125,7 +125,7 @@ export namespace Adapter {
return this.bot.isActive
}

setStatus(status: Status, error: Error = null) {
setStatus(status: Status, error?: Error) {
this.bot.status = status
this.bot.error = error
}
Expand Down
8 changes: 4 additions & 4 deletions packages/core/src/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export abstract class Bot<C extends Context = Context, T = any> {
public platform: string
public features: string[]
public adapter?: Adapter<C, this>
public error?: Error
public error: any
public callbacks: Dict<Function> = {}
public logger: Logger

Expand Down Expand Up @@ -131,7 +131,7 @@ export abstract class Bot<C extends Context = Context, T = any> {

online() {
this.status = Status.ONLINE
this.error = null
this.error = undefined
}

offline(error?: Error) {
Expand All @@ -145,7 +145,7 @@ export abstract class Bot<C extends Context = Context, T = any> {
try {
await this.context.parallel('bot-connect', this)
await this.adapter?.connect(this)
} catch (error) {
} catch (error: any) {
this.offline(error)
}
}
Expand Down Expand Up @@ -193,7 +193,7 @@ export abstract class Bot<C extends Context = Context, T = any> {

async createMessage(channelId: string, content: h.Fragment, referrer?: any, options?: SendOptions) {
const { MessageEncoder } = this.constructor as typeof Bot
return new MessageEncoder(this, channelId, referrer, options).send(content)
return new MessageEncoder!(this, channelId, referrer, options).send(content)
}

async sendMessage(channelId: string, content: h.Fragment, referrer?: any, options?: SendOptions) {
Expand Down
14 changes: 7 additions & 7 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Awaitable, defineProperty, Dict } from 'cosmokit'
import { Bot } from './bot'
import { ExtractParams, InternalRequest, InternalRouter, JsonForm } from './internal'
import { Session } from './session'
import { HTTP } from '@cordisjs/plugin-http'
import { FileResponse, HTTP } from '@cordisjs/plugin-http'
import { Meta, Response, SendOptions } from '@satorijs/protocol'
import h from '@satorijs/element'

Expand Down Expand Up @@ -88,7 +88,7 @@ declare module '@cordisjs/plugin-http' {
HTTP.createConfig = function createConfig(this, endpoint) {
return z.object({
endpoint: z.string().role('link').description('要连接的服务器地址。')
.default(typeof endpoint === 'string' ? endpoint : null)
.default(typeof endpoint === 'string' ? endpoint : undefined!)
.required(typeof endpoint === 'boolean' ? endpoint : false),
headers: z.dict(String).role('table').description('要附加的额外请求头。'),
...this.Config.dict,
Expand Down Expand Up @@ -172,7 +172,7 @@ export class Satori<C extends Context = Context> extends Service<unknown, C> {
public _loginSeq = 0
public _sessionSeq = 0

constructor(ctx?: C) {
constructor(ctx: C) {
super(ctx)
ctx.mixin('satori', ['bots', 'component'])

Expand All @@ -185,12 +185,12 @@ export class Satori<C extends Context = Context> extends Service<unknown, C> {
const { status, body, headers } = await self.handleInternalRoute('GET', url)
if (status >= 400) throw new Error(`Failed to fetch ${_url}, status code: ${status}`)
if (status >= 300) {
const location = headers?.get('location')
const location = headers?.get('location')!
return this.file(location, options)
}
const type = headers?.get('content-type')
const filename = headers?.get('content-disposition')?.split('filename=')[1]
return { data: body, filename, type, mime: type }
return { data: body, filename, type, mime: type } as FileResponse
})

this._internalRouter = new InternalRouter(ctx)
Expand Down Expand Up @@ -223,7 +223,7 @@ export class Satori<C extends Context = Context> extends Service<unknown, C> {
})
}

public bots = new Proxy([], {
public bots = new Proxy([] as Bot<C>[], {
get(target, prop) {
if (prop in target || typeof prop === 'symbol') {
return Reflect.get(target, prop)
Expand Down Expand Up @@ -270,7 +270,7 @@ export class Satori<C extends Context = Context> extends Service<unknown, C> {

toJSON(meta = false): Meta {
return {
logins: meta ? undefined : this.bots.map(bot => bot.toJSON()),
logins: meta ? undefined! : this.bots.map(bot => bot.toJSON()),
proxyUrls: [...this.proxyUrls],
}
}
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class AggregateError extends Error {
export abstract class MessageEncoder<C extends Context = Context, B extends Bot<C> = Bot<C>> {
public errors: Error[] = []
public results: Message[] = []
public session: C[typeof Context.session]
public session!: C[typeof Context.session]

constructor(public bot: B, public channelId: string, public referrer?: any, public options: SendOptions = {}) {}

Expand All @@ -38,7 +38,7 @@ export abstract class MessageEncoder<C extends Context = Context, B extends Bot<
})
for (const key in this.options.session || {}) {
if (key === 'id' || key === 'event') continue
this.session[key] = this.options.session[key]
this.session[key] = this.options.session![key]
}
await this.prepare()
const session = this.options.session ?? this.session
Expand Down
16 changes: 8 additions & 8 deletions packages/core/src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ export class Session<C extends Context = Context> {

public id: number // for backward compatibility
public sn: number
public bot: Bot<C>
public app: C['root']
public bot!: Bot<C>
public app!: C['root']
public event: Event
public locales: string[] = []

Expand All @@ -59,21 +59,21 @@ export class Session<C extends Context = Context> {
}

get isDirect() {
return this.event.channel.type === Channel.Type.DIRECT
return this.event.channel?.type === Channel.Type.DIRECT
}

set isDirect(value) {
(this.event.channel ??= {} as Channel).type = value ? Channel.Type.DIRECT : Channel.Type.TEXT
}

get author(): GuildMember & User {
get author() {
return {
...this.event.user,
...this.event.member,
userId: this.event.user?.id,
username: this.event.user?.name,
nickname: this.event.member?.name,
}
} as GuildMember & User
}

get uid() {
Expand Down Expand Up @@ -114,7 +114,7 @@ export class Session<C extends Context = Context> {
this.event.message.quote = undefined
this.event.message.elements = isNullable(value) ? value : h.parse(value)
if (this.event.message.elements?.[0]?.type === 'quote') {
const el = this.event.message.elements.shift()
const el = this.event.message.elements.shift()!
this.event.message.quote = Resource.decode(el)
}
}
Expand Down Expand Up @@ -146,7 +146,7 @@ export class Session<C extends Context = Context> {
event.message.content = this.content
delete event.message.elements
if (event.message.quote) {
event.message.content = Resource.encode('quote', event.message.quote) + event.message.content
event.message.content = Resource.encode('quote', event.message.quote) + event.message.content!
}
}
return event
Expand All @@ -163,7 +163,7 @@ export function defineAccessor(prototype: {}, name: string, keys: string[]) {
// See https://github.com/satorijs/satori/issues/166
if (value === undefined) return
const _keys = keys.slice()
const last = _keys.pop()
const last = _keys.pop()!
const data = _keys.reduce((data, key) => data[key] ??= {}, this)
data[last] = value
},
Expand Down
2 changes: 2 additions & 0 deletions packages/core/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
"compilerOptions": {
"rootDir": "src",
"outFile": "lib/index.d.ts",
"strict": true,
"noImplicitAny": false,
},
"include": [
"src"
Expand Down
2 changes: 1 addition & 1 deletion packages/protocol/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -492,7 +492,7 @@ export namespace WebSocket {
}

export interface WebSocket {
readonly url?: string
readonly url: string
readonly protocol?: string
readonly readyState?: number
close(code?: number, reason?: string): void
Expand Down

0 comments on commit 3d336e2

Please sign in to comment.