Repository navigation
Expand file tree
/
Copy pathStruct.mts
More file actions
794 lines (723 loc) · 21.7 KB
/
Copy pathStruct.mts
File metadata and controls
794 lines (723 loc) · 21.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
import { readBinaryCfg } from "./binCfgParser.mjs";
export type * from "./types.mjs";
export type * from "./enums.mjs";
export type Internal =
| "__internal__"
| "fork"
| "removeNode"
| "addNode"
| "clone"
| "entries"
| "forEach"
| "filter"
| "map"
| "toJson"
| "toString";
export type InternalPlus = Internal | "fromString" | "fromJson";
export interface DefaultEntries {
bpatch?: boolean;
bskipref?: boolean;
isArray?: boolean;
isRoot?: boolean;
rawName?: string;
refkey?: string | number;
refurl?: string;
removenode?: boolean;
useAsterisk?: boolean;
}
export type GetStructType<In> =
In extends Array<infer T>
? Struct & { [K in `${number}`]: GetStructType<T> }
: In extends Record<any, any>
? Struct & {
[key in keyof In]: key extends Internal
? Struct[key]
: GetStructType<In[key]>;
}
: In extends string
? In
: In extends number
? number
: In extends boolean
? boolean
: In;
const TAB = " ";
const WILDCARD = "_wildcard";
const KEYWORDS = [
/**
* Path of the cfg holding the base struct: relative to this file (resolves
* only inside this file's own mount), or `@<ConfigPathName>/<RelativePath>`
* to address an active config path. `@BaseGame/` is the `GameLite/GameData/`
* root. Config paths are active only for ZoneKit (Game Feature) mods.
* Omit refurl and refkey looks for the struct in the same file.
* @see toBaseGameRefurl
* @example MyMod : struct.begin {refurl=../DialogPoolPrototypes/Brodyaga.cfg; refkey=BusyTopic}
* @example CorpusMedlak : struct.begin {refurl=@BaseGame/ObjPrototypes/QuestObjPrototypes.cfg;refkey=CorpusMedlak}
*/
"refurl",
/**
* Key / name of the base struct to inherit from: a name, or a [numeric index].
* The base is deep-copied, then this struct's body merges on top.
*/
"refkey",
/**
* Placed on a nested struct/entry: tells the game NOT to inherit that property
* from the refkey base. Inheritors must specify their own value or it stays empty.
* @example
* [0] : struct.begin
* InfotopicDialogs : struct.begin
* InfotopicDialogChain = SomeChain{bskipref}
* struct.end
* struct.end
*/
"bskipref",
/**
* Partial override: merges this struct into the existing one field by field,
* recursing into nested structs. Siblings it doesn't list are kept. Without
* bpatch, a patch node whose key already exists replaces it whole.
*/
"bpatch",
];
/**
* Marks a struct as removed: `Key : removenode` deletes the existing node with
* that key. For non-structs, use bpatch and assign the value `empty` instead.
*/
const REMOVE_NODE = "removenode";
const INTERNAL_PROPS = new Map([
["__internal__", "_"],
["fork", ""], // methods
["removeNode", ""], // methods
["addNode", ""], // methods
["clone", ""], // methods
["entries", ""], // methods
["forEach", ""], // methods
["filter", ""], // methods
["map", ""], // methods
["fromJson", ""], // methods
["toJson", ""], // methods
["toString", ""], // methods
["fromString", ""], // methods
] as const);
const INTERNAL_PROPS_INV = new Map(
Array.from(INTERNAL_PROPS.entries()).map(([k, v]) => [v, k]),
);
const REF_INTERNAL_PROPS = new Map([
["rawName", "w"],
["refurl", "u"],
["refkey", "k"],
["bskipref", "s"],
["bpatch", "p"],
["isArray", "a"],
["isRoot", "r"],
["useAsterisk", "*"],
] as const);
const REF_INTERNAL_PROPS_INV = new Map(
Array.from(REF_INTERNAL_PROPS.entries()).map(([k, v]) => [v, k]),
);
/**
* This file is part of the Stalker 2 Modding Tools project.
* This is a base class for all structs.
*/
export class Struct implements Record<Internal, any> {
__internal__: Refs = new Refs();
/**
* Creates a new struct instance.
*/
constructor(parentOrRaw?: string | Struct | object) {
if (parentOrRaw instanceof Struct) {
Object.assign(this, parentOrRaw.clone());
}
if (typeof parentOrRaw === "string") {
Object.assign(this, Struct.fromString(parentOrRaw)[0]);
}
if (typeof parentOrRaw === "object" && parentOrRaw !== null) {
Object.assign(this, Struct.fromJson(parentOrRaw));
}
}
fork(clone = false) {
const patch = clone
? this.clone()
: createDynamicClassInstance(
this.__internal__.rawName || this.constructor.name,
);
patch.__internal__.isRoot = this.__internal__.isRoot;
patch.__internal__.isArray = this.__internal__.isArray;
patch.__internal__.useAsterisk = this.__internal__.useAsterisk;
function markAsbPatch(s: Struct) {
s.__internal__.bpatch = true;
Object.values(s)
.filter((v) => v instanceof Struct)
.forEach(markAsbPatch);
}
markAsbPatch(patch);
return patch as this;
}
removeNode(key: Exclude<keyof this, Symbol>) {
if (this.__internal__.bpatch !== true) {
throw new Error(
"Cannot remove node from non-patch struct. Use fork() first.",
);
}
if (this[key] instanceof Struct) {
this[key].__internal__.removenode = true;
} else {
console.warn(
`Attempting to remove node on non-struct value. Old value: '${this.__internal__.rawName}.${key}' = ${this[key]}. Assigning 'empty' instead.`,
);
this[key] = "empty" as any;
}
return this;
}
addNode(value: any, key?: string | number): this {
if (key === undefined) {
const nextIndex = Object.keys(this)
.map((k) => parseInt(k))
.filter((k) => !isNaN(k))
.sort((a, b) => a - b)
.pop();
key = nextIndex !== undefined ? nextIndex + 1 : 0;
}
if (typeof value === "object" && value !== null) {
if (!(value instanceof Struct)) {
value = new Struct(value);
}
value.__internal__.rawName = String(key);
}
this[key] = value;
return this;
}
clone() {
const newInstance = new Struct() as typeof this;
newInstance.__internal__ = new Refs(this.__internal__);
copyRawLiterals(this, newInstance);
this.forEach(([k, v]) => {
if (v instanceof Struct) {
newInstance[k] = v.clone();
} else {
newInstance[k] = v;
}
});
return newInstance;
}
entries<
K extends Exclude<keyof this, InternalPlus>,
V extends (typeof this)[K],
>() {
return Object.entries(this).filter(
([key]) => !INTERNAL_PROPS.has(key as any),
) as [K, V][];
}
forEach<
K extends Exclude<keyof this, InternalPlus>,
V extends (typeof this)[K],
>(callback: ([key, value]: [K, V], i: number, arr: [K, V][]) => void): void {
this.entries().forEach(([key, value], i, arr) =>
callback([key as K, value as V], i, arr as any),
);
}
/**
* Filters the struct entries based on a callback function. Returns a copy.
* @param callback
*/
filter<
K extends Exclude<keyof this, InternalPlus>,
V extends (typeof this)[K],
S extends this,
>(callback: (value: [K, V], index: number, array: [K, V][]) => boolean): S {
const clone = this.clone();
clone.entries().forEach((entry, i, arr) => {
if (!callback(entry as any, i, arr as any)) {
delete clone[entry[0]];
}
});
return clone as any;
}
/**
* Maps the struct entries based on a callback function. Returns a copy.
* @param callback
*/
map<K extends Exclude<keyof this, InternalPlus>, V extends (typeof this)[K]>(
callback: ([key, value]: [K, V], i: number, arr: [K, V][]) => V,
): this {
const clone = this.clone();
clone.entries().forEach(([key, value], i, arr) => {
clone[key] = callback([key as K, value as V], i, arr as any);
if (clone[key] === null || clone[key] === undefined) {
delete clone[key];
}
});
return clone;
}
static fromJson<T>(
obj: T,
minified = false,
): T extends object ? GetStructType<T> : T {
if (typeof obj === "object" && !!obj) {
const instance = new Struct();
Object.entries(obj).forEach(([key, value]) => {
const nKey = fromMinifiedKey(key, minified);
if (nKey === "__internal__") {
instance[nKey] = new Refs(
Object.fromEntries(
Object.entries(value).map(([k, v]) => [
fromMinifiedKey(k, minified),
v,
]),
),
);
} else {
instance[nKey] = Struct.fromJson(value, minified);
}
});
return instance as any;
}
return obj as any;
}
toJson<T extends object>(minify = false): T {
const obj = {};
Object.entries(this).forEach(([key, value]) => {
let nKey = maybeMinifyKey(key, minify);
if (value instanceof Struct) {
obj[nKey] = value.toJson(minify);
} else if (value instanceof Refs) {
obj[nKey] = Object.fromEntries(
Object.entries(value).map(([k, v]) => [maybeMinifyKey(k, minify), v]),
);
} else {
obj[nKey] = value;
}
});
return obj as T;
}
toString(): string {
if (!(this.__internal__ instanceof Refs)) {
this.__internal__ = new Refs(this.__internal__);
}
if (this.__internal__.isRoot && this.__internal__.removenode) {
return `${this.__internal__.rawName} : ${REMOVE_NODE}`;
}
let text: string = this.__internal__.isRoot
? `${this.__internal__.rawName} : `
: "";
text += "struct.begin";
const refs = this.__internal__.toString();
if (refs) {
text += ` {${refs}}`;
}
// Add all keys
const body = this.entries()
.map(([key, value]) => {
const nameAlreadyRendered =
value instanceof Struct && value.__internal__.isRoot;
const useAsterisk =
this.__internal__.isArray && this.__internal__.useAsterisk;
let keyOrIndex = "";
let equalsOrColon = "";
let spaceOrNoSpace = "";
if (!nameAlreadyRendered) {
keyOrIndex = renderKeyName(key as string, useAsterisk) + " ";
equalsOrColon = value instanceof Struct ? ":" : "=";
spaceOrNoSpace = value === "" ? "" : " ";
}
const renderedValue =
value instanceof Struct && value.__internal__.removenode
? REMOVE_NODE
: renderLiteral(this, key as string, value);
return pad(
`${keyOrIndex}${equalsOrColon}${spaceOrNoSpace}${renderedValue}`,
);
})
.join("\n");
text += body ? `\n${body}\nstruct.end` : "\nstruct.end";
return text;
}
static fromString<IntendedType>(text: string): (IntendedType & Struct)[] {
return walk(text.trim().split("\n")) as any[];
}
static fromBinary<IntendedType>(
bytes: ArrayBuffer | Uint8Array,
): (IntendedType & Struct)[] {
return readBinaryCfg(bytes) as any[];
}
}
export class Refs implements DefaultEntries {
rawName?: string;
refurl?: string;
refkey?: string | number;
bskipref?: boolean;
bpatch?: boolean;
isArray?: boolean;
isRoot?: boolean;
useAsterisk?: boolean;
removenode?: boolean;
constructor(ref?: string | Refs) {
if (typeof ref === "string") {
ref
.split(";")
.map((ref) => ref.trim())
.filter(Boolean)
.reduce((acc, ref) => {
const [key, value] = ref.split("=");
if (KEYWORDS.includes(key.trim())) {
acc[key.trim()] = value ? value.trim() : true;
}
return acc;
}, this);
}
if (typeof ref === "object") {
Object.assign(this, ref);
}
}
toString() {
return KEYWORDS.map((k) => [k, this[k]])
.filter(([_, v]) => v !== "" && v !== undefined && v !== false)
.map(([k, v]) => {
if (v === true) return k;
if (k === "refkey") {
return `${k}=${renderKeyName(`${v}`, this.useAsterisk)}`;
}
return `${k}=${v}`;
})
.join(";");
}
}
const structHeadRegex = new RegExp(
`^\\s*((.*)\\s*:)?\\s*struct\\.begin\\s*({\\s*((${KEYWORDS.join("|")})\\s*(=.+)?)\\s*})?`,
);
function parseHead(line: string, index: number): Struct {
const match = line.match(structHeadRegex);
if (!match) {
throw new Error(`Invalid struct head: ${line}`);
}
const dummy = createDynamicClassInstance(match[2]?.trim() || "", index);
if (match[3]) {
const parsed = new Refs(match[4]);
dummy.__internal__.refurl = parsed.refurl;
dummy.__internal__.refkey = parsed.refkey;
dummy.__internal__.bskipref = parsed.bskipref;
dummy.__internal__.bpatch = parsed.bpatch;
}
return dummy as Struct;
}
export function pad(text: string): string {
return `${TAB}${text.replace(/\n+/g, `\n${TAB}`)}`;
}
/** An array index: a number, or a string of digits only (a GUID such as `38475DEF...` is a key). */
function isNumber(ref: string | number): boolean {
return typeof ref === "number" || /^\d+$/.test(ref);
}
export function createDynamicClassInstance<T extends Struct = Struct>(
rawName: string,
index?: number,
): T {
const parsedName = parseStructName(rawName) || `UnnamedStruct${index}`;
const name = makeSafeClassName(parsedName);
return new (new Function(
"parent",
"Refs",
`return class ${name} extends parent {
__internal__ = new Refs({ rawName: "${rawName.trim()}" });
}`,
)(Struct, Refs))() as T;
}
function parseKeyValue(line: string, parent: Struct, index: number): void {
const match = line.match(/^(.*?)(\s*:\s*|\s*=\s*)(.*)$/);
if (!match) {
throw new Error(`Invalid key-value pair: ${line}`);
}
const key = parseKey(match[1].trim(), parent, index);
const raw = match[3].trim();
parent[key] = parseValue(raw);
rememberRawLiteral(parent, key, raw);
}
/**
* `;` starts a line comment just like `#` and `//` do.
* @example GameData/PhysicsInteractionPrototypes.cfg has `;` and `//` comments on adjacent lines.
*/
function isComment(line: string) {
return line.startsWith("#") || line.startsWith("//") || line.startsWith(";");
}
function walk(lines: string[]) {
const roots: Struct[] = [];
const stack = [];
let index = 0;
while (index < lines.length) {
const line = lines[index++].trim();
if (isComment(line)) {
continue; // Skip comments
}
const current = stack[stack.length - 1];
if (line.includes("struct.begin")) {
const newStruct = parseHead(line, index);
if (current) {
const key = parseKey(
renderStructName(newStruct.constructor.name),
current,
index,
);
current[key] = newStruct;
} else {
newStruct.__internal__.isRoot = true;
roots.push(newStruct);
}
stack.push(newStruct);
} else if (line.includes("struct.end")) {
stack.pop();
} else if (removeNodeRegex.test(line)) {
parseRemoveNode(line, current, index, roots);
} else if (line.includes("=") && current) {
parseKeyValue(line, current, index);
}
}
return roots;
}
const removeNodeRegex = new RegExp(`^([^=]+?)\\s*:\\s*${REMOVE_NODE}$`);
/**
* `Key : removenode` deletes the node with that key, so it is kept as an empty
* struct flagged `removenode` and renders back the same way.
*/
function parseRemoveNode(
line: string,
parent: Struct | undefined,
index: number,
roots: Struct[],
) {
const rawName = line.match(removeNodeRegex)[1].trim();
const node = createDynamicClassInstance(rawName, index);
node.__internal__.removenode = true;
if (parent) {
parent[parseKey(rawName, parent, index)] = node;
} else {
node.__internal__.isRoot = true;
roots.push(node);
}
}
/**
* Turns a path into a `@<mount>/` refurl. Accepts paths relative to the config
* path root, or full paths containing `GameLite/GameData/` (vanilla) or
* `GameLite/ModGameData/<mount>/` (a ZoneKit mod's own cfgs), with either
* slash style. `@` refurls resolve only while that config path is active,
* which happens for ZoneKit (Game Feature) mods; plain `~mods` pak mods have
* no active config paths and should use relative refurls.
* @example toMountRefurl("MyMod", "Mods/MyMod/Content/GameLite/ModGameData/MyMod/ItemPrototypes/Foo.cfg") // "@MyMod/ItemPrototypes/Foo.cfg"
*/
export function toMountRefurl(mount: string, path: string): string {
const escaped = mount.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const relative = path
.replace(/\\/g, "/")
.replace(
new RegExp(`^.*?GameLite/(GameData|ModGameData/${escaped})/`, "i"),
"",
)
.replace(/^(\.?\/)+/, "");
if (relative.split("/").includes("..")) {
throw new Error(`refurl can't leave its mount: '${path}'`);
}
return `@${mount}/${relative}`;
}
/**
* Refurl into the vanilla `GameLite/GameData/` root.
* @example toBaseGameRefurl("GameLite/GameData/ObjPrototypes/QuestObjPrototypes.cfg") // "@BaseGame/ObjPrototypes/QuestObjPrototypes.cfg"
*/
export function toBaseGameRefurl(path: string): string {
return toMountRefurl("BaseGame", path);
}
export function parseKey(key: string, parent: Struct, index: number) {
let normKey: string | number = key;
if (key.startsWith("[") && key.endsWith("]")) {
parent.__internal__.isArray = true;
normKey = extractKeyFromBrackets(key);
if (normKey === "*") {
parent.__internal__.useAsterisk = true;
return Object.keys(parent).length - 1;
}
if (parent[normKey] !== undefined) {
return `${normKey}_dupe_${index}`;
}
return normKey;
}
if (parent[normKey] !== undefined) {
return `${normKey}_dupe_${index}`;
}
return normKey;
}
export function parseValue(value: string): string | number | boolean {
if (value === "true" || value === "false") {
return value === "true";
}
try {
// understand +- 0.1f / 1. / 0.f / .1 / .1f -> ((\d*)\.?(\d+)|(\d+)\.?(\d*))f?
const matches = value.match(/^(-?)(\d*)\.?(\d*)f?$/);
const minus = matches[1];
const first = matches[2];
const second = matches[3];
if (first || second) {
return parseFloat(
`${minus ? "-" : ""}${first || 0}${second ? `.${second}` : ""}`,
);
}
} catch (e) {}
return value;
}
/**
* Numbers are stored as JS numbers, which loses the exact literal a cfg file
* used ("35.0" and "1e3" both become 35 / 1000). Renderers need the original
* text back, so the literal is kept next to the struct in a hidden,
* non-enumerable slot that toJson()/entries() never see.
*/
const RAW_LITERALS = "__rawLiterals__";
function rawLiterals(struct: Struct): Record<string, string> | undefined {
return struct[RAW_LITERALS];
}
export function rememberRawLiteral(
parent: Struct,
key: string | number,
raw: string,
) {
const value = parent[key];
// Only worth keeping when rendering the number would not reproduce the file.
if (typeof value !== "number" || String(value) === raw) {
return;
}
let literals = rawLiterals(parent);
if (!literals) {
literals = {};
Object.defineProperty(parent, RAW_LITERALS, {
value: literals,
enumerable: false,
writable: true,
configurable: true,
});
}
literals[key] = raw;
}
function copyRawLiterals(from: Struct, to: Struct) {
const literals = rawLiterals(from);
if (literals) {
Object.defineProperty(to, RAW_LITERALS, {
value: { ...literals },
enumerable: false,
writable: true,
configurable: true,
});
}
}
function renderLiteral(parent: Struct, key: string, value: any) {
const raw = rawLiterals(parent)?.[key];
// A reassigned field must render its new value, not the stale literal.
return raw !== undefined && parseValue(raw) === value ? raw : value;
}
function renderStructName(name: string): string {
if (name === WILDCARD) {
return "[*]"; // Special case for wildcard structs
}
if (`${name}`.startsWith("_")) {
return renderStructName(name.slice(1)); // Special case for indexed structs
}
if (isNumber(name)) {
return `[${parseInt(name)}]`;
}
return name;
}
function renderKeyName(key: string, useAsterisk?: boolean): string {
if (`${key}`.startsWith("_")) {
return renderKeyName(key.slice(1), useAsterisk); // Special case for indexed structs
}
if (`${key}`.includes("*") || useAsterisk) {
return "[*]"; // Special case for wildcard structs
}
if (`${key}`.includes("_dupe_")) {
return renderKeyName(key.slice(0, key.indexOf("_dupe_")));
}
if (isNumber(key)) {
return `[${parseInt(key)}]`;
}
return key;
}
function extractKeyFromBrackets(key: string) {
if (/\[(.+)]/.test(key)) {
return key.match(/\[(.+)]/)[1];
}
return "";
}
function parseStructName(name: string): string {
if (extractKeyFromBrackets(name) === "*") {
return WILDCARD; // Special case for wildcard structs
}
if (isNumber(extractKeyFromBrackets(name))) {
return `_${name.match(/\[(\d+)]/)[1]}`; // Special case for indexed structs
}
return name
.replace(/\W/g, "_")
.replace(/^\d+/, "_")
.replace(/_+/g, "_")
.replace(/^_+/, "");
}
const RESERVED_IDENTIFIERS = new Set([
"break",
"case",
"catch",
"class",
"const",
"continue",
"debugger",
"default",
"delete",
"do",
"else",
"export",
"extends",
"finally",
"for",
"function",
"if",
"import",
"in",
"instanceof",
"new",
"return",
"super",
"switch",
"this",
"throw",
"try",
"typeof",
"var",
"void",
"while",
"with",
"yield",
"enum",
"await",
"implements",
"package",
"protected",
"static",
"interface",
"private",
"public",
"let",
]);
function makeSafeClassName(name: string): string {
if (
!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ||
RESERVED_IDENTIFIERS.has(name)
) {
return `_${name}`;
}
return name;
}
function maybeMinifyKey(key: string, minify: boolean) {
return minify &&
(INTERNAL_PROPS.has(key as any) || REF_INTERNAL_PROPS.has(key as any))
? INTERNAL_PROPS.get(key as any) || REF_INTERNAL_PROPS.get(key as any)
: key;
}
function fromMinifiedKey(key: string, minified: boolean) {
if (!minified) return key;
return (
INTERNAL_PROPS_INV.get(key as any) ||
REF_INTERNAL_PROPS_INV.get(key as any) ||
key
);
}