Debian Codegraph @

closure-library/closure/goog/debug/debug.js

raw
1 // Copyright 2006 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview Logging and debugging utilities.
17 *
18 * @see ../demos/debug.html
19 */
20
21 goog.provide('goog.debug');
22
23 goog.require('goog.array');
24 goog.require('goog.debug.errorcontext');
25 goog.require('goog.userAgent');
26
27
28 /** @define {boolean} Whether logging should be enabled. */
29 goog.define('goog.debug.LOGGING_ENABLED', goog.DEBUG);
30
31
32 /** @define {boolean} Whether to force "sloppy" stack building. */
33 goog.define('goog.debug.FORCE_SLOPPY_STACKS', false);
34
35
36 /**
37 * Catches onerror events fired by windows and similar objects.
38 * @param {function(Object)} logFunc The function to call with the error
39 * information.
40 * @param {boolean=} opt_cancel Whether to stop the error from reaching the
41 * browser.
42 * @param {Object=} opt_target Object that fires onerror events.
43 */
44 goog.debug.catchErrors = function(logFunc, opt_cancel, opt_target) {
45 var target = opt_target || goog.global;
46 var oldErrorHandler = target.onerror;
47 var retVal = !!opt_cancel;
48
49 // Chrome interprets onerror return value backwards (http://crbug.com/92062)
50 // until it was fixed in webkit revision r94061 (Webkit 535.3). This
51 // workaround still needs to be skipped in Safari after the webkit change
52 // gets pushed out in Safari.
53 // See https://bugs.webkit.org/show_bug.cgi?id=67119
54 if (goog.userAgent.WEBKIT && !goog.userAgent.isVersionOrHigher('535.3')) {
55 retVal = !retVal;
56 }
57
58 /**
59 * New onerror handler for this target. This onerror handler follows the spec
60 * according to
61 * http://www.whatwg.org/specs/web-apps/current-work/#runtime-script-errors
62 * The spec was changed in August 2013 to support receiving column information
63 * and an error object for all scripts on the same origin or cross origin
64 * scripts with the proper headers. See
65 * https://mikewest.org/2013/08/debugging-runtime-errors-with-window-onerror
66 *
67 * @param {string} message The error message. For cross-origin errors, this
68 * will be scrubbed to just "Script error.". For new browsers that have
69 * updated to follow the latest spec, errors that come from origins that
70 * have proper cross origin headers will not be scrubbed.
71 * @param {string} url The URL of the script that caused the error. The URL
72 * will be scrubbed to "" for cross origin scripts unless the script has
73 * proper cross origin headers and the browser has updated to the latest
74 * spec.
75 * @param {number} line The line number in the script that the error
76 * occurred on.
77 * @param {number=} opt_col The optional column number that the error
78 * occurred on. Only browsers that have updated to the latest spec will
79 * include this.
80 * @param {Error=} opt_error The optional actual error object for this
81 * error that should include the stack. Only browsers that have updated
82 * to the latest spec will inlude this parameter.
83 * @return {boolean} Whether to prevent the error from reaching the browser.
84 */
85 target.onerror = function(message, url, line, opt_col, opt_error) {
86 if (oldErrorHandler) {
87 oldErrorHandler(message, url, line, opt_col, opt_error);
88 }
89 logFunc({
90 message: message,
91 fileName: url,
92 line: line,
93 lineNumber: line,
94 col: opt_col,
95 error: opt_error
96 });
97 return retVal;
98 };
99 };
100
101
102 /**
103 * Creates a string representing an object and all its properties.
104 * @param {Object|null|undefined} obj Object to expose.
105 * @param {boolean=} opt_showFn Show the functions as well as the properties,
106 * default is false.
107 * @return {string} The string representation of {@code obj}.
108 */
109 goog.debug.expose = function(obj, opt_showFn) {
110 if (typeof obj == 'undefined') {
111 return 'undefined';
112 }
113 if (obj == null) {
114 return 'NULL';
115 }
116 var str = [];
117
118 for (var x in obj) {
119 if (!opt_showFn && goog.isFunction(obj[x])) {
120 continue;
121 }
122 var s = x + ' = ';
123
124 try {
125 s += obj[x];
126 } catch (e) {
127 s += '*** ' + e + ' ***';
128 }
129 str.push(s);
130 }
131 return str.join('\n');
132 };
133
134
135 /**
136 * Creates a string representing a given primitive or object, and for an
137 * object, all its properties and nested objects. NOTE: The output will include
138 * Uids on all objects that were exposed. Any added Uids will be removed before
139 * returning.
140 * @param {*} obj Object to expose.
141 * @param {boolean=} opt_showFn Also show properties that are functions (by
142 * default, functions are omitted).
143 * @return {string} A string representation of {@code obj}.
144 */
145 goog.debug.deepExpose = function(obj, opt_showFn) {
146 var str = [];
147
148 // Track any objects where deepExpose added a Uid, so they can be cleaned up
149 // before return. We do this globally, rather than only on ancestors so that
150 // if the same object appears in the output, you can see it.
151 var uidsToCleanup = [];
152 var ancestorUids = {};
153
154 var helper = function(obj, space) {
155 var nestspace = space + ' ';
156
157 var indentMultiline = function(str) {
158 return str.replace(/\n/g, '\n' + space);
159 };
160
161
162 try {
163 if (!goog.isDef(obj)) {
164 str.push('undefined');
165 } else if (goog.isNull(obj)) {
166 str.push('NULL');
167 } else if (goog.isString(obj)) {
168 str.push('"' + indentMultiline(obj) + '"');
169 } else if (goog.isFunction(obj)) {
170 str.push(indentMultiline(String(obj)));
171 } else if (goog.isObject(obj)) {
172 // Add a Uid if needed. The struct calls implicitly adds them.
173 if (!goog.hasUid(obj)) {
174 uidsToCleanup.push(obj);
175 }
176 var uid = goog.getUid(obj);
177 if (ancestorUids[uid]) {
178 str.push('*** reference loop detected (id=' + uid + ') ***');
179 } else {
180 ancestorUids[uid] = true;
181 str.push('{');
182 for (var x in obj) {
183 if (!opt_showFn && goog.isFunction(obj[x])) {
184 continue;
185 }
186 str.push('\n');
187 str.push(nestspace);
188 str.push(x + ' = ');
189 helper(obj[x], nestspace);
190 }
191 str.push('\n' + space + '}');
192 delete ancestorUids[uid];
193 }
194 } else {
195 str.push(obj);
196 }
197 } catch (e) {
198 str.push('*** ' + e + ' ***');
199 }
200 };
201
202 helper(obj, '');
203
204 // Cleanup any Uids that were added by the deepExpose.
205 for (var i = 0; i < uidsToCleanup.length; i++) {
206 goog.removeUid(uidsToCleanup[i]);
207 }
208
209 return str.join('');
210 };
211
212
213 /**
214 * Recursively outputs a nested array as a string.
215 * @param {Array<?>} arr The array.
216 * @return {string} String representing nested array.
217 */
218 goog.debug.exposeArray = function(arr) {
219 var str = [];
220 for (var i = 0; i < arr.length; i++) {
221 if (goog.isArray(arr[i])) {
222 str.push(goog.debug.exposeArray(arr[i]));
223 } else {
224 str.push(arr[i]);
225 }
226 }
227 return '[ ' + str.join(', ') + ' ]';
228 };
229
230
231 /**
232 * Normalizes the error/exception object between browsers.
233 * @param {*} err Raw error object.
234 * @return {!{
235 * message: (?|undefined),
236 * name: (?|undefined),
237 * lineNumber: (?|undefined),
238 * fileName: (?|undefined),
239 * stack: (?|undefined)
240 * }} Normalized error object.
241 */
242 goog.debug.normalizeErrorObject = function(err) {
243 var href = goog.getObjectByName('window.location.href');
244 if (goog.isString(err)) {
245 return {
246 'message': err,
247 'name': 'Unknown error',
248 'lineNumber': 'Not available',
249 'fileName': href,
250 'stack': 'Not available'
251 };
252 }
253
254 var lineNumber, fileName;
255 var threwError = false;
256
257 try {
258 lineNumber = err.lineNumber || err.line || 'Not available';
259 } catch (e) {
260 // Firefox 2 sometimes throws an error when accessing 'lineNumber':
261 // Message: Permission denied to get property UnnamedClass.lineNumber
262 lineNumber = 'Not available';
263 threwError = true;
264 }
265
266 try {
267 fileName = err.fileName || err.filename || err.sourceURL ||
268 // $googDebugFname may be set before a call to eval to set the filename
269 // that the eval is supposed to present.
270 goog.global['$googDebugFname'] || href;
271 } catch (e) {
272 // Firefox 2 may also throw an error when accessing 'filename'.
273 fileName = 'Not available';
274 threwError = true;
275 }
276
277 // The IE Error object contains only the name and the message.
278 // The Safari Error object uses the line and sourceURL fields.
279 if (threwError || !err.lineNumber || !err.fileName || !err.stack ||
280 !err.message || !err.name) {
281 return {
282 'message': err.message || 'Not available',
283 'name': err.name || 'UnknownError',
284 'lineNumber': lineNumber,
285 'fileName': fileName,
286 'stack': err.stack || 'Not available'
287 };
288 }
289
290 // Standards error object
291 // Typed !Object. Should be a subtype of the return type, but it's not.
292 return /** @type {?} */ (err);
293 };
294
295
296 /**
297 * Converts an object to an Error using the object's toString if it's not
298 * already an Error, adds a stacktrace if there isn't one, and optionally adds
299 * an extra message.
300 * @param {*} err The original thrown error, object, or string.
301 * @param {string=} opt_message optional additional message to add to the
302 * error.
303 * @return {!Error} If err is an Error, it is enhanced and returned. Otherwise,
304 * it is converted to an Error which is enhanced and returned.
305 */
306 goog.debug.enhanceError = function(err, opt_message) {
307 var error;
308 if (!(err instanceof Error)) {
309 error = Error(err);
310 if (Error.captureStackTrace) {
311 // Trim this function off the call stack, if we can.
312 Error.captureStackTrace(error, goog.debug.enhanceError);
313 }
314 } else {
315 error = err;
316 }
317
318 if (!error.stack) {
319 error.stack = goog.debug.getStacktrace(goog.debug.enhanceError);
320 }
321 if (opt_message) {
322 // find the first unoccupied 'messageX' property
323 var x = 0;
324 while (error['message' + x]) {
325 ++x;
326 }
327 error['message' + x] = String(opt_message);
328 }
329 return error;
330 };
331
332
333 /**
334 * Converts an object to an Error using the object's toString if it's not
335 * already an Error, adds a stacktrace if there isn't one, and optionally adds
336 * context to the Error, which is reported by the closure error reporter.
337 * @param {*} err The original thrown error, object, or string.
338 * @param {!Object<string, string>=} opt_context Key-value context to add to the
339 * Error.
340 * @return {!Error} If err is an Error, it is enhanced and returned. Otherwise,
341 * it is converted to an Error which is enhanced and returned.
342 */
343 goog.debug.enhanceErrorWithContext = function(err, opt_context) {
344 var error = goog.debug.enhanceError(err);
345 if (opt_context) {
346 for (var key in opt_context) {
347 goog.debug.errorcontext.addErrorContext(error, key, opt_context[key]);
348 }
349 }
350 return error;
351 };
352
353
354 /**
355 * Gets the current stack trace. Simple and iterative - doesn't worry about
356 * catching circular references or getting the args.
357 * @param {number=} opt_depth Optional maximum depth to trace back to.
358 * @return {string} A string with the function names of all functions in the
359 * stack, separated by \n.
360 * @suppress {es5Strict}
361 */
362 goog.debug.getStacktraceSimple = function(opt_depth) {
363 if (!goog.debug.FORCE_SLOPPY_STACKS) {
364 var stack = goog.debug.getNativeStackTrace_(goog.debug.getStacktraceSimple);
365 if (stack) {
366 return stack;
367 }
368 // NOTE: browsers that have strict mode support also have native "stack"
369 // properties. Fall-through for legacy browser support.
370 }
371
372 var sb = [];
373 var fn = arguments.callee.caller;
374 var depth = 0;
375
376 while (fn && (!opt_depth || depth < opt_depth)) {
377 sb.push(goog.debug.getFunctionName(fn));
378 sb.push('()\n');
379
380 try {
381 fn = fn.caller;
382 } catch (e) {
383 sb.push('[exception trying to get caller]\n');
384 break;
385 }
386 depth++;
387 if (depth >= goog.debug.MAX_STACK_DEPTH) {
388 sb.push('[...long stack...]');
389 break;
390 }
391 }
392 if (opt_depth && depth >= opt_depth) {
393 sb.push('[...reached max depth limit...]');
394 } else {
395 sb.push('[end]');
396 }
397
398 return sb.join('');
399 };
400
401
402 /**
403 * Max length of stack to try and output
404 * @type {number}
405 */
406 goog.debug.MAX_STACK_DEPTH = 50;
407
408
409 /**
410 * @param {Function} fn The function to start getting the trace from.
411 * @return {?string}
412 * @private
413 */
414 goog.debug.getNativeStackTrace_ = function(fn) {
415 var tempErr = new Error();
416 if (Error.captureStackTrace) {
417 Error.captureStackTrace(tempErr, fn);
418 return String(tempErr.stack);
419 } else {
420 // IE10, only adds stack traces when an exception is thrown.
421 try {
422 throw tempErr;
423 } catch (e) {
424 tempErr = e;
425 }
426 var stack = tempErr.stack;
427 if (stack) {
428 return String(stack);
429 }
430 }
431 return null;
432 };
433
434
435 /**
436 * Gets the current stack trace, either starting from the caller or starting
437 * from a specified function that's currently on the call stack.
438 * @param {?Function=} fn If provided, when collecting the stack trace all
439 * frames above the topmost call to this function, including that call,
440 * will be left out of the stack trace.
441 * @return {string} Stack trace.
442 * @suppress {es5Strict}
443 */
444 goog.debug.getStacktrace = function(fn) {
445 var stack;
446 if (!goog.debug.FORCE_SLOPPY_STACKS) {
447 // Try to get the stack trace from the environment if it is available.
448 var contextFn = fn || goog.debug.getStacktrace;
449 stack = goog.debug.getNativeStackTrace_(contextFn);
450 }
451 if (!stack) {
452 // NOTE: browsers that have strict mode support also have native "stack"
453 // properties. This function will throw in strict mode.
454 stack = goog.debug.getStacktraceHelper_(fn || arguments.callee.caller, []);
455 }
456 return stack;
457 };
458
459
460 /**
461 * Private helper for getStacktrace().
462 * @param {?Function} fn If provided, when collecting the stack trace all
463 * frames above the topmost call to this function, including that call,
464 * will be left out of the stack trace.
465 * @param {Array<!Function>} visited List of functions visited so far.
466 * @return {string} Stack trace starting from function fn.
467 * @suppress {es5Strict}
468 * @private
469 */
470 goog.debug.getStacktraceHelper_ = function(fn, visited) {
471 var sb = [];
472
473 // Circular reference, certain functions like bind seem to cause a recursive
474 // loop so we need to catch circular references
475 if (goog.array.contains(visited, fn)) {
476 sb.push('[...circular reference...]');
477
478 // Traverse the call stack until function not found or max depth is reached
479 } else if (fn && visited.length < goog.debug.MAX_STACK_DEPTH) {
480 sb.push(goog.debug.getFunctionName(fn) + '(');
481 var args = fn.arguments;
482 // Args may be null for some special functions such as host objects or eval.
483 for (var i = 0; args && i < args.length; i++) {
484 if (i > 0) {
485 sb.push(', ');
486 }
487 var argDesc;
488 var arg = args[i];
489 switch (typeof arg) {
490 case 'object':
491 argDesc = arg ? 'object' : 'null';
492 break;
493
494 case 'string':
495 argDesc = arg;
496 break;
497
498 case 'number':
499 argDesc = String(arg);
500 break;
501
502 case 'boolean':
503 argDesc = arg ? 'true' : 'false';
504 break;
505
506 case 'function':
507 argDesc = goog.debug.getFunctionName(arg);
508 argDesc = argDesc ? argDesc : '[fn]';
509 break;
510
511 case 'undefined':
512 default:
513 argDesc = typeof arg;
514 break;
515 }
516
517 if (argDesc.length > 40) {
518 argDesc = argDesc.substr(0, 40) + '...';
519 }
520 sb.push(argDesc);
521 }
522 visited.push(fn);
523 sb.push(')\n');
524
525 try {
526 sb.push(goog.debug.getStacktraceHelper_(fn.caller, visited));
527 } catch (e) {
528 sb.push('[exception trying to get caller]\n');
529 }
530
531 } else if (fn) {
532 sb.push('[...long stack...]');
533 } else {
534 sb.push('[end]');
535 }
536 return sb.join('');
537 };
538
539
540 /**
541 * Set a custom function name resolver.
542 * @param {function(Function): string} resolver Resolves functions to their
543 * names.
544 */
545 goog.debug.setFunctionResolver = function(resolver) {
546 goog.debug.fnNameResolver_ = resolver;
547 };
548
549
550 /**
551 * Gets a function name
552 * @param {Function} fn Function to get name of.
553 * @return {string} Function's name.
554 */
555 goog.debug.getFunctionName = function(fn) {
556 if (goog.debug.fnNameCache_[fn]) {
557 return goog.debug.fnNameCache_[fn];
558 }
559 if (goog.debug.fnNameResolver_) {
560 var name = goog.debug.fnNameResolver_(fn);
561 if (name) {
562 goog.debug.fnNameCache_[fn] = name;
563 return name;
564 }
565 }
566
567 // Heuristically determine function name based on code.
568 var functionSource = String(fn);
569 if (!goog.debug.fnNameCache_[functionSource]) {
570 var matches = /function ([^\(]+)/.exec(functionSource);
571 if (matches) {
572 var method = matches[1];
573 goog.debug.fnNameCache_[functionSource] = method;
574 } else {
575 goog.debug.fnNameCache_[functionSource] = '[Anonymous]';
576 }
577 }
578
579 return goog.debug.fnNameCache_[functionSource];
580 };
581
582
583 /**
584 * Makes whitespace visible by replacing it with printable characters.
585 * This is useful in finding diffrences between the expected and the actual
586 * output strings of a testcase.
587 * @param {string} string whose whitespace needs to be made visible.
588 * @return {string} string whose whitespace is made visible.
589 */
590 goog.debug.makeWhitespaceVisible = function(string) {
591 return string.replace(/ /g, '[_]')
592 .replace(/\f/g, '[f]')
593 .replace(/\n/g, '[n]\n')
594 .replace(/\r/g, '[r]')
595 .replace(/\t/g, '[t]');
596 };
597
598
599 /**
600 * Returns the type of a value. If a constructor is passed, and a suitable
601 * string cannot be found, 'unknown type name' will be returned.
602 *
603 * <p>Forked rather than moved from {@link goog.asserts.getType_}
604 * to avoid adding a dependency to goog.asserts.
605 * @param {*} value A constructor, object, or primitive.
606 * @return {string} The best display name for the value, or 'unknown type name'.
607 */
608 goog.debug.runtimeType = function(value) {
609 if (value instanceof Function) {
610 return value.displayName || value.name || 'unknown type name';
611 } else if (value instanceof Object) {
612 return value.constructor.displayName || value.constructor.name ||
613 Object.prototype.toString.call(value);
614 } else {
615 return value === null ? 'null' : typeof value;
616 }
617 };
618
619
620 /**
621 * Hash map for storing function names that have already been looked up.
622 * @type {Object}
623 * @private
624 */
625 goog.debug.fnNameCache_ = {};
626
627
628 /**
629 * Resolves functions to their names. Resolved function names will be cached.
630 * @type {function(Function):string}
631 * @private
632 */
633 goog.debug.fnNameResolver_;
634
635
636 /**
637 * Private internal function to support goog.debug.freeze.
638 * @param {T} arg
639 * @return {T}
640 * @template T
641 * @private
642 */
643 goog.debug.freezeInternal_ = goog.DEBUG && Object.freeze || function(arg) {
644 return arg;
645 };
646
647
648 /**
649 * Freezes the given object, but only in debug mode (and in browsers that
650 * support it). Note that this is a shallow freeze, so for deeply nested
651 * objects it must be called at every level to ensure deep immutability.
652 * @param {T} arg
653 * @return {T}
654 * @template T
655 */
656 goog.debug.freeze = function(arg) {
657 // NOTE: this compiles to nothing, but hides the possible side effect of
658 // freezeInternal_ from the compiler so that the entire call can be
659 // removed if the result is not used.
660 return {
661 valueOf: function() {
662 return goog.debug.freezeInternal_(arg);
663 }
664 }.valueOf();
665 };