feat(cli): support generation of literal union from string enum (#2054)

* feat(cli): support generation of literal union from enum

* Remove const

---------

Co-authored-by: LongYinan <lynweklm@gmail.com>
This commit is contained in:
inokawa 2024-04-22 15:28:04 +09:00 committed by GitHub
parent 6b2164c85d
commit 0adc36ce1c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 18 additions and 1 deletions

View file

@ -10,6 +10,7 @@ export const DEFAULT_TYPE_DEF_HEADER = `/* auto-generated by NAPI-RS */
enum TypeDefKind {
Const = 'const',
Enum = 'enum',
StringEnum = 'string_enum',
Interface = 'interface',
Fn = 'fn',
Struct = 'struct',
@ -41,6 +42,14 @@ function prettyPrint(
s += `export ${enumName} ${line.name} {\n${line.def}\n}`
break
case TypeDefKind.StringEnum:
if (constEnum) {
s += `export const enum ${line.name} {\n${line.def}\n}`
} else {
s += `export type ${line.name} = ${line.def.replaceAll(/.*=/g, '').replaceAll(',', '|')};`
}
break
case TypeDefKind.Struct:
s += `export class ${line.name} {\n${line.def}\n}`
if (line.original_name && line.original_name !== line.name) {
@ -75,6 +84,7 @@ export async function processTypeDef(
switch (def.kind) {
case TypeDefKind.Const:
case TypeDefKind.Enum:
case TypeDefKind.StringEnum:
case TypeDefKind.Fn:
case TypeDefKind.Struct: {
exports.push(def.name)

View file

@ -136,6 +136,7 @@ pub struct NapiEnum {
pub comments: Vec<String>,
pub skip_typescript: bool,
pub register_name: Ident,
pub is_string_enum: bool,
}
#[derive(Debug, Clone)]

View file

@ -10,7 +10,11 @@ impl ToTypeDef for NapiEnum {
add_alias(self.name.to_string(), self.js_name.to_string());
Some(TypeDef {
kind: "enum".to_owned(),
kind: if self.is_string_enum {
"string_enum".to_owned()
} else {
"enum".to_owned()
},
name: self.js_name.to_owned(),
original_name: Some(self.name.to_string()),
def: self.gen_ts_variants(),

View file

@ -1070,6 +1070,7 @@ impl ConvertToAST for syn::ItemEnum {
.js_name()
.map_or_else(|| self.ident.to_string(), |(s, _)| s.to_string());
let is_string_enum = opts.string_enum().is_some();
let variants = match opts.string_enum() {
Some(case) => {
let case = case.map(|c| Ok::<Case, Diagnostic>(match c.0.as_str() {
@ -1183,6 +1184,7 @@ impl ConvertToAST for syn::ItemEnum {
comments: extract_doc_comments(&self.attrs),
skip_typescript: opts.skip_typescript().is_some(),
register_name: get_register_ident(self.ident.to_string().as_str()),
is_string_enum,
}),
})
}