UNPKG

1.85 kBJavaScriptView Raw
1const { 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 Regular expression to execute
6 */
7 function createRegexTransformStream(regex) {
8 let buffer = ''
9
10 const ts = new Transform({
11 transform(chunk, encoding, next) {
12 let lastMatch
13 let match
14 buffer += chunk.toString()
15
16 // thx stream-snitch
17 // https://github.com/dmotz/stream-snitch/blob/master/index.js#L52
18 // eslint-disable-next-line no-cond-assign
19 while (match = regex.exec(buffer)) {
20 ts.push(match)
21 lastMatch = match
22 if (!regex.global) break
23 }
24 if (lastMatch) {
25 buffer = buffer.slice(lastMatch.index + lastMatch[0].length)
26 }
27 next()
28 },
29 objectMode: true,
30 })
31
32 return ts
33}
34
35
36
37
38
39
40const $_lib_markers = require('./lib/markers');
41
42const $_Replaceable = require('./Replaceable');
43
44/* documentary types/rules.xml */
45/**
46 * @typedef {(match: string, ...params: string[]) => string} Replacer
47 *
48 * @typedef {(match: string, ...params: string[]) => Promise.<string>} AsyncReplacer
49 *
50 * @typedef {Object} Rule A replacement rule.
51 * @prop {RegExp} re A Regular expression to match against.
52 * @prop {string|Replacer|AsyncReplacer} replacement A replacement string, or a replacement string function.
53 */
54
55
56module.exports = createRegexTransformStream
57module.exports.makeMarkers = $_lib_markers.makeMarkers
58module.exports.makeCutRule = $_lib_markers.makeCutRule
59module.exports.makePasteRule = $_lib_markers.makePasteRule
60module.exports.Replaceable = $_Replaceable
61//# sourceMappingURL=index.js.map
\No newline at end of file