@@ -31,8 +31,41 @@ export class Opt<T = unknown> extends Variable<T> {
31
31
return super . getValue ( ) ;
32
32
} ;
33
33
init ( cacheFile : string ) : void {
34
- const cacheV = JSON . parse ( Utils . readFile ( cacheFile ) || '{}' ) [ this . id ] ;
35
- if ( cacheV !== undefined ) this . value = cacheV ;
34
+ // Find the configuration key based on either dot notation, or JavaScript objects.
35
+ const findKey = ( obj : unknown , path : string [ ] ) : T | undefined => {
36
+ const top = path . shift ( ) ;
37
+ if ( ! top ) {
38
+ // The path is empty, so this is our value.
39
+ return obj as T ;
40
+ }
41
+
42
+ if ( ! ( obj instanceof Object || obj instanceof Array ) ) {
43
+ // Not an array, not an object, but we need to go deeper.
44
+ // This is invalid, so return.
45
+ return undefined ;
46
+ }
47
+
48
+ const mergedPath = [ top , ...path ] . join ( "." ) ;
49
+ if ( mergedPath in obj ) {
50
+ // The key exists on this level with dot-notation, so we return that.
51
+ // Typescript does not know what to do with an untyped object, hence the any.
52
+ return ( obj as any ) [ mergedPath ] as T ;
53
+ }
54
+
55
+ if ( top in obj ) {
56
+ // The value exists but we are not there yet, so we recurse.
57
+ // Typescript does not know what to do with an untyped object, hence the any.
58
+ return findKey ( ( obj as any ) [ top ] as object , path ) ;
59
+ }
60
+
61
+ // Key does not exist :(
62
+ return undefined ;
63
+ }
64
+
65
+ const cacheV = findKey ( JSON . parse ( Utils . readFile ( cacheFile ) || '{}' ) , this . id . split ( "." ) ) ;
66
+ if ( cacheV !== undefined ) {
67
+ this . value = cacheV ;
68
+ }
36
69
37
70
this . connect ( 'changed' , ( ) => {
38
71
const cache = JSON . parse ( Utils . readFile ( cacheFile ) || '{}' ) ;
0 commit comments