All files / kernel-utils/src/vite-plugins replace-node-env-plugin.ts

100% Statements 8/8
100% Branches 6/6
100% Functions 2/2
100% Lines 8/8

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 48 49 50 51 52                                                            2x 2x     10x 3x     7x         7x 1x     6x        
import type { Plugin as RolldownPlugin } from 'rolldown';
 
export type ReplaceNodeEnvPluginOptions = {
  /**
   * The value to inline for `process.env.NODE_ENV`. Defaults to `'production'`.
   */
  value?: string;
};
 
/**
 * A Rolldown plugin that inlines `process.env.NODE_ENV` as a string literal in
 * any module that references it.
 *
 * This replaces the former build-config `define` (issue #812). Libraries such
 * as immer branch on `process.env.NODE_ENV`, and vats have no `process` global
 * at runtime, so the reference must be resolved at bundle time. The plugin
 * auto-detects the need: modules without the reference are left untouched.
 *
 * This is a textual replacement (the same class of approach as the sibling
 * {@link removeDynamicImportsPlugin}) and handles the dotted
 * `process.env.NODE_ENV` form, consistent with the `define` it replaces.
 *
 * @param options - Plugin options.
 * @param options.value - The value to inline for `process.env.NODE_ENV`.
 * Defaults to `'production'`.
 * @returns A Rolldown plugin.
 */
export function replaceNodeEnvPlugin({
  value = 'production',
}: ReplaceNodeEnvPluginOptions = {}): RolldownPlugin {
  const replacement = JSON.stringify(value);
  return {
    name: 'ocap-kernel:replace-node-env',
    transform(code) {
      if (!code.includes('process.env.NODE_ENV')) {
        return null;
      }
 
      const transformed = code.replace(
        /\bprocess\.env\.NODE_ENV\b/gu,
        replacement,
      );
 
      if (transformed === code) {
        return null;
      }
 
      return { code: transformed, map: null };
    },
  };
}