| 1 |
import type { NodePath, Scope } from "@babel/traverse"; |
| 2 |
import { types as t, template } from "@babel/core"; |
| 3 |
import syntaxDecorators from "@babel/plugin-syntax-decorators"; |
| 4 |
import ReplaceSupers from "@babel/helper-replace-supers"; |
| 5 |
import splitExportDeclaration from "@babel/helper-split-export-declaration"; |
| 6 |
import * as charCodes from "charcodes"; |
| 7 |
import type { PluginAPI, PluginObject, PluginPass } from "@babel/core"; |
| 8 |
import type { Options } from "./index"; |
| 9 |
|
| 10 |
type ClassDecoratableElement = |
| 11 |
| t.ClassMethod |
| 12 |
| t.ClassPrivateMethod |
| 13 |
| t.ClassProperty |
| 14 |
| t.ClassPrivateProperty |
| 15 |
| t.ClassAccessorProperty; |
| 16 |
|
| 17 |
type ClassElement = |
| 18 |
| ClassDecoratableElement |
| 19 |
| t.TSDeclareMethod |
| 20 |
| t.TSIndexSignature |
| 21 |
| t.StaticBlock; |
| 22 |
|
| 23 |
type DecoratorVersionKind = "2022-03" | "2021-12"; |
| 24 |
|
| 25 |
function incrementId(id: number[], idx = id.length - 1): void { |
| 26 |
// If index is -1, id needs an additional character, unshift A |
| 27 |
if (idx === -1) { |
| 28 |
id.unshift(charCodes.uppercaseA); |
| 29 |
return; |
| 30 |
} |
| 31 |
|
| 32 |
const current = id[idx]; |
| 33 |
|
| 34 |
if (current === charCodes.uppercaseZ) { |
| 35 |
// if current is Z, skip to a |
| 36 |
id[idx] = charCodes.lowercaseA; |
| 37 |
} else if (current === charCodes.lowercaseZ) { |
| 38 |
// if current is z, reset to A and carry the 1 |
| 39 |
id[idx] = charCodes.uppercaseA; |
| 40 |
incrementId(id, idx - 1); |
| 41 |
} else { |
| 42 |
// else, increment by one |
| 43 |
id[idx] = current + 1; |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* Generates a new private name that is unique to the given class. This can be |
| 49 |
* used to create extra class fields and methods for the implementation, while |
| 50 |
* keeping the length of those names as small as possible. This is important for |
| 51 |
* minification purposes (though private names can generally be minified, |
| 52 |
* transpilations and polyfills cannot yet). |
| 53 |
*/ |
| 54 |
function createPrivateUidGeneratorForClass( |
| 55 |
classPath: NodePath<t.ClassDeclaration | t.ClassExpression>, |
| 56 |
): () => t.PrivateName { |
| 57 |
const currentPrivateId: number[] = []; |
| 58 |
const privateNames = new Set<string>(); |
| 59 |
|
| 60 |
classPath.traverse({ |
| 61 |
PrivateName(path) { |
| 62 |
privateNames.add(path.node.id.name); |
| 63 |
}, |
| 64 |
}); |
| 65 |
|
| 66 |
return (): t.PrivateName => { |
| 67 |
let reifiedId; |
| 68 |
do { |
| 69 |
incrementId(currentPrivateId); |
| 70 |
reifiedId = String.fromCharCode(...currentPrivateId); |
| 71 |
} while (privateNames.has(reifiedId)); |
| 72 |
|
| 73 |
return t.privateName(t.identifier(reifiedId)); |
| 74 |
}; |
| 75 |
} |
| 76 |
|
| 77 |
/** |
| 78 |
* Wraps the above generator function so that it's run lazily the first time |
| 79 |
* it's actually required. Several types of decoration do not require this, so it |
| 80 |
* saves iterating the class elements an additional time and allocating the space |
| 81 |
* for the Sets of element names. |
| 82 |
*/ |
| 83 |
function createLazyPrivateUidGeneratorForClass( |
| 84 |
classPath: NodePath<t.ClassDeclaration | t.ClassExpression>, |
| 85 |
): () => t.PrivateName { |
| 86 |
let generator: () => t.PrivateName; |
| 87 |
|
| 88 |
return (): t.PrivateName => { |
| 89 |
if (!generator) { |
| 90 |
generator = createPrivateUidGeneratorForClass(classPath); |
| 91 |
} |
| 92 |
|
| 93 |
return generator(); |
| 94 |
}; |
| 95 |
} |
| 96 |
|
| 97 |
/** |
| 98 |
* Takes a class definition and replaces it with an equivalent class declaration |
| 99 |
* which is then assigned to a local variable. This allows us to reassign the |
| 100 |
* local variable with the decorated version of the class. The class definition |
| 101 |
* retains its original name so that `toString` is not affected, other |
| 102 |
* references to the class are renamed instead. |
| 103 |
*/ |
| 104 |
function replaceClassWithVar( |
| 105 |
path: NodePath<t.ClassDeclaration | t.ClassExpression>, |
| 106 |
): [t.Identifier, NodePath<t.ClassDeclaration | t.ClassExpression>] { |
| 107 |
if (path.type === "ClassDeclaration") { |
| 108 |
const varId = path.scope.generateUidIdentifierBasedOnNode(path.node.id); |
| 109 |
const classId = t.identifier(path.node.id.name); |
| 110 |
|
| 111 |
path.scope.rename(classId.name, varId.name); |
| 112 |
|
| 113 |
path.insertBefore( |
| 114 |
t.variableDeclaration("let", [t.variableDeclarator(varId)]), |
| 115 |
); |
| 116 |
path.get("id").replaceWith(classId); |
| 117 |
|
| 118 |
return [t.cloneNode(varId), path]; |
| 119 |
} else { |
| 120 |
let className: string; |
| 121 |
let varId: t.Identifier; |
| 122 |
|
| 123 |
if (path.node.id) { |
| 124 |
className = path.node.id.name; |
| 125 |
varId = path.scope.parent.generateDeclaredUidIdentifier(className); |
| 126 |
path.scope.rename(className, varId.name); |
| 127 |
} else if ( |
| 128 |
path.parentPath.node.type === "VariableDeclarator" && |
| 129 |
path.parentPath.node.id.type === "Identifier" |
| 130 |
) { |
| 131 |
className = path.parentPath.node.id.name; |
| 132 |
varId = path.scope.parent.generateDeclaredUidIdentifier(className); |
| 133 |
} else { |
| 134 |
varId = |
| 135 |
path.scope.parent.generateDeclaredUidIdentifier("decorated_class"); |
| 136 |
} |
| 137 |
|
| 138 |
const newClassExpr = t.classExpression( |
| 139 |
className && t.identifier(className), |
| 140 |
path.node.superClass, |
| 141 |
path.node.body, |
| 142 |
); |
| 143 |
|
| 144 |
const [newPath] = path.replaceWith( |
| 145 |
t.sequenceExpression([newClassExpr, varId]), |
| 146 |
); |
| 147 |
|
| 148 |
return [ |
| 149 |
t.cloneNode(varId), |
| 150 |
newPath.get("expressions.0") as NodePath<t.ClassExpression>, |
| 151 |
]; |
| 152 |
} |
| 153 |
} |
| 154 |
|
| 155 |
function generateClassProperty( |
| 156 |
key: t.PrivateName | t.Identifier, |
| 157 |
value: t.Expression | undefined, |
| 158 |
isStatic: boolean, |
| 159 |
): t.ClassPrivateProperty | t.ClassProperty { |
| 160 |
if (key.type === "PrivateName") { |
| 161 |
return t.classPrivateProperty(key, value, undefined, isStatic); |
| 162 |
} else { |
| 163 |
return t.classProperty(key, value, undefined, undefined, isStatic); |
| 164 |
} |
| 165 |
} |
| 166 |
|
| 167 |
function addProxyAccessorsFor( |
| 168 |
element: NodePath<ClassDecoratableElement>, |
| 169 |
originalKey: t.PrivateName | t.Expression, |
| 170 |
targetKey: t.PrivateName, |
| 171 |
isComputed = false, |
| 172 |
): void { |
| 173 |
const { static: isStatic } = element.node; |
| 174 |
|
| 175 |
const getterBody = t.blockStatement([ |
| 176 |
t.returnStatement( |
| 177 |
t.memberExpression(t.thisExpression(), t.cloneNode(targetKey)), |
| 178 |
), |
| 179 |
]); |
| 180 |
|
| 181 |
const setterBody = t.blockStatement([ |
| 182 |
t.expressionStatement( |
| 183 |
t.assignmentExpression( |
| 184 |
"=", |
| 185 |
t.memberExpression(t.thisExpression(), t.cloneNode(targetKey)), |
| 186 |
t.identifier("v"), |
| 187 |
), |
| 188 |
), |
| 189 |
]); |
| 190 |
|
| 191 |
let getter: t.ClassMethod | t.ClassPrivateMethod, |
| 192 |
setter: t.ClassMethod | t.ClassPrivateMethod; |
| 193 |
|
| 194 |
if (originalKey.type === "PrivateName") { |
| 195 |
getter = t.classPrivateMethod( |
| 196 |
"get", |
| 197 |
t.cloneNode(originalKey), |
| 198 |
[], |
| 199 |
getterBody, |
| 200 |
isStatic, |
| 201 |
); |
| 202 |
setter = t.classPrivateMethod( |
| 203 |
"set", |
| 204 |
t.cloneNode(originalKey), |
| 205 |
[t.identifier("v")], |
| 206 |
setterBody, |
| 207 |
isStatic, |
| 208 |
); |
| 209 |
} else { |
| 210 |
getter = t.classMethod( |
| 211 |
"get", |
| 212 |
t.cloneNode(originalKey), |
| 213 |
[], |
| 214 |
getterBody, |
| 215 |
isComputed, |
| 216 |
isStatic, |
| 217 |
); |
| 218 |
setter = t.classMethod( |
| 219 |
"set", |
| 220 |
t.cloneNode(originalKey), |
| 221 |
[t.identifier("v")], |
| 222 |
setterBody, |
| 223 |
isComputed, |
| 224 |
isStatic, |
| 225 |
); |
| 226 |
} |
| 227 |
|
| 228 |
element.insertAfter(setter); |
| 229 |
element.insertAfter(getter); |
| 230 |
} |
| 231 |
|
| 232 |
function extractProxyAccessorsFor( |
| 233 |
targetKey: t.PrivateName, |
| 234 |
): t.FunctionExpression[] { |
| 235 |
return [ |
| 236 |
t.functionExpression( |
| 237 |
undefined, |
| 238 |
[], |
| 239 |
t.blockStatement([ |
| 240 |
t.returnStatement( |
| 241 |
t.memberExpression(t.thisExpression(), t.cloneNode(targetKey)), |
| 242 |
), |
| 243 |
]), |
| 244 |
), |
| 245 |
t.functionExpression( |
| 246 |
undefined, |
| 247 |
[t.identifier("value")], |
| 248 |
t.blockStatement([ |
| 249 |
t.expressionStatement( |
| 250 |
t.assignmentExpression( |
| 251 |
"=", |
| 252 |
t.memberExpression(t.thisExpression(), t.cloneNode(targetKey)), |
| 253 |
t.identifier("value"), |
| 254 |
), |
| 255 |
), |
| 256 |
]), |
| 257 |
), |
| 258 |
]; |
| 259 |
} |
| 260 |
|
| 261 |
const FIELD = 0; |
| 262 |
const ACCESSOR = 1; |
| 263 |
const METHOD = 2; |
| 264 |
const GETTER = 3; |
| 265 |
const SETTER = 4; |
| 266 |
|
| 267 |
const STATIC = 5; |
| 268 |
|
| 269 |
function getElementKind(element: NodePath<ClassDecoratableElement>): number { |
| 270 |
switch (element.node.type) { |
| 271 |
case "ClassProperty": |
| 272 |
case "ClassPrivateProperty": |
| 273 |
return FIELD; |
| 274 |
case "ClassAccessorProperty": |
| 275 |
return ACCESSOR; |
| 276 |
case "ClassMethod": |
| 277 |
case "ClassPrivateMethod": |
| 278 |
if (element.node.kind === "get") { |
| 279 |
return GETTER; |
| 280 |
} else if (element.node.kind === "set") { |
| 281 |
return SETTER; |
| 282 |
} else { |
| 283 |
return METHOD; |
| 284 |
} |
| 285 |
} |
| 286 |
} |
| 287 |
|
| 288 |
// Information about the decorators applied to an element |
| 289 |
interface DecoratorInfo { |
| 290 |
// The expressions of the decorators themselves |
| 291 |
decorators: t.Expression[]; |
| 292 |
|
| 293 |
// The kind of the decorated value, matches the kind value passed to applyDecs |
| 294 |
kind: number; |
| 295 |
|
| 296 |
// whether or not the field is static |
| 297 |
isStatic: boolean; |
| 298 |
|
| 299 |
// The name of the decorator |
| 300 |
name: t.StringLiteral | t.Expression; |
| 301 |
|
| 302 |
privateMethods: t.FunctionExpression | t.FunctionExpression[] | undefined; |
| 303 |
|
| 304 |
// The names of local variables that will be used/returned from the decoration |
| 305 |
locals: t.Identifier | t.Identifier[] | undefined; |
| 306 |
} |
| 307 |
|
| 308 |
// Information about a computed property key. These must be evaluated |
| 309 |
// interspersed with decorator expressions, which is why they get added to the |
| 310 |
// array of DecoratorInfos later on. |
| 311 |
interface ComputedPropInfo { |
| 312 |
localComputedNameId: t.Identifier; |
| 313 |
keyNode: t.Expression; |
| 314 |
} |
| 315 |
|
| 316 |
function isDecoratorInfo( |
| 317 |
info: DecoratorInfo | ComputedPropInfo, |
| 318 |
): info is DecoratorInfo { |
| 319 |
return "decorators" in info; |
| 320 |
} |
| 321 |
|
| 322 |
function filteredOrderedDecoratorInfo( |
| 323 |
info: (DecoratorInfo | ComputedPropInfo)[], |
| 324 |
): DecoratorInfo[] { |
| 325 |
const filtered = info.filter(isDecoratorInfo); |
| 326 |
|
| 327 |
return [ |
| 328 |
...filtered.filter( |
| 329 |
el => el.isStatic && el.kind >= ACCESSOR && el.kind <= SETTER, |
| 330 |
), |
| 331 |
...filtered.filter( |
| 332 |
el => !el.isStatic && el.kind >= ACCESSOR && el.kind <= SETTER, |
| 333 |
), |
| 334 |
...filtered.filter(el => el.isStatic && el.kind === FIELD), |
| 335 |
...filtered.filter(el => !el.isStatic && el.kind === FIELD), |
| 336 |
]; |
| 337 |
} |
| 338 |
|
| 339 |
function generateDecorationExprs( |
| 340 |
info: (DecoratorInfo | ComputedPropInfo)[], |
| 341 |
): t.ArrayExpression { |
| 342 |
return t.arrayExpression( |
| 343 |
filteredOrderedDecoratorInfo(info).map(el => { |
| 344 |
const decs = |
| 345 |
el.decorators.length > 1 |
| 346 |
? t.arrayExpression(el.decorators) |
| 347 |
: el.decorators[0]; |
| 348 |
|
| 349 |
const kind = el.isStatic ? el.kind + STATIC : el.kind; |
| 350 |
|
| 351 |
const decInfo = [decs, t.numericLiteral(kind), el.name]; |
| 352 |
|
| 353 |
const { privateMethods } = el; |
| 354 |
|
| 355 |
if (Array.isArray(privateMethods)) { |
| 356 |
decInfo.push(...privateMethods); |
| 357 |
} else if (privateMethods) { |
| 358 |
decInfo.push(privateMethods); |
| 359 |
} |
| 360 |
|
| 361 |
return t.arrayExpression(decInfo); |
| 362 |
}), |
| 363 |
); |
| 364 |
} |
| 365 |
|
| 366 |
function extractElementLocalAssignments( |
| 367 |
decorationInfo: (DecoratorInfo | ComputedPropInfo)[], |
| 368 |
) { |
| 369 |
const localIds: t.Identifier[] = []; |
| 370 |
|
| 371 |
for (const el of filteredOrderedDecoratorInfo(decorationInfo)) { |
| 372 |
const { locals } = el; |
| 373 |
|
| 374 |
if (Array.isArray(locals)) { |
| 375 |
localIds.push(...locals); |
| 376 |
} else if (locals !== undefined) { |
| 377 |
localIds.push(locals); |
| 378 |
} |
| 379 |
} |
| 380 |
|
| 381 |
return localIds; |
| 382 |
} |
| 383 |
|
| 384 |
function addCallAccessorsFor( |
| 385 |
element: NodePath, |
| 386 |
key: t.PrivateName, |
| 387 |
getId: t.Identifier, |
| 388 |
setId: t.Identifier, |
| 389 |
) { |
| 390 |
element.insertAfter( |
| 391 |
t.classPrivateMethod( |
| 392 |
"get", |
| 393 |
t.cloneNode(key), |
| 394 |
[], |
| 395 |
t.blockStatement([ |
| 396 |
t.returnStatement( |
| 397 |
t.callExpression(t.cloneNode(getId), [t.thisExpression()]), |
| 398 |
), |
| 399 |
]), |
| 400 |
), |
| 401 |
); |
| 402 |
|
| 403 |
element.insertAfter( |
| 404 |
t.classPrivateMethod( |
| 405 |
"set", |
| 406 |
t.cloneNode(key), |
| 407 |
[t.identifier("v")], |
| 408 |
t.blockStatement([ |
| 409 |
t.expressionStatement( |
| 410 |
t.callExpression(t.cloneNode(setId), [ |
| 411 |
t.thisExpression(), |
| 412 |
t.identifier("v"), |
| 413 |
]), |
| 414 |
), |
| 415 |
]), |
| 416 |
), |
| 417 |
); |
| 418 |
} |
| 419 |
|
| 420 |
function isNotTsParameter( |
| 421 |
node: t.Identifier | t.Pattern | t.RestElement | t.TSParameterProperty, |
| 422 |
): node is t.Identifier | t.Pattern | t.RestElement { |
| 423 |
return node.type !== "TSParameterProperty"; |
| 424 |
} |
| 425 |
|
| 426 |
function movePrivateAccessor( |
| 427 |
element: NodePath<t.ClassPrivateMethod>, |
| 428 |
key: t.PrivateName, |
| 429 |
methodLocalVar: t.Identifier, |
| 430 |
isStatic: boolean, |
| 431 |
) { |
| 432 |
let params: (t.Identifier | t.RestElement)[]; |
| 433 |
let block: t.Statement[]; |
| 434 |
|
| 435 |
if (element.node.kind === "set") { |
| 436 |
params = [t.identifier("v")]; |
| 437 |
block = [ |
| 438 |
t.expressionStatement( |
| 439 |
t.callExpression(methodLocalVar, [ |
| 440 |
t.thisExpression(), |
| 441 |
t.identifier("v"), |
| 442 |
]), |
| 443 |
), |
| 444 |
]; |
| 445 |
} else { |
| 446 |
params = []; |
| 447 |
block = [ |
| 448 |
t.returnStatement(t.callExpression(methodLocalVar, [t.thisExpression()])), |
| 449 |
]; |
| 450 |
} |
| 451 |
|
| 452 |
element.replaceWith( |
| 453 |
t.classPrivateMethod( |
| 454 |
element.node.kind, |
| 455 |
t.cloneNode(key), |
| 456 |
params, |
| 457 |
t.blockStatement(block), |
| 458 |
isStatic, |
| 459 |
), |
| 460 |
); |
| 461 |
} |
| 462 |
|
| 463 |
function isClassDecoratableElementPath( |
| 464 |
path: NodePath<ClassElement>, |
| 465 |
): path is NodePath<ClassDecoratableElement> { |
| 466 |
const { type } = path; |
| 467 |
|
| 468 |
return ( |
| 469 |
type !== "TSDeclareMethod" && |
| 470 |
type !== "TSIndexSignature" && |
| 471 |
type !== "StaticBlock" |
| 472 |
); |
| 473 |
} |
| 474 |
|
| 475 |
function staticBlockToIIFE(block: t.StaticBlock) { |
| 476 |
return t.callExpression( |
| 477 |
t.arrowFunctionExpression([], t.blockStatement(block.body)), |
| 478 |
[], |
| 479 |
); |
| 480 |
} |
| 481 |
|
| 482 |
function maybeSequenceExpression(exprs: t.Expression[]) { |
| 483 |
if (exprs.length === 0) return t.unaryExpression("void", t.numericLiteral(0)); |
| 484 |
if (exprs.length === 1) return exprs[0]; |
| 485 |
return t.sequenceExpression(exprs); |
| 486 |
} |
| 487 |
|
| 488 |
function transformClass( |
| 489 |
path: NodePath<t.ClassExpression | t.ClassDeclaration>, |
| 490 |
state: PluginPass, |
| 491 |
constantSuper: boolean, |
| 492 |
version: DecoratorVersionKind, |
| 493 |
): NodePath { |
| 494 |
const body = path.get("body.body"); |
| 495 |
|
| 496 |
const classDecorators = path.node.decorators; |
| 497 |
let hasElementDecorators = false; |
| 498 |
|
| 499 |
const generateClassPrivateUid = createLazyPrivateUidGeneratorForClass(path); |
| 500 |
|
| 501 |
// Iterate over the class to see if we need to decorate it, and also to |
| 502 |
// transform simple auto accessors which are not decorated |
| 503 |
for (const element of body) { |
| 504 |
if (!isClassDecoratableElementPath(element)) { |
| 505 |
continue; |
| 506 |
} |
| 507 |
|
| 508 |
if (element.node.decorators && element.node.decorators.length > 0) { |
| 509 |
hasElementDecorators = true; |
| 510 |
} else if (element.node.type === "ClassAccessorProperty") { |
| 511 |
const { key, value, static: isStatic, computed } = element.node; |
| 512 |
|
| 513 |
const newId = generateClassPrivateUid(); |
| 514 |
|
| 515 |
const valueNode = value ? t.cloneNode(value) : undefined; |
| 516 |
|
| 517 |
const newField = generateClassProperty(newId, valueNode, isStatic); |
| 518 |
|
| 519 |
const [newPath] = element.replaceWith(newField); |
| 520 |
addProxyAccessorsFor(newPath, key, newId, computed); |
| 521 |
} |
| 522 |
} |
| 523 |
|
| 524 |
// If nothing is decorated, return |
| 525 |
if (!classDecorators && !hasElementDecorators) return; |
| 526 |
|
| 527 |
const elementDecoratorInfo: (DecoratorInfo | ComputedPropInfo)[] = []; |
| 528 |
|
| 529 |
// The initializer of the first non-static field will be injected with the protoInit call |
| 530 |
let firstFieldPath: |
| 531 |
| NodePath<t.ClassProperty | t.ClassPrivateProperty> |
| 532 |
| undefined; |
| 533 |
let constructorPath: NodePath<t.ClassMethod> | undefined; |
| 534 |
let requiresProtoInit = false; |
| 535 |
let requiresStaticInit = false; |
| 536 |
const decoratedPrivateMethods = new Set<string>(); |
| 537 |
|
| 538 |
let protoInitLocal: t.Identifier, |
| 539 |
staticInitLocal: t.Identifier, |
| 540 |
classInitLocal: t.Identifier, |
| 541 |
classIdLocal: t.Identifier; |
| 542 |
const assignments: t.AssignmentExpression[] = []; |
| 543 |
const scopeParent: Scope = path.scope.parent; |
| 544 |
|
| 545 |
const memoiseExpression = (expression: t.Expression, hint: string) => { |
| 546 |
const localEvaluatedId = scopeParent.generateDeclaredUidIdentifier(hint); |
| 547 |
assignments.push(t.assignmentExpression("=", localEvaluatedId, expression)); |
| 548 |
return t.cloneNode(localEvaluatedId); |
| 549 |
}; |
| 550 |
|
| 551 |
if (classDecorators) { |
| 552 |
classInitLocal = scopeParent.generateDeclaredUidIdentifier("initClass"); |
| 553 |
|
| 554 |
const [classId, classPath] = replaceClassWithVar(path); |
| 555 |
path = classPath; |
| 556 |
classIdLocal = classId; |
| 557 |
|
| 558 |
path.node.decorators = null; |
| 559 |
|
| 560 |
for (const classDecorator of classDecorators) { |
| 561 |
if (!scopeParent.isStatic(classDecorator.expression)) { |
| 562 |
classDecorator.expression = memoiseExpression( |
| 563 |
classDecorator.expression, |
| 564 |
"dec", |
| 565 |
); |
| 566 |
} |
| 567 |
} |
| 568 |
} else { |
| 569 |
if (!path.node.id) { |
| 570 |
path.node.id = path.scope.generateUidIdentifier("Class"); |
| 571 |
} |
| 572 |
classIdLocal = t.cloneNode(path.node.id); |
| 573 |
} |
| 574 |
|
| 575 |
if (hasElementDecorators) { |
| 576 |
for (const element of body) { |
| 577 |
if (!isClassDecoratableElementPath(element)) { |
| 578 |
continue; |
| 579 |
} |
| 580 |
|
| 581 |
const { node } = element; |
| 582 |
const decorators = element.get("decorators"); |
| 583 |
|
| 584 |
const hasDecorators = Array.isArray(decorators) && decorators.length > 0; |
| 585 |
|
| 586 |
if (hasDecorators) { |
| 587 |
for (const decoratorPath of decorators) { |
| 588 |
if (!scopeParent.isStatic(decoratorPath.node.expression)) { |
| 589 |
decoratorPath.node.expression = memoiseExpression( |
| 590 |
decoratorPath.node.expression, |
| 591 |
"dec", |
| 592 |
); |
| 593 |
} |
| 594 |
} |
| 595 |
} |
| 596 |
|
| 597 |
const isComputed = |
| 598 |
"computed" in element.node && element.node.computed === true; |
| 599 |
if (isComputed) { |
| 600 |
if (!scopeParent.isStatic(node.key)) { |
| 601 |
node.key = memoiseExpression(node.key as t.Expression, "computedKey"); |
| 602 |
} |
| 603 |
} |
| 604 |
|
| 605 |
const kind = getElementKind(element); |
| 606 |
const { key } = node; |
| 607 |
|
| 608 |
const isPrivate = key.type === "PrivateName"; |
| 609 |
|
| 610 |
const isStatic = !!element.node.static; |
| 611 |
|
| 612 |
let name = "computedKey"; |
| 613 |
|
| 614 |
if (isPrivate) { |
| 615 |
name = key.id.name; |
| 616 |
} else if (!isComputed && key.type === "Identifier") { |
| 617 |
name = key.name; |
| 618 |
} |
| 619 |
|
| 620 |
if (element.isClassMethod({ kind: "constructor" })) { |
| 621 |
constructorPath = element; |
| 622 |
} |
| 623 |
|
| 624 |
if (hasDecorators) { |
| 625 |
let locals: t.Identifier | t.Identifier[]; |
| 626 |
let privateMethods: t.FunctionExpression | t.FunctionExpression[]; |
| 627 |
|
| 628 |
if (kind === ACCESSOR) { |
| 629 |
const { value } = element.node as t.ClassAccessorProperty; |
| 630 |
|
| 631 |
const params: t.Expression[] = [t.thisExpression()]; |
| 632 |
|
| 633 |
if (value) { |
| 634 |
params.push(t.cloneNode(value)); |
| 635 |
} |
| 636 |
|
| 637 |
const newId = generateClassPrivateUid(); |
| 638 |
const newFieldInitId = |
| 639 |
element.scope.parent.generateDeclaredUidIdentifier(`init_${name}`); |
| 640 |
const newValue = t.callExpression( |
| 641 |
t.cloneNode(newFieldInitId), |
| 642 |
params, |
| 643 |
); |
| 644 |
|
| 645 |
const newField = generateClassProperty(newId, newValue, isStatic); |
| 646 |
const [newPath] = element.replaceWith(newField); |
| 647 |
|
| 648 |
if (isPrivate) { |
| 649 |
privateMethods = extractProxyAccessorsFor(newId); |
| 650 |
|
| 651 |
const getId = newPath.scope.parent.generateDeclaredUidIdentifier( |
| 652 |
`get_${name}`, |
| 653 |
); |
| 654 |
const setId = newPath.scope.parent.generateDeclaredUidIdentifier( |
| 655 |
`set_${name}`, |
| 656 |
); |
| 657 |
|
| 658 |
addCallAccessorsFor(newPath, key, getId, setId); |
| 659 |
|
| 660 |
locals = [newFieldInitId, getId, setId]; |
| 661 |
} else { |
| 662 |
addProxyAccessorsFor(newPath, key, newId, isComputed); |
| 663 |
locals = newFieldInitId; |
| 664 |
} |
| 665 |
} else if (kind === FIELD) { |
| 666 |
const initId = element.scope.parent.generateDeclaredUidIdentifier( |
| 667 |
`init_${name}`, |
| 668 |
); |
| 669 |
const valuePath = ( |
| 670 |
element as NodePath<t.ClassProperty | t.ClassPrivateProperty> |
| 671 |
).get("value"); |
| 672 |
|
| 673 |
valuePath.replaceWith( |
| 674 |
t.callExpression( |
| 675 |
t.cloneNode(initId), |
| 676 |
[t.thisExpression(), valuePath.node].filter(v => v), |
| 677 |
), |
| 678 |
); |
| 679 |
|
| 680 |
locals = initId; |
| 681 |
|
| 682 |
if (isPrivate) { |
| 683 |
privateMethods = extractProxyAccessorsFor(key); |
| 684 |
} |
| 685 |
} else if (isPrivate) { |
| 686 |
locals = element.scope.parent.generateDeclaredUidIdentifier( |
| 687 |
`call_${name}`, |
| 688 |
); |
| 689 |
|
| 690 |
const replaceSupers = new ReplaceSupers({ |
| 691 |
constantSuper, |
| 692 |
methodPath: element as NodePath<t.ClassPrivateMethod>, |
| 693 |
objectRef: classIdLocal, |
| 694 |
superRef: path.node.superClass, |
| 695 |
file: state.file, |
| 696 |
refToPreserve: classIdLocal, |
| 697 |
}); |
| 698 |
|
| 699 |
replaceSupers.replace(); |
| 700 |
|
| 701 |
const { |
| 702 |
params, |
| 703 |
body, |
| 704 |
async: isAsync, |
| 705 |
} = element.node as t.ClassPrivateMethod; |
| 706 |
|
| 707 |
privateMethods = t.functionExpression( |
| 708 |
undefined, |
| 709 |
params.filter(isNotTsParameter), |
| 710 |
body, |
| 711 |
isAsync, |
| 712 |
); |
| 713 |
|
| 714 |
if (kind === GETTER || kind === SETTER) { |
| 715 |
movePrivateAccessor( |
| 716 |
element as NodePath<t.ClassPrivateMethod>, |
| 717 |
t.cloneNode(key), |
| 718 |
t.cloneNode(locals), |
| 719 |
isStatic, |
| 720 |
); |
| 721 |
} else { |
| 722 |
const node = element.node as t.ClassPrivateMethod; |
| 723 |
|
| 724 |
// Unshift |
| 725 |
path.node.body.body.unshift( |
| 726 |
t.classPrivateProperty(key, t.cloneNode(locals), [], node.static), |
| 727 |
); |
| 728 |
|
| 729 |
decoratedPrivateMethods.add(key.id.name); |
| 730 |
|
| 731 |
element.remove(); |
| 732 |
} |
| 733 |
} |
| 734 |
|
| 735 |
let nameExpr: t.Expression; |
| 736 |
|
| 737 |
if (isComputed) { |
| 738 |
nameExpr = t.cloneNode(key as t.Expression); |
| 739 |
} else if (key.type === "PrivateName") { |
| 740 |
nameExpr = t.stringLiteral(key.id.name); |
| 741 |
} else if (key.type === "Identifier") { |
| 742 |
nameExpr = t.stringLiteral(key.name); |
| 743 |
} else { |
| 744 |
nameExpr = t.cloneNode(key as t.Expression); |
| 745 |
} |
| 746 |
|
| 747 |
elementDecoratorInfo.push({ |
| 748 |
kind, |
| 749 |
decorators: decorators.map(d => d.node.expression), |
| 750 |
name: nameExpr, |
| 751 |
isStatic, |
| 752 |
privateMethods, |
| 753 |
locals, |
| 754 |
}); |
| 755 |
|
| 756 |
if (kind !== FIELD) { |
| 757 |
if (isStatic) { |
| 758 |
requiresStaticInit = true; |
| 759 |
} else { |
| 760 |
requiresProtoInit = true; |
| 761 |
} |
| 762 |
} |
| 763 |
|
| 764 |
if (element.node) { |
| 765 |
element.node.decorators = null; |
| 766 |
} |
| 767 |
|
| 768 |
if ( |
| 769 |
!firstFieldPath && |
| 770 |
!isStatic && |
| 771 |
(kind === FIELD || kind === ACCESSOR) |
| 772 |
) { |
| 773 |
firstFieldPath = element as NodePath< |
| 774 |
t.ClassProperty | t.ClassPrivateProperty |
| 775 |
>; |
| 776 |
} |
| 777 |
} |
| 778 |
} |
| 779 |
} |
| 780 |
|
| 781 |
const elementDecorations = generateDecorationExprs(elementDecoratorInfo); |
| 782 |
const classDecorations = t.arrayExpression( |
| 783 |
(classDecorators || []).map(d => d.expression), |
| 784 |
); |
| 785 |
|
| 786 |
const elementLocals: t.Identifier[] = |
| 787 |
extractElementLocalAssignments(elementDecoratorInfo); |
| 788 |
|
| 789 |
if (requiresProtoInit) { |
| 790 |
protoInitLocal = scopeParent.generateDeclaredUidIdentifier("initProto"); |
| 791 |
elementLocals.push(protoInitLocal); |
| 792 |
|
| 793 |
const protoInitCall = t.callExpression(t.cloneNode(protoInitLocal), [ |
| 794 |
t.thisExpression(), |
| 795 |
]); |
| 796 |
|
| 797 |
if (firstFieldPath) { |
| 798 |
const value = firstFieldPath.get("value"); |
| 799 |
const body: t.Expression[] = [protoInitCall]; |
| 800 |
|
| 801 |
if (value.node) { |
| 802 |
body.push(value.node); |
| 803 |
} |
| 804 |
|
| 805 |
value.replaceWith(t.sequenceExpression(body)); |
| 806 |
} else if (constructorPath) { |
| 807 |
if (path.node.superClass) { |
| 808 |
path.traverse({ |
| 809 |
CallExpression: { |
| 810 |
exit(path) { |
| 811 |
if (!path.get("callee").isSuper()) return; |
| 812 |
|
| 813 |
path.replaceWith( |
| 814 |
t.callExpression(t.cloneNode(protoInitLocal), [path.node]), |
| 815 |
); |
| 816 |
|
| 817 |
path.skip(); |
| 818 |
}, |
| 819 |
}, |
| 820 |
}); |
| 821 |
} else { |
| 822 |
constructorPath.node.body.body.unshift( |
| 823 |
t.expressionStatement(protoInitCall), |
| 824 |
); |
| 825 |
} |
| 826 |
} else { |
| 827 |
const body: t.Statement[] = [t.expressionStatement(protoInitCall)]; |
| 828 |
|
| 829 |
if (path.node.superClass) { |
| 830 |
body.unshift( |
| 831 |
t.expressionStatement( |
| 832 |
t.callExpression(t.super(), [ |
| 833 |
t.spreadElement(t.identifier("args")), |
| 834 |
]), |
| 835 |
), |
| 836 |
); |
| 837 |
} |
| 838 |
|
| 839 |
path.node.body.body.unshift( |
| 840 |
t.classMethod( |
| 841 |
"constructor", |
| 842 |
t.identifier("constructor"), |
| 843 |
[t.restElement(t.identifier("args"))], |
| 844 |
t.blockStatement(body), |
| 845 |
), |
| 846 |
); |
| 847 |
} |
| 848 |
} |
| 849 |
|
| 850 |
if (requiresStaticInit) { |
| 851 |
staticInitLocal = scopeParent.generateDeclaredUidIdentifier("initStatic"); |
| 852 |
elementLocals.push(staticInitLocal); |
| 853 |
} |
| 854 |
|
| 855 |
if (decoratedPrivateMethods.size > 0) { |
| 856 |
path.traverse({ |
| 857 |
PrivateName(path) { |
| 858 |
if (!decoratedPrivateMethods.has(path.node.id.name)) return; |
| 859 |
|
| 860 |
const parentPath = path.parentPath; |
| 861 |
const parentParentPath = parentPath.parentPath; |
| 862 |
|
| 863 |
if ( |
| 864 |
// this.bar().#x = 123; |
| 865 |
(parentParentPath.node.type === "AssignmentExpression" && |
| 866 |
parentParentPath.node.left === parentPath.node) || |
| 867 |
// this.#x++; |
| 868 |
parentParentPath.node.type === "UpdateExpression" || |
| 869 |
// ([...this.#x] = foo); |
| 870 |
parentParentPath.node.type === "RestElement" || |
| 871 |
// ([this.#x] = foo); |
| 872 |
parentParentPath.node.type === "ArrayPattern" || |
| 873 |
// ({ a: this.#x } = bar); |
| 874 |
(parentParentPath.node.type === "ObjectProperty" && |
| 875 |
parentParentPath.node.value === parentPath.node && |
| 876 |
parentParentPath.parentPath.type === "ObjectPattern") || |
| 877 |
// for (this.#x of []); |
| 878 |
(parentParentPath.node.type === "ForOfStatement" && |
| 879 |
parentParentPath.node.left === parentPath.node) |
| 880 |
) { |
| 881 |
throw path.buildCodeFrameError( |
| 882 |
`Decorated private methods are not updatable, but "#${path.node.id.name}" is updated via this expression.`, |
| 883 |
); |
| 884 |
} |
| 885 |
}, |
| 886 |
}); |
| 887 |
} |
| 888 |
|
| 889 |
const classLocals: t.Identifier[] = []; |
| 890 |
let classInitInjected = false; |
| 891 |
const classInitCall = |
| 892 |
classInitLocal && t.callExpression(t.cloneNode(classInitLocal), []); |
| 893 |
|
| 894 |
const originalClass = path.node; |
| 895 |
|
| 896 |
if (classDecorators) { |
| 897 |
classLocals.push(classIdLocal, classInitLocal); |
| 898 |
const statics: ( |
| 899 |
| t.ClassProperty |
| 900 |
| t.ClassPrivateProperty |
| 901 |
| t.ClassPrivateMethod |
| 902 |
)[] = []; |
| 903 |
let staticBlocks: t.StaticBlock[] = []; |
| 904 |
path.get("body.body").forEach(element => { |
| 905 |
// Static blocks cannot be compiled to "instance blocks", but we can inline |
| 906 |
// them as IIFEs in the next property. |
| 907 |
if (element.isStaticBlock()) { |
| 908 |
staticBlocks.push(element.node); |
| 909 |
element.remove(); |
| 910 |
return; |
| 911 |
} |
| 912 |
|
| 913 |
const isProperty = |
| 914 |
element.isClassProperty() || element.isClassPrivateProperty(); |
| 915 |
|
| 916 |
if ( |
| 917 |
(isProperty || element.isClassPrivateMethod()) && |
| 918 |
element.node.static |
| 919 |
) { |
| 920 |
if (isProperty && staticBlocks.length > 0) { |
| 921 |
const allValues: t.Expression[] = staticBlocks.map(staticBlockToIIFE); |
| 922 |
if (element.node.value) allValues.push(element.node.value); |
| 923 |
element.node.value = maybeSequenceExpression(allValues); |
| 924 |
staticBlocks = []; |
| 925 |
} |
| 926 |
|
| 927 |
element.node.static = false; |
| 928 |
statics.push(element.node); |
| 929 |
element.remove(); |
| 930 |
} |
| 931 |
}); |
| 932 |
|
| 933 |
if (statics.length > 0 || staticBlocks.length > 0) { |
| 934 |
const staticsClass = template.expression.ast` |
| 935 |
class extends ${state.addHelper("identity")} {} |
| 936 |
` as t.ClassExpression; |
| 937 |
staticsClass.body.body = [ |
| 938 |
t.staticBlock([ |
| 939 |
t.toStatement(originalClass, true) || |
| 940 |
// If toStatement returns false, originalClass must be an anonymous ClassExpression, |
| 941 |
// because `export default @dec ...` has been handled in the export visitor before. |
| 942 |
t.expressionStatement(originalClass as t.ClassExpression), |
| 943 |
]), |
| 944 |
...statics, |
| 945 |
]; |
| 946 |
|
| 947 |
const constructorBody: t.Expression[] = []; |
| 948 |
|
| 949 |
const newExpr = t.newExpression(staticsClass, []); |
| 950 |
|
| 951 |
if (staticBlocks.length > 0) { |
| 952 |
constructorBody.push(...staticBlocks.map(staticBlockToIIFE)); |
| 953 |
} |
| 954 |
if (classInitCall) { |
| 955 |
classInitInjected = true; |
| 956 |
constructorBody.push(classInitCall); |
| 957 |
} |
| 958 |
if (constructorBody.length > 0) { |
| 959 |
constructorBody.unshift( |
| 960 |
t.callExpression(t.super(), [t.cloneNode(classIdLocal)]), |
| 961 |
); |
| 962 |
|
| 963 |
staticsClass.body.body.push( |
| 964 |
t.classMethod( |
| 965 |
"constructor", |
| 966 |
t.identifier("constructor"), |
| 967 |
[], |
| 968 |
t.blockStatement([ |
| 969 |
t.expressionStatement(t.sequenceExpression(constructorBody)), |
| 970 |
]), |
| 971 |
), |
| 972 |
); |
| 973 |
} else { |
| 974 |
newExpr.arguments.push(t.cloneNode(classIdLocal)); |
| 975 |
} |
| 976 |
|
| 977 |
path.replaceWith(newExpr); |
| 978 |
} |
| 979 |
} |
| 980 |
if (!classInitInjected && classInitCall) { |
| 981 |
path.node.body.body.push( |
| 982 |
t.staticBlock([t.expressionStatement(classInitCall)]), |
| 983 |
); |
| 984 |
} |
| 985 |
|
| 986 |
originalClass.body.body.unshift( |
| 987 |
t.staticBlock( |
| 988 |
[ |
| 989 |
t.expressionStatement( |
| 990 |
createLocalsAssignment( |
| 991 |
elementLocals, |
| 992 |
classLocals, |
| 993 |
elementDecorations, |
| 994 |
classDecorations, |
| 995 |
state, |
| 996 |
version, |
| 997 |
), |
| 998 |
), |
| 999 |
requiresStaticInit && |
| 1000 |
t.expressionStatement( |
| 1001 |
t.callExpression(t.cloneNode(staticInitLocal), [ |
| 1002 |
t.thisExpression(), |
| 1003 |
]), |
| 1004 |
), |
| 1005 |
].filter(Boolean), |
| 1006 |
), |
| 1007 |
); |
| 1008 |
|
| 1009 |
// When path is a ClassExpression, path.insertBefore will convert `path` |
| 1010 |
// into a SequenceExpression |
| 1011 |
path.insertBefore(assignments.map(expr => t.expressionStatement(expr))); |
| 1012 |
|
| 1013 |
// Recrawl the scope to make sure new identifiers are properly synced |
| 1014 |
path.scope.crawl(); |
| 1015 |
|
| 1016 |
return path; |
| 1017 |
} |
| 1018 |
|
| 1019 |
function createLocalsAssignment( |
| 1020 |
elementLocals: t.Identifier[], |
| 1021 |
classLocals: t.Identifier[], |
| 1022 |
elementDecorations: t.ArrayExpression, |
| 1023 |
classDecorations: t.ArrayExpression, |
| 1024 |
state: PluginPass, |
| 1025 |
version: DecoratorVersionKind, |
| 1026 |
) { |
| 1027 |
let lhs, rhs; |
| 1028 |
// TODO(Babel 8): Only keep the else branch |
| 1029 |
if ( |
| 1030 |
version === "2021-12" || |
| 1031 |
(version === "2022-03" && !state.availableHelper("applyDecs2203R")) |
| 1032 |
) { |
| 1033 |
lhs = t.arrayPattern([...elementLocals, ...classLocals]); |
| 1034 |
rhs = t.callExpression( |
| 1035 |
state.addHelper(version === "2021-12" ? "applyDecs" : "applyDecs2203"), |
| 1036 |
[t.thisExpression(), elementDecorations, classDecorations], |
| 1037 |
); |
| 1038 |
} else { |
| 1039 |
rhs = t.callExpression(state.addHelper("applyDecs2203R"), [ |
| 1040 |
t.thisExpression(), |
| 1041 |
elementDecorations, |
| 1042 |
classDecorations, |
| 1043 |
]); |
| 1044 |
// optimize `{ c: [classLocals] } = applyapplyDecs2203R(...)` to |
| 1045 |
// `[classLocals] = applyapplyDecs2203R(...).c` |
| 1046 |
if (elementLocals.length > 0) { |
| 1047 |
if (classLocals.length > 0) { |
| 1048 |
lhs = t.objectPattern([ |
| 1049 |
t.objectProperty(t.identifier("e"), t.arrayPattern(elementLocals)), |
| 1050 |
t.objectProperty(t.identifier("c"), t.arrayPattern(classLocals)), |
| 1051 |
]); |
| 1052 |
} else { |
| 1053 |
lhs = t.arrayPattern(elementLocals); |
| 1054 |
rhs = t.memberExpression(rhs, t.identifier("e"), false, false); |
| 1055 |
} |
| 1056 |
} else { |
| 1057 |
// invariant: classLocals.length > 0 |
| 1058 |
lhs = t.arrayPattern(classLocals); |
| 1059 |
rhs = t.memberExpression(rhs, t.identifier("c"), false, false); |
| 1060 |
} |
| 1061 |
} |
| 1062 |
return t.assignmentExpression("=", lhs, rhs); |
| 1063 |
} |
| 1064 |
|
| 1065 |
export default function ( |
| 1066 |
{ assertVersion, assumption }: PluginAPI, |
| 1067 |
{ loose }: Options, |
| 1068 |
version: "2022-03" | "2021-12", |
| 1069 |
): PluginObject { |
| 1070 |
assertVersion(version === "2021-12" ? "^7.16.0" : "^7.19.0"); |
| 1071 |
|
| 1072 |
const VISITED = new WeakSet<NodePath>(); |
| 1073 |
const constantSuper = assumption("constantSuper") ?? loose; |
| 1074 |
|
| 1075 |
return { |
| 1076 |
name: "proposal-decorators", |
| 1077 |
inherits: syntaxDecorators, |
| 1078 |
|
| 1079 |
visitor: { |
| 1080 |
"ExportNamedDeclaration|ExportDefaultDeclaration"( |
| 1081 |
path: NodePath<t.ExportNamedDeclaration | t.ExportDefaultDeclaration>, |
| 1082 |
) { |
| 1083 |
const { declaration } = path.node; |
| 1084 |
if ( |
| 1085 |
declaration?.type === "ClassDeclaration" && |
| 1086 |
// When compiling class decorators we need to replace the class |
| 1087 |
// binding, so we must split it in two separate declarations. |
| 1088 |
declaration.decorators?.length > 0 |
| 1089 |
) { |
| 1090 |
splitExportDeclaration(path); |
| 1091 |
} |
| 1092 |
}, |
| 1093 |
|
| 1094 |
Class(path, state) { |
| 1095 |
if (VISITED.has(path)) return; |
| 1096 |
|
| 1097 |
const newPath = transformClass(path, state, constantSuper, version); |
| 1098 |
if (newPath) VISITED.add(newPath); |
| 1099 |
}, |
| 1100 |
}, |
| 1101 |
}; |
| 1102 |
} |