import * as t from "../../lib/index.js";
import stringifyValidator from "../utils/stringifyValidator.js";
export default function generateAstTypes() {
let code = `// NOTE: This file is autogenerated. Do not modify.
// See packages/babel-types/scripts/generators/ast-types.js for script used.
interface BaseComment {
value: string;
start?: number;
end?: number;
loc?: SourceLocation;
// generator will skip the comment if ignore is true
ignore?: boolean;
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 {
type: Node["type"];
leadingComments?: Comment[] | null;
innerComments?: Comment[] | null;
trailingComments?: Comment[] | null;
start?: number | null;
end?: number | null;
loc?: SourceLocation | null;
range?: [number, number];
extra?: Record<string, unknown>;
}
export type CommentTypeShorthand = "leading" | "inner" | "trailing";
export type Node = ${t.TYPES.filter(k => !t.FLIPPED_ALIAS_KEYS[k])
.sort()
.join(" | ")};\n\n`;
const deprecatedAlias = {};
for (const type in t.DEPRECATED_KEYS) {
deprecatedAlias[t.DEPRECATED_KEYS[type]] = type;
}
for (const type in t.NODE_FIELDS) {
const fields = t.NODE_FIELDS[type];
const fieldNames = sortFieldNames(Object.keys(t.NODE_FIELDS[type]), type);
const struct = [];
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";
}
const alphaNumeric = /^\w+$/;
const optional = field.optional ? "?" : "";
if (t.isValidIdentifier(fieldName) || alphaNumeric.test(fieldName)) {
struct.push(`${fieldName}${optional}: ${typeAnnotation};`);
} else {
struct.push(`"${fieldName}"${optional}: ${typeAnnotation};`);
}
});
code += `export interface ${type} extends BaseNode {
type: "${type}";
${struct.join("\n ").trim()}
}\n\n`;
if (deprecatedAlias[type]) {
code += `/**
* @deprecated Use \`${type}\`
*/
export interface ${deprecatedAlias[type]} extends BaseNode {
type: "${deprecatedAlias[type]}";
${struct.join("\n ").trim()}
}\n\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 += `export type DeprecatedAliases = ${Object.keys(
t.DEPRECATED_KEYS
).join(" | ")}\n\n`;
return code;
}
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;
});
}
import * as t from "../../lib/index.js";
import * as definitions from "../../lib/definitions/index.js";
import formatBuilderName from "../utils/formatBuilderName.js";
import lowerFirst from "../utils/lowerFirst.js";
import stringifyValidator from "../utils/stringifyValidator.js";
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;
});
}
function generateBuilderArgs(type) {
const fields = t.NODE_FIELDS[type];
const fieldNames = sortFieldNames(Object.keys(t.NODE_FIELDS[type]), type);
const builderNames = t.BUILDER_KEYS[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, "t.");
if (isNullable(field) && !hasDefault(field)) {
typeAnnotation += " | null";
}
if (builderNames.includes(fieldName)) {
const field = definitions.NODE_FIELDS[type][fieldName];
const def = JSON.stringify(field.default);
const bindingIdentifierName = t.toBindingIdentifierName(fieldName);
let arg;
if (areAllRemainingFieldsNullable(fieldName, builderNames, fields)) {
arg = `${bindingIdentifierName}${
isNullable(field) && !def ? "?:" : ":"
} ${typeAnnotation}`;
} else {
arg = `${bindingIdentifierName}: ${typeAnnotation}${
isNullable(field) ? " | undefined" : ""
}`;
}
if (def !== "null" || isNullable(field)) {
arg += `= ${def}`;
}
args.push(arg);
}
});
return args;
}
export default function generateBuilders(kind) {
return kind === "uppercase.js"
? generateUppercaseBuilders()
: generateLowercaseBuilders();
}
function generateLowercaseBuilders() {
let output = `/*
* This file is auto-generated! Do not modify it directly.
* To re-generate run 'make build'
*/
import validateNode from "../validateNode";
import type * as t from "../..";
`;
const reservedNames = new Set(["super", "import"]);
Object.keys(definitions.BUILDER_KEYS).forEach(type => {
const defArgs = generateBuilderArgs(type);
const formatedBuilderName = formatBuilderName(type);
const formatedBuilderNameLocal = reservedNames.has(formatedBuilderName)
? `_${formatedBuilderName}`
: formatedBuilderName;
const fieldNames = sortFieldNames(
Object.keys(definitions.NODE_FIELDS[type]),
type
);
const builderNames = definitions.BUILDER_KEYS[type];
const objectFields = [["type", JSON.stringify(type)]];
fieldNames.forEach(fieldName => {
const field = definitions.NODE_FIELDS[type][fieldName];
if (builderNames.includes(fieldName)) {
const bindingIdentifierName = t.toBindingIdentifierName(fieldName);
objectFields.push([fieldName, bindingIdentifierName]);
} else if (!field.optional) {
const def = JSON.stringify(field.default);
objectFields.push([fieldName, def]);
}
});
output += `${
formatedBuilderNameLocal === formatedBuilderName ? "export " : ""
}function ${formatedBuilderNameLocal}(${defArgs.join(", ")}): t.${type} {`;
const nodeObjectExpression = `{\n${objectFields
.map(([k, v]) => (k === v ? ` ${k},` : ` ${k}: ${v},`))
.join("\n")}\n }`;
if (builderNames.length > 0) {
output += `\n return validateNode<t.${type}>(${nodeObjectExpression});`;
} else {
output += `\n return ${nodeObjectExpression};`;
}
output += `\n}\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];
const formatedBuilderName = formatBuilderName(type);
const formatedNewBuilderName = formatBuilderName(newType);
output += `/** @deprecated */
function ${type}(${generateBuilderArgs(newType).join(", ")}) {
console.trace("The node type ${type} has been renamed to ${newType}");
return ${formatedNewBuilderName}(${t.BUILDER_KEYS[newType].join(", ")});
}
export { ${type} 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 { ${type} as ${lowerFirst(type)} }\n`;
}
});
return output;
}
function generateUppercaseBuilders() {
let output = `/*
* This file is auto-generated! Do not modify it directly.
* To re-generate run 'make build'
*/
/**
* This file is written in JavaScript and not TypeScript because uppercase builders
* conflict with AST types. TypeScript reads the uppercase.d.ts file instead.
*/
export {\n`;
Object.keys(definitions.BUILDER_KEYS).forEach(type => {
const formatedBuilderName = formatBuilderName(type);
output += ` ${formatedBuilderName} as ${type},\n`;
});
Object.keys(definitions.DEPRECATED_KEYS).forEach(type => {
const formatedBuilderName = formatBuilderName(type);
output += ` ${formatedBuilderName} as ${type},\n`;
});
output += ` } from './index';\n`;
return output;
}
import * as definitions from "../../lib/definitions/index.js";
export default function generateConstants() {
let output = `/*
* 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;
}
import util from "util";
import stringifyValidator from "../utils/stringifyValidator.js";
import toFunctionName from "../utils/toFunctionName.js";
import * as t from "../../lib/index.js";
const readme = [
`---
id: babel-types
title: @babel/types
---
<!-- Do not modify! This file is automatically generated by
github.com/babel/babel/babel-types/scripts/generators/docs.js !-->
> 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`",
},
ClassPrivateMethod: {
computed: "'false'",
},
ClassPrivateProperty: {
computed: "'false'",
},
};
const APIHistory = {
ClassProperty: [["v7.6.0", "Supports `static`"]],
};
function formatHistory(historyItems) {
const lines = historyItems.map(
item => "| `" + item[0] + "` | " + item[1] + " |"
);
return [
"<details>",
" <summary>History</summary>",
"| Version | Changes |",
"| --- | --- |",
...lines,
"</details>",
];
}
function printAPIHistory(key, readme) {
if (APIHistory[key]) {
readme.push("");
readme.push(...formatHistory(APIHistory[key]));
}
}
function printNodeFields(key, readme) {
if (Object.keys(t.NODE_FIELDS[key]).length > 0) {
readme.push("");
readme.push("AST Node `" + key + "` shape:");
Object.keys(t.NODE_FIELDS[key])
.sort(function (fieldA, fieldB) {
const indexA = t.BUILDER_KEYS[key].indexOf(fieldA);
const indexB = t.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 = t.NODE_FIELDS[key][field].default;
const fieldDescription = ["`" + field + "`"];
const validator = t.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 || t.NODE_FIELDS[key][field].optional) {
fieldDescription.push(
" (default: `" + util.inspect(defaultValue) + "`"
);
if (t.BUILDER_KEYS[key].indexOf(field) < 0) {
fieldDescription.push(", excluded from builder function");
}
fieldDescription.push(")");
} else {
fieldDescription.push(" (required)");
}
readme.push("- " + fieldDescription.join(""));
});
}
}
function printAliasKeys(key, readme) {
if (t.ALIAS_KEYS[key] && t.ALIAS_KEYS[key].length) {
readme.push("");
readme.push(
"Aliases: " +
t.ALIAS_KEYS[key]
.map(function (key) {
return "[`" + key + "`](#" + key.toLowerCase() + ")";
})
.join(", ")
);
}
}
readme.push("### Node Builders");
readme.push("");
Object.keys(t.BUILDER_KEYS)
.sort()
.forEach(function (key) {
readme.push("#### " + toFunctionName(key));
readme.push("");
readme.push("```javascript");
readme.push(
"t." + toFunctionName(key) + "(" + t.BUILDER_KEYS[key].join(", ") + ");"
);
readme.push("```");
printAPIHistory(key, readme);
readme.push("");
readme.push(
"See also `t.is" +
key +
"(node, opts)` and `t.assert" +
key +
"(node, opts)`."
);
printNodeFields(key, readme);
printAliasKeys(key, readme);
readme.push("");
readme.push("---");
readme.push("");
});
function generateMapAliasToNodeTypes() {
const result = new Map();
for (const nodeType of Object.keys(t.ALIAS_KEYS)) {
const aliases = t.ALIAS_KEYS[nodeType];
if (!aliases) continue;
for (const alias of aliases) {
if (!result.has(alias)) {
result.set(alias, []);
}
const nodeTypes = result.get(alias);
nodeTypes.push(nodeType);
}
}
return result;
}
const aliasDescriptions = {
Accessor: "Deprecated. Will be removed in Babel 8.",
Binary:
"A cover of BinaryExpression and LogicalExpression, which share the same AST shape.",
Block: "Deprecated. Will be removed in Babel 8.",
BlockParent:
"A cover of AST nodes that start an execution context with new [LexicalEnvironment](https://tc39.es/ecma262/#table-additional-state-components-for-ecmascript-code-execution-contexts). In other words, they define the scope of `let` and `const` declarations.",
Class:
"A cover of ClassExpression and ClassDeclaration, which share the same AST shape.",
CompletionStatement:
"A statement that indicates the [completion records](https://tc39.es/ecma262/#sec-completion-record-specification-type). In other words, they define the control flow of the program, such as when should a loop break or an action throws critical errors.",
Conditional:
"A cover of ConditionalExpression and IfStatement, which share the same AST shape.",
Declaration:
"A cover of any [Declaration](https://tc39.es/ecma262/#prod-Declaration)s.",
EnumBody: "A cover of Flow enum bodies.",
EnumMember: "A cover of Flow enum membors.",
ExportDeclaration:
"A cover of any [ExportDeclaration](https://tc39.es/ecma262/#prod-ExportDeclaration)s.",
Expression:
"A cover of any [Expression](https://tc39.es/ecma262/#sec-ecmascript-language-expressions)s.",
ExpressionWrapper:
"A wrapper of expression that does not have runtime semantics.",
Flow: "A cover of AST nodes defined for Flow.",
FlowBaseAnnotation: "A cover of primary Flow type annotations.",
FlowDeclaration: "A cover of Flow declarations.",
FlowPredicate: "A cover of Flow predicates.",
FlowType: "A cover of Flow type annotations.",
For: "A cover of [ForStatement](https://tc39.es/ecma262/#sec-for-statement)s and [ForXStatement](#forxstatement)s.",
ForXStatement:
"A cover of [ForInStatements and ForOfStatements](https://tc39.es/ecma262/#sec-for-in-and-for-of-statements).",
Function:
"A cover of functions and [method](#method)s, the must have `body` and `params`. Note: `Function` is different to `FunctionParent`. For example, a `StaticBlock` is a `FunctionParent` but not `Function`.",
FunctionParent:
"A cover of AST nodes that start an execution context with new [VariableEnvironment](https://tc39.es/ecma262/#table-additional-state-components-for-ecmascript-code-execution-contexts). In other words, they define the scope of `var` declarations. FunctionParent did not include `Program` since Babel 7.",
Immutable:
"A cover of immutable objects and JSX elements. An object is [immutable](https://tc39.es/ecma262/#immutable-prototype-exotic-object) if no other properties can be defined once created.",
JSX: "A cover of AST nodes defined for [JSX](https://facebook.github.io/jsx/).",
LVal: "A cover of left hand side expressions used in the `left` of assignment expressions and [ForXStatement](#forxstatement)s. ",
Literal:
"A cover of [Literal](https://tc39.es/ecma262/#sec-primary-expression-literals)s, [Regular Expression Literal](https://tc39.es/ecma262/#sec-primary-expression-regular-expression-literals)s and [Template Literal](https://tc39.es/ecma262/#sec-template-literals)s.",
Loop: "A cover of loop statements.",
Method: "A cover of object methods and class methods.",
Miscellaneous:
"A cover of non-standard AST types that are sometimes useful for development.",
ModuleDeclaration:
"A cover of ImportDeclaration and [ExportDeclaration](#exportdeclaration)",
ModuleSpecifier:
"A cover of import and export specifiers. Note: It is _not_ the [ModuleSpecifier](https://tc39.es/ecma262/#prod-ModuleSpecifier) defined in the spec.",
ObjectMember:
"A cover of [members](https://tc39.es/ecma262/#prod-PropertyDefinitionList) in an object literal.",
Pattern:
"A cover of [BindingPattern](https://tc39.es/ecma262/#prod-BindingPattern) except Identifiers.",
PatternLike:
"A cover of [BindingPattern](https://tc39.es/ecma262/#prod-BindingPattern)s. ",
Private: "A cover of private class elements and private identifiers.",
Property: "A cover of object properties and class properties.",
Pureish:
"A cover of AST nodes which do not have side-effects. In other words, there is no observable behaviour changes if they are evaluated more than once.",
Scopable:
"A cover of [FunctionParent](#functionparent) and [BlockParent](#blockparent).",
Standardized:
"A cover of AST nodes which are part of an official ECMAScript specification.",
Statement:
"A cover of any [Statement](https://tc39.es/ecma262/#prod-Statement)s.",
TSBaseType: "A cover of primary TypeScript type annotations.",
TSEntityName: "A cover of ts entities.",
TSType: "A cover of TypeScript type annotations.",
TSTypeElement: "A cover of TypeScript type declarations.",
TypeScript: "A cover of AST nodes defined for TypeScript.",
Terminatorless:
"A cover of AST nodes whose semantic will change when a line terminator is inserted between the operator and the operand.",
UnaryLike: "A cover of UnaryExpression and SpreadElement.",
UserWhitespacable: "Deprecated. Will be removed in Babel 8.",
While:
"A cover of DoWhileStatement and WhileStatement, which share the same AST shape.",
};
const mapAliasToNodeTypes = generateMapAliasToNodeTypes();
readme.push("### Aliases");
readme.push("");
for (const alias of [...mapAliasToNodeTypes.keys()].sort()) {
const nodeTypes = mapAliasToNodeTypes.get(alias);
nodeTypes.sort();
if (!(alias in aliasDescriptions)) {
throw new Error(
'Missing alias descriptions of "' +
alias +
", which covers " +
nodeTypes.join(",")
);
}
readme.push("#### " + alias);
readme.push("");
readme.push(aliasDescriptions[alias]);
readme.push("```javascript");
readme.push("t.is" + alias + "(node);");
readme.push("```");
readme.push("");
readme.push("Covered nodes: ");
for (const nodeType of nodeTypes) {
readme.push("- [`" + nodeType + "`](#" + nodeType.toLowerCase() + ")");
}
readme.push("");
}
process.stdout.write(readme.join("\n"));
import * as t from "../../lib/index.js";
import stringifyValidator from "../utils/stringifyValidator.js";
import toFunctionName from "../utils/toFunctionName.js";
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;
extra?: { [string]: mixed };
}\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 export 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 (const typeName of t.TYPES) {
const isDeprecated = !!t.DEPRECATED_KEYS[typeName];
const realName = isDeprecated ? t.DEPRECATED_KEYS[typeName] : typeName;
let decl = `declare export function is${typeName}(node: ?Object, opts?: ?Object): boolean`;
if (t.NODE_FIELDS[realName]) {
decl += ` %checks (node instanceof ${NODE_PREFIX}${realName})`;
}
lines.push(decl);
lines.push(
`declare export function assert${typeName}(node: ?Object, opts?: ?Object): void`
);
}
lines.push(
`declare export var VISITOR_KEYS: { [type: string]: string[] }`,
// assert/
`declare export function assertNode(obj: any): void`,
// builders/
// eslint-disable-next-line max-len
`declare export function createTypeAnnotationBasedOnTypeof(type: 'string' | 'number' | 'undefined' | 'boolean' | 'function' | 'object' | 'symbol'): ${NODE_PREFIX}TypeAnnotation`,
// eslint-disable-next-line max-len
`declare export function createUnionTypeAnnotation(types: Array<${NODE_PREFIX}FlowType>): ${NODE_PREFIX}UnionTypeAnnotation`,
// eslint-disable-next-line max-len
`declare export function createFlowUnionType(types: Array<${NODE_PREFIX}FlowType>): ${NODE_PREFIX}UnionTypeAnnotation`,
// this smells like "internal API"
// eslint-disable-next-line max-len
`declare export 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 export function clone<T>(n: T): T;`,
`declare export function cloneDeep<T>(n: T): T;`,
`declare export function cloneDeepWithoutLoc<T>(n: T): T;`,
`declare export function cloneNode<T>(n: T, deep?: boolean, withoutLoc?: boolean): T;`,
`declare export function cloneWithoutLoc<T>(n: T): T;`,
// comments/
`declare type CommentTypeShorthand = 'leading' | 'inner' | 'trailing'`,
// eslint-disable-next-line max-len
`declare export function addComment<T: BabelNode>(node: T, type: CommentTypeShorthand, content: string, line?: boolean): T`,
// eslint-disable-next-line max-len
`declare export function addComments<T: BabelNode>(node: T, type: CommentTypeShorthand, comments: Array<Comment>): T`,
`declare export function inheritInnerComments(node: BabelNode, parent: BabelNode): void`,
`declare export function inheritLeadingComments(node: BabelNode, parent: BabelNode): void`,
`declare export function inheritsComments<T: BabelNode>(node: T, parent: BabelNode): void`,
`declare export function inheritTrailingComments(node: BabelNode, parent: BabelNode): void`,
`declare export function removeComments<T: BabelNode>(node: T): T`,
// converters/
`declare export function ensureBlock(node: ${NODE_PREFIX}, key: string): ${NODE_PREFIX}BlockStatement`,
`declare export function toBindingIdentifierName(name?: ?string): string`,
// eslint-disable-next-line max-len
`declare export function toBlock(node: ${NODE_PREFIX}Statement | ${NODE_PREFIX}Expression, parent?: ${NODE_PREFIX}Function | null): ${NODE_PREFIX}BlockStatement`,
// eslint-disable-next-line max-len
`declare export 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 export function toExpression(node: ${NODE_PREFIX}ExpressionStatement | ${NODE_PREFIX}Expression | ${NODE_PREFIX}Class | ${NODE_PREFIX}Function): ${NODE_PREFIX}Expression`,
`declare export function toIdentifier(name?: ?string): string`,
// eslint-disable-next-line max-len
`declare export 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 export function toStatement(node: ${NODE_PREFIX}Statement | ${NODE_PREFIX}Class | ${NODE_PREFIX}Function | ${NODE_PREFIX}AssignmentExpression, ignore?: boolean): ${NODE_PREFIX}Statement | void`,
`declare export function valueToNode(value: any): ${NODE_PREFIX}Expression`,
// modifications/
// eslint-disable-next-line max-len
`declare export function removeTypeDuplicates(types: Array<${NODE_PREFIX}FlowType>): Array<${NODE_PREFIX}FlowType>`,
// eslint-disable-next-line max-len
`declare export function appendToMemberExpression(member: ${NODE_PREFIX}MemberExpression, append: ${NODE_PREFIX}, computed?: boolean): ${NODE_PREFIX}MemberExpression`,
// eslint-disable-next-line max-len
`declare export function inherits<T: BabelNode>(child: T, parent: ${NODE_PREFIX} | null | void): T`,
// eslint-disable-next-line max-len
`declare export function prependToMemberExpression(member: ${NODE_PREFIX}MemberExpression, prepend: ${NODE_PREFIX}Expression): ${NODE_PREFIX}MemberExpression`,
`declare export function removeProperties<T>(n: T, opts: ?{}): void;`,
`declare export function removePropertiesDeep<T>(n: T, opts: ?{}): T;`,
// retrievers/
// eslint-disable-next-line max-len
`declare export var getBindingIdentifiers: {
(node: ${NODE_PREFIX}, duplicates?: boolean, outerOnly?: boolean): { [key: string]: ${NODE_PREFIX}Identifier | Array<${NODE_PREFIX}Identifier> },
keys: { [type: string]: string[] }
}`,
// eslint-disable-next-line max-len
`declare export function getOuterBindingIdentifiers(node: BabelNode, 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 export function traverse<T>(n: BabelNode, TraversalHandler<T> | TraversalHandlers<T>, state?: T): void;`,
`declare export function traverseFast<T>(n: BabelNode, h: TraversalHandler<T>, state?: T): void;`,
// utils/
// cleanJSXElementLiteralChild is not exported
// inherit is not exported
`declare export function shallowEqual(actual: Object, expected: Object): boolean`,
// validators/
// eslint-disable-next-line max-len
`declare export function buildMatchMemberExpression(match: string, allowPartial?: boolean): (?BabelNode) => boolean`,
`declare export function is(type: string, n: BabelNode, opts: Object): boolean;`,
`declare export function isBinding(node: BabelNode, parent: BabelNode, grandparent?: BabelNode): boolean`,
`declare export function isBlockScoped(node: BabelNode): boolean`,
`declare export function isImmutable(node: BabelNode): boolean`,
`declare export function isLet(node: BabelNode): boolean`,
`declare export function isNode(node: ?Object): boolean`,
`declare export function isNodesEquivalent(a: any, b: any): boolean`,
`declare export function isPlaceholderType(placeholderType: string, targetType: string): boolean`,
`declare export function isReferenced(node: BabelNode, parent: BabelNode, grandparent?: BabelNode): boolean`,
`declare export function isScope(node: BabelNode, parent: BabelNode): boolean`,
`declare export function isSpecifierDefault(specifier: BabelNodeModuleSpecifier): boolean`,
`declare export function isType(nodetype: ?string, targetType: string): boolean`,
`declare export function isValidES3Identifier(name: string): boolean`,
`declare export function isValidES3Identifier(name: string): boolean`,
`declare export function isValidIdentifier(name: string): boolean`,
`declare export function isVar(node: BabelNode): boolean`,
// eslint-disable-next-line max-len
`declare export function matchesPattern(node: ?BabelNode, match: string | Array<string>, allowPartial?: boolean): boolean`,
`declare export 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);
import * as t from "../../lib/index.js";
import stringifyValidator from "../utils/stringifyValidator.js";
import toFunctionName from "../utils/toFunctionName.js";
let code = `// NOTE: This file is autogenerated. Do not modify.
// See packages/babel-types/scripts/generators/typescript-legacy.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"];
extra?: Record<string, unknown>;
}
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 isDeprecated = !!t.DEPRECATED_KEYS[typeName];
const realName = isDeprecated ? t.DEPRECATED_KEYS[typeName] : typeName;
const result =
t.NODE_FIELDS[realName] || t.FLIPPED_ALIAS_KEYS[realName]
? `node is ${realName}`
: "boolean";
if (isDeprecated) {
lines.push(`/** @deprecated Use \`is${realName}\` */`);
}
lines.push(
`export function is${typeName}(node: object | null | undefined, opts?: object | null): ${result};`
);
if (isDeprecated) {
lines.push(`/** @deprecated Use \`assert${realName}\` */`);
}
lines.push(
`export function assert${typeName}(node: object | null | undefined, opts?: object | null): void;`
);
}
lines.push(
// assert/
`export function assertNode(obj: any): void`,
// 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`,
// 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;
});
}
import * as definitions from "../../lib/definitions/index.js";
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 as t.Placeholder).expectedNode"
) +
")";
}
const result =
definitions.NODE_FIELDS[type] || definitions.FLIPPED_ALIAS_KEYS[type]
? `node is t.${type}`
: "boolean";
return `export function is${type}(node: object | null | undefined, opts?: object | null): ${result} {
${deprecated || ""}
if (!node) return false;
const nodeType = (node as t.Node).type;
if (${
aliasSource ? aliasSource : `nodeType === ${targetType}`
}${placeholderSource}) {
if (typeof opts === "undefined") {
return true;
} else {
return shallowEqual(node, opts);
}
}
return false;
}
`;
}
export default function generateValidators() {
let output = `/*
* This file is auto-generated! Do not modify it directly.
* To re-generate run 'make build'
*/
import shallowEqual from "../../utils/shallowEqual";
import type * as t from "../..";\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;
}
const toLowerCase = Function.call.bind("".toLowerCase);
export default function formatBuilderName(type) {
// FunctionExpression -> functionExpression
// JSXIdentifier -> jsxIdentifier
// V8IntrinsicIdentifier -> v8IntrinsicIdentifier
return type.replace(/^([A-Z](?=[a-z0-9])|[A-Z]+(?=[A-Z]))/, toLowerCase);
}
export default function lowerFirst(string) {
return string[0].toLowerCase() + string.slice(1);
}
export default 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);
}
export default function toFunctionName(typeName) {
const _ = typeName.replace(/^TS/, "ts").replace(/^JSX/, "jsx");
return _.slice(0, 1).toLowerCase() + _.slice(1);
}
1.3.8 / 2022-02-02
==================
* deps: mime-types@~2.1.34
- deps: mime-db@~1.51.0
* deps: negotiator@0.6.3
1.3.7 / 2019-04-29
==================
* deps: negotiator@0.6.2
- Fix sorting charset, encoding, and language with extra parameters
1.3.6 / 2019-04-28
==================
* deps: mime-types@~2.1.24
- deps: mime-db@~1.40.0
1.3.5 / 2018-02-28
==================
* deps: mime-types@~2.1.18
- deps: mime-db@~1.33.0
1.3.4 / 2017-08-22
==================
* deps: mime-types@~2.1.16
- deps: mime-db@~1.29.0
1.3.3 / 2016-05-02
==================
* deps: mime-types@~2.1.11
- deps: mime-db@~1.23.0
* deps: negotiator@0.6.1
- perf: improve `Accept` parsing speed
- perf: improve `Accept-Charset` parsing speed
- perf: improve `Accept-Encoding` parsing speed
- perf: improve `Accept-Language` parsing speed
1.3.2 / 2016-03-08
==================
* deps: mime-types@~2.1.10
- Fix extension of `application/dash+xml`
- Update primary extension for `audio/mp4`
- deps: mime-db@~1.22.0
1.3.1 / 2016-01-19
==================
* deps: mime-types@~2.1.9
- deps: mime-db@~1.21.0
1.3.0 / 2015-09-29
==================
* deps: mime-types@~2.1.7
- deps: mime-db@~1.19.0
* deps: negotiator@0.6.0
- Fix including type extensions in parameters in `Accept` parsing
- Fix parsing `Accept` parameters with quoted equals
- Fix parsing `Accept` parameters with quoted semicolons
- Lazy-load modules from main entry point
- perf: delay type concatenation until needed
- perf: enable strict mode
- perf: hoist regular expressions
- perf: remove closures getting spec properties
- perf: remove a closure from media type parsing
- perf: remove property delete from media type parsing
1.2.13 / 2015-09-06
===================
* deps: mime-types@~2.1.6
- deps: mime-db@~1.18.0
1.2.12 / 2015-07-30
===================
* deps: mime-types@~2.1.4
- deps: mime-db@~1.16.0
1.2.11 / 2015-07-16
===================
* deps: mime-types@~2.1.3
- deps: mime-db@~1.15.0
1.2.10 / 2015-07-01
===================
* deps: mime-types@~2.1.2
- deps: mime-db@~1.14.0
1.2.9 / 2015-06-08
==================
* deps: mime-types@~2.1.1
- perf: fix deopt during mapping
1.2.8 / 2015-06-07
==================
* deps: mime-types@~2.1.0
- deps: mime-db@~1.13.0
* perf: avoid argument reassignment & argument slice
* perf: avoid negotiator recursive construction
* perf: enable strict mode
* perf: remove unnecessary bitwise operator
1.2.7 / 2015-05-10
==================
* deps: negotiator@0.5.3
- Fix media type parameter matching to be case-insensitive
1.2.6 / 2015-05-07
==================
* deps: mime-types@~2.0.11
- deps: mime-db@~1.9.1
* deps: negotiator@0.5.2
- Fix comparing media types with quoted values
- Fix splitting media types with quoted commas
1.2.5 / 2015-03-13
==================
* deps: mime-types@~2.0.10
- deps: mime-db@~1.8.0
1.2.4 / 2015-02-14
==================
* Support Node.js 0.6
* deps: mime-types@~2.0.9
- deps: mime-db@~1.7.0
* deps: negotiator@0.5.1
- Fix preference sorting to be stable for long acceptable lists
1.2.3 / 2015-01-31
==================
* deps: mime-types@~2.0.8
- deps: mime-db@~1.6.0
1.2.2 / 2014-12-30
==================
* deps: mime-types@~2.0.7
- deps: mime-db@~1.5.0
1.2.1 / 2014-12-30
==================
* deps: mime-types@~2.0.5
- deps: mime-db@~1.3.1
1.2.0 / 2014-12-19
==================
* deps: negotiator@0.5.0
- Fix list return order when large accepted list
- Fix missing identity encoding when q=0 exists
- Remove dynamic building of Negotiator class
1.1.4 / 2014-12-10
==================
* deps: mime-types@~2.0.4
- deps: mime-db@~1.3.0
1.1.3 / 2014-11-09
==================
* deps: mime-types@~2.0.3
- deps: mime-db@~1.2.0
1.1.2 / 2014-10-14
==================
* deps: negotiator@0.4.9
- Fix error when media type has invalid parameter
1.1.1 / 2014-09-28
==================
* deps: mime-types@~2.0.2
- deps: mime-db@~1.1.0
* deps: negotiator@0.4.8
- Fix all negotiations to be case-insensitive
- Stable sort preferences of same quality according to client order
1.1.0 / 2014-09-02
==================
* update `mime-types`
1.0.7 / 2014-07-04
==================
* Fix wrong type returned from `type` when match after unknown extension
1.0.6 / 2014-06-24
==================
* deps: negotiator@0.4.7
1.0.5 / 2014-06-20
==================
* fix crash when unknown extension given
1.0.4 / 2014-06-19
==================
* use `mime-types`
1.0.3 / 2014-06-11
==================
* deps: negotiator@0.4.6
- Order by specificity when quality is the same
1.0.2 / 2014-05-29
==================
* Fix interpretation when header not in request
* deps: pin negotiator@0.4.5
1.0.1 / 2014-01-18
==================
* Identity encoding isn't always acceptable
* deps: negotiator@~0.4.0
1.0.0 / 2013-12-27
==================
* Genesis
(The MIT License)
Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
Copyright (c) 2015 Douglas Christopher Wilson <doug@somethingdoug.com>
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.
# accepts
[![NPM Version][npm-version-image]][npm-url]
[![NPM Downloads][npm-downloads-image]][npm-url]
[![Node.js Version][node-version-image]][node-version-url]
[![Build Status][github-actions-ci-image]][github-actions-ci-url]
[![Test Coverage][coveralls-image]][coveralls-url]
Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator).
Extracted from [koa](https://www.npmjs.com/package/koa) for general use.
In addition to negotiator, it allows:
- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])`
as well as `('text/html', 'application/json')`.
- Allows type shorthands such as `json`.
- Returns `false` when no types match
- Treats non-existent headers as `*`
## Installation
This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
```sh
$ npm install accepts
```
## API
```js
var accepts = require('accepts')
```
### accepts(req)
Create a new `Accepts` object for the given `req`.
#### .charset(charsets)
Return the first accepted charset. If nothing in `charsets` is accepted,
then `false` is returned.
#### .charsets()
Return the charsets that the request accepts, in the order of the client's
preference (most preferred first).
#### .encoding(encodings)
Return the first accepted encoding. If nothing in `encodings` is accepted,
then `false` is returned.
#### .encodings()
Return the encodings that the request accepts, in the order of the client's
preference (most preferred first).
#### .language(languages)
Return the first accepted language. If nothing in `languages` is accepted,
then `false` is returned.
#### .languages()
Return the languages that the request accepts, in the order of the client's
preference (most preferred first).
#### .type(types)
Return the first accepted type (and it is returned as the same text as what
appears in the `types` array). If nothing in `types` is accepted, then `false`
is returned.
The `types` array can contain full MIME types or file extensions. Any value
that is not a full MIME types is passed to `require('mime-types').lookup`.
#### .types()
Return the types that the request accepts, in the order of the client's
preference (most preferred first).
## Examples
### Simple type negotiation
This simple example shows how to use `accepts` to return a different typed
respond body based on what the client wants to accept. The server lists it's
preferences in order and will get back the best match between the client and
server.
```js
var accepts = require('accepts')
var http = require('http')
function app (req, res) {
var accept = accepts(req)
// the order of this list is significant; should be server preferred order
switch (accept.type(['json', 'html'])) {
case 'json':
res.setHeader('Content-Type', 'application/json')
res.write('{"hello":"world!"}')
break
case 'html':
res.setHeader('Content-Type', 'text/html')
res.write('<b>hello, world!</b>')
break
default:
// the fallback is text/plain, so no need to specify it above
res.setHeader('Content-Type', 'text/plain')
res.write('hello, world!')
break
}
res.end()
}
http.createServer(app).listen(3000)
```
You can test this out with the cURL program:
```sh
curl -I -H'Accept: text/html' http://localhost:3000/
```
## License
[MIT](LICENSE)
[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/accepts/master
[coveralls-url]: https://coveralls.io/r/jshttp/accepts?branch=master
[github-actions-ci-image]: https://badgen.net/github/checks/jshttp/accepts/master?label=ci
[github-actions-ci-url]: https://github.com/jshttp/accepts/actions/workflows/ci.yml
[node-version-image]: https://badgen.net/npm/node/accepts
[node-version-url]: https://nodejs.org/en/download
[npm-downloads-image]: https://badgen.net/npm/dm/accepts
[npm-url]: https://npmjs.org/package/accepts
[npm-version-image]: https://badgen.net/npm/v/accepts
/*!
* accepts
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var Negotiator = require('negotiator')
var mime = require('mime-types')
/**
* Module exports.
* @public
*/
module.exports = Accepts
/**
* Create a new Accepts object for the given req.
*
* @param {object} req
* @public
*/
function Accepts (req) {
if (!(this instanceof Accepts)) {
return new Accepts(req)
}
this.headers = req.headers
this.negotiator = new Negotiator(req)
}
/**
* Check if the given `type(s)` is acceptable, returning
* the best match when true, otherwise `undefined`, in which
* case you should respond with 406 "Not Acceptable".
*
* The `type` value may be a single mime type string
* such as "application/json", the extension name
* such as "json" or an array `["json", "html", "text/plain"]`. When a list
* or array is given the _best_ match, if any is returned.
*
* Examples:
*
* // Accept: text/html
* this.types('html');
* // => "html"
*
* // Accept: text/*, application/json
* this.types('html');
* // => "html"
* this.types('text/html');
* // => "text/html"
* this.types('json', 'text');
* // => "json"
* this.types('application/json');
* // => "application/json"
*
* // Accept: text/*, application/json
* this.types('image/png');
* this.types('png');
* // => undefined
*
* // Accept: text/*;q=.5, application/json
* this.types(['html', 'json']);
* this.types('html', 'json');
* // => "json"
*
* @param {String|Array} types...
* @return {String|Array|Boolean}
* @public
*/
Accepts.prototype.type =
Accepts.prototype.types = function (types_) {
var types = types_
// support flattened arguments
if (types && !Array.isArray(types)) {
types = new Array(arguments.length)
for (var i = 0; i < types.length; i++) {
types[i] = arguments[i]
}
}
// no types, return all requested types
if (!types || types.length === 0) {
return this.negotiator.mediaTypes()
}
// no accept header, return first given type
if (!this.headers.accept) {
return types[0]
}
var mimes = types.map(extToMime)
var accepts = this.negotiator.mediaTypes(mimes.filter(validMime))
var first = accepts[0]
return first
? types[mimes.indexOf(first)]
: false
}
/**
* Return accepted encodings or best fit based on `encodings`.
*
* Given `Accept-Encoding: gzip, deflate`
* an array sorted by quality is returned:
*
* ['gzip', 'deflate']
*
* @param {String|Array} encodings...
* @return {String|Array}
* @public
*/
Accepts.prototype.encoding =
Accepts.prototype.encodings = function (encodings_) {
var encodings = encodings_
// support flattened arguments
if (encodings && !Array.isArray(encodings)) {
encodings = new Array(arguments.length)
for (var i = 0; i < encodings.length; i++) {
encodings[i] = arguments[i]
}
}
// no encodings, return all requested encodings
if (!encodings || encodings.length === 0) {
return this.negotiator.encodings()
}
return this.negotiator.encodings(encodings)[0] || false
}
/**
* Return accepted charsets or best fit based on `charsets`.
*
* Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5`
* an array sorted by quality is returned:
*
* ['utf-8', 'utf-7', 'iso-8859-1']
*
* @param {String|Array} charsets...
* @return {String|Array}
* @public
*/
Accepts.prototype.charset =
Accepts.prototype.charsets = function (charsets_) {
var charsets = charsets_
// support flattened arguments
if (charsets && !Array.isArray(charsets)) {
charsets = new Array(arguments.length)
for (var i = 0; i < charsets.length; i++) {
charsets[i] = arguments[i]
}
}
// no charsets, return all requested charsets
if (!charsets || charsets.length === 0) {
return this.negotiator.charsets()
}
return this.negotiator.charsets(charsets)[0] || false
}
/**
* Return accepted languages or best fit based on `langs`.
*
* Given `Accept-Language: en;q=0.8, es, pt`
* an array sorted by quality is returned:
*
* ['es', 'pt', 'en']
*
* @param {String|Array} langs...
* @return {Array|String}
* @public
*/
Accepts.prototype.lang =
Accepts.prototype.langs =
Accepts.prototype.language =
Accepts.prototype.languages = function (languages_) {
var languages = languages_
// support flattened arguments
if (languages && !Array.isArray(languages)) {
languages = new Array(arguments.length)
for (var i = 0; i < languages.length; i++) {
languages[i] = arguments[i]
}
}
// no languages, return all requested languages
if (!languages || languages.length === 0) {
return this.negotiator.languages()
}
return this.negotiator.languages(languages)[0] || false
}
/**
* Convert extnames to mime.
*
* @param {String} type
* @return {String}
* @private
*/
function extToMime (type) {
return type.indexOf('/') === -1
? mime.lookup(type)
: type
}
/**
* Check if mime is valid.
*
* @param {String} type
* @return {String}
* @private
*/
function validMime (type) {
return typeof type === 'string'
}
{
"name": "accepts",
"description": "Higher-level content negotiation",
"version": "1.3.8",
"contributors": [
"Douglas Christopher Wilson <doug@somethingdoug.com>",
"Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)"
],
"license": "MIT",
"repository": "jshttp/accepts",
"dependencies": {
"mime-types": "~2.1.34",
"negotiator": "0.6.3"
},
"devDependencies": {
"deep-equal": "1.0.1",
"eslint": "7.32.0",
"eslint-config-standard": "14.1.1",
"eslint-plugin-import": "2.25.4",
"eslint-plugin-markdown": "2.2.1",
"eslint-plugin-node": "11.1.0",
"eslint-plugin-promise": "4.3.1",
"eslint-plugin-standard": "4.1.0",
"mocha": "9.2.0",
"nyc": "15.1.0"
},
"files": [
"LICENSE",
"HISTORY.md",
"index.js"
],
"engines": {
"node": ">= 0.6"
},
"scripts": {
"lint": "eslint .",
"test": "mocha --reporter spec --check-leaks --bail test/",
"test-ci": "nyc --reporter=lcov --reporter=text npm test",
"test-cov": "nyc --reporter=html --reporter=text npm test"
},
"keywords": [
"content",
"negotiation",
"accept",
"accepts"
]
}
## 7.4.0 (2020-08-03)
### New features
Add support for logical assignment operators.
Add support for numeric separators.
## 7.3.1 (2020-06-11)
### Bug fixes
Make the string in the `version` export match the actual library version.
## 7.3.0 (2020-06-11)
### Bug fixes
Fix a bug that caused parsing of object patterns with a property named `set` that had a default value to fail.
### New features
Add support for optional chaining (`?.`).
## 7.2.0 (2020-05-09)
### Bug fixes
Fix precedence issue in parsing of async arrow functions.
### New features
Add support for nullish coalescing.
Add support for `import.meta`.
Support `export * as ...` syntax.
Upgrade to Unicode 13.
## 6.4.1 (2020-03-09)
### Bug fixes
More carefully check for valid UTF16 surrogate pairs in regexp validator.
## 7.1.1 (2020-03-01)
### Bug fixes
Treat `\8` and `\9` as invalid escapes in template strings.
Allow unicode escapes in property names that are keywords.
Don't error on an exponential operator expression as argument to `await`.
More carefully check for valid UTF16 surrogate pairs in regexp validator.
## 7.1.0 (2019-09-24)
### Bug fixes
Disallow trailing object literal commas when ecmaVersion is less than 5.
### New features
Add a static `acorn` property to the `Parser` class that contains the entire module interface, to allow plugins to access the instance of the library that they are acting on.
## 7.0.0 (2019-08-13)
### Breaking changes
Changes the node format for dynamic imports to use the `ImportExpression` node type, as defined in [ESTree](https://github.com/estree/estree/blob/master/es2020.md#importexpression).
Makes 10 (ES2019) the default value for the `ecmaVersion` option.
## 6.3.0 (2019-08-12)
### New features
`sourceType: "module"` can now be used even when `ecmaVersion` is less than 6, to parse module-style code that otherwise conforms to an older standard.
## 6.2.1 (2019-07-21)
### Bug fixes
Fix bug causing Acorn to treat some characters as identifier characters that shouldn't be treated as such.
Fix issue where setting the `allowReserved` option to `"never"` allowed reserved words in some circumstances.
## 6.2.0 (2019-07-04)
### Bug fixes
Improve valid assignment checking in `for`/`in` and `for`/`of` loops.
Disallow binding `let` in patterns.
### New features
Support bigint syntax with `ecmaVersion` >= 11.
Support dynamic `import` syntax with `ecmaVersion` >= 11.
Upgrade to Unicode version 12.
## 6.1.1 (2019-02-27)
### Bug fixes
Fix bug that caused parsing default exports of with names to fail.
## 6.1.0 (2019-02-08)
### Bug fixes
Fix scope checking when redefining a `var` as a lexical binding.
### New features
Split up `parseSubscripts` to use an internal `parseSubscript` method to make it easier to extend with plugins.
## 6.0.7 (2019-02-04)
### Bug fixes
Check that exported bindings are defined.
Don't treat `\u180e` as a whitespace character.
Check for duplicate parameter names in methods.
Don't allow shorthand properties when they are generators or async methods.
Forbid binding `await` in async arrow function's parameter list.
## 6.0.6 (2019-01-30)
### Bug fixes
The content of class declarations and expressions is now always parsed in strict mode.
Don't allow `let` or `const` to bind the variable name `let`.
Treat class declarations as lexical.
Don't allow a generator function declaration as the sole body of an `if` or `else`.
Ignore `"use strict"` when after an empty statement.
Allow string line continuations with special line terminator characters.
Treat `for` bodies as part of the `for` scope when checking for conflicting bindings.
Fix bug with parsing `yield` in a `for` loop initializer.
Implement special cases around scope checking for functions.
## 6.0.5 (2019-01-02)
### Bug fixes
Fix TypeScript type for `Parser.extend` and add `allowAwaitOutsideFunction` to options type.
Don't treat `let` as a keyword when the next token is `{` on the next line.
Fix bug that broke checking for parentheses around an object pattern in a destructuring assignment when `preserveParens` was on.
## 6.0.4 (2018-11-05)
### Bug fixes
Further improvements to tokenizing regular expressions in corner cases.
## 6.0.3 (2018-11-04)
### Bug fixes
Fix bug in tokenizing an expression-less return followed by a function followed by a regular expression.
Remove stray symlink in the package tarball.
## 6.0.2 (2018-09-26)
### Bug fixes
Fix bug where default expressions could fail to parse inside an object destructuring assignment expression.
## 6.0.1 (2018-09-14)
### Bug fixes
Fix wrong value in `version` export.
## 6.0.0 (2018-09-14)
### Bug fixes
Better handle variable-redefinition checks for catch bindings and functions directly under if statements.
Forbid `new.target` in top-level arrow functions.
Fix issue with parsing a regexp after `yield` in some contexts.
### New features
The package now comes with TypeScript definitions.
### Breaking changes
The default value of the `ecmaVersion` option is now 9 (2018).
Plugins work differently, and will have to be rewritten to work with this version.
The loose parser and walker have been moved into separate packages (`acorn-loose` and `acorn-walk`).
## 5.7.3 (2018-09-10)
### Bug fixes
Fix failure to tokenize regexps after expressions like `x.of`.
Better error message for unterminated template literals.
## 5.7.2 (2018-08-24)
### Bug fixes
Properly handle `allowAwaitOutsideFunction` in for statements.
Treat function declarations at the top level of modules like let bindings.
Don't allow async function declarations as the only statement under a label.
## 5.7.0 (2018-06-15)
### New features
Upgraded to Unicode 11.
## 5.6.0 (2018-05-31)
### New features
Allow U+2028 and U+2029 in string when ECMAVersion >= 10.
Allow binding-less catch statements when ECMAVersion >= 10.
Add `allowAwaitOutsideFunction` option for parsing top-level `await`.
## 5.5.3 (2018-03-08)
### Bug fixes
A _second_ republish of the code in 5.5.1, this time with yarn, to hopefully get valid timestamps.
## 5.5.2 (2018-03-08)
### Bug fixes
A republish of the code in 5.5.1 in an attempt to solve an issue with the file timestamps in the npm package being 0.
## 5.5.1 (2018-03-06)
### Bug fixes
Fix misleading error message for octal escapes in template strings.
## 5.5.0 (2018-02-27)
### New features
The identifier character categorization is now based on Unicode version 10.
Acorn will now validate the content of regular expressions, including new ES9 features.
## 5.4.0 (2018-02-01)
### Bug fixes
Disallow duplicate or escaped flags on regular expressions.
Disallow octal escapes in strings in strict mode.
### New features
Add support for async iteration.
Add support for object spread and rest.
## 5.3.0 (2017-12-28)
### Bug fixes
Fix parsing of floating point literals with leading zeroes in loose mode.
Allow duplicate property names in object patterns.
Don't allow static class methods named `prototype`.
Disallow async functions directly under `if` or `else`.
Parse right-hand-side of `for`/`of` as an assignment expression.
Stricter parsing of `for`/`in`.
Don't allow unicode escapes in contextual keywords.
### New features
Parsing class members was factored into smaller methods to allow plugins to hook into it.
## 5.2.1 (2017-10-30)
### Bug fixes
Fix a token context corruption bug.
## 5.2.0 (2017-10-30)
### Bug fixes
Fix token context tracking for `class` and `function` in property-name position.
Make sure `%*` isn't parsed as a valid operator.
Allow shorthand properties `get` and `set` to be followed by default values.
Disallow `super` when not in callee or object position.
### New features
Support [`directive` property](https://github.com/estree/estree/compare/b3de58c9997504d6fba04b72f76e6dd1619ee4eb...1da8e603237144f44710360f8feb7a9977e905e0) on directive expression statements.
## 5.1.2 (2017-09-04)
### Bug fixes
Disable parsing of legacy HTML-style comments in modules.
Fix parsing of async methods whose names are keywords.
## 5.1.1 (2017-07-06)
### Bug fixes
Fix problem with disambiguating regexp and division after a class.
## 5.1.0 (2017-07-05)
### Bug fixes
Fix tokenizing of regexps in an object-desctructuring `for`/`of` loop and after `yield`.
Parse zero-prefixed numbers with non-octal digits as decimal.
Allow object/array patterns in rest parameters.
Don't error when `yield` is used as a property name.
Allow `async` as a shorthand object property.
### New features
Implement the [template literal revision proposal](https://github.com/tc39/proposal-template-literal-revision) for ES9.
## 5.0.3 (2017-04-01)
### Bug fixes
Fix spurious duplicate variable definition errors for named functions.
## 5.0.2 (2017-03-30)
### Bug fixes
A binary operator after a parenthesized arrow expression is no longer incorrectly treated as an error.
## 5.0.0 (2017-03-28)
### Bug fixes
Raise an error for duplicated lexical bindings.
Fix spurious error when an assignement expression occurred after a spread expression.
Accept regular expressions after `of` (in `for`/`of`), `yield` (in a generator), and braced arrow functions.
Allow labels in front or `var` declarations, even in strict mode.
### Breaking changes
Parse declarations following `export default` as declaration nodes, not expressions. This means that class and function declarations nodes can now have `null` as their `id`.
## 4.0.11 (2017-02-07)
### Bug fixes
Allow all forms of member expressions to be parenthesized as lvalue.
## 4.0.10 (2017-02-07)
### Bug fixes
Don't expect semicolons after default-exported functions or classes, even when they are expressions.
Check for use of `'use strict'` directives in non-simple parameter functions, even when already in strict mode.
## 4.0.9 (2017-02-06)
### Bug fixes
Fix incorrect error raised for parenthesized simple assignment targets, so that `(x) = 1` parses again.
## 4.0.8 (2017-02-03)
### Bug fixes
Solve spurious parenthesized pattern errors by temporarily erring on the side of accepting programs that our delayed errors don't handle correctly yet.
## 4.0.7 (2017-02-02)
### Bug fixes
Accept invalidly rejected code like `(x).y = 2` again.
Don't raise an error when a function _inside_ strict code has a non-simple parameter list.
## 4.0.6 (2017-02-02)
### Bug fixes
Fix exponential behavior (manifesting itself as a complete hang for even relatively small source files) introduced by the new 'use strict' check.
## 4.0.5 (2017-02-02)
### Bug fixes
Disallow parenthesized pattern expressions.
Allow keywords as export names.
Don't allow the `async` keyword to be parenthesized.
Properly raise an error when a keyword contains a character escape.
Allow `"use strict"` to appear after other string literal expressions.
Disallow labeled declarations.
## 4.0.4 (2016-12-19)
### Bug fixes
Fix crash when `export` was followed by a keyword that can't be
exported.
## 4.0.3 (2016-08-16)
### Bug fixes
Allow regular function declarations inside single-statement `if` branches in loose mode. Forbid them entirely in strict mode.
Properly parse properties named `async` in ES2017 mode.
Fix bug where reserved words were broken in ES2017 mode.
## 4.0.2 (2016-08-11)
### Bug fixes
Don't ignore period or 'e' characters after octal numbers.
Fix broken parsing for call expressions in default parameter values of arrow functions.
## 4.0.1 (2016-08-08)
### Bug fixes
Fix false positives in duplicated export name errors.
## 4.0.0 (2016-08-07)
### Breaking changes
The default `ecmaVersion` option value is now 7.
A number of internal method signatures changed, so plugins might need to be updated.
### Bug fixes
The parser now raises errors on duplicated export names.
`arguments` and `eval` can now be used in shorthand properties.
Duplicate parameter names in non-simple argument lists now always produce an error.
### New features
The `ecmaVersion` option now also accepts year-style version numbers
(2015, etc).
Support for `async`/`await` syntax when `ecmaVersion` is >= 8.
Support for trailing commas in call expressions when `ecmaVersion` is >= 8.
## 3.3.0 (2016-07-25)
### Bug fixes
Fix bug in tokenizing of regexp operator after a function declaration.
Fix parser crash when parsing an array pattern with a hole.
### New features
Implement check against complex argument lists in functions that enable strict mode in ES7.
## 3.2.0 (2016-06-07)
### Bug fixes
Improve handling of lack of unicode regexp support in host
environment.
Properly reject shorthand properties whose name is a keyword.
### New features
Visitors created with `visit.make` now have their base as _prototype_, rather than copying properties into a fresh object.
## 3.1.0 (2016-04-18)
### Bug fixes
Properly tokenize the division operator directly after a function expression.
Allow trailing comma in destructuring arrays.
## 3.0.4 (2016-02-25)
### Fixes
Allow update expressions as left-hand-side of the ES7 exponential operator.
## 3.0.2 (2016-02-10)
### Fixes
Fix bug that accidentally made `undefined` a reserved word when parsing ES7.
## 3.0.0 (2016-02-10)
### Breaking changes
The default value of the `ecmaVersion` option is now 6 (used to be 5).
Support for comprehension syntax (which was dropped from the draft spec) has been removed.
### Fixes
`let` and `yield` are now “contextual keywords”, meaning you can mostly use them as identifiers in ES5 non-strict code.
A parenthesized class or function expression after `export default` is now parsed correctly.
### New features
When `ecmaVersion` is set to 7, Acorn will parse the exponentiation operator (`**`).
The identifier character ranges are now based on Unicode 8.0.0.
Plugins can now override the `raiseRecoverable` method to override the way non-critical errors are handled.
## 2.7.0 (2016-01-04)
### Fixes
Stop allowing rest parameters in setters.
Disallow `y` rexexp flag in ES5.
Disallow `\00` and `\000` escapes in strict mode.
Raise an error when an import name is a reserved word.
## 2.6.2 (2015-11-10)
### Fixes
Don't crash when no options object is passed.
## 2.6.0 (2015-11-09)
### Fixes
Add `await` as a reserved word in module sources.
Disallow `yield` in a parameter default value for a generator.
Forbid using a comma after a rest pattern in an array destructuring.
### New features
Support parsing stdin in command-line tool.
## 2.5.0 (2015-10-27)
### Fixes
Fix tokenizer support in the command-line tool.
Stop allowing `new.target` outside of functions.
Remove legacy `guard` and `guardedHandler` properties from try nodes.
Stop allowing multiple `__proto__` properties on an object literal in strict mode.
Don't allow rest parameters to be non-identifier patterns.
Check for duplicate paramter names in arrow functions.
MIT License
Copyright (C) 2012-2018 by various contributors (see AUTHORS)
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.
# Acorn
A tiny, fast JavaScript parser written in JavaScript.
## Community
Acorn is open source software released under an
[MIT license](https://github.com/acornjs/acorn/blob/master/acorn/LICENSE).
You are welcome to
[report bugs](https://github.com/acornjs/acorn/issues) or create pull
requests on [github](https://github.com/acornjs/acorn). For questions
and discussion, please use the
[Tern discussion forum](https://discuss.ternjs.net).
## Installation
The easiest way to install acorn is from [`npm`](https://www.npmjs.com/):
```sh
npm install acorn
```
Alternately, you can download the source and build acorn yourself:
```sh
git clone https://github.com/acornjs/acorn.git
cd acorn
npm install
```
## Interface
**parse**`(input, options)` is the main interface to the library. The
`input` parameter is a string, `options` can be undefined or an object
setting some of the options listed below. The return value will be an
abstract syntax tree object as specified by the [ESTree
spec](https://github.com/estree/estree).
```javascript
let acorn = require("acorn");
console.log(acorn.parse("1 + 1"));
```
When encountering a syntax error, the parser will raise a
`SyntaxError` object with a meaningful message. The error object will
have a `pos` property that indicates the string offset at which the
error occurred, and a `loc` object that contains a `{line, column}`
object referring to that same position.
Options can be provided by passing a second argument, which should be
an object containing any of these fields:
- **ecmaVersion**: Indicates the ECMAScript version to parse. Must be
either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018), 10 (2019) or 11
(2020, partial support). This influences support for strict mode,
the set of reserved words, and support for new syntax features.
Default is 10.
**NOTE**: Only 'stage 4' (finalized) ECMAScript features are being
implemented by Acorn. Other proposed new features can be implemented
through plugins.
- **sourceType**: Indicate the mode the code should be parsed in. Can be
either `"script"` or `"module"`. This influences global strict mode
and parsing of `import` and `export` declarations.
**NOTE**: If set to `"module"`, then static `import` / `export` syntax
will be valid, even if `ecmaVersion` is less than 6.
- **onInsertedSemicolon**: If given a callback, that callback will be
called whenever a missing semicolon is inserted by the parser. The
callback will be given the character offset of the point where the
semicolon is inserted as argument, and if `locations` is on, also a
`{line, column}` object representing this position.
- **onTrailingComma**: Like `onInsertedSemicolon`, but for trailing
commas.
- **allowReserved**: If `false`, using a reserved word will generate
an error. Defaults to `true` for `ecmaVersion` 3, `false` for higher
versions. When given the value `"never"`, reserved words and
keywords can also not be used as property names (as in Internet
Explorer's old parser).
- **allowReturnOutsideFunction**: By default, a return statement at
the top level raises an error. Set this to `true` to accept such
code.
- **allowImportExportEverywhere**: By default, `import` and `export`
declarations can only appear at a program's top level. Setting this
option to `true` allows them anywhere where a statement is allowed.
- **allowAwaitOutsideFunction**: By default, `await` expressions can
only appear inside `async` functions. Setting this option to
`true` allows to have top-level `await` expressions. They are
still not allowed in non-`async` functions, though.
- **allowHashBang**: When this is enabled (off by default), if the
code starts with the characters `#!` (as in a shellscript), the
first line will be treated as a comment.
- **locations**: When `true`, each node has a `loc` object attached
with `start` and `end` subobjects, each of which contains the
one-based line and zero-based column numbers in `{line, column}`
form. Default is `false`.
- **onToken**: If a function is passed for this option, each found
token will be passed in same format as tokens returned from
`tokenizer().getToken()`.
If array is passed, each found token is pushed to it.
Note that you are not allowed to call the parser from the
callback—that will corrupt its internal state.
- **onComment**: If a function is passed for this option, whenever a
comment is encountered the function will be called with the
following parameters:
- `block`: `true` if the comment is a block comment, false if it
is a line comment.
- `text`: The content of the comment.
- `start`: Character offset of the start of the comment.
- `end`: Character offset of the end of the comment.
When the `locations` options is on, the `{line, column}` locations
of the comment’s start and end are passed as two additional
parameters.
If array is passed for this option, each found comment is pushed
to it as object in Esprima format:
```javascript
{
"type": "Line" | "Block",
"value": "comment text",
"start": Number,
"end": Number,
// If `locations` option is on:
"loc": {
"start": {line: Number, column: Number}
"end": {line: Number, column: Number}
},
// If `ranges` option is on:
"range": [Number, Number]
}
```
Note that you are not allowed to call the parser from the
callback—that will corrupt its internal state.
- **ranges**: Nodes have their start and end characters offsets
recorded in `start` and `end` properties (directly on the node,
rather than the `loc` object, which holds line/column data. To also
add a
[semi-standardized](https://bugzilla.mozilla.org/show_bug.cgi?id=745678)
`range` property holding a `[start, end]` array with the same
numbers, set the `ranges` option to `true`.
- **program**: It is possible to parse multiple files into a single
AST by passing the tree produced by parsing the first file as the
`program` option in subsequent parses. This will add the toplevel
forms of the parsed file to the "Program" (top) node of an existing
parse tree.
- **sourceFile**: When the `locations` option is `true`, you can pass
this option to add a `source` attribute in every node’s `loc`
object. Note that the contents of this option are not examined or
processed in any way; you are free to use whatever format you
choose.
- **directSourceFile**: Like `sourceFile`, but a `sourceFile` property
will be added (regardless of the `location` option) directly to the
nodes, rather than the `loc` object.
- **preserveParens**: If this option is `true`, parenthesized expressions
are represented by (non-standard) `ParenthesizedExpression` nodes
that have a single `expression` property containing the expression
inside parentheses.
**parseExpressionAt**`(input, offset, options)` will parse a single
expression in a string, and return its AST. It will not complain if
there is more of the string left after the expression.
**tokenizer**`(input, options)` returns an object with a `getToken`
method that can be called repeatedly to get the next token, a `{start,
end, type, value}` object (with added `loc` property when the
`locations` option is enabled and `range` property when the `ranges`
option is enabled). When the token's type is `tokTypes.eof`, you
should stop calling the method, since it will keep returning that same
token forever.
In ES6 environment, returned result can be used as any other
protocol-compliant iterable:
```javascript
for (let token of acorn.tokenizer(str)) {
// iterate over the tokens
}
// transform code to array of tokens:
var tokens = [...acorn.tokenizer(str)];
```
**tokTypes** holds an object mapping names to the token type objects
that end up in the `type` properties of tokens.
**getLineInfo**`(input, offset)` can be used to get a `{line,
column}` object for a given program string and offset.
### The `Parser` class
Instances of the **`Parser`** class contain all the state and logic
that drives a parse. It has static methods `parse`,
`parseExpressionAt`, and `tokenizer` that match the top-level
functions by the same name.
When extending the parser with plugins, you need to call these methods
on the extended version of the class. To extend a parser with plugins,
you can use its static `extend` method.
```javascript
var acorn = require("acorn");
var jsx = require("acorn-jsx");
var JSXParser = acorn.Parser.extend(jsx());
JSXParser.parse("foo(<bar/>)");
```
The `extend` method takes any number of plugin values, and returns a
new `Parser` class that includes the extra parser logic provided by
the plugins.
## Command line interface
The `bin/acorn` utility can be used to parse a file from the command
line. It accepts as arguments its input file and the following
options:
- `--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|--ecma10`: Sets the ECMAScript version
to parse. Default is version 9.
- `--module`: Sets the parsing mode to `"module"`. Is set to `"script"` otherwise.
- `--locations`: Attaches a "loc" object to each node with "start" and
"end" subobjects, each of which contains the one-based line and
zero-based column numbers in `{line, column}` form.
- `--allow-hash-bang`: If the code starts with the characters #! (as
in a shellscript), the first line will be treated as a comment.
- `--compact`: No whitespace is used in the AST output.
- `--silent`: Do not output the AST, just return the exit status.
- `--help`: Print the usage information and quit.
The utility spits out the syntax tree as JSON data.
## Existing plugins
- [`acorn-jsx`](https://github.com/RReverser/acorn-jsx): Parse [Facebook JSX syntax extensions](https://github.com/facebook/jsx)
Plugins for ECMAScript proposals:
- [`acorn-stage3`](https://github.com/acornjs/acorn-stage3): Parse most stage 3 proposals, bundling:
- [`acorn-class-fields`](https://github.com/acornjs/acorn-class-fields): Parse [class fields proposal](https://github.com/tc39/proposal-class-fields)
- [`acorn-import-meta`](https://github.com/acornjs/acorn-import-meta): Parse [import.meta proposal](https://github.com/tc39/proposal-import-meta)
- [`acorn-private-methods`](https://github.com/acornjs/acorn-private-methods): parse [private methods, getters and setters proposal](https://github.com/tc39/proposal-private-methods)n