1 | const { Transform } = require('stream');
|
2 |
|
3 | /**
|
4 | * Create a Transform stream which will maintain a buffer with data received from a Readable stream and write data when the buffer can be matched against the regex. It will push the whole match object (or objects when the g flag is used) returned by `/regex/.exec(buffer)`.
|
5 | * @param {!RegExp} regex The regular expression to execute.
|
6 | */
|
7 | function createRegexTransformStream(regex) {
|
8 | let buffer = ''
|
9 |
|
10 | /** @suppress {checkTypes} */
|
11 | const ts = new Transform({
|
12 | transform(chunk, encoding, next) {
|
13 | let lastMatch
|
14 | let match
|
15 | buffer += chunk.toString()
|
16 |
|
17 | // thx stream-snitch
|
18 | // https://github.com/dmotz/stream-snitch/blob/master/index.js#L52
|
19 | // eslint-disable-next-line no-cond-assign
|
20 | while (match = regex.exec(buffer)) {
|
21 | ts.push(match)
|
22 | lastMatch = match
|
23 | if (!regex.global) break
|
24 | }
|
25 | if (lastMatch) {
|
26 | buffer = buffer.slice(lastMatch.index + lastMatch[0].length)
|
27 | }
|
28 | next()
|
29 | },
|
30 | objectMode: true,
|
31 | })
|
32 |
|
33 | return ts
|
34 | }
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 | const $_lib_markers = require('./lib/markers');
|
41 |
|
42 | const $_Replaceable = require('./Replaceable');
|
43 | const $_SyncReplaceable = require('./SyncReplaceable');
|
44 |
|
45 | /* documentary types/rules.xml */
|
46 | /**
|
47 | * @suppress {nonStandardJsDocs}
|
48 | * @typedef {_restream.Replacer} Replacer
|
49 | */
|
50 | /**
|
51 | * @suppress {nonStandardJsDocs}
|
52 | * @typedef {function(this:*, ...string): string} _restream.Replacer
|
53 | */
|
54 | /**
|
55 | * @suppress {nonStandardJsDocs}
|
56 | * @typedef {_restream.AsyncReplacer} AsyncReplacer
|
57 | */
|
58 | /**
|
59 | * @suppress {nonStandardJsDocs}
|
60 | * @typedef {function(this:*, ...string): !Promise<string>} _restream.AsyncReplacer
|
61 | */
|
62 | /**
|
63 | * @suppress {nonStandardJsDocs}
|
64 | * @typedef {_restream.Rule} Rule A replacement rule.
|
65 | */
|
66 | /**
|
67 | * @suppress {nonStandardJsDocs}
|
68 | * @typedef {Object} _restream.Rule A replacement rule.
|
69 | * @prop {!RegExp} re The regular expression to match input against.
|
70 | * @prop {!(string|_restream.Replacer|_restream.AsyncReplacer)} replacement The replacement string, or the replacer function.
|
71 | */
|
72 |
|
73 |
|
74 | module.exports = createRegexTransformStream
|
75 | module.exports.makeMarkers = $_lib_markers.makeMarkers
|
76 | module.exports.makeCutRule = $_lib_markers.makeCutRule
|
77 | module.exports.makePasteRule = $_lib_markers.makePasteRule
|
78 | module.exports.Replaceable = $_Replaceable
|
79 | module.exports.SerialAsyncReplaceable = $_Replaceable.SerialAsyncReplaceable
|
80 | module.exports.SyncReplaceable = $_SyncReplaceable |
\ | No newline at end of file |