Updated the files.

This commit is contained in:
Batuhan Berk Başoğlu 2024-02-08 19:38:41 -05:00
parent 1553e6b971
commit 753967d4f5
23418 changed files with 3784666 additions and 0 deletions

View file

@ -0,0 +1,22 @@
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1,19 @@
# @babel/helper-create-class-features-plugin
> Compile class public and private fields, private methods and decorators to ES6
See our website [@babel/helper-create-class-features-plugin](https://babeljs.io/docs/babel-helper-create-class-features-plugin) for more information.
## Install
Using npm:
```sh
npm install --save @babel/helper-create-class-features-plugin
```
or using yarn:
```sh
yarn add @babel/helper-create-class-features-plugin
```

View file

@ -0,0 +1,137 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.buildDecoratedClass = buildDecoratedClass;
exports.hasDecorators = hasDecorators;
exports.hasOwnDecorators = hasOwnDecorators;
var _core = require("@babel/core");
var _helperReplaceSupers = require("@babel/helper-replace-supers");
var _helperFunctionName = require("@babel/helper-function-name");
function hasOwnDecorators(node) {
var _node$decorators;
return !!((_node$decorators = node.decorators) != null && _node$decorators.length);
}
function hasDecorators(node) {
return hasOwnDecorators(node) || node.body.body.some(hasOwnDecorators);
}
function prop(key, value) {
if (!value) return null;
return _core.types.objectProperty(_core.types.identifier(key), value);
}
function method(key, body) {
return _core.types.objectMethod("method", _core.types.identifier(key), [], _core.types.blockStatement(body));
}
function takeDecorators(node) {
let result;
if (node.decorators && node.decorators.length > 0) {
result = _core.types.arrayExpression(node.decorators.map(decorator => decorator.expression));
}
node.decorators = undefined;
return result;
}
function getKey(node) {
if (node.computed) {
return node.key;
} else if (_core.types.isIdentifier(node.key)) {
return _core.types.stringLiteral(node.key.name);
} else {
return _core.types.stringLiteral(String(node.key.value));
}
}
function extractElementDescriptor(file, classRef, superRef, path) {
const isMethod = path.isClassMethod();
if (path.isPrivate()) {
throw path.buildCodeFrameError(`Private ${isMethod ? "methods" : "fields"} in decorated classes are not supported yet.`);
}
if (path.node.type === "ClassAccessorProperty") {
throw path.buildCodeFrameError(`Accessor properties are not supported in 2018-09 decorator transform, please specify { "version": "2021-12" } instead.`);
}
if (path.node.type === "StaticBlock") {
throw path.buildCodeFrameError(`Static blocks are not supported in 2018-09 decorator transform, please specify { "version": "2021-12" } instead.`);
}
const {
node,
scope
} = path;
if (!path.isTSDeclareMethod()) {
new _helperReplaceSupers.default({
methodPath: path,
objectRef: classRef,
superRef,
file,
refToPreserve: classRef
}).replace();
}
const properties = [prop("kind", _core.types.stringLiteral(_core.types.isClassMethod(node) ? node.kind : "field")), prop("decorators", takeDecorators(node)), prop("static", node.static && _core.types.booleanLiteral(true)), prop("key", getKey(node))].filter(Boolean);
if (_core.types.isClassMethod(node)) {
const id = node.computed ? null : node.key;
const transformed = _core.types.toExpression(node);
properties.push(prop("value", (0, _helperFunctionName.default)({
node: transformed,
id,
scope
}) || transformed));
} else if (_core.types.isClassProperty(node) && node.value) {
properties.push(method("value", _core.template.statements.ast`return ${node.value}`));
} else {
properties.push(prop("value", scope.buildUndefinedNode()));
}
path.remove();
return _core.types.objectExpression(properties);
}
function addDecorateHelper(file) {
return file.addHelper("decorate");
}
function buildDecoratedClass(ref, path, elements, file) {
const {
node,
scope
} = path;
const initializeId = scope.generateUidIdentifier("initialize");
const isDeclaration = node.id && path.isDeclaration();
const isStrict = path.isInStrictMode();
const {
superClass
} = node;
node.type = "ClassDeclaration";
if (!node.id) node.id = _core.types.cloneNode(ref);
let superId;
if (superClass) {
superId = scope.generateUidIdentifierBasedOnNode(node.superClass, "super");
node.superClass = superId;
}
const classDecorators = takeDecorators(node);
const definitions = _core.types.arrayExpression(elements.filter(element => !element.node.abstract && element.node.type !== "TSIndexSignature").map(path => extractElementDescriptor(file, node.id, superId, path)));
const wrapperCall = _core.template.expression.ast`
${addDecorateHelper(file)}(
${classDecorators || _core.types.nullLiteral()},
function (${initializeId}, ${superClass ? _core.types.cloneNode(superId) : null}) {
${node}
return { F: ${_core.types.cloneNode(node.id)}, d: ${definitions} };
},
${superClass}
)
`;
if (!isStrict) {
wrapperCall.arguments[1].body.directives.push(_core.types.directive(_core.types.directiveLiteral("use strict")));
}
let replacement = wrapperCall;
let classPathDesc = "arguments.1.body.body.0";
if (isDeclaration) {
replacement = _core.template.statement.ast`let ${ref} = ${wrapperCall}`;
classPathDesc = "declarations.0.init." + classPathDesc;
}
return {
instanceNodes: [_core.template.statement.ast`
${_core.types.cloneNode(initializeId)}(this)
`],
wrapClass(path) {
path.replaceWith(replacement);
return path.get(classPathDesc);
}
};
}
//# sourceMappingURL=decorators-2018-09.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,950 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _default;
var _core = require("@babel/core");
var _helperReplaceSupers = require("@babel/helper-replace-supers");
var _helperSplitExportDeclaration = require("@babel/helper-split-export-declaration");
var _helperSkipTransparentExpressionWrappers = require("@babel/helper-skip-transparent-expression-wrappers");
var _fields = require("./fields.js");
function incrementId(id, idx = id.length - 1) {
if (idx === -1) {
id.unshift(65);
return;
}
const current = id[idx];
if (current === 90) {
id[idx] = 97;
} else if (current === 122) {
id[idx] = 65;
incrementId(id, idx - 1);
} else {
id[idx] = current + 1;
}
}
function createPrivateUidGeneratorForClass(classPath) {
const currentPrivateId = [];
const privateNames = new Set();
classPath.traverse({
PrivateName(path) {
privateNames.add(path.node.id.name);
}
});
return () => {
let reifiedId;
do {
incrementId(currentPrivateId);
reifiedId = String.fromCharCode(...currentPrivateId);
} while (privateNames.has(reifiedId));
return _core.types.privateName(_core.types.identifier(reifiedId));
};
}
function createLazyPrivateUidGeneratorForClass(classPath) {
let generator;
return () => {
if (!generator) {
generator = createPrivateUidGeneratorForClass(classPath);
}
return generator();
};
}
function replaceClassWithVar(path, className) {
if (path.type === "ClassDeclaration") {
const id = path.node.id;
const className = id.name;
const varId = path.scope.generateUidIdentifierBasedOnNode(id);
const classId = _core.types.identifier(className);
path.scope.rename(className, varId.name);
path.get("id").replaceWith(classId);
return {
id: _core.types.cloneNode(varId),
path
};
} else {
let varId;
if (path.node.id) {
className = path.node.id.name;
varId = path.scope.parent.generateDeclaredUidIdentifier(className);
path.scope.rename(className, varId.name);
} else {
varId = path.scope.parent.generateDeclaredUidIdentifier(typeof className === "string" ? className : "decorated_class");
}
const newClassExpr = _core.types.classExpression(typeof className === "string" ? _core.types.identifier(className) : null, path.node.superClass, path.node.body);
const [newPath] = path.replaceWith(_core.types.sequenceExpression([newClassExpr, varId]));
return {
id: _core.types.cloneNode(varId),
path: newPath.get("expressions.0")
};
}
}
function generateClassProperty(key, value, isStatic) {
if (key.type === "PrivateName") {
return _core.types.classPrivateProperty(key, value, undefined, isStatic);
} else {
return _core.types.classProperty(key, value, undefined, undefined, isStatic);
}
}
function addProxyAccessorsFor(className, element, originalKey, targetKey, version, isComputed = false) {
const {
static: isStatic
} = element.node;
const thisArg = version === "2023-05" && isStatic ? className : _core.types.thisExpression();
const getterBody = _core.types.blockStatement([_core.types.returnStatement(_core.types.memberExpression(_core.types.cloneNode(thisArg), _core.types.cloneNode(targetKey)))]);
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")))]);
let getter, setter;
if (originalKey.type === "PrivateName") {
getter = _core.types.classPrivateMethod("get", _core.types.cloneNode(originalKey), [], getterBody, isStatic);
setter = _core.types.classPrivateMethod("set", _core.types.cloneNode(originalKey), [_core.types.identifier("v")], setterBody, isStatic);
} else {
getter = _core.types.classMethod("get", _core.types.cloneNode(originalKey), [], getterBody, isComputed, isStatic);
setter = _core.types.classMethod("set", _core.types.cloneNode(originalKey), [_core.types.identifier("v")], setterBody, isComputed, isStatic);
}
element.insertAfter(setter);
element.insertAfter(getter);
}
function extractProxyAccessorsFor(targetKey, version) {
if (version !== "2023-05" && version !== "2023-01") {
return [_core.template.expression.ast`
function () {
return this.${_core.types.cloneNode(targetKey)};
}
`, _core.template.expression.ast`
function (value) {
this.${_core.types.cloneNode(targetKey)} = value;
}
`];
}
return [_core.template.expression.ast`
o => o.${_core.types.cloneNode(targetKey)}
`, _core.template.expression.ast`
(o, v) => o.${_core.types.cloneNode(targetKey)} = v
`];
}
function prependExpressionsToFieldInitializer(expressions, fieldPath) {
const initializer = fieldPath.get("value");
if (initializer.node) {
expressions.push(initializer.node);
} else if (expressions.length > 0) {
expressions[expressions.length - 1] = _core.types.unaryExpression("void", expressions[expressions.length - 1]);
}
initializer.replaceWith(maybeSequenceExpression(expressions));
}
function prependExpressionsToConstructor(expressions, constructorPath) {
constructorPath.node.body.body.unshift(_core.types.expressionStatement(maybeSequenceExpression(expressions)));
}
function isProtoInitCallExpression(expression, protoInitCall) {
return _core.types.isCallExpression(expression) && _core.types.isIdentifier(expression.callee, {
name: protoInitCall.name
});
}
function optimizeSuperCallAndExpressions(expressions, protoInitLocal) {
if (expressions.length >= 2 && isProtoInitCallExpression(expressions[1], protoInitLocal)) {
const mergedSuperCall = _core.types.callExpression(_core.types.cloneNode(protoInitLocal), [expressions[0]]);
expressions.splice(0, 2, mergedSuperCall);
}
if (expressions.length >= 2 && _core.types.isThisExpression(expressions[expressions.length - 1]) && isProtoInitCallExpression(expressions[expressions.length - 2], protoInitLocal)) {
expressions.splice(expressions.length - 1, 1);
}
return maybeSequenceExpression(expressions);
}
function insertExpressionsAfterSuperCallAndOptimize(expressions, constructorPath, protoInitLocal) {
constructorPath.traverse({
CallExpression: {
exit(path) {
if (!path.get("callee").isSuper()) return;
const newNodes = [path.node, ...expressions.map(expr => _core.types.cloneNode(expr))];
if (path.isCompletionRecord()) {
newNodes.push(_core.types.thisExpression());
}
path.replaceWith(optimizeSuperCallAndExpressions(newNodes, protoInitLocal));
path.skip();
}
},
ClassMethod(path) {
if (path.node.kind === "constructor") {
path.skip();
}
}
});
}
function createConstructorFromExpressions(expressions, isDerivedClass) {
const body = [_core.types.expressionStatement(maybeSequenceExpression(expressions))];
if (isDerivedClass) {
body.unshift(_core.types.expressionStatement(_core.types.callExpression(_core.types.super(), [_core.types.spreadElement(_core.types.identifier("args"))])));
}
return _core.types.classMethod("constructor", _core.types.identifier("constructor"), isDerivedClass ? [_core.types.restElement(_core.types.identifier("args"))] : [], _core.types.blockStatement(body));
}
const FIELD = 0;
const ACCESSOR = 1;
const METHOD = 2;
const GETTER = 3;
const SETTER = 4;
const STATIC_OLD_VERSION = 5;
const STATIC = 8;
const DECORATORS_HAVE_THIS = 16;
function getElementKind(element) {
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;
}
}
}
function isDecoratorInfo(info) {
return "decorators" in info;
}
function filteredOrderedDecoratorInfo(info) {
const filtered = info.filter(isDecoratorInfo);
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)];
}
function generateDecorationList(decorators, decoratorsThis, version) {
const decsCount = decorators.length;
const hasOneThis = decoratorsThis.some(Boolean);
const decs = [];
for (let i = 0; i < decsCount; i++) {
if (version === "2023-05" && hasOneThis) {
decs.push(decoratorsThis[i] || _core.types.unaryExpression("void", _core.types.numericLiteral(0)));
}
decs.push(decorators[i]);
}
return {
hasThis: hasOneThis,
decs
};
}
function generateDecorationExprs(info, version) {
return _core.types.arrayExpression(filteredOrderedDecoratorInfo(info).map(el => {
const {
decs,
hasThis
} = generateDecorationList(el.decorators, el.decoratorsThis, version);
let flag = el.kind;
if (el.isStatic) {
flag += version === "2023-05" ? STATIC : STATIC_OLD_VERSION;
}
if (hasThis) flag += DECORATORS_HAVE_THIS;
return _core.types.arrayExpression([decs.length === 1 ? decs[0] : _core.types.arrayExpression(decs), _core.types.numericLiteral(flag), el.name, ...(el.privateMethods || [])]);
}));
}
function extractElementLocalAssignments(decorationInfo) {
const localIds = [];
for (const el of filteredOrderedDecoratorInfo(decorationInfo)) {
const {
locals
} = el;
if (Array.isArray(locals)) {
localIds.push(...locals);
} else if (locals !== undefined) {
localIds.push(locals);
}
}
return localIds;
}
function addCallAccessorsFor(element, key, getId, setId) {
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()]))])));
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")]))])));
}
function isNotTsParameter(node) {
return node.type !== "TSParameterProperty";
}
function movePrivateAccessor(element, key, methodLocalVar, isStatic) {
let params;
let block;
if (element.node.kind === "set") {
params = [_core.types.identifier("v")];
block = [_core.types.expressionStatement(_core.types.callExpression(methodLocalVar, [_core.types.thisExpression(), _core.types.identifier("v")]))];
} else {
params = [];
block = [_core.types.returnStatement(_core.types.callExpression(methodLocalVar, [_core.types.thisExpression()]))];
}
element.replaceWith(_core.types.classPrivateMethod(element.node.kind, _core.types.cloneNode(key), params, _core.types.blockStatement(block), isStatic));
}
function isClassDecoratableElementPath(path) {
const {
type
} = path;
return type !== "TSDeclareMethod" && type !== "TSIndexSignature" && type !== "StaticBlock";
}
function staticBlockToIIFE(block) {
return _core.types.callExpression(_core.types.arrowFunctionExpression([], _core.types.blockStatement(block.body)), []);
}
function maybeSequenceExpression(exprs) {
if (exprs.length === 0) return _core.types.unaryExpression("void", _core.types.numericLiteral(0));
if (exprs.length === 1) return exprs[0];
return _core.types.sequenceExpression(exprs);
}
function createSetFunctionNameCall(state, className) {
return _core.types.callExpression(state.addHelper("setFunctionName"), [_core.types.thisExpression(), className]);
}
function createToPropertyKeyCall(state, propertyKey) {
return _core.types.callExpression(state.addHelper("toPropertyKey"), [propertyKey]);
}
function checkPrivateMethodUpdateError(path, decoratedPrivateMethods) {
const privateNameVisitor = (0, _fields.privateNameVisitorFactory)({
PrivateName(path, state) {
if (!state.privateNamesMap.has(path.node.id.name)) return;
const parentPath = path.parentPath;
const parentParentPath = parentPath.parentPath;
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) {
throw path.buildCodeFrameError(`Decorated private methods are read-only, but "#${path.node.id.name}" is updated via this expression.`);
}
}
});
const privateNamesMap = new Map();
for (const name of decoratedPrivateMethods) {
privateNamesMap.set(name, null);
}
path.traverse(privateNameVisitor, {
privateNamesMap: privateNamesMap
});
}
function transformClass(path, state, constantSuper, version, className, propertyVisitor) {
const body = path.get("body.body");
const classDecorators = path.node.decorators;
let hasElementDecorators = false;
const generateClassPrivateUid = createLazyPrivateUidGeneratorForClass(path);
const assignments = [];
const scopeParent = path.scope.parent;
const memoiseExpression = (expression, hint) => {
const localEvaluatedId = scopeParent.generateDeclaredUidIdentifier(hint);
assignments.push(_core.types.assignmentExpression("=", localEvaluatedId, expression));
return _core.types.cloneNode(localEvaluatedId);
};
let protoInitLocal;
let staticInitLocal;
for (const element of body) {
if (!isClassDecoratableElementPath(element)) {
continue;
}
if (isDecorated(element.node)) {
switch (element.node.type) {
case "ClassProperty":
propertyVisitor.ClassProperty(element, state);
break;
case "ClassPrivateProperty":
propertyVisitor.ClassPrivateProperty(element, state);
break;
case "ClassAccessorProperty":
propertyVisitor.ClassAccessorProperty(element, state);
default:
if (element.node.static) {
var _staticInitLocal;
(_staticInitLocal = staticInitLocal) != null ? _staticInitLocal : staticInitLocal = scopeParent.generateDeclaredUidIdentifier("initStatic");
} else {
var _protoInitLocal;
(_protoInitLocal = protoInitLocal) != null ? _protoInitLocal : protoInitLocal = scopeParent.generateDeclaredUidIdentifier("initProto");
}
break;
}
hasElementDecorators = true;
} else if (element.node.type === "ClassAccessorProperty") {
propertyVisitor.ClassAccessorProperty(element, state);
const {
key,
value,
static: isStatic,
computed
} = element.node;
const newId = generateClassPrivateUid();
const newField = generateClassProperty(newId, value, isStatic);
const keyPath = element.get("key");
const [newPath] = element.replaceWith(newField);
addProxyAccessorsFor(path.node.id, newPath, computed && !keyPath.isConstantExpression() ? memoiseExpression(createToPropertyKeyCall(state, key), "computedKey") : key, newId, version, computed);
}
}
if (!classDecorators && !hasElementDecorators) {
if (assignments.length > 0) {
path.insertBefore(assignments.map(expr => _core.types.expressionStatement(expr)));
path.scope.crawl();
}
return;
}
const elementDecoratorInfo = [];
let constructorPath;
const decoratedPrivateMethods = new Set();
let classInitLocal, classIdLocal;
const decoratorsThis = new Map();
const maybeExtractDecorators = (decorators, memoiseInPlace) => {
let needMemoise = false;
for (const decorator of decorators) {
const {
expression
} = decorator;
if (version === "2023-05" && _core.types.isMemberExpression(expression)) {
let object;
if (_core.types.isSuper(expression.object) || _core.types.isThisExpression(expression.object)) {
needMemoise = true;
if (memoiseInPlace) {
object = memoiseExpression(_core.types.thisExpression(), "obj");
} else {
object = _core.types.thisExpression();
}
} else {
if (!scopeParent.isStatic(expression.object)) {
needMemoise = true;
if (memoiseInPlace) {
expression.object = memoiseExpression(expression.object, "obj");
}
}
object = _core.types.cloneNode(expression.object);
}
decoratorsThis.set(decorator, object);
}
if (!scopeParent.isStatic(expression)) {
needMemoise = true;
if (memoiseInPlace) {
decorator.expression = memoiseExpression(expression, "dec");
}
}
}
return needMemoise && !memoiseInPlace;
};
let needsDeclaraionForClassBinding = false;
let classDecorationsFlag = 0;
let classDecorations = [];
let classDecorationsId;
if (classDecorators) {
classInitLocal = scopeParent.generateDeclaredUidIdentifier("initClass");
needsDeclaraionForClassBinding = path.isClassDeclaration();
({
id: classIdLocal,
path
} = replaceClassWithVar(path, className));
path.node.decorators = null;
const needMemoise = maybeExtractDecorators(classDecorators, false);
const {
hasThis,
decs
} = generateDecorationList(classDecorators.map(el => el.expression), classDecorators.map(dec => decoratorsThis.get(dec)), version);
classDecorationsFlag = hasThis ? 1 : 0;
classDecorations = decs;
if (needMemoise) {
classDecorationsId = memoiseExpression(_core.types.arrayExpression(classDecorations), "classDecs");
}
} else {
if (!path.node.id) {
path.node.id = path.scope.generateUidIdentifier("Class");
}
classIdLocal = _core.types.cloneNode(path.node.id);
}
let lastInstancePrivateName;
let needsInstancePrivateBrandCheck = false;
let fieldInitializerAssignments = [];
if (hasElementDecorators) {
if (protoInitLocal) {
const protoInitCall = _core.types.callExpression(_core.types.cloneNode(protoInitLocal), [_core.types.thisExpression()]);
fieldInitializerAssignments.push(protoInitCall);
}
for (const element of body) {
if (!isClassDecoratableElementPath(element)) {
continue;
}
const {
node
} = element;
const decorators = element.node.decorators;
const hasDecorators = !!(decorators != null && decorators.length);
if (hasDecorators) {
maybeExtractDecorators(decorators, true);
}
const isComputed = "computed" in element.node && element.node.computed;
if (isComputed) {
if (!element.get("key").isConstantExpression()) {
node.key = memoiseExpression(createToPropertyKeyCall(state, node.key), "computedKey");
}
}
const kind = getElementKind(element);
const {
key
} = node;
const isPrivate = key.type === "PrivateName";
const isStatic = element.node.static;
let name = "computedKey";
if (isPrivate) {
name = key.id.name;
} else if (!isComputed && key.type === "Identifier") {
name = key.name;
}
if (isPrivate && !isStatic) {
if (hasDecorators) {
needsInstancePrivateBrandCheck = true;
}
if (_core.types.isClassPrivateProperty(node) || !lastInstancePrivateName) {
lastInstancePrivateName = key;
}
}
if (element.isClassMethod({
kind: "constructor"
})) {
constructorPath = element;
}
if (hasDecorators) {
let locals;
let privateMethods;
if (kind === ACCESSOR) {
const {
value
} = element.node;
const params = [_core.types.thisExpression()];
if (value) {
params.push(_core.types.cloneNode(value));
}
const newId = generateClassPrivateUid();
const newFieldInitId = element.scope.parent.generateDeclaredUidIdentifier(`init_${name}`);
const newValue = _core.types.callExpression(_core.types.cloneNode(newFieldInitId), params);
const newField = generateClassProperty(newId, newValue, isStatic);
const [newPath] = element.replaceWith(newField);
if (isPrivate) {
privateMethods = extractProxyAccessorsFor(newId, version);
const getId = newPath.scope.parent.generateDeclaredUidIdentifier(`get_${name}`);
const setId = newPath.scope.parent.generateDeclaredUidIdentifier(`set_${name}`);
addCallAccessorsFor(newPath, key, getId, setId);
locals = [newFieldInitId, getId, setId];
} else {
addProxyAccessorsFor(path.node.id, newPath, key, newId, version, isComputed);
locals = newFieldInitId;
}
} else if (kind === FIELD) {
const initId = element.scope.parent.generateDeclaredUidIdentifier(`init_${name}`);
const valuePath = element.get("value");
valuePath.replaceWith(_core.types.callExpression(_core.types.cloneNode(initId), [_core.types.thisExpression(), valuePath.node].filter(v => v)));
locals = initId;
if (isPrivate) {
privateMethods = extractProxyAccessorsFor(key, version);
}
} else if (isPrivate) {
locals = element.scope.parent.generateDeclaredUidIdentifier(`call_${name}`);
const replaceSupers = new _helperReplaceSupers.default({
constantSuper,
methodPath: element,
objectRef: classIdLocal,
superRef: path.node.superClass,
file: state.file,
refToPreserve: classIdLocal
});
replaceSupers.replace();
const {
params,
body,
async: isAsync
} = element.node;
privateMethods = [_core.types.functionExpression(undefined, params.filter(isNotTsParameter), body, isAsync)];
if (kind === GETTER || kind === SETTER) {
movePrivateAccessor(element, _core.types.cloneNode(key), _core.types.cloneNode(locals), isStatic);
} else {
const node = element.node;
path.node.body.body.unshift(_core.types.classPrivateProperty(key, _core.types.cloneNode(locals), [], node.static));
decoratedPrivateMethods.add(key.id.name);
element.remove();
}
}
let nameExpr;
if (isComputed) {
nameExpr = _core.types.cloneNode(key);
} else if (key.type === "PrivateName") {
nameExpr = _core.types.stringLiteral(key.id.name);
} else if (key.type === "Identifier") {
nameExpr = _core.types.stringLiteral(key.name);
} else {
nameExpr = _core.types.cloneNode(key);
}
elementDecoratorInfo.push({
kind,
decorators: decorators.map(d => d.expression),
decoratorsThis: decorators.map(d => decoratorsThis.get(d)),
name: nameExpr,
isStatic,
privateMethods,
locals
});
if (element.node) {
element.node.decorators = null;
}
}
if (fieldInitializerAssignments.length > 0 && !isStatic && (kind === FIELD || kind === ACCESSOR)) {
prependExpressionsToFieldInitializer(fieldInitializerAssignments, element);
fieldInitializerAssignments = [];
}
}
}
if (fieldInitializerAssignments.length > 0) {
const isDerivedClass = !!path.node.superClass;
if (constructorPath) {
if (isDerivedClass) {
insertExpressionsAfterSuperCallAndOptimize(fieldInitializerAssignments, constructorPath, protoInitLocal);
} else {
prependExpressionsToConstructor(fieldInitializerAssignments, constructorPath);
}
} else {
path.node.body.body.unshift(createConstructorFromExpressions(fieldInitializerAssignments, isDerivedClass));
}
fieldInitializerAssignments = [];
}
const elementDecorations = generateDecorationExprs(elementDecoratorInfo, version);
const elementLocals = extractElementLocalAssignments(elementDecoratorInfo);
if (protoInitLocal) {
elementLocals.push(protoInitLocal);
}
if (staticInitLocal) {
elementLocals.push(staticInitLocal);
}
const classLocals = [];
let classInitInjected = false;
const classInitCall = classInitLocal && _core.types.callExpression(_core.types.cloneNode(classInitLocal), []);
const originalClass = path.node;
if (classDecorators) {
classLocals.push(classIdLocal, classInitLocal);
const statics = [];
let staticBlocks = [];
path.get("body.body").forEach(element => {
if (element.isStaticBlock()) {
staticBlocks.push(element.node);
element.remove();
return;
}
const isProperty = element.isClassProperty() || element.isClassPrivateProperty();
if ((isProperty || element.isClassPrivateMethod()) && element.node.static) {
if (isProperty && staticBlocks.length > 0) {
const allValues = staticBlocks.map(staticBlockToIIFE);
if (element.node.value) allValues.push(element.node.value);
element.node.value = maybeSequenceExpression(allValues);
staticBlocks = [];
}
element.node.static = false;
statics.push(element.node);
element.remove();
}
});
if (statics.length > 0 || staticBlocks.length > 0) {
const staticsClass = _core.template.expression.ast`
class extends ${state.addHelper("identity")} {}
`;
staticsClass.body.body = [_core.types.staticBlock([_core.types.toStatement(originalClass, true) || _core.types.expressionStatement(originalClass)]), ...statics];
const constructorBody = [];
const newExpr = _core.types.newExpression(staticsClass, []);
if (staticBlocks.length > 0) {
constructorBody.push(...staticBlocks.map(staticBlockToIIFE));
}
if (classInitCall) {
classInitInjected = true;
constructorBody.push(classInitCall);
}
if (constructorBody.length > 0) {
constructorBody.unshift(_core.types.callExpression(_core.types.super(), [_core.types.cloneNode(classIdLocal)]));
staticsClass.body.body.push(_core.types.classMethod("constructor", _core.types.identifier("constructor"), [], _core.types.blockStatement([_core.types.expressionStatement(_core.types.sequenceExpression(constructorBody))])));
} else {
newExpr.arguments.push(_core.types.cloneNode(classIdLocal));
}
path.replaceWith(newExpr);
}
}
if (!classInitInjected && classInitCall) {
path.node.body.body.push(_core.types.staticBlock([_core.types.expressionStatement(classInitCall)]));
}
let {
superClass
} = originalClass;
if (superClass && version === "2023-05") {
const id = path.scope.maybeGenerateMemoised(superClass);
if (id) {
originalClass.superClass = _core.types.assignmentExpression("=", id, superClass);
superClass = id;
}
}
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)));
path.insertBefore(assignments.map(expr => _core.types.expressionStatement(expr)));
if (needsDeclaraionForClassBinding) {
path.insertBefore(_core.types.variableDeclaration("let", [_core.types.variableDeclarator(_core.types.cloneNode(classIdLocal))]));
}
if (decoratedPrivateMethods.size > 0) {
checkPrivateMethodUpdateError(path, decoratedPrivateMethods);
}
path.scope.crawl();
return path;
}
function createLocalsAssignment(elementLocals, classLocals, elementDecorations, classDecorations, classDecorationsFlag, maybePrivateBranName, setClassName, superClass, state, version) {
let lhs, rhs;
const args = [setClassName ? createSetFunctionNameCall(state, setClassName) : _core.types.thisExpression(), elementDecorations, classDecorations];
{
if (version === "2021-12" || version === "2022-03" && !state.availableHelper("applyDecs2203R")) {
const lhs = _core.types.arrayPattern([...elementLocals, ...classLocals]);
const rhs = _core.types.callExpression(state.addHelper(version === "2021-12" ? "applyDecs" : "applyDecs2203"), args);
return _core.types.assignmentExpression("=", lhs, rhs);
}
}
if (version === "2023-05") {
if (maybePrivateBranName || superClass || classDecorationsFlag.value !== 0) {
args.push(classDecorationsFlag);
}
if (maybePrivateBranName) {
args.push(_core.template.expression.ast`
_ => ${_core.types.cloneNode(maybePrivateBranName)} in _
`);
} else if (superClass) {
args.push(_core.types.unaryExpression("void", _core.types.numericLiteral(0)));
}
if (superClass) args.push(superClass);
rhs = _core.types.callExpression(state.addHelper("applyDecs2305"), args);
} else if (version === "2023-01") {
if (maybePrivateBranName) {
args.push(_core.template.expression.ast`
_ => ${_core.types.cloneNode(maybePrivateBranName)} in _
`);
}
rhs = _core.types.callExpression(state.addHelper("applyDecs2301"), args);
} else {
rhs = _core.types.callExpression(state.addHelper("applyDecs2203R"), args);
}
if (elementLocals.length > 0) {
if (classLocals.length > 0) {
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))]);
} else {
lhs = _core.types.arrayPattern(elementLocals);
rhs = _core.types.memberExpression(rhs, _core.types.identifier("e"), false, false);
}
} else {
lhs = _core.types.arrayPattern(classLocals);
rhs = _core.types.memberExpression(rhs, _core.types.identifier("c"), false, false);
}
return _core.types.assignmentExpression("=", lhs, rhs);
}
function isProtoKey(node) {
return node.type === "Identifier" ? node.name === "__proto__" : node.value === "__proto__";
}
function isDecorated(node) {
return node.decorators && node.decorators.length > 0;
}
function shouldTransformElement(node) {
switch (node.type) {
case "ClassAccessorProperty":
return true;
case "ClassMethod":
case "ClassProperty":
case "ClassPrivateMethod":
case "ClassPrivateProperty":
return isDecorated(node);
default:
return false;
}
}
function shouldTransformClass(node) {
return isDecorated(node) || node.body.body.some(shouldTransformElement);
}
function NamedEvaluationVisitoryFactory(isAnonymous, visitor) {
function handleComputedProperty(propertyPath, key, state) {
switch (key.type) {
case "StringLiteral":
return _core.types.stringLiteral(key.value);
case "NumericLiteral":
case "BigIntLiteral":
{
const keyValue = key.value + "";
propertyPath.get("key").replaceWith(_core.types.stringLiteral(keyValue));
return _core.types.stringLiteral(keyValue);
}
default:
{
const ref = propertyPath.scope.maybeGenerateMemoised(key);
propertyPath.get("key").replaceWith(_core.types.assignmentExpression("=", ref, createToPropertyKeyCall(state, key)));
return _core.types.cloneNode(ref);
}
}
}
return {
VariableDeclarator(path, state) {
const id = path.node.id;
if (id.type === "Identifier") {
const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("init"));
if (isAnonymous(initializer)) {
const name = id.name;
visitor(initializer, state, name);
}
}
},
AssignmentExpression(path, state) {
const id = path.node.left;
if (id.type === "Identifier") {
const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("right"));
if (isAnonymous(initializer)) {
switch (path.node.operator) {
case "=":
case "&&=":
case "||=":
case "??=":
visitor(initializer, state, id.name);
}
}
}
},
AssignmentPattern(path, state) {
const id = path.node.left;
if (id.type === "Identifier") {
const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("right"));
if (isAnonymous(initializer)) {
const name = id.name;
visitor(initializer, state, name);
}
}
},
ObjectExpression(path, state) {
for (const propertyPath of path.get("properties")) {
const {
node
} = propertyPath;
if (node.type !== "ObjectProperty") continue;
const id = node.key;
const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(propertyPath.get("value"));
if (isAnonymous(initializer)) {
if (!node.computed) {
if (!isProtoKey(id)) {
if (id.type === "Identifier") {
visitor(initializer, state, id.name);
} else {
const className = _core.types.stringLiteral(id.value + "");
visitor(initializer, state, className);
}
}
} else {
const ref = handleComputedProperty(propertyPath, id, state);
visitor(initializer, state, ref);
}
}
}
},
ClassPrivateProperty(path, state) {
const {
node
} = path;
const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("value"));
if (isAnonymous(initializer)) {
const className = _core.types.stringLiteral("#" + node.key.id.name);
visitor(initializer, state, className);
}
},
ClassAccessorProperty(path, state) {
const {
node
} = path;
const id = node.key;
const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("value"));
if (isAnonymous(initializer)) {
if (!node.computed) {
if (id.type === "Identifier") {
visitor(initializer, state, id.name);
} else if (id.type === "PrivateName") {
const className = _core.types.stringLiteral("#" + id.id.name);
visitor(initializer, state, className);
} else {
const className = _core.types.stringLiteral(id.value + "");
visitor(initializer, state, className);
}
} else {
const ref = handleComputedProperty(path, id, state);
visitor(initializer, state, ref);
}
}
},
ClassProperty(path, state) {
const {
node
} = path;
const id = node.key;
const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("value"));
if (isAnonymous(initializer)) {
if (!node.computed) {
if (id.type === "Identifier") {
visitor(initializer, state, id.name);
} else {
const className = _core.types.stringLiteral(id.value + "");
visitor(initializer, state, className);
}
} else {
const ref = handleComputedProperty(path, id, state);
visitor(initializer, state, ref);
}
}
}
};
}
function isDecoratedAnonymousClassExpression(path) {
return path.isClassExpression({
id: null
}) && shouldTransformClass(path.node);
}
function _default({
assertVersion,
assumption
}, {
loose
}, version, inherits) {
var _assumption;
{
if (version === "2023-05" || version === "2023-01") {
assertVersion("^7.21.0");
} else if (version === "2021-12") {
assertVersion("^7.16.0");
} else {
assertVersion("^7.19.0");
}
}
const VISITED = new WeakSet();
const constantSuper = (_assumption = assumption("constantSuper")) != null ? _assumption : loose;
const namedEvaluationVisitor = NamedEvaluationVisitoryFactory(isDecoratedAnonymousClassExpression, visitClass);
function visitClass(path, state, className) {
var _className, _node$id;
if (VISITED.has(path)) return;
const {
node
} = path;
(_className = className) != null ? _className : className = (_node$id = node.id) == null ? void 0 : _node$id.name;
const newPath = transformClass(path, state, constantSuper, version, className, namedEvaluationVisitor);
if (newPath) {
VISITED.add(newPath);
return;
}
VISITED.add(path);
}
return {
name: "proposal-decorators",
inherits: inherits,
visitor: Object.assign({
ExportDefaultDeclaration(path, state) {
const {
declaration
} = path.node;
if ((declaration == null ? void 0 : declaration.type) === "ClassDeclaration" && isDecorated(declaration)) {
const isAnonymous = !declaration.id;
const updatedVarDeclarationPath = (0, _helperSplitExportDeclaration.default)(path);
if (isAnonymous) {
visitClass(updatedVarDeclarationPath, state, _core.types.stringLiteral("default"));
}
}
},
ExportNamedDeclaration(path) {
const {
declaration
} = path.node;
if ((declaration == null ? void 0 : declaration.type) === "ClassDeclaration" && isDecorated(declaration)) {
(0, _helperSplitExportDeclaration.default)(path);
}
},
Class(path, state) {
visitClass(path, state, undefined);
}
}, namedEvaluationVisitor)
};
}
//# sourceMappingURL=decorators.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,132 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.FEATURES = void 0;
exports.enableFeature = enableFeature;
exports.isLoose = isLoose;
exports.shouldTransform = shouldTransform;
var _decorators = require("./decorators-2018-09.js");
const FEATURES = exports.FEATURES = Object.freeze({
fields: 1 << 1,
privateMethods: 1 << 2,
decorators: 1 << 3,
privateIn: 1 << 4,
staticBlocks: 1 << 5
});
const featuresSameLoose = new Map([[FEATURES.fields, "@babel/plugin-transform-class-properties"], [FEATURES.privateMethods, "@babel/plugin-transform-private-methods"], [FEATURES.privateIn, "@babel/plugin-transform-private-property-in-object"]]);
const featuresKey = "@babel/plugin-class-features/featuresKey";
const looseKey = "@babel/plugin-class-features/looseKey";
{
var looseLowPriorityKey = "@babel/plugin-class-features/looseLowPriorityKey/#__internal__@babel/preset-env__please-overwrite-loose-instead-of-throwing";
}
{
var canIgnoreLoose = function (file, feature) {
return !!(file.get(looseLowPriorityKey) & feature);
};
}
function enableFeature(file, feature, loose) {
if (!hasFeature(file, feature) || canIgnoreLoose(file, feature)) {
file.set(featuresKey, file.get(featuresKey) | feature);
if (loose === "#__internal__@babel/preset-env__prefer-true-but-false-is-ok-if-it-prevents-an-error") {
setLoose(file, feature, true);
file.set(looseLowPriorityKey, file.get(looseLowPriorityKey) | feature);
} else if (loose === "#__internal__@babel/preset-env__prefer-false-but-true-is-ok-if-it-prevents-an-error") {
setLoose(file, feature, false);
file.set(looseLowPriorityKey, file.get(looseLowPriorityKey) | feature);
} else {
setLoose(file, feature, loose);
}
}
let resolvedLoose;
for (const [mask, name] of featuresSameLoose) {
if (!hasFeature(file, mask)) continue;
{
if (canIgnoreLoose(file, mask)) continue;
}
const loose = isLoose(file, mask);
if (resolvedLoose === !loose) {
throw new Error("'loose' mode configuration must be the same for @babel/plugin-transform-class-properties, " + "@babel/plugin-transform-private-methods and " + "@babel/plugin-transform-private-property-in-object (when they are enabled).");
} else {
resolvedLoose = loose;
{
var higherPriorityPluginName = name;
}
}
}
if (resolvedLoose !== undefined) {
for (const [mask, name] of featuresSameLoose) {
if (hasFeature(file, mask) && isLoose(file, mask) !== resolvedLoose) {
setLoose(file, mask, resolvedLoose);
console.warn(`Though the "loose" option was set to "${!resolvedLoose}" in your @babel/preset-env ` + `config, it will not be used for ${name} since the "loose" mode option was set to ` + `"${resolvedLoose}" for ${higherPriorityPluginName}.\nThe "loose" option must be the ` + `same for @babel/plugin-transform-class-properties, @babel/plugin-transform-private-methods ` + `and @babel/plugin-transform-private-property-in-object (when they are enabled): you can ` + `silence this warning by explicitly adding\n` + `\t["${name}", { "loose": ${resolvedLoose} }]\n` + `to the "plugins" section of your Babel config.`);
}
}
}
}
function hasFeature(file, feature) {
return !!(file.get(featuresKey) & feature);
}
function isLoose(file, feature) {
return !!(file.get(looseKey) & feature);
}
function setLoose(file, feature, loose) {
if (loose) file.set(looseKey, file.get(looseKey) | feature);else file.set(looseKey, file.get(looseKey) & ~feature);
{
file.set(looseLowPriorityKey, file.get(looseLowPriorityKey) & ~feature);
}
}
function shouldTransform(path, file) {
let decoratorPath = null;
let publicFieldPath = null;
let privateFieldPath = null;
let privateMethodPath = null;
let staticBlockPath = null;
if ((0, _decorators.hasOwnDecorators)(path.node)) {
decoratorPath = path.get("decorators.0");
}
for (const el of path.get("body.body")) {
if (!decoratorPath && (0, _decorators.hasOwnDecorators)(el.node)) {
decoratorPath = el.get("decorators.0");
}
if (!publicFieldPath && el.isClassProperty()) {
publicFieldPath = el;
}
if (!privateFieldPath && el.isClassPrivateProperty()) {
privateFieldPath = el;
}
if (!privateMethodPath && el.isClassPrivateMethod != null && el.isClassPrivateMethod()) {
privateMethodPath = el;
}
if (!staticBlockPath && el.isStaticBlock != null && el.isStaticBlock()) {
staticBlockPath = el;
}
}
if (decoratorPath && privateFieldPath) {
throw privateFieldPath.buildCodeFrameError("Private fields in decorated classes are not supported yet.");
}
if (decoratorPath && privateMethodPath) {
throw privateMethodPath.buildCodeFrameError("Private methods in decorated classes are not supported yet.");
}
if (decoratorPath && !hasFeature(file, FEATURES.decorators)) {
throw path.buildCodeFrameError("Decorators are not enabled." + "\nIf you are using " + '["@babel/plugin-proposal-decorators", { "version": "legacy" }], ' + 'make sure it comes *before* "@babel/plugin-transform-class-properties" ' + "and enable loose mode, like so:\n" + '\t["@babel/plugin-proposal-decorators", { "version": "legacy" }]\n' + '\t["@babel/plugin-transform-class-properties", { "loose": true }]');
}
if (privateMethodPath && !hasFeature(file, FEATURES.privateMethods)) {
throw privateMethodPath.buildCodeFrameError("Class private methods are not enabled. " + "Please add `@babel/plugin-transform-private-methods` to your configuration.");
}
if ((publicFieldPath || privateFieldPath) && !hasFeature(file, FEATURES.fields) && !hasFeature(file, FEATURES.privateMethods)) {
throw path.buildCodeFrameError("Class fields are not enabled. " + "Please add `@babel/plugin-transform-class-properties` to your configuration.");
}
if (staticBlockPath && !hasFeature(file, FEATURES.staticBlocks)) {
throw path.buildCodeFrameError("Static class blocks are not enabled. " + "Please add `@babel/plugin-transform-class-static-block` to your configuration.");
}
if (decoratorPath || privateMethodPath || staticBlockPath) {
return true;
}
if ((publicFieldPath || privateFieldPath) && hasFeature(file, FEATURES.fields)) {
return true;
}
return false;
}
//# sourceMappingURL=features.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,845 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.buildCheckInRHS = buildCheckInRHS;
exports.buildFieldsInitNodes = buildFieldsInitNodes;
exports.buildPrivateNamesMap = buildPrivateNamesMap;
exports.buildPrivateNamesNodes = buildPrivateNamesNodes;
exports.privateNameVisitorFactory = privateNameVisitorFactory;
exports.transformPrivateNamesUsage = transformPrivateNamesUsage;
var _core = require("@babel/core");
var _helperReplaceSupers = require("@babel/helper-replace-supers");
var _helperEnvironmentVisitor = require("@babel/helper-environment-visitor");
var _helperMemberExpressionToFunctions = require("@babel/helper-member-expression-to-functions");
var _helperOptimiseCallExpression = require("@babel/helper-optimise-call-expression");
var _helperAnnotateAsPure = require("@babel/helper-annotate-as-pure");
var _helperSkipTransparentExpressionWrappers = require("@babel/helper-skip-transparent-expression-wrappers");
var ts = require("./typescript.js");
function buildPrivateNamesMap(props) {
const privateNamesMap = new Map();
for (const prop of props) {
if (prop.isPrivate()) {
const {
name
} = prop.node.key.id;
const update = privateNamesMap.has(name) ? privateNamesMap.get(name) : {
id: prop.scope.generateUidIdentifier(name),
static: prop.node.static,
method: !prop.isProperty()
};
if (prop.isClassPrivateMethod()) {
if (prop.node.kind === "get") {
update.getId = prop.scope.generateUidIdentifier(`get_${name}`);
} else if (prop.node.kind === "set") {
update.setId = prop.scope.generateUidIdentifier(`set_${name}`);
} else if (prop.node.kind === "method") {
update.methodId = prop.scope.generateUidIdentifier(name);
}
}
privateNamesMap.set(name, update);
}
}
return privateNamesMap;
}
function buildPrivateNamesNodes(privateNamesMap, privateFieldsAsProperties, privateFieldsAsSymbols, state) {
const initNodes = [];
for (const [name, value] of privateNamesMap) {
const {
static: isStatic,
method: isMethod,
getId,
setId
} = value;
const isAccessor = getId || setId;
const id = _core.types.cloneNode(value.id);
let init;
if (privateFieldsAsProperties) {
init = _core.types.callExpression(state.addHelper("classPrivateFieldLooseKey"), [_core.types.stringLiteral(name)]);
} else if (privateFieldsAsSymbols) {
init = _core.types.callExpression(_core.types.identifier("Symbol"), [_core.types.stringLiteral(name)]);
} else if (!isStatic) {
init = _core.types.newExpression(_core.types.identifier(!isMethod || isAccessor ? "WeakMap" : "WeakSet"), []);
}
if (init) {
(0, _helperAnnotateAsPure.default)(init);
initNodes.push(_core.template.statement.ast`var ${id} = ${init}`);
}
}
return initNodes;
}
function privateNameVisitorFactory(visitor) {
const nestedVisitor = _core.traverse.visitors.merge([Object.assign({}, visitor), _helperEnvironmentVisitor.default]);
const privateNameVisitor = Object.assign({}, visitor, {
Class(path) {
const {
privateNamesMap
} = this;
const body = path.get("body.body");
const visiblePrivateNames = new Map(privateNamesMap);
const redeclared = [];
for (const prop of body) {
if (!prop.isPrivate()) continue;
const {
name
} = prop.node.key.id;
visiblePrivateNames.delete(name);
redeclared.push(name);
}
if (!redeclared.length) {
return;
}
path.get("body").traverse(nestedVisitor, Object.assign({}, this, {
redeclared
}));
path.traverse(privateNameVisitor, Object.assign({}, this, {
privateNamesMap: visiblePrivateNames
}));
path.skipKey("body");
}
});
return privateNameVisitor;
}
const privateNameVisitor = privateNameVisitorFactory({
PrivateName(path, {
noDocumentAll
}) {
const {
privateNamesMap,
redeclared
} = this;
const {
node,
parentPath
} = path;
if (!parentPath.isMemberExpression({
property: node
}) && !parentPath.isOptionalMemberExpression({
property: node
})) {
return;
}
const {
name
} = node.id;
if (!privateNamesMap.has(name)) return;
if (redeclared && redeclared.includes(name)) return;
this.handle(parentPath, noDocumentAll);
}
});
function unshadow(name, scope, innerBinding) {
while ((_scope = scope) != null && _scope.hasBinding(name) && !scope.bindingIdentifierEquals(name, innerBinding)) {
var _scope;
scope.rename(name);
scope = scope.parent;
}
}
function buildCheckInRHS(rhs, file, inRHSIsObject) {
if (inRHSIsObject || !(file.availableHelper != null && file.availableHelper("checkInRHS"))) return rhs;
return _core.types.callExpression(file.addHelper("checkInRHS"), [rhs]);
}
const privateInVisitor = privateNameVisitorFactory({
BinaryExpression(path, {
file
}) {
const {
operator,
left,
right
} = path.node;
if (operator !== "in") return;
if (!_core.types.isPrivateName(left)) return;
const {
privateFieldsAsProperties,
privateNamesMap,
redeclared
} = this;
const {
name
} = left.id;
if (!privateNamesMap.has(name)) return;
if (redeclared && redeclared.includes(name)) return;
unshadow(this.classRef.name, path.scope, this.innerBinding);
if (privateFieldsAsProperties) {
const {
id
} = privateNamesMap.get(name);
path.replaceWith(_core.template.expression.ast`
Object.prototype.hasOwnProperty.call(${buildCheckInRHS(right, file)}, ${_core.types.cloneNode(id)})
`);
return;
}
const {
id,
static: isStatic
} = privateNamesMap.get(name);
if (isStatic) {
path.replaceWith(_core.template.expression.ast`${buildCheckInRHS(right, file)} === ${_core.types.cloneNode(this.classRef)}`);
return;
}
path.replaceWith(_core.template.expression.ast`${_core.types.cloneNode(id)}.has(${buildCheckInRHS(right, file)})`);
}
});
const privateNameHandlerSpec = {
memoise(member, count) {
const {
scope
} = member;
const {
object
} = member.node;
const memo = scope.maybeGenerateMemoised(object);
if (!memo) {
return;
}
this.memoiser.set(object, memo, count);
},
receiver(member) {
const {
object
} = member.node;
if (this.memoiser.has(object)) {
return _core.types.cloneNode(this.memoiser.get(object));
}
return _core.types.cloneNode(object);
},
get(member) {
const {
classRef,
privateNamesMap,
file,
innerBinding
} = this;
const {
name
} = member.node.property.id;
const {
id,
static: isStatic,
method: isMethod,
methodId,
getId,
setId
} = privateNamesMap.get(name);
const isAccessor = getId || setId;
if (isStatic) {
const helperName = isMethod && !isAccessor ? "classStaticPrivateMethodGet" : "classStaticPrivateFieldSpecGet";
unshadow(classRef.name, member.scope, innerBinding);
return _core.types.callExpression(file.addHelper(helperName), [this.receiver(member), _core.types.cloneNode(classRef), _core.types.cloneNode(id)]);
}
if (isMethod) {
if (isAccessor) {
if (!getId && setId) {
if (file.availableHelper("writeOnlyError")) {
return _core.types.sequenceExpression([this.receiver(member), _core.types.callExpression(file.addHelper("writeOnlyError"), [_core.types.stringLiteral(`#${name}`)])]);
}
console.warn(`@babel/helpers is outdated, update it to silence this warning.`);
}
return _core.types.callExpression(file.addHelper("classPrivateFieldGet"), [this.receiver(member), _core.types.cloneNode(id)]);
}
return _core.types.callExpression(file.addHelper("classPrivateMethodGet"), [this.receiver(member), _core.types.cloneNode(id), _core.types.cloneNode(methodId)]);
}
return _core.types.callExpression(file.addHelper("classPrivateFieldGet"), [this.receiver(member), _core.types.cloneNode(id)]);
},
boundGet(member) {
this.memoise(member, 1);
return _core.types.callExpression(_core.types.memberExpression(this.get(member), _core.types.identifier("bind")), [this.receiver(member)]);
},
set(member, value) {
const {
classRef,
privateNamesMap,
file
} = this;
const {
name
} = member.node.property.id;
const {
id,
static: isStatic,
method: isMethod,
setId,
getId
} = privateNamesMap.get(name);
const isAccessor = getId || setId;
if (isStatic) {
const helperName = isMethod && !isAccessor ? "classStaticPrivateMethodSet" : "classStaticPrivateFieldSpecSet";
return _core.types.callExpression(file.addHelper(helperName), [this.receiver(member), _core.types.cloneNode(classRef), _core.types.cloneNode(id), value]);
}
if (isMethod) {
if (setId) {
return _core.types.callExpression(file.addHelper("classPrivateFieldSet"), [this.receiver(member), _core.types.cloneNode(id), value]);
}
return _core.types.sequenceExpression([this.receiver(member), value, _core.types.callExpression(file.addHelper("readOnlyError"), [_core.types.stringLiteral(`#${name}`)])]);
}
return _core.types.callExpression(file.addHelper("classPrivateFieldSet"), [this.receiver(member), _core.types.cloneNode(id), value]);
},
destructureSet(member) {
const {
classRef,
privateNamesMap,
file
} = this;
const {
name
} = member.node.property.id;
const {
id,
static: isStatic
} = privateNamesMap.get(name);
if (isStatic) {
try {
var helper = file.addHelper("classStaticPrivateFieldDestructureSet");
} catch (_unused) {
throw new Error("Babel can not transpile `[C.#p] = [0]` with @babel/helpers < 7.13.10, \n" + "please update @babel/helpers to the latest version.");
}
return _core.types.memberExpression(_core.types.callExpression(helper, [this.receiver(member), _core.types.cloneNode(classRef), _core.types.cloneNode(id)]), _core.types.identifier("value"));
}
return _core.types.memberExpression(_core.types.callExpression(file.addHelper("classPrivateFieldDestructureSet"), [this.receiver(member), _core.types.cloneNode(id)]), _core.types.identifier("value"));
},
call(member, args) {
this.memoise(member, 1);
return (0, _helperOptimiseCallExpression.default)(this.get(member), this.receiver(member), args, false);
},
optionalCall(member, args) {
this.memoise(member, 1);
return (0, _helperOptimiseCallExpression.default)(this.get(member), this.receiver(member), args, true);
},
delete() {
throw new Error("Internal Babel error: deleting private elements is a parsing error.");
}
};
const privateNameHandlerLoose = {
get(member) {
const {
privateNamesMap,
file
} = this;
const {
object
} = member.node;
const {
name
} = member.node.property.id;
return _core.template.expression`BASE(REF, PROP)[PROP]`({
BASE: file.addHelper("classPrivateFieldLooseBase"),
REF: _core.types.cloneNode(object),
PROP: _core.types.cloneNode(privateNamesMap.get(name).id)
});
},
set() {
throw new Error("private name handler with loose = true don't need set()");
},
boundGet(member) {
return _core.types.callExpression(_core.types.memberExpression(this.get(member), _core.types.identifier("bind")), [_core.types.cloneNode(member.node.object)]);
},
simpleSet(member) {
return this.get(member);
},
destructureSet(member) {
return this.get(member);
},
call(member, args) {
return _core.types.callExpression(this.get(member), args);
},
optionalCall(member, args) {
return _core.types.optionalCallExpression(this.get(member), args, true);
},
delete() {
throw new Error("Internal Babel error: deleting private elements is a parsing error.");
}
};
function transformPrivateNamesUsage(ref, path, privateNamesMap, {
privateFieldsAsProperties,
noDocumentAll,
innerBinding
}, state) {
if (!privateNamesMap.size) return;
const body = path.get("body");
const handler = privateFieldsAsProperties ? privateNameHandlerLoose : privateNameHandlerSpec;
(0, _helperMemberExpressionToFunctions.default)(body, privateNameVisitor, Object.assign({
privateNamesMap,
classRef: ref,
file: state
}, handler, {
noDocumentAll,
innerBinding
}));
body.traverse(privateInVisitor, {
privateNamesMap,
classRef: ref,
file: state,
privateFieldsAsProperties,
innerBinding
});
}
function buildPrivateFieldInitLoose(ref, prop, privateNamesMap) {
const {
id
} = privateNamesMap.get(prop.node.key.id.name);
const value = prop.node.value || prop.scope.buildUndefinedNode();
return inheritPropComments(_core.template.statement.ast`
Object.defineProperty(${ref}, ${_core.types.cloneNode(id)}, {
// configurable is false by default
// enumerable is false by default
writable: true,
value: ${value}
});
`, prop);
}
function buildPrivateInstanceFieldInitSpec(ref, prop, privateNamesMap, state) {
const {
id
} = privateNamesMap.get(prop.node.key.id.name);
const value = prop.node.value || prop.scope.buildUndefinedNode();
{
if (!state.availableHelper("classPrivateFieldInitSpec")) {
return inheritPropComments(_core.template.statement.ast`${_core.types.cloneNode(id)}.set(${ref}, {
// configurable is always false for private elements
// enumerable is always false for private elements
writable: true,
value: ${value},
})`, prop);
}
}
const helper = state.addHelper("classPrivateFieldInitSpec");
return inheritPropComments(_core.template.statement.ast`${helper}(
${_core.types.thisExpression()},
${_core.types.cloneNode(id)},
{
writable: true,
value: ${value}
},
)`, prop);
}
function buildPrivateStaticFieldInitSpec(prop, privateNamesMap) {
const privateName = privateNamesMap.get(prop.node.key.id.name);
const {
id,
getId,
setId,
initAdded
} = privateName;
const isAccessor = getId || setId;
if (!prop.isProperty() && (initAdded || !isAccessor)) return;
if (isAccessor) {
privateNamesMap.set(prop.node.key.id.name, Object.assign({}, privateName, {
initAdded: true
}));
return inheritPropComments(_core.template.statement.ast`
var ${_core.types.cloneNode(id)} = {
// configurable is false by default
// enumerable is false by default
// writable is false by default
get: ${getId ? getId.name : prop.scope.buildUndefinedNode()},
set: ${setId ? setId.name : prop.scope.buildUndefinedNode()}
}
`, prop);
}
const value = prop.node.value || prop.scope.buildUndefinedNode();
return inheritPropComments(_core.template.statement.ast`
var ${_core.types.cloneNode(id)} = {
// configurable is false by default
// enumerable is false by default
writable: true,
value: ${value}
};
`, prop);
}
function buildPrivateMethodInitLoose(ref, prop, privateNamesMap) {
const privateName = privateNamesMap.get(prop.node.key.id.name);
const {
methodId,
id,
getId,
setId,
initAdded
} = privateName;
if (initAdded) return;
if (methodId) {
return inheritPropComments(_core.template.statement.ast`
Object.defineProperty(${ref}, ${id}, {
// configurable is false by default
// enumerable is false by default
// writable is false by default
value: ${methodId.name}
});
`, prop);
}
const isAccessor = getId || setId;
if (isAccessor) {
privateNamesMap.set(prop.node.key.id.name, Object.assign({}, privateName, {
initAdded: true
}));
return inheritPropComments(_core.template.statement.ast`
Object.defineProperty(${ref}, ${id}, {
// configurable is false by default
// enumerable is false by default
// writable is false by default
get: ${getId ? getId.name : prop.scope.buildUndefinedNode()},
set: ${setId ? setId.name : prop.scope.buildUndefinedNode()}
});
`, prop);
}
}
function buildPrivateInstanceMethodInitSpec(ref, prop, privateNamesMap, state) {
const privateName = privateNamesMap.get(prop.node.key.id.name);
const {
getId,
setId,
initAdded
} = privateName;
if (initAdded) return;
const isAccessor = getId || setId;
if (isAccessor) {
return buildPrivateAccessorInitialization(ref, prop, privateNamesMap, state);
}
return buildPrivateInstanceMethodInitialization(ref, prop, privateNamesMap, state);
}
function buildPrivateAccessorInitialization(ref, prop, privateNamesMap, state) {
const privateName = privateNamesMap.get(prop.node.key.id.name);
const {
id,
getId,
setId
} = privateName;
privateNamesMap.set(prop.node.key.id.name, Object.assign({}, privateName, {
initAdded: true
}));
{
if (!state.availableHelper("classPrivateFieldInitSpec")) {
return inheritPropComments(_core.template.statement.ast`
${id}.set(${ref}, {
get: ${getId ? getId.name : prop.scope.buildUndefinedNode()},
set: ${setId ? setId.name : prop.scope.buildUndefinedNode()}
});
`, prop);
}
}
const helper = state.addHelper("classPrivateFieldInitSpec");
return inheritPropComments(_core.template.statement.ast`${helper}(
${_core.types.thisExpression()},
${_core.types.cloneNode(id)},
{
get: ${getId ? getId.name : prop.scope.buildUndefinedNode()},
set: ${setId ? setId.name : prop.scope.buildUndefinedNode()}
},
)`, prop);
}
function buildPrivateInstanceMethodInitialization(ref, prop, privateNamesMap, state) {
const privateName = privateNamesMap.get(prop.node.key.id.name);
const {
id
} = privateName;
{
if (!state.availableHelper("classPrivateMethodInitSpec")) {
return inheritPropComments(_core.template.statement.ast`${id}.add(${ref})`, prop);
}
}
const helper = state.addHelper("classPrivateMethodInitSpec");
return inheritPropComments(_core.template.statement.ast`${helper}(
${_core.types.thisExpression()},
${_core.types.cloneNode(id)}
)`, prop);
}
function buildPublicFieldInitLoose(ref, prop) {
const {
key,
computed
} = prop.node;
const value = prop.node.value || prop.scope.buildUndefinedNode();
return inheritPropComments(_core.types.expressionStatement(_core.types.assignmentExpression("=", _core.types.memberExpression(ref, key, computed || _core.types.isLiteral(key)), value)), prop);
}
function buildPublicFieldInitSpec(ref, prop, state) {
const {
key,
computed
} = prop.node;
const value = prop.node.value || prop.scope.buildUndefinedNode();
return inheritPropComments(_core.types.expressionStatement(_core.types.callExpression(state.addHelper("defineProperty"), [ref, computed || _core.types.isLiteral(key) ? key : _core.types.stringLiteral(key.name), value])), prop);
}
function buildPrivateStaticMethodInitLoose(ref, prop, state, privateNamesMap) {
const privateName = privateNamesMap.get(prop.node.key.id.name);
const {
id,
methodId,
getId,
setId,
initAdded
} = privateName;
if (initAdded) return;
const isAccessor = getId || setId;
if (isAccessor) {
privateNamesMap.set(prop.node.key.id.name, Object.assign({}, privateName, {
initAdded: true
}));
return inheritPropComments(_core.template.statement.ast`
Object.defineProperty(${ref}, ${id}, {
// configurable is false by default
// enumerable is false by default
// writable is false by default
get: ${getId ? getId.name : prop.scope.buildUndefinedNode()},
set: ${setId ? setId.name : prop.scope.buildUndefinedNode()}
})
`, prop);
}
return inheritPropComments(_core.template.statement.ast`
Object.defineProperty(${ref}, ${id}, {
// configurable is false by default
// enumerable is false by default
// writable is false by default
value: ${methodId.name}
});
`, prop);
}
function buildPrivateMethodDeclaration(prop, privateNamesMap, privateFieldsAsProperties = false) {
const privateName = privateNamesMap.get(prop.node.key.id.name);
const {
id,
methodId,
getId,
setId,
getterDeclared,
setterDeclared,
static: isStatic
} = privateName;
const {
params,
body,
generator,
async
} = prop.node;
const isGetter = getId && !getterDeclared && params.length === 0;
const isSetter = setId && !setterDeclared && params.length > 0;
let declId = methodId;
if (isGetter) {
privateNamesMap.set(prop.node.key.id.name, Object.assign({}, privateName, {
getterDeclared: true
}));
declId = getId;
} else if (isSetter) {
privateNamesMap.set(prop.node.key.id.name, Object.assign({}, privateName, {
setterDeclared: true
}));
declId = setId;
} else if (isStatic && !privateFieldsAsProperties) {
declId = id;
}
return inheritPropComments(_core.types.functionDeclaration(_core.types.cloneNode(declId), params, body, generator, async), prop);
}
const thisContextVisitor = _core.traverse.visitors.merge([{
UnaryExpression(path) {
const {
node
} = path;
if (node.operator === "delete") {
const argument = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrapperNodes)(node.argument);
if (_core.types.isThisExpression(argument)) {
path.replaceWith(_core.types.booleanLiteral(true));
}
}
},
ThisExpression(path, state) {
state.needsClassRef = true;
path.replaceWith(_core.types.cloneNode(state.classRef));
},
MetaProperty(path) {
const {
node,
scope
} = path;
if (node.meta.name === "new" && node.property.name === "target") {
path.replaceWith(scope.buildUndefinedNode());
}
}
}, _helperEnvironmentVisitor.default]);
const innerReferencesVisitor = {
ReferencedIdentifier(path, state) {
if (path.scope.bindingIdentifierEquals(path.node.name, state.innerBinding)) {
state.needsClassRef = true;
path.node.name = state.classRef.name;
}
}
};
function replaceThisContext(path, ref, innerBindingRef) {
var _state$classRef;
const state = {
classRef: ref,
needsClassRef: false,
innerBinding: innerBindingRef
};
if (!path.isMethod()) {
path.traverse(thisContextVisitor, state);
}
if (innerBindingRef != null && (_state$classRef = state.classRef) != null && _state$classRef.name && state.classRef.name !== innerBindingRef.name) {
path.traverse(innerReferencesVisitor, state);
}
return state.needsClassRef;
}
function isNameOrLength({
key,
computed
}) {
if (key.type === "Identifier") {
return !computed && (key.name === "name" || key.name === "length");
}
if (key.type === "StringLiteral") {
return key.value === "name" || key.value === "length";
}
return false;
}
function inheritPropComments(node, prop) {
_core.types.inheritLeadingComments(node, prop.node);
_core.types.inheritInnerComments(node, prop.node);
return node;
}
function buildFieldsInitNodes(ref, superRef, props, privateNamesMap, file, setPublicClassFields, privateFieldsAsProperties, constantSuper, innerBindingRef) {
var _ref, _ref2;
let classRefFlags = 0;
let injectSuperRef;
const staticNodes = [];
const instanceNodes = [];
let lastInstanceNodeReturnsThis = false;
const pureStaticNodes = [];
let classBindingNode = null;
const getSuperRef = _core.types.isIdentifier(superRef) ? () => superRef : () => {
var _injectSuperRef;
(_injectSuperRef = injectSuperRef) != null ? _injectSuperRef : injectSuperRef = props[0].scope.generateUidIdentifierBasedOnNode(superRef);
return injectSuperRef;
};
const classRefForInnerBinding = (_ref = ref) != null ? _ref : props[0].scope.generateUidIdentifier((innerBindingRef == null ? void 0 : innerBindingRef.name) || "Class");
(_ref2 = ref) != null ? _ref2 : ref = _core.types.cloneNode(innerBindingRef);
for (const prop of props) {
prop.isClassProperty() && ts.assertFieldTransformed(prop);
const isStatic = !(_core.types.isStaticBlock != null && _core.types.isStaticBlock(prop.node)) && prop.node.static;
const isInstance = !isStatic;
const isPrivate = prop.isPrivate();
const isPublic = !isPrivate;
const isField = prop.isProperty();
const isMethod = !isField;
const isStaticBlock = prop.isStaticBlock == null ? void 0 : prop.isStaticBlock();
if (isStatic) classRefFlags |= 1;
if (isStatic || isMethod && isPrivate || isStaticBlock) {
new _helperReplaceSupers.default({
methodPath: prop,
constantSuper,
file: file,
refToPreserve: innerBindingRef,
getSuperRef,
getObjectRef() {
classRefFlags |= 2;
if (isStatic || isStaticBlock) {
return classRefForInnerBinding;
} else {
return _core.types.memberExpression(classRefForInnerBinding, _core.types.identifier("prototype"));
}
}
}).replace();
const replaced = replaceThisContext(prop, classRefForInnerBinding, innerBindingRef);
if (replaced) {
classRefFlags |= 2;
}
}
lastInstanceNodeReturnsThis = false;
switch (true) {
case isStaticBlock:
{
const blockBody = prop.node.body;
if (blockBody.length === 1 && _core.types.isExpressionStatement(blockBody[0])) {
staticNodes.push(inheritPropComments(blockBody[0], prop));
} else {
staticNodes.push(_core.types.inheritsComments(_core.template.statement.ast`(() => { ${blockBody} })()`, prop.node));
}
break;
}
case isStatic && isPrivate && isField && privateFieldsAsProperties:
staticNodes.push(buildPrivateFieldInitLoose(_core.types.cloneNode(ref), prop, privateNamesMap));
break;
case isStatic && isPrivate && isField && !privateFieldsAsProperties:
staticNodes.push(buildPrivateStaticFieldInitSpec(prop, privateNamesMap));
break;
case isStatic && isPublic && isField && setPublicClassFields:
if (!isNameOrLength(prop.node)) {
staticNodes.push(buildPublicFieldInitLoose(_core.types.cloneNode(ref), prop));
break;
}
case isStatic && isPublic && isField && !setPublicClassFields:
staticNodes.push(buildPublicFieldInitSpec(_core.types.cloneNode(ref), prop, file));
break;
case isInstance && isPrivate && isField && privateFieldsAsProperties:
instanceNodes.push(buildPrivateFieldInitLoose(_core.types.thisExpression(), prop, privateNamesMap));
break;
case isInstance && isPrivate && isField && !privateFieldsAsProperties:
instanceNodes.push(buildPrivateInstanceFieldInitSpec(_core.types.thisExpression(), prop, privateNamesMap, file));
break;
case isInstance && isPrivate && isMethod && privateFieldsAsProperties:
instanceNodes.unshift(buildPrivateMethodInitLoose(_core.types.thisExpression(), prop, privateNamesMap));
pureStaticNodes.push(buildPrivateMethodDeclaration(prop, privateNamesMap, privateFieldsAsProperties));
break;
case isInstance && isPrivate && isMethod && !privateFieldsAsProperties:
instanceNodes.unshift(buildPrivateInstanceMethodInitSpec(_core.types.thisExpression(), prop, privateNamesMap, file));
pureStaticNodes.push(buildPrivateMethodDeclaration(prop, privateNamesMap, privateFieldsAsProperties));
break;
case isStatic && isPrivate && isMethod && !privateFieldsAsProperties:
staticNodes.unshift(buildPrivateStaticFieldInitSpec(prop, privateNamesMap));
pureStaticNodes.push(buildPrivateMethodDeclaration(prop, privateNamesMap, privateFieldsAsProperties));
break;
case isStatic && isPrivate && isMethod && privateFieldsAsProperties:
staticNodes.unshift(buildPrivateStaticMethodInitLoose(_core.types.cloneNode(ref), prop, file, privateNamesMap));
pureStaticNodes.push(buildPrivateMethodDeclaration(prop, privateNamesMap, privateFieldsAsProperties));
break;
case isInstance && isPublic && isField && setPublicClassFields:
instanceNodes.push(buildPublicFieldInitLoose(_core.types.thisExpression(), prop));
break;
case isInstance && isPublic && isField && !setPublicClassFields:
lastInstanceNodeReturnsThis = true;
instanceNodes.push(buildPublicFieldInitSpec(_core.types.thisExpression(), prop, file));
break;
default:
throw new Error("Unreachable.");
}
}
if (classRefFlags & 2 && innerBindingRef != null) {
classBindingNode = _core.types.expressionStatement(_core.types.assignmentExpression("=", _core.types.cloneNode(classRefForInnerBinding), _core.types.cloneNode(innerBindingRef)));
}
return {
staticNodes: staticNodes.filter(Boolean),
instanceNodes: instanceNodes.filter(Boolean),
lastInstanceNodeReturnsThis,
pureStaticNodes: pureStaticNodes.filter(Boolean),
classBindingNode,
wrapClass(path) {
for (const prop of props) {
prop.node.leadingComments = null;
prop.remove();
}
if (injectSuperRef) {
path.scope.push({
id: _core.types.cloneNode(injectSuperRef)
});
path.set("superClass", _core.types.assignmentExpression("=", injectSuperRef, path.node.superClass));
}
if (classRefFlags !== 0) {
if (path.isClassExpression()) {
path.scope.push({
id: ref
});
path.replaceWith(_core.types.assignmentExpression("=", _core.types.cloneNode(ref), path.node));
} else {
if (innerBindingRef == null) {
path.node.id = ref;
}
if (classBindingNode != null) {
path.scope.push({
id: classRefForInnerBinding
});
}
}
}
return path;
}
};
}
//# sourceMappingURL=fields.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,242 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "FEATURES", {
enumerable: true,
get: function () {
return _features.FEATURES;
}
});
Object.defineProperty(exports, "buildCheckInRHS", {
enumerable: true,
get: function () {
return _fields.buildCheckInRHS;
}
});
exports.createClassFeaturePlugin = createClassFeaturePlugin;
Object.defineProperty(exports, "enableFeature", {
enumerable: true,
get: function () {
return _features.enableFeature;
}
});
Object.defineProperty(exports, "injectInitialization", {
enumerable: true,
get: function () {
return _misc.injectInitialization;
}
});
var _core = require("@babel/core");
var _helperFunctionName = require("@babel/helper-function-name");
var _helperSplitExportDeclaration = require("@babel/helper-split-export-declaration");
var _decorators = require("./decorators.js");
var _semver = require("semver");
var _fields = require("./fields.js");
var _decorators2 = require("./decorators-2018-09.js");
var _misc = require("./misc.js");
var _features = require("./features.js");
var _typescript = require("./typescript.js");
const versionKey = "@babel/plugin-class-features/version";
function createClassFeaturePlugin({
name,
feature,
loose,
manipulateOptions,
api,
inherits,
decoratorVersion
}) {
if (feature & _features.FEATURES.decorators) {
{
if (decoratorVersion === "2021-12" || decoratorVersion === "2022-03" || decoratorVersion === "2023-01" || decoratorVersion === "2023-05") {
return (0, _decorators.default)(api, {
loose
}, decoratorVersion, inherits);
}
}
}
{
var _api;
(_api = api) != null ? _api : api = {
assumption: () => void 0
};
}
const setPublicClassFields = api.assumption("setPublicClassFields");
const privateFieldsAsSymbols = api.assumption("privateFieldsAsSymbols");
const privateFieldsAsProperties = api.assumption("privateFieldsAsProperties");
const constantSuper = api.assumption("constantSuper");
const noDocumentAll = api.assumption("noDocumentAll");
if (privateFieldsAsProperties && privateFieldsAsSymbols) {
throw new Error(`Cannot enable both the "privateFieldsAsProperties" and ` + `"privateFieldsAsSymbols" assumptions as the same time.`);
}
const privateFieldsAsSymbolsOrProperties = privateFieldsAsProperties || privateFieldsAsSymbols;
if (loose === true) {
const explicit = [];
if (setPublicClassFields !== undefined) {
explicit.push(`"setPublicClassFields"`);
}
if (privateFieldsAsProperties !== undefined) {
explicit.push(`"privateFieldsAsProperties"`);
}
if (privateFieldsAsSymbols !== undefined) {
explicit.push(`"privateFieldsAsSymbols"`);
}
if (explicit.length !== 0) {
console.warn(`[${name}]: You are using the "loose: true" option and you are` + ` explicitly setting a value for the ${explicit.join(" and ")}` + ` assumption${explicit.length > 1 ? "s" : ""}. The "loose" option` + ` can cause incompatibilities with the other class features` + ` plugins, so it's recommended that you replace it with the` + ` following top-level option:\n` + `\t"assumptions": {\n` + `\t\t"setPublicClassFields": true,\n` + `\t\t"privateFieldsAsSymbols": true\n` + `\t}`);
}
}
return {
name,
manipulateOptions,
inherits,
pre(file) {
(0, _features.enableFeature)(file, feature, loose);
{
if (typeof file.get(versionKey) === "number") {
file.set(versionKey, "7.23.10");
return;
}
}
if (!file.get(versionKey) || _semver.lt(file.get(versionKey), "7.23.10")) {
file.set(versionKey, "7.23.10");
}
},
visitor: {
Class(path, {
file
}) {
var _ref;
if (file.get(versionKey) !== "7.23.10") return;
if (!(0, _features.shouldTransform)(path, file)) return;
const pathIsClassDeclaration = path.isClassDeclaration();
if (pathIsClassDeclaration) (0, _typescript.assertFieldTransformed)(path);
const loose = (0, _features.isLoose)(file, feature);
let constructor;
const isDecorated = (0, _decorators2.hasDecorators)(path.node);
const props = [];
const elements = [];
const computedPaths = [];
const privateNames = new Set();
const body = path.get("body");
for (const path of body.get("body")) {
if ((path.isClassProperty() || path.isClassMethod()) && path.node.computed) {
computedPaths.push(path);
}
if (path.isPrivate()) {
const {
name
} = path.node.key.id;
const getName = `get ${name}`;
const setName = `set ${name}`;
if (path.isClassPrivateMethod()) {
if (path.node.kind === "get") {
if (privateNames.has(getName) || privateNames.has(name) && !privateNames.has(setName)) {
throw path.buildCodeFrameError("Duplicate private field");
}
privateNames.add(getName).add(name);
} else if (path.node.kind === "set") {
if (privateNames.has(setName) || privateNames.has(name) && !privateNames.has(getName)) {
throw path.buildCodeFrameError("Duplicate private field");
}
privateNames.add(setName).add(name);
}
} else {
if (privateNames.has(name) && !privateNames.has(getName) && !privateNames.has(setName) || privateNames.has(name) && (privateNames.has(getName) || privateNames.has(setName))) {
throw path.buildCodeFrameError("Duplicate private field");
}
privateNames.add(name);
}
}
if (path.isClassMethod({
kind: "constructor"
})) {
constructor = path;
} else {
elements.push(path);
if (path.isProperty() || path.isPrivate() || path.isStaticBlock != null && path.isStaticBlock()) {
props.push(path);
}
}
}
{
if (!props.length && !isDecorated) return;
}
const innerBinding = path.node.id;
let ref;
if (!innerBinding || !pathIsClassDeclaration) {
(0, _helperFunctionName.default)(path);
ref = path.scope.generateUidIdentifier((innerBinding == null ? void 0 : innerBinding.name) || "Class");
}
const classRefForDefine = (_ref = ref) != null ? _ref : _core.types.cloneNode(innerBinding);
const privateNamesMap = (0, _fields.buildPrivateNamesMap)(props);
const privateNamesNodes = (0, _fields.buildPrivateNamesNodes)(privateNamesMap, privateFieldsAsProperties != null ? privateFieldsAsProperties : loose, privateFieldsAsSymbols != null ? privateFieldsAsSymbols : false, file);
(0, _fields.transformPrivateNamesUsage)(classRefForDefine, path, privateNamesMap, {
privateFieldsAsProperties: privateFieldsAsSymbolsOrProperties != null ? privateFieldsAsSymbolsOrProperties : loose,
noDocumentAll,
innerBinding
}, file);
let keysNodes, staticNodes, instanceNodes, lastInstanceNodeReturnsThis, pureStaticNodes, classBindingNode, wrapClass;
{
if (isDecorated) {
staticNodes = pureStaticNodes = keysNodes = [];
({
instanceNodes,
wrapClass
} = (0, _decorators2.buildDecoratedClass)(classRefForDefine, path, elements, file));
} else {
keysNodes = (0, _misc.extractComputedKeys)(path, computedPaths, file);
({
staticNodes,
pureStaticNodes,
instanceNodes,
lastInstanceNodeReturnsThis,
classBindingNode,
wrapClass
} = (0, _fields.buildFieldsInitNodes)(ref, path.node.superClass, props, privateNamesMap, file, setPublicClassFields != null ? setPublicClassFields : loose, privateFieldsAsSymbolsOrProperties != null ? privateFieldsAsSymbolsOrProperties : loose, constantSuper != null ? constantSuper : loose, innerBinding));
}
}
if (instanceNodes.length > 0) {
(0, _misc.injectInitialization)(path, constructor, instanceNodes, (referenceVisitor, state) => {
{
if (isDecorated) return;
}
for (const prop of props) {
if (_core.types.isStaticBlock != null && _core.types.isStaticBlock(prop.node) || prop.node.static) continue;
prop.traverse(referenceVisitor, state);
}
}, lastInstanceNodeReturnsThis);
}
const wrappedPath = wrapClass(path);
wrappedPath.insertBefore([...privateNamesNodes, ...keysNodes]);
if (staticNodes.length > 0) {
wrappedPath.insertAfter(staticNodes);
}
if (pureStaticNodes.length > 0) {
wrappedPath.find(parent => parent.isStatement() || parent.isDeclaration()).insertAfter(pureStaticNodes);
}
if (classBindingNode != null && pathIsClassDeclaration) {
wrappedPath.insertAfter(classBindingNode);
}
},
ExportDefaultDeclaration(path, {
file
}) {
{
if (file.get(versionKey) !== "7.23.10") return;
const decl = path.get("declaration");
if (decl.isClassDeclaration() && (0, _decorators2.hasDecorators)(decl.node)) {
if (decl.node.id) {
(0, _helperSplitExportDeclaration.default)(path);
} else {
decl.node.type = "ClassExpression";
}
}
}
}
}
};
}
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,124 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.extractComputedKeys = extractComputedKeys;
exports.injectInitialization = injectInitialization;
var _core = require("@babel/core");
var _helperEnvironmentVisitor = require("@babel/helper-environment-visitor");
const findBareSupers = _core.traverse.visitors.merge([{
Super(path) {
const {
node,
parentPath
} = path;
if (parentPath.isCallExpression({
callee: node
})) {
this.push(parentPath);
}
}
}, _helperEnvironmentVisitor.default]);
const referenceVisitor = {
"TSTypeAnnotation|TypeAnnotation"(path) {
path.skip();
},
ReferencedIdentifier(path, {
scope
}) {
if (scope.hasOwnBinding(path.node.name)) {
scope.rename(path.node.name);
path.skip();
}
}
};
function handleClassTDZ(path, state) {
if (state.classBinding && state.classBinding === path.scope.getBinding(path.node.name)) {
const classNameTDZError = state.file.addHelper("classNameTDZError");
const throwNode = _core.types.callExpression(classNameTDZError, [_core.types.stringLiteral(path.node.name)]);
path.replaceWith(_core.types.sequenceExpression([throwNode, path.node]));
path.skip();
}
}
const classFieldDefinitionEvaluationTDZVisitor = {
ReferencedIdentifier: handleClassTDZ
};
function injectInitialization(path, constructor, nodes, renamer, lastReturnsThis) {
if (!nodes.length) return;
const isDerived = !!path.node.superClass;
if (!constructor) {
const newConstructor = _core.types.classMethod("constructor", _core.types.identifier("constructor"), [], _core.types.blockStatement([]));
if (isDerived) {
newConstructor.params = [_core.types.restElement(_core.types.identifier("args"))];
newConstructor.body.body.push(_core.template.statement.ast`super(...args)`);
}
[constructor] = path.get("body").unshiftContainer("body", newConstructor);
}
if (renamer) {
renamer(referenceVisitor, {
scope: constructor.scope
});
}
if (isDerived) {
const bareSupers = [];
constructor.traverse(findBareSupers, bareSupers);
let isFirst = true;
for (const bareSuper of bareSupers) {
if (isFirst) {
isFirst = false;
} else {
nodes = nodes.map(n => _core.types.cloneNode(n));
}
if (!bareSuper.parentPath.isExpressionStatement()) {
const allNodes = [bareSuper.node, ...nodes.map(n => _core.types.toExpression(n))];
if (!lastReturnsThis) allNodes.push(_core.types.thisExpression());
bareSuper.replaceWith(_core.types.sequenceExpression(allNodes));
} else {
bareSuper.insertAfter(nodes);
}
}
} else {
constructor.get("body").unshiftContainer("body", nodes);
}
}
function extractComputedKeys(path, computedPaths, file) {
const declarations = [];
const state = {
classBinding: path.node.id && path.scope.getBinding(path.node.id.name),
file
};
for (const computedPath of computedPaths) {
const computedKey = computedPath.get("key");
if (computedKey.isReferencedIdentifier()) {
handleClassTDZ(computedKey, state);
} else {
computedKey.traverse(classFieldDefinitionEvaluationTDZVisitor, state);
}
const computedNode = computedPath.node;
if (!computedKey.isConstantExpression()) {
const scope = path.scope;
const isUidReference = _core.types.isIdentifier(computedKey.node) && scope.hasUid(computedKey.node.name);
const isMemoiseAssignment = computedKey.isAssignmentExpression({
operator: "="
}) && _core.types.isIdentifier(computedKey.node.left) && scope.hasUid(computedKey.node.left.name);
if (isUidReference) {
continue;
} else if (isMemoiseAssignment) {
declarations.push(_core.types.expressionStatement(_core.types.cloneNode(computedNode.key)));
computedNode.key = _core.types.cloneNode(computedNode.key.left);
} else {
const ident = path.scope.generateUidIdentifierBasedOnNode(computedNode.key);
scope.push({
id: ident,
kind: "let"
});
declarations.push(_core.types.expressionStatement(_core.types.assignmentExpression("=", _core.types.cloneNode(ident), computedNode.key)));
computedNode.key = _core.types.cloneNode(ident);
}
}
}
return declarations;
}
//# sourceMappingURL=misc.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.assertFieldTransformed = assertFieldTransformed;
function assertFieldTransformed(path) {
if (path.node.declare || false) {
throw path.buildCodeFrameError(`TypeScript 'declare' fields must first be transformed by ` + `@babel/plugin-transform-typescript.\n` + `If you have already enabled that plugin (or '@babel/preset-typescript'), make sure ` + `that it runs before any plugin related to additional class features:\n` + ` - @babel/plugin-transform-class-properties\n` + ` - @babel/plugin-transform-private-methods\n` + ` - @babel/plugin-proposal-decorators`);
}
}
//# sourceMappingURL=typescript.js.map

View file

@ -0,0 +1 @@
{"version":3,"names":["assertFieldTransformed","path","node","declare","buildCodeFrameError"],"sources":["../src/typescript.ts"],"sourcesContent":["import type { NodePath } from \"@babel/traverse\";\nimport type * as t from \"@babel/types\";\n\nexport function assertFieldTransformed(\n path: NodePath<t.ClassProperty | t.ClassDeclaration>,\n) {\n if (\n path.node.declare ||\n (process.env.BABEL_8_BREAKING\n ? path.isClassProperty({ definite: true })\n : false)\n ) {\n throw path.buildCodeFrameError(\n `TypeScript 'declare' fields must first be transformed by ` +\n `@babel/plugin-transform-typescript.\\n` +\n `If you have already enabled that plugin (or '@babel/preset-typescript'), make sure ` +\n `that it runs before any plugin related to additional class features:\\n` +\n ` - @babel/plugin-transform-class-properties\\n` +\n ` - @babel/plugin-transform-private-methods\\n` +\n ` - @babel/plugin-proposal-decorators`,\n );\n }\n}\n"],"mappings":";;;;;;AAGO,SAASA,sBAAsBA,CACpCC,IAAoD,EACpD;EACA,IACEA,IAAI,CAACC,IAAI,CAACC,OAAO,IAGb,KAAM,EACV;IACA,MAAMF,IAAI,CAACG,mBAAmB,CAC3B,2DAA0D,GACxD,uCAAsC,GACtC,qFAAoF,GACpF,wEAAuE,GACvE,+CAA8C,GAC9C,8CAA6C,GAC7C,sCACL,CAAC;EACH;AACF"}

View file

@ -0,0 +1 @@
../semver/bin/semver.js

View file

@ -0,0 +1,15 @@
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

View file

@ -0,0 +1,443 @@
semver(1) -- The semantic versioner for npm
===========================================
## Install
```bash
npm install semver
````
## Usage
As a node module:
```js
const semver = require('semver')
semver.valid('1.2.3') // '1.2.3'
semver.valid('a.b.c') // null
semver.clean(' =v1.2.3 ') // '1.2.3'
semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true
semver.gt('1.2.3', '9.8.7') // false
semver.lt('1.2.3', '9.8.7') // true
semver.minVersion('>=1.0.0') // '1.0.0'
semver.valid(semver.coerce('v2')) // '2.0.0'
semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7'
```
As a command-line utility:
```
$ semver -h
A JavaScript implementation of the https://semver.org/ specification
Copyright Isaac Z. Schlueter
Usage: semver [options] <version> [<version> [...]]
Prints valid versions sorted by SemVer precedence
Options:
-r --range <range>
Print versions that match the specified range.
-i --increment [<level>]
Increment a version by the specified level. Level can
be one of: major, minor, patch, premajor, preminor,
prepatch, or prerelease. Default level is 'patch'.
Only one version may be specified.
--preid <identifier>
Identifier to be used to prefix premajor, preminor,
prepatch or prerelease version increments.
-l --loose
Interpret versions and ranges loosely
-p --include-prerelease
Always include prerelease versions in range matching
-c --coerce
Coerce a string into SemVer if possible
(does not imply --loose)
--rtl
Coerce version strings right to left
--ltr
Coerce version strings left to right (default)
Program exits successfully if any valid version satisfies
all supplied ranges, and prints all satisfying versions.
If no satisfying versions are found, then exits failure.
Versions are printed in ascending order, so supplying
multiple versions to the utility will just sort them.
```
## Versions
A "version" is described by the `v2.0.0` specification found at
<https://semver.org/>.
A leading `"="` or `"v"` character is stripped off and ignored.
## Ranges
A `version range` is a set of `comparators` which specify versions
that satisfy the range.
A `comparator` is composed of an `operator` and a `version`. The set
of primitive `operators` is:
* `<` Less than
* `<=` Less than or equal to
* `>` Greater than
* `>=` Greater than or equal to
* `=` Equal. If no operator is specified, then equality is assumed,
so this operator is optional, but MAY be included.
For example, the comparator `>=1.2.7` would match the versions
`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6`
or `1.1.0`.
Comparators can be joined by whitespace to form a `comparator set`,
which is satisfied by the **intersection** of all of the comparators
it includes.
A range is composed of one or more comparator sets, joined by `||`. A
version matches a range if and only if every comparator in at least
one of the `||`-separated comparator sets is satisfied by the version.
For example, the range `>=1.2.7 <1.3.0` would match the versions
`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`,
or `1.1.0`.
The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`,
`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`.
### Prerelease Tags
If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then
it will only be allowed to satisfy comparator sets if at least one
comparator with the same `[major, minor, patch]` tuple also has a
prerelease tag.
For example, the range `>1.2.3-alpha.3` would be allowed to match the
version `1.2.3-alpha.7`, but it would *not* be satisfied by
`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater
than" `1.2.3-alpha.3` according to the SemVer sort rules. The version
range only accepts prerelease tags on the `1.2.3` version. The
version `3.4.5` *would* satisfy the range, because it does not have a
prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`.
The purpose for this behavior is twofold. First, prerelease versions
frequently are updated very quickly, and contain many breaking changes
that are (by the author's design) not yet fit for public consumption.
Therefore, by default, they are excluded from range matching
semantics.
Second, a user who has opted into using a prerelease version has
clearly indicated the intent to use *that specific* set of
alpha/beta/rc versions. By including a prerelease tag in the range,
the user is indicating that they are aware of the risk. However, it
is still not appropriate to assume that they have opted into taking a
similar risk on the *next* set of prerelease versions.
Note that this behavior can be suppressed (treating all prerelease
versions as if they were normal versions, for the purpose of range
matching) by setting the `includePrerelease` flag on the options
object to any
[functions](https://github.com/npm/node-semver#functions) that do
range matching.
#### Prerelease Identifiers
The method `.inc` takes an additional `identifier` string argument that
will append the value of the string as a prerelease identifier:
```javascript
semver.inc('1.2.3', 'prerelease', 'beta')
// '1.2.4-beta.0'
```
command-line example:
```bash
$ semver 1.2.3 -i prerelease --preid beta
1.2.4-beta.0
```
Which then can be used to increment further:
```bash
$ semver 1.2.4-beta.0 -i prerelease
1.2.4-beta.1
```
### Advanced Range Syntax
Advanced range syntax desugars to primitive comparators in
deterministic ways.
Advanced ranges may be combined in the same way as primitive
comparators using white space or `||`.
#### Hyphen Ranges `X.Y.Z - A.B.C`
Specifies an inclusive set.
* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4`
If a partial version is provided as the first version in the inclusive
range, then the missing pieces are replaced with zeroes.
* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4`
If a partial version is provided as the second version in the
inclusive range, then all versions that start with the supplied parts
of the tuple are accepted, but nothing that would be greater than the
provided tuple parts.
* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0`
* `1.2.3 - 2` := `>=1.2.3 <3.0.0`
#### X-Ranges `1.2.x` `1.X` `1.2.*` `*`
Any of `X`, `x`, or `*` may be used to "stand in" for one of the
numeric values in the `[major, minor, patch]` tuple.
* `*` := `>=0.0.0` (Any version satisfies)
* `1.x` := `>=1.0.0 <2.0.0` (Matching major version)
* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions)
A partial version range is treated as an X-Range, so the special
character is in fact optional.
* `""` (empty string) := `*` := `>=0.0.0`
* `1` := `1.x.x` := `>=1.0.0 <2.0.0`
* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0`
#### Tilde Ranges `~1.2.3` `~1.2` `~1`
Allows patch-level changes if a minor version is specified on the
comparator. Allows minor-level changes if not.
* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0`
* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`)
* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`)
* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0`
* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`)
* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`)
* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in
the `1.2.3` version will be allowed, if they are greater than or
equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but
`1.2.4-beta.2` would not, because it is a prerelease of a
different `[major, minor, patch]` tuple.
#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4`
Allows changes that do not modify the left-most non-zero element in the
`[major, minor, patch]` tuple. In other words, this allows patch and
minor updates for versions `1.0.0` and above, patch updates for
versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`.
Many authors treat a `0.x` version as if the `x` were the major
"breaking-change" indicator.
Caret ranges are ideal when an author may make breaking changes
between `0.2.4` and `0.3.0` releases, which is a common practice.
However, it presumes that there will *not* be breaking changes between
`0.2.4` and `0.2.5`. It allows for changes that are presumed to be
additive (but non-breaking), according to commonly observed practices.
* `^1.2.3` := `>=1.2.3 <2.0.0`
* `^0.2.3` := `>=0.2.3 <0.3.0`
* `^0.0.3` := `>=0.0.3 <0.0.4`
* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in
the `1.2.3` version will be allowed, if they are greater than or
equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but
`1.2.4-beta.2` would not, because it is a prerelease of a
different `[major, minor, patch]` tuple.
* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the
`0.0.3` version *only* will be allowed, if they are greater than or
equal to `beta`. So, `0.0.3-pr.2` would be allowed.
When parsing caret ranges, a missing `patch` value desugars to the
number `0`, but will allow flexibility within that value, even if the
major and minor versions are both `0`.
* `^1.2.x` := `>=1.2.0 <2.0.0`
* `^0.0.x` := `>=0.0.0 <0.1.0`
* `^0.0` := `>=0.0.0 <0.1.0`
A missing `minor` and `patch` values will desugar to zero, but also
allow flexibility within those values, even if the major version is
zero.
* `^1.x` := `>=1.0.0 <2.0.0`
* `^0.x` := `>=0.0.0 <1.0.0`
### Range Grammar
Putting all this together, here is a Backus-Naur grammar for ranges,
for the benefit of parser authors:
```bnf
range-set ::= range ( logical-or range ) *
logical-or ::= ( ' ' ) * '||' ( ' ' ) *
range ::= hyphen | simple ( ' ' simple ) * | ''
hyphen ::= partial ' - ' partial
simple ::= primitive | partial | tilde | caret
primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
xr ::= 'x' | 'X' | '*' | nr
nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) *
tilde ::= '~' partial
caret ::= '^' partial
qualifier ::= ( '-' pre )? ( '+' build )?
pre ::= parts
build ::= parts
parts ::= part ( '.' part ) *
part ::= nr | [-0-9A-Za-z]+
```
## Functions
All methods and classes take a final `options` object argument. All
options in this object are `false` by default. The options supported
are:
- `loose` Be more forgiving about not-quite-valid semver strings.
(Any resulting output will always be 100% strict compliant, of
course.) For backwards compatibility reasons, if the `options`
argument is a boolean value instead of an object, it is interpreted
to be the `loose` param.
- `includePrerelease` Set to suppress the [default
behavior](https://github.com/npm/node-semver#prerelease-tags) of
excluding prerelease tagged versions from ranges unless they are
explicitly opted into.
Strict-mode Comparators and Ranges will be strict about the SemVer
strings that they parse.
* `valid(v)`: Return the parsed version, or null if it's not valid.
* `inc(v, release)`: Return the version incremented by the release
type (`major`, `premajor`, `minor`, `preminor`, `patch`,
`prepatch`, or `prerelease`), or null if it's not valid
* `premajor` in one call will bump the version up to the next major
version and down to a prerelease of that major version.
`preminor`, and `prepatch` work the same way.
* If called from a non-prerelease version, the `prerelease` will work the
same as `prepatch`. It increments the patch version, then makes a
prerelease. If the input version is already a prerelease it simply
increments it.
* `prerelease(v)`: Returns an array of prerelease components, or null
if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]`
* `major(v)`: Return the major version number.
* `minor(v)`: Return the minor version number.
* `patch(v)`: Return the patch version number.
* `intersects(r1, r2, loose)`: Return true if the two supplied ranges
or comparators intersect.
* `parse(v)`: Attempt to parse a string as a semantic version, returning either
a `SemVer` object or `null`.
### Comparison
* `gt(v1, v2)`: `v1 > v2`
* `gte(v1, v2)`: `v1 >= v2`
* `lt(v1, v2)`: `v1 < v2`
* `lte(v1, v2)`: `v1 <= v2`
* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent,
even if they're not the exact same string. You already know how to
compare strings.
* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`.
* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call
the corresponding function above. `"==="` and `"!=="` do simple
string comparison, but are included for completeness. Throws if an
invalid comparison string is provided.
* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if
`v2` is greater. Sorts in ascending order if passed to `Array.sort()`.
* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions
in descending order when passed to `Array.sort()`.
* `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions
are equal. Sorts in ascending order if passed to `Array.sort()`.
`v2` is greater. Sorts in ascending order if passed to `Array.sort()`.
* `diff(v1, v2)`: Returns difference between two versions by the release type
(`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`),
or null if the versions are the same.
### Comparators
* `intersects(comparator)`: Return true if the comparators intersect
### Ranges
* `validRange(range)`: Return the valid range or null if it's not valid
* `satisfies(version, range)`: Return true if the version satisfies the
range.
* `maxSatisfying(versions, range)`: Return the highest version in the list
that satisfies the range, or `null` if none of them do.
* `minSatisfying(versions, range)`: Return the lowest version in the list
that satisfies the range, or `null` if none of them do.
* `minVersion(range)`: Return the lowest version that can possibly match
the given range.
* `gtr(version, range)`: Return `true` if version is greater than all the
versions possible in the range.
* `ltr(version, range)`: Return `true` if version is less than all the
versions possible in the range.
* `outside(version, range, hilo)`: Return true if the version is outside
the bounds of the range in either the high or low direction. The
`hilo` argument must be either the string `'>'` or `'<'`. (This is
the function called by `gtr` and `ltr`.)
* `intersects(range)`: Return true if any of the ranges comparators intersect
Note that, since ranges may be non-contiguous, a version might not be
greater than a range, less than a range, *or* satisfy a range! For
example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9`
until `2.0.0`, so the version `1.2.10` would not be greater than the
range (because `2.0.1` satisfies, which is higher), nor less than the
range (since `1.2.8` satisfies, which is lower), and it also does not
satisfy the range.
If you want to know if a version satisfies or does not satisfy a
range, use the `satisfies(version, range)` function.
### Coercion
* `coerce(version, options)`: Coerces a string to semver if possible
This aims to provide a very forgiving translation of a non-semver string to
semver. It looks for the first digit in a string, and consumes all
remaining characters which satisfy at least a partial semver (e.g., `1`,
`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer
versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All
surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes
`3.4.0`). Only text which lacks digits will fail coercion (`version one`
is not valid). The maximum length for any semver component considered for
coercion is 16 characters; longer components will be ignored
(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any
semver component is `Integer.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value
components are invalid (`9999999999999999.4.7.4` is likely invalid).
If the `options.rtl` flag is set, then `coerce` will return the right-most
coercible tuple that does not share an ending index with a longer coercible
tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not
`4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of
any other overlapping SemVer tuple.
### Clean
* `clean(version)`: Clean a string to be a valid semver if possible
This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges.
ex.
* `s.clean(' = v 2.1.5foo')`: `null`
* `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'`
* `s.clean(' = v 2.1.5-foo')`: `null`
* `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'`
* `s.clean('=v2.1.5')`: `'2.1.5'`
* `s.clean(' =v2.1.5')`: `2.1.5`
* `s.clean(' 2.1.5 ')`: `'2.1.5'`
* `s.clean('~1.0.0')`: `null`

View file

@ -0,0 +1,174 @@
#!/usr/bin/env node
// Standalone semver comparison program.
// Exits successfully and prints matching version(s) if
// any supplied version is valid and passes all tests.
var argv = process.argv.slice(2)
var versions = []
var range = []
var inc = null
var version = require('../package.json').version
var loose = false
var includePrerelease = false
var coerce = false
var rtl = false
var identifier
var semver = require('../semver')
var reverse = false
var options = {}
main()
function main () {
if (!argv.length) return help()
while (argv.length) {
var a = argv.shift()
var indexOfEqualSign = a.indexOf('=')
if (indexOfEqualSign !== -1) {
a = a.slice(0, indexOfEqualSign)
argv.unshift(a.slice(indexOfEqualSign + 1))
}
switch (a) {
case '-rv': case '-rev': case '--rev': case '--reverse':
reverse = true
break
case '-l': case '--loose':
loose = true
break
case '-p': case '--include-prerelease':
includePrerelease = true
break
case '-v': case '--version':
versions.push(argv.shift())
break
case '-i': case '--inc': case '--increment':
switch (argv[0]) {
case 'major': case 'minor': case 'patch': case 'prerelease':
case 'premajor': case 'preminor': case 'prepatch':
inc = argv.shift()
break
default:
inc = 'patch'
break
}
break
case '--preid':
identifier = argv.shift()
break
case '-r': case '--range':
range.push(argv.shift())
break
case '-c': case '--coerce':
coerce = true
break
case '--rtl':
rtl = true
break
case '--ltr':
rtl = false
break
case '-h': case '--help': case '-?':
return help()
default:
versions.push(a)
break
}
}
var options = { loose: loose, includePrerelease: includePrerelease, rtl: rtl }
versions = versions.map(function (v) {
return coerce ? (semver.coerce(v, options) || { version: v }).version : v
}).filter(function (v) {
return semver.valid(v)
})
if (!versions.length) return fail()
if (inc && (versions.length !== 1 || range.length)) { return failInc() }
for (var i = 0, l = range.length; i < l; i++) {
versions = versions.filter(function (v) {
return semver.satisfies(v, range[i], options)
})
if (!versions.length) return fail()
}
return success(versions)
}
function failInc () {
console.error('--inc can only be used on a single version with no range')
fail()
}
function fail () { process.exit(1) }
function success () {
var compare = reverse ? 'rcompare' : 'compare'
versions.sort(function (a, b) {
return semver[compare](a, b, options)
}).map(function (v) {
return semver.clean(v, options)
}).map(function (v) {
return inc ? semver.inc(v, inc, options, identifier) : v
}).forEach(function (v, i, _) { console.log(v) })
}
function help () {
console.log(['SemVer ' + version,
'',
'A JavaScript implementation of the https://semver.org/ specification',
'Copyright Isaac Z. Schlueter',
'',
'Usage: semver [options] <version> [<version> [...]]',
'Prints valid versions sorted by SemVer precedence',
'',
'Options:',
'-r --range <range>',
' Print versions that match the specified range.',
'',
'-i --increment [<level>]',
' Increment a version by the specified level. Level can',
' be one of: major, minor, patch, premajor, preminor,',
" prepatch, or prerelease. Default level is 'patch'.",
' Only one version may be specified.',
'',
'--preid <identifier>',
' Identifier to be used to prefix premajor, preminor,',
' prepatch or prerelease version increments.',
'',
'-l --loose',
' Interpret versions and ranges loosely',
'',
'-p --include-prerelease',
' Always include prerelease versions in range matching',
'',
'-c --coerce',
' Coerce a string into SemVer if possible',
' (does not imply --loose)',
'',
'--rtl',
' Coerce version strings right to left',
'',
'--ltr',
' Coerce version strings left to right (default)',
'',
'Program exits successfully if any valid version satisfies',
'all supplied ranges, and prints all satisfying versions.',
'',
'If no satisfying versions are found, then exits failure.',
'',
'Versions are printed in ascending order, so supplying',
'multiple versions to the utility will just sort them.'
].join('\n'))
}

View file

@ -0,0 +1,38 @@
{
"name": "semver",
"version": "6.3.1",
"description": "The semantic version parser used by npm.",
"main": "semver.js",
"scripts": {
"test": "tap test/ --100 --timeout=30",
"lint": "echo linting disabled",
"postlint": "template-oss-check",
"template-oss-apply": "template-oss-apply --force",
"lintfix": "npm run lint -- --fix",
"snap": "tap test/ --100 --timeout=30",
"posttest": "npm run lint"
},
"devDependencies": {
"@npmcli/template-oss": "4.17.0",
"tap": "^12.7.0"
},
"license": "ISC",
"repository": {
"type": "git",
"url": "https://github.com/npm/node-semver.git"
},
"bin": {
"semver": "./bin/semver.js"
},
"files": [
"bin",
"range.bnf",
"semver.js"
],
"author": "GitHub Inc.",
"templateOSS": {
"//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
"content": "./scripts/template-oss",
"version": "4.17.0"
}
}

View file

@ -0,0 +1,16 @@
range-set ::= range ( logical-or range ) *
logical-or ::= ( ' ' ) * '||' ( ' ' ) *
range ::= hyphen | simple ( ' ' simple ) * | ''
hyphen ::= partial ' - ' partial
simple ::= primitive | partial | tilde | caret
primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
xr ::= 'x' | 'X' | '*' | nr
nr ::= '0' | [1-9] ( [0-9] ) *
tilde ::= '~' partial
caret ::= '^' partial
qualifier ::= ( '-' pre )? ( '+' build )?
pre ::= parts
build ::= parts
parts ::= part ( '.' part ) *
part ::= nr | [-0-9A-Za-z]+

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,45 @@
{
"name": "@babel/helper-create-class-features-plugin",
"version": "7.23.10",
"author": "The Babel Team (https://babel.dev/team)",
"license": "MIT",
"description": "Compile class public and private fields, private methods and decorators to ES6",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel.git",
"directory": "packages/babel-helper-create-class-features-plugin"
},
"main": "./lib/index.js",
"publishConfig": {
"access": "public"
},
"keywords": [
"babel",
"babel-plugin"
],
"dependencies": {
"@babel/helper-annotate-as-pure": "^7.22.5",
"@babel/helper-environment-visitor": "^7.22.20",
"@babel/helper-function-name": "^7.23.0",
"@babel/helper-member-expression-to-functions": "^7.23.0",
"@babel/helper-optimise-call-expression": "^7.22.5",
"@babel/helper-replace-supers": "^7.22.20",
"@babel/helper-skip-transparent-expression-wrappers": "^7.22.5",
"@babel/helper-split-export-declaration": "^7.22.6",
"semver": "^6.3.1"
},
"peerDependencies": {
"@babel/core": "^7.0.0"
},
"devDependencies": {
"@babel/core": "^7.23.9",
"@babel/helper-plugin-test-runner": "^7.22.5",
"@babel/preset-env": "^7.23.9",
"@types/charcodes": "^0.2.0",
"charcodes": "^0.2.0"
},
"engines": {
"node": ">=6.9.0"
},
"type": "commonjs"
}