inline-enums.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. // @ts-check
  2. /**
  3. * We used const enums before, but it caused some issues: #1228, so we
  4. * switched to regular enums. But we still want to keep the zero-cost benefit
  5. * of const enums, and minimize the impact on bundle size as much as possible.
  6. *
  7. * Here we pre-process all the enums in the project and turn them into
  8. * global replacements, and rewrite the original declarations as object literals.
  9. *
  10. * This file is expected to be executed with project root as cwd.
  11. */
  12. import * as assert from 'node:assert'
  13. import {
  14. existsSync,
  15. mkdirSync,
  16. readFileSync,
  17. rmSync,
  18. writeFileSync,
  19. } from 'node:fs'
  20. import * as path from 'node:path'
  21. import { parse } from '@babel/parser'
  22. import { execaSync } from 'execa'
  23. import MagicString from 'magic-string'
  24. /**
  25. * @typedef {{ readonly name: string, readonly value: string | number }} EnumMember
  26. * @typedef {{ readonly id: string, readonly range: readonly [start: number, end: number], readonly members: ReadonlyArray<EnumMember>}} EnumDeclaration
  27. * @typedef {{ readonly declarations: { readonly [file: string] : ReadonlyArray<EnumDeclaration>}, readonly defines: { readonly [ id_key: `${string}.${string}`]: string } }} EnumData
  28. */
  29. const ENUM_CACHE_PATH = 'temp/enum.json'
  30. /**
  31. * @param {string} exp
  32. * @returns {string | number}
  33. */
  34. function evaluate(exp) {
  35. return new Function(`return ${exp}`)()
  36. }
  37. // this is called in the build script entry once
  38. // so the data can be shared across concurrent Rollup processes
  39. export function scanEnums() {
  40. /** @type {{ [file: string]: EnumDeclaration[] }} */
  41. const declarations = Object.create(null)
  42. /** @type {{ [id_key: `${string}.${string}`]: string; }} */
  43. const defines = Object.create(null)
  44. // 1. grep for files with exported enum
  45. const { stdout } = execaSync('git', ['grep', `export enum`])
  46. const files = [...new Set(stdout.split('\n').map(line => line.split(':')[0]))]
  47. // 2. parse matched files to collect enum info
  48. for (const relativeFile of files) {
  49. const file = path.resolve(process.cwd(), relativeFile)
  50. const content = readFileSync(file, 'utf-8')
  51. const ast = parse(content, {
  52. plugins: ['typescript'],
  53. sourceType: 'module',
  54. })
  55. /** @type {Set<string>} */
  56. const enumIds = new Set()
  57. for (const node of ast.program.body) {
  58. if (
  59. node.type === 'ExportNamedDeclaration' &&
  60. node.declaration &&
  61. node.declaration.type === 'TSEnumDeclaration'
  62. ) {
  63. const decl = node.declaration
  64. const id = decl.id.name
  65. if (enumIds.has(id)) {
  66. throw new Error(
  67. `not support declaration merging for enum ${id} in ${file}`,
  68. )
  69. }
  70. enumIds.add(id)
  71. /** @type {string | number | undefined} */
  72. let lastInitialized
  73. /** @type {Array<EnumMember>} */
  74. const members = []
  75. for (let i = 0; i < decl.members.length; i++) {
  76. const e = decl.members[i]
  77. const key = e.id.type === 'Identifier' ? e.id.name : e.id.value
  78. const fullKey = /** @type {const} */ (`${id}.${key}`)
  79. const saveValue = (/** @type {string | number} */ value) => {
  80. // We need allow same name enum in different file.
  81. // For example: enum ErrorCodes exist in both @vue/compiler-core and @vue/runtime-core
  82. // But not allow `ErrorCodes.__EXTEND_POINT__` appear in two same name enum
  83. if (fullKey in defines) {
  84. throw new Error(`name conflict for enum ${id} in ${file}`)
  85. }
  86. members.push({
  87. name: key,
  88. value,
  89. })
  90. defines[fullKey] = JSON.stringify(value)
  91. }
  92. const init = e.initializer
  93. if (init) {
  94. /** @type {string | number} */
  95. let value
  96. if (
  97. init.type === 'StringLiteral' ||
  98. init.type === 'NumericLiteral'
  99. ) {
  100. value = init.value
  101. }
  102. // e.g. 1 << 2
  103. else if (init.type === 'BinaryExpression') {
  104. const resolveValue = (
  105. /** @type {import('@babel/types').Expression | import('@babel/types').PrivateName} */ node,
  106. ) => {
  107. assert.ok(typeof node.start === 'number')
  108. assert.ok(typeof node.end === 'number')
  109. if (
  110. node.type === 'NumericLiteral' ||
  111. node.type === 'StringLiteral'
  112. ) {
  113. return node.value
  114. } else if (node.type === 'MemberExpression') {
  115. const exp = /** @type {`${string}.${string}`} */ (
  116. content.slice(node.start, node.end)
  117. )
  118. if (!(exp in defines)) {
  119. throw new Error(
  120. `unhandled enum initialization expression ${exp} in ${file}`,
  121. )
  122. }
  123. return defines[exp]
  124. } else {
  125. throw new Error(
  126. `unhandled BinaryExpression operand type ${node.type} in ${file}`,
  127. )
  128. }
  129. }
  130. const exp = `${resolveValue(init.left)}${
  131. init.operator
  132. }${resolveValue(init.right)}`
  133. value = evaluate(exp)
  134. } else if (init.type === 'UnaryExpression') {
  135. if (
  136. init.argument.type === 'StringLiteral' ||
  137. init.argument.type === 'NumericLiteral'
  138. ) {
  139. const exp = `${init.operator}${init.argument.value}`
  140. value = evaluate(exp)
  141. } else {
  142. throw new Error(
  143. `unhandled UnaryExpression argument type ${init.argument.type} in ${file}`,
  144. )
  145. }
  146. } else {
  147. throw new Error(
  148. `unhandled initializer type ${init.type} for ${fullKey} in ${file}`,
  149. )
  150. }
  151. lastInitialized = value
  152. saveValue(lastInitialized)
  153. } else {
  154. if (lastInitialized === undefined) {
  155. // first initialized
  156. lastInitialized = 0
  157. saveValue(lastInitialized)
  158. } else if (typeof lastInitialized === 'number') {
  159. lastInitialized++
  160. saveValue(lastInitialized)
  161. } else {
  162. // should not happen
  163. throw new Error(`wrong enum initialization sequence in ${file}`)
  164. }
  165. }
  166. }
  167. if (!(file in declarations)) {
  168. declarations[file] = []
  169. }
  170. assert.ok(typeof node.start === 'number')
  171. assert.ok(typeof node.end === 'number')
  172. declarations[file].push({
  173. id,
  174. range: [node.start, node.end],
  175. members,
  176. })
  177. }
  178. }
  179. }
  180. // 3. save cache
  181. if (!existsSync('temp')) mkdirSync('temp')
  182. /** @type {EnumData} */
  183. const enumData = {
  184. declarations,
  185. defines,
  186. }
  187. writeFileSync(ENUM_CACHE_PATH, JSON.stringify(enumData))
  188. return () => {
  189. rmSync(ENUM_CACHE_PATH, { force: true })
  190. }
  191. }
  192. /**
  193. * @returns {[import('rollup').Plugin, Record<string, string>]}
  194. */
  195. export function inlineEnums() {
  196. if (!existsSync(ENUM_CACHE_PATH)) {
  197. throw new Error('enum cache needs to be initialized before creating plugin')
  198. }
  199. /**
  200. * @type {EnumData}
  201. */
  202. const enumData = JSON.parse(readFileSync(ENUM_CACHE_PATH, 'utf-8'))
  203. // 3. during transform:
  204. // 3.1 files w/ enum declaration: rewrite declaration as object literal
  205. // 3.2 files using enum: inject into esbuild define
  206. /**
  207. * @type {import('rollup').Plugin}
  208. */
  209. const plugin = {
  210. name: 'inline-enum',
  211. transform(code, id) {
  212. /**
  213. * @type {MagicString | undefined}
  214. */
  215. let s
  216. if (id in enumData.declarations) {
  217. s = s || new MagicString(code)
  218. for (const declaration of enumData.declarations[id]) {
  219. const {
  220. range: [start, end],
  221. id,
  222. members,
  223. } = declaration
  224. s.update(
  225. start,
  226. end,
  227. `export const ${id} = {${members
  228. .flatMap(({ name, value }) => {
  229. const forwardMapping =
  230. JSON.stringify(name) + ': ' + JSON.stringify(value)
  231. const reverseMapping =
  232. JSON.stringify(value.toString()) + ': ' + JSON.stringify(name)
  233. // see https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings
  234. return typeof value === 'string'
  235. ? [
  236. forwardMapping,
  237. // string enum members do not get a reverse mapping generated at all
  238. ]
  239. : [
  240. forwardMapping,
  241. // other enum members should support enum reverse mapping
  242. reverseMapping,
  243. ]
  244. })
  245. .join(',\n')}}`,
  246. )
  247. }
  248. }
  249. if (s) {
  250. return {
  251. code: s.toString(),
  252. map: s.generateMap(),
  253. }
  254. }
  255. },
  256. }
  257. return [plugin, enumData.defines]
  258. }