injected-script-source.js 37.1 KB
Newer Older
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
/*
 * Copyright (C) 2007 Apple Inc.  All rights reserved.
 * Copyright (C) 2013 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

"use strict";

/**
 * @param {!InjectedScriptHostClass} InjectedScriptHost
 * @param {!Window|!WorkerGlobalScope} inspectedGlobalObject
 * @param {number} injectedScriptId
36
 * @suppress {uselessCode}
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
 */
(function (InjectedScriptHost, inspectedGlobalObject, injectedScriptId) {

/**
 * @param {!Array.<T>} array
 * @param {...} var_args
 * @template T
 */
function push(array, var_args)
{
    for (var i = 1; i < arguments.length; ++i)
        array[array.length] = arguments[i];
}

/**
 * @param {*} obj
 * @return {string}
 * @suppress {uselessCode}
 */
function toString(obj)
{
    // We don't use String(obj) because String could be overridden.
    // Also the ("" + obj) expression may throw.
    try {
        return "" + obj;
    } catch (e) {
        var name = InjectedScriptHost.internalConstructorName(obj) || InjectedScriptHost.subtype(obj) || (typeof obj);
        return "#<" + name + ">";
    }
}

/**
 * @param {*} obj
 * @return {string}
 */
function toStringDescription(obj)
{
    if (typeof obj === "number" && obj === 0 && 1 / obj < 0)
        return "-0"; // Negative zero.
    return toString(obj);
}

/**
 * @param {number|string} obj
 * @return {boolean}
 */
function isUInt32(obj)
{
    if (typeof obj === "number")
        return obj >>> 0 === obj && (obj > 0 || 1 / obj > 0);
    return "" + (obj >>> 0) === obj;
}

/**
 * FireBug's array detection.
 * @param {*} obj
 * @return {boolean}
 */
function isArrayLike(obj)
{
    if (typeof obj !== "object")
        return false;
99 100 101 102 103 104
    var splice = InjectedScriptHost.getProperty(obj, "splice");
    if (typeof splice === "function") {
        if (!InjectedScriptHost.objectHasOwnProperty(/** @type {!Object} */ (obj), "length"))
            return false;
        var len = InjectedScriptHost.getProperty(obj, "length");
        return typeof len === "number" && isUInt32(len);
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
    }
    return false;
}

/**
 * @param {number} a
 * @param {number} b
 * @return {number}
 */
function max(a, b)
{
    return a > b ? a : b;
}

/**
 * FIXME: Remove once ES6 is supported natively by JS compiler.
 * @param {*} obj
 * @return {boolean}
 */
function isSymbol(obj)
{
    var type = typeof obj;
    return (type === "symbol");
}

/**
 * DOM Attributes which have observable side effect on getter, in the form of
 *   {interfaceName1: {attributeName1: true,
 *                     attributeName2: true,
 *                     ...},
 *    interfaceName2: {...},
 *    ...}
 * @type {!Object<string, !Object<string, boolean>>}
 * @const
 */
140 141 142 143 144
var domAttributesWithObservableSideEffectOnGet = {
    Request: { body: true, __proto__: null },
    Response: { body: true, __proto__: null },
    __proto__: null
}
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168

/**
 * @param {!Object} object
 * @param {string} attribute
 * @return {boolean}
 */
function doesAttributeHaveObservableSideEffectOnGet(object, attribute)
{
    for (var interfaceName in domAttributesWithObservableSideEffectOnGet) {
        var interfaceFunction = inspectedGlobalObject[interfaceName];
        // Call to instanceOf looks safe after typeof check.
        var isInstance = typeof interfaceFunction === "function" && /* suppressBlacklist */ object instanceof interfaceFunction;
        if (isInstance)
            return attribute in domAttributesWithObservableSideEffectOnGet[interfaceName];
    }
    return false;
}

/**
 * @constructor
 */
var InjectedScript = function()
{
}
169
InjectedScriptHost.nullifyPrototype(InjectedScript);
170 171

/**
172
 * @type {!Object<string, boolean>}
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
 * @const
 */
InjectedScript.primitiveTypes = {
    "undefined": true,
    "boolean": true,
    "number": true,
    "string": true,
    __proto__: null
}

/**
 * @type {!Object<string, string>}
 * @const
 */
InjectedScript.closureTypes = { __proto__: null };
InjectedScript.closureTypes["local"] = "Local";
InjectedScript.closureTypes["closure"] = "Closure";
InjectedScript.closureTypes["catch"] = "Catch";
InjectedScript.closureTypes["block"] = "Block";
InjectedScript.closureTypes["script"] = "Script";
InjectedScript.closureTypes["with"] = "With Block";
InjectedScript.closureTypes["global"] = "Global";
195
InjectedScript.closureTypes["eval"] = "Eval";
196
InjectedScript.closureTypes["module"] = "Module";
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

InjectedScript.prototype = {
    /**
     * @param {*} object
     * @return {boolean}
     */
    isPrimitiveValue: function(object)
    {
        // FIXME(33716): typeof document.all is always 'undefined'.
        return InjectedScript.primitiveTypes[typeof object] && !this._isHTMLAllCollection(object);
    },

    /**
     * @param {*} object
     * @return {boolean}
     */
    _shouldPassByValue: function(object)
    {
        return typeof object === "object" && InjectedScriptHost.subtype(object) === "internal#location";
    },

    /**
     * @param {*} object
     * @param {string} groupName
     * @param {boolean} forceValueType
     * @param {boolean} generatePreview
     * @return {!RuntimeAgent.RemoteObject}
     */
    wrapObject: function(object, groupName, forceValueType, generatePreview)
    {
        return this._wrapObject(object, groupName, forceValueType, generatePreview);
    },

    /**
     * @param {!Array<!Object>} array
     * @param {string} property
     * @param {string} groupName
     * @param {boolean} forceValueType
     * @param {boolean} generatePreview
     */
    wrapPropertyInArray: function(array, property, groupName, forceValueType, generatePreview)
    {
        for (var i = 0; i < array.length; ++i) {
            if (typeof array[i] === "object" && property in array[i])
                array[i][property] = this.wrapObject(array[i][property], groupName, forceValueType, generatePreview);
        }
    },

    /**
     * @param {!Object} table
     * @param {!Array.<string>|string|boolean} columns
     * @return {!RuntimeAgent.RemoteObject}
     */
    wrapTable: function(table, columns)
    {
        var columnNames = null;
        if (typeof columns === "string")
            columns = [columns];
        if (InjectedScriptHost.subtype(columns) === "array") {
            columnNames = [];
            for (var i = 0; i < columns.length; ++i)
                columnNames[i] = toString(columns[i]);
        }
        return this._wrapObject(table, "console", false, true, columnNames, true);
    },

    /**
     * This method cannot throw.
     * @param {*} object
     * @param {string=} objectGroupName
     * @param {boolean=} forceValueType
     * @param {boolean=} generatePreview
     * @param {?Array.<string>=} columnNames
     * @param {boolean=} isTable
     * @param {boolean=} doNotBind
     * @param {*=} customObjectConfig
     * @return {!RuntimeAgent.RemoteObject}
     * @suppress {checkTypes}
     */
    _wrapObject: function(object, objectGroupName, forceValueType, generatePreview, columnNames, isTable, doNotBind, customObjectConfig)
    {
        try {
            return new InjectedScript.RemoteObject(object, objectGroupName, doNotBind, forceValueType, generatePreview, columnNames, isTable, undefined, customObjectConfig);
        } catch (e) {
            try {
                var description = injectedScript._describe(e);
            } catch (ex) {
                var description = "<failed to convert exception to string>";
            }
            return new InjectedScript.RemoteObject(description);
        }
    },

    /**
     * @param {!Object|symbol} object
     * @param {string=} objectGroupName
     * @return {string}
     */
    _bind: function(object, objectGroupName)
    {
        var id = InjectedScriptHost.bind(object, objectGroupName || "");
        return "{\"injectedScriptId\":" + injectedScriptId + ",\"id\":" + id + "}";
    },

    /**
     * @param {!Object} object
     * @param {string} objectGroupName
     * @param {boolean} ownProperties
     * @param {boolean} accessorPropertiesOnly
     * @param {boolean} generatePreview
     * @return {!Array<!RuntimeAgent.PropertyDescriptor>|boolean}
     */
    getProperties: function(object, objectGroupName, ownProperties, accessorPropertiesOnly, generatePreview)
    {
        var subtype = this._subtype(object);
        if (subtype === "internal#scope") {
            // Internally, scope contains object with scope variables and additional information like type,
            // we use additional information for preview and would like to report variables as scope
            // properties.
            object = object.object;
        }

        // Go over properties, wrap object values.
320 321 322
        var descriptors = this._propertyDescriptors(object, addPropertyIfNeeded, ownProperties, accessorPropertiesOnly);
        for (var i = 0; i < descriptors.length; ++i) {
            var descriptor = descriptors[i];
323 324 325 326 327 328 329 330 331 332 333 334 335 336
            if ("get" in descriptor)
                descriptor.get = this._wrapObject(descriptor.get, objectGroupName);
            if ("set" in descriptor)
                descriptor.set = this._wrapObject(descriptor.set, objectGroupName);
            if ("value" in descriptor)
                descriptor.value = this._wrapObject(descriptor.value, objectGroupName, false, generatePreview);
            if (!("configurable" in descriptor))
                descriptor.configurable = false;
            if (!("enumerable" in descriptor))
                descriptor.enumerable = false;
            if ("symbol" in descriptor)
                descriptor.symbol = this._wrapObject(descriptor.symbol, objectGroupName);
        }
        return descriptors;
337 338 339 340 341 342 343 344 345 346

        /**
         * @param {!Array<!Object>} descriptors
         * @param {!Object} descriptor
         * @return {boolean}
         */
        function addPropertyIfNeeded(descriptors, descriptor) {
            push(descriptors, descriptor);
            return true;
        }
347 348 349 350 351 352 353 354 355 356 357
    },

    /**
     * @param {!Object} object
     * @return {?Object}
     */
    _objectPrototype: function(object)
    {
        if (InjectedScriptHost.subtype(object) === "proxy")
            return null;
        try {
358
            return InjectedScriptHost.getPrototypeOf(object);
359 360 361 362 363 364 365
        } catch (e) {
            return null;
        }
    },

    /**
     * @param {!Object} object
366
     * @param {!function(!Array<!Object>, !Object)} addPropertyIfNeeded
367 368
     * @param {boolean=} ownProperties
     * @param {boolean=} accessorPropertiesOnly
369 370
     * @param {?Array<string>=} propertyNamesOnly
     * @return {!Array<!Object>}
371
     */
372
    _propertyDescriptors: function(object, addPropertyIfNeeded, ownProperties, accessorPropertiesOnly, propertyNamesOnly)
373
    {
374
        var descriptors = [];
375
        InjectedScriptHost.nullifyPrototype(descriptors);
376
        var propertyProcessed = { __proto__: null };
377
        var subtype = InjectedScriptHost.subtype(object);
378 379

        /**
380 381 382 383
         * @param {!Object} o
         * @param {!Array<string|number|symbol>=} properties
         * @param {number=} objectLength
         * @return {boolean}
384
         */
385
        function process(o, properties, objectLength)
386
        {
387 388 389 390 391 392 393
            // When properties is not provided, iterate over the object's indices.
            var length = properties ? properties.length : objectLength;
            for (var i = 0; i < length; ++i) {
                var property = properties ? properties[i] : ("" + i);
                if (propertyProcessed[property])
                    continue;
                propertyProcessed[property] = true;
394 395 396 397 398 399
                var name;
                if (isSymbol(property))
                    name = /** @type {string} */ (injectedScript._describe(property));
                else
                    name = typeof property === "number" ? ("" + property) : /** @type {string} */(property);

400
                if (subtype === "internal#scopeList" && name === "length")
401 402
                    continue;

403
                var descriptor;
404
                try {
405
                    descriptor = InjectedScriptHost.getOwnPropertyDescriptor(o, property);
406 407 408
                    if (descriptor) {
                        InjectedScriptHost.nullifyPrototype(descriptor);
                    }
409 410
                    var isAccessorProperty = descriptor && ("get" in descriptor || "set" in descriptor);
                    if (accessorPropertiesOnly && !isAccessorProperty)
411
                        continue;
412 413 414 415 416 417 418
                    if (descriptor && "get" in descriptor && "set" in descriptor && name !== "__proto__" &&
                            InjectedScriptHost.formatAccessorsAsProperties(object, descriptor.get) &&
                            !doesAttributeHaveObservableSideEffectOnGet(object, name)) {
                        descriptor.value = object[property];
                        descriptor.isOwn = true;
                        delete descriptor.get;
                        delete descriptor.set;
419 420 421 422
                    }
                } catch (e) {
                    if (accessorPropertiesOnly)
                        continue;
423
                    descriptor = { value: e, wasThrown: true, __proto__: null };
424 425 426 427 428 429
                }

                // Not all bindings provide proper descriptors. Fall back to the non-configurable, non-enumerable,
                // non-writable property.
                if (!descriptor) {
                    try {
430
                        descriptor = { value: o[property], writable: false, __proto__: null };
431 432 433 434
                    } catch (e) {
                        // Silent catch.
                        continue;
                    }
435 436 437 438 439 440 441
                }

                descriptor.name = name;
                if (o === object)
                    descriptor.isOwn = true;
                if (isSymbol(property))
                    descriptor.symbol = property;
442 443
                if (!addPropertyIfNeeded(descriptors, descriptor))
                    return false;
444
            }
445
            return true;
446 447 448 449 450
        }

        if (propertyNamesOnly) {
            for (var i = 0; i < propertyNamesOnly.length; ++i) {
                var name = propertyNamesOnly[i];
451 452
                for (var o = object; this._isDefined(o); o = this._objectPrototype(/** @type {!Object} */ (o))) {
                    o = /** @type {!Object} */ (o);
453
                    if (InjectedScriptHost.objectHasOwnProperty(o, name)) {
454 455
                        if (!process(o, [name]))
                            return descriptors;
456 457 458 459 460 461
                        break;
                    }
                    if (ownProperties)
                        break;
                }
            }
462
            return descriptors;
463 464 465 466
        }

        var skipGetOwnPropertyNames;
        try {
467
            skipGetOwnPropertyNames = subtype === "typedarray" && object.length > 500000;
468 469 470
        } catch (e) {
        }

471 472
        for (var o = object; this._isDefined(o); o = this._objectPrototype(/** @type {!Object} */ (o))) {
            o = /** @type {!Object} */ (o);
473 474
            if (InjectedScriptHost.subtype(o) === "proxy")
                continue;
475 476 477 478 479 480 481

            try {
                if (skipGetOwnPropertyNames && o === object) {
                    if (!process(o, undefined, o.length))
                        return descriptors;
                } else {
                    // First call Object.keys() to enforce ordering of the property descriptors.
482
                    if (!process(o, InjectedScriptHost.keys(o)))
483
                        return descriptors;
484
                    if (!process(o, InjectedScriptHost.getOwnPropertyNames(o)))
485 486
                        return descriptors;
                }
487 488
                if (!process(o, InjectedScriptHost.getOwnPropertySymbols(o)))
                    return descriptors;
489 490 491 492 493 494 495 496 497 498

                if (ownProperties) {
                    var proto = this._objectPrototype(o);
                    if (proto && !accessorPropertiesOnly) {
                        var descriptor = { name: "__proto__", value: proto, writable: true, configurable: true, enumerable: false, isOwn: true, __proto__: null };
                        if (!addPropertyIfNeeded(descriptors, descriptor))
                            return descriptors;
                    }
                }
            } catch (e) {
499
            }
500 501

            if (ownProperties)
502 503
                break;
        }
504
        return descriptors;
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
    },

    /**
     * @param {string|undefined} objectGroupName
     * @param {*} jsonMLObject
     * @throws {string} error message
     */
    _substituteObjectTagsInCustomPreview: function(objectGroupName, jsonMLObject)
    {
        var maxCustomPreviewRecursionDepth = 20;
        this._customPreviewRecursionDepth = (this._customPreviewRecursionDepth || 0) + 1
        try {
            if (this._customPreviewRecursionDepth >= maxCustomPreviewRecursionDepth)
                throw new Error("Too deep hierarchy of inlined custom previews");

            if (!isArrayLike(jsonMLObject))
                return;

            if (jsonMLObject[0] === "object") {
                var attributes = jsonMLObject[1];
                var originObject = attributes["object"];
                var config = attributes["config"];
                if (typeof originObject === "undefined")
                    throw new Error("Illegal format: obligatory attribute \"object\" isn't specified");

                jsonMLObject[1] = this._wrapObject(originObject, objectGroupName, false, false, null, false, false, config);
                return;
            }

            for (var i = 0; i < jsonMLObject.length; ++i)
                this._substituteObjectTagsInCustomPreview(objectGroupName, jsonMLObject[i]);
        } finally {
            this._customPreviewRecursionDepth--;
        }
    },

    /**
     * @param {*} object
     * @return {boolean}
     */
    _isDefined: function(object)
    {
        return !!object || this._isHTMLAllCollection(object);
    },

    /**
     * @param {*} object
     * @return {boolean}
     */
    _isHTMLAllCollection: function(object)
    {
        // document.all is reported as undefined, but we still want to process it.
        return (typeof object === "undefined") && !!InjectedScriptHost.subtype(object);
    },

    /**
     * @param {*} obj
     * @return {?string}
     */
    _subtype: function(obj)
    {
        if (obj === null)
            return "null";

        if (this.isPrimitiveValue(obj))
            return null;

        var subtype = InjectedScriptHost.subtype(obj);
        if (subtype)
            return subtype;

        if (isArrayLike(obj))
            return "array";

        // If owning frame has navigated to somewhere else window properties will be undefined.
        return null;
    },

    /**
     * @param {*} obj
     * @return {?string}
     */
    _describe: function(obj)
    {
        if (this.isPrimitiveValue(obj))
            return null;

        var subtype = this._subtype(obj);

        if (subtype === "regexp")
            return toString(obj);

        if (subtype === "date")
            return toString(obj);

        if (subtype === "node") {
            var description = "";
            if (obj.nodeName)
                description = obj.nodeName.toLowerCase();
            else if (obj.constructor)
                description = obj.constructor.name.toLowerCase();

            switch (obj.nodeType) {
            case 1 /* Node.ELEMENT_NODE */:
                description += obj.id ? "#" + obj.id : "";
                var className = obj.className;
                description += (className && typeof className === "string") ? "." + className.trim().replace(/\s+/g, ".") : "";
                break;
            case 10 /*Node.DOCUMENT_TYPE_NODE */:
                description = "<!DOCTYPE " + description + ">";
                break;
            }
            return description;
        }

        if (subtype === "proxy")
            return "Proxy";

        var className = InjectedScriptHost.internalConstructorName(obj);
        if (subtype === "array" || subtype === "typedarray") {
            if (typeof obj.length === "number")
626 627 628 629 630 631 632
                return className + "(" + obj.length + ")";
            return className;
        }

        if (subtype === "map" || subtype === "set") {
            if (typeof obj.size === "number")
                return className + "(" + obj.size + ")";
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
            return className;
        }

        if (typeof obj === "function")
            return toString(obj);

        if (isSymbol(obj)) {
            try {
                // It isn't safe, because Symbol.prototype.toString can be overriden.
                return /* suppressBlacklist */ obj.toString() || "Symbol";
            } catch (e) {
                return "Symbol";
            }
        }

        if (InjectedScriptHost.subtype(obj) === "error") {
            try {
                var stack = obj.stack;
                var message = obj.message && obj.message.length ? ": " + obj.message : "";
                var firstCallFrame = /^\s+at\s/m.exec(stack);
                var stackMessageEnd = firstCallFrame ? firstCallFrame.index : -1;
                if (stackMessageEnd !== -1) {
                    var stackTrace = stack.substr(stackMessageEnd);
                    return className + message + "\n" + stackTrace;
                }
                return className + message;
            } catch(e) {
            }
        }

        if (subtype === "internal#entry") {
            if ("key" in obj)
                return "{" + this._describeIncludingPrimitives(obj.key) + " => " + this._describeIncludingPrimitives(obj.value) + "}";
            return this._describeIncludingPrimitives(obj.value);
        }

        if (subtype === "internal#scopeList")
            return "Scopes[" + obj.length + "]";

        if (subtype === "internal#scope")
            return (InjectedScript.closureTypes[obj.type] || "Unknown") + (obj.name ? " (" + obj.name + ")" : "");

        return className;
    },

    /**
     * @param {*} value
     * @return {string}
     */
    _describeIncludingPrimitives: function(value)
    {
        if (typeof value === "string")
            return "\"" + value.replace(/\n/g, "\u21B5") + "\"";
        if (value === null)
            return "" + value;
        return this.isPrimitiveValue(value) ? toStringDescription(value) : (this._describe(value) || "");
    },

    /**
     * @param {boolean} enabled
     */
    setCustomObjectFormatterEnabled: function(enabled)
    {
        this._customObjectFormatterEnabled = enabled;
    }
}

/**
 * @type {!InjectedScript}
 * @const
 */
var injectedScript = new InjectedScript();

/**
 * @constructor
 * @param {*} object
 * @param {string=} objectGroupName
 * @param {boolean=} doNotBind
 * @param {boolean=} forceValueType
 * @param {boolean=} generatePreview
 * @param {?Array.<string>=} columnNames
 * @param {boolean=} isTable
 * @param {boolean=} skipEntriesPreview
 * @param {*=} customObjectConfig
 */
InjectedScript.RemoteObject = function(object, objectGroupName, doNotBind, forceValueType, generatePreview, columnNames, isTable, skipEntriesPreview, customObjectConfig)
{
    this.type = typeof object;
    if (this.type === "undefined" && injectedScript._isHTMLAllCollection(object))
        this.type = "object";

    if (injectedScript.isPrimitiveValue(object) || object === null || forceValueType) {
        // We don't send undefined values over JSON.
        if (this.type !== "undefined")
            this.value = object;

        // Null object is object with 'null' subtype.
        if (object === null)
            this.subtype = "null";

        // Provide user-friendly number values.
        if (this.type === "number") {
            this.description = toStringDescription(object);
            switch (this.description) {
            case "NaN":
            case "Infinity":
            case "-Infinity":
            case "-0":
                delete this.value;
                this.unserializableValue = this.description;
                break;
            }
        }

        return;
    }

    if (injectedScript._shouldPassByValue(object)) {
        this.value = object;
        this.subtype = injectedScript._subtype(object);
        this.description = injectedScript._describeIncludingPrimitives(object);
        return;
    }

    object = /** @type {!Object} */ (object);

    if (!doNotBind)
        this.objectId = injectedScript._bind(object, objectGroupName);
    var subtype = injectedScript._subtype(object);
    if (subtype)
        this.subtype = subtype;
    var className = InjectedScriptHost.internalConstructorName(object);
    if (className)
        this.className = className;
    this.description = injectedScript._describe(object);

    if (generatePreview && this.type === "object") {
        if (this.subtype === "proxy")
            this.preview = this._generatePreview(InjectedScriptHost.proxyTargetValue(object), undefined, columnNames, isTable, skipEntriesPreview);
        else if (this.subtype !== "node")
            this.preview = this._generatePreview(object, undefined, columnNames, isTable, skipEntriesPreview);
    }

    if (injectedScript._customObjectFormatterEnabled) {
        var customPreview = this._customPreview(object, objectGroupName, customObjectConfig);
        if (customPreview)
            this.customPreview = customPreview;
    }
}

InjectedScript.RemoteObject.prototype = {

    /**
     * @param {*} object
     * @param {string=} objectGroupName
     * @param {*=} customObjectConfig
     * @return {?RuntimeAgent.CustomPreview}
     */
    _customPreview: function(object, objectGroupName, customObjectConfig)
    {
        /**
         * @param {!Error} error
         */
        function logError(error)
        {
            // We use user code to generate custom output for object, we can use user code for reporting error too.
            Promise.resolve().then(/* suppressBlacklist */ inspectedGlobalObject.console.error.bind(inspectedGlobalObject.console, "Custom Formatter Failed: " + error.message));
        }

        /**
         * @param {*} object
         * @param {*=} customObjectConfig
         * @return {*}
         */
        function wrap(object, customObjectConfig)
        {
            return injectedScript._wrapObject(object, objectGroupName, false, false, null, false, false, customObjectConfig);
        }

        try {
            var formatters = inspectedGlobalObject["devtoolsFormatters"];
            if (!formatters || !isArrayLike(formatters))
                return null;

            for (var i = 0; i < formatters.length; ++i) {
                try {
                    var formatted = formatters[i].header(object, customObjectConfig);
                    if (!formatted)
                        continue;

                    var hasBody = formatters[i].hasBody(object, customObjectConfig);
                    injectedScript._substituteObjectTagsInCustomPreview(objectGroupName, formatted);
                    var formatterObjectId = injectedScript._bind(formatters[i], objectGroupName);
                    var bindRemoteObjectFunctionId = injectedScript._bind(wrap, objectGroupName);
                    var result = {header: JSON.stringify(formatted), hasBody: !!hasBody, formatterObjectId: formatterObjectId, bindRemoteObjectFunctionId: bindRemoteObjectFunctionId};
                    if (customObjectConfig)
                        result["configObjectId"] = injectedScript._bind(customObjectConfig, objectGroupName);
                    return result;
                } catch (e) {
                    logError(e);
                }
            }
        } catch (e) {
            logError(e);
        }
        return null;
    },

    /**
     * @return {!RuntimeAgent.ObjectPreview} preview
     */
    _createEmptyPreview: function()
    {
        var preview = {
            type: /** @type {!RuntimeAgent.ObjectPreviewType.<string>} */ (this.type),
            description: this.description || toStringDescription(this.value),
            overflow: false,
            properties: [],
            __proto__: null
        };
        if (this.subtype)
            preview.subtype = /** @type {!RuntimeAgent.ObjectPreviewSubtype.<string>} */ (this.subtype);
        return preview;
    },

    /**
     * @param {!Object} object
     * @param {?Array.<string>=} firstLevelKeys
     * @param {?Array.<string>=} secondLevelKeys
     * @param {boolean=} isTable
     * @param {boolean=} skipEntriesPreview
     * @return {!RuntimeAgent.ObjectPreview} preview
     */
    _generatePreview: function(object, firstLevelKeys, secondLevelKeys, isTable, skipEntriesPreview)
    {
        var preview = this._createEmptyPreview();
        var firstLevelKeysCount = firstLevelKeys ? firstLevelKeys.length : 0;
        var propertiesThreshold = {
            properties: isTable ? 1000 : max(5, firstLevelKeysCount),
            indexes: isTable ? 1000 : max(100, firstLevelKeysCount),
            __proto__: null
        };
875
        var subtype = this.subtype;
876 877

        try {
878
            var descriptors = injectedScript._propertyDescriptors(object, addPropertyIfNeeded, false /* ownProperties */, undefined /* accessorPropertiesOnly */, firstLevelKeys);
879 880 881 882 883 884 885 886 887 888

            // Add internal properties to preview.
            var rawInternalProperties = InjectedScriptHost.getInternalProperties(object) || [];
            var internalProperties = [];
            var entries = null;
            for (var i = 0; i < rawInternalProperties.length; i += 2) {
                if (rawInternalProperties[i] === "[[Entries]]") {
                    entries = /** @type {!Array<*>} */(rawInternalProperties[i + 1]);
                    continue;
                }
889
                var internalPropertyDescriptor = {
890 891 892 893 894
                    name: rawInternalProperties[i],
                    value: rawInternalProperties[i + 1],
                    isOwn: true,
                    enumerable: true,
                    __proto__: null
895 896 897
                };
                if (!addPropertyIfNeeded(descriptors, internalPropertyDescriptor))
                    break;
898
            }
899
            this._appendPropertyPreviewDescriptors(preview, descriptors, secondLevelKeys, isTable);
900

901
            if (subtype === "map" || subtype === "set" || subtype === "weakmap" || subtype === "weakset" || subtype === "iterator")
902 903 904 905 906 907
                this._appendEntriesPreview(entries, preview, skipEntriesPreview);

        } catch (e) {}

        return preview;

908 909 910 911 912 913 914 915
        /**
         * @param {!Array<!Object>} descriptors
         * @param {!Object} descriptor
         * @return {boolean}
         */
        function addPropertyIfNeeded(descriptors, descriptor) {
            if (descriptor.wasThrown)
                return true;
916 917

            // Ignore __proto__ property.
918 919
            if (descriptor.name === "__proto__")
                return true;
920 921

            // Ignore length property of array.
922 923
            if ((subtype === "array" || subtype === "typedarray") && descriptor.name === "length")
                return true;
924 925

            // Ignore size property of map, set.
926 927
            if ((subtype === "map" || subtype === "set") && descriptor.name === "size")
                return true;
928 929 930

            // Never preview prototype properties.
            if (!descriptor.isOwn)
931
                return true;
932

933
            // Ignore computed properties unless they have getters.
934 935 936 937 938 939 940 941 942 943 944 945
            if (!("value" in descriptor) && !descriptor.get)
                return true;

            if (toString(descriptor.name >>> 0) === descriptor.name)
                propertiesThreshold.indexes--;
            else
                propertiesThreshold.properties--;

            var canContinue = propertiesThreshold.indexes >= 0 && propertiesThreshold.properties >= 0;
            if (!canContinue) {
                preview.overflow = true;
                return false;
946
            }
947 948 949 950
            push(descriptors, descriptor);
            return true;
        }
    },
951

952 953 954 955 956 957 958 959 960 961 962
    /**
     * @param {!RuntimeAgent.ObjectPreview} preview
     * @param {!Array.<*>|!Iterable.<*>} descriptors
     * @param {?Array.<string>=} secondLevelKeys
     * @param {boolean=} isTable
     */
    _appendPropertyPreviewDescriptors: function(preview, descriptors, secondLevelKeys, isTable)
    {
        for (var i = 0; i < descriptors.length; ++i) {
            var descriptor = descriptors[i];
            var name = descriptor.name;
963 964 965 966 967 968 969
            var value = descriptor.value;
            var type = typeof value;

            // Special-case HTMLAll.
            if (type === "undefined" && injectedScript._isHTMLAllCollection(value))
                type = "object";

970 971 972 973 974 975
            // Ignore computed properties unless they have getters.
            if (descriptor.get && !("value" in descriptor)) {
                push(preview.properties, { name: name, type: "accessor", __proto__: null });
                continue;
            }

976 977
            // Render own properties.
            if (value === null) {
978
                push(preview.properties, { name: name, type: "object", subtype: "null", value: "null", __proto__: null });
979 980 981 982 983 984 985
                continue;
            }

            var maxLength = 100;
            if (InjectedScript.primitiveTypes[type]) {
                if (type === "string" && value.length > maxLength)
                    value = this._abbreviateString(value, maxLength, true);
986
                push(preview.properties, { name: name, type: type, value: toStringDescription(value), __proto__: null });
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
                continue;
            }

            var property = { name: name, type: type, __proto__: null };
            var subtype = injectedScript._subtype(value);
            if (subtype)
                property.subtype = subtype;

            if (secondLevelKeys === null || secondLevelKeys) {
                var subPreview = this._generatePreview(value, secondLevelKeys || undefined, undefined, isTable);
                property.valuePreview = subPreview;
                if (subPreview.overflow)
                    preview.overflow = true;
            } else {
                var description = "";
                if (type !== "function")
                    description = this._abbreviateString(/** @type {string} */ (injectedScript._describe(value)), maxLength, subtype === "regexp");
                property.value = description;
            }
            push(preview.properties, property);
        }
    },

    /**
     * @param {?Array<*>} entries
     * @param {!RuntimeAgent.ObjectPreview} preview
     * @param {boolean=} skipEntriesPreview
     */
    _appendEntriesPreview: function(entries, preview, skipEntriesPreview)
    {
        if (!entries)
            return;
        if (skipEntriesPreview) {
            if (entries.length)
                preview.overflow = true;
            return;
        }
        preview.entries = [];
        var entriesThreshold = 5;
        for (var i = 0; i < entries.length; ++i) {
            if (preview.entries.length >= entriesThreshold) {
                preview.overflow = true;
                break;
            }
1031 1032
            var entry = entries[i];
            InjectedScriptHost.nullifyPrototype(entry);
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
            var previewEntry = {
                value: generateValuePreview(entry.value),
                __proto__: null
            };
            if ("key" in entry)
                previewEntry.key = generateValuePreview(entry.key);
            push(preview.entries, previewEntry);
        }

        /**
         * @param {*} value
         * @return {!RuntimeAgent.ObjectPreview}
         */
        function generateValuePreview(value)
        {
            var remoteObject = new InjectedScript.RemoteObject(value, undefined, true, undefined, true, undefined, undefined, true);
            var valuePreview = remoteObject.preview || remoteObject._createEmptyPreview();
            return valuePreview;
        }
    },

    /**
     * @param {string} string
     * @param {number} maxLength
     * @param {boolean=} middle
     * @return {string}
     */
    _abbreviateString: function(string, maxLength, middle)
    {
        if (string.length <= maxLength)
            return string;
        if (middle) {
            var leftHalf = maxLength >> 1;
            var rightHalf = maxLength - leftHalf - 1;
            return string.substr(0, leftHalf) + "\u2026" + string.substr(string.length - rightHalf, rightHalf);
        }
        return string.substr(0, maxLength) + "\u2026";
    },

    __proto__: null
}

return injectedScript;
})