Socket
Socket
Sign inDemoInstall

hermes-parser

Package Overview
Dependencies
Maintainers
3
Versions
41
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

hermes-parser - npm Package Compare versions

Comparing version 0.5.0 to 0.6.0

33

dist/generated/visitor-keys.js
/**
* Copyright (c) Facebook, Inc. and its affiliates.
* Copyright (c) Meta Platforms, Inc. and affiliates.
*

@@ -10,2 +10,7 @@ * This source code is licensed under the MIT license found in the

*/
// lint directives to let us do some basic validation of generated files
/* eslint no-undef: 'error', no-unused-vars: ['error', {vars: "local"}], no-redeclare: 'error' */
/* global $NonMaybeType, $Partial, $ReadOnly, $ReadOnlyArray */
'use strict';

@@ -17,7 +22,7 @@

exports.NODE_LIST_CHILD = exports.NODE_CHILD = exports.HERMES_AST_VISITOR_KEYS = void 0;
var NODE_CHILD = 'Node';
const NODE_CHILD = 'Node';
exports.NODE_CHILD = NODE_CHILD;
var NODE_LIST_CHILD = 'NodeList';
const NODE_LIST_CHILD = 'NodeList';
exports.NODE_LIST_CHILD = NODE_LIST_CHILD;
var HERMES_AST_VISITOR_KEYS = {
const HERMES_AST_VISITOR_KEYS = {
AnyTypeAnnotation: {},

@@ -53,2 +58,4 @@ ArrayExpression: {

},
BigIntLiteral: {},
BigIntLiteralTypeAnnotation: {},
BinaryExpression: {

@@ -84,3 +91,3 @@ left: 'Node',

superTypeParameters: 'Node',
"implements": 'NodeList',
implements: 'NodeList',
decorators: 'NodeList',

@@ -94,3 +101,3 @@ body: 'Node'

superTypeParameters: 'Node',
"implements": 'NodeList',
implements: 'NodeList',
decorators: 'NodeList',

@@ -127,4 +134,4 @@ body: 'Node'

typeParameters: 'Node',
"extends": 'NodeList',
"implements": 'NodeList',
extends: 'NodeList',
implements: 'NodeList',
mixins: 'NodeList',

@@ -151,3 +158,3 @@ body: 'Node'

typeParameters: 'Node',
"extends": 'NodeList',
extends: 'NodeList',
body: 'Node'

@@ -269,3 +276,3 @@ },

params: 'NodeList',
"this": 'Node',
this: 'Node',
returnType: 'Node',

@@ -322,3 +329,3 @@ rest: 'Node',

typeParameters: 'Node',
"extends": 'NodeList',
extends: 'NodeList',
body: 'Node'

@@ -331,3 +338,3 @@ },

InterfaceTypeAnnotation: {
"extends": 'NodeList',
extends: 'NodeList',
body: 'Node'

@@ -548,3 +555,3 @@ },

variance: 'Node',
"default": 'Node'
default: 'Node'
},

@@ -551,0 +558,0 @@ TypeParameterDeclaration: {

@@ -6,14 +6,25 @@ "use strict";

});
exports["default"] = void 0;
exports.default = void 0;
var _visitorKeys = require("./generated/visitor-keys");
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
/*
This class does some very "javascripty" things in the name of
performance which are ultimately impossible to soundly type.
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
So instead of adding strict types and a large number of suppression
comments, instead it is left untyped and subclasses are strictly
typed via a separate flow declaration file.
*/
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/**

@@ -23,10 +34,6 @@ * The base class for transforming the Hermes AST to the desired output format.

*/
var HermesASTAdapter = /*#__PURE__*/function () {
function HermesASTAdapter(options) {
_classCallCheck(this, HermesASTAdapter);
_defineProperty(this, "sourceFilename", void 0);
_defineProperty(this, "sourceType", void 0);
class HermesASTAdapter {
constructor(options) {
this.sourceFilename = void 0;
this.sourceType = void 0;
this.sourceFilename = options.sourceFilename;

@@ -41,160 +48,142 @@ this.sourceType = options.sourceType;

_createClass(HermesASTAdapter, [{
key: "transform",
value: function transform(program) {
// Comments are not traversed via visitor keys
var comments = program.comments;
transform(program) {
// Comments are not traversed via visitor keys
const comments = program.comments;
for (var i = 0; i < comments.length; i++) {
var comment = comments[i];
this.fixSourceLocation(comment);
comments[i] = this.mapComment(comment);
} // The first comment may be an interpreter directive and is stored directly on the program node
for (let i = 0; i < comments.length; i++) {
const comment = comments[i];
this.fixSourceLocation(comment);
comments[i] = this.mapComment(comment);
} // The first comment may be an interpreter directive and is stored directly on the program node
program.interpreter = comments.length > 0 && comments[0].type === 'InterpreterDirective' ? comments.shift() : null; // Tokens are not traversed via visitor keys
program.interpreter = comments.length > 0 && comments[0].type === 'InterpreterDirective' ? comments.shift() : null; // Tokens are not traversed via visitor keys
var tokens = program.tokens;
const tokens = program.tokens;
if (tokens) {
for (var _i = 0; _i < tokens.length; _i++) {
this.fixSourceLocation(tokens[_i]);
}
if (tokens) {
for (let i = 0; i < tokens.length; i++) {
this.fixSourceLocation(tokens[i]);
}
return this.mapNode(program);
}
/**
* Transform a Hermes AST node to the output AST format.
*
* This may modify the input node in-place and return that same node, or a completely
* new node may be constructed and returned. Overriden in child classes.
*/
}, {
key: "mapNode",
value: function mapNode(_node) {
throw new Error('Implemented in subclasses');
}
}, {
key: "mapNodeDefault",
value: function mapNodeDefault(node) {
var visitorKeys = _visitorKeys.HERMES_AST_VISITOR_KEYS[node.type];
return this.mapNode(program);
}
/**
* Transform a Hermes AST node to the output AST format.
*
* This may modify the input node in-place and return that same node, or a completely
* new node may be constructed and returned. Overriden in child classes.
*/
for (var key in visitorKeys) {
var childType = visitorKeys[key];
if (childType === _visitorKeys.NODE_CHILD) {
var child = node[key];
mapNode(_node) {
throw new Error('Implemented in subclasses');
}
if (child != null) {
node[key] = this.mapNode(child);
}
} else if (childType === _visitorKeys.NODE_LIST_CHILD) {
var children = node[key];
mapNodeDefault(node) {
const visitorKeys = _visitorKeys.HERMES_AST_VISITOR_KEYS[node.type];
for (var i = 0; i < children.length; i++) {
var _child = children[i];
for (const key in visitorKeys) {
const childType = visitorKeys[key];
if (_child != null) {
children[i] = this.mapNode(_child);
}
if (childType === _visitorKeys.NODE_CHILD) {
const child = node[key];
if (child != null) {
node[key] = this.mapNode(child);
}
} else if (childType === _visitorKeys.NODE_LIST_CHILD) {
const children = node[key];
for (let i = 0; i < children.length; i++) {
const child = children[i];
if (child != null) {
children[i] = this.mapNode(child);
}
}
}
return node;
}
/**
* Update the source location for this node depending on the output AST format.
* This can modify the input node in-place. Overriden in child classes.
*/
}, {
key: "fixSourceLocation",
value: function fixSourceLocation(_node) {
throw new Error('Implemented in subclasses');
return node;
}
/**
* Update the source location for this node depending on the output AST format.
* This can modify the input node in-place. Overriden in child classes.
*/
fixSourceLocation(_node) {
throw new Error('Implemented in subclasses');
}
getSourceType() {
var _this$sourceType;
return (_this$sourceType = this.sourceType) != null ? _this$sourceType : 'script';
}
setModuleSourceType() {
if (this.sourceType == null) {
this.sourceType = 'module';
}
}, {
key: "getSourceType",
value: function getSourceType() {
var _this$sourceType;
}
return (_this$sourceType = this.sourceType) !== null && _this$sourceType !== void 0 ? _this$sourceType : 'script';
mapComment(node) {
return node;
}
mapEmpty(_node) {
// $FlowExpectedError
return null;
}
mapImportDeclaration(node) {
if (node.importKind === 'value') {
this.setModuleSourceType();
}
}, {
key: "setModuleSourceType",
value: function setModuleSourceType() {
if (this.sourceType == null) {
this.sourceType = 'module';
}
}
}, {
key: "mapComment",
value: function mapComment(node) {
return node;
}
}, {
key: "mapEmpty",
value: function mapEmpty(_node) {
// $FlowExpectedError
return null;
}
}, {
key: "mapImportDeclaration",
value: function mapImportDeclaration(node) {
if (node.importKind === 'value') {
this.setModuleSourceType();
}
return this.mapNodeDefault(node);
return this.mapNodeDefault(node);
}
mapImportSpecifier(node) {
if (node.importKind === 'value') {
node.importKind = null;
}
}, {
key: "mapImportSpecifier",
value: function mapImportSpecifier(node) {
if (node.importKind === 'value') {
node.importKind = null;
}
return this.mapNodeDefault(node);
}
}, {
key: "mapExportDefaultDeclaration",
value: function mapExportDefaultDeclaration(node) {
return this.mapNodeDefault(node);
}
mapExportDefaultDeclaration(node) {
this.setModuleSourceType();
return this.mapNodeDefault(node);
}
mapExportNamedDeclaration(node) {
if (node.exportKind === 'value') {
this.setModuleSourceType();
return this.mapNodeDefault(node);
}
}, {
key: "mapExportNamedDeclaration",
value: function mapExportNamedDeclaration(node) {
if (node.exportKind === 'value') {
this.setModuleSourceType();
}
return this.mapNodeDefault(node);
}
}, {
key: "mapExportAllDeclaration",
value: function mapExportAllDeclaration(node) {
if (node.exportKind === 'value') {
this.setModuleSourceType();
}
return this.mapNodeDefault(node);
}
return this.mapNodeDefault(node);
mapExportAllDeclaration(node) {
if (node.exportKind === 'value') {
this.setModuleSourceType();
}
}, {
key: "mapPrivateProperty",
value: function mapPrivateProperty(node) {
throw new SyntaxError(this.formatError(node, 'Private properties are not supported'));
}
}, {
key: "formatError",
value: function formatError(node, message) {
return "".concat(message, " (").concat(node.loc.start.line, ":").concat(node.loc.start.column, ")");
}
}]);
return HermesASTAdapter;
}();
return this.mapNodeDefault(node);
}
exports["default"] = HermesASTAdapter;
mapPrivateProperty(node) {
throw new SyntaxError(this.formatError(node, 'Private properties are not supported'));
}
formatError(node, message) {
return `${message} (${node.loc.start.line}:${node.loc.start.column})`;
}
}
exports.default = HermesASTAdapter;
/**
* Copyright (c) Facebook, Inc. and its affiliates.
* Copyright (c) Meta Platforms, Inc. and affiliates.
*

@@ -21,25 +21,25 @@ * This source code is licensed under the MIT license found in the

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var hermesParse = _HermesParserWASM["default"].cwrap('hermesParse', 'number', ['number', 'number', 'number', 'number', 'number']);
const hermesParse = _HermesParserWASM.default.cwrap('hermesParse', 'number', ['number', 'number', 'number', 'number', 'number']);
var hermesParseResult_free = _HermesParserWASM["default"].cwrap('hermesParseResult_free', 'void', ['number']);
const hermesParseResult_free = _HermesParserWASM.default.cwrap('hermesParseResult_free', 'void', ['number']);
var hermesParseResult_getError = _HermesParserWASM["default"].cwrap('hermesParseResult_getError', 'string', ['number']);
const hermesParseResult_getError = _HermesParserWASM.default.cwrap('hermesParseResult_getError', 'string', ['number']);
var hermesParseResult_getErrorLine = _HermesParserWASM["default"].cwrap('hermesParseResult_getErrorLine', 'number', ['number']);
const hermesParseResult_getErrorLine = _HermesParserWASM.default.cwrap('hermesParseResult_getErrorLine', 'number', ['number']);
var hermesParseResult_getErrorColumn = _HermesParserWASM["default"].cwrap('hermesParseResult_getErrorColumn', 'number', ['number']);
const hermesParseResult_getErrorColumn = _HermesParserWASM.default.cwrap('hermesParseResult_getErrorColumn', 'number', ['number']);
var hermesParseResult_getProgramBuffer = _HermesParserWASM["default"].cwrap('hermesParseResult_getProgramBuffer', 'number', ['number']);
const hermesParseResult_getProgramBuffer = _HermesParserWASM.default.cwrap('hermesParseResult_getProgramBuffer', 'number', ['number']);
var hermesParseResult_getPositionBuffer = _HermesParserWASM["default"].cwrap('hermesParseResult_getPositionBuffer', 'number', ['number']);
const hermesParseResult_getPositionBuffer = _HermesParserWASM.default.cwrap('hermesParseResult_getPositionBuffer', 'number', ['number']);
var hermesParseResult_getPositionBufferSize = _HermesParserWASM["default"].cwrap('hermesParseResult_getPositionBufferSize', 'number', ['number']); // Copy a string into the WASM heap and null-terminate
const hermesParseResult_getPositionBufferSize = _HermesParserWASM.default.cwrap('hermesParseResult_getPositionBufferSize', 'number', ['number']); // Copy a string into the WASM heap and null-terminate
function copyToHeap(buffer, addr) {
_HermesParserWASM["default"].HEAP8.set(buffer, addr);
_HermesParserWASM.default.HEAP8.set(buffer, addr);
_HermesParserWASM["default"].HEAP8[addr + buffer.length] = 0;
_HermesParserWASM.default.HEAP8[addr + buffer.length] = 0;
}

@@ -49,5 +49,5 @@

// Allocate space on heap for source text
var sourceBuffer = Buffer.from(source, 'utf8');
const sourceBuffer = Buffer.from(source, 'utf8');
var sourceAddr = _HermesParserWASM["default"]._malloc(sourceBuffer.length + 1);
const sourceAddr = _HermesParserWASM.default._malloc(sourceBuffer.length + 1);

@@ -61,10 +61,10 @@ if (!sourceAddr) {

copyToHeap(sourceBuffer, sourceAddr);
var parseResult = hermesParse(sourceAddr, sourceBuffer.length + 1, options.flow === 'detect', options.tokens, options.allowReturnOutsideFunction);
const parseResult = hermesParse(sourceAddr, sourceBuffer.length + 1, options.flow === 'detect', options.tokens, options.allowReturnOutsideFunction);
try {
// Extract and throw error from parse result if parsing failed
var err = hermesParseResult_getError(parseResult);
const err = hermesParseResult_getError(parseResult);
if (err) {
var syntaxError = new SyntaxError(err); // $FlowExpectedError[prop-missing]
const syntaxError = new SyntaxError(err); // $FlowExpectedError[prop-missing]

@@ -78,3 +78,3 @@ syntaxError.loc = {

var deserializer = new _HermesParserDeserializer["default"](hermesParseResult_getProgramBuffer(parseResult), hermesParseResult_getPositionBuffer(parseResult), hermesParseResult_getPositionBufferSize(parseResult), _HermesParserWASM["default"], options);
const deserializer = new _HermesParserDeserializer.default(hermesParseResult_getProgramBuffer(parseResult), hermesParseResult_getPositionBuffer(parseResult), hermesParseResult_getPositionBufferSize(parseResult), _HermesParserWASM.default, options);
return deserializer.deserialize();

@@ -85,4 +85,4 @@ } finally {

} finally {
_HermesParserWASM["default"]._free(sourceAddr);
_HermesParserWASM.default._free(sourceAddr);
}
}
/**
* Copyright (c) Facebook, Inc. and its affiliates.
* Copyright (c) Meta Platforms, Inc. and affiliates.
*

@@ -23,12 +23,12 @@ * This source code is licensed under the MIT license found in the

});
exports["default"] = HermesParserDecodeUTF8String;
exports.default = HermesParserDecodeUTF8String;
function HermesParserDecodeUTF8String(ptrIn, length, heap) {
var ptr = ptrIn;
var endPtr = ptr + length;
var str = '';
let ptr = ptrIn;
const endPtr = ptr + length;
let str = '';
while (ptr < endPtr) {
// ASCII characters fit in single byte code point
var u0 = heap[ptr++];
let u0 = heap[ptr++];

@@ -41,5 +41,5 @@ if (!(u0 & 0x80)) {

var u1 = heap[ptr++] & 0x3f;
const u1 = heap[ptr++] & 0x3f;
if ((u0 & 0xe0) == 0xc0) {
if ((u0 & 0xe0) === 0xc0) {
str += String.fromCharCode((u0 & 0x1f) << 6 | u1);

@@ -49,5 +49,5 @@ continue;

var u2 = heap[ptr++] & 0x3f;
const u2 = heap[ptr++] & 0x3f;
if ((u0 & 0xf0) == 0xe0) {
if ((u0 & 0xf0) === 0xe0) {
// Three byte code point

@@ -54,0 +54,0 @@ u0 = (u0 & 0x0f) << 12 | u1 << 6 | u2;

/**
* Copyright (c) Facebook, Inc. and its affiliates.
* Copyright (c) Meta Platforms, Inc. and affiliates.
*

@@ -15,3 +15,3 @@ * This source code is licensed under the MIT license found in the

});
exports["default"] = void 0;
exports.default = void 0;

@@ -22,38 +22,18 @@ var _HermesParserDecodeUTF8String = _interopRequireDefault(require("./HermesParserDecodeUTF8String"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var HermesParserDeserializer = /*#__PURE__*/function () {
class HermesParserDeserializer {
// Matches StoredComment::Kind enum in JSLexer.h
// Matches TokenType enum in HermesParserJSSerializer.h
function HermesParserDeserializer(programBuffer, positionBuffer, positionBufferSize, wasmParser, options) {
_classCallCheck(this, HermesParserDeserializer);
_defineProperty(this, "programBufferIdx", void 0);
_defineProperty(this, "positionBufferIdx", void 0);
_defineProperty(this, "positionBufferSize", void 0);
_defineProperty(this, "locMap", void 0);
_defineProperty(this, "HEAPU8", void 0);
_defineProperty(this, "HEAPU32", void 0);
_defineProperty(this, "HEAPF64", void 0);
_defineProperty(this, "options", void 0);
_defineProperty(this, "commentTypes", ['CommentLine', 'CommentBlock', 'InterpreterDirective']);
_defineProperty(this, "tokenTypes", ['Boolean', 'Identifier', 'Keyword', 'Null', 'Numeric', 'Punctuator', 'String', 'RegularExpression', 'Template', 'JSXText']);
constructor(programBuffer, positionBuffer, positionBufferSize, wasmParser, options) {
this.programBufferIdx = void 0;
this.positionBufferIdx = void 0;
this.positionBufferSize = void 0;
this.locMap = void 0;
this.HEAPU8 = void 0;
this.HEAPU32 = void 0;
this.HEAPF64 = void 0;
this.options = void 0;
this.commentTypes = ['CommentLine', 'CommentBlock', 'InterpreterDirective'];
this.tokenTypes = ['Boolean', 'Identifier', 'Keyword', 'Null', 'Numeric', 'BigInt', 'Punctuator', 'String', 'RegularExpression', 'Template', 'JSXText'];
// Program and position buffer are memory addresses, so we must convert

@@ -75,206 +55,192 @@ // into indices into HEAPU32 (an array of 4-byte integers).

_createClass(HermesParserDeserializer, [{
key: "next",
value: function next() {
var num = this.HEAPU32[this.programBufferIdx++];
return num;
}
}, {
key: "deserialize",
value: function deserialize() {
var program = {
type: 'Program',
loc: this.addEmptyLoc(),
body: this.deserializeNodeList(),
comments: this.deserializeComments()
};
next() {
const num = this.HEAPU32[this.programBufferIdx++];
return num;
}
if (this.options.tokens === true) {
program.tokens = this.deserializeTokens();
}
deserialize() {
const program = {
type: 'Program',
loc: this.addEmptyLoc(),
body: this.deserializeNodeList(),
comments: this.deserializeComments()
};
this.fillLocs();
return program;
if (this.options.tokens === true) {
program.tokens = this.deserializeTokens();
}
/**
* Booleans are serialized as a single 4-byte integer.
*/
}, {
key: "deserializeBoolean",
value: function deserializeBoolean() {
return Boolean(this.next());
}
/**
* Numbers are serialized directly into program buffer, taking up 8 bytes
* preceded by 4 bytes of alignment padding if necessary.
*/
this.fillLocs();
return program;
}
/**
* Booleans are serialized as a single 4-byte integer.
*/
}, {
key: "deserializeNumber",
value: function deserializeNumber() {
var floatIdx; // Numbers are aligned on 8-byte boundaries, so skip padding if we are at
// an odd index into the 4-byte aligned program buffer.
if (this.programBufferIdx % 2 === 0) {
floatIdx = this.programBufferIdx / 2;
this.programBufferIdx += 2;
} else {
floatIdx = (this.programBufferIdx + 1) / 2;
this.programBufferIdx += 3;
}
deserializeBoolean() {
return Boolean(this.next());
}
/**
* Numbers are serialized directly into program buffer, taking up 8 bytes
* preceded by 4 bytes of alignment padding if necessary.
*/
return this.HEAPF64[floatIdx];
deserializeNumber() {
let floatIdx; // Numbers are aligned on 8-byte boundaries, so skip padding if we are at
// an odd index into the 4-byte aligned program buffer.
if (this.programBufferIdx % 2 === 0) {
floatIdx = this.programBufferIdx / 2;
this.programBufferIdx += 2;
} else {
floatIdx = (this.programBufferIdx + 1) / 2;
this.programBufferIdx += 3;
}
/**
* Strings are serialized as a 4-byte pointer into the heap, followed
* by their size as a 4-byte integer. The size is only present if the
* pointer is non-null.
*/
}, {
key: "deserializeString",
value: function deserializeString() {
var ptr = this.next();
return this.HEAPF64[floatIdx];
}
/**
* Strings are serialized as a 4-byte pointer into the heap, followed
* by their size as a 4-byte integer. The size is only present if the
* pointer is non-null.
*/
if (ptr === 0) {
return null;
}
var size = this.next();
return (0, _HermesParserDecodeUTF8String["default"])(ptr, size, this.HEAPU8);
deserializeString() {
const ptr = this.next();
if (ptr === 0) {
return null;
}
/**
* Nodes are serialized as a 4-byte integer denoting their node kind,
* followed by a 4-byte loc ID, followed by serialized node properties.
*
* If the node kind is 0 the node is null, otherwise the node kind - 1 is an
* index into the array of node deserialization functions.
*/
}, {
key: "deserializeNode",
value: function deserializeNode() {
var nodeType = this.next();
const size = this.next();
return (0, _HermesParserDecodeUTF8String.default)(ptr, size, this.HEAPU8);
}
/**
* Nodes are serialized as a 4-byte integer denoting their node kind,
* followed by a 4-byte loc ID, followed by serialized node properties.
*
* If the node kind is 0 the node is null, otherwise the node kind - 1 is an
* index into the array of node deserialization functions.
*/
if (nodeType === 0) {
return null;
}
var nodeDeserializer = _HermesParserNodeDeserializers["default"][nodeType - 1].bind(this);
deserializeNode() {
const nodeType = this.next();
return nodeDeserializer();
if (nodeType === 0) {
return null;
}
/**
* Node lists are serialized as a 4-byte integer denoting the number of
* elements in the list, followed by the serialized elements.
*/
}, {
key: "deserializeNodeList",
value: function deserializeNodeList() {
var size = this.next();
var nodeList = [];
const nodeDeserializer = _HermesParserNodeDeserializers.default[nodeType - 1].bind(this);
for (var i = 0; i < size; i++) {
nodeList.push(this.deserializeNode());
}
return nodeDeserializer();
}
/**
* Node lists are serialized as a 4-byte integer denoting the number of
* elements in the list, followed by the serialized elements.
*/
return nodeList;
deserializeNodeList() {
const size = this.next();
const nodeList = [];
for (let i = 0; i < size; i++) {
nodeList.push(this.deserializeNode());
}
/**
* Comments are serialized as a node list, where each comment is serialized
* as a 4-byte integer denoting comment type, followed by a 4-byte value
* denoting the loc ID, followed by a serialized string for the comment value.
*/
}, {
key: "deserializeComments",
value: function deserializeComments() {
var size = this.next();
var comments = [];
return nodeList;
}
/**
* Comments are serialized as a node list, where each comment is serialized
* as a 4-byte integer denoting comment type, followed by a 4-byte value
* denoting the loc ID, followed by a serialized string for the comment value.
*/
for (var i = 0; i < size; i++) {
var commentType = this.commentTypes[this.next()];
var loc = this.addEmptyLoc();
var value = this.deserializeString();
comments.push({
type: commentType,
loc: loc,
value: value
});
}
return comments;
deserializeComments() {
const size = this.next();
const comments = [];
for (let i = 0; i < size; i++) {
const commentType = this.commentTypes[this.next()];
const loc = this.addEmptyLoc();
const value = this.deserializeString();
comments.push({
type: commentType,
loc,
value
});
}
}, {
key: "deserializeTokens",
value: function deserializeTokens() {
var size = this.next();
var tokens = [];
for (var i = 0; i < size; i++) {
var tokenType = this.tokenTypes[this.next()];
var loc = this.addEmptyLoc();
var value = this.deserializeString();
tokens.push({
type: tokenType,
loc: loc,
value: value
});
}
return comments;
}
return tokens;
}
/**
* While deserializing the AST locations are represented by
* a 4-byte loc ID. This is used to create a map of loc IDs to empty loc
* objects that are filled after the AST has been deserialized.
*/
deserializeTokens() {
const size = this.next();
const tokens = [];
}, {
key: "addEmptyLoc",
value: function addEmptyLoc() {
// $FlowExpectedError
var loc = {};
this.locMap[this.next()] = loc;
return loc;
for (let i = 0; i < size; i++) {
const tokenType = this.tokenTypes[this.next()];
const loc = this.addEmptyLoc();
const value = this.deserializeString();
tokens.push({
type: tokenType,
loc,
value
});
}
/**
* Positions are serialized as a loc ID which denotes which loc it is associated with,
* followed by kind which denotes whether it is a start or end position,
* followed by line, column, and offset (4-bytes each).
*/
}, {
key: "fillLocs",
value: function fillLocs() {
for (var i = 0; i < this.positionBufferSize; i++) {
var locId = this.HEAPU32[this.positionBufferIdx++];
var kind = this.HEAPU32[this.positionBufferIdx++];
var line = this.HEAPU32[this.positionBufferIdx++];
var column = this.HEAPU32[this.positionBufferIdx++];
var offset = this.HEAPU32[this.positionBufferIdx++];
var loc = this.locMap[locId];
return tokens;
}
/**
* While deserializing the AST locations are represented by
* a 4-byte loc ID. This is used to create a map of loc IDs to empty loc
* objects that are filled after the AST has been deserialized.
*/
if (kind === 0) {
loc.start = {
line: line,
column: column
};
loc.rangeStart = offset;
} else {
loc.end = {
line: line,
column: column
};
loc.rangeEnd = offset;
}
addEmptyLoc() {
// $FlowExpectedError
const loc = {};
this.locMap[this.next()] = loc;
return loc;
}
/**
* Positions are serialized as a loc ID which denotes which loc it is associated with,
* followed by kind which denotes whether it is a start or end position,
* followed by line, column, and offset (4-bytes each).
*/
fillLocs() {
for (let i = 0; i < this.positionBufferSize; i++) {
const locId = this.HEAPU32[this.positionBufferIdx++];
const kind = this.HEAPU32[this.positionBufferIdx++];
const line = this.HEAPU32[this.positionBufferIdx++];
const column = this.HEAPU32[this.positionBufferIdx++];
const offset = this.HEAPU32[this.positionBufferIdx++];
const loc = this.locMap[locId];
if (kind === 0) {
loc.start = {
line,
column
};
loc.rangeStart = offset;
} else {
loc.end = {
line,
column
};
loc.rangeEnd = offset;
}
}
}]);
}
return HermesParserDeserializer;
}();
}
exports["default"] = HermesParserDeserializer;
exports.default = HermesParserDeserializer;
/**
* Copyright (c) Facebook, Inc. and its affiliates.
* Copyright (c) Meta Platforms, Inc. and affiliates.
*

@@ -10,2 +10,7 @@ * This source code is licensed under the MIT license found in the

*/
// lint directives to let us do some basic validation of generated files
/* eslint no-undef: 'error', no-unused-vars: ['error', {vars: "local"}], no-redeclare: 'error' */
/* global $NonMaybeType, $Partial, $ReadOnly, $ReadOnlyArray */
'use strict';

@@ -131,3 +136,3 @@

body: this.deserializeNode(),
"await": this.deserializeBoolean()
await: this.deserializeBoolean()
};

@@ -305,2 +310,10 @@ }

function deserializeBigIntLiteral() {
return {
type: 'BigIntLiteral',
loc: this.addEmptyLoc(),
bigint: this.deserializeString()
};
}
function deserializeThisExpression() {

@@ -635,3 +648,3 @@ return {

superTypeParameters: this.deserializeNode(),
"implements": this.deserializeNodeList(),
implements: this.deserializeNodeList(),
decorators: this.deserializeNodeList(),

@@ -650,3 +663,3 @@ body: this.deserializeNode()

superTypeParameters: this.deserializeNode(),
"implements": this.deserializeNodeList(),
implements: this.deserializeNodeList(),
decorators: this.deserializeNodeList(),

@@ -672,3 +685,3 @@ body: this.deserializeNode()

computed: this.deserializeBoolean(),
"static": this.deserializeBoolean(),
static: this.deserializeBoolean(),
declare: this.deserializeBoolean(),

@@ -687,3 +700,3 @@ optional: this.deserializeBoolean(),

value: this.deserializeNode(),
"static": this.deserializeBoolean(),
static: this.deserializeBoolean(),
declare: this.deserializeBoolean(),

@@ -704,3 +717,3 @@ optional: this.deserializeBoolean(),

computed: this.deserializeBoolean(),
"static": this.deserializeBoolean()
static: this.deserializeBoolean()
};

@@ -927,2 +940,11 @@ }

function deserializeJSXStringLiteral() {
return {
type: 'JSXStringLiteral',
loc: this.addEmptyLoc(),
value: this.deserializeString(),
raw: this.deserializeString()
};
}
function deserializeJSXText() {

@@ -1003,3 +1025,4 @@ return {

loc: this.addEmptyLoc(),
value: this.deserializeString()
value: this.deserializeString(),
raw: this.deserializeString()
};

@@ -1017,2 +1040,10 @@ }

function deserializeBigIntLiteralTypeAnnotation() {
return {
type: 'BigIntLiteralTypeAnnotation',
loc: this.addEmptyLoc(),
raw: this.deserializeString()
};
}
function deserializeBooleanTypeAnnotation() {

@@ -1074,3 +1105,3 @@ return {

params: this.deserializeNodeList(),
"this": this.deserializeNode(),
this: this.deserializeNode(),
returnType: this.deserializeNode(),

@@ -1181,3 +1212,3 @@ rest: this.deserializeNode(),

loc: this.addEmptyLoc(),
"extends": this.deserializeNodeList(),
extends: this.deserializeNodeList(),
body: this.deserializeNode()

@@ -1214,3 +1245,3 @@ };

typeParameters: this.deserializeNode(),
"extends": this.deserializeNodeList(),
extends: this.deserializeNodeList(),
body: this.deserializeNode()

@@ -1247,3 +1278,3 @@ };

typeParameters: this.deserializeNode(),
"extends": this.deserializeNodeList(),
extends: this.deserializeNodeList(),
body: this.deserializeNode()

@@ -1259,4 +1290,4 @@ };

typeParameters: this.deserializeNode(),
"extends": this.deserializeNodeList(),
"implements": this.deserializeNodeList(),
extends: this.deserializeNodeList(),
implements: this.deserializeNodeList(),
mixins: this.deserializeNodeList(),

@@ -1291,3 +1322,3 @@ body: this.deserializeNode()

source: this.deserializeNode(),
"default": this.deserializeBoolean()
default: this.deserializeBoolean()
};

@@ -1369,3 +1400,3 @@ }

optional: this.deserializeBoolean(),
"static": this.deserializeBoolean(),
static: this.deserializeBoolean(),
proto: this.deserializeBoolean(),

@@ -1392,3 +1423,3 @@ variance: this.deserializeNode(),

optional: this.deserializeBoolean(),
"static": this.deserializeBoolean(),
static: this.deserializeBoolean(),
method: this.deserializeBoolean()

@@ -1403,3 +1434,3 @@ };

value: this.deserializeNode(),
"static": this.deserializeBoolean()
static: this.deserializeBoolean()
};

@@ -1415,3 +1446,3 @@ }

value: this.deserializeNode(),
"static": this.deserializeBoolean(),
static: this.deserializeBoolean(),
variance: this.deserializeNode()

@@ -1444,3 +1475,3 @@ };

variance: this.deserializeNode(),
"default": this.deserializeNode()
default: this.deserializeNode()
};

@@ -1726,4 +1757,4 @@ }

readonly: this.deserializeBoolean(),
"static": this.deserializeBoolean(),
"export": this.deserializeBoolean()
static: this.deserializeBoolean(),
export: this.deserializeBoolean()
};

@@ -1748,3 +1779,3 @@ }

body: this.deserializeNode(),
"extends": this.deserializeNodeList(),
extends: this.deserializeNodeList(),
typeParameters: this.deserializeNode()

@@ -1829,3 +1860,3 @@ };

constraint: this.deserializeNode(),
"default": this.deserializeNode()
default: this.deserializeNode()
};

@@ -1895,4 +1926,4 @@ }

readonly: this.deserializeBoolean(),
"static": this.deserializeBoolean(),
"export": this.deserializeBoolean()
static: this.deserializeBoolean(),
export: this.deserializeBoolean()
};

@@ -1978,2 +2009,2 @@ }

module.exports = [deserializeEmpty, deserializeMetadata, deserializeFunctionLikeFirst, deserializeProgram, deserializeFunctionExpression, deserializeArrowFunctionExpression, deserializeFunctionDeclaration, deserializeFunctionLikeLast, deserializeStatementFirst, deserializeLoopStatementFirst, deserializeWhileStatement, deserializeDoWhileStatement, deserializeForInStatement, deserializeForOfStatement, deserializeForStatement, deserializeLoopStatementLast, deserializeDebuggerStatement, deserializeEmptyStatement, deserializeBlockStatement, deserializeBreakStatement, deserializeContinueStatement, deserializeThrowStatement, deserializeReturnStatement, deserializeWithStatement, deserializeSwitchStatement, deserializeLabeledStatement, deserializeExpressionStatement, deserializeTryStatement, deserializeIfStatement, deserializeStatementLast, deserializeNullLiteral, deserializeBooleanLiteral, deserializeStringLiteral, deserializeNumericLiteral, deserializeRegExpLiteral, deserializeThisExpression, deserializeSuper, deserializeSequenceExpression, deserializeObjectExpression, deserializeArrayExpression, deserializeSpreadElement, deserializeNewExpression, deserializeYieldExpression, deserializeAwaitExpression, deserializeImportExpression, deserializeCallExpressionLikeFirst, deserializeCallExpression, deserializeOptionalCallExpression, deserializeCallExpressionLikeLast, deserializeAssignmentExpression, deserializeUnaryExpression, deserializeUpdateExpression, deserializeMemberExpressionLikeFirst, deserializeMemberExpression, deserializeOptionalMemberExpression, deserializeMemberExpressionLikeLast, deserializeLogicalExpression, deserializeConditionalExpression, deserializeBinaryExpression, deserializeDirective, deserializeDirectiveLiteral, deserializeIdentifier, deserializePrivateName, deserializeMetaProperty, deserializeSwitchCase, deserializeCatchClause, deserializeVariableDeclarator, deserializeVariableDeclaration, deserializeTemplateLiteral, deserializeTaggedTemplateExpression, deserializeTemplateElement, deserializeProperty, deserializeClassDeclaration, deserializeClassExpression, deserializeClassBody, deserializeClassProperty, deserializeClassPrivateProperty, deserializeMethodDefinition, deserializeImportDeclaration, deserializeImportSpecifier, deserializeImportDefaultSpecifier, deserializeImportNamespaceSpecifier, deserializeImportAttribute, deserializeExportNamedDeclaration, deserializeExportSpecifier, deserializeExportNamespaceSpecifier, deserializeExportDefaultDeclaration, deserializeExportAllDeclaration, deserializePatternFirst, deserializeObjectPattern, deserializeArrayPattern, deserializeRestElement, deserializeAssignmentPattern, deserializePatternLast, deserializeJSXIdentifier, deserializeJSXMemberExpression, deserializeJSXNamespacedName, deserializeJSXEmptyExpression, deserializeJSXExpressionContainer, deserializeJSXSpreadChild, deserializeJSXOpeningElement, deserializeJSXClosingElement, deserializeJSXAttribute, deserializeJSXSpreadAttribute, deserializeJSXText, deserializeJSXElement, deserializeJSXFragment, deserializeJSXOpeningFragment, deserializeJSXClosingFragment, deserializeExistsTypeAnnotation, deserializeEmptyTypeAnnotation, deserializeStringTypeAnnotation, deserializeNumberTypeAnnotation, deserializeStringLiteralTypeAnnotation, deserializeNumberLiteralTypeAnnotation, deserializeBooleanTypeAnnotation, deserializeBooleanLiteralTypeAnnotation, deserializeNullLiteralTypeAnnotation, deserializeSymbolTypeAnnotation, deserializeAnyTypeAnnotation, deserializeMixedTypeAnnotation, deserializeVoidTypeAnnotation, deserializeFunctionTypeAnnotation, deserializeFunctionTypeParam, deserializeNullableTypeAnnotation, deserializeQualifiedTypeIdentifier, deserializeTypeofTypeAnnotation, deserializeTupleTypeAnnotation, deserializeArrayTypeAnnotation, deserializeUnionTypeAnnotation, deserializeIntersectionTypeAnnotation, deserializeGenericTypeAnnotation, deserializeIndexedAccessType, deserializeOptionalIndexedAccessType, deserializeInterfaceTypeAnnotation, deserializeTypeAlias, deserializeOpaqueType, deserializeInterfaceDeclaration, deserializeDeclareTypeAlias, deserializeDeclareOpaqueType, deserializeDeclareInterface, deserializeDeclareClass, deserializeDeclareFunction, deserializeDeclareVariable, deserializeDeclareExportDeclaration, deserializeDeclareExportAllDeclaration, deserializeDeclareModule, deserializeDeclareModuleExports, deserializeInterfaceExtends, deserializeClassImplements, deserializeTypeAnnotation, deserializeObjectTypeAnnotation, deserializeObjectTypeProperty, deserializeObjectTypeSpreadProperty, deserializeObjectTypeInternalSlot, deserializeObjectTypeCallProperty, deserializeObjectTypeIndexer, deserializeVariance, deserializeTypeParameterDeclaration, deserializeTypeParameter, deserializeTypeParameterInstantiation, deserializeTypeCastExpression, deserializeInferredPredicate, deserializeDeclaredPredicate, deserializeEnumDeclaration, deserializeEnumStringBody, deserializeEnumNumberBody, deserializeEnumBooleanBody, deserializeEnumSymbolBody, deserializeEnumDefaultedMember, deserializeEnumStringMember, deserializeEnumNumberMember, deserializeEnumBooleanMember, deserializeTSTypeAnnotation, deserializeTSAnyKeyword, deserializeTSNumberKeyword, deserializeTSBooleanKeyword, deserializeTSStringKeyword, deserializeTSSymbolKeyword, deserializeTSVoidKeyword, deserializeTSThisType, deserializeTSLiteralType, deserializeTSIndexedAccessType, deserializeTSArrayType, deserializeTSTypeReference, deserializeTSQualifiedName, deserializeTSFunctionType, deserializeTSConstructorType, deserializeTSTypePredicate, deserializeTSTupleType, deserializeTSTypeAssertion, deserializeTSAsExpression, deserializeTSParameterProperty, deserializeTSTypeAliasDeclaration, deserializeTSInterfaceDeclaration, deserializeTSInterfaceHeritage, deserializeTSInterfaceBody, deserializeTSEnumDeclaration, deserializeTSEnumMember, deserializeTSModuleDeclaration, deserializeTSModuleBlock, deserializeTSModuleMember, deserializeTSTypeParameterDeclaration, deserializeTSTypeParameter, deserializeTSTypeParameterInstantiation, deserializeTSUnionType, deserializeTSIntersectionType, deserializeTSTypeQuery, deserializeTSConditionalType, deserializeTSTypeLiteral, deserializeTSPropertySignature, deserializeTSMethodSignature, deserializeTSIndexSignature, deserializeTSCallSignatureDeclaration, deserializeCoverFirst, deserializeCoverEmptyArgs, deserializeCoverTrailingComma, deserializeCoverInitializer, deserializeCoverRestElement, deserializeCoverTypedIdentifier, deserializeCoverLast];
module.exports = [deserializeEmpty, deserializeMetadata, deserializeFunctionLikeFirst, deserializeProgram, deserializeFunctionExpression, deserializeArrowFunctionExpression, deserializeFunctionDeclaration, deserializeFunctionLikeLast, deserializeStatementFirst, deserializeLoopStatementFirst, deserializeWhileStatement, deserializeDoWhileStatement, deserializeForInStatement, deserializeForOfStatement, deserializeForStatement, deserializeLoopStatementLast, deserializeDebuggerStatement, deserializeEmptyStatement, deserializeBlockStatement, deserializeBreakStatement, deserializeContinueStatement, deserializeThrowStatement, deserializeReturnStatement, deserializeWithStatement, deserializeSwitchStatement, deserializeLabeledStatement, deserializeExpressionStatement, deserializeTryStatement, deserializeIfStatement, deserializeStatementLast, deserializeNullLiteral, deserializeBooleanLiteral, deserializeStringLiteral, deserializeNumericLiteral, deserializeRegExpLiteral, deserializeBigIntLiteral, deserializeThisExpression, deserializeSuper, deserializeSequenceExpression, deserializeObjectExpression, deserializeArrayExpression, deserializeSpreadElement, deserializeNewExpression, deserializeYieldExpression, deserializeAwaitExpression, deserializeImportExpression, deserializeCallExpressionLikeFirst, deserializeCallExpression, deserializeOptionalCallExpression, deserializeCallExpressionLikeLast, deserializeAssignmentExpression, deserializeUnaryExpression, deserializeUpdateExpression, deserializeMemberExpressionLikeFirst, deserializeMemberExpression, deserializeOptionalMemberExpression, deserializeMemberExpressionLikeLast, deserializeLogicalExpression, deserializeConditionalExpression, deserializeBinaryExpression, deserializeDirective, deserializeDirectiveLiteral, deserializeIdentifier, deserializePrivateName, deserializeMetaProperty, deserializeSwitchCase, deserializeCatchClause, deserializeVariableDeclarator, deserializeVariableDeclaration, deserializeTemplateLiteral, deserializeTaggedTemplateExpression, deserializeTemplateElement, deserializeProperty, deserializeClassDeclaration, deserializeClassExpression, deserializeClassBody, deserializeClassProperty, deserializeClassPrivateProperty, deserializeMethodDefinition, deserializeImportDeclaration, deserializeImportSpecifier, deserializeImportDefaultSpecifier, deserializeImportNamespaceSpecifier, deserializeImportAttribute, deserializeExportNamedDeclaration, deserializeExportSpecifier, deserializeExportNamespaceSpecifier, deserializeExportDefaultDeclaration, deserializeExportAllDeclaration, deserializePatternFirst, deserializeObjectPattern, deserializeArrayPattern, deserializeRestElement, deserializeAssignmentPattern, deserializePatternLast, deserializeJSXIdentifier, deserializeJSXMemberExpression, deserializeJSXNamespacedName, deserializeJSXEmptyExpression, deserializeJSXExpressionContainer, deserializeJSXSpreadChild, deserializeJSXOpeningElement, deserializeJSXClosingElement, deserializeJSXAttribute, deserializeJSXSpreadAttribute, deserializeJSXStringLiteral, deserializeJSXText, deserializeJSXElement, deserializeJSXFragment, deserializeJSXOpeningFragment, deserializeJSXClosingFragment, deserializeExistsTypeAnnotation, deserializeEmptyTypeAnnotation, deserializeStringTypeAnnotation, deserializeNumberTypeAnnotation, deserializeStringLiteralTypeAnnotation, deserializeNumberLiteralTypeAnnotation, deserializeBigIntLiteralTypeAnnotation, deserializeBooleanTypeAnnotation, deserializeBooleanLiteralTypeAnnotation, deserializeNullLiteralTypeAnnotation, deserializeSymbolTypeAnnotation, deserializeAnyTypeAnnotation, deserializeMixedTypeAnnotation, deserializeVoidTypeAnnotation, deserializeFunctionTypeAnnotation, deserializeFunctionTypeParam, deserializeNullableTypeAnnotation, deserializeQualifiedTypeIdentifier, deserializeTypeofTypeAnnotation, deserializeTupleTypeAnnotation, deserializeArrayTypeAnnotation, deserializeUnionTypeAnnotation, deserializeIntersectionTypeAnnotation, deserializeGenericTypeAnnotation, deserializeIndexedAccessType, deserializeOptionalIndexedAccessType, deserializeInterfaceTypeAnnotation, deserializeTypeAlias, deserializeOpaqueType, deserializeInterfaceDeclaration, deserializeDeclareTypeAlias, deserializeDeclareOpaqueType, deserializeDeclareInterface, deserializeDeclareClass, deserializeDeclareFunction, deserializeDeclareVariable, deserializeDeclareExportDeclaration, deserializeDeclareExportAllDeclaration, deserializeDeclareModule, deserializeDeclareModuleExports, deserializeInterfaceExtends, deserializeClassImplements, deserializeTypeAnnotation, deserializeObjectTypeAnnotation, deserializeObjectTypeProperty, deserializeObjectTypeSpreadProperty, deserializeObjectTypeInternalSlot, deserializeObjectTypeCallProperty, deserializeObjectTypeIndexer, deserializeVariance, deserializeTypeParameterDeclaration, deserializeTypeParameter, deserializeTypeParameterInstantiation, deserializeTypeCastExpression, deserializeInferredPredicate, deserializeDeclaredPredicate, deserializeEnumDeclaration, deserializeEnumStringBody, deserializeEnumNumberBody, deserializeEnumBooleanBody, deserializeEnumSymbolBody, deserializeEnumDefaultedMember, deserializeEnumStringMember, deserializeEnumNumberMember, deserializeEnumBooleanMember, deserializeTSTypeAnnotation, deserializeTSAnyKeyword, deserializeTSNumberKeyword, deserializeTSBooleanKeyword, deserializeTSStringKeyword, deserializeTSSymbolKeyword, deserializeTSVoidKeyword, deserializeTSThisType, deserializeTSLiteralType, deserializeTSIndexedAccessType, deserializeTSArrayType, deserializeTSTypeReference, deserializeTSQualifiedName, deserializeTSFunctionType, deserializeTSConstructorType, deserializeTSTypePredicate, deserializeTSTupleType, deserializeTSTypeAssertion, deserializeTSAsExpression, deserializeTSParameterProperty, deserializeTSTypeAliasDeclaration, deserializeTSInterfaceDeclaration, deserializeTSInterfaceHeritage, deserializeTSInterfaceBody, deserializeTSEnumDeclaration, deserializeTSEnumMember, deserializeTSModuleDeclaration, deserializeTSModuleBlock, deserializeTSModuleMember, deserializeTSTypeParameterDeclaration, deserializeTSTypeParameter, deserializeTSTypeParameterInstantiation, deserializeTSUnionType, deserializeTSIntersectionType, deserializeTSTypeQuery, deserializeTSConditionalType, deserializeTSTypeLiteral, deserializeTSPropertySignature, deserializeTSMethodSignature, deserializeTSIndexSignature, deserializeTSCallSignatureDeclaration, deserializeCoverFirst, deserializeCoverEmptyArgs, deserializeCoverTrailingComma, deserializeCoverInitializer, deserializeCoverRestElement, deserializeCoverTypedIdentifier, deserializeCoverLast];
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
exports.default = void 0;
var _HermesASTAdapter2 = _interopRequireDefault(require("./HermesASTAdapter"));
var _HermesASTAdapter = _interopRequireDefault(require("./HermesASTAdapter"));
var _excluded = ["comments"];
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
/*
This class does some very "javascripty" things in the name of
performance which are ultimately impossible to soundly type.
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
So instead of adding strict types and a large number of suppression
comments, instead it is left untyped and subclasses are strictly
typed via a separate flow declaration file.
*/
class HermesToBabelAdapter extends _HermesASTAdapter.default {
fixSourceLocation(node) {
var _this$sourceFilename;
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
const loc = node.loc;
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
if (loc == null) {
return;
}
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
node.loc = {
source: (_this$sourceFilename = this.sourceFilename) != null ? _this$sourceFilename : null,
start: loc.start,
end: loc.end
};
node.start = loc.rangeStart;
node.end = loc.rangeEnd;
}
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
mapNode(node) {
this.fixSourceLocation(node);
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
switch (node.type) {
case 'Program':
return this.mapProgram(node);
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
case 'BlockStatement':
return this.mapNodeWithDirectives(node);
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
case 'Empty':
return this.mapEmpty(node);
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
case 'Identifier':
return this.mapIdentifier(node);
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
case 'TemplateElement':
return this.mapTemplateElement(node);
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
case 'GenericTypeAnnotation':
return this.mapGenericTypeAnnotation(node);
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
case 'SymbolTypeAnnotation':
return this.mapSymbolTypeAnnotation(node);
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
case 'Property':
return this.mapProperty(node);
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
case 'MethodDefinition':
return this.mapMethodDefinition(node);
var HermesToBabelAdapter = /*#__PURE__*/function (_HermesASTAdapter) {
_inherits(HermesToBabelAdapter, _HermesASTAdapter);
case 'ImportDeclaration':
return this.mapImportDeclaration(node);
var _super = _createSuper(HermesToBabelAdapter);
case 'ImportSpecifier':
return this.mapImportSpecifier(node);
function HermesToBabelAdapter() {
_classCallCheck(this, HermesToBabelAdapter);
case 'ExportDefaultDeclaration':
return this.mapExportDefaultDeclaration(node);
return _super.apply(this, arguments);
}
case 'ExportNamedDeclaration':
return this.mapExportNamedDeclaration(node);
_createClass(HermesToBabelAdapter, [{
key: "fixSourceLocation",
value: function fixSourceLocation(node) {
var _this$sourceFilename;
case 'ExportAllDeclaration':
return this.mapExportAllDeclaration(node);
var loc = node.loc;
case 'RestElement':
return this.mapRestElement(node);
if (loc == null) {
return;
}
case 'ImportExpression':
return this.mapImportExpression(node);
node.loc = {
source: (_this$sourceFilename = this.sourceFilename) !== null && _this$sourceFilename !== void 0 ? _this$sourceFilename : null,
start: loc.start,
end: loc.end
};
node.start = loc.rangeStart;
node.end = loc.rangeEnd;
}
}, {
key: "mapNode",
value: function mapNode(node) {
this.fixSourceLocation(node);
case 'JSXStringLiteral':
return this.mapJSXStringLiteral(node);
switch (node.type) {
case 'Program':
return this.mapProgram(node);
case 'PrivateName':
case 'ClassPrivateProperty':
return this.mapPrivateProperty(node);
case 'BlockStatement':
return this.mapNodeWithDirectives(node);
case 'FunctionDeclaration':
case 'FunctionExpression':
return this.mapFunction(node);
case 'Empty':
return this.mapEmpty(node);
case 'IndexedAccessType':
case 'OptionalIndexedAccessType':
return this.mapUnsupportedTypeAnnotation(node);
case 'Identifier':
return this.mapIdentifier(node);
default:
return this.mapNodeDefault(node);
}
}
case 'TemplateElement':
return this.mapTemplateElement(node);
mapProgram(node) {
// Visit child nodes and convert to directives
const {
comments,
...program
} = this.mapNodeWithDirectives(node);
program.sourceType = this.getSourceType(); // Adjust start loc to beginning of file
case 'GenericTypeAnnotation':
return this.mapGenericTypeAnnotation(node);
program.loc.start = {
line: 1,
column: 0
};
program.start = 0; // Adjust end loc to include last comment if program ends with a comment
case 'SymbolTypeAnnotation':
return this.mapSymbolTypeAnnotation(node);
if (comments.length > 0) {
const lastComment = comments[comments.length - 1];
case 'Property':
return this.mapProperty(node);
if (lastComment.end > program.end) {
program.loc.end = lastComment.loc.end;
program.end = lastComment.end;
}
} // Rename root node to File node and move Program node under program property
case 'MethodDefinition':
return this.mapMethodDefinition(node);
case 'ImportDeclaration':
return this.mapImportDeclaration(node);
return {
type: 'File',
loc: program.loc,
start: program.start,
end: program.end,
program,
comments
};
}
case 'ImportSpecifier':
return this.mapImportSpecifier(node);
mapNodeWithDirectives(node) {
const directives = [];
case 'ExportDefaultDeclaration':
return this.mapExportDefaultDeclaration(node);
for (const child of node.body) {
if (child.type === 'ExpressionStatement' && child.directive != null) {
// Visit directive children
const directiveChild = this.mapNode(child); // Modify string literal node to be DirectiveLiteral node
case 'ExportNamedDeclaration':
return this.mapExportNamedDeclaration(node);
directiveChild.expression.type = 'DirectiveLiteral'; // Construct Directive node with DirectiveLiteral value
case 'ExportAllDeclaration':
return this.mapExportAllDeclaration(node);
case 'RestElement':
return this.mapRestElement(node);
case 'ImportExpression':
return this.mapImportExpression(node);
case 'PrivateName':
case 'ClassPrivateProperty':
return this.mapPrivateProperty(node);
case 'FunctionDeclaration':
case 'FunctionExpression':
return this.mapFunction(node);
case 'IndexedAccessType':
case 'OptionalIndexedAccessType':
return this.mapUnsupportedTypeAnnotation(node);
default:
return this.mapNodeDefault(node);
directives.push({
type: 'Directive',
loc: directiveChild.loc,
start: directiveChild.start,
end: directiveChild.end,
value: directiveChild.expression
});
} else {
// Once we have found the first non-directive node we know there cannot be any more directives
break;
}
}
}, {
key: "mapProgram",
value: function mapProgram(node) {
// Visit child nodes and convert to directives
var _this$mapNodeWithDire = this.mapNodeWithDirectives(node),
comments = _this$mapNodeWithDire.comments,
program = _objectWithoutProperties(_this$mapNodeWithDire, _excluded);
} // Move directives from body to new directives array
program.sourceType = this.getSourceType(); // Adjust start loc to beginning of file
program.loc.start = {
line: 1,
column: 0
};
program.start = 0; // Adjust end loc to include last comment if program ends with a comment
node.directives = directives;
if (comments.length > 0) {
var lastComment = comments[comments.length - 1];
if (directives.length !== 0) {
node.body = node.body.slice(directives.length);
} // Visit expression statement children
if (lastComment.end > program.end) {
program.loc.end = lastComment.loc.end;
program.end = lastComment.end;
}
} // Rename root node to File node and move Program node under program property
const body = node.body;
return {
type: 'File',
loc: program.loc,
start: program.start,
end: program.end,
program: program,
comments: comments
};
}
}, {
key: "mapNodeWithDirectives",
value: function mapNodeWithDirectives(node) {
var directives = [];
for (let i = 0; i < body.length; i++) {
const child = body[i];
var _iterator = _createForOfIteratorHelper(node.body),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var _child = _step.value;
if (_child.type === 'ExpressionStatement' && _child.directive != null) {
// Visit directive children
var directiveChild = this.mapNode(_child); // Modify string literal node to be DirectiveLiteral node
directiveChild.expression.type = 'DirectiveLiteral'; // Construct Directive node with DirectiveLiteral value
directives.push({
type: 'Directive',
loc: directiveChild.loc,
start: directiveChild.start,
end: directiveChild.end,
value: directiveChild.expression
});
} else {
// Once we have found the first non-directive node we know there cannot be any more directives
break;
}
} // Move directives from body to new directives array
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
if (child != null) {
body[i] = this.mapNode(child);
}
}
node.directives = directives;
return node;
}
if (directives.length !== 0) {
node.body = node.body.slice(directives.length);
} // Visit expression statement children
mapIdentifier(node) {
node.loc.identifierName = node.name;
return this.mapNodeDefault(node);
}
mapTemplateElement(node) {
// Adjust start loc to exclude "`" at beginning of template literal if this is the first quasi,
// otherwise exclude "}" from previous expression.
const startCharsToExclude = 1; // Adjust end loc to exclude "`" at end of template literal if this is the last quasi,
// otherwise exclude "${" from next expression.
var body = node.body;
for (var i = 0; i < body.length; i++) {
var child = body[i];
if (child != null) {
body[i] = this.mapNode(child);
}
}
return node;
}
}, {
key: "mapIdentifier",
value: function mapIdentifier(node) {
node.loc.identifierName = node.name;
return this.mapNodeDefault(node);
}
}, {
key: "mapTemplateElement",
value: function mapTemplateElement(node) {
// Adjust start loc to exclude "`" at beginning of template literal if this is the first quasi,
// otherwise exclude "}" from previous expression.
var startCharsToExclude = 1; // Adjust end loc to exclude "`" at end of template literal if this is the last quasi,
// otherwise exclude "${" from next expression.
var endCharsToExclude = node.tail ? 1 : 2;
return {
type: 'TemplateElement',
loc: {
start: {
line: node.loc.start.line,
column: node.loc.start.column + startCharsToExclude
},
end: {
line: node.loc.end.line,
column: node.loc.end.column - endCharsToExclude
}
const endCharsToExclude = node.tail ? 1 : 2;
return {
type: 'TemplateElement',
loc: {
start: {
line: node.loc.start.line,
column: node.loc.start.column + startCharsToExclude
},
start: node.start + startCharsToExclude,
end: node.end - endCharsToExclude,
tail: node.tail,
value: {
cooked: node.cooked,
raw: node.raw
end: {
line: node.loc.end.line,
column: node.loc.end.column - endCharsToExclude
}
};
}
}, {
key: "mapGenericTypeAnnotation",
value: function mapGenericTypeAnnotation(node) {
// Convert simple `this` generic type to ThisTypeAnnotation
if (node.typeParameters === null && node.id.type === 'Identifier' && node.id.name === 'this') {
return {
type: 'ThisTypeAnnotation',
loc: node.loc,
start: node.start,
end: node.end
};
},
start: node.start + startCharsToExclude,
end: node.end - endCharsToExclude,
tail: node.tail,
value: {
cooked: node.cooked,
raw: node.raw
}
};
}
return this.mapNodeDefault(node);
}
}, {
key: "mapSymbolTypeAnnotation",
value: function mapSymbolTypeAnnotation(node) {
mapGenericTypeAnnotation(node) {
// Convert simple `this` generic type to ThisTypeAnnotation
if (node.typeParameters == null && node.id.type === 'Identifier' && node.id.name === 'this') {
return {
type: 'GenericTypeAnnotation',
type: 'ThisTypeAnnotation',
loc: node.loc,
start: node.start,
end: node.end,
id: {
type: 'Identifier',
loc: node.loc,
start: node.start,
end: node.end,
name: 'symbol'
},
typeParameters: null
end: node.end
};
}
}, {
key: "mapProperty",
value: function mapProperty(node) {
var key = this.mapNode(node.key);
var value = this.mapNode(node.value); // Convert methods, getters, and setters to ObjectMethod nodes
if (node.method || node.kind !== 'init') {
// Properties under the FunctionExpression value that should be moved
// to the ObjectMethod node itself.
var id = value.id,
params = value.params,
body = value.body,
async = value.async,
generator = value.generator,
returnType = value.returnType,
typeParameters = value.typeParameters,
predicate = value.predicate;
return {
type: 'ObjectMethod',
loc: node.loc,
start: node.start,
end: node.end,
// Non getter or setter methods have `kind = method`
kind: node.kind === 'init' ? 'method' : node.kind,
computed: node.computed,
key: key,
id: id,
params: params,
body: body,
async: async,
generator: generator,
returnType: returnType,
typeParameters: typeParameters,
predicate: predicate
};
} else {
// Non-method property nodes should be renamed to ObjectProperty
node.type = 'ObjectProperty';
return node;
}
}
}, {
key: "mapMethodDefinition",
value: function mapMethodDefinition(node) {
var key = this.mapNode(node.key);
var value = this.mapNode(node.value); // Properties under the FunctionExpression value that should be moved
// to the ClassMethod node itself.
return this.mapNodeDefault(node);
}
var id = value.id,
params = value.params,
body = value.body,
async = value.async,
generator = value.generator,
returnType = value.returnType,
typeParameters = value.typeParameters,
predicate = value.predicate;
return {
type: 'ClassMethod',
mapSymbolTypeAnnotation(node) {
return {
type: 'GenericTypeAnnotation',
loc: node.loc,
start: node.start,
end: node.end,
id: {
type: 'Identifier',
loc: node.loc,
start: node.start,
end: node.end,
kind: node.kind,
computed: node.computed,
"static": node["static"],
key: key,
id: id,
params: params,
body: body,
async: async,
generator: generator,
returnType: returnType,
typeParameters: typeParameters,
predicate: predicate
};
}
}, {
key: "mapRestElement",
value: function mapRestElement(node) {
var restElement = this.mapNodeDefault(node); // Hermes puts type annotations on rest elements on the argument node,
// but Babel expects type annotations on the rest element node itself.
name: 'symbol'
},
typeParameters: null
};
}
var annotation = restElement.argument.typeAnnotation;
mapProperty(node) {
const key = this.mapNode(node.key);
const value = this.mapNode(node.value); // Convert methods, getters, and setters to ObjectMethod nodes
if (annotation != null) {
restElement.typeAnnotation = annotation;
restElement.argument.typeAnnotation = null;
}
return restElement;
}
}, {
key: "mapImportExpression",
value: function mapImportExpression(node) {
// Babel expects ImportExpression to be structued as a regular
// CallExpression where the callee is an Import node.
if (node.method || node.kind !== 'init') {
// Properties under the FunctionExpression value that should be moved
// to the ObjectMethod node itself.
const {
id,
params,
body,
async,
generator,
returnType,
typeParameters,
predicate
} = value;
return {
type: 'CallExpression',
type: 'ObjectMethod',
loc: node.loc,
start: node.start,
end: node.end,
callee: {
type: 'Import',
loc: node.loc,
start: node.start,
end: node.end
},
arguments: [this.mapNode(node.source)]
// Non getter or setter methods have `kind = method`
kind: node.kind === 'init' ? 'method' : node.kind,
computed: node.computed,
key,
id,
params,
body,
async,
generator,
returnType,
typeParameters,
predicate
};
} else {
// Non-method property nodes should be renamed to ObjectProperty
node.type = 'ObjectProperty';
return node;
}
}, {
key: "mapFunction",
value: function mapFunction(node) {
// Remove the first parameter if it is a this-type annotation,
// which is not recognized by Babel.
if (node.params.length !== 0 && node.params[0].name === 'this') {
node.params.shift();
}
}
return this.mapNodeDefault(node);
mapMethodDefinition(node) {
const key = this.mapNode(node.key);
const value = this.mapNode(node.value); // Properties under the FunctionExpression value that should be moved
// to the ClassMethod node itself.
const {
id,
params,
body,
async,
generator,
returnType,
typeParameters,
predicate
} = value;
return {
type: 'ClassMethod',
loc: node.loc,
start: node.start,
end: node.end,
kind: node.kind,
computed: node.computed,
static: node.static,
key,
id,
params,
body,
async,
generator,
returnType,
typeParameters,
predicate
};
}
mapRestElement(node) {
const restElement = this.mapNodeDefault(node); // Hermes puts type annotations on rest elements on the argument node,
// but Babel expects type annotations on the rest element node itself.
const annotation = restElement.argument.typeAnnotation;
if (annotation != null) {
restElement.typeAnnotation = annotation;
restElement.argument.typeAnnotation = null;
}
/**
* If Babel (the version we target) does not support a type annotation we
* parse, we need to return some other valid type annotation in its place.
*/
}, {
key: "mapUnsupportedTypeAnnotation",
value: function mapUnsupportedTypeAnnotation(node) {
return {
type: 'AnyTypeAnnotation',
return restElement;
}
mapImportExpression(node) {
// Babel expects ImportExpression to be structued as a regular
// CallExpression where the callee is an Import node.
return {
type: 'CallExpression',
loc: node.loc,
start: node.start,
end: node.end,
callee: {
type: 'Import',
loc: node.loc,
start: node.start,
end: node.end
};
},
arguments: [this.mapNode(node.source)]
};
}
mapJSXStringLiteral(node) {
// Babel expects StringLiterals in JSX,
// but Hermes uses JSXStringLiteral to attach the raw value without
// having to internally attach it to every single string literal.
return {
type: 'StringLiteral',
loc: node.loc,
start: node.start,
end: node.end,
value: node.value
};
}
mapFunction(node) {
// Remove the first parameter if it is a this-type annotation,
// which is not recognized by Babel.
if (node.params.length !== 0 && node.params[0].name === 'this') {
node.params.shift();
}
}]);
return HermesToBabelAdapter;
}(_HermesASTAdapter2["default"]);
return this.mapNodeDefault(node);
}
/**
* If Babel (the version we target) does not support a type annotation we
* parse, we need to return some other valid type annotation in its place.
*/
exports["default"] = HermesToBabelAdapter;
mapUnsupportedTypeAnnotation(node) {
return {
type: 'AnyTypeAnnotation',
loc: node.loc,
start: node.start,
end: node.end
};
}
}
exports.default = HermesToBabelAdapter;
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
exports.default = void 0;
var _HermesASTAdapter2 = _interopRequireDefault(require("./HermesASTAdapter"));
var _HermesASTAdapter = _interopRequireDefault(require("./HermesASTAdapter"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
/*
This class does some very "javascripty" things in the name of
performance which are ultimately impossible to soundly type.
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
So instead of adding strict types and a large number of suppression
comments, instead it is left untyped and subclasses are strictly
typed via a separate flow declaration file.
*/
class HermesToESTreeAdapter extends _HermesASTAdapter.default {
constructor(options, code) {
super(options);
this.code = void 0;
this.code = code;
}
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
fixSourceLocation(node) {
var _this$sourceFilename;
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
const loc = node.loc;
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
if (loc == null) {
return;
}
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
node.loc = {
source: (_this$sourceFilename = this.sourceFilename) != null ? _this$sourceFilename : null,
start: loc.start,
end: loc.end
};
node.range = [loc.rangeStart, loc.rangeEnd];
}
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
mapNode(node) {
this.fixSourceLocation(node);
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
switch (node.type) {
case 'Program':
return this.mapProgram(node);
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
case 'NullLiteral':
return this.mapNullLiteral(node);
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
case 'BooleanLiteral':
case 'StringLiteral':
case 'NumericLiteral':
case 'JSXStringLiteral':
return this.mapSimpleLiteral(node);
var HermesToESTreeAdapter = /*#__PURE__*/function (_HermesASTAdapter) {
_inherits(HermesToESTreeAdapter, _HermesASTAdapter);
case 'BigIntLiteral':
return this.mapBigIntLiteral(node);
var _super = _createSuper(HermesToESTreeAdapter);
case 'RegExpLiteral':
return this.mapRegExpLiteral(node);
function HermesToESTreeAdapter(options, code) {
var _this;
case 'Empty':
return this.mapEmpty(node);
_classCallCheck(this, HermesToESTreeAdapter);
case 'TemplateElement':
return this.mapTemplateElement(node);
_this = _super.call(this, options);
case 'BigIntLiteralTypeAnnotation':
return this.mapBigIntLiteralTypeAnnotation(node);
_defineProperty(_assertThisInitialized(_this), "code", void 0);
case 'GenericTypeAnnotation':
return this.mapGenericTypeAnnotation(node);
_this.code = code;
return _this;
}
case 'ImportDeclaration':
return this.mapImportDeclaration(node);
_createClass(HermesToESTreeAdapter, [{
key: "fixSourceLocation",
value: function fixSourceLocation(node) {
var _this$sourceFilename;
case 'ImportSpecifier':
return this.mapImportSpecifier(node);
var loc = node.loc;
case 'ExportDefaultDeclaration':
return this.mapExportDefaultDeclaration(node);
if (loc == null) {
return;
}
case 'ExportNamedDeclaration':
return this.mapExportNamedDeclaration(node);
node.loc = {
source: (_this$sourceFilename = this.sourceFilename) !== null && _this$sourceFilename !== void 0 ? _this$sourceFilename : null,
start: loc.start,
end: loc.end
};
node.range = [loc.rangeStart, loc.rangeEnd];
case 'ExportAllDeclaration':
return this.mapExportAllDeclaration(node);
case 'PrivateName':
case 'ClassPrivateProperty':
return this.mapPrivateProperty(node);
default:
return this.mapNodeDefault(node);
}
}, {
key: "mapNode",
value: function mapNode(node) {
this.fixSourceLocation(node);
}
switch (node.type) {
case 'Program':
return this.mapProgram(node);
mapProgram(node) {
node = this.mapNodeDefault(node);
node.sourceType = this.getSourceType();
return node;
}
case 'NullLiteral':
return this.mapNullLiteral(node);
mapSimpleLiteral(node) {
return {
type: 'Literal',
loc: node.loc,
range: node.range,
value: node.value,
raw: this.code.slice(node.range[0], node.range[1]),
literalType: (() => {
switch (node.type) {
case 'NullLiteral':
return 'null';
case 'BooleanLiteral':
case 'StringLiteral':
case 'NumericLiteral':
return this.mapSimpleLiteral(node);
case 'BooleanLiteral':
return 'boolean';
case 'RegExpLiteral':
return this.mapRegExpLiteral(node);
case 'StringLiteral':
case 'JSXStringLiteral':
return 'string';
case 'Empty':
return this.mapEmpty(node);
case 'NumericLiteral':
return 'numeric';
case 'TemplateElement':
return this.mapTemplateElement(node);
case 'BigIntLiteral':
return 'bigint';
case 'GenericTypeAnnotation':
return this.mapGenericTypeAnnotation(node);
case 'RegExpLiteral':
return 'regexp';
}
case 'ImportDeclaration':
return this.mapImportDeclaration(node);
return null;
})()
};
}
case 'ImportSpecifier':
return this.mapImportSpecifier(node);
mapBigIntLiteral(node) {
const newNode = this.mapSimpleLiteral(node);
const bigint = node.bigint // estree spec is to not have a trailing `n` on this property
// https://github.com/estree/estree/blob/db962bb417a97effcfe9892f87fbb93c81a68584/es2020.md#bigintliteral
.replace(/n$/, '') // `BigInt` doesn't accept numeric separator and `bigint` property should not include numeric separator
.replace(/_/, '');
return { ...newNode,
// coerce the string to a bigint value if supported by the environment
value: typeof BigInt === 'function' ? BigInt(bigint) : null,
bigint
};
}
case 'ExportDefaultDeclaration':
return this.mapExportDefaultDeclaration(node);
mapNullLiteral(node) {
return { ...this.mapSimpleLiteral(node),
value: null
};
}
case 'ExportNamedDeclaration':
return this.mapExportNamedDeclaration(node);
mapRegExpLiteral(node) {
const {
pattern,
flags
} = node; // Create RegExp value if possible. This can fail when the flags are invalid.
case 'ExportAllDeclaration':
return this.mapExportAllDeclaration(node);
let value;
case 'PrivateName':
case 'ClassPrivateProperty':
return this.mapPrivateProperty(node);
try {
value = new RegExp(pattern, flags);
} catch (e) {
value = null;
}
default:
return this.mapNodeDefault(node);
return { ...this.mapSimpleLiteral(node),
value,
regex: {
pattern,
flags
}
}
}, {
key: "mapProgram",
value: function mapProgram(node) {
node = this.mapNodeDefault(node);
node.sourceType = this.getSourceType();
return node;
}
}, {
key: "mapSimpleLiteral",
value: function mapSimpleLiteral(node) {
node.type = 'Literal';
node.raw = this.code.slice(node.range[0], node.range[1]);
return node;
}
}, {
key: "mapNullLiteral",
value: function mapNullLiteral(node) {
node.type = 'Literal';
node.value = null;
node.raw = this.code.slice(node.range[0], node.range[1]);
return node;
}
}, {
key: "mapRegExpLiteral",
value: function mapRegExpLiteral(node) {
var pattern = node.pattern,
flags = node.flags; // Create RegExp value if possible. This can fail when the flags are invalid.
};
}
var value;
mapBigIntLiteralTypeAnnotation(node) {
node.value = null;
return node;
}
try {
value = new RegExp(pattern, flags);
} catch (e) {
value = null;
mapTemplateElement(node) {
return {
type: 'TemplateElement',
loc: node.loc,
range: node.range,
tail: node.tail,
value: {
cooked: node.cooked,
raw: node.raw
}
};
}
mapGenericTypeAnnotation(node) {
// Convert simple `this` generic type to ThisTypeAnnotation
if (node.typeParameters == null && node.id.type === 'Identifier' && node.id.name === 'this') {
return {
type: 'Literal',
type: 'ThisTypeAnnotation',
loc: node.loc,
range: node.range,
value: value,
raw: this.code.slice(node.range[0], node.range[1]),
regex: {
pattern: pattern,
flags: flags
}
range: node.range
};
}
}, {
key: "mapTemplateElement",
value: function mapTemplateElement(node) {
return {
type: 'TemplateElement',
loc: node.loc,
range: node.range,
tail: node.tail,
value: {
cooked: node.cooked,
raw: node.raw
}
};
}
}, {
key: "mapGenericTypeAnnotation",
value: function mapGenericTypeAnnotation(node) {
// Convert simple `this` generic type to ThisTypeAnnotation
if (node.typeParameters === null && node.id.type === 'Identifier' && node.id.name === 'this') {
return {
type: 'ThisTypeAnnotation',
loc: node.loc,
range: node.range
};
}
return this.mapNodeDefault(node);
}
}, {
key: "mapComment",
value: function mapComment(node) {
if (node.type === 'CommentBlock') {
node.type = 'Block';
} else if (node.type === 'CommentLine') {
node.type = 'Line';
}
return this.mapNodeDefault(node);
}
return node;
mapComment(node) {
if (node.type === 'CommentBlock') {
node.type = 'Block';
} else if (node.type === 'CommentLine') {
node.type = 'Line';
}
}]);
return HermesToESTreeAdapter;
}(_HermesASTAdapter2["default"]);
return node;
}
exports["default"] = HermesToESTreeAdapter;
}
exports.default = HermesToESTreeAdapter;
/**
* Copyright (c) Facebook, Inc. and its affiliates.
* Copyright (c) Meta Platforms, Inc. and affiliates.
*

@@ -12,4 +12,2 @@ * This source code is licensed under the MIT license found in the

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
Object.defineProperty(exports, "__esModule", {

@@ -26,21 +24,14 @@ value: true

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var DEFAULTS = {
const DEFAULTS = {
flow: 'detect'
};
function getOptions() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _objectSpread({}, DEFAULTS);
function getOptions(options = { ...DEFAULTS
}) {
// Default to detecting whether to parse Flow syntax by the presence

@@ -50,3 +41,3 @@ // of an pragma.

options.flow = DEFAULTS.flow;
} else if (options.flow != 'all' && options.flow != 'detect') {
} else if (options.flow !== 'all' && options.flow !== 'detect') {
throw new Error('flow option must be "all" or "detect"');

@@ -68,3 +59,3 @@ }

function getAdapter(options, code) {
return options.babel === true ? new _HermesToBabelAdapter["default"](options) : new _HermesToESTreeAdapter["default"](options, code);
return options.babel === true ? new _HermesToBabelAdapter.default(options) : new _HermesToESTreeAdapter.default(options, code);
} // $FlowExpectedError[unclear-type]

@@ -75,6 +66,6 @@

function parse(code, opts) {
var options = getOptions(opts);
var ast = HermesParser.parse(code, options);
var adapter = getAdapter(options, code);
const options = getOptions(opts);
const ast = HermesParser.parse(code, options);
const adapter = getAdapter(options, code);
return adapter.transform(ast);
}
{
"name": "hermes-parser",
"version": "0.5.0",
"version": "0.6.0",
"description": "A JavaScript parser built from the Hermes engine",

@@ -12,4 +12,7 @@ "main": "dist/index.js",

"dependencies": {
"hermes-estree": "0.5.0"
"hermes-estree": "0.6.0"
},
"devDependencies": {
"hermes-transform": "0.6.0"
},
"files": [

@@ -16,0 +19,0 @@ "dist"

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc