()
| 27 | * to prevent "module not found" errors. |
| 28 | */ |
| 29 | export default function featureFlagsPlugin(): Plugin { |
| 30 | const features = getEnabledFeatures() |
| 31 | |
| 32 | const virtualModuleId = 'bun:bundle' |
| 33 | const resolvedVirtualModuleId = '\0' + virtualModuleId |
| 34 | |
| 35 | return { |
| 36 | name: 'feature-flags', |
| 37 | |
| 38 | // Resolve bun:bundle as a virtual module (prevents "module not found") |
| 39 | resolveId(id) { |
| 40 | if (id === virtualModuleId) { |
| 41 | return resolvedVirtualModuleId |
| 42 | } |
| 43 | }, |
| 44 | |
| 45 | // Provide a stub export for bun:bundle (unused at runtime after transform) |
| 46 | load(id) { |
| 47 | if (id === resolvedVirtualModuleId) { |
| 48 | return 'export function feature(name) { return false; }' |
| 49 | } |
| 50 | }, |
| 51 | |
| 52 | // Replace feature('X') calls with true/false literals at transform time, |
| 53 | // and transpile `using` declarations for Node.js compatibility. |
| 54 | transform(code, id) { |
| 55 | // Skip node_modules |
| 56 | if (id.includes('node_modules')) return null |
| 57 | |
| 58 | let modified = false |
| 59 | |
| 60 | // 1. Replace feature('X') calls with boolean literals |
| 61 | let matchCount = 0 |
| 62 | let transformed = code.replace(FEATURE_CALL_RE, (match, flagName) => { |
| 63 | matchCount++ |
| 64 | return features.has(flagName) ? 'true' : 'false' |
| 65 | }) |
| 66 | if (matchCount > 0) modified = true |
| 67 | |
| 68 | // 2. Transpile `using _ = expr;` to `const _ = expr;` for Node.js compat. |
| 69 | // Node.js v22 does not support `using` declarations (Explicit Resource Management). |
| 70 | // Safe because: SLOW_OPERATION_LOGGING is not enabled, so slowLogging returns |
| 71 | // a no-op disposable whose [Symbol.dispose]() is empty. |
| 72 | if (transformed.includes('using _')) { |
| 73 | transformed = transformed.replace(/\busing\s+(_\w*)\s*=/g, 'const $1 =') |
| 74 | modified = true |
| 75 | } |
| 76 | |
| 77 | if (!modified) return null |
| 78 | |
| 79 | return { code: transformed, map: null } |
| 80 | }, |
| 81 | } |
| 82 | } |
no test coverage detected