Skip to content

Commit b015d34

Browse files
authored
fix: address edge case in comment stripping (#1780)
Unforunately, cdfb491 introduced issues with certain edge cases for comments. Fixing the edge case in the regular expression is likely to reintroduce the issue that commit was addressing. This change replaces the regular expression entirely with a function that iterates through the string instead of regular expressions.
1 parent e27aaab commit b015d34

File tree

2 files changed

+36
-6
lines changed

2 files changed

+36
-6
lines changed

lib/autoInject.js

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,37 @@ var FN_ARGS = /^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/;
66
var ARROW_FN_ARGS = /^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/;
77
var FN_ARG_SPLIT = /,/;
88
var FN_ARG = /(=.+)?(\s*)$/;
9-
var STRIP_COMMENTS = /(\/\*(?:[^/]|\/(?!\*))*\*\/)|\/\/.*$/mg;
9+
10+
function stripComments(string) {
11+
let stripped = '';
12+
let index = 0;
13+
let endBlockComment = string.indexOf('*/');
14+
while (index < string.length) {
15+
if (string[index] === '/' && string[index+1] === '/') {
16+
// inline comment
17+
let endIndex = string.indexOf('\n', index);
18+
index = (endIndex === -1) ? string.length : endIndex;
19+
} else if ((endBlockComment !== -1) && (string[index] === '/') && (string[index+1] === '*')) {
20+
// block comment
21+
let endIndex = string.indexOf('*/', index);
22+
if (endIndex !== -1) {
23+
index = endIndex + 2;
24+
endBlockComment = string.indexOf('*/', index);
25+
} else {
26+
stripped += string[index];
27+
index++;
28+
}
29+
} else {
30+
stripped += string[index];
31+
index++;
32+
}
33+
}
34+
return stripped;
35+
}
1036

1137
function parseParams(func) {
12-
const src = func.toString().replace(STRIP_COMMENTS, '');
13-
let match = src.match(FN_ARGS)
38+
const src = stripComments(func.toString());
39+
let match = src.match(FN_ARGS);
1440
if (!match) {
1541
match = src.match(ARROW_FN_ARGS);
1642
}

test/autoInject.js

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -243,13 +243,17 @@ describe('autoInject', () => {
243243
,callback) {
244244
callback(null, true);
245245
},
246-
task3: function task3(callback) {
246+
task3: function task3(task4 /* /* )
247+
*/, callback) {
247248
callback(null, true);
248-
}
249+
},
250+
task4: function task4(callback) {
251+
callback(null, true);
252+
},
249253
},
250254
(err, result) => {
251255
expect(err).to.eql(null);
252-
expect(result).to.deep.eql({task1: true, task2: true, task3: true});
256+
expect(result).to.deep.eql({task1: true, task2: true, task3: true, task4: true});
253257
done();
254258
});
255259
});

0 commit comments

Comments
 (0)