decorators.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = _default;
  6. var _core = require("@babel/core");
  7. var _helperReplaceSupers = require("@babel/helper-replace-supers");
  8. var _helperSplitExportDeclaration = require("@babel/helper-split-export-declaration");
  9. var _helperSkipTransparentExpressionWrappers = require("@babel/helper-skip-transparent-expression-wrappers");
  10. var _fields = require("./fields.js");
  11. function incrementId(id, idx = id.length - 1) {
  12. if (idx === -1) {
  13. id.unshift(65);
  14. return;
  15. }
  16. const current = id[idx];
  17. if (current === 90) {
  18. id[idx] = 97;
  19. } else if (current === 122) {
  20. id[idx] = 65;
  21. incrementId(id, idx - 1);
  22. } else {
  23. id[idx] = current + 1;
  24. }
  25. }
  26. function createPrivateUidGeneratorForClass(classPath) {
  27. const currentPrivateId = [];
  28. const privateNames = new Set();
  29. classPath.traverse({
  30. PrivateName(path) {
  31. privateNames.add(path.node.id.name);
  32. }
  33. });
  34. return () => {
  35. let reifiedId;
  36. do {
  37. incrementId(currentPrivateId);
  38. reifiedId = String.fromCharCode(...currentPrivateId);
  39. } while (privateNames.has(reifiedId));
  40. return _core.types.privateName(_core.types.identifier(reifiedId));
  41. };
  42. }
  43. function createLazyPrivateUidGeneratorForClass(classPath) {
  44. let generator;
  45. return () => {
  46. if (!generator) {
  47. generator = createPrivateUidGeneratorForClass(classPath);
  48. }
  49. return generator();
  50. };
  51. }
  52. function replaceClassWithVar(path, className) {
  53. if (path.type === "ClassDeclaration") {
  54. const id = path.node.id;
  55. const className = id.name;
  56. const varId = path.scope.generateUidIdentifierBasedOnNode(id);
  57. const classId = _core.types.identifier(className);
  58. path.scope.rename(className, varId.name);
  59. path.get("id").replaceWith(classId);
  60. return {
  61. id: _core.types.cloneNode(varId),
  62. path
  63. };
  64. } else {
  65. let varId;
  66. if (path.node.id) {
  67. className = path.node.id.name;
  68. varId = path.scope.parent.generateDeclaredUidIdentifier(className);
  69. path.scope.rename(className, varId.name);
  70. } else {
  71. varId = path.scope.parent.generateDeclaredUidIdentifier(typeof className === "string" ? className : "decorated_class");
  72. }
  73. const newClassExpr = _core.types.classExpression(typeof className === "string" ? _core.types.identifier(className) : null, path.node.superClass, path.node.body);
  74. const [newPath] = path.replaceWith(_core.types.sequenceExpression([newClassExpr, varId]));
  75. return {
  76. id: _core.types.cloneNode(varId),
  77. path: newPath.get("expressions.0")
  78. };
  79. }
  80. }
  81. function generateClassProperty(key, value, isStatic) {
  82. if (key.type === "PrivateName") {
  83. return _core.types.classPrivateProperty(key, value, undefined, isStatic);
  84. } else {
  85. return _core.types.classProperty(key, value, undefined, undefined, isStatic);
  86. }
  87. }
  88. function addProxyAccessorsFor(className, element, originalKey, targetKey, version, isComputed = false) {
  89. const {
  90. static: isStatic
  91. } = element.node;
  92. const thisArg = version === "2023-05" && isStatic ? className : _core.types.thisExpression();
  93. const getterBody = _core.types.blockStatement([_core.types.returnStatement(_core.types.memberExpression(_core.types.cloneNode(thisArg), _core.types.cloneNode(targetKey)))]);
  94. const setterBody = _core.types.blockStatement([_core.types.expressionStatement(_core.types.assignmentExpression("=", _core.types.memberExpression(_core.types.cloneNode(thisArg), _core.types.cloneNode(targetKey)), _core.types.identifier("v")))]);
  95. let getter, setter;
  96. if (originalKey.type === "PrivateName") {
  97. getter = _core.types.classPrivateMethod("get", _core.types.cloneNode(originalKey), [], getterBody, isStatic);
  98. setter = _core.types.classPrivateMethod("set", _core.types.cloneNode(originalKey), [_core.types.identifier("v")], setterBody, isStatic);
  99. } else {
  100. getter = _core.types.classMethod("get", _core.types.cloneNode(originalKey), [], getterBody, isComputed, isStatic);
  101. setter = _core.types.classMethod("set", _core.types.cloneNode(originalKey), [_core.types.identifier("v")], setterBody, isComputed, isStatic);
  102. }
  103. element.insertAfter(setter);
  104. element.insertAfter(getter);
  105. }
  106. function extractProxyAccessorsFor(targetKey, version) {
  107. if (version !== "2023-05" && version !== "2023-01") {
  108. return [_core.template.expression.ast`
  109. function () {
  110. return this.${_core.types.cloneNode(targetKey)};
  111. }
  112. `, _core.template.expression.ast`
  113. function (value) {
  114. this.${_core.types.cloneNode(targetKey)} = value;
  115. }
  116. `];
  117. }
  118. return [_core.template.expression.ast`
  119. o => o.${_core.types.cloneNode(targetKey)}
  120. `, _core.template.expression.ast`
  121. (o, v) => o.${_core.types.cloneNode(targetKey)} = v
  122. `];
  123. }
  124. function prependExpressionsToFieldInitializer(expressions, fieldPath) {
  125. const initializer = fieldPath.get("value");
  126. if (initializer.node) {
  127. expressions.push(initializer.node);
  128. } else if (expressions.length > 0) {
  129. expressions[expressions.length - 1] = _core.types.unaryExpression("void", expressions[expressions.length - 1]);
  130. }
  131. initializer.replaceWith(maybeSequenceExpression(expressions));
  132. }
  133. function prependExpressionsToConstructor(expressions, constructorPath) {
  134. constructorPath.node.body.body.unshift(_core.types.expressionStatement(maybeSequenceExpression(expressions)));
  135. }
  136. function isProtoInitCallExpression(expression, protoInitCall) {
  137. return _core.types.isCallExpression(expression) && _core.types.isIdentifier(expression.callee, {
  138. name: protoInitCall.name
  139. });
  140. }
  141. function optimizeSuperCallAndExpressions(expressions, protoInitLocal) {
  142. if (expressions.length >= 2 && isProtoInitCallExpression(expressions[1], protoInitLocal)) {
  143. const mergedSuperCall = _core.types.callExpression(_core.types.cloneNode(protoInitLocal), [expressions[0]]);
  144. expressions.splice(0, 2, mergedSuperCall);
  145. }
  146. if (expressions.length >= 2 && _core.types.isThisExpression(expressions[expressions.length - 1]) && isProtoInitCallExpression(expressions[expressions.length - 2], protoInitLocal)) {
  147. expressions.splice(expressions.length - 1, 1);
  148. }
  149. return maybeSequenceExpression(expressions);
  150. }
  151. function insertExpressionsAfterSuperCallAndOptimize(expressions, constructorPath, protoInitLocal) {
  152. constructorPath.traverse({
  153. CallExpression: {
  154. exit(path) {
  155. if (!path.get("callee").isSuper()) return;
  156. const newNodes = [path.node, ...expressions.map(expr => _core.types.cloneNode(expr))];
  157. if (path.isCompletionRecord()) {
  158. newNodes.push(_core.types.thisExpression());
  159. }
  160. path.replaceWith(optimizeSuperCallAndExpressions(newNodes, protoInitLocal));
  161. path.skip();
  162. }
  163. },
  164. ClassMethod(path) {
  165. if (path.node.kind === "constructor") {
  166. path.skip();
  167. }
  168. }
  169. });
  170. }
  171. function createConstructorFromExpressions(expressions, isDerivedClass) {
  172. const body = [_core.types.expressionStatement(maybeSequenceExpression(expressions))];
  173. if (isDerivedClass) {
  174. body.unshift(_core.types.expressionStatement(_core.types.callExpression(_core.types.super(), [_core.types.spreadElement(_core.types.identifier("args"))])));
  175. }
  176. return _core.types.classMethod("constructor", _core.types.identifier("constructor"), isDerivedClass ? [_core.types.restElement(_core.types.identifier("args"))] : [], _core.types.blockStatement(body));
  177. }
  178. const FIELD = 0;
  179. const ACCESSOR = 1;
  180. const METHOD = 2;
  181. const GETTER = 3;
  182. const SETTER = 4;
  183. const STATIC_OLD_VERSION = 5;
  184. const STATIC = 8;
  185. const DECORATORS_HAVE_THIS = 16;
  186. function getElementKind(element) {
  187. switch (element.node.type) {
  188. case "ClassProperty":
  189. case "ClassPrivateProperty":
  190. return FIELD;
  191. case "ClassAccessorProperty":
  192. return ACCESSOR;
  193. case "ClassMethod":
  194. case "ClassPrivateMethod":
  195. if (element.node.kind === "get") {
  196. return GETTER;
  197. } else if (element.node.kind === "set") {
  198. return SETTER;
  199. } else {
  200. return METHOD;
  201. }
  202. }
  203. }
  204. function isDecoratorInfo(info) {
  205. return "decorators" in info;
  206. }
  207. function filteredOrderedDecoratorInfo(info) {
  208. const filtered = info.filter(isDecoratorInfo);
  209. return [...filtered.filter(el => el.isStatic && el.kind >= ACCESSOR && el.kind <= SETTER), ...filtered.filter(el => !el.isStatic && el.kind >= ACCESSOR && el.kind <= SETTER), ...filtered.filter(el => el.isStatic && el.kind === FIELD), ...filtered.filter(el => !el.isStatic && el.kind === FIELD)];
  210. }
  211. function generateDecorationList(decorators, decoratorsThis, version) {
  212. const decsCount = decorators.length;
  213. const hasOneThis = decoratorsThis.some(Boolean);
  214. const decs = [];
  215. for (let i = 0; i < decsCount; i++) {
  216. if (version === "2023-05" && hasOneThis) {
  217. decs.push(decoratorsThis[i] || _core.types.unaryExpression("void", _core.types.numericLiteral(0)));
  218. }
  219. decs.push(decorators[i]);
  220. }
  221. return {
  222. hasThis: hasOneThis,
  223. decs
  224. };
  225. }
  226. function generateDecorationExprs(info, version) {
  227. return _core.types.arrayExpression(filteredOrderedDecoratorInfo(info).map(el => {
  228. const {
  229. decs,
  230. hasThis
  231. } = generateDecorationList(el.decorators, el.decoratorsThis, version);
  232. let flag = el.kind;
  233. if (el.isStatic) {
  234. flag += version === "2023-05" ? STATIC : STATIC_OLD_VERSION;
  235. }
  236. if (hasThis) flag += DECORATORS_HAVE_THIS;
  237. return _core.types.arrayExpression([decs.length === 1 ? decs[0] : _core.types.arrayExpression(decs), _core.types.numericLiteral(flag), el.name, ...(el.privateMethods || [])]);
  238. }));
  239. }
  240. function extractElementLocalAssignments(decorationInfo) {
  241. const localIds = [];
  242. for (const el of filteredOrderedDecoratorInfo(decorationInfo)) {
  243. const {
  244. locals
  245. } = el;
  246. if (Array.isArray(locals)) {
  247. localIds.push(...locals);
  248. } else if (locals !== undefined) {
  249. localIds.push(locals);
  250. }
  251. }
  252. return localIds;
  253. }
  254. function addCallAccessorsFor(element, key, getId, setId) {
  255. element.insertAfter(_core.types.classPrivateMethod("get", _core.types.cloneNode(key), [], _core.types.blockStatement([_core.types.returnStatement(_core.types.callExpression(_core.types.cloneNode(getId), [_core.types.thisExpression()]))])));
  256. element.insertAfter(_core.types.classPrivateMethod("set", _core.types.cloneNode(key), [_core.types.identifier("v")], _core.types.blockStatement([_core.types.expressionStatement(_core.types.callExpression(_core.types.cloneNode(setId), [_core.types.thisExpression(), _core.types.identifier("v")]))])));
  257. }
  258. function isNotTsParameter(node) {
  259. return node.type !== "TSParameterProperty";
  260. }
  261. function movePrivateAccessor(element, key, methodLocalVar, isStatic) {
  262. let params;
  263. let block;
  264. if (element.node.kind === "set") {
  265. params = [_core.types.identifier("v")];
  266. block = [_core.types.expressionStatement(_core.types.callExpression(methodLocalVar, [_core.types.thisExpression(), _core.types.identifier("v")]))];
  267. } else {
  268. params = [];
  269. block = [_core.types.returnStatement(_core.types.callExpression(methodLocalVar, [_core.types.thisExpression()]))];
  270. }
  271. element.replaceWith(_core.types.classPrivateMethod(element.node.kind, _core.types.cloneNode(key), params, _core.types.blockStatement(block), isStatic));
  272. }
  273. function isClassDecoratableElementPath(path) {
  274. const {
  275. type
  276. } = path;
  277. return type !== "TSDeclareMethod" && type !== "TSIndexSignature" && type !== "StaticBlock";
  278. }
  279. function staticBlockToIIFE(block) {
  280. return _core.types.callExpression(_core.types.arrowFunctionExpression([], _core.types.blockStatement(block.body)), []);
  281. }
  282. function maybeSequenceExpression(exprs) {
  283. if (exprs.length === 0) return _core.types.unaryExpression("void", _core.types.numericLiteral(0));
  284. if (exprs.length === 1) return exprs[0];
  285. return _core.types.sequenceExpression(exprs);
  286. }
  287. function createSetFunctionNameCall(state, className) {
  288. return _core.types.callExpression(state.addHelper("setFunctionName"), [_core.types.thisExpression(), className]);
  289. }
  290. function createToPropertyKeyCall(state, propertyKey) {
  291. return _core.types.callExpression(state.addHelper("toPropertyKey"), [propertyKey]);
  292. }
  293. function checkPrivateMethodUpdateError(path, decoratedPrivateMethods) {
  294. const privateNameVisitor = (0, _fields.privateNameVisitorFactory)({
  295. PrivateName(path, state) {
  296. if (!state.privateNamesMap.has(path.node.id.name)) return;
  297. const parentPath = path.parentPath;
  298. const parentParentPath = parentPath.parentPath;
  299. if (parentParentPath.node.type === "AssignmentExpression" && parentParentPath.node.left === parentPath.node || parentParentPath.node.type === "UpdateExpression" || parentParentPath.node.type === "RestElement" || parentParentPath.node.type === "ArrayPattern" || parentParentPath.node.type === "ObjectProperty" && parentParentPath.node.value === parentPath.node && parentParentPath.parentPath.type === "ObjectPattern" || parentParentPath.node.type === "ForOfStatement" && parentParentPath.node.left === parentPath.node) {
  300. throw path.buildCodeFrameError(`Decorated private methods are read-only, but "#${path.node.id.name}" is updated via this expression.`);
  301. }
  302. }
  303. });
  304. const privateNamesMap = new Map();
  305. for (const name of decoratedPrivateMethods) {
  306. privateNamesMap.set(name, null);
  307. }
  308. path.traverse(privateNameVisitor, {
  309. privateNamesMap: privateNamesMap
  310. });
  311. }
  312. function transformClass(path, state, constantSuper, version, className, propertyVisitor) {
  313. const body = path.get("body.body");
  314. const classDecorators = path.node.decorators;
  315. let hasElementDecorators = false;
  316. const generateClassPrivateUid = createLazyPrivateUidGeneratorForClass(path);
  317. const assignments = [];
  318. const scopeParent = path.scope.parent;
  319. const memoiseExpression = (expression, hint) => {
  320. const localEvaluatedId = scopeParent.generateDeclaredUidIdentifier(hint);
  321. assignments.push(_core.types.assignmentExpression("=", localEvaluatedId, expression));
  322. return _core.types.cloneNode(localEvaluatedId);
  323. };
  324. let protoInitLocal;
  325. let staticInitLocal;
  326. for (const element of body) {
  327. if (!isClassDecoratableElementPath(element)) {
  328. continue;
  329. }
  330. if (isDecorated(element.node)) {
  331. switch (element.node.type) {
  332. case "ClassProperty":
  333. propertyVisitor.ClassProperty(element, state);
  334. break;
  335. case "ClassPrivateProperty":
  336. propertyVisitor.ClassPrivateProperty(element, state);
  337. break;
  338. case "ClassAccessorProperty":
  339. propertyVisitor.ClassAccessorProperty(element, state);
  340. default:
  341. if (element.node.static) {
  342. var _staticInitLocal;
  343. (_staticInitLocal = staticInitLocal) != null ? _staticInitLocal : staticInitLocal = scopeParent.generateDeclaredUidIdentifier("initStatic");
  344. } else {
  345. var _protoInitLocal;
  346. (_protoInitLocal = protoInitLocal) != null ? _protoInitLocal : protoInitLocal = scopeParent.generateDeclaredUidIdentifier("initProto");
  347. }
  348. break;
  349. }
  350. hasElementDecorators = true;
  351. } else if (element.node.type === "ClassAccessorProperty") {
  352. propertyVisitor.ClassAccessorProperty(element, state);
  353. const {
  354. key,
  355. value,
  356. static: isStatic,
  357. computed
  358. } = element.node;
  359. const newId = generateClassPrivateUid();
  360. const newField = generateClassProperty(newId, value, isStatic);
  361. const keyPath = element.get("key");
  362. const [newPath] = element.replaceWith(newField);
  363. addProxyAccessorsFor(path.node.id, newPath, computed && !keyPath.isConstantExpression() ? memoiseExpression(createToPropertyKeyCall(state, key), "computedKey") : key, newId, version, computed);
  364. }
  365. }
  366. if (!classDecorators && !hasElementDecorators) {
  367. if (assignments.length > 0) {
  368. path.insertBefore(assignments.map(expr => _core.types.expressionStatement(expr)));
  369. path.scope.crawl();
  370. }
  371. return;
  372. }
  373. const elementDecoratorInfo = [];
  374. let constructorPath;
  375. const decoratedPrivateMethods = new Set();
  376. let classInitLocal, classIdLocal;
  377. const decoratorsThis = new Map();
  378. const maybeExtractDecorators = (decorators, memoiseInPlace) => {
  379. let needMemoise = false;
  380. for (const decorator of decorators) {
  381. const {
  382. expression
  383. } = decorator;
  384. if (version === "2023-05" && _core.types.isMemberExpression(expression)) {
  385. let object;
  386. if (_core.types.isSuper(expression.object) || _core.types.isThisExpression(expression.object)) {
  387. needMemoise = true;
  388. if (memoiseInPlace) {
  389. object = memoiseExpression(_core.types.thisExpression(), "obj");
  390. } else {
  391. object = _core.types.thisExpression();
  392. }
  393. } else {
  394. if (!scopeParent.isStatic(expression.object)) {
  395. needMemoise = true;
  396. if (memoiseInPlace) {
  397. expression.object = memoiseExpression(expression.object, "obj");
  398. }
  399. }
  400. object = _core.types.cloneNode(expression.object);
  401. }
  402. decoratorsThis.set(decorator, object);
  403. }
  404. if (!scopeParent.isStatic(expression)) {
  405. needMemoise = true;
  406. if (memoiseInPlace) {
  407. decorator.expression = memoiseExpression(expression, "dec");
  408. }
  409. }
  410. }
  411. return needMemoise && !memoiseInPlace;
  412. };
  413. let needsDeclaraionForClassBinding = false;
  414. let classDecorationsFlag = 0;
  415. let classDecorations = [];
  416. let classDecorationsId;
  417. if (classDecorators) {
  418. classInitLocal = scopeParent.generateDeclaredUidIdentifier("initClass");
  419. needsDeclaraionForClassBinding = path.isClassDeclaration();
  420. ({
  421. id: classIdLocal,
  422. path
  423. } = replaceClassWithVar(path, className));
  424. path.node.decorators = null;
  425. const needMemoise = maybeExtractDecorators(classDecorators, false);
  426. const {
  427. hasThis,
  428. decs
  429. } = generateDecorationList(classDecorators.map(el => el.expression), classDecorators.map(dec => decoratorsThis.get(dec)), version);
  430. classDecorationsFlag = hasThis ? 1 : 0;
  431. classDecorations = decs;
  432. if (needMemoise) {
  433. classDecorationsId = memoiseExpression(_core.types.arrayExpression(classDecorations), "classDecs");
  434. }
  435. } else {
  436. if (!path.node.id) {
  437. path.node.id = path.scope.generateUidIdentifier("Class");
  438. }
  439. classIdLocal = _core.types.cloneNode(path.node.id);
  440. }
  441. let lastInstancePrivateName;
  442. let needsInstancePrivateBrandCheck = false;
  443. let fieldInitializerAssignments = [];
  444. if (hasElementDecorators) {
  445. if (protoInitLocal) {
  446. const protoInitCall = _core.types.callExpression(_core.types.cloneNode(protoInitLocal), [_core.types.thisExpression()]);
  447. fieldInitializerAssignments.push(protoInitCall);
  448. }
  449. for (const element of body) {
  450. if (!isClassDecoratableElementPath(element)) {
  451. continue;
  452. }
  453. const {
  454. node
  455. } = element;
  456. const decorators = element.node.decorators;
  457. const hasDecorators = !!(decorators != null && decorators.length);
  458. if (hasDecorators) {
  459. maybeExtractDecorators(decorators, true);
  460. }
  461. const isComputed = "computed" in element.node && element.node.computed;
  462. if (isComputed) {
  463. if (!element.get("key").isConstantExpression()) {
  464. node.key = memoiseExpression(createToPropertyKeyCall(state, node.key), "computedKey");
  465. }
  466. }
  467. const kind = getElementKind(element);
  468. const {
  469. key
  470. } = node;
  471. const isPrivate = key.type === "PrivateName";
  472. const isStatic = element.node.static;
  473. let name = "computedKey";
  474. if (isPrivate) {
  475. name = key.id.name;
  476. } else if (!isComputed && key.type === "Identifier") {
  477. name = key.name;
  478. }
  479. if (isPrivate && !isStatic) {
  480. if (hasDecorators) {
  481. needsInstancePrivateBrandCheck = true;
  482. }
  483. if (_core.types.isClassPrivateProperty(node) || !lastInstancePrivateName) {
  484. lastInstancePrivateName = key;
  485. }
  486. }
  487. if (element.isClassMethod({
  488. kind: "constructor"
  489. })) {
  490. constructorPath = element;
  491. }
  492. if (hasDecorators) {
  493. let locals;
  494. let privateMethods;
  495. if (kind === ACCESSOR) {
  496. const {
  497. value
  498. } = element.node;
  499. const params = [_core.types.thisExpression()];
  500. if (value) {
  501. params.push(_core.types.cloneNode(value));
  502. }
  503. const newId = generateClassPrivateUid();
  504. const newFieldInitId = element.scope.parent.generateDeclaredUidIdentifier(`init_${name}`);
  505. const newValue = _core.types.callExpression(_core.types.cloneNode(newFieldInitId), params);
  506. const newField = generateClassProperty(newId, newValue, isStatic);
  507. const [newPath] = element.replaceWith(newField);
  508. if (isPrivate) {
  509. privateMethods = extractProxyAccessorsFor(newId, version);
  510. const getId = newPath.scope.parent.generateDeclaredUidIdentifier(`get_${name}`);
  511. const setId = newPath.scope.parent.generateDeclaredUidIdentifier(`set_${name}`);
  512. addCallAccessorsFor(newPath, key, getId, setId);
  513. locals = [newFieldInitId, getId, setId];
  514. } else {
  515. addProxyAccessorsFor(path.node.id, newPath, key, newId, version, isComputed);
  516. locals = newFieldInitId;
  517. }
  518. } else if (kind === FIELD) {
  519. const initId = element.scope.parent.generateDeclaredUidIdentifier(`init_${name}`);
  520. const valuePath = element.get("value");
  521. valuePath.replaceWith(_core.types.callExpression(_core.types.cloneNode(initId), [_core.types.thisExpression(), valuePath.node].filter(v => v)));
  522. locals = initId;
  523. if (isPrivate) {
  524. privateMethods = extractProxyAccessorsFor(key, version);
  525. }
  526. } else if (isPrivate) {
  527. locals = element.scope.parent.generateDeclaredUidIdentifier(`call_${name}`);
  528. const replaceSupers = new _helperReplaceSupers.default({
  529. constantSuper,
  530. methodPath: element,
  531. objectRef: classIdLocal,
  532. superRef: path.node.superClass,
  533. file: state.file,
  534. refToPreserve: classIdLocal
  535. });
  536. replaceSupers.replace();
  537. const {
  538. params,
  539. body,
  540. async: isAsync
  541. } = element.node;
  542. privateMethods = [_core.types.functionExpression(undefined, params.filter(isNotTsParameter), body, isAsync)];
  543. if (kind === GETTER || kind === SETTER) {
  544. movePrivateAccessor(element, _core.types.cloneNode(key), _core.types.cloneNode(locals), isStatic);
  545. } else {
  546. const node = element.node;
  547. path.node.body.body.unshift(_core.types.classPrivateProperty(key, _core.types.cloneNode(locals), [], node.static));
  548. decoratedPrivateMethods.add(key.id.name);
  549. element.remove();
  550. }
  551. }
  552. let nameExpr;
  553. if (isComputed) {
  554. nameExpr = _core.types.cloneNode(key);
  555. } else if (key.type === "PrivateName") {
  556. nameExpr = _core.types.stringLiteral(key.id.name);
  557. } else if (key.type === "Identifier") {
  558. nameExpr = _core.types.stringLiteral(key.name);
  559. } else {
  560. nameExpr = _core.types.cloneNode(key);
  561. }
  562. elementDecoratorInfo.push({
  563. kind,
  564. decorators: decorators.map(d => d.expression),
  565. decoratorsThis: decorators.map(d => decoratorsThis.get(d)),
  566. name: nameExpr,
  567. isStatic,
  568. privateMethods,
  569. locals
  570. });
  571. if (element.node) {
  572. element.node.decorators = null;
  573. }
  574. }
  575. if (fieldInitializerAssignments.length > 0 && !isStatic && (kind === FIELD || kind === ACCESSOR)) {
  576. prependExpressionsToFieldInitializer(fieldInitializerAssignments, element);
  577. fieldInitializerAssignments = [];
  578. }
  579. }
  580. }
  581. if (fieldInitializerAssignments.length > 0) {
  582. const isDerivedClass = !!path.node.superClass;
  583. if (constructorPath) {
  584. if (isDerivedClass) {
  585. insertExpressionsAfterSuperCallAndOptimize(fieldInitializerAssignments, constructorPath, protoInitLocal);
  586. } else {
  587. prependExpressionsToConstructor(fieldInitializerAssignments, constructorPath);
  588. }
  589. } else {
  590. path.node.body.body.unshift(createConstructorFromExpressions(fieldInitializerAssignments, isDerivedClass));
  591. }
  592. fieldInitializerAssignments = [];
  593. }
  594. const elementDecorations = generateDecorationExprs(elementDecoratorInfo, version);
  595. const elementLocals = extractElementLocalAssignments(elementDecoratorInfo);
  596. if (protoInitLocal) {
  597. elementLocals.push(protoInitLocal);
  598. }
  599. if (staticInitLocal) {
  600. elementLocals.push(staticInitLocal);
  601. }
  602. const classLocals = [];
  603. let classInitInjected = false;
  604. const classInitCall = classInitLocal && _core.types.callExpression(_core.types.cloneNode(classInitLocal), []);
  605. const originalClass = path.node;
  606. if (classDecorators) {
  607. classLocals.push(classIdLocal, classInitLocal);
  608. const statics = [];
  609. let staticBlocks = [];
  610. path.get("body.body").forEach(element => {
  611. if (element.isStaticBlock()) {
  612. staticBlocks.push(element.node);
  613. element.remove();
  614. return;
  615. }
  616. const isProperty = element.isClassProperty() || element.isClassPrivateProperty();
  617. if ((isProperty || element.isClassPrivateMethod()) && element.node.static) {
  618. if (isProperty && staticBlocks.length > 0) {
  619. const allValues = staticBlocks.map(staticBlockToIIFE);
  620. if (element.node.value) allValues.push(element.node.value);
  621. element.node.value = maybeSequenceExpression(allValues);
  622. staticBlocks = [];
  623. }
  624. element.node.static = false;
  625. statics.push(element.node);
  626. element.remove();
  627. }
  628. });
  629. if (statics.length > 0 || staticBlocks.length > 0) {
  630. const staticsClass = _core.template.expression.ast`
  631. class extends ${state.addHelper("identity")} {}
  632. `;
  633. staticsClass.body.body = [_core.types.staticBlock([_core.types.toStatement(originalClass, true) || _core.types.expressionStatement(originalClass)]), ...statics];
  634. const constructorBody = [];
  635. const newExpr = _core.types.newExpression(staticsClass, []);
  636. if (staticBlocks.length > 0) {
  637. constructorBody.push(...staticBlocks.map(staticBlockToIIFE));
  638. }
  639. if (classInitCall) {
  640. classInitInjected = true;
  641. constructorBody.push(classInitCall);
  642. }
  643. if (constructorBody.length > 0) {
  644. constructorBody.unshift(_core.types.callExpression(_core.types.super(), [_core.types.cloneNode(classIdLocal)]));
  645. staticsClass.body.body.push(_core.types.classMethod("constructor", _core.types.identifier("constructor"), [], _core.types.blockStatement([_core.types.expressionStatement(_core.types.sequenceExpression(constructorBody))])));
  646. } else {
  647. newExpr.arguments.push(_core.types.cloneNode(classIdLocal));
  648. }
  649. path.replaceWith(newExpr);
  650. }
  651. }
  652. if (!classInitInjected && classInitCall) {
  653. path.node.body.body.push(_core.types.staticBlock([_core.types.expressionStatement(classInitCall)]));
  654. }
  655. let {
  656. superClass
  657. } = originalClass;
  658. if (superClass && version === "2023-05") {
  659. const id = path.scope.maybeGenerateMemoised(superClass);
  660. if (id) {
  661. originalClass.superClass = _core.types.assignmentExpression("=", id, superClass);
  662. superClass = id;
  663. }
  664. }
  665. originalClass.body.body.unshift(_core.types.staticBlock([_core.types.expressionStatement(createLocalsAssignment(elementLocals, classLocals, elementDecorations, classDecorationsId ? _core.types.cloneNode(classDecorationsId) : _core.types.arrayExpression(classDecorations), _core.types.numericLiteral(classDecorationsFlag), needsInstancePrivateBrandCheck ? lastInstancePrivateName : null, typeof className === "object" ? className : undefined, _core.types.cloneNode(superClass), state, version)), staticInitLocal && _core.types.expressionStatement(_core.types.callExpression(_core.types.cloneNode(staticInitLocal), [_core.types.thisExpression()]))].filter(Boolean)));
  666. path.insertBefore(assignments.map(expr => _core.types.expressionStatement(expr)));
  667. if (needsDeclaraionForClassBinding) {
  668. path.insertBefore(_core.types.variableDeclaration("let", [_core.types.variableDeclarator(_core.types.cloneNode(classIdLocal))]));
  669. }
  670. if (decoratedPrivateMethods.size > 0) {
  671. checkPrivateMethodUpdateError(path, decoratedPrivateMethods);
  672. }
  673. path.scope.crawl();
  674. return path;
  675. }
  676. function createLocalsAssignment(elementLocals, classLocals, elementDecorations, classDecorations, classDecorationsFlag, maybePrivateBranName, setClassName, superClass, state, version) {
  677. let lhs, rhs;
  678. const args = [setClassName ? createSetFunctionNameCall(state, setClassName) : _core.types.thisExpression(), elementDecorations, classDecorations];
  679. {
  680. if (version === "2021-12" || version === "2022-03" && !state.availableHelper("applyDecs2203R")) {
  681. const lhs = _core.types.arrayPattern([...elementLocals, ...classLocals]);
  682. const rhs = _core.types.callExpression(state.addHelper(version === "2021-12" ? "applyDecs" : "applyDecs2203"), args);
  683. return _core.types.assignmentExpression("=", lhs, rhs);
  684. }
  685. }
  686. if (version === "2023-05") {
  687. if (maybePrivateBranName || superClass || classDecorationsFlag.value !== 0) {
  688. args.push(classDecorationsFlag);
  689. }
  690. if (maybePrivateBranName) {
  691. args.push(_core.template.expression.ast`
  692. _ => ${_core.types.cloneNode(maybePrivateBranName)} in _
  693. `);
  694. } else if (superClass) {
  695. args.push(_core.types.unaryExpression("void", _core.types.numericLiteral(0)));
  696. }
  697. if (superClass) args.push(superClass);
  698. rhs = _core.types.callExpression(state.addHelper("applyDecs2305"), args);
  699. } else if (version === "2023-01") {
  700. if (maybePrivateBranName) {
  701. args.push(_core.template.expression.ast`
  702. _ => ${_core.types.cloneNode(maybePrivateBranName)} in _
  703. `);
  704. }
  705. rhs = _core.types.callExpression(state.addHelper("applyDecs2301"), args);
  706. } else {
  707. rhs = _core.types.callExpression(state.addHelper("applyDecs2203R"), args);
  708. }
  709. if (elementLocals.length > 0) {
  710. if (classLocals.length > 0) {
  711. lhs = _core.types.objectPattern([_core.types.objectProperty(_core.types.identifier("e"), _core.types.arrayPattern(elementLocals)), _core.types.objectProperty(_core.types.identifier("c"), _core.types.arrayPattern(classLocals))]);
  712. } else {
  713. lhs = _core.types.arrayPattern(elementLocals);
  714. rhs = _core.types.memberExpression(rhs, _core.types.identifier("e"), false, false);
  715. }
  716. } else {
  717. lhs = _core.types.arrayPattern(classLocals);
  718. rhs = _core.types.memberExpression(rhs, _core.types.identifier("c"), false, false);
  719. }
  720. return _core.types.assignmentExpression("=", lhs, rhs);
  721. }
  722. function isProtoKey(node) {
  723. return node.type === "Identifier" ? node.name === "__proto__" : node.value === "__proto__";
  724. }
  725. function isDecorated(node) {
  726. return node.decorators && node.decorators.length > 0;
  727. }
  728. function shouldTransformElement(node) {
  729. switch (node.type) {
  730. case "ClassAccessorProperty":
  731. return true;
  732. case "ClassMethod":
  733. case "ClassProperty":
  734. case "ClassPrivateMethod":
  735. case "ClassPrivateProperty":
  736. return isDecorated(node);
  737. default:
  738. return false;
  739. }
  740. }
  741. function shouldTransformClass(node) {
  742. return isDecorated(node) || node.body.body.some(shouldTransformElement);
  743. }
  744. function NamedEvaluationVisitoryFactory(isAnonymous, visitor) {
  745. function handleComputedProperty(propertyPath, key, state) {
  746. switch (key.type) {
  747. case "StringLiteral":
  748. return _core.types.stringLiteral(key.value);
  749. case "NumericLiteral":
  750. case "BigIntLiteral":
  751. {
  752. const keyValue = key.value + "";
  753. propertyPath.get("key").replaceWith(_core.types.stringLiteral(keyValue));
  754. return _core.types.stringLiteral(keyValue);
  755. }
  756. default:
  757. {
  758. const ref = propertyPath.scope.maybeGenerateMemoised(key);
  759. propertyPath.get("key").replaceWith(_core.types.assignmentExpression("=", ref, createToPropertyKeyCall(state, key)));
  760. return _core.types.cloneNode(ref);
  761. }
  762. }
  763. }
  764. return {
  765. VariableDeclarator(path, state) {
  766. const id = path.node.id;
  767. if (id.type === "Identifier") {
  768. const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("init"));
  769. if (isAnonymous(initializer)) {
  770. const name = id.name;
  771. visitor(initializer, state, name);
  772. }
  773. }
  774. },
  775. AssignmentExpression(path, state) {
  776. const id = path.node.left;
  777. if (id.type === "Identifier") {
  778. const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("right"));
  779. if (isAnonymous(initializer)) {
  780. switch (path.node.operator) {
  781. case "=":
  782. case "&&=":
  783. case "||=":
  784. case "??=":
  785. visitor(initializer, state, id.name);
  786. }
  787. }
  788. }
  789. },
  790. AssignmentPattern(path, state) {
  791. const id = path.node.left;
  792. if (id.type === "Identifier") {
  793. const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("right"));
  794. if (isAnonymous(initializer)) {
  795. const name = id.name;
  796. visitor(initializer, state, name);
  797. }
  798. }
  799. },
  800. ObjectExpression(path, state) {
  801. for (const propertyPath of path.get("properties")) {
  802. const {
  803. node
  804. } = propertyPath;
  805. if (node.type !== "ObjectProperty") continue;
  806. const id = node.key;
  807. const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(propertyPath.get("value"));
  808. if (isAnonymous(initializer)) {
  809. if (!node.computed) {
  810. if (!isProtoKey(id)) {
  811. if (id.type === "Identifier") {
  812. visitor(initializer, state, id.name);
  813. } else {
  814. const className = _core.types.stringLiteral(id.value + "");
  815. visitor(initializer, state, className);
  816. }
  817. }
  818. } else {
  819. const ref = handleComputedProperty(propertyPath, id, state);
  820. visitor(initializer, state, ref);
  821. }
  822. }
  823. }
  824. },
  825. ClassPrivateProperty(path, state) {
  826. const {
  827. node
  828. } = path;
  829. const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("value"));
  830. if (isAnonymous(initializer)) {
  831. const className = _core.types.stringLiteral("#" + node.key.id.name);
  832. visitor(initializer, state, className);
  833. }
  834. },
  835. ClassAccessorProperty(path, state) {
  836. const {
  837. node
  838. } = path;
  839. const id = node.key;
  840. const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("value"));
  841. if (isAnonymous(initializer)) {
  842. if (!node.computed) {
  843. if (id.type === "Identifier") {
  844. visitor(initializer, state, id.name);
  845. } else if (id.type === "PrivateName") {
  846. const className = _core.types.stringLiteral("#" + id.id.name);
  847. visitor(initializer, state, className);
  848. } else {
  849. const className = _core.types.stringLiteral(id.value + "");
  850. visitor(initializer, state, className);
  851. }
  852. } else {
  853. const ref = handleComputedProperty(path, id, state);
  854. visitor(initializer, state, ref);
  855. }
  856. }
  857. },
  858. ClassProperty(path, state) {
  859. const {
  860. node
  861. } = path;
  862. const id = node.key;
  863. const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("value"));
  864. if (isAnonymous(initializer)) {
  865. if (!node.computed) {
  866. if (id.type === "Identifier") {
  867. visitor(initializer, state, id.name);
  868. } else {
  869. const className = _core.types.stringLiteral(id.value + "");
  870. visitor(initializer, state, className);
  871. }
  872. } else {
  873. const ref = handleComputedProperty(path, id, state);
  874. visitor(initializer, state, ref);
  875. }
  876. }
  877. }
  878. };
  879. }
  880. function isDecoratedAnonymousClassExpression(path) {
  881. return path.isClassExpression({
  882. id: null
  883. }) && shouldTransformClass(path.node);
  884. }
  885. function _default({
  886. assertVersion,
  887. assumption
  888. }, {
  889. loose
  890. }, version, inherits) {
  891. var _assumption;
  892. {
  893. if (version === "2023-05" || version === "2023-01") {
  894. assertVersion("^7.21.0");
  895. } else if (version === "2021-12") {
  896. assertVersion("^7.16.0");
  897. } else {
  898. assertVersion("^7.19.0");
  899. }
  900. }
  901. const VISITED = new WeakSet();
  902. const constantSuper = (_assumption = assumption("constantSuper")) != null ? _assumption : loose;
  903. const namedEvaluationVisitor = NamedEvaluationVisitoryFactory(isDecoratedAnonymousClassExpression, visitClass);
  904. function visitClass(path, state, className) {
  905. var _className, _node$id;
  906. if (VISITED.has(path)) return;
  907. const {
  908. node
  909. } = path;
  910. (_className = className) != null ? _className : className = (_node$id = node.id) == null ? void 0 : _node$id.name;
  911. const newPath = transformClass(path, state, constantSuper, version, className, namedEvaluationVisitor);
  912. if (newPath) {
  913. VISITED.add(newPath);
  914. return;
  915. }
  916. VISITED.add(path);
  917. }
  918. return {
  919. name: "proposal-decorators",
  920. inherits: inherits,
  921. visitor: Object.assign({
  922. ExportDefaultDeclaration(path, state) {
  923. const {
  924. declaration
  925. } = path.node;
  926. if ((declaration == null ? void 0 : declaration.type) === "ClassDeclaration" && isDecorated(declaration)) {
  927. const isAnonymous = !declaration.id;
  928. const updatedVarDeclarationPath = (0, _helperSplitExportDeclaration.default)(path);
  929. if (isAnonymous) {
  930. visitClass(updatedVarDeclarationPath, state, _core.types.stringLiteral("default"));
  931. }
  932. }
  933. },
  934. ExportNamedDeclaration(path) {
  935. const {
  936. declaration
  937. } = path.node;
  938. if ((declaration == null ? void 0 : declaration.type) === "ClassDeclaration" && isDecorated(declaration)) {
  939. (0, _helperSplitExportDeclaration.default)(path);
  940. }
  941. },
  942. Class(path, state) {
  943. visitClass(path, state, undefined);
  944. }
  945. }, namedEvaluationVisitor)
  946. };
  947. }
  948. //# sourceMappingURL=decorators.js.map