inline-enums-rollup.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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 { parseSync } from 'oxc-parser'
  22. import { spawnSync } from 'node:child_process'
  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. /**
  38. * @param {import('oxc-parser').Expression | import('oxc-parser').PrivateIdentifier} exp
  39. * @returns { exp is import('oxc-parser').StringLiteral | import('oxc-parser').NumericLiteral }
  40. */
  41. function isStringOrNumberLiteral(exp) {
  42. return (
  43. exp.type === 'Literal' &&
  44. (typeof exp.value === 'string' || typeof exp.value === 'number')
  45. )
  46. }
  47. // this is called in the build script entry once
  48. // so the data can be shared across concurrent Rolldown processes
  49. export function scanEnums() {
  50. /** @type {{ [file: string]: EnumDeclaration[] }} */
  51. const declarations = Object.create(null)
  52. /** @type {{ [id_key: `${string}.${string}`]: string; }} */
  53. const defines = Object.create(null)
  54. // 1. grep for files with exported enum
  55. const { stdout } = spawnSync('git', ['grep', `enum `])
  56. const files = [
  57. ...new Set(
  58. stdout
  59. .toString()
  60. .trim()
  61. .split('\n')
  62. .map(line => line.split(':')[0]),
  63. ),
  64. ]
  65. // 2. parse matched files to collect enum info
  66. for (const relativeFile of files) {
  67. const file = path.resolve(process.cwd(), relativeFile)
  68. const content = readFileSync(file, 'utf-8')
  69. const res = parseSync(file, content, {
  70. sourceType: 'module',
  71. })
  72. /** @type {Set<string>} */
  73. const enumIds = new Set()
  74. for (const node of res.program.body) {
  75. let decl
  76. if (node.type === 'TSEnumDeclaration') {
  77. decl = node
  78. }
  79. if (
  80. node.type === 'ExportNamedDeclaration' &&
  81. node.declaration &&
  82. node.declaration.type === 'TSEnumDeclaration'
  83. ) {
  84. decl = node.declaration
  85. }
  86. if (decl) {
  87. const id = decl.id.name
  88. if (enumIds.has(id)) {
  89. throw new Error(
  90. `not support declaration merging for enum ${id} in ${file}`,
  91. )
  92. }
  93. enumIds.add(id)
  94. /** @type {string | number | undefined} */
  95. let lastInitialized
  96. /** @type {Array<EnumMember>} */
  97. const members = []
  98. for (let i = 0; i < decl.body.members.length; i++) {
  99. const e = decl.body.members[i]
  100. const key =
  101. e.id.type === 'Identifier'
  102. ? e.id.name
  103. : e.id.type === 'Literal'
  104. ? e.id.value
  105. : ''
  106. if (key === '') continue
  107. const fullKey = /** @type {const} */ (`${id}.${key}`)
  108. const saveValue = (/** @type {string | number} */ value) => {
  109. // We need allow same name enum in different file.
  110. // For example: enum ErrorCodes exist in both @vue/compiler-core and @vue/runtime-core
  111. // But not allow `ErrorCodes.__EXTEND_POINT__` appear in two same name enum
  112. if (fullKey in defines) {
  113. throw new Error(`name conflict for enum ${id} in ${file}`)
  114. }
  115. members.push({
  116. name: key,
  117. value,
  118. })
  119. defines[fullKey] = JSON.stringify(value)
  120. }
  121. const init = e.initializer
  122. if (init) {
  123. /** @type {string | number} */
  124. let value
  125. if (isStringOrNumberLiteral(init)) {
  126. value = init.value
  127. }
  128. // e.g. 1 << 2
  129. else if (init.type === 'BinaryExpression') {
  130. const resolveValue = (
  131. /** @type {import('oxc-parser').Expression | import('oxc-parser').PrivateIdentifier} */ node,
  132. ) => {
  133. assert.ok(typeof node.start === 'number')
  134. assert.ok(typeof node.end === 'number')
  135. if (isStringOrNumberLiteral(node)) {
  136. return node.value
  137. } else if (
  138. node.type === 'MemberExpression' ||
  139. // @ts-expect-error oxc only type
  140. node.type === 'StaticMemberExpression'
  141. ) {
  142. const exp = /** @type {`${string}.${string}`} */ (
  143. content.slice(node.start, node.end)
  144. )
  145. if (!(exp in defines)) {
  146. throw new Error(
  147. `unhandled enum initialization expression ${exp} in ${file}`,
  148. )
  149. }
  150. return defines[exp]
  151. } else {
  152. throw new Error(
  153. `unhandled BinaryExpression operand type ${node.type} in ${file}`,
  154. )
  155. }
  156. }
  157. const exp = `${resolveValue(init.left)}${
  158. init.operator
  159. }${resolveValue(init.right)}`
  160. value = evaluate(exp)
  161. } else if (init.type === 'UnaryExpression') {
  162. if (isStringOrNumberLiteral(init.argument)) {
  163. const exp = `${init.operator}${init.argument.value}`
  164. value = evaluate(exp)
  165. } else {
  166. throw new Error(
  167. `unhandled UnaryExpression argument type ${init.argument.type} in ${file}`,
  168. )
  169. }
  170. } else {
  171. throw new Error(
  172. `unhandled initializer type ${init.type} for ${fullKey} in ${file}`,
  173. )
  174. }
  175. lastInitialized = value
  176. saveValue(lastInitialized)
  177. } else {
  178. if (lastInitialized === undefined) {
  179. // first initialized
  180. lastInitialized = 0
  181. saveValue(lastInitialized)
  182. } else if (typeof lastInitialized === 'number') {
  183. lastInitialized++
  184. saveValue(lastInitialized)
  185. } else {
  186. // should not happen
  187. throw new Error(`wrong enum initialization sequence in ${file}`)
  188. }
  189. }
  190. }
  191. if (!(file in declarations)) {
  192. declarations[file] = []
  193. }
  194. assert.ok(typeof node.start === 'number')
  195. assert.ok(typeof node.end === 'number')
  196. declarations[file].push({
  197. id,
  198. range: [node.start, node.end],
  199. members,
  200. })
  201. }
  202. }
  203. }
  204. // 3. save cache
  205. try {
  206. mkdirSync('temp')
  207. } catch {}
  208. /** @type {EnumData} */
  209. const enumData = {
  210. declarations,
  211. defines,
  212. }
  213. writeFileSync(ENUM_CACHE_PATH, JSON.stringify(enumData))
  214. return () => {
  215. rmSync(ENUM_CACHE_PATH, { force: true })
  216. }
  217. }
  218. /**
  219. * @returns {[import('rolldown').Plugin, Record<string, string>]}
  220. */
  221. export function inlineEnums() {
  222. if (!existsSync(ENUM_CACHE_PATH)) {
  223. throw new Error('enum cache needs to be initialized before creating plugin')
  224. }
  225. /**
  226. * @type {EnumData}
  227. */
  228. const enumData = JSON.parse(readFileSync(ENUM_CACHE_PATH, 'utf-8'))
  229. // 3. during transform:
  230. // 3.1 files w/ enum declaration: rewrite declaration as object literal
  231. // 3.2 files using enum: inject into rolldown define
  232. /**
  233. * @type {import('rolldown').Plugin}
  234. */
  235. const plugin = {
  236. name: 'inline-enum',
  237. transform(code, id) {
  238. /**
  239. * @type {MagicString | undefined}
  240. */
  241. let s
  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. // see https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings
  260. return typeof value === 'string'
  261. ? [
  262. forwardMapping,
  263. // string enum members do not get a reverse mapping generated at all
  264. ]
  265. : [
  266. forwardMapping,
  267. // other enum members should support enum reverse mapping
  268. reverseMapping,
  269. ]
  270. })
  271. .join(',\n')}}`,
  272. )
  273. }
  274. }
  275. if (s) {
  276. return {
  277. code: s.toString(),
  278. map: s.generateMap(),
  279. }
  280. }
  281. },
  282. }
  283. return [plugin, enumData.defines]
  284. }