All files / src/lib adapter.ts

0% Statements 0/78
0% Branches 0/21
0% Functions 0/32
0% Lines 0/70

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
/* eslint-disable security/detect-object-injection */
import { AsyncAPIDocumentInterface as AsyncAPIDocument, ServerInterface } from '@asyncapi/parser'
import EventEmitter from 'events'
import uriTemplates from 'uri-templates'
import GleeQuoreConnection from './connection.js'
import GleeQuore from '../index.js'
import GleeQuoreMessage from './message.js'
import { resolveFunctions } from './util.js'
import { AuthProps } from '../index.d.js'
 
export type EnrichedEvent = {
  connection?: GleeQuoreConnection
  serverName: string
  server: ServerInterface
}
 
export type AuthEvent = {
  serverName: string
  authProps: AuthProps
  done: any
  doc: any
}
 
export interface GleeQuoreAdapterOptions {
  glee: GleeQuore;
  serverName: string;
  server: ServerInterface;
  parsedAsyncAPI: AsyncAPIDocument;
}
 
class GleeQuoreAdapter extends EventEmitter {
  private _glee: GleeQuore
  private _serverName: string
  private _AsyncAPIServer: ServerInterface
  private _parsedAsyncAPI: AsyncAPIDocument
  private _channelNames: string[]
  private _operationIds: string[]
  private _channelAddresses: string[]
  private _connections: GleeQuoreConnection[]
  private _serverUrlExpanded: string
 
 
  constructor({ glee, serverName, server, parsedAsyncAPI }: GleeQuoreAdapterOptions) {
    super()
 
    this._glee = glee
    this._serverName = serverName
    this._AsyncAPIServer = server
 
    this._parsedAsyncAPI = parsedAsyncAPI
    this._channelNames = this._parsedAsyncAPI.channels().all().map(e => e.id())
    this._channelAddresses = this._parsedAsyncAPI.channels().all().map(c => c.address())
    this._operationIds = this._parsedAsyncAPI.operations().all().map(o => o.id())
    this._connections = []
 
    const uriTemplateValues = new Map()
    process.env.GLEE_SERVER_VARIABLES?.split(',').forEach((t) => {
      const [localServerName, variable, value] = t.split(':')
      Iif (localServerName === this._serverName) {
        uriTemplateValues.set(variable, value)
      }
    })
    this._serverUrlExpanded = uriTemplates(this._AsyncAPIServer.url()).fill(
      Object.fromEntries(uriTemplateValues.entries())
    )
 
    this.on('error', (err) => {
      this._glee.injectError(err)
    })
    this.on('message', (message, connection) => {
      const conn = new GleeQuoreConnection({
        connection,
        channels: this._connections.find((c) => c.rawConnection === connection)
          .channels,
        serverName,
        server,
        parsedAsyncAPI,
      })
      this._glee.injectMessage(message, serverName, conn)
    })
 
    function enrichEvent(ev): EnrichedEvent {
      return {
        ...ev,
        ...{
          serverName,
          server,
        },
      }
    }
 
    function enrichAuthEvent(ev): AuthEvent {
      return {
        ...ev,
        ...{
          serverName,
          authProps: ev.authProps,
          callback: ev.callback,
          doc: ev.doc,
        },
      }
    }
 
    function createConnection(ev: {
      channels?: string[]
      channel?: string
      connection: any
    }): GleeQuoreConnection {
      let channels = ev.channels
      Iif (!channels && ev.channel) channels = [ev.channel]
 
      return new GleeQuoreConnection({
        connection: ev.connection,
        channels,
        serverName,
        server,
        parsedAsyncAPI,
      })
    }
 
    this.on('auth', (ev) => {
      this._glee.emitInternalEvent('adapter:auth', enrichAuthEvent(ev))
    })
 
    this.on('connect', (ev) => {
      const conn = createConnection(ev)
      this._connections.push(conn)
 
      this._glee.emitInternalEvent(
        'adapter:connect',
        enrichEvent({
          connection: conn,
        })
      )
    })
 
    this.on('server:ready', (ev) => {
      this._glee.emitInternalEvent('adapter:server:ready', enrichEvent(ev))
    })
 
    this.on('server:connection:open', (ev) => {
      const conn = createConnection(ev)
      this._connections.push(conn)
 
      this._glee.emitInternalEvent(
        'adapter:server:connection:open',
        enrichEvent({
          connection: conn,
        })
      )
    })
 
    this.on('reconnect', (ev) => {
      const conn = createConnection(ev)
 
      this._glee.emitInternalEvent(
        'adapter:reconnect',
        enrichEvent({
          connection: conn,
        })
      )
    })
 
    this.on('close', (ev) => {
      const conn = createConnection(ev)
 
      this._glee.emitInternalEvent(
        'adapter:close',
        enrichEvent({
          connection: conn,
        })
      )
    })
  }
 
  get app(): GleeQuore {
    return this._glee
  }
 
  get serverName(): string {
    return this._serverName
  }
 
  get AsyncAPIServer(): ServerInterface {
    return this._AsyncAPIServer
  }
 
  get parsedAsyncAPI(): AsyncAPIDocument {
    return this._parsedAsyncAPI
  }
 
  get channelNames(): string[] {
    return this._channelNames
  }
 
  get operationIds(): string[] {
    return this._operationIds
  }
 
  get channelAddresses(): string[] {
    return this._channelAddresses
  }
 
  get connections(): GleeQuoreConnection[] {
    return this._connections
  }
 
  get serverUrlExpanded(): string {
    return this._serverUrlExpanded
  }
 
  async resolveProtocolConfig(protocol: string) {
    Iif (!this.app.options[protocol]) return undefined
    const protocolConfig = { ...this.app.options[protocol] }
    Iif (!protocolConfig) return undefined
 
    await resolveFunctions(protocolConfig)
    return protocolConfig
  }
 
  async getAuthConfig(auth: any) {
    Iif (!auth) return
    Iif (typeof auth !== 'function') {
      await resolveFunctions(auth)
      return auth
    }
 
    return await auth({
      serverName: this._serverName,
      parsedAsyncAPI: this._parsedAsyncAPI,
    })
  }
 
  /**
   * Returns a list of the channels a given adapter has to subscribe to.
   */
  getSubscribedChannels(): string[] {
    return this._channelNames.filter((channelName) => {
      const channel = this._parsedAsyncAPI.channels().get(channelName)
      Iif (channel.operations().filterByReceive().length > 0) return true
 
      const channelServers = channel.servers()
        ? channel.servers()
        : channel.extensions().get('x-servers')?.value() || this._parsedAsyncAPI.allServers()
      return channelServers.includes(this._serverName)
    })
  }
 
  /**
   * Connects to the remote server.
   */
  async connect(): Promise<any> {
    throw new Error('Method `connect` is not implemented.')
  }
 
  /**
   * Sends a message to the remote server.
   *
   * @param {GleeQuoreMessage} message The message to send.
   */
 
  async send(
    message: GleeQuoreMessage /* eslint-disable-line @typescript-eslint/no-unused-vars */
  ): Promise<any> {
    throw new Error('Method `send` is not implemented.')
  }
}
 
export default GleeQuoreAdapter