Advertisement
pexea12

bootstrap.js

Nov 29th, 2015
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*!
  2.  * Casper is a navigation utility for PhantomJS.
  3.  *
  4.  * Documentation: http://casperjs.org/
  5.  * Repository:    http://github.com/n1k0/casperjs
  6.  *
  7.  * Copyright (c) 2011-2012 Nicolas Perriault
  8.  *
  9.  * Part of source code is Copyright Joyent, Inc. and other Node contributors.
  10.  *
  11.  * Permission is hereby granted, free of charge, to any person obtaining a
  12.  * copy of this software and associated documentation files (the "Software"),
  13.  * to deal in the Software without restriction, including without limitation
  14.  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  15.  * and/or sell copies of the Software, and to permit persons to whom the
  16.  * Software is furnished to do so, subject to the following conditions:
  17.  *
  18.  * The above copyright notice and this permission notice shall be included
  19.  * in all copies or substantial portions of the Software.
  20.  *
  21.  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  22.  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23.  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  24.  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25.  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  26.  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  27.  * DEALINGS IN THE SOFTWARE.
  28.  *
  29.  */
  30.  
  31. /*eslint max-statements:0, complexity:0*/
  32.  
  33. // node check
  34. if ('process' in this && process.title === "node") {
  35.     console.error('CasperJS cannot be executed within a nodejs environment');
  36.     process.exit(1);
  37. }
  38.  
  39. // phantom check
  40. if (!('phantom' in this)) {
  41.     console.error('CasperJS needs to be executed in a PhantomJS environment http://phantomjs.org/');
  42. } else {
  43.     if (phantom.version.major === 2) {
  44.         //setting other phantom.args if using phantomjs 2.x
  45.         var system = require('system');
  46.         var argsdeprecated = system.args;
  47.         argsdeprecated.shift();
  48.         phantom.args = argsdeprecated;
  49.     }
  50. }
  51.  
  52.  
  53. // Common polyfills
  54. if (typeof Function.prototype.bind !== "function") {
  55.     // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Compatibility
  56.     Function.prototype.bind = function (oThis) {
  57.         "use strict";
  58.         if (typeof this !== "function") {
  59.             // closest thing possible to the ECMAScript 5 internal IsCallable function
  60.             throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  61.         }
  62.         var aArgs = Array.prototype.slice.call(arguments, 1),
  63.             fToBind = this,
  64.             fNOP = function() {},
  65.             fBound = function() {
  66.               return fToBind.apply(this instanceof fNOP && oThis ? this : oThis,
  67.                                    aArgs.concat(Array.prototype.slice.call(arguments)));
  68.             };
  69.         fNOP.prototype = this.prototype;
  70.         fBound.prototype = new fNOP();
  71.         return fBound;
  72.     };
  73. }
  74.  
  75. // Custom base error
  76. var CasperError = function CasperError(msg) {
  77.     "use strict";
  78.     Error.call(this);
  79.     this.message = msg;
  80.     this.name = 'CasperError';
  81. };
  82. CasperError.prototype = Object.getPrototypeOf(new Error());
  83.  
  84. // casperjs env initialization
  85. (function(global, phantom){
  86.     "use strict";
  87.     // phantom args
  88.     // NOTE: we can't use require('system').args here for some very obscure reason
  89.     //       do not even attempt at using it as it creates infinite recursion
  90.     var phantomArgs = phantom.args;
  91.  
  92.     if (phantom.casperLoaded) {
  93.         return;
  94.     }
  95.  
  96.     function __exit(statusCode){
  97.         setTimeout(function() { phantom.exit(statusCode); }, 0);
  98.     }
  99.  
  100.     function __die(message) {
  101.         if (message) {
  102.             console.error(message);
  103.         }
  104.         __exit(1);
  105.     }
  106.  
  107.     function __terminate(message) {
  108.         if (message) {
  109.             console.log(message);
  110.         }
  111.         __exit();
  112.     }
  113.  
  114.     (function (version) {
  115.         // required version check
  116.         if (version.major === 1) {
  117.             if (version.minor < 8) {
  118.                 return __die('CasperJS needs at least PhantomJS v1.8 or later.');
  119.             }
  120.             if (version.minor === 8 && version.patch < 1) {
  121.                 return __die('CasperJS needs at least PhantomJS v1.8.1 or later.');
  122.             }
  123.         } else if (version.major === 2) {
  124.             console.log("Warning PhantomJS v2.0 not yet released. There will not be any official support for any bugs until stable version is released!");
  125.         }
  126.         else return __die('CasperJS needs PhantomJS v1.x or v2.x');
  127.     })(phantom.version);
  128.  
  129.     // Hooks in default phantomjs error handler
  130.     phantom.onError = function onPhantomError(msg, trace) {
  131.         phantom.defaultErrorHandler.apply(phantom, arguments);
  132.         // print a hint when a possible casperjs command misuse is detected
  133.         if (msg.indexOf("ReferenceError: Can't find variable: casper") === 0) {
  134.             console.error('Hint: you may want to use the `casperjs test` command.');
  135.         }
  136.         // exits on syntax error
  137.         if (msg.indexOf('SyntaxError: Parse error') === 0) {
  138.             __die();
  139.         }
  140.     };
  141.  
  142.     // Patching fs
  143.     var fs = (function patchFs(fs) {
  144.         if (!fs.hasOwnProperty('basename')) {
  145.             fs.basename = function basename(path) {
  146.                 return path.replace(/.*\//, '');
  147.             };
  148.         }
  149.         if (!fs.hasOwnProperty('dirname')) {
  150.             fs.dirname = function dirname(path) {
  151.                 if (!path) return undefined;
  152.                 return path.toString().replace(/\\/g, '/').replace(/\/[^\/]*$/, '');
  153.             };
  154.         }
  155.         if (!fs.hasOwnProperty('isWindows')) {
  156.             fs.isWindows = function isWindows() {
  157.                 var testPath = arguments[0] || this.workingDirectory;
  158.                 return (/^[a-z]{1,2}:/i).test(testPath) || testPath.indexOf("\\\\") === 0;
  159.             };
  160.         }
  161.         if (fs.hasOwnProperty('joinPath')) {
  162.             fs.pathJoin = fs.joinPath;
  163.         } else if (!fs.hasOwnProperty('pathJoin')) {
  164.             fs.pathJoin = function pathJoin() {
  165.                 return Array.prototype.join.call(arguments, '/');
  166.             };
  167.         }
  168.         return fs;
  169.     })(require('fs'));
  170.  
  171.     // CasperJS root path
  172.     if (!phantom.casperPath) {
  173.         try {
  174.             phantom.casperPath = phantom.args.map(function _map(arg) {
  175.                 var match = arg.match(/^--casper-path=(.*)/);
  176.                 if (match) {
  177.                     return fs.absolute(match[1]);
  178.                 }
  179.             }).filter(function _filter(path) {
  180.                 return fs.isDirectory(path);
  181.             }).pop();
  182.         } catch (e) {
  183.             return __die("Couldn't find nor compute phantom.casperPath, exiting.");
  184.         }
  185.     }
  186.  
  187.     /**
  188.      * Prints CasperJS help.
  189.      */
  190.     function printHelp() {
  191.         var engine = phantom.casperEngine === 'slimerjs' ? slimer : phantom;
  192.         var version = [engine.version.major, engine.version.minor, engine.version.patch].join('.');
  193.         return __terminate([
  194.             'CasperJS version ' + phantom.casperVersion.toString() +
  195.             ' at ' + phantom.casperPath + ', using ' + phantom.casperEngine + ' version ' + version,
  196.             fs.read(fs.pathJoin(phantom.casperPath, 'bin', 'usage.txt'))
  197.         ].join('\n'));
  198.     }
  199.  
  200.     /**
  201.      * Patched require to allow loading of native casperjs modules.
  202.      * Every casperjs module have to first call this function in order to
  203.      * load a native casperjs module:
  204.      *
  205.      *     var require = patchRequire(require);
  206.      *     var utils = require('utils');
  207.      *
  208.      * Useless for SlimerJS
  209.      */
  210.     function patchRequire(require) {
  211.         if (require.patched) {
  212.             return require;
  213.         }
  214.         function fromPackageJson(module, dir) {
  215.             var pkgPath, pkgContents, pkg;
  216.             pkgPath = fs.pathJoin(dir, module, 'package.json');
  217.             if (!fs.exists(pkgPath)) {
  218.                 return;
  219.             }
  220.             pkgContents = fs.read(pkgPath);
  221.             if (!pkgContents) {
  222.                 return;
  223.             }
  224.             try {
  225.                 pkg = JSON.parse(pkgContents);
  226.             } catch (e) {
  227.                 return;
  228.             }
  229.             if (typeof pkg === "object" && pkg.main) {
  230.                 return fs.absolute(fs.pathJoin(dir, module, pkg.main));
  231.             }
  232.         }
  233.         function resolveFile(path, dir) {
  234.             var extensions = ['js', 'coffee', 'json'];
  235.             var basenames = [path, path + '/index'];
  236.             var paths = [];
  237.             var nodejsScript = fromPackageJson(path, dir);
  238.             if (nodejsScript) {
  239.                 return nodejsScript;
  240.             }
  241.             basenames.forEach(function(basename) {
  242.                 paths.push(fs.absolute(fs.pathJoin(dir, basename)));
  243.                 extensions.forEach(function(extension) {
  244.                     paths.push(fs.absolute(fs.pathJoin(dir, [basename, extension].join('.'))));
  245.                 });
  246.             });
  247.             for (var i = 0; i < paths.length; i++) {
  248.                 if (fs.isFile(paths[i])) {
  249.                     return paths[i];
  250.                 }
  251.             }
  252.             return null;
  253.         }
  254.         function getCurrentScriptRoot() {
  255.             if ((phantom.casperScriptBaseDir || "").indexOf(fs.workingDirectory) === 0) {
  256.                 return phantom.casperScriptBaseDir;
  257.             }
  258.             return fs.absolute(fs.pathJoin(fs.workingDirectory, phantom.casperScriptBaseDir));
  259.         }
  260.         function casperBuiltinPath(path) {
  261.             return resolveFile(path, fs.pathJoin(phantom.casperPath, 'modules'));
  262.         }
  263.         function nodeModulePath(path) {
  264.             var resolved, prevBaseDir;
  265.             var baseDir = getCurrentScriptRoot();
  266.             do {
  267.                 resolved = resolveFile(path, fs.pathJoin(baseDir, 'node_modules'));
  268.                 prevBaseDir = baseDir;
  269.                 baseDir = fs.absolute(fs.pathJoin(prevBaseDir, '..'));
  270.             } while (!resolved && baseDir !== '/' && baseDir !== prevBaseDir);
  271.             return resolved;
  272.         }
  273.         function localModulePath(path) {
  274.             return resolveFile(path, phantom.casperScriptBaseDir || fs.workingDirectory);
  275.         }
  276.         var patchedRequire = function patchedRequire(path) {
  277.             try {
  278.                 return require(casperBuiltinPath(path) ||
  279.                                nodeModulePath(path)    ||
  280.                                localModulePath(path)   ||
  281.                                path);
  282.             } catch (e) {
  283.                 throw new CasperError("Can't find module " + path);
  284.             }
  285.         };
  286.         patchedRequire.cache = require.cache;
  287.         patchedRequire.extensions = require.extensions;
  288.         patchedRequire.stubs = require.stubs;
  289.         patchedRequire.patched = true;
  290.         return patchedRequire;
  291.     }
  292.  
  293.     /**
  294.      * Initializes the CasperJS Command Line Interface.
  295.      */
  296.     function initCasperCli(casperArgs) {
  297.         /*eslint complexity:0*/
  298.         var baseTestsPath = fs.pathJoin(phantom.casperPath, 'tests');
  299.  
  300.         function setScriptBaseDir(scriptName) {
  301.             var dir = fs.dirname(scriptName);
  302.             if (dir === scriptName) {
  303.                 dir = '.';
  304.             }
  305.             phantom.casperScriptBaseDir = dir;
  306.         }
  307.  
  308.         if (!!casperArgs.options.version) {
  309.             return __terminate(phantom.casperVersion.toString());
  310.         } else if (casperArgs.get(0) === "test") {
  311.             phantom.casperScript = fs.absolute(fs.pathJoin(baseTestsPath, 'run.js'));
  312.             phantom.casperTest = true;
  313.             casperArgs.drop("test");
  314.             setScriptBaseDir(casperArgs.get(0));
  315.         } else if (casperArgs.get(0) === "selftest") {
  316.             phantom.casperScript = fs.absolute(fs.pathJoin(baseTestsPath, 'run.js'));
  317.             phantom.casperSelfTest = phantom.casperTest = true;
  318.             casperArgs.options.includes = fs.pathJoin(baseTestsPath, 'selftest.js');
  319.             if (casperArgs.args.length <= 1) {
  320.                 casperArgs.args.push(fs.pathJoin(baseTestsPath, 'suites'));
  321.             }
  322.             casperArgs.drop("selftest");
  323.             phantom.casperScriptBaseDir = fs.dirname(casperArgs.get(1) || fs.dirname(phantom.casperScript));
  324.         } else if (casperArgs.args.length === 0 || !!casperArgs.options.help) {
  325.             return printHelp();
  326.         }
  327.  
  328.         if (!phantom.casperScript) {
  329.             phantom.casperScript = casperArgs.get(0);
  330.         }
  331.  
  332.         if (phantom.casperScript !== "/dev/stdin" && !fs.isFile(phantom.casperScript)) {
  333.             return __die('Unable to open file: ' + phantom.casperScript);
  334.         }
  335.  
  336.         if (!phantom.casperScriptBaseDir) {
  337.             setScriptBaseDir(phantom.casperScript);
  338.         }
  339.  
  340.         // filter out the called script name from casper args
  341.         casperArgs.drop(phantom.casperScript);
  342.     }
  343.  
  344.     // CasperJS version, extracted from package.json - see http://semver.org/
  345.     phantom.casperVersion = (function getCasperVersion(path) {
  346.         var parts, patchPart, pkg, pkgFile;
  347.         pkgFile = fs.absolute(fs.pathJoin(path, 'package.json'));
  348.         if (!fs.exists(pkgFile)) {
  349.             throw new CasperError('Cannot find package.json at ' + pkgFile);
  350.         }
  351.         try {
  352.             pkg = JSON.parse(require('fs').read(pkgFile));
  353.         } catch (e) {
  354.             throw new CasperError('Cannot read package file contents: ' + e);
  355.         }
  356.         parts  = pkg.version.trim().split(".");
  357.         if (parts.length < 3) {
  358.             throw new CasperError("Invalid version number");
  359.         }
  360.         patchPart = parts[2].split('-');
  361.         return {
  362.             major: ~~parts[0]       || 0,
  363.             minor: ~~parts[1]       || 0,
  364.             patch: ~~patchPart[0]   || 0,
  365.             ident: patchPart[1]     || "",
  366.             toString: function toString() {
  367.                 var version = [this.major, this.minor, this.patch].join('.');
  368.                 if (this.ident) {
  369.                     version = [version, this.ident].join('-');
  370.                 }
  371.                 return version;
  372.             }
  373.         };
  374.     })(phantom.casperPath);
  375.  
  376.     if ("paths" in global.require) {
  377.         // declare a dummy patchRequire function
  378.         global.patchRequire = function(req) {return req;};
  379.  
  380.         require.paths.push(fs.pathJoin(phantom.casperPath, 'modules'));
  381.         require.paths.push(fs.workingDirectory);
  382.     } else {
  383.         global.__require = require;
  384.         global.patchRequire = patchRequire; // must be called in every casperjs module as of 1.1
  385.         global.require = patchRequire(global.require);
  386.     }
  387.  
  388.     if ("slimer" in global) {
  389.         require.globals.patchRequire = global.patchRequire;
  390.         require.globals.CasperError = CasperError;
  391.         phantom.casperEngine = "slimerjs";
  392.     } else {
  393.         phantom.casperEngine = "phantomjs";
  394.     }
  395.  
  396.     // casper cli args
  397.     phantom.casperArgs = require('cli').parse(phantomArgs);
  398.  
  399.     if (true === phantom.casperArgs.get('cli')) {
  400.         initCasperCli(phantom.casperArgs);
  401.     }
  402.  
  403.     if ("paths" in global.require) {
  404.         if ((phantom.casperScriptBaseDir || "").indexOf(fs.workingDirectory) === 0) {
  405.             require.paths.push(phantom.casperScriptBaseDir);
  406.         } else {
  407.             require.paths.push(fs.pathJoin(fs.workingDirectory, phantom.casperScriptBaseDir));
  408.         }
  409.         require.paths.push(fs.pathJoin(require.paths[require.paths.length-1], 'node_modules'));
  410.     }
  411.  
  412.     // casper loading status flag
  413.     phantom.casperLoaded = true;
  414.  
  415.     // passed casperjs script execution
  416.     if (phantom.casperScript && !phantom.injectJs(phantom.casperScript)) {
  417.         return __die('Unable to load script ' + phantom.casperScript + '; check file syntax');
  418.     }
  419. })(this, phantom);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement