magicast
Version:
Modify a JS/TS file and write back magically just like JSON!
1,401 lines • 344 kB
JavaScript
import * as babelParser from "@babel/parser";
//#region \0rolldown/runtime.js
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
//#endregion
//#region vendor/ast-types/src/shared.ts
function shared_default(fork) {
var types = fork.use(typesPlugin);
var Type = types.Type;
var builtin = types.builtInTypes;
var isNumber = builtin.number;
function geq(than) {
return Type.from((value) => isNumber.check(value) && value >= than, isNumber + " >= " + than);
}
const defaults = {
"null": function() {
return null;
},
"emptyArray": function() {
return [];
},
"false": function() {
return false;
},
"true": function() {
return true;
},
"undefined": function() {},
"use strict": function() {
return "use strict";
}
};
var naiveIsPrimitive = Type.or(builtin.string, builtin.number, builtin.boolean, builtin.null, builtin.undefined);
return {
geq,
defaults,
isPrimitive: Type.from((value) => {
if (value === null) return true;
var type = typeof value;
if (type === "object" || type === "function") return false;
return true;
}, naiveIsPrimitive.toString())
};
}
//#endregion
//#region vendor/ast-types/src/types.ts
const Op = Object.prototype;
const objToStr = Op.toString;
const hasOwn$6 = Op.hasOwnProperty;
var BaseType = class {
assert(value, deep) {
if (!this.check(value, deep)) {
var str = shallowStringify(value);
throw new Error(str + " does not match type " + this);
}
return true;
}
arrayOf() {
return new ArrayType(this);
}
};
var ArrayType = class extends BaseType {
elemType;
kind = "ArrayType";
constructor(elemType) {
super();
this.elemType = elemType;
}
toString() {
return "[" + this.elemType + "]";
}
check(value, deep) {
return Array.isArray(value) && value.every((elem) => this.elemType.check(elem, deep));
}
};
var IdentityType = class extends BaseType {
value;
kind = "IdentityType";
constructor(value) {
super();
this.value = value;
}
toString() {
return String(this.value);
}
check(value, deep) {
const result = value === this.value;
if (!result && typeof deep === "function") deep(this, value);
return result;
}
};
var ObjectType = class extends BaseType {
fields;
kind = "ObjectType";
constructor(fields) {
super();
this.fields = fields;
}
toString() {
return "{ " + this.fields.join(", ") + " }";
}
check(value, deep) {
return objToStr.call(value) === objToStr.call({}) && this.fields.every((field) => {
return field.type.check(value[field.name], deep);
});
}
};
var OrType = class extends BaseType {
types;
kind = "OrType";
constructor(types) {
super();
this.types = types;
}
toString() {
return this.types.join(" | ");
}
check(value, deep) {
if (this.types.some((type) => type.check(value, !!deep))) return true;
if (typeof deep === "function") deep(this, value);
return false;
}
};
var PredicateType = class extends BaseType {
name;
predicate;
kind = "PredicateType";
constructor(name, predicate) {
super();
this.name = name;
this.predicate = predicate;
}
toString() {
return this.name;
}
check(value, deep) {
const result = this.predicate(value, deep);
if (!result && typeof deep === "function") deep(this, value);
return result;
}
};
var Def = class Def {
type;
typeName;
baseNames = [];
ownFields = Object.create(null);
allSupertypes = Object.create(null);
supertypeList = [];
allFields = Object.create(null);
fieldNames = [];
finalized = false;
buildable = false;
buildParams = [];
constructor(type, typeName) {
this.type = type;
this.typeName = typeName;
}
isSupertypeOf(that) {
if (that instanceof Def) {
if (this.finalized !== true || that.finalized !== true) throw new Error("");
return hasOwn$6.call(that.allSupertypes, this.typeName);
} else throw new Error(that + " is not a Def");
}
checkAllFields(value, deep) {
var allFields = this.allFields;
if (this.finalized !== true) throw new Error("" + this.typeName);
function checkFieldByName(name) {
var field = allFields[name];
var type = field.type;
var child = field.getValue(value);
return type.check(child, deep);
}
return value !== null && typeof value === "object" && Object.keys(allFields).every(checkFieldByName);
}
bases(...supertypeNames) {
var bases = this.baseNames;
if (this.finalized) {
if (supertypeNames.length !== bases.length) throw new Error("");
for (var i = 0; i < supertypeNames.length; i++) if (supertypeNames[i] !== bases[i]) throw new Error("");
return this;
}
supertypeNames.forEach((baseName) => {
if (bases.indexOf(baseName) < 0) bases.push(baseName);
});
return this;
}
};
var Field = class {
name;
type;
defaultFn;
hidden;
constructor(name, type, defaultFn, hidden) {
this.name = name;
this.type = type;
this.defaultFn = defaultFn;
this.hidden = !!hidden;
}
toString() {
return JSON.stringify(this.name) + ": " + this.type;
}
getValue(obj) {
var value = obj[this.name];
if (typeof value !== "undefined") return value;
if (typeof this.defaultFn === "function") value = this.defaultFn.call(obj);
return value;
}
};
function shallowStringify(value) {
if (Array.isArray(value)) return "[" + value.map(shallowStringify).join(", ") + "]";
if (value && typeof value === "object") return "{ " + Object.keys(value).map(function(key) {
return key + ": " + value[key];
}).join(", ") + " }";
return JSON.stringify(value);
}
function typesPlugin(_fork) {
const Type = {
or(...types) {
return new OrType(types.map((type) => Type.from(type)));
},
from(value, name) {
if (value instanceof ArrayType || value instanceof IdentityType || value instanceof ObjectType || value instanceof OrType || value instanceof PredicateType) return value;
if (value instanceof Def) return value.type;
if (isArray.check(value)) {
if (value.length !== 1) throw new Error("only one element type is permitted for typed arrays");
return new ArrayType(Type.from(value[0]));
}
if (isObject.check(value)) return new ObjectType(Object.keys(value).map((name) => {
return new Field(name, Type.from(value[name], name));
}));
if (typeof value === "function") {
var bicfIndex = builtInCtorFns.indexOf(value);
if (bicfIndex >= 0) return builtInCtorTypes[bicfIndex];
if (typeof name !== "string") throw new Error("missing name");
return new PredicateType(name, value);
}
return new IdentityType(value);
},
def(typeName) {
return hasOwn$6.call(defCache, typeName) ? defCache[typeName] : defCache[typeName] = new DefImpl(typeName);
},
hasDef(typeName) {
return hasOwn$6.call(defCache, typeName);
}
};
var builtInCtorFns = [];
var builtInCtorTypes = [];
function defBuiltInType(name, example) {
const objStr = objToStr.call(example);
const type = new PredicateType(name, (value) => objToStr.call(value) === objStr);
if (example && typeof example.constructor === "function") {
builtInCtorFns.push(example.constructor);
builtInCtorTypes.push(type);
}
return type;
}
const isString = defBuiltInType("string", "truthy");
const isFunction = defBuiltInType("function", function() {});
const isArray = defBuiltInType("array", []);
const isObject = defBuiltInType("object", {});
const isRegExp = defBuiltInType("RegExp", /./);
const isDate = defBuiltInType("Date", /* @__PURE__ */ new Date());
const isNumber = defBuiltInType("number", 3);
const isBoolean = defBuiltInType("boolean", true);
const isNull = defBuiltInType("null", null);
const isUndefined = defBuiltInType("undefined", void 0);
const builtInTypes = {
string: isString,
function: isFunction,
array: isArray,
object: isObject,
RegExp: isRegExp,
Date: isDate,
number: isNumber,
boolean: isBoolean,
null: isNull,
undefined: isUndefined,
BigInt: typeof BigInt === "function" ? defBuiltInType("BigInt", BigInt(1234)) : new PredicateType("BigInt", () => false)
};
var defCache = Object.create(null);
function defFromValue(value) {
if (value && typeof value === "object") {
var type = value.type;
if (typeof type === "string" && hasOwn$6.call(defCache, type)) {
var d = defCache[type];
if (d.finalized) return d;
}
}
return null;
}
class DefImpl extends Def {
constructor(typeName) {
super(new PredicateType(typeName, (value, deep) => this.check(value, deep)), typeName);
}
check(value, deep) {
if (this.finalized !== true) throw new Error("prematurely checking unfinalized type " + this.typeName);
if (value === null || typeof value !== "object") return false;
var vDef = defFromValue(value);
if (!vDef) {
if (this.typeName === "SourceLocation" || this.typeName === "Position") return this.checkAllFields(value, deep);
return false;
}
if (deep && vDef === this) return this.checkAllFields(value, deep);
if (!this.isSupertypeOf(vDef)) return false;
if (!deep) return true;
return vDef.checkAllFields(value, deep) && this.checkAllFields(value, false);
}
build(...buildParams) {
this.buildParams = buildParams;
if (this.buildable) return this;
this.field("type", String, () => this.typeName);
this.buildable = true;
const addParam = (built, param, arg, isArgAvailable) => {
if (hasOwn$6.call(built, param)) return;
var all = this.allFields;
if (!hasOwn$6.call(all, param)) throw new Error("" + param);
var field = all[param];
var type = field.type;
var value;
if (isArgAvailable) value = arg;
else if (field.defaultFn) value = field.defaultFn.call(built);
else {
var message = "no value or default function given for field " + JSON.stringify(param) + " of " + this.typeName + "(" + this.buildParams.map(function(name) {
return all[name];
}).join(", ") + ")";
throw new Error(message);
}
if (!type.check(value)) throw new Error(shallowStringify(value) + " does not match field " + field + " of type " + this.typeName);
built[param] = value;
};
const builder = (...args) => {
var argc = args.length;
if (!this.finalized) throw new Error("attempting to instantiate unfinalized type " + this.typeName);
var built = Object.create(nodePrototype);
this.buildParams.forEach(function(param, i) {
if (i < argc) addParam(built, param, args[i], true);
else addParam(built, param, null, false);
});
Object.keys(this.allFields).forEach(function(param) {
addParam(built, param, null, false);
});
if (built.type !== this.typeName) throw new Error("");
return built;
};
builder.from = (obj) => {
if (!this.finalized) throw new Error("attempting to instantiate unfinalized type " + this.typeName);
var built = Object.create(nodePrototype);
Object.keys(this.allFields).forEach(function(param) {
if (hasOwn$6.call(obj, param)) addParam(built, param, obj[param], true);
else addParam(built, param, null, false);
});
if (built.type !== this.typeName) throw new Error("");
return built;
};
Object.defineProperty(builders, getBuilderName(this.typeName), {
enumerable: true,
value: builder
});
return this;
}
field(name, type, defaultFn, hidden) {
if (this.finalized) {
console.error("Ignoring attempt to redefine field " + JSON.stringify(name) + " of finalized type " + JSON.stringify(this.typeName));
return this;
}
this.ownFields[name] = new Field(name, Type.from(type), defaultFn, hidden);
return this;
}
finalize() {
if (!this.finalized) {
var allFields = this.allFields;
var allSupertypes = this.allSupertypes;
this.baseNames.forEach((name) => {
var def = defCache[name];
if (def instanceof Def) {
def.finalize();
extend(allFields, def.allFields);
extend(allSupertypes, def.allSupertypes);
} else {
var message = "unknown supertype name " + JSON.stringify(name) + " for subtype " + JSON.stringify(this.typeName);
throw new Error(message);
}
});
extend(allFields, this.ownFields);
allSupertypes[this.typeName] = this;
this.fieldNames.length = 0;
for (var fieldName in allFields) if (hasOwn$6.call(allFields, fieldName) && !allFields[fieldName].hidden) this.fieldNames.push(fieldName);
Object.defineProperty(namedTypes, this.typeName, {
enumerable: true,
value: this.type
});
this.finalized = true;
populateSupertypeList(this.typeName, this.supertypeList);
if (this.buildable && this.supertypeList.lastIndexOf("Expression") >= 0) wrapExpressionBuilderWithStatement(this.typeName);
}
}
}
function getSupertypeNames(typeName) {
if (!hasOwn$6.call(defCache, typeName)) throw new Error("");
var d = defCache[typeName];
if (d.finalized !== true) throw new Error("");
return d.supertypeList.slice(1);
}
function computeSupertypeLookupTable(candidates) {
var table = {};
var typeNames = Object.keys(defCache);
var typeNameCount = typeNames.length;
for (var i = 0; i < typeNameCount; ++i) {
var typeName = typeNames[i];
var d = defCache[typeName];
if (d.finalized !== true) throw new Error("" + typeName);
for (var j = 0; j < d.supertypeList.length; ++j) {
var superTypeName = d.supertypeList[j];
if (hasOwn$6.call(candidates, superTypeName)) {
table[typeName] = superTypeName;
break;
}
}
}
return table;
}
var builders = Object.create(null);
var nodePrototype = {};
function defineMethod(name, func) {
var old = nodePrototype[name];
if (isUndefined.check(func)) delete nodePrototype[name];
else {
isFunction.assert(func);
Object.defineProperty(nodePrototype, name, {
enumerable: true,
configurable: true,
value: func
});
}
return old;
}
function getBuilderName(typeName) {
return typeName.replace(/^[A-Z]+/, function(upperCasePrefix) {
var len = upperCasePrefix.length;
switch (len) {
case 0: return "";
case 1: return upperCasePrefix.toLowerCase();
default: return upperCasePrefix.slice(0, len - 1).toLowerCase() + upperCasePrefix.charAt(len - 1);
}
});
}
function getStatementBuilderName(typeName) {
typeName = getBuilderName(typeName);
return typeName.replace(/(Expression)?$/, "Statement");
}
var namedTypes = {};
function getFieldNames(object) {
var d = defFromValue(object);
if (d) return d.fieldNames.slice(0);
if ("type" in object) throw new Error("did not recognize object of type " + JSON.stringify(object.type));
return Object.keys(object);
}
function getFieldValue(object, fieldName) {
var d = defFromValue(object);
if (d) {
var field = d.allFields[fieldName];
if (field) return field.getValue(object);
}
return object && object[fieldName];
}
function eachField(object, callback, context) {
getFieldNames(object).forEach(function(name) {
callback.call(this, name, getFieldValue(object, name));
}, context);
}
function someField(object, callback, context) {
return getFieldNames(object).some(function(name) {
return callback.call(this, name, getFieldValue(object, name));
}, context);
}
function wrapExpressionBuilderWithStatement(typeName) {
var wrapperName = getStatementBuilderName(typeName);
if (builders[wrapperName]) return;
var wrapped = builders[getBuilderName(typeName)];
if (!wrapped) return;
const builder = function(...args) {
return builders.expressionStatement(wrapped.apply(builders, args));
};
builder.from = function(...args) {
return builders.expressionStatement(wrapped.from.apply(builders, args));
};
builders[wrapperName] = builder;
}
function populateSupertypeList(typeName, list) {
list.length = 0;
list.push(typeName);
var lastSeen = Object.create(null);
for (var pos = 0; pos < list.length; ++pos) {
typeName = list[pos];
var d = defCache[typeName];
if (d.finalized !== true) throw new Error("");
if (hasOwn$6.call(lastSeen, typeName)) delete list[lastSeen[typeName]];
lastSeen[typeName] = pos;
list.push.apply(list, d.baseNames);
}
for (var to = 0, from = to, len = list.length; from < len; ++from) if (hasOwn$6.call(list, from)) list[to++] = list[from];
list.length = to;
}
function extend(into, from) {
Object.keys(from).forEach(function(name) {
into[name] = from[name];
});
return into;
}
function finalize() {
Object.keys(defCache).forEach(function(name) {
defCache[name].finalize();
});
}
return {
Type,
builtInTypes,
getSupertypeNames,
computeSupertypeLookupTable,
builders,
defineMethod,
getBuilderName,
getStatementBuilderName,
namedTypes,
getFieldNames,
getFieldValue,
eachField,
someField,
finalize
};
}
//#endregion
//#region vendor/ast-types/src/path.ts
var hasOwn$5 = Object.prototype.hasOwnProperty;
function pathPlugin(fork) {
var types = fork.use(typesPlugin);
var isArray = types.builtInTypes.array;
var isNumber = types.builtInTypes.number;
const Path = function Path(value, parentPath, name) {
if (!(this instanceof Path)) throw new Error("Path constructor cannot be invoked without 'new'");
if (parentPath) {
if (!(parentPath instanceof Path)) throw new Error("");
} else {
parentPath = null;
name = null;
}
this.value = value;
this.parentPath = parentPath;
this.name = name;
this.__childCache = null;
};
var Pp = Path.prototype;
function getChildCache(path) {
return path.__childCache || (path.__childCache = Object.create(null));
}
function getChildPath(path, name) {
var cache = getChildCache(path);
var actualChildValue = path.getValueProperty(name);
var childPath = cache[name];
if (!hasOwn$5.call(cache, name) || childPath.value !== actualChildValue) childPath = cache[name] = new path.constructor(actualChildValue, path, name);
return childPath;
}
Pp.getValueProperty = function getValueProperty(name) {
return this.value[name];
};
Pp.get = function get(...names) {
var path = this;
var count = names.length;
for (var i = 0; i < count; ++i) path = getChildPath(path, names[i]);
return path;
};
Pp.each = function each(callback, context) {
var childPaths = [];
var len = this.value.length;
var i = 0;
for (var i = 0; i < len; ++i) if (hasOwn$5.call(this.value, i)) childPaths[i] = this.get(i);
context = context || this;
for (i = 0; i < len; ++i) if (hasOwn$5.call(childPaths, i)) callback.call(context, childPaths[i]);
};
Pp.map = function map(callback, context) {
var result = [];
this.each(function(childPath) {
result.push(callback.call(this, childPath));
}, context);
return result;
};
Pp.filter = function filter(callback, context) {
var result = [];
this.each(function(childPath) {
if (callback.call(this, childPath)) result.push(childPath);
}, context);
return result;
};
function emptyMoves() {}
function getMoves(path, offset, start, end) {
isArray.assert(path.value);
if (offset === 0) return emptyMoves;
var length = path.value.length;
if (length < 1) return emptyMoves;
var argc = arguments.length;
if (argc === 2) {
start = 0;
end = length;
} else if (argc === 3) {
start = Math.max(start, 0);
end = length;
} else {
start = Math.max(start, 0);
end = Math.min(end, length);
}
isNumber.assert(start);
isNumber.assert(end);
var moves = Object.create(null);
var cache = getChildCache(path);
for (var i = start; i < end; ++i) if (hasOwn$5.call(path.value, i)) {
var childPath = path.get(i);
if (childPath.name !== i) throw new Error("");
var newIndex = i + offset;
childPath.name = newIndex;
moves[newIndex] = childPath;
delete cache[i];
}
delete cache.length;
return function() {
for (var newIndex in moves) {
var childPath = moves[newIndex];
if (childPath.name !== +newIndex) throw new Error("");
cache[newIndex] = childPath;
path.value[newIndex] = childPath.value;
}
};
}
Pp.shift = function shift() {
var move = getMoves(this, -1);
var result = this.value.shift();
move();
return result;
};
Pp.unshift = function unshift(...args) {
var move = getMoves(this, args.length);
var result = this.value.unshift.apply(this.value, args);
move();
return result;
};
Pp.push = function push(...args) {
isArray.assert(this.value);
delete getChildCache(this).length;
return this.value.push.apply(this.value, args);
};
Pp.pop = function pop() {
isArray.assert(this.value);
var cache = getChildCache(this);
delete cache[this.value.length - 1];
delete cache.length;
return this.value.pop();
};
Pp.insertAt = function insertAt(index) {
var argc = arguments.length;
var move = getMoves(this, argc - 1, index);
if (move === emptyMoves && argc <= 1) return this;
index = Math.max(index, 0);
for (var i = 1; i < argc; ++i) this.value[index + i - 1] = arguments[i];
move();
return this;
};
Pp.insertBefore = function insertBefore(...args) {
var pp = this.parentPath;
var argc = args.length;
var insertAtArgs = [this.name];
for (var i = 0; i < argc; ++i) insertAtArgs.push(args[i]);
return pp.insertAt.apply(pp, insertAtArgs);
};
Pp.insertAfter = function insertAfter(...args) {
var pp = this.parentPath;
var argc = args.length;
var insertAtArgs = [this.name + 1];
for (var i = 0; i < argc; ++i) insertAtArgs.push(args[i]);
return pp.insertAt.apply(pp, insertAtArgs);
};
function repairRelationshipWithParent(path) {
if (!(path instanceof Path)) throw new Error("");
var pp = path.parentPath;
if (!pp) return path;
var parentValue = pp.value;
var parentCache = getChildCache(pp);
if (parentValue[path.name] === path.value) parentCache[path.name] = path;
else if (isArray.check(parentValue)) {
var i = parentValue.indexOf(path.value);
if (i >= 0) parentCache[path.name = i] = path;
} else {
parentValue[path.name] = path.value;
parentCache[path.name] = path;
}
if (parentValue[path.name] !== path.value) throw new Error("");
if (path.parentPath.get(path.name) !== path) throw new Error("");
return path;
}
Pp.replace = function replace(replacement) {
var results = [];
var parentValue = this.parentPath.value;
var parentCache = getChildCache(this.parentPath);
var count = arguments.length;
repairRelationshipWithParent(this);
if (isArray.check(parentValue)) {
var originalLength = parentValue.length;
var move = getMoves(this.parentPath, count - 1, this.name + 1);
var spliceArgs = [this.name, 1];
for (var i = 0; i < count; ++i) spliceArgs.push(arguments[i]);
if (parentValue.splice.apply(parentValue, spliceArgs)[0] !== this.value) throw new Error("");
if (parentValue.length !== originalLength - 1 + count) throw new Error("");
move();
if (count === 0) {
delete this.value;
delete parentCache[this.name];
this.__childCache = null;
} else {
if (parentValue[this.name] !== replacement) throw new Error("");
if (this.value !== replacement) {
this.value = replacement;
this.__childCache = null;
}
for (i = 0; i < count; ++i) results.push(this.parentPath.get(this.name + i));
if (results[0] !== this) throw new Error("");
}
} else if (count === 1) {
if (this.value !== replacement) this.__childCache = null;
this.value = parentValue[this.name] = replacement;
results.push(this);
} else if (count === 0) {
delete parentValue[this.name];
delete this.value;
this.__childCache = null;
} else throw new Error("Could not replace path");
return results;
};
return Path;
}
//#endregion
//#region vendor/ast-types/src/scope.ts
var hasOwn$4 = Object.prototype.hasOwnProperty;
function scopePlugin(fork) {
var types = fork.use(typesPlugin);
var Type = types.Type;
var namedTypes = types.namedTypes;
var Node = namedTypes.Node;
var Expression = namedTypes.Expression;
var isArray = types.builtInTypes.array;
var b = types.builders;
const Scope = function Scope(path, parentScope) {
if (!(this instanceof Scope)) throw new Error("Scope constructor cannot be invoked without 'new'");
if (!TypeParameterScopeType.check(path.value)) ScopeType.assert(path.value);
var depth;
if (parentScope) {
if (!(parentScope instanceof Scope)) throw new Error("");
depth = parentScope.depth + 1;
} else {
parentScope = null;
depth = 0;
}
Object.defineProperties(this, {
path: { value: path },
node: { value: path.value },
isGlobal: {
value: !parentScope,
enumerable: true
},
depth: { value: depth },
parent: { value: parentScope },
bindings: { value: {} },
types: { value: {} }
});
};
var ScopeType = Type.or(namedTypes.Program, namedTypes.Function, namedTypes.CatchClause);
var TypeParameterScopeType = Type.or(namedTypes.Function, namedTypes.ClassDeclaration, namedTypes.ClassExpression, namedTypes.InterfaceDeclaration, namedTypes.TSInterfaceDeclaration, namedTypes.TypeAlias, namedTypes.TSTypeAliasDeclaration);
var FlowOrTSTypeParameterType = Type.or(namedTypes.TypeParameter, namedTypes.TSTypeParameter);
Scope.isEstablishedBy = function(node) {
return ScopeType.check(node) || TypeParameterScopeType.check(node);
};
var Sp = Scope.prototype;
Sp.didScan = false;
Sp.declares = function(name) {
this.scan();
return hasOwn$4.call(this.bindings, name);
};
Sp.declaresType = function(name) {
this.scan();
return hasOwn$4.call(this.types, name);
};
Sp.declareTemporary = function(prefix) {
if (prefix) {
if (!/^[a-z$_]/i.test(prefix)) throw new Error("");
} else prefix = "t$";
prefix += this.depth.toString(36) + "$";
this.scan();
var index = 0;
while (this.declares(prefix + index)) ++index;
var name = prefix + index;
return this.bindings[name] = types.builders.identifier(name);
};
Sp.injectTemporary = function(identifier, init) {
identifier || (identifier = this.declareTemporary());
var bodyPath = this.path.get("body");
if (namedTypes.BlockStatement.check(bodyPath.value)) bodyPath = bodyPath.get("body");
bodyPath.unshift(b.variableDeclaration("var", [b.variableDeclarator(identifier, init || null)]));
return identifier;
};
Sp.scan = function(force) {
if (force || !this.didScan) {
for (var name in this.bindings) delete this.bindings[name];
for (var name in this.types) delete this.types[name];
scanScope(this.path, this.bindings, this.types);
this.didScan = true;
}
};
Sp.getBindings = function() {
this.scan();
return this.bindings;
};
Sp.getTypes = function() {
this.scan();
return this.types;
};
function scanScope(path, bindings, scopeTypes) {
var node = path.value;
if (TypeParameterScopeType.check(node)) {
const params = path.get("typeParameters", "params");
if (isArray.check(params.value)) params.each((childPath) => {
addTypeParameter(childPath, scopeTypes);
});
}
if (ScopeType.check(node)) if (namedTypes.CatchClause.check(node)) addPattern(path.get("param"), bindings);
else recursiveScanScope(path, bindings, scopeTypes);
}
function recursiveScanScope(path, bindings, scopeTypes) {
var node = path.value;
if (path.parent && namedTypes.FunctionExpression.check(path.parent.node) && path.parent.node.id) addPattern(path.parent.get("id"), bindings);
if (!node) {} else if (isArray.check(node)) path.each((childPath) => {
recursiveScanChild(childPath, bindings, scopeTypes);
});
else if (namedTypes.Function.check(node)) {
path.get("params").each((paramPath) => {
addPattern(paramPath, bindings);
});
recursiveScanChild(path.get("body"), bindings, scopeTypes);
recursiveScanScope(path.get("typeParameters"), bindings, scopeTypes);
} else if (namedTypes.TypeAlias && namedTypes.TypeAlias.check(node) || namedTypes.InterfaceDeclaration && namedTypes.InterfaceDeclaration.check(node) || namedTypes.TSTypeAliasDeclaration && namedTypes.TSTypeAliasDeclaration.check(node) || namedTypes.TSInterfaceDeclaration && namedTypes.TSInterfaceDeclaration.check(node)) addTypePattern(path.get("id"), scopeTypes);
else if (namedTypes.VariableDeclarator.check(node)) {
addPattern(path.get("id"), bindings);
recursiveScanChild(path.get("init"), bindings, scopeTypes);
} else if (node.type === "ImportSpecifier" || node.type === "ImportNamespaceSpecifier" || node.type === "ImportDefaultSpecifier") addPattern(path.get(node.local ? "local" : node.name ? "name" : "id"), bindings);
else if (Node.check(node) && !Expression.check(node)) types.eachField(node, function(name, child) {
var childPath = path.get(name);
if (!pathHasValue(childPath, child)) throw new Error("");
recursiveScanChild(childPath, bindings, scopeTypes);
});
}
function pathHasValue(path, value) {
if (path.value === value) return true;
if (Array.isArray(path.value) && path.value.length === 0 && Array.isArray(value) && value.length === 0) return true;
return false;
}
function recursiveScanChild(path, bindings, scopeTypes) {
var node = path.value;
if (!node || Expression.check(node)) {} else if (namedTypes.FunctionDeclaration.check(node) && node.id !== null) addPattern(path.get("id"), bindings);
else if (namedTypes.ClassDeclaration && namedTypes.ClassDeclaration.check(node) && node.id !== null) {
addPattern(path.get("id"), bindings);
recursiveScanScope(path.get("typeParameters"), bindings, scopeTypes);
} else if (namedTypes.InterfaceDeclaration && namedTypes.InterfaceDeclaration.check(node) || namedTypes.TSInterfaceDeclaration && namedTypes.TSInterfaceDeclaration.check(node)) addTypePattern(path.get("id"), scopeTypes);
else if (ScopeType.check(node)) {
if (namedTypes.CatchClause.check(node) && namedTypes.Identifier.check(node.param)) {
var catchParamName = node.param.name;
var hadBinding = hasOwn$4.call(bindings, catchParamName);
recursiveScanScope(path.get("body"), bindings, scopeTypes);
if (!hadBinding) delete bindings[catchParamName];
}
} else recursiveScanScope(path, bindings, scopeTypes);
}
function addPattern(patternPath, bindings) {
var pattern = patternPath.value;
namedTypes.Pattern.assert(pattern);
if (namedTypes.Identifier.check(pattern)) if (hasOwn$4.call(bindings, pattern.name)) bindings[pattern.name].push(patternPath);
else bindings[pattern.name] = [patternPath];
else if (namedTypes.AssignmentPattern && namedTypes.AssignmentPattern.check(pattern)) addPattern(patternPath.get("left"), bindings);
else if (namedTypes.ObjectPattern && namedTypes.ObjectPattern.check(pattern)) patternPath.get("properties").each(function(propertyPath) {
var property = propertyPath.value;
if (namedTypes.Pattern.check(property)) addPattern(propertyPath, bindings);
else if (namedTypes.Property.check(property) || namedTypes.ObjectProperty && namedTypes.ObjectProperty.check(property)) addPattern(propertyPath.get("value"), bindings);
else if (namedTypes.SpreadProperty && namedTypes.SpreadProperty.check(property)) addPattern(propertyPath.get("argument"), bindings);
});
else if (namedTypes.ArrayPattern && namedTypes.ArrayPattern.check(pattern)) patternPath.get("elements").each(function(elementPath) {
var element = elementPath.value;
if (namedTypes.Pattern.check(element)) addPattern(elementPath, bindings);
else if (namedTypes.SpreadElement && namedTypes.SpreadElement.check(element)) addPattern(elementPath.get("argument"), bindings);
});
else if (namedTypes.PropertyPattern && namedTypes.PropertyPattern.check(pattern)) addPattern(patternPath.get("pattern"), bindings);
else if (namedTypes.SpreadElementPattern && namedTypes.SpreadElementPattern.check(pattern) || namedTypes.RestElement && namedTypes.RestElement.check(pattern) || namedTypes.SpreadPropertyPattern && namedTypes.SpreadPropertyPattern.check(pattern)) addPattern(patternPath.get("argument"), bindings);
}
function addTypePattern(patternPath, types) {
var pattern = patternPath.value;
namedTypes.Pattern.assert(pattern);
if (namedTypes.Identifier.check(pattern)) if (hasOwn$4.call(types, pattern.name)) types[pattern.name].push(patternPath);
else types[pattern.name] = [patternPath];
}
function addTypeParameter(parameterPath, types) {
var parameter = parameterPath.value;
FlowOrTSTypeParameterType.assert(parameter);
if (hasOwn$4.call(types, parameter.name)) types[parameter.name].push(parameterPath);
else types[parameter.name] = [parameterPath];
}
Sp.lookup = function(name) {
for (var scope = this; scope; scope = scope.parent) if (scope.declares(name)) break;
return scope;
};
Sp.lookupType = function(name) {
for (var scope = this; scope; scope = scope.parent) if (scope.declaresType(name)) break;
return scope;
};
Sp.getGlobalScope = function() {
var scope = this;
while (!scope.isGlobal) scope = scope.parent;
return scope;
};
return Scope;
}
//#endregion
//#region vendor/ast-types/src/node-path.ts
function nodePathPlugin(fork) {
var types = fork.use(typesPlugin);
var n = types.namedTypes;
var b = types.builders;
var isNumber = types.builtInTypes.number;
var isArray = types.builtInTypes.array;
var Path = fork.use(pathPlugin);
var Scope = fork.use(scopePlugin);
const NodePath = function NodePath(value, parentPath, name) {
if (!(this instanceof NodePath)) throw new Error("NodePath constructor cannot be invoked without 'new'");
Path.call(this, value, parentPath, name);
};
var NPp = NodePath.prototype = Object.create(Path.prototype, { constructor: {
value: NodePath,
enumerable: false,
writable: true,
configurable: true
} });
Object.defineProperties(NPp, {
node: { get: function() {
Object.defineProperty(this, "node", {
configurable: true,
value: this._computeNode()
});
return this.node;
} },
parent: { get: function() {
Object.defineProperty(this, "parent", {
configurable: true,
value: this._computeParent()
});
return this.parent;
} },
scope: { get: function() {
Object.defineProperty(this, "scope", {
configurable: true,
value: this._computeScope()
});
return this.scope;
} }
});
NPp.replace = function() {
delete this.node;
delete this.parent;
delete this.scope;
return Path.prototype.replace.apply(this, arguments);
};
NPp.prune = function() {
var remainingNodePath = this.parent;
this.replace();
return cleanUpNodesAfterPrune(remainingNodePath);
};
NPp._computeNode = function() {
var value = this.value;
if (n.Node.check(value)) return value;
var pp = this.parentPath;
return pp && pp.node || null;
};
NPp._computeParent = function() {
var value = this.value;
var pp = this.parentPath;
if (!n.Node.check(value)) {
while (pp && !n.Node.check(pp.value)) pp = pp.parentPath;
if (pp) pp = pp.parentPath;
}
while (pp && !n.Node.check(pp.value)) pp = pp.parentPath;
return pp || null;
};
NPp._computeScope = function() {
var value = this.value;
var pp = this.parentPath;
var scope = pp && pp.scope;
if (n.Node.check(value) && Scope.isEstablishedBy(value)) scope = new Scope(this, scope);
return scope || null;
};
NPp.getValueProperty = function(name) {
return types.getFieldValue(this.value, name);
};
/**
* Determine whether this.node needs to be wrapped in parentheses in order
* for a parser to reproduce the same local AST structure.
*
* For instance, in the expression `(1 + 2) * 3`, the BinaryExpression
* whose operator is "+" needs parentheses, because `1 + 2 * 3` would
* parse differently.
*
* If assumeExpressionContext === true, we don't worry about edge cases
* like an anonymous FunctionExpression appearing lexically first in its
* enclosing statement and thus needing parentheses to avoid being parsed
* as a FunctionDeclaration with a missing name.
*/
NPp.needsParens = function(assumeExpressionContext) {
var pp = this.parentPath;
if (!pp) return false;
var node = this.value;
if (!n.Expression.check(node)) return false;
if (node.type === "Identifier") return false;
while (!n.Node.check(pp.value)) {
pp = pp.parentPath;
if (!pp) return false;
}
var parent = pp.value;
switch (node.type) {
case "UnaryExpression":
case "SpreadElement":
case "SpreadProperty": return parent.type === "MemberExpression" && this.name === "object" && parent.object === node;
case "BinaryExpression":
case "LogicalExpression": switch (parent.type) {
case "CallExpression": return this.name === "callee" && parent.callee === node;
case "UnaryExpression":
case "SpreadElement":
case "SpreadProperty": return true;
case "MemberExpression": return this.name === "object" && parent.object === node;
case "BinaryExpression":
case "LogicalExpression": {
const n = node;
const pp = PRECEDENCE[parent.operator];
const np = PRECEDENCE[n.operator];
if (pp > np) return true;
if (pp === np && this.name === "right") {
if (parent.right !== n) throw new Error("Nodes must be equal");
return true;
}
}
default: return false;
}
case "SequenceExpression": switch (parent.type) {
case "ForStatement": return false;
case "ExpressionStatement": return this.name !== "expression";
default: return true;
}
case "YieldExpression": switch (parent.type) {
case "BinaryExpression":
case "LogicalExpression":
case "UnaryExpression":
case "SpreadElement":
case "SpreadProperty":
case "CallExpression":
case "MemberExpression":
case "NewExpression":
case "ConditionalExpression":
case "YieldExpression": return true;
default: return false;
}
case "Literal": return parent.type === "MemberExpression" && isNumber.check(node.value) && this.name === "object" && parent.object === node;
case "AssignmentExpression":
case "ConditionalExpression": switch (parent.type) {
case "UnaryExpression":
case "SpreadElement":
case "SpreadProperty":
case "BinaryExpression":
case "LogicalExpression": return true;
case "CallExpression": return this.name === "callee" && parent.callee === node;
case "ConditionalExpression": return this.name === "test" && parent.test === node;
case "MemberExpression": return this.name === "object" && parent.object === node;
default: return false;
}
default: if (parent.type === "NewExpression" && this.name === "callee" && parent.callee === node) return containsCallExpression(node);
}
if (assumeExpressionContext !== true && !this.canBeFirstInStatement() && this.firstInStatement()) return true;
return false;
};
function isBinary(node) {
return n.BinaryExpression.check(node) || n.LogicalExpression.check(node);
}
var PRECEDENCE = {};
[
["||"],
["&&"],
["|"],
["^"],
["&"],
[
"==",
"===",
"!=",
"!=="
],
[
"<",
">",
"<=",
">=",
"in",
"instanceof"
],
[
">>",
"<<",
">>>"
],
["+", "-"],
[
"*",
"/",
"%"
]
].forEach(function(tier, i) {
tier.forEach(function(op) {
PRECEDENCE[op] = i;
});
});
function containsCallExpression(node) {
if (n.CallExpression.check(node)) return true;
if (isArray.check(node)) return node.some(containsCallExpression);
if (n.Node.check(node)) return types.someField(node, function(_name, child) {
return containsCallExpression(child);
});
return false;
}
NPp.canBeFirstInStatement = function() {
var node = this.node;
return !n.FunctionExpression.check(node) && !n.ObjectExpression.check(node);
};
NPp.firstInStatement = function() {
return firstInStatement(this);
};
function firstInStatement(path) {
for (var node, parent; path.parent; path = path.parent) {
node = path.node;
parent = path.parent.node;
if (n.BlockStatement.check(parent) && path.parent.name === "body" && path.name === 0) {
if (parent.body[0] !== node) throw new Error("Nodes must be equal");
return true;
}
if (n.ExpressionStatement.check(parent) && path.name === "expression") {
if (parent.expression !== node) throw new Error("Nodes must be equal");
return true;
}
if (n.SequenceExpression.check(parent) && path.parent.name === "expressions" && path.name === 0) {
if (parent.expressions[0] !== node) throw new Error("Nodes must be equal");
continue;
}
if (n.CallExpression.check(parent) && path.name === "callee") {
if (parent.callee !== node) throw new Error("Nodes must be equal");
continue;
}
if (n.MemberExpression.check(parent) && path.name === "object") {
if (parent.object !== node) throw new Error("Nodes must be equal");
continue;
}
if (n.ConditionalExpression.check(parent) && path.name === "test") {
if (parent.test !== node) throw new Error("Nodes must be equal");
continue;
}
if (isBinary(parent) && path.name === "left") {
if (parent.left !== node) throw new Error("Nodes must be equal");
continue;
}
if (n.UnaryExpression.check(parent) && !parent.prefix && path.name === "argument") {
if (parent.argument !== node) throw new Error("Nodes must be equal");
continue;
}
return false;
}
return true;
}
/**
* Pruning certain nodes will result in empty or incomplete nodes, here we clean those nodes up.
*/
function cleanUpNodesAfterPrune(remainingNodePath) {
if (n.VariableDeclaration.check(remainingNodePath.node)) {
var declarations = remainingNodePath.get("declarations").value;
if (!declarations || declarations.length === 0) return remainingNodePath.prune();
} else if (n.ExpressionStatement.check(remainingNodePath.node)) {
if (!remainingNodePath.get("expression").value) return remainingNodePath.prune();
} else if (n.IfStatement.check(remainingNodePath.node)) cleanUpIfStatementAfterPrune(remainingNodePath);
return remainingNodePath;
}
function cleanUpIfStatementAfterPrune(ifStatement) {
var testExpression = ifStatement.get("test").value;
var alternate = ifStatement.get("alternate").value;
var consequent = ifStatement.get("consequent").value;
if (!consequent && !alternate) {
var testExpressionStatement = b.expressionStatement(testExpression);
ifStatement.replace(testExpressionStatement);
} else if (!consequent && alternate) {
var negatedTestExpression = b.unaryExpression("!", testExpression, true);
if (n.UnaryExpression.check(testExpression) && testExpression.operator === "!") negatedTestExpression = testExpression.argument;
ifStatement.get("test").replace(negatedTestExpression);
ifStatement.get("consequent").replace(alternate);
ifStatement.get("alternate").replace();
}
}
return NodePath;
}
//#endregion
//#region vendor/ast-types/src/path-visitor.ts
var hasOwn$3 = Object.prototype.hasOwnProperty;
function pathVisitorPlugin(fork) {
var types = fork.use(typesPlugin);
var NodePath = fork.use(nodePathPlugin);
var isArray = types.builtInTypes.array;
var isObject = types.builtInTypes.object;
var isFunction = types.builtInTypes.function;
var undefined;
const PathVisitor = function PathVisitor() {
if (!(this instanceof PathVisitor)) throw new Error("PathVisitor constructor cannot be invoked without 'new'");
this._reusableContextStack = [];
this._methodNameTable = computeMethodNameTable(this);
this._shouldVisitComments = hasOwn$3.call(this._methodNameTable, "Block") || hasOwn$3.call(this._methodNameTable, "Line");
this.Context = makeContextConstructor(this);
this._visiting = false;
this._changeReported = false;
};
function computeMethodNameTable(visitor) {
var typeNames = Object.create(null);
for (var methodName in visitor) if (/^visit[A-Z]/.test(methodName)) typeNames[methodName.slice(5)] = true;
var supertypeTable = types.computeSupertypeLookupTable(typeNames);
var methodNameTable = Object.create(null);
var typeNameKeys = Object.keys(supertypeTable);
var typeNameCount = typeNameKeys.length;
for (var i = 0; i < typeNameCount; ++i) {
var typeName = typeNameKeys[i];
methodName = "visit" + supertypeTable[typeName];
if (isFunction.check(visitor[methodName])) methodNameTable[typeName] = methodName;
}
return methodNameTable;
}
PathVisitor.fromMethodsObject = function fromMethodsObject(methods) {
if (methods instanceof PathVisitor) return methods;
if (!isObject.check(methods)) return new PathVisitor();
const Visitor = function Visitor() {
if (!(this instanceof Visitor)) throw new Error("Visitor constructor cannot be invoked without 'new'");
PathVisitor.call(this);
};
var Vp = Visitor.prototype = Object.create(PVp);
Vp.constructor = Visitor;
extend(Vp, methods);
extend(Visitor, PathVisitor);
isFunction.assert(Visitor.fromMethodsObject);
isFunction.assert(Visitor.visit);
return new Visitor();
};
function extend(target, source) {
for (var property in source) if (hasOwn$3.call(source, property)) target[property] = source[property];
return target;
}
PathVisitor.visit = function visit(node, methods) {
return PathVisitor.fromMethodsObject(methods).visit(node);
};
var PVp = PathVisitor.prototype;
PVp.visit = function() {
if (this._visiting) throw new Error("Recursively calling visitor.visit(path) resets visitor state. Try this.visit(path) or this.traverse(path) instead.");
this._visiting = true;
this._changeReported = false;
this._abortRequested = false;
var argc = arguments.length;
var args = new Array(argc);
for (var i = 0; i < argc; ++i) args[i] = arguments[i];
if (!(args[0] instanceof NodePath)) args[0] = new NodePath({ root: args[0] }).get("root");
this.reset.apply(this, args);
var didNotThrow;
try {
var root = this.visitWithoutReset(args[0]);
didNotThrow = true;
} finally {
this._visiting = false;
if (!didNotThrow && this._abortRequested) return args[0].value;
}
return root;
};
PVp.AbortRequest = function AbortRequest() {};
PVp.abort = function() {
var visitor = this;
visitor._abortRequested = true;
var request = new visitor.AbortRequest();
request.cancel = function() {
visitor._abortRequested = false;
};
throw request;
};
PVp.reset = function(_path) {};
PVp.visitWithoutReset = function(path) {
if (this instanceof this.Context) return this.visitor.visitWithoutReset(path);
if (!(path instanceof NodePath)) throw new Error("");
var value = path.value;
var methodName = value && typeof value === "object" && typeof value.type === "string" && this._methodNameTable[value.type];
if (methodName) {
var context = this.acquireContext(path);
try {
return context.invokeVisitorMethod(methodName);
} finally {
this.releaseContext(context);
}
} else return visitChildren(path, this);
};
function visitChildren(path, visitor) {
if (!(path instanceof NodePath)) throw new Error("");
if (!(visitor instanceof PathVisitor)) throw new Error("");
var value = path.value;
if (isArray.check(value)) path.each(visitor.visitWithoutReset, visitor);
else if (!isObject.check(value)) {} else {
var childNames = types.getFieldNames(value);
if (visitor._shouldVisitComments && value.comments && childNames.indexOf("comments") < 0) childNames.push("comments");
var childCount = childNames.length;
var childPaths = [];
for (var i = 0; i < childCount; ++i) {
var childName = childNames[i];
if (!hasOwn$3.call(value, childName)) value[childName] = types.getFieldValue(value, childName);
childPaths.push(path.get(childName));
}
for (var i = 0; i < childCount; ++i) visitor.visitWithoutReset(childPaths[i]);
}
return path.value;
}
PVp.acquireContext = function(path) {
if (this._reusableContextStack.length === 0) return new this.Context(path);
return this._reusableContextStack.pop().reset(path);
};
PVp.releaseContext = function(context) {
if (!(context instanceof this.Context)) throw new Error("");
this._reusableContextStack.push(context);
context.currentPath = null;
};
PVp.reportChanged = function() {
this._changeReported = true;
};
PVp.wasChangeReported = function() {
return this._changeReported;
};
function makeContextConstructor(visitor) {
function Context(path) {
if (!(this instanceof Context)) throw new Error("");
if (!(this instanceof PathVisitor)) throw new Error("");
if (!(path instanceof NodePath)) throw new Error("");
Object.defineProperty(this, "visitor", {
value: visitor,
writable: false,
enumerable: true,
configurable: false
});
this.currentPath = path;
this.needToCallTraverse = true;
Object.seal(this);
}
if (!(visitor instanceof PathVisitor)) throw new Error("");
var Cp = Context.prototype = Object.create(visitor);
Cp.constructor = Context;
extend(Cp, sharedContextProtoMethods);
return Context;
}
var sharedContextProtoMethods = Object.create(null);
sharedContextProtoMethods.reset = function reset(path) {
if (!(this instanceof this.Context)) throw new Error("");
if (!(path instanceof NodePath)) throw new Error("");
this.currentPath = path;
this.needToCallTraverse = true;
return this;
};
sharedContextProtoMethods.invokeVisitorMethod = function invokeVisitorMethod(methodName) {
if (!(this instanceof this.Context)) throw new Error("");
if (!(this.currentPath instanceof NodePath)) throw new Error("");
var result = this.visitor[methodName].call(this, this.currentPath);
if (result === false) this.needToCallTraverse = false;
else if (result !==