events.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. import { defineProperty, Promisify } from 'cosmokit'
  2. import { Context } from './context.ts'
  3. import { Fiber, FiberState } from './fiber.ts'
  4. import { DisposableList, symbols } from './utils.ts'
  5. /**
  6. * Return whether an event result should stop a bail-style dispatch.
  7. *
  8. * @param value — a listener's return value.
  9. * @returns `true` unless `value` is `null`, `false`, or `undefined`.
  10. */
  11. export function isBailed(value: any) {
  12. return value !== null && value !== false && value !== undefined
  13. }
  14. /** Extract the parameter tuple from a function type. */
  15. export type Parameters<F> = F extends (...args: infer P) => any ? P : never
  16. /** Extract the return type from a function type. */
  17. export type ReturnType<F> = F extends (...args: any) => infer R ? R : never
  18. /** Extract the explicit `this` type from a function type. */
  19. export type ThisType<F> = F extends (this: infer T, ...args: any) => any ? T : never
  20. /**
  21. * Event dispatch strategy used by the event service.
  22. *
  23. * `emit` runs synchronous listeners without awaiting them, `parallel` awaits
  24. * all listeners together, `serial` awaits them in order until one bails,
  25. * `bail` stops on the first synchronous bail value, and `waterfall` composes
  26. * listeners around a final `next` callback.
  27. */
  28. export type DispatchMode = 'emit' | 'parallel' | 'serial' | 'bail' | 'waterfall'
  29. declare module './context.ts' {
  30. export interface Context {
  31. /* eslint-disable max-len */
  32. /**
  33. * Dispatch an event, running all listeners concurrently.
  34. *
  35. * @param name — the event name.
  36. * @param args — arguments passed to every listener.
  37. * @returns a promise resolving once every listener has settled.
  38. */
  39. parallel<K extends keyof Events>(name: K, ...args: Parameters<Events[K]>): Promise<void>
  40. /** Same as above, with an explicit `this` for listeners (also used for filtering). */
  41. parallel<K extends keyof Events>(thisArg: NoInfer<ThisType<Events[K]>>, name: K, ...args: Parameters<Events[K]>): Promise<void>
  42. /**
  43. * Dispatch an event synchronously, ignoring listener return values.
  44. *
  45. * @param name — the event name.
  46. * @param args — arguments passed to every listener.
  47. */
  48. emit<K extends keyof Events>(name: K, ...args: Parameters<Events[K]>): void
  49. /** Same as above, with an explicit `this` for listeners (also used for filtering). */
  50. emit<K extends keyof Events>(thisArg: NoInfer<ThisType<Events[K]>>, name: K, ...args: Parameters<Events[K]>): void
  51. /**
  52. * Dispatch an event, awaiting listeners in order until one bails.
  53. *
  54. * @param name — the event name.
  55. * @param args — arguments passed to each listener.
  56. * @returns the first bail value (non-null, non-false, non-undefined), if any.
  57. */
  58. serial<K extends keyof Events>(name: K, ...args: Parameters<Events[K]>): Promisify<ReturnType<Events[K]>>
  59. /** Same as above, with an explicit `this` for listeners (also used for filtering). */
  60. serial<K extends keyof Events>(thisArg: NoInfer<ThisType<Events[K]>>, name: K, ...args: Parameters<Events[K]>): Promisify<ReturnType<Events[K]>>
  61. /**
  62. * Dispatch an event, calling listeners in order until one bails.
  63. *
  64. * @param name — the event name.
  65. * @param args — arguments passed to each listener.
  66. * @returns the first bail value (non-null, non-false, non-undefined), if any.
  67. */
  68. bail<K extends keyof Events>(name: K, ...args: Parameters<Events[K]>): ReturnType<Events[K]>
  69. /** Same as above, with an explicit `this` for listeners (also used for filtering). */
  70. bail<K extends keyof Events>(thisArg: NoInfer<ThisType<Events[K]>>, name: K, ...args: Parameters<Events[K]>): ReturnType<Events[K]>
  71. /**
  72. * Dispatch an event whose last argument is a `next` continuation.
  73. *
  74. * Each listener wraps the rest of the chain: calling `next()` invokes the
  75. * next listener (finally the built-in behavior); not calling it vetoes.
  76. *
  77. * @param name — the event name.
  78. * @param args — listener arguments; the final one is the innermost `next`.
  79. * @returns the outermost listener's return value.
  80. */
  81. waterfall<K extends keyof Events>(name: K, ...args: Parameters<Events[K]>): ReturnType<Events[K]>
  82. /** Same as above, with an explicit `this` for listeners (also used for filtering). */
  83. waterfall<K extends keyof Events>(thisArg: NoInfer<ThisType<Events[K]>>, name: K, ...args: Parameters<Events[K]>): ReturnType<Events[K]>
  84. /**
  85. * Register an event listener owned by the current fiber.
  86. *
  87. * @param name — the event name to listen for.
  88. * @param listener — called with the dispatch arguments.
  89. * @param options — listener options; a boolean is shorthand for `prepend`.
  90. * @returns a disposer removing the listener; `true` if it was still registered.
  91. */
  92. on<K extends keyof Events>(name: K, listener: Events[K], options?: boolean | EventOptions): () => boolean
  93. /**
  94. * Same as `on()`, but the listener disposes itself after its first call.
  95. *
  96. * @param name — the event name to listen for.
  97. * @param listener — called at most once with the dispatch arguments.
  98. * @param options — listener options; a boolean is shorthand for `prepend`.
  99. * @returns a disposer removing the listener; `true` if it was still registered.
  100. */
  101. once<K extends keyof Events>(name: K, listener: Events[K], options?: boolean | EventOptions): () => boolean
  102. /* eslint-enable max-len */
  103. }
  104. }
  105. /** Options accepted by `ctx.on()` and `ctx.once()`. */
  106. export interface EventOptions {
  107. /** Add the listener before existing listeners for the same event. */
  108. prepend?: boolean
  109. /** Receive the event regardless of context filter checks. */
  110. global?: boolean
  111. }
  112. /** Registered listener record stored by the event service. */
  113. export interface Hook extends EventOptions {
  114. ctx: Context
  115. callback: (...args: any[]) => any
  116. }
  117. /**
  118. * Event bus installed as `ctx.events` and mixed into every context.
  119. *
  120. * The service supports concurrent, synchronous, serial, bail, and waterfall
  121. * dispatch and automatically disposes listeners with their owning fiber.
  122. */
  123. export class EventsService {
  124. _hooks: Record<keyof any, Hook[]> = {}
  125. constructor(private ctx: Context) {
  126. defineProperty(this, symbols.tracker, {
  127. property: 'ctx',
  128. noShadow: true,
  129. })
  130. this.on('internal/listener', function (this: Context, name, listener, options: EventOptions) {
  131. if (name === 'internal/update' && !options.global) {
  132. const hooks = this.fiber._hooks['internal/update'] ??= new DisposableList()
  133. const method = options.prepend ? 'unshift' : 'push'
  134. return hooks[method](listener)
  135. }
  136. })
  137. this.on('internal/update', function (config, noSave, next) {
  138. const cbs = [...this._hooks['internal/update'] || []]
  139. const _next = () => {
  140. const cb = cbs.shift() ?? next
  141. return cb.call(this, config, noSave, _next)
  142. }
  143. return _next()
  144. }, { global: true, prepend: true })
  145. }
  146. /**
  147. * Resolve listeners for one dispatch and apply context filtering.
  148. *
  149. * @param type — the dispatch mode, reported on `internal/dispatch`.
  150. * @param args — the raw dispatch arguments; consumed up to the event name.
  151. * @returns the matching listener callbacks, bound to the dispatch `this`.
  152. */
  153. dispatch(type: string, args: any[]) {
  154. const thisArg = typeof args[0] === 'object' || typeof args[0] === 'function' ? args.shift() : null
  155. const name: string = args.shift()
  156. if (!name.startsWith('internal/')) {
  157. this.emit('internal/dispatch', type, name, args, thisArg)
  158. }
  159. const filter = thisArg?.[Context.filter]
  160. return (this._hooks[name] || [])
  161. .filter(hook => hook.global || !filter || filter.call(thisArg, hook.ctx))
  162. .map(hook => hook.callback.bind(thisArg))
  163. }
  164. /**
  165. * Run listeners concurrently and wait for all of them.
  166. *
  167. * @param args — optional `this`, the event name, then listener arguments.
  168. * @returns a promise resolving once every listener has settled.
  169. */
  170. async parallel(...args: any[]) {
  171. const results = await Promise.allSettled(this.dispatch('emit', args).map(async cb => cb(...args)))
  172. const errors = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected')
  173. if (errors.length) throw new AggregateError(errors.map(error => error.reason))
  174. }
  175. /**
  176. * Run listeners synchronously without waiting for returned promises.
  177. *
  178. * @param args — optional `this`, the event name, then listener arguments.
  179. */
  180. emit(...args: any[]) {
  181. this.dispatch('emit', args).map(cb => cb(...args))
  182. }
  183. /**
  184. * Run listeners in order, awaiting each, until one returns a bail value.
  185. *
  186. * @param args — optional `this`, the event name, then listener arguments.
  187. * @returns the first bail value (see {@link isBailed}), if any.
  188. */
  189. async serial(...args: any[]) {
  190. for (const cb of this.dispatch('serial', args)) {
  191. const result = await cb(...args)
  192. if (isBailed(result)) return result
  193. }
  194. }
  195. /**
  196. * Run listeners synchronously until one returns a bail value.
  197. *
  198. * @param args — optional `this`, the event name, then listener arguments.
  199. * @returns the first bail value (see {@link isBailed}), if any.
  200. */
  201. bail(...args: any[]) {
  202. for (const cb of this.dispatch('bail', args)) {
  203. const result = cb(...args)
  204. if (isBailed(result)) return result
  205. }
  206. }
  207. /**
  208. * Compose listeners around the final `next` callback.
  209. *
  210. * The last dispatch argument is treated as the innermost `next`. Listeners
  211. * run outermost-first; a listener that does not call `next()` vetoes the
  212. * rest of the chain, including the built-in behavior.
  213. *
  214. * @param args — optional `this`, the event name, listener arguments, then `next`.
  215. * @returns the outermost listener's return value.
  216. */
  217. waterfall(...args: any[]) {
  218. const cbs = this.dispatch('waterfall', args)
  219. const inner = args.pop()
  220. const next = () => {
  221. const cb = cbs.shift() ?? inner
  222. return cb(...args)
  223. }
  224. args.push(next)
  225. return next()
  226. }
  227. /**
  228. * Store a listener record as an effect on the current fiber.
  229. *
  230. * @param label — effect label shown in fiber diagnostics.
  231. * @param hooks — the listener list for one event.
  232. * @param callback — the listener to store.
  233. * @param options — placement and filtering options.
  234. * @returns a disposer that unregisters the listener.
  235. */
  236. register(label: string, hooks: Hook[], callback: any, options: EventOptions): () => void {
  237. const method = options.prepend ? 'unshift' : 'push'
  238. return this.ctx.fiber.effect(() => {
  239. hooks[method]({ ctx: this.ctx, callback, ...options })
  240. return () => this.unregister(hooks, callback)
  241. }, label)
  242. }
  243. /**
  244. * Remove a stored listener record.
  245. *
  246. * @param hooks — the listener list for one event.
  247. * @param callback — the listener to remove.
  248. * @returns `true` if the listener was found and removed.
  249. */
  250. unregister(hooks: Hook[], callback: any) {
  251. const index = hooks.findIndex(hook => hook.callback === callback)
  252. if (index >= 0) {
  253. hooks.splice(index, 1)
  254. return true
  255. }
  256. }
  257. /**
  258. * Register an event listener owned by the current fiber.
  259. *
  260. * The listener is removed automatically when the fiber unloads. Throws
  261. * `CordisError('INACTIVE_EFFECT')` if the fiber is already disposed.
  262. *
  263. * @param name — the event name to listen for.
  264. * @param listener — called with the dispatch arguments.
  265. * @param options — listener options; a boolean is shorthand for `prepend`.
  266. * @returns a disposer removing the listener; `true` if it was still registered.
  267. */
  268. on(name: string | symbol, listener: (...args: any) => any, options?: boolean | EventOptions) {
  269. if (typeof options !== 'object') {
  270. options = { prepend: options }
  271. }
  272. // handle special events
  273. this.ctx.fiber.assertActive()
  274. listener = this.ctx.reflect.bind(listener)
  275. const result = this.bail(this.ctx, 'internal/listener', name, listener, options)
  276. if (result) return result
  277. const hooks = this._hooks[name] ||= []
  278. const label = `ctx.on(${typeof name === 'string' ? JSON.stringify(name) : name.toString()})`
  279. return this.register(label, hooks, listener, options)
  280. }
  281. /**
  282. * Register an event listener that disposes itself after the first call.
  283. *
  284. * @param name — the event name to listen for.
  285. * @param listener — called at most once with the dispatch arguments.
  286. * @param options — listener options; a boolean is shorthand for `prepend`.
  287. * @returns a disposer removing the listener; `true` if it was still registered.
  288. */
  289. once(name: string, listener: (...args: any) => any, options?: boolean | EventOptions) {
  290. const dispose = this.on(name, function (...args: any[]) {
  291. dispose()
  292. return listener.apply(this, args)
  293. }, options)
  294. return dispose
  295. }
  296. }
  297. /**
  298. * Built-in framework events used by core services and extension points.
  299. *
  300. * Plugin and status events track fiber lifecycle, service events observe
  301. * dependency registration, update/get/set/listener events allow core services
  302. * to intercept runtime operations, and `internal/dispatch` exposes event-bus
  303. * diagnostics before public events are delivered.
  304. */
  305. export interface Events {
  306. /** A plugin fiber was created or its uid was cleared on disposal. */
  307. 'internal/plugin'(fiber: Fiber): void
  308. /** A fiber changed lifecycle state; receives the fiber and its previous state. */
  309. 'internal/status'(fiber: Fiber, oldValue: FiberState): void
  310. /** Interception hook for a service binding (no core producer). */
  311. 'internal/service'(this: Context, name: string, value: any): void
  312. /** Waterfall: a fiber config update is being applied; skip `next()` to veto. */
  313. 'internal/update'(this: Fiber, config: any, noSave: boolean, next: () => void): void
  314. /** Waterfall: a service is being read through the context proxy. */
  315. 'internal/get'(ctx: Context, name: string, error: Error, next: () => any): any
  316. /** Waterfall: a service is being written through the context proxy. */
  317. 'internal/set'(ctx: Context, name: string, value: any, error: Error, next: () => boolean): boolean
  318. /** Bail: a listener is being registered; a non-null result replaces registration. */
  319. 'internal/listener'(this: Context, name: string, listener: any, prepend: boolean): void
  320. /** An event is being dispatched to listeners (fired for non-internal events only). */
  321. 'internal/dispatch'(mode: DispatchMode, name: string, args: any[], thisArg: any): void
  322. }