casper.js 41.5 KB
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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
/*!
 * Casper is a navigation utility for PhantomJS.
 *
 * Documentation: http://n1k0.github.com/casperjs/
 * Repository:    http://github.com/n1k0/casperjs
 *
 * Copyright (c) 2011 Nicolas Perriault
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

var fs = require('fs');
var utils = require('utils');

exports.create = function(options) {
    return new Casper(options);
};

/**
 * Main Casper object.
 *
 * @param  Object  options  Casper options
 */
var Casper = function(options) {
    var DEFAULT_DIE_MESSAGE = "Suite explicitely interrupted without any message given.";
    var DEFAULT_USER_AGENT  = "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1";
    // init & checks
    if (!(this instanceof arguments.callee)) {
        return new Casper(options);
    }
    // default options
    this.defaults = {
        clientScripts:       [],
        faultTolerant:       true,
        logLevel:            "error",
        httpStatusHandlers:  {},
        onAlert:             null,
        onDie:               null,
        onError:             null,
        onLoadError:         null,
        onPageInitialized:   null,
        onResourceReceived:  null,
        onResourceRequested: null,
        onStepComplete:      null,
        onStepTimeout:       null,
        onTimeout:           null,
        page:                null,
        pageSettings:        {
            localToRemoteUrlAccessEnabled: true,
            userAgent:                     DEFAULT_USER_AGENT
        },
        stepTimeout:         null,
        timeout:             null,
        verbose:             false
    };
    // properties
    this.checker = null;
    this.cli = phantom.casperArgs;
    this.colorizer = require('colorizer').create();
    this.currentUrl = 'about:blank';
    this.currentHTTPStatus = 200;
    this.defaultWaitTimeout = 5000;
    this.history = [];
    this.loadInProgress = false;
    this.logFormats = {};
    this.logLevels = ["debug", "info", "warning", "error"];
    this.logStyles = {
        debug:   'INFO',
        info:    'PARAMETER',
        warning: 'COMMENT',
        error:   'ERROR'
    };
    this.options = utils.mergeObjects(this.defaults, options);
    this.page = null;
    this.pendingWait = false;
    this.requestUrl = 'about:blank';
    this.resources = [];
    this.result = {
        log:    [],
        status: "success",
        time:   0
    };
    this.started = false;
    this.step = -1;
    this.steps = [];
    this.test = require('tester').create(this);
};

/**
 * Casper prototype
 */
Casper.prototype = {
    /**
     * Go a step back in browser's history
     *
     * @return Casper
     */
    back: function() {
        return this.then(function(self) {
            self.evaluate(function() {
                history.back();
            });
        });
    },

    /**
     * Encodes a resource using the base64 algorithm synchroneously using
     * client-side XMLHttpRequest.
     *
     * NOTE: we cannot use window.btoa() for some strange reasons here.
     *
     * @param  String  url     The url to download
     * @param  String  method  The method to use, optional: default GET
     * @param  String  data    The data to send, optional
     * @return string          Base64 encoded result
     */
    base64encode: function(url, method, data) {
        return this.evaluate(function(url, method, data) {
            return __utils__.getBase64(url, method, data);
        }, { url: url, method: method, data: data });
    },

    /**
     * Proxy method for WebPage#render. Adds a clipRect parameter for
     * automatically set page clipRect setting values and sets it back once
     * done. If the cliprect parameter is omitted, the full page viewport
     * area will be rendered.
     *
     * @param  String  targetFile  A target filename
     * @param  mixed   clipRect    An optional clipRect object (optional)
     * @return Casper
     */
    capture: function(targetFile, clipRect) {
        var previousClipRect;
        targetFile = require('fs').absolute(targetFile);
        if (clipRect) {
            if (!utils.isType(clipRect, "object")) {
                throw new Error("clipRect must be an Object instance.");
            }
            previousClipRect = this.page.clipRect;
            this.page.clipRect = clipRect;
            this.log('Capturing page to ' + targetFile + ' with clipRect' + JSON.stringify(clipRect), "debug");
        } else {
            this.log('Capturing page to ' + targetFile, "debug");
        }
        if (!this.page.render(targetFile)) {
            this.log('Failed to save screenshot to ' + targetFile + '; please check permissions', "error");
        }
        if (previousClipRect) {
            this.page.clipRect = previousClipRect;
        }
        return this;
    },

    /**
     * Captures the page area containing the provided selector.
     *
     * @param  String  targetFile  Target destination file path.
     * @param  String  selector    CSS3 selector
     * @return Casper
     */
    captureSelector: function(targetFile, selector) {
        return this.capture(targetFile, this.evaluate(function(selector) {
            try {
                var clipRect = document.querySelector(selector).getBoundingClientRect();
                return {
                    top:    clipRect.top,
                    left:   clipRect.left,
                    width:  clipRect.width,
                    height: clipRect.height
                };
            } catch (e) {
                __utils__.log("Unable to fetch bounds for element " + selector, "warning");
            }
        }, { selector: selector }));
    },

    /**
     * Checks for any further navigation step to process.
     *
     * @param  Casper    self        A self reference
     * @param  function  onComplete  An options callback to apply on completion
     */
    checkStep: function(self, onComplete) {
        if (self.pendingWait || self.loadInProgress) {
            return;
        }
        var step = self.steps[self.step++];
        if (utils.isType(step, "function")) {
            self.runStep(step);
        } else {
            self.result.time = new Date().getTime() - self.startTime;
            self.log("Done " + self.steps.length + " steps in " + self.result.time + 'ms.', "info");
            clearInterval(self.checker);
            if (utils.isType(onComplete, "function")) {
                try {
                    onComplete.call(self, self);
                } catch (err) {
                    self.log("Could not complete final step: " + err, "error");
                }
            } else {
                // default behavior is to exit phantom
                self.exit();
            }
        }
    },

    /**
     * Emulates a click on the element from the provided selector, if
     * possible. In case of success, `true` is returned.
     *
     * @param  String   selector        A DOM CSS3 compatible selector
     * @param  Boolean  fallbackToHref  Whether to try to relocate to the value of any href attribute (default: true)
     * @return Boolean
     */
    click: function(selector, fallbackToHref) {
        fallbackToHref = utils.isType(fallbackToHref, "undefined") ? true : !!fallbackToHref;
        this.log("click on selector: " + selector, "debug");
        return this.evaluate(function(selector, fallbackToHref) {
            return __utils__.click(selector, fallbackToHref);
        }, {
            selector:       selector,
            fallbackToHref: fallbackToHref
        });
    },

    /**
     * Creates a step definition.
     *
     * @param  Function  fn       The step function to call
     * @param  Object    options  Step options
     * @return Function  The final step function
     */
    createStep: function(fn, options) {
        if (!utils.isType(fn, "function")) {
            throw new Error("createStep(): a step definition must be a function");
        }
        fn.options = utils.isType(options, "object") ? options : {};
        return fn;
    },

    /**
     * Logs the HTML code of the current page.
     *
     * @return Casper
     */
    debugHTML: function() {
        this.echo(this.evaluate(function() {
            return document.body.innerHTML;
        }));
        return this;
    },

    /**
     * Logs the textual contents of the current page.
     *
     * @return Casper
     */
    debugPage: function() {
        this.echo(this.evaluate(function() {
            return document.body.innerText;
        }));
        return this;
    },

    /**
     * Exit phantom on failure, with a logged error message.
     *
     * @param  String  message  An optional error message
     * @param  Number  status   An optional exit status code (must be > 0)
     * @return Casper
     */
    die: function(message, status) {
        this.result.status = 'error';
        this.result.time = new Date().getTime() - this.startTime;
        message = utils.isType(message, "string") && message.length > 0 ? message : DEFAULT_DIE_MESSAGE;
        this.log(message, "error");
        if (utils.isType(this.options.onDie, "function")) {
            this.options.onDie.call(this, this, message, status);
        }
        return this.exit(Number(status) > 0 ? Number(status) : 1);
    },

    /**
     * Downloads a resource and saves it on the filesystem.
     *
     * @param  String  url         The url of the resource to download
     * @param  String  targetPath  The destination file path
     * @return Casper
     */
    download: function(url, targetPath) {
        var cu = require('clientutils').create();
        try {
            fs.write(targetPath, cu.decode(this.base64encode(url)), 'w');
        } catch (e) {
            this.log("Error while downloading " + url + " to " + targetPath + ": " + e, "error");
        }
        return this;
    },

    /**
     * Iterates over the values of a provided array and execute a callback
     * for each item.
     *
     * @param  Array     array
     * @param  Function  fn     Callback: function(self, item, index)
     * @return Casper
     */
    each: function(array, fn) {
        if (!utils.isType(array, "array")) {
            this.log("each() only works with arrays", "error");
            return this;
        }
        (function(self) {
            array.forEach(function(item, i) {
                fn(self, item, i);
            });
        })(this);
        return this;
    },

    /**
     * Prints something to stdout.
     *
     * @param  String  text  A string to echo to stdout
     * @return Casper
     */
    echo: function(text, style) {
        console.log(style ? this.colorizer.colorize(text, style) : text);
        return this;
    },

    /**
     * Evaluates an expression in the page context, a bit like what
     * WebPage#evaluate does, but the passed function can also accept
     * parameters if a context Object is also passed:
     *
     *     casper.evaluate(function(username, password) {
     *         document.querySelector('#username').value = username;
     *         document.querySelector('#password').value = password;
     *         document.querySelector('#submit').click();
     *     }, {
     *         username: 'Bazoonga',
     *         password: 'baz00nga'
     *     })
     *
     * FIXME: waiting for a patch of PhantomJS to allow direct passing of
     * arguments to the function.
     * TODO: don't forget to keep this backward compatible.
     *
     * @param  Function  fn       The function to be evaluated within current page DOM
     * @param  Object    context  Object containing the parameters to inject into the function
     * @return mixed
     * @see    WebPage#evaluate
     */
    evaluate: function(fn, context) {
        context = utils.isType(context, "object") ? context : {};
        var newFn = require('injector').create(fn).process(context);
        return this.page.evaluate(newFn);
    },

    /**
     * Evaluates an expression within the current page DOM and die() if it
     * returns false.
     *
     * @param  function  fn       The expression to evaluate
     * @param  String    message  The error message to log
     * @return Casper
     */
    evaluateOrDie: function(fn, message) {
        if (!this.evaluate(fn)) {
            return this.die(message);
        }
        return this;
    },

    /**
     * Checks if an element matching the provided CSS3 selector exists in
     * current page DOM.
     *
     * @param  String  selector  A CSS3 selector
     * @return Boolean
     */
    exists: function(selector) {
        return this.evaluate(function(selector) {
            return __utils__.exists(selector);
        }, { selector: selector });
    },

    /**
     * Checks if an element matching the provided CSS3 selector is visible
     * current page DOM by checking that offsetWidth and offsetHeight are
     * both non-zero.
     *
     * @param  String  selector  A CSS3 selector
     * @return Boolean
     */
    visible: function(selector) {
        return this.evaluate(function(selector) {
            return __utils__.visible(selector);
        }, { selector: selector });
    },

    /**
     * Exits phantom.
     *
     * @param  Number  status  Status
     * @return Casper
     */
    exit: function(status) {
        phantom.exit(status);
        return this;
    },

    /**
     * Fetches innerText within the element(s) matching a given CSS3
     * selector.
     *
     * @param  String  selector  A CSS3 selector
     * @return String
     */
    fetchText: function(selector) {
        return this.evaluate(function(selector) {
            return __utils__.fetchText(selector);
        }, { selector: selector });
    },

    /**
     * Fills a form with provided field values.
     *
     * @param  String  selector  A CSS3 selector to the target form to fill
     * @param  Object  vals      Field values
     * @param  Boolean submit    Submit the form?
     */
    fill: function(selector, vals, submit) {
        submit = submit === true ? submit : false;
        if (!utils.isType(selector, "string") || !selector.length) {
            throw new Error("Form selector must be a non-empty string");
        }
        if (!utils.isType(vals, "object")) {
            throw new Error("Form values must be provided as an object");
        }
        var fillResults = this.evaluate(function(selector, values) {
           return __utils__.fill(selector, values);
        }, {
            selector: selector,
            values:   vals
        });
        if (!fillResults) {
            throw new Error("Unable to fill form");
        } else if (fillResults.errors.length > 0) {
            (function(self){
                fillResults.errors.forEach(function(error) {
                    self.log("form error: " + error, "error");
                });
            })(this);
            if (submit) {
                this.log("Errors encountered while filling form; submission aborted", "warning");
                submit = false;
            }
        }
        // File uploads
        if (fillResults.files && fillResults.files.length > 0) {
            (function(self) {
                fillResults.files.forEach(function(file) {
                    var fileFieldSelector = [selector, 'input[name="' + file.name + '"]'].join(' ');
                    self.page.uploadFile(fileFieldSelector, file.path);
                });
            })(this);
        }
        // Form submission?
        if (submit) {
            this.evaluate(function(selector) {
                var form = document.querySelector(selector);
                var method = form.getAttribute('method').toUpperCase() || "GET";
                var action = form.getAttribute('action') || "unknown";
                __utils__.log('submitting form to ' + action + ', HTTP ' + method, 'info');
                form.submit();
            }, { selector: selector });
        }
    },

    /**
     * Go a step forward in browser's history
     *
     * @return Casper
     */
    forward: function(then) {
        return this.then(function(self) {
            self.evaluate(function() {
                history.forward();
            });
        });
    },

    /**
     * Retrieves current document url.
     *
     * @return String
     */
    getCurrentUrl: function() {
        return decodeURIComponent(this.evaluate(function() {
            return document.location.href;
        }));
    },

    /**
     * Retrieves global variable.
     *
     * @param  String  name  The name of the global variable to retrieve
     * @return mixed
     */
    getGlobal: function(name) {
        var result = this.evaluate(function(name) {
            var result = {};
            try {
                result.value = JSON.stringify(window[name]);
            } catch (e) {
                result.error = 'Unable to JSON encode window.' + name + ': ' + e;
            }
            return result;
        }, {'name': name});
        if (result.error) {
            throw result.error;
        } else {
            return JSON.parse(result.value);
        }
    },

    /**
     * Retrieves current page title, if any.
     *
     * @return String
     */
    getTitle: function() {
        return this.evaluate(function() {
            return document.title;
        });
    },

    /**
     * Logs a message.
     *
     * @param  String  message  The message to log
     * @param  String  level    The log message level (from Casper.logLevels property)
     * @param  String  space    Space from where the logged event occured (default: "phantom")
     * @return Casper
     */
    log: function(message, level, space) {
        level = level && this.logLevels.indexOf(level) > -1 ? level : "debug";
        space = space ? space : "phantom";
        if (level === "error" && utils.isType(this.options.onError, "function")) {
            this.options.onError.call(this, this, message, space);
        }
        if (this.logLevels.indexOf(level) < this.logLevels.indexOf(this.options.logLevel)) {
            return this; // skip logging
        }
        var entry = {
            level:   level,
            space:   space,
            message: message,
            date:    new Date().toString()
        };
        if (level in this.logFormats && utils.isType(this.logFormats[level], "function")) {
            message = this.logFormats[level](message, level, space);
        } else {
            var levelStr = this.colorizer.colorize('[' + level + ']', this.logStyles[level]);
            message = levelStr + ' [' + space + '] ' + message;
        }
        if (this.options.verbose) {
            this.echo(message); // direct output
        }
        this.result.log.push(entry);
        return this;
    },

    /**
     * Opens a page. Takes only one argument, the url to open (using the
     * callback argument would defeat the whole purpose of Casper
     * actually).
     *
     * @param  String  location  The url to open
     * @return Casper
     */
    open: function(location, options) {
        options = utils.isType(options, "object") ? options : {};
        this.requestUrl = location;
        // http auth
        var httpAuthMatch = location.match(/^https?:\/\/(.+):(.+)@/i);
        if (httpAuthMatch) {
            this.setHttpAuth(httpAuthMatch[1], httpAuthMatch[2]);
        }
        this.page.open(location);
        return this;
    },

    /**
     * Repeats a step a given number of times.
     *
     * @param  Number    times  Number of times to repeat step
     * @aram   function  then   The step closure
     * @return Casper
     * @see    Casper#then
     */
    repeat: function(times, then) {
        for (var i = 0; i < times; i++) {
            this.then(then);
        }
        return this;
    },

    /**
     * Checks if a given resource was loaded by the remote page.
     *
     * @param  Function/String  test  A test function or string. In case a string is passed, url matching will be tested.
     * @return Boolean
     */
    resourceExists: function(test) {
        var testFn;
        if (utils.isType(test, "string")) {
            testFn = function (res) {
                return res.url.search(test) !== -1;
            };
        } else {
          testFn = test;
        }
        return this.resources.some(testFn);
    },

    /**
     * Runs the whole suite of steps.
     *
     * @param  function  onComplete  an optional callback
     * @param  Number    time        an optional amount of milliseconds for interval checking
     * @return Casper
     */
    run: function(onComplete, time) {
        if (!this.steps || this.steps.length < 1) {
            this.log("No steps defined, aborting", "error");
            return this;
        }
        this.log("Running suite: " + this.steps.length + " step" + (this.steps.length > 1 ? "s" : ""), "info");
        this.checker = setInterval(this.checkStep, (time ? time: 250), this, onComplete);
        return this;
    },

    /**
     * Runs a step.
     *
     * @param  Function  step
     */
    runStep: function(step) {
        var skipLog = utils.isType(step.options, "object") && step.options.skipLog === true;
        var stepInfo = "Step " + (this.step) + "/" + this.steps.length;
        var stepResult;
        if (!skipLog) {
            this.log(stepInfo + ' ' + this.getCurrentUrl() + ' (HTTP ' + this.currentHTTPStatus + ')', "info");
        }
        if (utils.isType(this.options.stepTimeout, "number") && this.options.stepTimeout > 0) {
            var stepTimeoutCheckInterval = setInterval(function(self, start, stepNum) {
                if (new Date().getTime() - start > self.options.stepTimeout) {
                    if (self.step == stepNum) {
                        if (utils.isType(self.options.onStepTimeout, "function")) {
                            self.options.onStepTimeout.call(self, self);
                        } else {
                            self.die("Maximum step execution timeout exceeded for step " + stepNum, "error");
                        }
                    }
                    clearInterval(stepTimeoutCheckInterval);
                }
            }, this.options.stepTimeout, this, new Date().getTime(), this.step);
        }
        try {
            stepResult = step.call(this, this);
        } catch (e) {
            if (this.options.faultTolerant) {
                this.log("Step error: " + e, "error");
            } else {
                throw e;
            }
        }
        if (utils.isType(this.options.onStepComplete, "function")) {
            this.options.onStepComplete.call(this, this, stepResult);
        }
        if (!skipLog) {
            this.log(stepInfo + ": done in " + (new Date().getTime() - this.startTime) + "ms.", "info");
        }
    },

    /**
     * Sets HTTP authentication parameters.
     *
     * @param  String   username  The HTTP_AUTH_USER value
     * @param  String   password  The HTTP_AUTH_PW value
     * @return Casper
     */
    setHttpAuth: function(username, password) {
        if (!this.started) {
            throw new Error("Casper must be started in order to use the setHttpAuth() method");
        }
        if (!utils.isType(username, "string") || !utils.isType(password, "string")) {
            throw new Error("Both username and password must be strings");
        }
        this.page.settings.userName = username;
        this.page.settings.password = password;
        this.log("Setting HTTP authentication for user " + username, "info");
        return this;
    },

    /**
     * Configures and starts Casper.
     *
     * @param  String   location  An optional location to open on start
     * @param  function then      Next step function to execute on page loaded (optional)
     * @return Casper
     */
    start: function(location, then) {
        this.log('Starting...', "info");
        this.startTime = new Date().getTime();
        this.history = [];
        this.steps = [];
        this.step = 0;
        // Option checks
        if (this.logLevels.indexOf(this.options.logLevel) < 0) {
            this.log("Unknown log level '" + this.options.logLevel + "', defaulting to 'warning'", "warning");
            this.options.logLevel = "warning";
        }
        // WebPage
        if (!utils.isWebPage(this.page)) {
            if (utils.isWebPage(this.options.page)) {
                this.page = this.options.page;
            } else {
                this.page = createPage(this);
            }
        }
        this.page.settings = utils.mergeObjects(this.page.settings, this.options.pageSettings);
        if (utils.isType(this.options.clipRect, "object")) {
            this.page.clipRect = this.options.clipRect;
        }
        if (utils.isType(this.options.viewportSize, "object")) {
            this.page.viewportSize = this.options.viewportSize;
        }
        this.started = true;
        if (utils.isType(this.options.timeout, "number") && this.options.timeout > 0) {
            this.log("Execution timeout set to " + this.options.timeout + 'ms', "info");
            setTimeout(function(self) {
                if (utils.isType(self.options.onTimeout, "function")) {
                    self.options.onTimeout.call(self, self);
                } else {
                    self.die("Timeout of " + self.options.timeout + "ms exceeded, exiting.");
                }
            }, this.options.timeout, this);
        }
        if (utils.isType(this.options.onPageInitialized, "function")) {
            this.log("Post-configuring WebPage instance", "debug");
            this.options.onPageInitialized.call(this, this.page);
        }
        if (utils.isType(location, "string") && location.length > 0) {
            return this.thenOpen(location, utils.isType(then, "function") ? then : this.createStep(function(self) {
                self.log("start page is loaded", "debug");
            }));
        }
        return this;
    },

    /**
     * Schedules the next step in the navigation process.
     *
     * @param  function  step  A function to be called as a step
     * @return Casper
     */
    then: function(step) {
        if (!this.started) {
            throw new Error("Casper not started; please use Casper#start");
        }
        if (!utils.isType(step, "function")) {
            throw new Error("You can only define a step as a function");
        }
        // check if casper is running
        if (this.checker === null) {
            // append step to the end of the queue
            step.level = 0;
            this.steps.push(step);
        } else {
            // insert substep a level deeper
            try {
                step.level = this.steps[this.step - 1].level + 1;
            } catch (e) {
                step.level = 0;
            }
            var insertIndex = this.step;
            while (this.steps[insertIndex] && step.level === this.steps[insertIndex].level) {
                insertIndex++;
            }
            this.steps.splice(insertIndex, 0, step);
        }
        return this;
    },

    /**
     * Adds a new navigation step for clicking on a provided link selector
     * and execute an optional next step.
     *
     * @param  String   selector        A DOM CSS3 compatible selector
     * @param  Function then            Next step function to execute on page loaded (optional)
     * @param  Boolean  fallbackToHref  Whether to try to relocate to the value of any href attribute (default: true)
     * @return Casper
     * @see    Casper#click
     * @see    Casper#then
     */
    thenClick: function(selector, then, fallbackToHref) {
        this.then(function(self) {
            self.click(selector, fallbackToHref);
        });
        return utils.isType(then, "function") ? this.then(then) : this;
    },

    /**
     * Adds a new navigation step to perform code evaluation within the
     * current retrieved page DOM.
     *
     * @param  function  fn       The function to be evaluated within current page DOM
     * @param  object    context  Optional function parameters context
     * @return Casper
     * @see    Casper#evaluate
     */
    thenEvaluate: function(fn, context) {
        return this.then(function(self) {
            self.evaluate(fn, context);
        });
    },

    /**
     * Adds a new navigation step for opening the provided location.
     *
     * @param  String   location  The URL to load
     * @param  function then      Next step function to execute on page loaded (optional)
     * @return Casper
     * @see    Casper#open
     */
    thenOpen: function(location, then) {
        this.then(this.createStep(function(self) {
            self.open(location);
        }, {
            skipLog: true
        }));
        return utils.isType(then, "function") ? this.then(then) : this;
    },

    /**
     * Adds a new navigation step for opening and evaluate an expression
     * against the DOM retrieved from the provided location.
     *
     * @param  String    location  The url to open
     * @param  function  fn        The function to be evaluated within current page DOM
     * @param  object    context   Optional function parameters context
     * @return Casper
     * @see    Casper#evaluate
     * @see    Casper#open
     */
    thenOpenAndEvaluate: function(location, fn, context) {
        return this.thenOpen(location).thenEvaluate(fn, context);
    },

    /**
     * Changes the current viewport size.
     *
     * @param  Number  width   The viewport width, in pixels
     * @param  Number  height  The viewport height, in pixels
     * @return Casper
     */
    viewport: function(width, height) {
        if (!this.started) {
            throw new Error("Casper must be started in order to set viewport at runtime");
        }
        if (!utils.isType(width, "number") || !utils.isType(height, "number") || width <= 0 || height <= 0) {
            throw new Error("Invalid viewport width/height set: " + width + 'x' + height);
        }
        this.page.viewportSize = {
            width: width,
            height: height
        };
        return this;
    },

    /**
     * Adds a new step that will wait for a given amount of time (expressed
     * in milliseconds) before processing an optional next one.
     *
     * @param  Number    timeout  The max amount of time to wait, in milliseconds
     * @param  Function  then     Next step to process (optional)
     * @return Casper
     */
    wait: function(timeout, then) {
        timeout = Number(timeout, 10);
        if (!utils.isType(timeout, "number") || timeout < 1) {
            this.die("wait() only accepts a positive integer > 0 as a timeout value");
        }
        if (then && !utils.isType(then, "function")) {
            this.die("wait() a step definition must be a function");
        }
        return this.then(function(self) {
            self.waitStart();
            setTimeout(function() {
              self.log("wait() finished wating for " + timeout + "ms.", "info");
              if (then) {
                then.call(self, self);
              }
              self.waitDone();
            }, timeout);
        });
    },

    waitStart: function() {
        this.pendingWait = true;
    },

    waitDone: function() {
        this.pendingWait = false;
    },

    /**
     * Waits until a function returns true to process a next step.
     *
     * @param  Function  testFx     A function to be evaluated for returning condition satisfecit
     * @param  Function  then       The next step to perform (optional)
     * @param  Function  onTimeout  A callback function to call on timeout (optional)
     * @param  Number    timeout    The max amount of time to wait, in milliseconds (optional)
     * @return Casper
     */
    waitFor: function(testFx, then, onTimeout, timeout) {
        timeout = timeout ? timeout : this.defaultWaitTimeout;
        if (!utils.isType(testFx, "function")) {
            this.die("waitFor() needs a test function");
        }
        if (then && !utils.isType(then, "function")) {
            this.die("waitFor() next step definition must be a function");
        }
        return this.then(function(self) {
            self.waitStart();
            var start = new Date().getTime();
            var condition = false;
            var interval = setInterval(function(self, testFx, timeout, onTimeout) {
                if ((new Date().getTime() - start < timeout) && !condition) {
                    condition = testFx(self);
                } else {
                    self.waitDone();
                    if (!condition) {
                        self.log("Casper.waitFor() timeout", "warning");
                        if (utils.isType(onTimeout, "function")) {
                            onTimeout.call(self, self);
                        } else {
                            self.die("Timeout of " + timeout + "ms expired, exiting.", "error");
                        }
                        clearInterval(interval);
                    } else {
                        self.log("waitFor() finished in " + (new Date().getTime() - start) + "ms.", "info");
                        if (then) {
                            self.then(then);
                        }
                        clearInterval(interval);
                    }
                }
          }, 100, self, testFx, timeout, onTimeout);
        });
    },

    /**
     * Waits until a given resource is loaded
     *
     * @param  String/Function  test       A function to test if the resource exists. A string will be matched against the resources url.
     * @param  Function         then       The next step to perform (optional)
     * @param  Function         onTimeout  A callback function to call on timeout (optional)
     * @param  Number           timeout    The max amount of time to wait, in milliseconds (optional)
     * @return Casper
     */
    waitForResource: function(test, then, onTimeout, timeout) {
        timeout = timeout ? timeout : this.defaultWaitTimeout;
        return this.waitFor(function(self) {
            return self.resourceExists(test);
        }, then, onTimeout, timeout);
    },

    /**
     * Waits until an element matching the provided CSS3 selector exists in
     * remote DOM to process a next step.
     *
     * @param  String    selector   A CSS3 selector
     * @param  Function  then       The next step to perform (optional)
     * @param  Function  onTimeout  A callback function to call on timeout (optional)
     * @param  Number    timeout    The max amount of time to wait, in milliseconds (optional)
     * @return Casper
     */
    waitForSelector: function(selector, then, onTimeout, timeout) {
        timeout = timeout ? timeout : this.defaultWaitTimeout;
        return this.waitFor(function(self) {
            return self.exists(selector);
        }, then, onTimeout, timeout);
    },

    /**
     * Waits until an element matching the provided CSS3 selector does not
     * exist in the remote DOM to process a next step.
     *
     * @param  String    selector   A CSS3 selector
     * @param  Function  then       The next step to perform (optional)
     * @param  Function  onTimeout  A callback function to call on timeout (optional)
     * @param  Number    timeout    The max amount of time to wait, in milliseconds (optional)
     * @return Casper
     */
    waitWhileSelector: function(selector, then, onTimeout, timeout) {
        timeout = timeout ? timeout : this.defaultWaitTimeout;
        return this.waitFor(function(self) {
            return !self.exists(selector);
        }, then, onTimeout, timeout);
    },

    /**
     * Waits until an element matching the provided CSS3 selector is
     * visible in the remote DOM to process a next step.
     *
     * @param  String    selector   A CSS3 selector
     * @param  Function  then       The next step to perform (optional)
     * @param  Function  onTimeout  A callback function to call on timeout (optional)
     * @param  Number    timeout    The max amount of time to wait, in milliseconds (optional)
     * @return Casper
     */
    waitUntilVisible: function(selector, then, onTimeout, timeout) {
        timeout = timeout ? timeout : this.defaultWaitTimeout;
        return this.waitFor(function(self) {
            return self.visible(selector);
        }, then, onTimeout, timeout);
    },

    /**
     * Waits until an element matching the provided CSS3 selector is no
     * longer visible in remote DOM to process a next step.
     *
     * @param  String    selector   A CSS3 selector
     * @param  Function  then       The next step to perform (optional)
     * @param  Function  onTimeout  A callback function to call on timeout (optional)
     * @param  Number    timeout    The max amount of time to wait, in milliseconds (optional)
     * @return Casper
     */
    waitWhileVisible: function(selector, then, onTimeout, timeout) {
        timeout = timeout ? timeout : this.defaultWaitTimeout;
        return this.waitFor(function(self) {
            return !self.visible(selector);
        }, then, onTimeout, timeout);
    }
};

/**
 * Extends Casper's prototype with provided one.
 *
 * @param  Object  proto  Prototype methods to add to Casper
 */
Casper.extend = function(proto) {
    if (!utils.isType(proto, "object")) {
        throw new Error("extends() only accept objects as prototypes");
    }
    utils.mergeObjects(Casper.prototype, proto);
};

exports.Casper = Casper;

/**
 * Creates a new WebPage instance for Casper use.
 *
 * @param  Casper  casper  A Casper instance
 * @return WebPage
 */
function createPage(casper) {
    var page;
    if (phantom.version.major <= 1 && phantom.version.minor < 3 && utils.isType(require, "function")) {
        page = new WebPage();
    } else {
        page = require('webpage').create();
    }
    page.onAlert = function(message) {
        casper.log('[alert] ' + message, "info", "remote");
        if (utils.isType(casper.options.onAlert, "function")) {
            casper.options.onAlert.call(casper, casper, message);
        }
    };
    page.onConsoleMessage = function(msg) {
        var level = "info", test = /^\[casper:(\w+)\]\s?(.*)/.exec(msg);
        if (test && test.length === 3) {
            level = test[1];
            msg = test[2];
        }
        casper.log(msg, level, "remote");
    };
    page.onLoadStarted = function() {
        casper.resources = [];
        casper.loadInProgress = true;
    };
    page.onLoadFinished = function(status) {
        if (status !== "success") {
            var message = 'Loading resource failed with status=' + status;
            if (casper.currentHTTPStatus) {
                message += ' (HTTP ' + casper.currentHTTPStatus + ')';
            }
            message += ': ' + casper.requestUrl;
            casper.log(message, "warning");
            if (utils.isType(casper.options.onLoadError, "function")) {
                casper.options.onLoadError.call(casper, casper, casper.requestUrl, status);
            }
        }
        if (casper.options.clientScripts) {
            if (!utils.isType(casper.options.clientScripts, "array")) {
                casper.log("The clientScripts option must be an array", "error");
            } else {
                for (var i = 0; i < casper.options.clientScripts.length; i++) {
                    var script = casper.options.clientScripts[i];
                    if (casper.page.injectJs(script)) {
                        casper.log('Automatically injected ' + script + ' client side', "debug");
                    } else {
                        casper.log('Failed injecting ' + script + ' client side', "warning");
                    }
                }
            }
        }
        // Client-side utils injection
        var clientUtilsPath = fs.pathJoin(phantom.casperPath, 'modules', 'clientutils.js');
        if (true === page.injectJs(clientUtilsPath)) {
            casper.log("Successfully injected Casper client-side utilities", "debug");
        } else {
            casper.log("Failed to instantiate Casper client-side utilities!", "warning");
        }
        // history
        casper.history.push(casper.getCurrentUrl());
        casper.loadInProgress = false;
    };
    page.onResourceReceived = function(resource) {
        if (utils.isType(casper.options.onResourceReceived, "function")) {
            casper.options.onResourceReceived.call(casper, casper, resource);
        }
        if (resource.stage === "end") {
            casper.resources.push(resource);
        }
        if (resource.url === casper.requestUrl && resource.stage === "start") {
            casper.currentHTTPStatus = resource.status;
            if (utils.isType(casper.options.httpStatusHandlers, "object") &&
                resource.status in casper.options.httpStatusHandlers &&
                utils.isType(casper.options.httpStatusHandlers[resource.status], "function")) {
                casper.options.httpStatusHandlers[resource.status].call(casper, casper, resource);
            }
            casper.currentUrl = resource.url;
        }
    };
    page.onResourceRequested = function(request) {
        if (utils.isType(casper.options.onResourceRequested, "function")) {
            casper.options.onResourceRequested.call(casper, casper, request);
        }
    };
    return page;
}