Code coverage report for es6-middleware/index.js

Statements: 94.44% (17 / 18)      Branches: 75% (6 / 8)      Functions: 100% (4 / 4)      Lines: 94.44% (17 / 18)      Ignored: none     

All files » es6-middleware/ » index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85                    1                     1                           1 12   12   2               12 6             12 12     3 1       12                       1 12 12     12    
/*
 * Copyright (c) 2014, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */
 
/*jslint node: true, nomen: true */
 
'use strict';
 
var libfs = require('fs'),
    vm = require('vm'),
    contextForRunInContext = vm.createContext({
        require: null,
        module: null,
        console: {},
        window: {},
        document: {},
        global: {}
    });
 
module.exports = {
    detect: detect,
    extract: extract
};
 
/**
Analyze a javascript file, collecting the module or modules information when possible.
 
@method extract
@default
@param {string} file The filesystem path for the javascript to be analyzed
@return {object|array} an object or a collection of object with the info gathered
    from the analysis, it usually includes objects with `type` and `name` per module.
**/
function extract(file) {
    var mods = [];
 
    contextForRunInContext.YUI = {
        add: function (name, fn, version, config) {
            mods.push({
                type: 'yui',
                name: name,
                version: version,
                config: config
            });
        }
    };
    contextForRunInContext.define = function (name, fn, version, config) {
        mods.push({
            type: 'amd',
            name: name,
            version: version,
            config: config
        });
    };
    try {
        vm.runInContext(libfs.readFileSync(file, 'utf8'), contextForRunInContext, file);
    } catch (e) {
        // very dummy detection process for ES modules
        if (e.toString() === 'SyntaxError: Unexpected reserved word') {
            mods.push({type: 'es'});
        }
    }
    // returning an array when more than one module is defined in the file
    return mods.length > 1 ? mods : mods[0];
}
 
/**
Analyze a javascript file, detecting if the file is a YUI,
AMD or ES module.
 
@method detect
@default
@param {string} file The filesystem path for the javascript to be analyzed
@return {string} `yui` or `amd` or `es`
**/
function detect(file) {
    var mod = extract(file);
    Iif (mod instanceof Array) {
        mod = mod.shift(); // picking up the first module from the list
    }
    return mod && mod.type;
}