-
-
Notifications
You must be signed in to change notification settings - Fork 5.7k
/
Copy pathdecorators.ts
2510 lines (2307 loc) · 76.7 KB
/
decorators.ts
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
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { NodePath, Scope, Visitor } from "@babel/core";
import { types as t, template } from "@babel/core";
import ReplaceSupers from "@babel/helper-replace-supers";
import type { PluginAPI, PluginObject, PluginPass } from "@babel/core";
import { skipTransparentExprWrappers } from "@babel/helper-skip-transparent-expression-wrappers";
import {
privateNameVisitorFactory,
type PrivateNameVisitorState,
} from "./fields.ts";
import { memoiseComputedKey } from "./misc.ts";
// We inline this package
// eslint-disable-next-line import/no-extraneous-dependencies
import * as charCodes from "charcodes";
interface Options {
/** @deprecated use `constantSuper` assumption instead. Only supported in 2021-12 version. */
loose?: boolean;
}
type ClassDecoratableElement =
| t.ClassMethod
| t.ClassPrivateMethod
| t.ClassProperty
| t.ClassPrivateProperty
| t.ClassAccessorProperty;
type ClassElement =
| ClassDecoratableElement
| t.TSDeclareMethod
| t.TSIndexSignature
| t.StaticBlock;
type ClassElementCanHaveComputedKeys =
| t.ClassMethod
| t.ClassProperty
| t.ClassAccessorProperty;
// TODO(Babel 8): Only keep 2023-11
export type DecoratorVersionKind =
| "2023-11"
| "2023-05"
| "2023-01"
| "2022-03"
| "2021-12";
function incrementId(id: number[], idx = id.length - 1): void {
// If index is -1, id needs an additional character, unshift A
if (idx === -1) {
id.unshift(charCodes.uppercaseA);
return;
}
const current = id[idx];
if (current === charCodes.uppercaseZ) {
// if current is Z, skip to a
id[idx] = charCodes.lowercaseA;
} else if (current === charCodes.lowercaseZ) {
// if current is z, reset to A and carry the 1
id[idx] = charCodes.uppercaseA;
incrementId(id, idx - 1);
} else {
// else, increment by one
id[idx] = current + 1;
}
}
/**
* Generates a new private name that is unique to the given class. This can be
* used to create extra class fields and methods for the implementation, while
* keeping the length of those names as small as possible. This is important for
* minification purposes (though private names can generally be minified,
* transpilations and polyfills cannot yet).
*/
function createPrivateUidGeneratorForClass(
classPath: NodePath<t.ClassDeclaration | t.ClassExpression>,
): () => t.PrivateName {
const currentPrivateId: number[] = [];
const privateNames = new Set<string>();
classPath.traverse({
PrivateName(path) {
privateNames.add(path.node.id.name);
},
});
return (): t.PrivateName => {
let reifiedId;
do {
incrementId(currentPrivateId);
reifiedId = String.fromCharCode(...currentPrivateId);
} while (privateNames.has(reifiedId));
return t.privateName(t.identifier(reifiedId));
};
}
/**
* Wraps the above generator function so that it's run lazily the first time
* it's actually required. Several types of decoration do not require this, so it
* saves iterating the class elements an additional time and allocating the space
* for the Sets of element names.
*/
function createLazyPrivateUidGeneratorForClass(
classPath: NodePath<t.ClassDeclaration | t.ClassExpression>,
): () => t.PrivateName {
let generator: () => t.PrivateName;
return (): t.PrivateName => {
if (!generator) {
generator = createPrivateUidGeneratorForClass(classPath);
}
return generator();
};
}
/**
* Takes a class definition and the desired class name if anonymous and
* replaces it with an equivalent class declaration (path) which is then
* assigned to a local variable (id). This allows us to reassign the local variable with the
* decorated version of the class. The class definition retains its original
* name so that `toString` is not affected, other references to the class
* are renamed instead.
*/
function replaceClassWithVar(
path: NodePath<t.ClassDeclaration | t.ClassExpression>,
className: string | t.Identifier | t.StringLiteral | undefined,
): {
id: t.Identifier;
path: NodePath<t.ClassDeclaration | t.ClassExpression>;
} {
const id = path.node.id;
const scope = path.scope;
if (path.type === "ClassDeclaration") {
const className = id.name;
const varId = scope.generateUidIdentifierBasedOnNode(id);
const classId = t.identifier(className);
scope.rename(className, varId.name);
path.get("id").replaceWith(classId);
return { id: t.cloneNode(varId), path };
} else {
let varId: t.Identifier;
if (id) {
className = id.name;
varId = generateLetUidIdentifier(scope.parent, className);
scope.rename(className, varId.name);
} else {
varId = generateLetUidIdentifier(
scope.parent,
typeof className === "string" ? className : "decorated_class",
);
}
const newClassExpr = t.classExpression(
typeof className === "string" ? t.identifier(className) : null,
path.node.superClass,
path.node.body,
);
const [newPath] = path.replaceWith(
t.sequenceExpression([newClassExpr, varId]),
);
return {
id: t.cloneNode(varId),
path: newPath.get("expressions.0") as NodePath<t.ClassExpression>,
};
}
}
function generateClassProperty(
key: t.PrivateName | t.Identifier,
value: t.Expression | undefined,
isStatic: boolean,
): t.ClassPrivateProperty | t.ClassProperty {
if (key.type === "PrivateName") {
return t.classPrivateProperty(key, value, undefined, isStatic);
} else {
return t.classProperty(key, value, undefined, undefined, isStatic);
}
}
function assignIdForAnonymousClass(
path: NodePath<t.Class>,
className: string | t.Identifier | t.StringLiteral | undefined,
) {
if (!path.node.id) {
path.node.id =
typeof className === "string"
? t.identifier(className)
: path.scope.generateUidIdentifier("Class");
}
}
function addProxyAccessorsFor(
className: t.Identifier,
element: NodePath<ClassDecoratableElement>,
getterKey: t.PrivateName | t.Expression,
setterKey: t.PrivateName | t.Expression,
targetKey: t.PrivateName,
isComputed: boolean,
isStatic: boolean,
version: DecoratorVersionKind,
): void {
const thisArg =
(version === "2023-11" ||
(!process.env.BABEL_8_BREAKING && version === "2023-05")) &&
isStatic
? className
: t.thisExpression();
const getterBody = t.blockStatement([
t.returnStatement(
t.memberExpression(t.cloneNode(thisArg), t.cloneNode(targetKey)),
),
]);
const setterBody = t.blockStatement([
t.expressionStatement(
t.assignmentExpression(
"=",
t.memberExpression(t.cloneNode(thisArg), t.cloneNode(targetKey)),
t.identifier("v"),
),
),
]);
let getter: t.ClassMethod | t.ClassPrivateMethod,
setter: t.ClassMethod | t.ClassPrivateMethod;
if (getterKey.type === "PrivateName") {
getter = t.classPrivateMethod("get", getterKey, [], getterBody, isStatic);
setter = t.classPrivateMethod(
"set",
setterKey as t.PrivateName,
[t.identifier("v")],
setterBody,
isStatic,
);
} else {
getter = t.classMethod(
"get",
getterKey,
[],
getterBody,
isComputed,
isStatic,
);
setter = t.classMethod(
"set",
setterKey as t.Expression,
[t.identifier("v")],
setterBody,
isComputed,
isStatic,
);
}
element.insertAfter(setter);
element.insertAfter(getter);
}
function extractProxyAccessorsFor(
targetKey: t.PrivateName,
version: DecoratorVersionKind,
): (t.FunctionExpression | t.ArrowFunctionExpression)[] {
if (version !== "2023-11" && version !== "2023-05" && version !== "2023-01") {
return [
template.expression.ast`
function () {
return this.${t.cloneNode(targetKey)};
}
` as t.FunctionExpression,
template.expression.ast`
function (value) {
this.${t.cloneNode(targetKey)} = value;
}
` as t.FunctionExpression,
];
}
return [
template.expression.ast`
o => o.${t.cloneNode(targetKey)}
` as t.ArrowFunctionExpression,
template.expression.ast`
(o, v) => o.${t.cloneNode(targetKey)} = v
` as t.ArrowFunctionExpression,
];
}
/**
* Get the last element for the given computed key path.
*
* This function unwraps transparent wrappers and gets the last item when
* the key is a SequenceExpression.
*
* @param {NodePath<t.Expression>} path The key of a computed class element
* @returns {NodePath<t.Expression>} The simple completion result
*/
function getComputedKeyLastElement(
path: NodePath<t.Expression>,
): NodePath<t.Expression> {
path = skipTransparentExprWrappers(path);
if (path.isSequenceExpression()) {
const expressions = path.get("expressions");
return getComputedKeyLastElement(expressions[expressions.length - 1]);
}
return path;
}
/**
* Get a memoiser of the computed key path.
*
* This function does not mutate AST. If the computed key is not a constant
* expression, this function must be called after the key has been memoised.
*
* @param {NodePath<t.Expression>} path The key of a computed class element.
* @returns {t.Expression} A clone of key if key is a constant expression,
* otherwise a memoiser identifier.
*/
function getComputedKeyMemoiser(path: NodePath<t.Expression>): t.Expression {
const element = getComputedKeyLastElement(path);
if (element.isConstantExpression()) {
return t.cloneNode(path.node);
} else if (element.isIdentifier() && path.scope.hasUid(element.node.name)) {
return t.cloneNode(path.node);
} else if (
element.isAssignmentExpression() &&
element.get("left").isIdentifier()
) {
return t.cloneNode(element.node.left as t.Identifier);
} else {
throw new Error(
`Internal Error: the computed key ${path.toString()} has not yet been memoised.`,
);
}
}
/**
* Prepend expressions to the computed key of the given field path.
*
* If the computed key is a sequence expression, this function will unwrap
* the sequence expression for optimal output size.
*
* @param {t.Expression[]} expressions
* @param {(NodePath<
* t.ClassMethod | t.ClassProperty | t.ClassAccessorProperty
* >)} fieldPath
*/
function prependExpressionsToComputedKey(
expressions: t.Expression[],
fieldPath: NodePath<
t.ClassMethod | t.ClassProperty | t.ClassAccessorProperty
>,
) {
const key = fieldPath.get("key") as NodePath<t.Expression>;
if (key.isSequenceExpression()) {
expressions.push(...key.node.expressions);
} else {
expressions.push(key.node);
}
key.replaceWith(maybeSequenceExpression(expressions));
}
/**
* Append expressions to the computed key of the given field path.
*
* If the computed key is a constant expression or uid reference, it
* will prepend expressions before the comptued key. Otherwise it will
* memoise the computed key to preserve its completion result.
*
* @param {t.Expression[]} expressions
* @param {(NodePath<
* t.ClassMethod | t.ClassProperty | t.ClassAccessorProperty
* >)} fieldPath
*/
function appendExpressionsToComputedKey(
expressions: t.Expression[],
fieldPath: NodePath<
t.ClassMethod | t.ClassProperty | t.ClassAccessorProperty
>,
) {
const key = fieldPath.get("key") as NodePath<t.Expression>;
const completion = getComputedKeyLastElement(key);
if (completion.isConstantExpression()) {
prependExpressionsToComputedKey(expressions, fieldPath);
} else {
const scopeParent = key.scope.parent;
const maybeAssignment = memoiseComputedKey(
completion.node,
scopeParent,
scopeParent.generateUid("computedKey"),
);
if (!maybeAssignment) {
// If the memoiseComputedKey returns undefined, the key is already a uid reference,
// treat it as a constant expression and prepend expressions before it
prependExpressionsToComputedKey(expressions, fieldPath);
} else {
const expressionSequence = [
...expressions,
// preserve the completion result
t.cloneNode(maybeAssignment.left),
];
const completionParent = completion.parentPath;
if (completionParent.isSequenceExpression()) {
completionParent.pushContainer("expressions", expressionSequence);
} else {
completion.replaceWith(
maybeSequenceExpression([
t.cloneNode(maybeAssignment),
...expressionSequence,
]),
);
}
}
}
}
/**
* Prepend expressions to the field initializer. If the initializer is not defined,
* this function will wrap the last expression within a `void` unary expression.
*
* @param {t.Expression[]} expressions
* @param {(NodePath<
* t.ClassProperty | t.ClassPrivateProperty | t.ClassAccessorProperty
* >)} fieldPath
*/
function prependExpressionsToFieldInitializer(
expressions: t.Expression[],
fieldPath: NodePath<
t.ClassProperty | t.ClassPrivateProperty | t.ClassAccessorProperty
>,
) {
const initializer = fieldPath.get("value");
if (initializer.node) {
expressions.push(initializer.node);
} else if (expressions.length > 0) {
expressions[expressions.length - 1] = t.unaryExpression(
"void",
expressions[expressions.length - 1],
);
}
initializer.replaceWith(maybeSequenceExpression(expressions));
}
function prependExpressionsToStaticBlock(
expressions: t.Expression[],
blockPath: NodePath<t.StaticBlock>,
) {
blockPath.unshiftContainer(
"body",
t.expressionStatement(maybeSequenceExpression(expressions)),
);
}
function prependExpressionsToConstructor(
expressions: t.Expression[],
constructorPath: NodePath<t.ClassMethod>,
) {
constructorPath.node.body.body.unshift(
t.expressionStatement(maybeSequenceExpression(expressions)),
);
}
function isProtoInitCallExpression(
expression: t.Expression,
protoInitCall: t.Identifier,
) {
return (
t.isCallExpression(expression) &&
t.isIdentifier(expression.callee, { name: protoInitCall.name })
);
}
/**
* Optimize super call and its following expressions
*
* @param {t.Expression[]} expressions Mutated by this function. The first element must by a super call
* @param {t.Identifier} protoInitLocal The generated protoInit id
* @returns optimized expression
*/
function optimizeSuperCallAndExpressions(
expressions: t.Expression[],
protoInitLocal: t.Identifier,
) {
if (protoInitLocal) {
if (
expressions.length >= 2 &&
isProtoInitCallExpression(expressions[1], protoInitLocal)
) {
// Merge `super(), protoInit(this)` into `protoInit(super())`
const mergedSuperCall = t.callExpression(t.cloneNode(protoInitLocal), [
expressions[0],
]);
expressions.splice(0, 2, mergedSuperCall);
}
// Merge `protoInit(super()), this` into `protoInit(super())`
if (
expressions.length >= 2 &&
t.isThisExpression(expressions[expressions.length - 1]) &&
isProtoInitCallExpression(
expressions[expressions.length - 2],
protoInitLocal,
)
) {
expressions.splice(expressions.length - 1, 1);
}
}
return maybeSequenceExpression(expressions);
}
/**
* Insert expressions immediately after super() and optimize the output if possible.
* This function will preserve the completion result using the trailing this expression.
*
* @param {t.Expression[]} expressions
* @param {NodePath<t.ClassMethod>} constructorPath
* @param {t.Identifier} protoInitLocal The generated protoInit id
* @returns
*/
function insertExpressionsAfterSuperCallAndOptimize(
expressions: t.Expression[],
constructorPath: NodePath<t.ClassMethod>,
protoInitLocal: t.Identifier,
) {
constructorPath.traverse({
CallExpression: {
exit(path) {
if (!path.get("callee").isSuper()) return;
const newNodes = [
path.node,
...expressions.map(expr => t.cloneNode(expr)),
];
// preserve completion result if super() is in an RHS or a return statement
if (path.isCompletionRecord()) {
newNodes.push(t.thisExpression());
}
path.replaceWith(
optimizeSuperCallAndExpressions(newNodes, protoInitLocal),
);
path.skip();
},
},
ClassMethod(path) {
if (path.node.kind === "constructor") {
path.skip();
}
},
});
}
/**
* Build a class constructor node from the given expressions. If the class is
* derived, the constructor will call super() first to ensure that `this`
* in the expressions work as expected.
*
* @param {t.Expression[]} expressions
* @param {boolean} isDerivedClass
* @returns The class constructor node
*/
function createConstructorFromExpressions(
expressions: t.Expression[],
isDerivedClass: boolean,
) {
const body: t.Statement[] = [
t.expressionStatement(maybeSequenceExpression(expressions)),
];
if (isDerivedClass) {
body.unshift(
t.expressionStatement(
t.callExpression(t.super(), [t.spreadElement(t.identifier("args"))]),
),
);
}
return t.classMethod(
"constructor",
t.identifier("constructor"),
isDerivedClass ? [t.restElement(t.identifier("args"))] : [],
t.blockStatement(body),
);
}
function createStaticBlockFromExpressions(expressions: t.Expression[]) {
return t.staticBlock([
t.expressionStatement(maybeSequenceExpression(expressions)),
]);
}
// 3 bits reserved to this (0-7)
const FIELD = 0;
const ACCESSOR = 1;
const METHOD = 2;
const GETTER = 3;
const SETTER = 4;
const STATIC_OLD_VERSION = 5; // Before 2023-05
const STATIC = 8; // 1 << 3
const DECORATORS_HAVE_THIS = 16; // 1 << 4
function getElementKind(element: NodePath<ClassDecoratableElement>): number {
switch (element.node.type) {
case "ClassProperty":
case "ClassPrivateProperty":
return FIELD;
case "ClassAccessorProperty":
return ACCESSOR;
case "ClassMethod":
case "ClassPrivateMethod":
if (element.node.kind === "get") {
return GETTER;
} else if (element.node.kind === "set") {
return SETTER;
} else {
return METHOD;
}
}
}
// Information about the decorators applied to an element
interface DecoratorInfo {
// An array of applied decorators or a memoised identifier
decoratorsArray: t.Identifier | t.ArrayExpression | t.Expression;
decoratorsHaveThis: boolean;
// The kind of the decorated value, matches the kind value passed to applyDecs
kind: number;
// whether or not the field is static
isStatic: boolean;
// The name of the decorator
name: t.StringLiteral | t.Expression;
privateMethods:
| (t.FunctionExpression | t.ArrowFunctionExpression)[]
| undefined;
// The names of local variables that will be used/returned from the decoration
locals: t.Identifier | t.Identifier[] | undefined;
}
/**
* Sort decoration info in the application order:
* - static non-fields
* - instance non-fields
* - static fields
* - instance fields
*
* @param {DecoratorInfo[]} info
* @returns {DecoratorInfo[]} Sorted decoration info
*/
function toSortedDecoratorInfo(info: DecoratorInfo[]): DecoratorInfo[] {
return [
...info.filter(
el => el.isStatic && el.kind >= ACCESSOR && el.kind <= SETTER,
),
...info.filter(
el => !el.isStatic && el.kind >= ACCESSOR && el.kind <= SETTER,
),
...info.filter(el => el.isStatic && el.kind === FIELD),
...info.filter(el => !el.isStatic && el.kind === FIELD),
];
}
type GenerateDecorationListResult = {
// The zipped decorators array that will be passed to generateDecorationExprs
decs: t.Expression[];
// Whether there are non-empty decorator this values
haveThis: boolean;
};
/**
* Zip decorators and decorator this values into an array
*
* @param {t.Decorator[]} decorators
* @param {((t.Expression | undefined)[])} decoratorsThis decorator this values
* @param {DecoratorVersionKind} version
* @returns {GenerateDecorationListResult}
*/
function generateDecorationList(
decorators: t.Decorator[],
decoratorsThis: (t.Expression | undefined)[],
version: DecoratorVersionKind,
): GenerateDecorationListResult {
const decsCount = decorators.length;
const haveOneThis = decoratorsThis.some(Boolean);
const decs: t.Expression[] = [];
for (let i = 0; i < decsCount; i++) {
if (
(version === "2023-11" ||
(!process.env.BABEL_8_BREAKING && version === "2023-05")) &&
haveOneThis
) {
decs.push(
decoratorsThis[i] || t.unaryExpression("void", t.numericLiteral(0)),
);
}
decs.push(decorators[i].expression);
}
return { haveThis: haveOneThis, decs };
}
function generateDecorationExprs(
decorationInfo: DecoratorInfo[],
version: DecoratorVersionKind,
): t.ArrayExpression {
return t.arrayExpression(
decorationInfo.map(el => {
let flag = el.kind;
if (el.isStatic) {
flag +=
version === "2023-11" ||
(!process.env.BABEL_8_BREAKING && version === "2023-05")
? STATIC
: STATIC_OLD_VERSION;
}
if (el.decoratorsHaveThis) flag += DECORATORS_HAVE_THIS;
return t.arrayExpression([
el.decoratorsArray,
t.numericLiteral(flag),
el.name,
...(el.privateMethods || []),
]);
}),
);
}
function extractElementLocalAssignments(decorationInfo: DecoratorInfo[]) {
const localIds: t.Identifier[] = [];
for (const el of decorationInfo) {
const { locals } = el;
if (Array.isArray(locals)) {
localIds.push(...locals);
} else if (locals !== undefined) {
localIds.push(locals);
}
}
return localIds;
}
function addCallAccessorsFor(
version: DecoratorVersionKind,
element: NodePath,
key: t.PrivateName,
getId: t.Identifier,
setId: t.Identifier,
isStatic: boolean,
) {
element.insertAfter(
t.classPrivateMethod(
"get",
t.cloneNode(key),
[],
t.blockStatement([
t.returnStatement(
t.callExpression(
t.cloneNode(getId),
(process.env.BABEL_8_BREAKING || version === "2023-11") && isStatic
? []
: [t.thisExpression()],
),
),
]),
isStatic,
),
);
element.insertAfter(
t.classPrivateMethod(
"set",
t.cloneNode(key),
[t.identifier("v")],
t.blockStatement([
t.expressionStatement(
t.callExpression(
t.cloneNode(setId),
(process.env.BABEL_8_BREAKING || version === "2023-11") && isStatic
? [t.identifier("v")]
: [t.thisExpression(), t.identifier("v")],
),
),
]),
isStatic,
),
);
}
function movePrivateAccessor(
element: NodePath<t.ClassPrivateMethod>,
key: t.PrivateName,
methodLocalVar: t.Identifier,
isStatic: boolean,
) {
let params: (t.Identifier | t.RestElement)[];
let block: t.Statement[];
if (element.node.kind === "set") {
params = [t.identifier("v")];
block = [
t.expressionStatement(
t.callExpression(methodLocalVar, [
t.thisExpression(),
t.identifier("v"),
]),
),
];
} else {
params = [];
block = [
t.returnStatement(t.callExpression(methodLocalVar, [t.thisExpression()])),
];
}
element.replaceWith(
t.classPrivateMethod(
element.node.kind,
t.cloneNode(key),
params,
t.blockStatement(block),
isStatic,
),
);
}
function isClassDecoratableElementPath(
path: NodePath<ClassElement>,
): path is NodePath<ClassDecoratableElement> {
const { type } = path;
return (
type !== "TSDeclareMethod" &&
type !== "TSIndexSignature" &&
type !== "StaticBlock"
);
}
function staticBlockToIIFE(block: t.StaticBlock) {
return t.callExpression(
t.arrowFunctionExpression([], t.blockStatement(block.body)),
[],
);
}
function staticBlockToFunctionClosure(block: t.StaticBlock) {
return t.functionExpression(null, [], t.blockStatement(block.body));
}
function fieldInitializerToClosure(value: t.Expression) {
return t.functionExpression(
null,
[],
t.blockStatement([t.returnStatement(value)]),
);
}
function maybeSequenceExpression(exprs: t.Expression[]) {
if (exprs.length === 0) return t.unaryExpression("void", t.numericLiteral(0));
if (exprs.length === 1) return exprs[0];
return t.sequenceExpression(exprs);
}
/**
* Create FunctionExpression from a ClassPrivateMethod.
* The returned FunctionExpression node takes ownership of the private method's body and params.
*
* @param {t.ClassPrivateMethod} node
* @returns
*/
function createFunctionExpressionFromPrivateMethod(node: t.ClassPrivateMethod) {
const { params, body, generator: isGenerator, async: isAsync } = node;
return t.functionExpression(
undefined,
// @ts-expect-error todo: Improve typings: TSParameterProperty is only allowed in constructor
params,
body,
isGenerator,
isAsync,
);
}
function createSetFunctionNameCall(
state: PluginPass,
className: t.Identifier | t.StringLiteral,
) {
return t.callExpression(state.addHelper("setFunctionName"), [
t.thisExpression(),
className,
]);
}
function createToPropertyKeyCall(state: PluginPass, propertyKey: t.Expression) {
return t.callExpression(state.addHelper("toPropertyKey"), [propertyKey]);
}
function createPrivateBrandCheckClosure(brandName: t.PrivateName) {
return t.arrowFunctionExpression(
[t.identifier("_")],
t.binaryExpression("in", t.cloneNode(brandName), t.identifier("_")),
);
}
function usesPrivateField(expression: t.Node) {
try {
t.traverseFast(expression, node => {
if (t.isPrivateName(node)) {
// TODO: Add early return support to t.traverseFast
// eslint-disable-next-line @typescript-eslint/only-throw-error
throw null;
}
});
return false;
} catch {
return true;
}
}
/**
* Convert a non-computed class element to its equivalent computed form.
*
* This function is to provide a decorator evaluation storage from non-computed
* class elements.
*
* @param {(NodePath<t.ClassProperty | t.ClassMethod>)} path A non-computed class property or method
*/
function convertToComputedKey(path: NodePath<t.ClassProperty | t.ClassMethod>) {
const { node } = path;
node.computed = true;
if (t.isIdentifier(node.key)) {
node.key = t.stringLiteral(node.key.name);
}
}
function hasInstancePrivateAccess(path: NodePath, privateNames: string[]) {
let containsInstancePrivateAccess = false;
if (privateNames.length > 0) {
const privateNameVisitor = privateNameVisitorFactory<
PrivateNameVisitorState<null>,
null
>({
PrivateName(path, state) {
if (state.privateNamesMap.has(path.node.id.name)) {
containsInstancePrivateAccess = true;
path.stop();
}
},
});
const privateNamesMap = new Map<string, null>();
for (const name of privateNames) {
privateNamesMap.set(name, null);
}
path.traverse(privateNameVisitor, {
privateNamesMap: privateNamesMap,
});
}
return containsInstancePrivateAccess;
}
function checkPrivateMethodUpdateError(
path: NodePath<t.Class>,
decoratedPrivateMethods: Set<string>,
) {
const privateNameVisitor = privateNameVisitorFactory<
PrivateNameVisitorState<null>,
null
>({
PrivateName(path, state) {
if (!state.privateNamesMap.has(path.node.id.name)) return;
const parentPath = path.parentPath;
const parentParentPath = parentPath.parentPath;
if (
// this.bar().#x = 123;
(parentParentPath.node.type === "AssignmentExpression" &&
parentParentPath.node.left === parentPath.node) ||
// this.#x++;
parentParentPath.node.type === "UpdateExpression" ||
// ([...this.#x] = foo);
parentParentPath.node.type === "RestElement" ||
// ([this.#x] = foo);
parentParentPath.node.type === "ArrayPattern" ||
// ({ a: this.#x } = bar);
(parentParentPath.node.type === "ObjectProperty" &&
parentParentPath.node.value === parentPath.node &&
parentParentPath.parentPath.type === "ObjectPattern") ||
// for (this.#x of []);
(parentParentPath.node.type === "ForOfStatement" &&
parentParentPath.node.left === parentPath.node)
) {
throw path.buildCodeFrameError(