Skip to content

Commit

Permalink
fix: comment stripping should remove multiline comments (#279)
Browse files Browse the repository at this point in the history
  • Loading branch information
cjpearson committed Oct 4, 2024
1 parent 2348417 commit 918e835
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
15 changes: 11 additions & 4 deletions src/syntax.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ const ESM_RE =
const CJS_RE =
/([\s;]|^)(module.exports\b|exports\.\w|require\s*\(|global\.\w)/m;

const COMMENT_RE = /\/\*.+?\*\/|\/\/.*(?=[nr])/g;
const MULTI_LINE_COMMENT_RE = /\/\*.+?\*\//gs;
const SINGLE_LINE_COMMENT_RE = /\/\/.*/g;

const BUILTIN_EXTENSIONS = new Set([".mjs", ".cjs", ".node", ".wasm"]);

Expand All @@ -37,7 +38,9 @@ export function hasESMSyntax(
opts: DetectSyntaxOptions = {},
): boolean {
if (opts.stripComments) {
code = code.replace(COMMENT_RE, "");
code = code
.replace(SINGLE_LINE_COMMENT_RE, "")
.replace(MULTI_LINE_COMMENT_RE, "");

Check warning on line 43 in src/syntax.ts

View check run for this annotation

Codecov / codecov/patch

src/syntax.ts#L41-L43

Added lines #L41 - L43 were not covered by tests
}
return ESM_RE.test(code);
}
Expand All @@ -54,7 +57,9 @@ export function hasCJSSyntax(
opts: DetectSyntaxOptions = {},
): boolean {
if (opts.stripComments) {
code = code.replace(COMMENT_RE, "");
code = code
.replace(SINGLE_LINE_COMMENT_RE, "")
.replace(MULTI_LINE_COMMENT_RE, "");

Check warning on line 62 in src/syntax.ts

View check run for this annotation

Codecov / codecov/patch

src/syntax.ts#L60-L62

Added lines #L60 - L62 were not covered by tests
}
return CJS_RE.test(code);
}
Expand All @@ -68,7 +73,9 @@ export function hasCJSSyntax(
*/
export function detectSyntax(code: string, opts: DetectSyntaxOptions = {}) {
if (opts.stripComments) {
code = code.replace(COMMENT_RE, "");
code = code
.replace(SINGLE_LINE_COMMENT_RE, "")
.replace(MULTI_LINE_COMMENT_RE, "");
}
// We strip comments once hence not passing opts down to hasESMSyntax and hasCJSSyntax
const hasESM = hasESMSyntax(code, {});
Expand Down
2 changes: 2 additions & 0 deletions test/syntax.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ const staticTests = {
const staticTestsWithComments = {
'// They\'re exposed using "export import" so that types are passed along as expected\nmodule.exports={};':
{ hasESM: false, hasCJS: true, isMixed: false },
"/* export * */": { hasESM: false, hasCJS: false, isMixed: false },
"/* \n export * \n */": { hasESM: false, hasCJS: false, isMixed: false },
};

describe("detectSyntax", () => {
Expand Down

0 comments on commit 918e835

Please sign in to comment.