1 | 'use strict'
|
2 |
|
3 | const Transform = require('stream').Transform
|
4 | const Writable = require('stream').Writable
|
5 |
|
6 | const BEGIN_READY_RE = /{begin(\d+)}([\s\S]*){ready\1}/g
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | function createRegexTransformStream(regex) {
|
17 | let buffer = ''
|
18 |
|
19 | const ts = new Transform({ objectMode: true })
|
20 |
|
21 |
|
22 | ts._transform = function (chunk, enc, next) {
|
23 | let lastMatch
|
24 | let match
|
25 | buffer += chunk.toString()
|
26 |
|
27 |
|
28 |
|
29 |
|
30 | while (match = regex.exec(buffer)) {
|
31 | this.push(match)
|
32 | lastMatch = match
|
33 | if (!regex.global) break
|
34 | }
|
35 | if (lastMatch) {
|
36 | buffer = buffer.slice(lastMatch.index + lastMatch[0].length)
|
37 | }
|
38 | next()
|
39 | }
|
40 |
|
41 | return ts
|
42 | }
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 | function createBeginReadyMatchTransformStream() {
|
51 | const ts = new Transform({ objectMode: true })
|
52 |
|
53 | ts._transform = (match, enc, next) => {
|
54 | const data = {
|
55 | cn: match[1],
|
56 | d: match[2].trim(),
|
57 | }
|
58 | next(null, data)
|
59 | }
|
60 | return ts
|
61 | }
|
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 |
|
68 |
|
69 |
|
70 | function createResolverWriteStream() {
|
71 | const ws = new Writable({
|
72 | objectMode: true,
|
73 | })
|
74 | ws._resolveMap = {}
|
75 | ws.addToResolveMap = function(commandNumber, resolve) {
|
76 | if (typeof commandNumber !== 'string') {
|
77 | throw new Error('commandNumber argument must be a string')
|
78 | }
|
79 | if (typeof resolve !== 'function') {
|
80 | throw new Error('resolve argument must be a function')
|
81 | }
|
82 | if (this._resolveMap[commandNumber]) {
|
83 | throw new Error('Command with the same number is already expected')
|
84 | }
|
85 | this._resolveMap[commandNumber] = resolve
|
86 | }
|
87 | ws._write = function (obj, enc, next) {
|
88 | const commandNumber = obj.cn
|
89 | const data = obj.d
|
90 | const resolve = this._resolveMap[commandNumber]
|
91 | if (resolve) {
|
92 | resolve(data)
|
93 | delete this._resolveMap[commandNumber]
|
94 | next()
|
95 | } else {
|
96 | next(new Error(`Command with index ${commandNumber} not found`))
|
97 | }
|
98 | }
|
99 | return ws
|
100 | }
|
101 |
|
102 |
|
103 |
|
104 |
|
105 |
|
106 |
|
107 |
|
108 | function setupResolveWriteStreamPipe(rs) {
|
109 | const rts = createRegexTransformStream(BEGIN_READY_RE)
|
110 | const brmts = createBeginReadyMatchTransformStream()
|
111 | const rws = createResolverWriteStream()
|
112 |
|
113 | return rs.pipe(rts).pipe(brmts).pipe(rws)
|
114 | }
|
115 |
|
116 | module.exports = {
|
117 | createRegexTransformStream,
|
118 | createBeginReadyMatchTransformStream,
|
119 | createResolverWriteStream,
|
120 | BEGIN_READY_RE,
|
121 | setupResolveWriteStreamPipe,
|
122 | }
|