| 217 | * @returns {[import('rollup').Plugin, Record<string, string>]} |
| 218 | */ |
| 219 | export function inlineEnums() { |
| 220 | if (!existsSync(ENUM_CACHE_PATH)) { |
| 221 | throw new Error('enum cache needs to be initialized before creating plugin') |
| 222 | } |
| 223 | /** |
| 224 | * @type {EnumData} |
| 225 | */ |
| 226 | const enumData = JSON.parse(readFileSync(ENUM_CACHE_PATH, 'utf-8')) |
| 227 | |
| 228 | // 3. during transform: |
| 229 | // 3.1 files w/ enum declaration: rewrite declaration as object literal |
| 230 | // 3.2 files using enum: inject into esbuild define |
| 231 | /** |
| 232 | * @type {import('rollup').Plugin} |
| 233 | */ |
| 234 | const plugin = { |
| 235 | name: 'inline-enum', |
| 236 | transform(code, id) { |
| 237 | /** |
| 238 | * @type {MagicString | undefined} |
| 239 | */ |
| 240 | let s |
| 241 | |
| 242 | if (id in enumData.declarations) { |
| 243 | s = s || new MagicString(code) |
| 244 | for (const declaration of enumData.declarations[id]) { |
| 245 | const { |
| 246 | range: [start, end], |
| 247 | id, |
| 248 | members, |
| 249 | } = declaration |
| 250 | s.update( |
| 251 | start, |
| 252 | end, |
| 253 | `export const ${id} = {${members |
| 254 | .flatMap(({ name, value }) => { |
| 255 | const forwardMapping = |
| 256 | JSON.stringify(name) + ': ' + JSON.stringify(value) |
| 257 | const reverseMapping = |
| 258 | JSON.stringify(value.toString()) + ': ' + JSON.stringify(name) |
| 259 | |
| 260 | // see https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings |
| 261 | return typeof value === 'string' |
| 262 | ? [ |
| 263 | forwardMapping, |
| 264 | // string enum members do not get a reverse mapping generated at all |
| 265 | ] |
| 266 | : [ |
| 267 | forwardMapping, |
| 268 | // other enum members should support enum reverse mapping |
| 269 | reverseMapping, |
| 270 | ] |
| 271 | }) |
| 272 | .join(',\n')}}`, |
| 273 | ) |
| 274 | } |
| 275 | } |
| 276 | |