1
- import { parse , type Node } from "kdljs" ;
1
+ import { parse , type Value , type Node } from "kdljs" ;
2
2
import type { Enum , Event , Property , Interface , WebIdl } from "./types" ;
3
3
import { readdir , readFile } from "fs/promises" ;
4
4
import { merge } from "./helpers.js" ;
@@ -7,6 +7,16 @@ type DeepPartial<T> = T extends object
7
7
? { [ K in keyof T ] ?: DeepPartial < T [ K ] > }
8
8
: T ;
9
9
10
+ function optionalMember < const T > ( prop : string , type : T , value ?: Value ) {
11
+ if ( value === undefined ) {
12
+ return { } ;
13
+ }
14
+ if ( typeof value !== type ) {
15
+ throw new Error ( `Expected type ${ value } for ${ prop } ` ) ;
16
+ }
17
+ return { [ prop ] : value as T extends "string" ? string : T extends "number" ? number : T extends "boolean" ? boolean : never } ;
18
+ }
19
+
10
20
/**
11
21
* Converts patch files in KDL to match the [types](types.d.ts).
12
22
*/
@@ -92,15 +102,12 @@ function handleMixin(node: Node): DeepPartial<Interface> {
92
102
}
93
103
}
94
104
95
- const result = {
105
+ return {
96
106
name,
97
107
events : { event } ,
98
108
properties : { property } ,
109
+ ...optionalMember ( "extends" , "string" , node . properties ?. extends ) ,
99
110
} as DeepPartial < Interface > ;
100
- if ( node . properties . extends ) {
101
- result . extends = node . properties . extends as string ;
102
- }
103
- return result ;
104
111
}
105
112
106
113
/**
@@ -119,19 +126,12 @@ function handleEvent(child: Node): Event {
119
126
* @param child The child node to handle.
120
127
*/
121
128
function handleProperty ( child : Node ) : Partial < Property > {
122
- const result : Partial < Property > = {
129
+ return {
123
130
name : child . values [ 0 ] as string ,
131
+ ...optionalMember ( "exposed" , "string" , child . properties ?. exposed ) ,
132
+ ...optionalMember ( "optional" , "boolean" , child . properties ?. optional ) ,
133
+ ...optionalMember ( "overrideType" , "string" , child . properties ?. overrideType ) ,
124
134
} ;
125
-
126
- const props : ( keyof Property ) [ ] = [ "exposed" , "optional" , "overrideType" ] ;
127
-
128
- props . forEach ( ( prop ) => {
129
- const value = child . properties [ prop ] ;
130
- if ( value !== undefined ) {
131
- result [ prop ] = value as any ;
132
- }
133
- } ) ;
134
- return result ;
135
135
}
136
136
137
137
/**
0 commit comments