Add node modules and compiled JavaScript from main

This commit is contained in:
Oliver King 2022-06-21 13:37:16 +00:00
parent d893f27da9
commit 4b42a5ec78
6750 changed files with 1745644 additions and 10860 deletions

View file

@ -0,0 +1,29 @@
"use strict";
const path = require("path");
const chalk = require("chalk");
const generateBuilders = require("./generators/generateBuilders");
const generateValidators = require("./generators/generateValidators");
const generateAsserts = require("./generators/generateAsserts");
const generateConstants = require("./generators/generateConstants");
const format = require("../../../scripts/utils/formatCode");
const writeFile = require("../../../scripts/utils/writeFileAndMkDir");
const baseDir = path.join(__dirname, "../src");
console.log("Generating @babel/types dynamic functions");
const buildersFile = path.join(baseDir, "builders/generated/index.js");
writeFile(buildersFile, format(generateBuilders(), buildersFile));
console.log(` ${chalk.green("✔")} Generated builders`);
const validatorsFile = path.join(baseDir, "validators/generated/index.js");
writeFile(validatorsFile, format(generateValidators(), validatorsFile));
console.log(` ${chalk.green("✔")} Generated validators`);
const assertsFile = path.join(baseDir, "asserts/generated/index.js");
writeFile(assertsFile, format(generateAsserts(), assertsFile));
console.log(` ${chalk.green("✔")} Generated asserts`);
const constantsFile = path.join(baseDir, "constants/generated/index.js");
writeFile(constantsFile, format(generateConstants(), constantsFile));
console.log(` ${chalk.green("✔")} Generated constants`);

121
node_modules/@babel/types/scripts/generators/docs.js generated vendored Normal file
View file

@ -0,0 +1,121 @@
"use strict";
const util = require("util");
const stringifyValidator = require("../utils/stringifyValidator");
const toFunctionName = require("../utils/toFunctionName");
const types = require("../../");
const readme = [
`# @babel/types
> This module contains methods for building ASTs manually and for checking the types of AST nodes.
## Install
\`\`\`sh
npm install --save-dev @babel/types
\`\`\`
## API`,
];
const customTypes = {
ClassMethod: {
key: "if computed then `Expression` else `Identifier | Literal`",
},
Identifier: {
name: "`string`",
},
MemberExpression: {
property: "if computed then `Expression` else `Identifier`",
},
ObjectMethod: {
key: "if computed then `Expression` else `Identifier | Literal`",
},
ObjectProperty: {
key: "if computed then `Expression` else `Identifier | Literal`",
},
};
Object.keys(types.BUILDER_KEYS)
.sort()
.forEach(function (key) {
readme.push("### " + key[0].toLowerCase() + key.substr(1));
readme.push("```javascript");
readme.push(
"t." +
toFunctionName(key) +
"(" +
types.BUILDER_KEYS[key].join(", ") +
")"
);
readme.push("```");
readme.push("");
readme.push(
"See also `t.is" +
key +
"(node, opts)` and `t.assert" +
key +
"(node, opts)`."
);
readme.push("");
if (types.ALIAS_KEYS[key] && types.ALIAS_KEYS[key].length) {
readme.push(
"Aliases: " +
types.ALIAS_KEYS[key]
.map(function (key) {
return "`" + key + "`";
})
.join(", ")
);
readme.push("");
}
Object.keys(types.NODE_FIELDS[key])
.sort(function (fieldA, fieldB) {
const indexA = types.BUILDER_KEYS[key].indexOf(fieldA);
const indexB = types.BUILDER_KEYS[key].indexOf(fieldB);
if (indexA === indexB) return fieldA < fieldB ? -1 : 1;
if (indexA === -1) return 1;
if (indexB === -1) return -1;
return indexA - indexB;
})
.forEach(function (field) {
const defaultValue = types.NODE_FIELDS[key][field].default;
const fieldDescription = ["`" + field + "`"];
const validator = types.NODE_FIELDS[key][field].validate;
if (customTypes[key] && customTypes[key][field]) {
fieldDescription.push(`: ${customTypes[key][field]}`);
} else if (validator) {
try {
fieldDescription.push(
": `" + stringifyValidator(validator, "") + "`"
);
} catch (ex) {
if (ex.code === "UNEXPECTED_VALIDATOR_TYPE") {
console.log(
"Unrecognised validator type for " + key + "." + field
);
console.dir(ex.validator, { depth: 10, colors: true });
}
}
}
if (defaultValue !== null || types.NODE_FIELDS[key][field].optional) {
fieldDescription.push(
" (default: `" + util.inspect(defaultValue) + "`"
);
if (types.BUILDER_KEYS[key].indexOf(field) < 0) {
fieldDescription.push(", excluded from builder function");
}
fieldDescription.push(")");
} else {
fieldDescription.push(" (required)");
}
readme.push(" - " + fieldDescription.join(""));
});
readme.push("");
readme.push("---");
readme.push("");
});
process.stdout.write(readme.join("\n"));

248
node_modules/@babel/types/scripts/generators/flow.js generated vendored Normal file
View file

@ -0,0 +1,248 @@
"use strict";
const t = require("../../");
const stringifyValidator = require("../utils/stringifyValidator");
const toFunctionName = require("../utils/toFunctionName");
const NODE_PREFIX = "BabelNode";
let code = `// NOTE: This file is autogenerated. Do not modify.
// See packages/babel-types/scripts/generators/flow.js for script used.
declare class ${NODE_PREFIX}Comment {
value: string;
start: number;
end: number;
loc: ${NODE_PREFIX}SourceLocation;
}
declare class ${NODE_PREFIX}CommentBlock extends ${NODE_PREFIX}Comment {
type: "CommentBlock";
}
declare class ${NODE_PREFIX}CommentLine extends ${NODE_PREFIX}Comment {
type: "CommentLine";
}
declare class ${NODE_PREFIX}SourceLocation {
start: {
line: number;
column: number;
};
end: {
line: number;
column: number;
};
}
declare class ${NODE_PREFIX} {
leadingComments?: Array<${NODE_PREFIX}Comment>;
innerComments?: Array<${NODE_PREFIX}Comment>;
trailingComments?: Array<${NODE_PREFIX}Comment>;
start: ?number;
end: ?number;
loc: ?${NODE_PREFIX}SourceLocation;
}\n\n`;
//
const lines = [];
for (const type in t.NODE_FIELDS) {
const fields = t.NODE_FIELDS[type];
const struct = ['type: "' + type + '";'];
const args = [];
const builderNames = t.BUILDER_KEYS[type];
Object.keys(t.NODE_FIELDS[type])
.sort((fieldA, fieldB) => {
const indexA = t.BUILDER_KEYS[type].indexOf(fieldA);
const indexB = t.BUILDER_KEYS[type].indexOf(fieldB);
if (indexA === indexB) return fieldA < fieldB ? -1 : 1;
if (indexA === -1) return 1;
if (indexB === -1) return -1;
return indexA - indexB;
})
.forEach(fieldName => {
const field = fields[fieldName];
let suffix = "";
if (field.optional || field.default != null) suffix += "?";
let typeAnnotation = "any";
const validate = field.validate;
if (validate) {
typeAnnotation = stringifyValidator(validate, NODE_PREFIX);
}
if (typeAnnotation) {
suffix += ": " + typeAnnotation;
}
if (builderNames.includes(fieldName)) {
args.push(t.toBindingIdentifierName(fieldName) + suffix);
}
if (t.isValidIdentifier(fieldName)) {
struct.push(fieldName + suffix + ";");
}
});
code += `declare class ${NODE_PREFIX}${type} extends ${NODE_PREFIX} {
${struct.join("\n ").trim()}
}\n\n`;
// Flow chokes on super() and import() :/
if (type !== "Super" && type !== "Import") {
lines.push(
`declare function ${toFunctionName(type)}(${args.join(
", "
)}): ${NODE_PREFIX}${type};`
);
} else {
const functionName = toFunctionName(type);
lines.push(
`declare function _${functionName}(${args.join(
", "
)}): ${NODE_PREFIX}${type};`,
`declare export { _${functionName} as ${functionName} }`
);
}
}
for (let i = 0; i < t.TYPES.length; i++) {
let decl = `declare function is${t.TYPES[i]}(node: ?Object, opts?: ?Object): boolean`;
if (t.NODE_FIELDS[t.TYPES[i]]) {
decl += ` %checks (node instanceof ${NODE_PREFIX}${t.TYPES[i]})`;
}
lines.push(decl);
}
lines.push(
// builders/
// eslint-disable-next-line max-len
`declare function createTypeAnnotationBasedOnTypeof(type: 'string' | 'number' | 'undefined' | 'boolean' | 'function' | 'object' | 'symbol'): ${NODE_PREFIX}TypeAnnotation`,
// eslint-disable-next-line max-len
`declare function createUnionTypeAnnotation(types: Array<${NODE_PREFIX}FlowType>): ${NODE_PREFIX}UnionTypeAnnotation`,
// eslint-disable-next-line max-len
`declare function createFlowUnionType(types: Array<${NODE_PREFIX}FlowType>): ${NODE_PREFIX}UnionTypeAnnotation`,
// this smells like "internal API"
// eslint-disable-next-line max-len
`declare function buildChildren(node: { children: Array<${NODE_PREFIX}JSXText | ${NODE_PREFIX}JSXExpressionContainer | ${NODE_PREFIX}JSXSpreadChild | ${NODE_PREFIX}JSXElement | ${NODE_PREFIX}JSXFragment | ${NODE_PREFIX}JSXEmptyExpression> }): Array<${NODE_PREFIX}JSXText | ${NODE_PREFIX}JSXExpressionContainer | ${NODE_PREFIX}JSXSpreadChild | ${NODE_PREFIX}JSXElement | ${NODE_PREFIX}JSXFragment>`,
// clone/
`declare function clone<T>(n: T): T;`,
`declare function cloneDeep<T>(n: T): T;`,
`declare function cloneDeepWithoutLoc<T>(n: T): T;`,
`declare function cloneNode<T>(n: T, deep?: boolean, withoutLoc?: boolean): T;`,
`declare function cloneWithoutLoc<T>(n: T): T;`,
// comments/
`declare type CommentTypeShorthand = 'leading' | 'inner' | 'trailing'`,
// eslint-disable-next-line max-len
`declare function addComment<T: Node>(node: T, type: CommentTypeShorthand, content: string, line?: boolean): T`,
// eslint-disable-next-line max-len
`declare function addComments<T: Node>(node: T, type: CommentTypeShorthand, comments: Array<Comment>): T`,
`declare function inheritInnerComments(node: Node, parent: Node): void`,
`declare function inheritLeadingComments(node: Node, parent: Node): void`,
`declare function inheritsComments<T: Node>(node: T, parent: Node): void`,
`declare function inheritTrailingComments(node: Node, parent: Node): void`,
`declare function removeComments<T: Node>(node: T): T`,
// converters/
`declare function ensureBlock(node: ${NODE_PREFIX}, key: string): ${NODE_PREFIX}BlockStatement`,
`declare function toBindingIdentifierName(name?: ?string): string`,
// eslint-disable-next-line max-len
`declare function toBlock(node: ${NODE_PREFIX}Statement | ${NODE_PREFIX}Expression, parent?: ${NODE_PREFIX}Function | null): ${NODE_PREFIX}BlockStatement`,
// eslint-disable-next-line max-len
`declare function toComputedKey(node: ${NODE_PREFIX}Method | ${NODE_PREFIX}Property, key?: ${NODE_PREFIX}Expression | ${NODE_PREFIX}Identifier): ${NODE_PREFIX}Expression`,
// eslint-disable-next-line max-len
`declare function toExpression(node: ${NODE_PREFIX}ExpressionStatement | ${NODE_PREFIX}Expression | ${NODE_PREFIX}Class | ${NODE_PREFIX}Function): ${NODE_PREFIX}Expression`,
`declare function toIdentifier(name?: ?string): string`,
// eslint-disable-next-line max-len
`declare function toKeyAlias(node: ${NODE_PREFIX}Method | ${NODE_PREFIX}Property, key?: ${NODE_PREFIX}): string`,
// toSequenceExpression relies on types that aren't declared in flow
// eslint-disable-next-line max-len
`declare function toStatement(node: ${NODE_PREFIX}Statement | ${NODE_PREFIX}Class | ${NODE_PREFIX}Function | ${NODE_PREFIX}AssignmentExpression, ignore?: boolean): ${NODE_PREFIX}Statement | void`,
`declare function valueToNode(value: any): ${NODE_PREFIX}Expression`,
// modifications/
// eslint-disable-next-line max-len
`declare function removeTypeDuplicates(types: Array<${NODE_PREFIX}FlowType>): Array<${NODE_PREFIX}FlowType>`,
// eslint-disable-next-line max-len
`declare function appendToMemberExpression(member: ${NODE_PREFIX}MemberExpression, append: ${NODE_PREFIX}, computed?: boolean): ${NODE_PREFIX}MemberExpression`,
// eslint-disable-next-line max-len
`declare function inherits<T: Node>(child: T, parent: ${NODE_PREFIX} | null | void): T`,
// eslint-disable-next-line max-len
`declare function prependToMemberExpression(member: ${NODE_PREFIX}MemberExpression, prepend: ${NODE_PREFIX}Expression): ${NODE_PREFIX}MemberExpression`,
`declare function removeProperties<T>(n: T, opts: ?{}): void;`,
`declare function removePropertiesDeep<T>(n: T, opts: ?{}): T;`,
// retrievers/
// eslint-disable-next-line max-len
`declare function getBindingIdentifiers(node: ${NODE_PREFIX}, duplicates: boolean, outerOnly?: boolean): { [key: string]: ${NODE_PREFIX}Identifier | Array<${NODE_PREFIX}Identifier> }`,
// eslint-disable-next-line max-len
`declare function getOuterBindingIdentifiers(node: Node, duplicates: boolean): { [key: string]: ${NODE_PREFIX}Identifier | Array<${NODE_PREFIX}Identifier> }`,
// traverse/
`declare type TraversalAncestors = Array<{
node: BabelNode,
key: string,
index?: number,
}>;
declare type TraversalHandler<T> = (BabelNode, TraversalAncestors, T) => void;
declare type TraversalHandlers<T> = {
enter?: TraversalHandler<T>,
exit?: TraversalHandler<T>,
};`.replace(/(^|\n) {2}/g, "$1"),
// eslint-disable-next-line
`declare function traverse<T>(n: BabelNode, TraversalHandler<T> | TraversalHandlers<T>, state?: T): void;`,
`declare function traverseFast<T>(n: Node, h: TraversalHandler<T>, state?: T): void;`,
// utils/
// cleanJSXElementLiteralChild is not exported
// inherit is not exported
`declare function shallowEqual(actual: Object, expected: Object): boolean`,
// validators/
// eslint-disable-next-line max-len
`declare function buildMatchMemberExpression(match: string, allowPartial?: boolean): (?BabelNode) => boolean`,
`declare function is(type: string, n: BabelNode, opts: Object): boolean;`,
`declare function isBinding(node: BabelNode, parent: BabelNode, grandparent?: BabelNode): boolean`,
`declare function isBlockScoped(node: BabelNode): boolean`,
`declare function isImmutable(node: BabelNode): boolean`,
`declare function isLet(node: BabelNode): boolean`,
`declare function isNode(node: ?Object): boolean`,
`declare function isNodesEquivalent(a: any, b: any): boolean`,
`declare function isPlaceholderType(placeholderType: string, targetType: string): boolean`,
`declare function isReferenced(node: BabelNode, parent: BabelNode, grandparent?: BabelNode): boolean`,
`declare function isScope(node: BabelNode, parent: BabelNode): boolean`,
`declare function isSpecifierDefault(specifier: BabelNodeModuleSpecifier): boolean`,
`declare function isType(nodetype: ?string, targetType: string): boolean`,
`declare function isValidES3Identifier(name: string): boolean`,
`declare function isValidES3Identifier(name: string): boolean`,
`declare function isValidIdentifier(name: string): boolean`,
`declare function isVar(node: BabelNode): boolean`,
// eslint-disable-next-line max-len
`declare function matchesPattern(node: ?BabelNode, match: string | Array<string>, allowPartial?: boolean): boolean`,
`declare function validate(n: BabelNode, key: string, value: mixed): void;`
);
for (const type in t.FLIPPED_ALIAS_KEYS) {
const types = t.FLIPPED_ALIAS_KEYS[type];
code += `type ${NODE_PREFIX}${type} = ${types
.map(type => `${NODE_PREFIX}${type}`)
.join(" | ")};\n`;
}
code += `\ndeclare module "@babel/types" {
${lines.join("\n").replace(/\n/g, "\n ").trim()}
}\n`;
//
process.stdout.write(code);

View file

@ -0,0 +1,44 @@
"use strict";
const definitions = require("../../lib/definitions");
function addAssertHelper(type) {
return `export function assert${type}(node: Object, opts?: Object = {}): void {
assert("${type}", node, opts) }
`;
}
module.exports = function generateAsserts() {
let output = `// @flow
/*
* This file is auto-generated! Do not modify it directly.
* To re-generate run 'make build'
*/
import is from "../../validators/is";
function assert(type: string, node: Object, opts?: Object): void {
if (!is(type, node, opts)) {
throw new Error(
\`Expected type "\${type}" with option \${JSON.stringify((opts: any))}, \` +
\`but instead got "\${node.type}".\`,
);
}
}\n\n`;
Object.keys(definitions.VISITOR_KEYS).forEach(type => {
output += addAssertHelper(type);
});
Object.keys(definitions.FLIPPED_ALIAS_KEYS).forEach(type => {
output += addAssertHelper(type);
});
Object.keys(definitions.DEPRECATED_KEYS).forEach(type => {
const newType = definitions.DEPRECATED_KEYS[type];
output += `export function assert${type}(node: Object, opts: Object): void {
console.trace("The node type ${type} has been renamed to ${newType}");
assert("${type}", node, opts);
}\n`;
});
return output;
};

View file

@ -0,0 +1,57 @@
"use strict";
const definitions = require("../../lib/definitions");
const formatBuilderName = require("../utils/formatBuilderName");
const lowerFirst = require("../utils/lowerFirst");
module.exports = function generateBuilders() {
let output = `// @flow
/*
* This file is auto-generated! Do not modify it directly.
* To re-generate run 'make build'
*/
import builder from "../builder";\n\n`;
const reservedNames = new Set(["super", "import"]);
Object.keys(definitions.BUILDER_KEYS).forEach(type => {
const formatedBuilderName = formatBuilderName(type);
const formatedBuilderNameLocal = reservedNames.has(formatedBuilderName)
? `_${formatedBuilderName}`
: formatedBuilderName;
output += `${
formatedBuilderNameLocal === formatedBuilderName ? "export " : ""
}function ${formatedBuilderNameLocal}(...args: Array<any>): Object { return builder("${type}", ...args); }\n`;
// This is needed for backwards compatibility.
// arrayExpression -> ArrayExpression
output += `export { ${formatedBuilderNameLocal} as ${type} };\n`;
if (formatedBuilderNameLocal !== formatedBuilderName) {
output += `export { ${formatedBuilderNameLocal} as ${formatedBuilderName} };\n`;
}
// This is needed for backwards compatibility.
// It should be removed in the next major version.
// JSXIdentifier -> jSXIdentifier
if (/^[A-Z]{2}/.test(type)) {
output += `export { ${formatedBuilderNameLocal} as ${lowerFirst(
type
)} }\n`;
}
});
Object.keys(definitions.DEPRECATED_KEYS).forEach(type => {
const newType = definitions.DEPRECATED_KEYS[type];
output += `export function ${type}(...args: Array<any>): Object {
console.trace("The node type ${type} has been renamed to ${newType}");
return builder("${type}", ...args);
}
export { ${type} as ${formatBuilderName(type)} };\n`;
// This is needed for backwards compatibility.
// It should be removed in the next major version.
// JSXIdentifier -> jSXIdentifier
if (/^[A-Z]{2}/.test(type)) {
output += `export { ${type} as ${lowerFirst(type)} }\n`;
}
});
return output;
};

View file

@ -0,0 +1,17 @@
"use strict";
const definitions = require("../../lib/definitions");
module.exports = function generateConstants() {
let output = `// @flow
/*
* This file is auto-generated! Do not modify it directly.
* To re-generate run 'make build'
*/
import { FLIPPED_ALIAS_KEYS } from "../../definitions";\n\n`;
Object.keys(definitions.FLIPPED_ALIAS_KEYS).forEach(type => {
output += `export const ${type.toUpperCase()}_TYPES = FLIPPED_ALIAS_KEYS["${type}"];\n`;
});
return output;
};

View file

@ -0,0 +1,78 @@
"use strict";
const definitions = require("../../lib/definitions");
const has = Function.call.bind(Object.prototype.hasOwnProperty);
function joinComparisons(leftArr, right) {
return (
leftArr.map(JSON.stringify).join(` === ${right} || `) + ` === ${right}`
);
}
function addIsHelper(type, aliasKeys, deprecated) {
const targetType = JSON.stringify(type);
let aliasSource = "";
if (aliasKeys) {
aliasSource = " || " + joinComparisons(aliasKeys, "nodeType");
}
let placeholderSource = "";
const placeholderTypes = [];
if (
definitions.PLACEHOLDERS.includes(type) &&
has(definitions.FLIPPED_ALIAS_KEYS, type)
) {
placeholderTypes.push(type);
}
if (has(definitions.PLACEHOLDERS_FLIPPED_ALIAS, type)) {
placeholderTypes.push(...definitions.PLACEHOLDERS_FLIPPED_ALIAS[type]);
}
if (placeholderTypes.length > 0) {
placeholderSource =
' || nodeType === "Placeholder" && (' +
joinComparisons(placeholderTypes, "node.expectedNode") +
")";
}
return `export function is${type}(node: ?Object, opts?: Object): boolean {
${deprecated || ""}
if (!node) return false;
const nodeType = node.type;
if (nodeType === ${targetType}${aliasSource}${placeholderSource}) {
if (typeof opts === "undefined") {
return true;
} else {
return shallowEqual(node, opts);
}
}
return false;
}
`;
}
module.exports = function generateValidators() {
let output = `// @flow
/*
* This file is auto-generated! Do not modify it directly.
* To re-generate run 'make build'
*/
import shallowEqual from "../../utils/shallowEqual";\n\n`;
Object.keys(definitions.VISITOR_KEYS).forEach(type => {
output += addIsHelper(type);
});
Object.keys(definitions.FLIPPED_ALIAS_KEYS).forEach(type => {
output += addIsHelper(type, definitions.FLIPPED_ALIAS_KEYS[type]);
});
Object.keys(definitions.DEPRECATED_KEYS).forEach(type => {
const newType = definitions.DEPRECATED_KEYS[type];
const deprecated = `console.trace("The node type ${type} has been renamed to ${newType}");`;
output += addIsHelper(type, null, deprecated);
});
return output;
};

View file

@ -0,0 +1,364 @@
"use strict";
const t = require("../../");
const stringifyValidator = require("../utils/stringifyValidator");
const toFunctionName = require("../utils/toFunctionName");
let code = `// NOTE: This file is autogenerated. Do not modify.
// See packages/babel-types/scripts/generators/typescript.js for script used.
interface BaseComment {
value: string;
start: number;
end: number;
loc: SourceLocation;
type: "CommentBlock" | "CommentLine";
}
export interface CommentBlock extends BaseComment {
type: "CommentBlock";
}
export interface CommentLine extends BaseComment {
type: "CommentLine";
}
export type Comment = CommentBlock | CommentLine;
export interface SourceLocation {
start: {
line: number;
column: number;
};
end: {
line: number;
column: number;
};
}
interface BaseNode {
leadingComments: ReadonlyArray<Comment> | null;
innerComments: ReadonlyArray<Comment> | null;
trailingComments: ReadonlyArray<Comment> | null;
start: number | null;
end: number | null;
loc: SourceLocation | null;
type: Node["type"];
}
export type Node = ${t.TYPES.sort().join(" | ")};\n\n`;
//
const lines = [];
for (const type in t.NODE_FIELDS) {
const fields = t.NODE_FIELDS[type];
const fieldNames = sortFieldNames(Object.keys(t.NODE_FIELDS[type]), type);
const builderNames = t.BUILDER_KEYS[type];
const struct = ['type: "' + type + '";'];
const args = [];
fieldNames.forEach(fieldName => {
const field = fields[fieldName];
// Future / annoying TODO:
// MemberExpression.property, ObjectProperty.key and ObjectMethod.key need special cases; either:
// - convert the declaration to chain() like ClassProperty.key and ClassMethod.key,
// - declare an alias type for valid keys, detect the case and reuse it here,
// - declare a disjoint union with, for example, ObjectPropertyBase,
// ObjectPropertyLiteralKey and ObjectPropertyComputedKey, and declare ObjectProperty
// as "ObjectPropertyBase & (ObjectPropertyLiteralKey | ObjectPropertyComputedKey)"
let typeAnnotation = stringifyValidator(field.validate, "");
if (isNullable(field) && !hasDefault(field)) {
typeAnnotation += " | null";
}
if (builderNames.includes(fieldName)) {
if (areAllRemainingFieldsNullable(fieldName, builderNames, fields)) {
args.push(
`${t.toBindingIdentifierName(fieldName)}${
isNullable(field) ? "?:" : ":"
} ${typeAnnotation}`
);
} else {
args.push(
`${t.toBindingIdentifierName(fieldName)}: ${typeAnnotation}${
isNullable(field) ? " | undefined" : ""
}`
);
}
}
const alphaNumeric = /^\w+$/;
if (t.isValidIdentifier(fieldName) || alphaNumeric.test(fieldName)) {
struct.push(`${fieldName}: ${typeAnnotation};`);
} else {
struct.push(`"${fieldName}": ${typeAnnotation};`);
}
});
code += `export interface ${type} extends BaseNode {
${struct.join("\n ").trim()}
}\n\n`;
// super and import are reserved words in JavaScript
if (type !== "Super" && type !== "Import") {
lines.push(
`export function ${toFunctionName(type)}(${args.join(", ")}): ${type};`
);
} else {
const functionName = toFunctionName(type);
lines.push(
`declare function _${functionName}(${args.join(", ")}): ${type};`,
`export { _${functionName} as ${functionName}}`
);
}
}
for (const typeName of t.TYPES) {
const result =
t.NODE_FIELDS[typeName] || t.FLIPPED_ALIAS_KEYS[typeName]
? `node is ${typeName}`
: "boolean";
lines.push(
`export function is${typeName}(node: object | null | undefined, opts?: object | null): ${result};`,
// TypeScript 3.7: https://github.com/microsoft/TypeScript/pull/32695 will allow assert declarations
// eslint-disable-next-line max-len
`// export function assert${typeName}(node: object | null | undefined, opts?: object | null): asserts ${
result === "boolean" ? "node" : result
};`
);
}
lines.push(
// assert/
// Commented out as this declaration requires TypeScript 3.7 (what do?)
`// export function assertNode(obj: any): asserts obj is Node`,
// builders/
// eslint-disable-next-line max-len
`export function createTypeAnnotationBasedOnTypeof(type: 'string' | 'number' | 'undefined' | 'boolean' | 'function' | 'object' | 'symbol'): StringTypeAnnotation | VoidTypeAnnotation | NumberTypeAnnotation | BooleanTypeAnnotation | GenericTypeAnnotation`,
`export function createUnionTypeAnnotation<T extends FlowType>(types: [T]): T`,
`export function createFlowUnionType<T extends FlowType>(types: [T]): T`,
// this probably misbehaves if there are 0 elements, and it's not a UnionTypeAnnotation if there's only 1
// it is possible to require "2 or more" for this overload ([T, T, ...T[]]) but it requires typescript 3.0
`export function createUnionTypeAnnotation(types: ReadonlyArray<FlowType>): UnionTypeAnnotation`,
`export function createFlowUnionType(types: ReadonlyArray<FlowType>): UnionTypeAnnotation`,
// this smells like "internal API"
// eslint-disable-next-line max-len
`export function buildChildren(node: { children: ReadonlyArray<JSXText | JSXExpressionContainer | JSXSpreadChild | JSXElement | JSXFragment | JSXEmptyExpression> }): JSXElement['children']`,
// clone/
`export function clone<T extends Node>(n: T): T;`,
`export function cloneDeep<T extends Node>(n: T): T;`,
`export function cloneDeepWithoutLoc<T extends Node>(n: T): T;`,
`export function cloneNode<T extends Node>(n: T, deep?: boolean, withoutLoc?: boolean): T;`,
`export function cloneWithoutLoc<T extends Node>(n: T): T;`,
// comments/
`export type CommentTypeShorthand = 'leading' | 'inner' | 'trailing'`,
// eslint-disable-next-line max-len
`export function addComment<T extends Node>(node: T, type: CommentTypeShorthand, content: string, line?: boolean): T`,
// eslint-disable-next-line max-len
`export function addComments<T extends Node>(node: T, type: CommentTypeShorthand, comments: ReadonlyArray<Comment>): T`,
`export function inheritInnerComments(node: Node, parent: Node): void`,
`export function inheritLeadingComments(node: Node, parent: Node): void`,
`export function inheritsComments<T extends Node>(node: T, parent: Node): void`,
`export function inheritTrailingComments(node: Node, parent: Node): void`,
`export function removeComments<T extends Node>(node: T): T`,
// converters/
// eslint-disable-next-line max-len
`export function ensureBlock(node: Extract<Node, { body: BlockStatement | Statement | Expression }>): BlockStatement`,
// too complex?
// eslint-disable-next-line max-len
`export function ensureBlock<K extends keyof Extract<Node, { body: BlockStatement | Statement | Expression }> = 'body'>(node: Extract<Node, Record<K, BlockStatement | Statement | Expression>>, key: K): BlockStatement`,
// gatherSequenceExpressions is not exported
`export function toBindingIdentifierName(name: { toString(): string } | null | undefined): string`,
`export function toBlock(node: Statement | Expression, parent?: Function | null): BlockStatement`,
// it is possible for `node` to be an arbitrary object if `key` is always provided,
// but that doesn't look like intended API
// eslint-disable-next-line max-len
`export function toComputedKey<T extends Extract<Node, { computed: boolean | null }>>(node: T, key?: Expression | Identifier): Expression`,
`export function toExpression(node: Function): FunctionExpression`,
`export function toExpression(node: Class): ClassExpression`,
`export function toExpression(node: ExpressionStatement | Expression | Class | Function): Expression`,
`export function toIdentifier(name: { toString(): string } | null | undefined): string`,
`export function toKeyAlias(node: Method | Property, key?: Node): string`,
// NOTE: this actually uses Scope from @babel/traverse, but we can't add a dependency on its types,
// as they live in @types. Declare the structural subset that is required.
// eslint-disable-next-line max-len
`export function toSequenceExpression(nodes: ReadonlyArray<Node>, scope: { push(value: { id: LVal; kind: 'var'; init?: Expression}): void; buildUndefinedNode(): Node }): SequenceExpression | undefined`,
`export function toStatement(node: AssignmentExpression, ignore?: boolean): ExpressionStatement`,
`export function toStatement(node: Statement | AssignmentExpression, ignore?: boolean): Statement`,
`export function toStatement(node: Class, ignore: true): ClassDeclaration | undefined`,
`export function toStatement(node: Class, ignore?: boolean): ClassDeclaration`,
`export function toStatement(node: Function, ignore: true): FunctionDeclaration | undefined`,
`export function toStatement(node: Function, ignore?: boolean): FunctionDeclaration`,
// eslint-disable-next-line max-len
`export function toStatement(node: Statement | Class | Function | AssignmentExpression, ignore: true): Statement | undefined`,
// eslint-disable-next-line max-len
`export function toStatement(node: Statement | Class | Function | AssignmentExpression, ignore?: boolean): Statement`,
// eslint-disable-next-line max-len
`export function valueToNode(value: undefined): Identifier`, // (should this not be a UnaryExpression to avoid shadowing?)
`export function valueToNode(value: boolean): BooleanLiteral`,
`export function valueToNode(value: null): NullLiteral`,
`export function valueToNode(value: string): StringLiteral`,
// Infinities and NaN need to use a BinaryExpression; negative values must be wrapped in UnaryExpression
`export function valueToNode(value: number): NumericLiteral | BinaryExpression | UnaryExpression`,
`export function valueToNode(value: RegExp): RegExpLiteral`,
// eslint-disable-next-line max-len
`export function valueToNode(value: ReadonlyArray<undefined | boolean | null | string | number | RegExp | object>): ArrayExpression`,
// this throws with objects that are not PlainObject according to lodash,
// or if there are non-valueToNode-able values
`export function valueToNode(value: object): ObjectExpression`,
// eslint-disable-next-line max-len
`export function valueToNode(value: undefined | boolean | null | string | number | RegExp | object): Expression`,
// modifications/
// eslint-disable-next-line max-len
`export function removeTypeDuplicates(types: ReadonlyArray<FlowType | false | null | undefined>): FlowType[]`,
// eslint-disable-next-line max-len
`export function appendToMemberExpression<T extends Pick<MemberExpression, 'object' | 'property'>>(member: T, append: MemberExpression['property'], computed?: boolean): T`,
// eslint-disable-next-line max-len
`export function inherits<T extends Node | null | undefined>(child: T, parent: Node | null | undefined): T`,
// eslint-disable-next-line max-len
`export function prependToMemberExpression<T extends Pick<MemberExpression, 'object' | 'property'>>(member: T, prepend: MemberExpression['object']): T`,
`export function removeProperties(
n: Node,
opts?: { preserveComments: boolean } | null
): void;`,
`export function removePropertiesDeep<T extends Node>(
n: T,
opts?: { preserveComments: boolean } | null
): T;`,
// retrievers/
// eslint-disable-next-line max-len
`export function getBindingIdentifiers(node: Node, duplicates: true, outerOnly?: boolean): Record<string, Array<Identifier>>`,
// eslint-disable-next-line max-len
`export function getBindingIdentifiers(node: Node, duplicates?: false, outerOnly?: boolean): Record<string, Identifier>`,
// eslint-disable-next-line max-len
`export function getBindingIdentifiers(node: Node, duplicates: boolean, outerOnly?: boolean): Record<string, Identifier | Array<Identifier>>`,
// eslint-disable-next-line max-len
`export function getOuterBindingIdentifiers(node: Node, duplicates: true): Record<string, Array<Identifier>>`,
`export function getOuterBindingIdentifiers(node: Node, duplicates?: false): Record<string, Identifier>`,
// eslint-disable-next-line max-len
`export function getOuterBindingIdentifiers(node: Node, duplicates: boolean): Record<string, Identifier | Array<Identifier>>`,
// traverse/
`export type TraversalAncestors = ReadonlyArray<{
node: Node,
key: string,
index?: number,
}>;
export type TraversalHandler<T> = (
this: undefined, node: Node, parent: TraversalAncestors, type: T
) => void;
export type TraversalHandlers<T> = {
enter?: TraversalHandler<T>,
exit?: TraversalHandler<T>,
};`.replace(/(^|\n) {2}/g, "$1"),
// eslint-disable-next-line
`export function traverse<T>(n: Node, h: TraversalHandler<T> | TraversalHandlers<T>, state?: T): void;`,
`export function traverseFast<T>(n: Node, h: TraversalHandler<T>, state?: T): void;`,
// utils/
// cleanJSXElementLiteralChild is not exported
// inherit is not exported
`export function shallowEqual<T extends object>(actual: object, expected: T): actual is T`,
// validators/
// eslint-disable-next-line max-len
`export function buildMatchMemberExpression(match: string, allowPartial?: boolean): (node: Node | null | undefined) => node is MemberExpression`,
// eslint-disable-next-line max-len
`export function is<T extends Node['type']>(type: T, n: Node | null | undefined, required?: undefined): n is Extract<Node, { type: T }>`,
// eslint-disable-next-line max-len
`export function is<T extends Node['type'], P extends Extract<Node, { type: T }>>(type: T, n: Node | null | undefined, required: Partial<P>): n is P`,
// eslint-disable-next-line max-len
`export function is<P extends Node>(type: string, n: Node | null | undefined, required: Partial<P>): n is P`,
`export function is(type: string, n: Node | null | undefined, required?: Partial<Node>): n is Node`,
`export function isBinding(node: Node, parent: Node, grandparent?: Node): boolean`,
// eslint-disable-next-line max-len
`export function isBlockScoped(node: Node): node is FunctionDeclaration | ClassDeclaration | VariableDeclaration`,
`export function isImmutable(node: Node): node is Immutable`,
`export function isLet(node: Node): node is VariableDeclaration`,
`export function isNode(node: object | null | undefined): node is Node`,
`export function isNodesEquivalent<T extends Partial<Node>>(a: T, b: any): b is T`,
`export function isNodesEquivalent(a: any, b: any): boolean`,
`export function isPlaceholderType(placeholderType: Node['type'], targetType: Node['type']): boolean`,
`export function isReferenced(node: Node, parent: Node, grandparent?: Node): boolean`,
`export function isScope(node: Node, parent: Node): node is Scopable`,
`export function isSpecifierDefault(specifier: ModuleSpecifier): boolean`,
`export function isType<T extends Node['type']>(nodetype: string, targetType: T): nodetype is T`,
`export function isType(nodetype: string | null | undefined, targetType: string): boolean`,
`export function isValidES3Identifier(name: string): boolean`,
`export function isValidIdentifier(name: string): boolean`,
`export function isVar(node: Node): node is VariableDeclaration`,
// the MemberExpression implication is incidental, but it follows from the implementation
// eslint-disable-next-line max-len
`export function matchesPattern(node: Node | null | undefined, match: string | ReadonlyArray<string>, allowPartial?: boolean): node is MemberExpression`,
// TypeScript 3.7: ": asserts n is T"
// eslint-disable-next-line max-len
`export function validate<T extends Node, K extends keyof T>(n: Node | null | undefined, key: K, value: T[K]): void`,
`export function validate(n: Node, key: string, value: any): void;`
);
for (const type in t.DEPRECATED_KEYS) {
code += `/**
* @deprecated Use \`${t.DEPRECATED_KEYS[type]}\`
*/
export type ${type} = ${t.DEPRECATED_KEYS[type]};\n
`;
}
for (const type in t.FLIPPED_ALIAS_KEYS) {
const types = t.FLIPPED_ALIAS_KEYS[type];
code += `export type ${type} = ${types
.map(type => `${type}`)
.join(" | ")};\n`;
}
code += "\n";
code += "export interface Aliases {\n";
for (const type in t.FLIPPED_ALIAS_KEYS) {
code += ` ${type}: ${type};\n`;
}
code += "}\n\n";
code += lines.join("\n") + "\n";
//
process.stdout.write(code);
//
function areAllRemainingFieldsNullable(fieldName, fieldNames, fields) {
const index = fieldNames.indexOf(fieldName);
return fieldNames.slice(index).every(_ => isNullable(fields[_]));
}
function hasDefault(field) {
return field.default != null;
}
function isNullable(field) {
return field.optional || hasDefault(field);
}
function sortFieldNames(fields, type) {
return fields.sort((fieldA, fieldB) => {
const indexA = t.BUILDER_KEYS[type].indexOf(fieldA);
const indexB = t.BUILDER_KEYS[type].indexOf(fieldB);
if (indexA === indexB) return fieldA < fieldB ? -1 : 1;
if (indexA === -1) return 1;
if (indexB === -1) return -1;
return indexA - indexB;
});
}

View file

@ -0,0 +1,10 @@
"use strict";
const toLowerCase = Function.call.bind("".toLowerCase);
module.exports = function formatBuilderName(type) {
// FunctionExpression -> functionExpression
// JSXIdentifier -> jsxIdentifier
// V8IntrinsicIdentifier -> v8IntrinsicIdentifier
return type.replace(/^([A-Z](?=[a-z0-9])|[A-Z]+(?=[A-Z]))/, toLowerCase);
};

View file

@ -0,0 +1,4 @@
"use strict";
module.exports = function lowerFirst(string) {
return string[0].toLowerCase() + string.slice(1);
};

View file

@ -0,0 +1,66 @@
module.exports = function stringifyValidator(validator, nodePrefix) {
if (validator === undefined) {
return "any";
}
if (validator.each) {
return `Array<${stringifyValidator(validator.each, nodePrefix)}>`;
}
if (validator.chainOf) {
return stringifyValidator(validator.chainOf[1], nodePrefix);
}
if (validator.oneOf) {
return validator.oneOf.map(JSON.stringify).join(" | ");
}
if (validator.oneOfNodeTypes) {
return validator.oneOfNodeTypes.map(_ => nodePrefix + _).join(" | ");
}
if (validator.oneOfNodeOrValueTypes) {
return validator.oneOfNodeOrValueTypes
.map(_ => {
return isValueType(_) ? _ : nodePrefix + _;
})
.join(" | ");
}
if (validator.type) {
return validator.type;
}
if (validator.shapeOf) {
return (
"{ " +
Object.keys(validator.shapeOf)
.map(shapeKey => {
const propertyDefinition = validator.shapeOf[shapeKey];
if (propertyDefinition.validate) {
const isOptional =
propertyDefinition.optional || propertyDefinition.default != null;
return (
shapeKey +
(isOptional ? "?: " : ": ") +
stringifyValidator(propertyDefinition.validate)
);
}
return null;
})
.filter(Boolean)
.join(", ") +
" }"
);
}
return ["any"];
};
/**
* Heuristic to decide whether or not the given type is a value type (eg. "null")
* or a Node type (eg. "Expression").
*/
function isValueType(type) {
return type.charAt(0).toLowerCase() === type.charAt(0);
}

View file

@ -0,0 +1,4 @@
module.exports = function toFunctionName(typeName) {
const _ = typeName.replace(/^TS/, "ts").replace(/^JSX/, "jsx");
return _.slice(0, 1).toLowerCase() + _.slice(1);
};