PageSourceSearch

https://sso.inet.vn/public/angularjs/node_modules/angular-sanitize/angular-sanitize.js

js inet.vn collected 2026-10-01 13:59:16 UTC 26,997 bytes, 739 lines download raw bytes

1/**
2 * @license AngularJS v1.5.11
3 * (c) 2010-2017 Google, Inc. http://angularjs.org
4 * License: MIT
5 */
6(function(window, angular) {'use strict';
7
8/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
9 *     Any commits to this file should be reviewed with security in mind.  *
10 *   Changes to this file can potentially create security vulnerabilities. *
11 *          An approval from 2 Core members with history of modifying      *
12 *                         this file is required.                          *
13 *                                                                         *
14 *  Does the change somehow allow for arbitrary javascript to be executed? *
15 *    Or allows for someone to change the prototype of built-in objects?   *
16 *     Or gives undesired access to variables likes document or window?    *
17 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
18
19var $sanitizeMinErr = angular.$$minErr('$sanitize');
20var bind;
21var extend;
22var forEach;
23var isDefined;
24var lowercase;
25var noop;
26var htmlParser;
27var htmlSanitizeWriter;
28
29/**
30 * @ngdoc module
31 * @name ngSanitize
32 * @description
33 *
34 * # ngSanitize
35 *
36 * The `ngSanitize` module provides functionality to sanitize HTML.
37 *
38 *
39 * <div doc-module-components="ngSanitize"></div>
40 *
41 * See {@link ngSanitize.$sanitize `$sanitize`} for usage.
42 */
43
44/**
45 * @ngdoc service
46 * @name $sanitize
47 * @kind function
48 *
49 * @description
50 *   Sanitizes an html string by stripping all potentially dangerous tokens.
51 *
52 *   The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are
53 *   then serialized back to properly escaped html string. This means that no unsafe input can make
54 *   it into the returned string.
55 *
56 *   The whitelist for URL sanitization of attribute values is configured using the functions
57 *   `aHrefSanitizationWhitelist` and `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider
58 *   `$compileProvider`}.
59 *
60 *   The input may also contain SVG markup if this is enabled via {@link $sanitizeProvider}.
61 *
62 * @param {string} html HTML input.
63 * @returns {string} Sanitized HTML.
64 *
65 * @example
66   <example module="sanitizeExample" deps="angular-sanitize.js" name="sanitize-service">
67   <file name="index.html">
68     <script>
69         angular.module('sanitizeExample', ['ngSanitize'])
70           .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) {
71             $scope.snippet =
72               '<p style="color:blue">an html\n' +
73               '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' +
74               'snippet</p>';
75             $scope.deliberatelyTrustDangerousSnippet = function() {
76               return $sce.trustAsHtml($scope.snippet);
77             };
78           }]);
79     </script>
80     <div ng-controller="ExampleController">
81        Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
82       <table>
83         <tr>
84           <td>Directive</td>
85           <td>How</td>
86           <td>Source</td>
87           <td>Rendered</td>
88         </tr>
89         <tr id="bind-html-with-sanitize">
90           <td>ng-bind-html</td>
91           <td>Automatically uses $sanitize</td>
92           <td><pre>&lt;div ng-bind-html="snippet"&gt;<br/>&lt;/div&gt;</pre></td>
93           <td><div ng-bind-html="snippet"></div></td>
94         </tr>
95         <tr id="bind-html-with-trust">
96           <td>ng-bind-html</td>
97           <td>Bypass $sanitize by explicitly trusting the dangerous value</td>
98           <td>
99           <pre>&lt;div ng-bind-html="deliberatelyTrustDangerousSnippet()"&gt;
100&lt;/div&gt;</pre>
101           </td>
102           <td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td>
103         </tr>
104         <tr id="bind-default">
105           <td>ng-bind</td>
106           <td>Automatically escapes</td>
107           <td><pre>&lt;div ng-bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td>
108           <td><div ng-bind="snippet"></div></td>
109         </tr>
110       </table>
111       </div>
112   </file>
113   <file name="protractor.js" type="protractor">
114     it('should sanitize the html snippet by default', function() {
115       expect(element(by.css('#bind-html-with-sanitize div')).getAttribute('innerHTML')).
116         toBe('<p>an html\n<em>click here</em>\nsnippet</p>');
117     });
118
119     it('should inline raw snippet if bound to a trusted value', function() {
120       expect(element(by.css('#bind-html-with-trust div')).getAttribute('innerHTML')).
121         toBe("<p style=\"color:blue\">an html\n" +
122              "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
123              "snippet</p>");
124     });
125
126     it('should escape snippet without any filter', function() {
127       expect(element(by.css('#bind-default div')).getAttribute('innerHTML')).
128         toBe("&lt;p style=\"color:blue\"&gt;an html\n" +
129              "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" +
130              "snippet&lt;/p&gt;");
131     });
132
133     it('should update', function() {
134       element(by.model('snippet')).clear();
135       element(by.model('snippet')).sendKeys('new <b onclick="alert(1)">text</b>');
136       expect(element(by.css('#bind-html-with-sanitize div')).getAttribute('innerHTML')).
137         toBe('new <b>text</b>');
138       expect(element(by.css('#bind-html-with-trust div')).getAttribute('innerHTML')).toBe(
139         'new <b onclick="alert(1)">text</b>');
140       expect(element(by.css('#bind-default div')).getAttribute('innerHTML')).toBe(
141         "new &lt;b onclick=\"alert(1)\"&gt;text&lt;/b&gt;");
142     });
143   </file>
144   </example>
145 */
146
147
148/**
149 * @ngdoc provider
150 * @name $sanitizeProvider
151 * @this
152 *
153 * @description
154 * Creates and configures {@link $sanitize} instance.
155 */
156function $SanitizeProvider() {
157  var svgEnabled = false;
158
159  this.$get = ['$$sanitizeUri', function($$sanitizeUri) {
160    if (svgEnabled) {
161      extend(validElements, svgElements);
162    }
163    return function(html) {
164      var buf = [];
165      htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) {
166        return !/^unsafe:/.test($$sanitizeUri(uri, isImage));
167      }));
168      return buf.join('');
169    };
170  }];
171
172
173  /**
174   * @ngdoc method
175   * @name $sanitizeProvider#enableSvg
176   * @kind function
177   *
178   * @description
179   * Enables a subset of svg to be supported by the sanitizer.
180   *
181   * <div class="alert alert-warning">
182   *   <p>By enabling this setting without taking other precautions, you might expose your
183   *   application to click-hijacking attacks. In these attacks, sanitized svg elements could be positioned
184   *   outside of the containing element and be rendered over other elements on the page (e.g. a login
185   *   link). Such behavior can then result in phishing incidents.</p>
186   *
187   *   <p>To protect against these, explicitly setup `overflow: hidden` css rule for all potential svg
188   *   tags within the sanitized content:</p>
189   *
190   *   <br>
191   *
192   *   <pre><code>
193   *   .rootOfTheIncludedContent svg {
194   *     overflow: hidden !important;
195   *   }
196   *   </code></pre>
197   * </div>
198   *
199   * @param {boolean=} flag Enable or disable SVG support in the sanitizer.
200   * @returns {boolean|ng.$sanitizeProvider} Returns the currently configured value if called
201   *    without an argument or self for chaining otherwise.
202   */
203  this.enableSvg = function(enableSvg) {
204    if (isDefined(enableSvg)) {
205      svgEnabled = enableSvg;
206      return this;
207    } else {
208      return svgEnabled;
209    }
210  };
211
212  //////////////////////////////////////////////////////////////////////////////////////////////////
213  // Private stuff
214  //////////////////////////////////////////////////////////////////////////////////////////////////
215
216  bind = angular.bind;
217  extend = angular.extend;
218  forEach = angular.forEach;
219  isDefined = angular.isDefined;
220  lowercase = angular.lowercase;
221  noop = angular.noop;
222
223  htmlParser = htmlParserImpl;
224  htmlSanitizeWriter = htmlSanitizeWriterImpl;
225
226  // Regular Expressions for parsing tags and attributes
227  var SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
228    // Match everything outside of normal chars and " (quote character)
229    NON_ALPHANUMERIC_REGEXP = /([^#-~ |!])/g;
230
231
232  // Good source of info about elements and attributes
233  // http://dev.w3.org/html5/spec/Overview.html#semantics
234  // http://simon.html5.org/html-elements
235
236  // Safe Void Elements - HTML5
237  // http://dev.w3.org/html5/spec/Overview.html#void-elements
238  var voidElements = toMap('area,br,col,hr,img,wbr');
239
240  // Elements that you can, intentionally, leave open (and which close themselves)
241  // http://dev.w3.org/html5/spec/Overview.html#optional-tags
242  var optionalEndTagBlockElements = toMap('colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr'),
243      optionalEndTagInlineElements = toMap('rp,rt'),
244      optionalEndTagElements = extend({},
245                                              optionalEndTagInlineElements,
246                                              optionalEndTagBlockElements);
247
248  // Safe Block Elements - HTML5
249  var blockElements = extend({}, optionalEndTagBlockElements, toMap('address,article,' +
250          'aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,' +
251          'h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,section,table,ul'));
252
253  // Inline Elements - HTML5
254  var inlineElements = extend({}, optionalEndTagInlineElements, toMap('a,abbr,acronym,b,' +
255          'bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,' +
256          'samp,small,span,strike,strong,sub,sup,time,tt,u,var'));
257
258  // SVG Elements
259  // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements
260  // Note: the elements animate,animateColor,animateMotion,animateTransform,set are intentionally omitted.
261  // They can potentially allow for arbitrary javascript to be executed. See #11290
262  var svgElements = toMap('circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,' +
263          'hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,' +
264          'radialGradient,rect,stop,svg,switch,text,title,tspan');
265
266  // Blocked Elements (will be stripped)
267  var blockedElements = toMap('script,style');
268
269  var validElements = extend({},
270                                     voidElements,
271                                     blockElements,
272                                     inlineElements,
273                                     optionalEndTagElements);
274
275  //Attributes that have href and hence need to be sanitized
276  var uriAttrs = toMap('background,cite,href,longdesc,src,xlink:href');
277
278  var htmlAttrs = toMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' +
279      'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' +
280      'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' +
281      'scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,' +
282      'valign,value,vspace,width');
283
284  // SVG attributes (without "id" and "name" attributes)
285  // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes
286  var svgAttrs = toMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' +
287      'baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,' +
288      'cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,' +
289      'font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,' +
290      'height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,keySplines,keyTimes,lang,' +
291      'marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mathematical,' +
292      'max,min,offset,opacity,orient,origin,overline-position,overline-thickness,panose-1,' +
293      'path,pathLength,points,preserveAspectRatio,r,refX,refY,repeatCount,repeatDur,' +
294      'requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,stemv,stop-color,' +
295      'stop-opacity,strikethrough-position,strikethrough-thickness,stroke,stroke-dasharray,' +
296      'stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,' +
297      'stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,underline-position,' +
298      'underline-thickness,unicode,unicode-range,units-per-em,values,version,viewBox,visibility,' +
299      'width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,xlink:show,xlink:title,' +
300      'xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,zoomAndPan', true);
301
302  var validAttrs = extend({},
303                                  uriAttrs,
304                                  svgAttrs,
305                                  htmlAttrs);
306
307  function toMap(str, lowercaseKeys) {
308    var obj = {}, items = str.split(','), i;
309    for (i = 0; i < items.length; i++) {
310      obj[lowercaseKeys ? lowercase(items[i]) : items[i]] = true;
311    }
312    return obj;
313  }
314
315  var inertBodyElement;
316  (function(window) {
317    var doc;
318    if (window.document && window.document.implementation) {
319      doc = window.document.implementation.createHTMLDocument('inert');
320    } else {
321      throw $sanitizeMinErr('noinert', 'Can\'t create an inert html document');
322    }
323    var docElement = doc.documentElement || doc.getDocumentElement();
324    var bodyElements = docElement.getElementsByTagName('body');
325
326    // usually there should be only one body element in the document, but IE doesn't have any, so we need to create one
327    if (bodyElements.length === 1) {
328      inertBodyElement = bodyElements[0];
329    } else {
330      var html = doc.createElement('html');
331      inertBodyElement = doc.createElement('body');
332      html.appendChild(inertBodyElement);
333      doc.appendChild(html);
334    }
335  })(window);
336
337  /**
338   * @example
339   * htmlParser(htmlString, {
340   *     start: function(tag, attrs) {},
341   *     end: function(tag) {},
342   *     chars: function(text) {},
343   *     comment: function(text) {}
344   * });
345   *
346   * @param {string} html string
347   * @param {object} handler
348   */
349  function htmlParserImpl(html, handler) {
350    if (html === null || html === undefined) {
351      html = '';
352    } else if (typeof html !== 'string') {
353      html = '' + html;
354    }
355    inertBodyElement.innerHTML = html;
356
357    //mXSS protection
358    var mXSSAttempts = 5;
359    do {
360      if (mXSSAttempts === 0) {
361        throw $sanitizeMinErr('uinput', 'Failed to sanitize html because the input is unstable');
362      }
363      mXSSAttempts--;
364
365      // strip custom-namespaced attributes on IE<=11
366      if (window.document.documentMode) {
367        stripCustomNsAttrs(inertBodyElement);
368      }
369      html = inertBodyElement.innerHTML; //trigger mXSS
370      inertBodyElement.innerHTML = html;
371    } while (html !== inertBodyElement.innerHTML);
372
373    var node = inertBodyElement.firstChild;
374    while (node) {
375      switch (node.nodeType) {
376        case 1: // ELEMENT_NODE
377          handler.start(node.nodeName.toLowerCase(), attrToMap(node.attributes));
378          break;
379        case 3: // TEXT NODE
380          handler.chars(node.textContent);
381          break;
382      }
383
384      var nextNode;
385      if (!(nextNode = node.firstChild)) {
386      if (node.nodeType === 1) {
387          handler.end(node.nodeName.toLowerCase());
388        }
389        nextNode = node.nextSibling;
390        if (!nextNode) {
391          while (nextNode == null) {
392            node = node.parentNode;
393            if (node === inertBodyElement) break;
394            nextNode = node.nextSibling;
395          if (node.nodeType === 1) {
396              handler.end(node.nodeName.toLowerCase());
397            }
398          }
399        }
400      }
401      node = nextNode;
402    }
403
404    while ((node = inertBodyElement.firstChild)) {
405      inertBodyElement.removeChild(node);
406    }
407  }
408
409  function attrToMap(attrs) {
410    var map = {};
411    for (var i = 0, ii = attrs.length; i < ii; i++) {
412      var attr = attrs[i];
413      map[attr.name] = attr.value;
414    }
415    return map;
416  }
417
418
419  /**
420   * Escapes all potentially dangerous characters, so that the
421   * resulting string can be safely inserted into attribute or
422   * element text.
423   * @param value
424   * @returns {string} escaped text
425   */
426  function encodeEntities(value) {
427    return value.
428      replace(/&/g, '&amp;').
429      replace(SURROGATE_PAIR_REGEXP, function(value) {
430        var hi = value.charCodeAt(0);
431        var low = value.charCodeAt(1);
432        return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
433      }).
434      replace(NON_ALPHANUMERIC_REGEXP, function(value) {
435        return '&#' + value.charCodeAt(0) + ';';
436      }).
437      replace(/</g, '&lt;').
438      replace(/>/g, '&gt;');
439  }
440
441  /**
442   * create an HTML/XML writer which writes to buffer
443   * @param {Array} buf use buf.join('') to get out sanitized html string
444   * @returns {object} in the form of {
445   *     start: function(tag, attrs) {},
446   *     end: function(tag) {},
447   *     chars: function(text) {},
448   *     comment: function(text) {}
449   * }
450   */
451  function htmlSanitizeWriterImpl(buf, uriValidator) {
452    var ignoreCurrentElement = false;
vendor: 3,676 bytes, lines 453-573
453    var out = bind(buf, buf.push);
454    return {
455      start: function(tag, attrs) {
456        tag = lowercase(tag);
457        if (!ignoreCurrentElement && blockedElements[tag]) {
458          ignoreCurrentElement = tag;
459        }
460        if (!ignoreCurrentElement && validElements[tag] === true) {
461          out('<');
462          out(tag);
463          forEach(attrs, function(value, key) {
464            var lkey = lowercase(key);
465            var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background');
466            if (validAttrs[lkey] === true &&
467              (uriAttrs[lkey] !== true || uriValidator(value, isImage))) {
468              out(' ');
469              out(key);
470              out('="');
471              out(encodeEntities(value));
472              out('"');
473            }
474          });
475          out('>');
476        }
477      },
478      end: function(tag) {
479        tag = lowercase(tag);
480        if (!ignoreCurrentElement && validElements[tag] === true && voidElements[tag] !== true) {
481          out('</');
482          out(tag);
483          out('>');
484        }
485        // eslint-disable-next-line eqeqeq
486        if (tag == ignoreCurrentElement) {
487          ignoreCurrentElement = false;
488        }
489      },
490      chars: function(chars) {
491        if (!ignoreCurrentElement) {
492          out(encodeEntities(chars));
493        }
494      }
495    };
496  }
497
498
499  /**
500   * When IE9-11 comes across an unknown namespaced attribute e.g. 'xlink:foo' it adds 'xmlns:ns1' attribute to declare
501   * ns1 namespace and prefixes the attribute with 'ns1' (e.g. 'ns1:xlink:foo'). This is undesirable since we don't want
502   * to allow any of these custom attributes. This method strips them all.
503   *
504   * @param node Root element to process
505   */
506  function stripCustomNsAttrs(node) {
507    while (node) {
508      if (node.nodeType === window.Node.ELEMENT_NODE) {
509        var attrs = node.attributes;
510        for (var i = 0, l = attrs.length; i < l; i++) {
511          var attrNode = attrs[i];
512          var attrName = attrNode.name.toLowerCase();
513          if (attrName === 'xmlns:ns1' || attrName.lastIndexOf('ns1:', 0) === 0) {
514            node.removeAttributeNode(attrNode);
515            i--;
516            l--;
517          }
518        }
519      }
520
521      var nextNode = node.firstChild;
522      if (nextNode) {
523        stripCustomNsAttrs(nextNode);
524      }
525
526      node = node.nextSibling;
527    }
528  }
529}
530
531function sanitizeText(chars) {
532  var buf = [];
533  var writer = htmlSanitizeWriter(buf, noop);
534  writer.chars(chars);
535  return buf.join('');
536}
537
538
539// define ngSanitize module and register $sanitize service
540angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider);
541
542/**
543 * @ngdoc filter
544 * @name linky
545 * @kind function
546 *
547 * @description
548 * Finds links in text input and turns them into html links. Supports `http/https/ftp/mailto` and
549 * plain email address links.
550 *
551 * Requires the {@link ngSanitize `ngSanitize`} module to be installed.
552 *
553 * @param {string} text Input text.
554 * @param {string} target Window (`_blank|_self|_parent|_top`) or named frame to open links in.
555 * @param {object|function(url)} [attributes] Add custom attributes to the link element.
556 *
557 *    Can be one of:
558 *
559 *    - `object`: A map of attributes
560 *    - `function`: Takes the url as a parameter and returns a map of attributes
561 *
562 *    If the map of attributes contains a value for `target`, it overrides the value of
563 *    the target parameter.
564 *
565 *
566 * @returns {string} Html-linkified and {@link $sanitize sanitized} text.
567 *
568 * @usage
569   <span ng-bind-html="linky_expression | linky"></span>
570 *
571 * @example
572   <example module="linkyExample" deps="angular-sanitize.js" name="linky-filter">
573     <file name="index.html">
574       <div ng-controller="ExampleController">
575       Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
576       <table>
577         <tr>
578           <th>Filter</th>
579           <th>Source</th>
580           <th>Rendered</th>
581         </tr>
582         <tr id="linky-filter">
583           <td>linky filter</td>
584           <td>
585             <pre>&lt;div ng-bind-html="snippet | linky"&gt;<br>&lt;/div&gt;</pre>
586           </td>
587           <td>
588             <div ng-bind-html="snippet | linky"></div>
589           </td>
590         </tr>
591         <tr id="linky-target">
592          <td>linky target</td>
593          <td>
594            <pre>&lt;div ng-bind-html="snippetWithSingleURL | linky:'_blank'"&gt;<br>&lt;/div&gt;</pre>
595          </td>
596          <td>
597            <div ng-bind-html="snippetWithSingleURL | linky:'_blank'"></div>
598          </td>
599         </tr>
600         <tr id="linky-custom-attributes">
601          <td>linky custom attributes</td>
602          <td>
603            <pre>&lt;div ng-bind-html="snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}"&gt;<br>&lt;/div&gt;</pre>
604          </td>
605          <td>
606            <div ng-bind-html="snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}"></div>
607          </td>
608         </tr>
609         <tr id="escaped-html">
610           <td>no filter</td>
611           <td><pre>&lt;div ng-bind="snippet"&gt;<br>&lt;/div&gt;</pre></td>
612           <td><div ng-bind="snippet"></div></td>
613         </tr>
614       </table>
615     </file>
616     <file name="script.js">
617       angular.module('linkyExample', ['ngSanitize'])
618         .controller('ExampleController', ['$scope', function($scope) {
619           $scope.snippet =
620             'Pretty text with some links:\n' +
621             'http://angularjs.org/,\n' +
622             'mailto:[email protected],\n' +
623             '[email protected],\n' +
624             'and one more: ftp://127.0.0.1/.';
625           $scope.snippetWithSingleURL = 'http://angularjs.org/';
626         }]);
627     </file>
628     <file name="protractor.js" type="protractor">
629       it('should linkify the snippet with urls', function() {
630         expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
631             toBe('Pretty text with some links: http://angularjs.org/, [email protected], ' +
632                  '[email protected], and one more: ftp://127.0.0.1/.');
633         expect(element.all(by.css('#linky-filter a')).count()).toEqual(4);
634       });
635
636       it('should not linkify snippet without the linky filter', function() {
637         expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()).
638             toBe('Pretty text with some links: http://angularjs.org/, mailto:[email protected], ' +
639                  '[email protected], and one more: ftp://127.0.0.1/.');
640         expect(element.all(by.css('#escaped-html a')).count()).toEqual(0);
641       });
642
643       it('should update', function() {
644         element(by.model('snippet')).clear();
645         element(by.model('snippet')).sendKeys('new http://link.');
646         expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
647             toBe('new http://link.');
648         expect(element.all(by.css('#linky-filter a')).count()).toEqual(1);
649         expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText())
650             .toBe('new http://link.');
651       });
652
653       it('should work with the target property', function() {
654        expect(element(by.id('linky-target')).
655            element(by.binding("snippetWithSingleURL | linky:'_blank'")).getText()).
656            toBe('http://angularjs.org/');
657        expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank');
658       });
659
660       it('should optionally add custom attributes', function() {
661        expect(element(by.id('linky-custom-attributes')).
662            element(by.binding("snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}")).getText()).
663            toBe('http://angularjs.org/');
664        expect(element(by.css('#linky-custom-attributes a')).getAttribute('rel')).toEqual('nofollow');
665       });
666     </file>
667   </example>
668 */
669angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) {
670  var LINKY_URL_REGEXP =
671        /((
vendor: 2,023 bytes, lines 671-739
671ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/i,
672      MAILTO_REGEXP = /^mailto:/i;
673
674  var linkyMinErr = angular.$$minErr('linky');
675  var isDefined = angular.isDefined;
676  var isFunction = angular.isFunction;
677  var isObject = angular.isObject;
678  var isString = angular.isString;
679
680  return function(text, target, attributes) {
681    if (text == null || text === '') return text;
682    if (!isString(text)) throw linkyMinErr('notstring', 'Expected string but received: {0}', text);
683
684    var attributesFn =
685      isFunction(attributes) ? attributes :
686      isObject(attributes) ? function getAttributesObject() {return attributes;} :
687      function getEmptyAttributesObject() {return {};};
688
689    var match;
690    var raw = text;
691    var html = [];
692    var url;
693    var i;
694    while ((match = raw.match(LINKY_URL_REGEXP))) {
695      // We can not end in these as they are sometimes found at the end of the sentence
696      url = match[0];
697      // if we did not match ftp/http/www/mailto then assume mailto
698      if (!match[2] && !match[4]) {
699        url = (match[3] ? 'http://' : 'mailto:') + url;
700      }
701      i = match.index;
702      addText(raw.substr(0, i));
703      addLink(url, match[0].replace(MAILTO_REGEXP, ''));
704      raw = raw.substring(i + match[0].length);
705    }
706    addText(raw);
707    return $sanitize(html.join(''));
708
709    function addText(text) {
710      if (!text) {
711        return;
712      }
713      html.push(sanitizeText(text));
714    }
715
716    function addLink(url, text) {
717      var key, linkAttributes = attributesFn(url);
718      html.push('<a ');
719
720      for (key in linkAttributes) {
721        html.push(key + '="' + linkAttributes[key] + '" ');
722      }
723
724      if (isDefined(target) && !('target' in linkAttributes)) {
725        html.push('target="',
726                  target,
727                  '" ');
728      }
729      html.push('href="',
730                url.replace(/"/g, '&quot;'),
731                '">');
732      addText(text);
733      html.push('</a>');
734    }
735  };
736}]);
737
738
739})(window, window.angular);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.