All files / cli/src/vite strip-comments-plugin.ts

100% Statements 12/12
100% Branches 2/2
100% Functions 2/2
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47                                2x     15x   15x           15x 7x         8x 8x   8x 10x 10x     8x 8x        
import type { Comment } from 'acorn';
import { parse } from 'acorn';
import type { Plugin } from 'vite';
 
/**
 * Rollup plugin that strips comments from bundled code using AST parsing.
 *
 * SES rejects code containing `import(` patterns, even when they appear
 * in comments. This plugin uses Acorn to definitively identify comment nodes
 * and removes them to avoid triggering that detection.
 *
 * Uses the `renderChunk` hook to process the final output.
 *
 * @returns A Rollup plugin.
 */
export function stripCommentsPlugin(): Plugin {
  return {
    name: 'strip-comments',
    renderChunk(code) {
      const comments: Comment[] = [];
 
      parse(code, {
        ecmaVersion: 'latest',
        sourceType: 'script',
        onComment: comments,
      });
 
      if (comments.length === 0) {
        return null;
      }
 
      // Build result by copying non-comment ranges.
      // Comments are sorted by position since acorn parses linearly.
      let result = '';
      let position = 0;
 
      for (const comment of comments) {
        result += code.slice(position, comment.start);
        position = comment.end;
      }
 
      result += code.slice(position);
      return result;
    },
  };
}