-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.ts
87 lines (75 loc) · 1.65 KB
/
index.ts
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
import util from 'util'
import debugModule from 'debug'
import linewise from 'linewise'
import { Writable, Duplex } from 'stream'
const debug = debugModule('slate-irc-parser')
export default class Parser extends Writable {
nlstream: Duplex
/**
* Initialize IRC parser.
*
* @api public
*/
constructor() {
super()
this.nlstream = linewise.getPerLineBuffer()
this.nlstream.on('data', this.online.bind(this))
this.nlstream.resume()
}
/**
* Write `chunk`.
*
* @param {Buffer} chunk
* @api public
*/
write(chunk: Buffer): boolean {
return this.nlstream.write(chunk)
}
/**
* Parse lines and emit "message" events.
*
* @param {String} line
* @api private
*/
online(line: String): void {
// Remove a single CR at the end of the line if it does exist
line = line.replace(/\r$/, '')
debug('line %s', util.inspect(line))
const orig = line
// prefix
let prefix
if (':' == line[0]) {
const i = line.indexOf(' ')
prefix = line.slice(1, i)
line = line.slice(i + 1)
}
// command
let i = line.indexOf(' ')
if (-1 == i) i = line.length
const command = line.slice(0, i)
line = line.slice(i)
// params
i = line.indexOf(' :')
if (-1 == i) i = line.length
const params = line.slice(1, i)
line = line.slice(i + 2)
const msg = {
prefix: prefix || '',
command: command,
params: params || '',
trailing: line || '',
string: orig,
}
debug('message %j', msg)
this.emit('message', msg)
}
/**
* Emit "end".
*
* @api public
*/
end() {
this.emit('end')
return this
}
}