Add pearcord-integration-worker templates, PearcordIntegrationWorker class, createIntegrationWorker/buildIntegrationWorkerScript, receipt retention get/set, and emit app-event on bot bridge for local worker subscriptions. Co-authored-by: Cursor <[email protected]>
87 lines
2.6 KiB
JavaScript
87 lines
2.6 KiB
JavaScript
'use strict'
|
|
|
|
const EventEmitter = require('bare-events')
|
|
const { APP_EVENT_CATEGORIES } = require('pearcord-app-events')
|
|
const { getWorkerTemplate } = require('pearcord-integration-worker')
|
|
|
|
/**
|
|
* Headless integration worker wired to an active PearcordPlatform guild session.
|
|
*/
|
|
class PearcordIntegrationWorker extends EventEmitter {
|
|
constructor (platform, opts = {}) {
|
|
super()
|
|
if (!platform) throw new Error('platform required')
|
|
this.platform = platform
|
|
this.templateId = null
|
|
this._listener = null
|
|
this._receiptUnwire = null
|
|
this._platformEventUnwire = null
|
|
this._recentEvents = []
|
|
this._recentReceipts = []
|
|
this.maxRecent = opts.maxRecent || 64
|
|
}
|
|
|
|
async start (opts = {}) {
|
|
const templateId = opts.templateId || null
|
|
const tpl = templateId ? getWorkerTemplate(templateId) : null
|
|
this.templateId = templateId
|
|
|
|
let categories = opts.categories
|
|
if (categories == null && tpl) categories = tpl.categories
|
|
if (categories == null) categories = APP_EVENT_CATEGORIES.MESSAGES
|
|
|
|
if (!this.platform.guild?.guild) {
|
|
throw new Error('join a guild first')
|
|
}
|
|
|
|
this._listener = this.platform.createAppListener(categories)
|
|
const onEvent = (payload) => {
|
|
if (tpl?.eventTypes?.length && !tpl.eventTypes.includes(payload.type)) return
|
|
this._pushRecent(this._recentEvents, payload)
|
|
this.emit('event', payload)
|
|
}
|
|
this._listener.on('event', onEvent)
|
|
this.platform.on('app-event', onEvent)
|
|
this._platformEventUnwire = () => this.platform.removeListener('app-event', onEvent)
|
|
|
|
const traceReceipts = tpl?.listensReceipts || templateId === 'delivery-tracer'
|
|
if (traceReceipts) {
|
|
const onReceipt = (receipt) => {
|
|
this._pushRecent(this._recentReceipts, receipt)
|
|
this.emit('receipt', receipt)
|
|
}
|
|
this.platform.on('automation-delivery', onReceipt)
|
|
this._receiptUnwire = () =>
|
|
this.platform.removeListener('automation-delivery', onReceipt)
|
|
}
|
|
|
|
this.emit('started', {
|
|
templateId,
|
|
guildId: this.platform.guild.guild.id,
|
|
categories
|
|
})
|
|
return this
|
|
}
|
|
|
|
_pushRecent (arr, row) {
|
|
arr.push(row)
|
|
if (arr.length > this.maxRecent) arr.splice(0, arr.length - this.maxRecent)
|
|
}
|
|
|
|
async stop () {
|
|
this._listener?._unwire?.()
|
|
this._listener = null
|
|
if (this._platformEventUnwire) {
|
|
this._platformEventUnwire()
|
|
this._platformEventUnwire = null
|
|
}
|
|
if (this._receiptUnwire) {
|
|
this._receiptUnwire()
|
|
this._receiptUnwire = null
|
|
}
|
|
this.emit('stopped')
|
|
}
|
|
}
|
|
|
|
module.exports = { PearcordIntegrationWorker }
|