react / wstein / node_modules / jest-cli / node_modules / istanbul / node_modules / js-yaml / lib / js-yaml / type / js / function.js
81154 views'use strict';12var esprima;34// Browserified version does not have esprima5//6// 1. For node.js just require module as deps7// 2. For browser try to require mudule via external AMD system.8// If not found - try to fallback to window.esprima. If not9// found too - then fail to parse.10//11try {12esprima = require('esprima');13} catch (_) {14/*global window */15if (typeof window !== 'undefined') { esprima = window.esprima; }16}1718var Type = require('../../type');1920function resolveJavascriptFunction(data) {21if (null === data) {22return false;23}2425try {26var source = '(' + data + ')',27ast = esprima.parse(source, { range: true }),28params = [],29body;3031if ('Program' !== ast.type ||321 !== ast.body.length ||33'ExpressionStatement' !== ast.body[0].type ||34'FunctionExpression' !== ast.body[0].expression.type) {35return false;36}3738return true;39} catch (err) {40return false;41}42}4344function constructJavascriptFunction(data) {45/*jslint evil:true*/4647var source = '(' + data + ')',48ast = esprima.parse(source, { range: true }),49params = [],50body;5152if ('Program' !== ast.type ||531 !== ast.body.length ||54'ExpressionStatement' !== ast.body[0].type ||55'FunctionExpression' !== ast.body[0].expression.type) {56throw new Error('Failed to resolve function');57}5859ast.body[0].expression.params.forEach(function (param) {60params.push(param.name);61});6263body = ast.body[0].expression.body.range;6465// Esprima's ranges include the first '{' and the last '}' characters on66// function expressions. So cut them out.67/*eslint-disable no-new-func*/68return new Function(params, source.slice(body[0] + 1, body[1] - 1));69}7071function representJavascriptFunction(object /*, style*/) {72return object.toString();73}7475function isFunction(object) {76return '[object Function]' === Object.prototype.toString.call(object);77}7879module.exports = new Type('tag:yaml.org,2002:js/function', {80kind: 'scalar',81resolve: resolveJavascriptFunction,82construct: constructJavascriptFunction,83predicate: isFunction,84represent: representJavascriptFunction85});868788