soyutils.js 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767
  1. /*
  2. * Copyright 2008 Google Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /**
  17. * @fileoverview
  18. * Utility functions and classes for Soy.
  19. *
  20. * <p>
  21. * The top portion of this file contains utilities for Soy users:<ul>
  22. * <li> soy.StringBuilder: Compatible with the 'stringbuilder' code style.
  23. * <li> soy.renderElement: Render template and set as innerHTML of an element.
  24. * <li> soy.renderAsFragment: Render template and return as HTML fragment.
  25. * </ul>
  26. *
  27. * <p>
  28. * The bottom portion of this file contains utilities that should only be called
  29. * by Soy-generated JS code. Please do not use these functions directly from
  30. * your hand-writen code. Their names all start with '$$'.
  31. *
  32. * @author Garrett Boyer
  33. * @author Mike Samuel
  34. * @author Kai Huang
  35. * @author Aharon Lanin
  36. */
  37. // COPIED FROM nogoog_shim.js
  38. // Create closure namespaces.
  39. var goog = goog || {};
  40. goog.DEBUG = false;
  41. goog.inherits = function(childCtor, parentCtor) {
  42. /** @constructor */
  43. function tempCtor() {}
  44. tempCtor.prototype = parentCtor.prototype;
  45. childCtor.superClass_ = parentCtor.prototype;
  46. childCtor.prototype = new tempCtor();
  47. childCtor.prototype.constructor = childCtor;
  48. };
  49. // Just enough browser detection for this file.
  50. if (!goog.userAgent) {
  51. goog.userAgent = (function() {
  52. var userAgent = "";
  53. if ("undefined" !== typeof navigator && navigator
  54. && "string" == typeof navigator.userAgent) {
  55. userAgent = navigator.userAgent;
  56. }
  57. var isOpera = userAgent.indexOf('Opera') == 0;
  58. return {
  59. jscript: {
  60. /**
  61. * @type {boolean}
  62. */
  63. HAS_JSCRIPT: 'ScriptEngine' in this
  64. },
  65. /**
  66. * @type {boolean}
  67. */
  68. OPERA: isOpera,
  69. /**
  70. * @type {boolean}
  71. */
  72. IE: !isOpera && userAgent.indexOf('MSIE') != -1,
  73. /**
  74. * @type {boolean}
  75. */
  76. WEBKIT: !isOpera && userAgent.indexOf('WebKit') != -1
  77. };
  78. })();
  79. }
  80. if (!goog.asserts) {
  81. goog.asserts = {
  82. /**
  83. * @param {*} condition Condition to check.
  84. */
  85. assert: function (condition) {
  86. if (!condition) {
  87. throw Error('Assertion error');
  88. }
  89. },
  90. /**
  91. * @param {...*} var_args
  92. */
  93. fail: function (var_args) {}
  94. };
  95. }
  96. // Stub out the document wrapper used by renderAs*.
  97. if (!goog.dom) {
  98. goog.dom = {};
  99. /**
  100. * @param {Document=} d
  101. * @constructor
  102. */
  103. goog.dom.DomHelper = function(d) {
  104. this.document_ = d || document;
  105. };
  106. /**
  107. * @return {!Document}
  108. */
  109. goog.dom.DomHelper.prototype.getDocument = function() {
  110. return this.document_;
  111. };
  112. /**
  113. * Creates a new element.
  114. * @param {string} name Tag name.
  115. * @return {!Element}
  116. */
  117. goog.dom.DomHelper.prototype.createElement = function(name) {
  118. return this.document_.createElement(name);
  119. };
  120. /**
  121. * Creates a new document fragment.
  122. * @return {!DocumentFragment}
  123. */
  124. goog.dom.DomHelper.prototype.createDocumentFragment = function() {
  125. return this.document_.createDocumentFragment();
  126. };
  127. }
  128. if (!goog.format) {
  129. goog.format = {
  130. insertWordBreaks: function(str, maxCharsBetweenWordBreaks) {
  131. str = String(str);
  132. var resultArr = [];
  133. var resultArrLen = 0;
  134. // These variables keep track of important state inside str.
  135. var isInTag = false; // whether we're inside an HTML tag
  136. var isMaybeInEntity = false; // whether we might be inside an HTML entity
  137. var numCharsWithoutBreak = 0; // number of chars since last word break
  138. var flushIndex = 0; // index of first char not yet flushed to resultArr
  139. for (var i = 0, n = str.length; i < n; ++i) {
  140. var charCode = str.charCodeAt(i);
  141. // If hit maxCharsBetweenWordBreaks, and not space next, then add <wbr>.
  142. if (numCharsWithoutBreak >= maxCharsBetweenWordBreaks &&
  143. // space
  144. charCode != 32) {
  145. resultArr[resultArrLen++] = str.substring(flushIndex, i);
  146. flushIndex = i;
  147. resultArr[resultArrLen++] = goog.format.WORD_BREAK;
  148. numCharsWithoutBreak = 0;
  149. }
  150. if (isInTag) {
  151. // If inside an HTML tag and we see '>', it's the end of the tag.
  152. if (charCode == 62) {
  153. isInTag = false;
  154. }
  155. } else if (isMaybeInEntity) {
  156. switch (charCode) {
  157. // Inside an entity, a ';' is the end of the entity.
  158. // The entity that just ended counts as one char, so increment
  159. // numCharsWithoutBreak.
  160. case 59: // ';'
  161. isMaybeInEntity = false;
  162. ++numCharsWithoutBreak;
  163. break;
  164. // If maybe inside an entity and we see '<', we weren't actually in
  165. // an entity. But now we're inside and HTML tag.
  166. case 60: // '<'
  167. isMaybeInEntity = false;
  168. isInTag = true;
  169. break;
  170. // If maybe inside an entity and we see ' ', we weren't actually in
  171. // an entity. Just correct the state and reset the
  172. // numCharsWithoutBreak since we just saw a space.
  173. case 32: // ' '
  174. isMaybeInEntity = false;
  175. numCharsWithoutBreak = 0;
  176. break;
  177. }
  178. } else { // !isInTag && !isInEntity
  179. switch (charCode) {
  180. // When not within a tag or an entity and we see '<', we're now
  181. // inside an HTML tag.
  182. case 60: // '<'
  183. isInTag = true;
  184. break;
  185. // When not within a tag or an entity and we see '&', we might be
  186. // inside an entity.
  187. case 38: // '&'
  188. isMaybeInEntity = true;
  189. break;
  190. // When we see a space, reset the numCharsWithoutBreak count.
  191. case 32: // ' '
  192. numCharsWithoutBreak = 0;
  193. break;
  194. // When we see a non-space, increment the numCharsWithoutBreak.
  195. default:
  196. ++numCharsWithoutBreak;
  197. break;
  198. }
  199. }
  200. }
  201. // Flush the remaining chars at the end of the string.
  202. resultArr[resultArrLen++] = str.substring(flushIndex);
  203. return resultArr.join('');
  204. },
  205. /**
  206. * String inserted as a word break by insertWordBreaks(). Safari requires
  207. * <wbr></wbr>, Opera needs the 'shy' entity, though this will give a
  208. * visible hyphen at breaks. Other browsers just use <wbr>.
  209. * @type {string}
  210. * @private
  211. */
  212. WORD_BREAK: goog.userAgent.WEBKIT
  213. ? '<wbr></wbr>' : goog.userAgent.OPERA ? '&shy;' : '<wbr>'
  214. };
  215. }
  216. if (!goog.i18n) {
  217. goog.i18n = {
  218. bidi: {
  219. /**
  220. * Check the directionality of a piece of text, return true if the piece
  221. * of text should be laid out in RTL direction.
  222. * @param {string} text The piece of text that need to be detected.
  223. * @param {boolean=} opt_isHtml Whether {@code text} is HTML/HTML-escaped.
  224. * Default: false.
  225. * @return {boolean}
  226. * @private
  227. */
  228. detectRtlDirectionality: function(text, opt_isHtml) {
  229. text = soyshim.$$bidiStripHtmlIfNecessary_(text, opt_isHtml);
  230. return soyshim.$$bidiRtlWordRatio_(text)
  231. > soyshim.$$bidiRtlDetectionThreshold_;
  232. }
  233. }
  234. };
  235. }
  236. /**
  237. * Directionality enum.
  238. * @enum {number}
  239. */
  240. goog.i18n.bidi.Dir = {
  241. RTL: -1,
  242. UNKNOWN: 0,
  243. LTR: 1
  244. };
  245. /**
  246. * Convert a directionality given in various formats to a goog.i18n.bidi.Dir
  247. * constant. Useful for interaction with different standards of directionality
  248. * representation.
  249. *
  250. * @param {goog.i18n.bidi.Dir|number|boolean} givenDir Directionality given in
  251. * one of the following formats:
  252. * 1. A goog.i18n.bidi.Dir constant.
  253. * 2. A number (positive = LRT, negative = RTL, 0 = unknown).
  254. * 3. A boolean (true = RTL, false = LTR).
  255. * @return {goog.i18n.bidi.Dir} A goog.i18n.bidi.Dir constant matching the given
  256. * directionality.
  257. */
  258. goog.i18n.bidi.toDir = function(givenDir) {
  259. if (typeof givenDir == 'number') {
  260. return givenDir > 0 ? goog.i18n.bidi.Dir.LTR :
  261. givenDir < 0 ? goog.i18n.bidi.Dir.RTL : goog.i18n.bidi.Dir.UNKNOWN;
  262. } else {
  263. return givenDir ? goog.i18n.bidi.Dir.RTL : goog.i18n.bidi.Dir.LTR;
  264. }
  265. };
  266. /**
  267. * Utility class for formatting text for display in a potentially
  268. * opposite-directionality context without garbling. Provides the following
  269. * functionality:
  270. *
  271. * @param {goog.i18n.bidi.Dir|number|boolean} dir The context
  272. * directionality as a number
  273. * (positive = LRT, negative = RTL, 0 = unknown).
  274. * @constructor
  275. */
  276. goog.i18n.BidiFormatter = function(dir) {
  277. this.dir_ = goog.i18n.bidi.toDir(dir);
  278. };
  279. /**
  280. * Returns 'dir="ltr"' or 'dir="rtl"', depending on {@code text}'s estimated
  281. * directionality, if it is not the same as the context directionality.
  282. * Otherwise, returns the empty string.
  283. *
  284. * @param {string} text Text whose directionality is to be estimated.
  285. * @param {boolean=} opt_isHtml Whether {@code text} is HTML / HTML-escaped.
  286. * Default: false.
  287. * @return {string} 'dir="rtl"' for RTL text in non-RTL context; 'dir="ltr"' for
  288. * LTR text in non-LTR context; else, the empty string.
  289. */
  290. goog.i18n.BidiFormatter.prototype.dirAttr = function (text, opt_isHtml) {
  291. var dir = soy.$$bidiTextDir(text, opt_isHtml);
  292. return dir && dir != this.dir_ ? dir < 0 ? 'dir="rtl"' : 'dir="ltr"' : '';
  293. };
  294. /**
  295. * Returns the trailing horizontal edge, i.e. "right" or "left", depending on
  296. * the global bidi directionality.
  297. * @return {string} "left" for RTL context and "right" otherwise.
  298. */
  299. goog.i18n.BidiFormatter.prototype.endEdge = function () {
  300. return this.dir_ < 0 ? 'left' : 'right';
  301. };
  302. /**
  303. * Returns the Unicode BiDi mark matching the context directionality (LRM for
  304. * LTR context directionality, RLM for RTL context directionality), or the
  305. * empty string for neutral / unknown context directionality.
  306. *
  307. * @return {string} LRM for LTR context directionality and RLM for RTL context
  308. * directionality.
  309. */
  310. goog.i18n.BidiFormatter.prototype.mark = function () {
  311. return (
  312. (this.dir_ > 0) ? '\u200E' /*LRM*/ :
  313. (this.dir_ < 0) ? '\u200F' /*RLM*/ :
  314. '');
  315. };
  316. /**
  317. * Returns a Unicode BiDi mark matching the context directionality (LRM or RLM)
  318. * if the directionality or the exit directionality of {@code text} are opposite
  319. * to the context directionality. Otherwise returns the empty string.
  320. *
  321. * @param {string} text The input text.
  322. * @param {boolean=} opt_isHtml Whether {@code text} is HTML / HTML-escaped.
  323. * Default: false.
  324. * @return {string} A Unicode bidi mark matching the global directionality or
  325. * the empty string.
  326. */
  327. goog.i18n.BidiFormatter.prototype.markAfter = function (text, opt_isHtml) {
  328. var dir = soy.$$bidiTextDir(text, opt_isHtml);
  329. return soyshim.$$bidiMarkAfterKnownDir_(this.dir_, dir, text, opt_isHtml);
  330. };
  331. /**
  332. * Formats a string of unknown directionality for use in HTML output of the
  333. * context directionality, so an opposite-directionality string is neither
  334. * garbled nor garbles what follows it.
  335. *
  336. * @param {string} str The input text.
  337. * @param {boolean=} placeholder This argument exists for consistency with the
  338. * Closure Library. Specifying it has no effect.
  339. * @return {string} Input text after applying the above processing.
  340. */
  341. goog.i18n.BidiFormatter.prototype.spanWrap = function(str, placeholder) {
  342. str = String(str);
  343. var textDir = soy.$$bidiTextDir(str, true);
  344. var reset = soyshim.$$bidiMarkAfterKnownDir_(this.dir_, textDir, str, true);
  345. if (textDir > 0 && this.dir_ <= 0) {
  346. str = '<span dir="ltr">' + str + '</span>';
  347. } else if (textDir < 0 && this.dir_ >= 0) {
  348. str = '<span dir="rtl">' + str + '</span>';
  349. }
  350. return str + reset;
  351. };
  352. /**
  353. * Returns the leading horizontal edge, i.e. "left" or "right", depending on
  354. * the global bidi directionality.
  355. * @return {string} "right" for RTL context and "left" otherwise.
  356. */
  357. goog.i18n.BidiFormatter.prototype.startEdge = function () {
  358. return this.dir_ < 0 ? 'right' : 'left';
  359. };
  360. /**
  361. * Formats a string of unknown directionality for use in plain-text output of
  362. * the context directionality, so an opposite-directionality string is neither
  363. * garbled nor garbles what follows it.
  364. * As opposed to {@link #spanWrap}, this makes use of unicode BiDi formatting
  365. * characters. In HTML, its *only* valid use is inside of elements that do not
  366. * allow mark-up, e.g. an 'option' tag.
  367. *
  368. * @param {string} str The input text.
  369. * @param {boolean=} placeholder This argument exists for consistency with the
  370. * Closure Library. Specifying it has no effect.
  371. * @return {string} Input text after applying the above processing.
  372. */
  373. goog.i18n.BidiFormatter.prototype.unicodeWrap = function(str, placeholder) {
  374. str = String(str);
  375. var textDir = soy.$$bidiTextDir(str, true);
  376. var reset = soyshim.$$bidiMarkAfterKnownDir_(this.dir_, textDir, str, true);
  377. if (textDir > 0 && this.dir_ <= 0) {
  378. str = '\u202A' + str + '\u202C';
  379. } else if (textDir < 0 && this.dir_ >= 0) {
  380. str = '\u202B' + str + '\u202C';
  381. }
  382. return str + reset;
  383. };
  384. if (!goog.string) {
  385. goog.string = {
  386. /**
  387. * Converts \r\n, \r, and \n to <br>s
  388. * @param {*} str The string in which to convert newlines.
  389. * @param {boolean=} opt_xml Whether to use XML compatible tags.
  390. * @return {string} A copy of {@code str} with converted newlines.
  391. */
  392. newLineToBr: function(str, opt_xml) {
  393. str = String(str);
  394. // This quick test helps in the case when there are no chars to replace,
  395. // in the worst case this makes barely a difference to the time taken.
  396. if (!goog.string.NEWLINE_TO_BR_RE_.test(str)) {
  397. return str;
  398. }
  399. return str.replace(/(\r\n|\r|\n)/g, opt_xml ? '<br />' : '<br>');
  400. },
  401. urlEncode: encodeURIComponent,
  402. /**
  403. * Regular expression used within newlineToBr().
  404. * @type {RegExp}
  405. * @private
  406. */
  407. NEWLINE_TO_BR_RE_: /[\r\n]/
  408. };
  409. }
  410. /**
  411. * Utility class to facilitate much faster string concatenation in IE,
  412. * using Array.join() rather than the '+' operator. For other browsers
  413. * we simply use the '+' operator.
  414. *
  415. * @param {Object|number|string|boolean=} opt_a1 Optional first initial item
  416. * to append.
  417. * @param {...Object|number|string|boolean} var_args Other initial items to
  418. * append, e.g., new goog.string.StringBuffer('foo', 'bar').
  419. * @constructor
  420. */
  421. goog.string.StringBuffer = function(opt_a1, var_args) {
  422. /**
  423. * Internal buffer for the string to be concatenated.
  424. * @type {string|Array}
  425. * @private
  426. */
  427. this.buffer_ = goog.userAgent.jscript.HAS_JSCRIPT ? [] : '';
  428. if (opt_a1 != null) {
  429. this.append.apply(this, arguments);
  430. }
  431. };
  432. /**
  433. * Length of internal buffer (faster than calling buffer_.length).
  434. * Only used for IE.
  435. * @type {number}
  436. * @private
  437. */
  438. goog.string.StringBuffer.prototype.bufferLength_ = 0;
  439. /**
  440. * Appends one or more items to the string.
  441. *
  442. * Calling this with null, undefined, or empty arguments is an error.
  443. *
  444. * @param {Object|number|string|boolean} a1 Required first string.
  445. * @param {Object|number|string|boolean=} opt_a2 Optional second string.
  446. * @param {...Object|number|string|boolean} var_args Other items to append,
  447. * e.g., sb.append('foo', 'bar', 'baz').
  448. * @return {goog.string.StringBuffer} This same StringBuilder object.
  449. */
  450. goog.string.StringBuffer.prototype.append = function(a1, opt_a2, var_args) {
  451. if (goog.userAgent.jscript.HAS_JSCRIPT) {
  452. if (opt_a2 == null) { // no second argument (note: undefined == null)
  453. // Array assignment is 2x faster than Array push. Also, use a1
  454. // directly to avoid arguments instantiation, another 2x improvement.
  455. this.buffer_[this.bufferLength_++] = a1;
  456. } else {
  457. var arr = /**@type {Array.<number|string|boolean>}*/(this.buffer_);
  458. arr.push.apply(arr, arguments);
  459. this.bufferLength_ = this.buffer_.length;
  460. }
  461. } else {
  462. // Use a1 directly to avoid arguments instantiation for single-arg case.
  463. this.buffer_ += a1;
  464. if (opt_a2 != null) { // no second argument (note: undefined == null)
  465. for (var i = 1; i < arguments.length; i++) {
  466. this.buffer_ += arguments[i];
  467. }
  468. }
  469. }
  470. return this;
  471. };
  472. /**
  473. * Clears the string.
  474. */
  475. goog.string.StringBuffer.prototype.clear = function() {
  476. if (goog.userAgent.jscript.HAS_JSCRIPT) {
  477. this.buffer_.length = 0; // reuse array to avoid creating new object
  478. this.bufferLength_ = 0;
  479. } else {
  480. this.buffer_ = '';
  481. }
  482. };
  483. /**
  484. * Returns the concatenated string.
  485. *
  486. * @return {string} The concatenated string.
  487. */
  488. goog.string.StringBuffer.prototype.toString = function() {
  489. if (goog.userAgent.jscript.HAS_JSCRIPT) {
  490. var str = this.buffer_.join('');
  491. // Given a string with the entire contents, simplify the StringBuilder by
  492. // setting its contents to only be this string, rather than many fragments.
  493. this.clear();
  494. if (str) {
  495. this.append(str);
  496. }
  497. return str;
  498. } else {
  499. return /** @type {string} */ (this.buffer_);
  500. }
  501. };
  502. if (!goog.soy) goog.soy = {
  503. /**
  504. * Helper function to render a Soy template and then set the
  505. * output string as the innerHTML of an element. It is recommended
  506. * to use this helper function instead of directly setting
  507. * innerHTML in your hand-written code, so that it will be easier
  508. * to audit the code for cross-site scripting vulnerabilities.
  509. *
  510. * @param {Function} template The Soy template defining element's content.
  511. * @param {Object=} opt_templateData The data for the template.
  512. * @param {Object=} opt_injectedData The injected data for the template.
  513. * @param {(goog.dom.DomHelper|Document)=} opt_dom The context in which DOM
  514. * nodes will be created.
  515. */
  516. renderAsElement: function(
  517. template, opt_templateData, opt_injectedData, opt_dom) {
  518. return /** @type {!Element} */ (soyshim.$$renderWithWrapper_(
  519. template, opt_templateData, opt_dom, true /* asElement */,
  520. opt_injectedData));
  521. },
  522. /**
  523. * Helper function to render a Soy template into a single node or
  524. * a document fragment. If the rendered HTML string represents a
  525. * single node, then that node is returned (note that this is
  526. * *not* a fragment, despite them name of the method). Otherwise a
  527. * document fragment is returned containing the rendered nodes.
  528. *
  529. * @param {Function} template The Soy template defining element's content.
  530. * @param {Object=} opt_templateData The data for the template.
  531. * @param {Object=} opt_injectedData The injected data for the template.
  532. * @param {(goog.dom.DomHelper|Document)=} opt_dom The context in which DOM
  533. * nodes will be created.
  534. * @return {!Node} The resulting node or document fragment.
  535. */
  536. renderAsFragment: function(
  537. template, opt_templateData, opt_injectedData, opt_dom) {
  538. return soyshim.$$renderWithWrapper_(
  539. template, opt_templateData, opt_dom, false /* asElement */,
  540. opt_injectedData);
  541. },
  542. /**
  543. * Helper function to render a Soy template and then set the output string as
  544. * the innerHTML of an element. It is recommended to use this helper function
  545. * instead of directly setting innerHTML in your hand-written code, so that it
  546. * will be easier to audit the code for cross-site scripting vulnerabilities.
  547. *
  548. * NOTE: New code should consider using goog.soy.renderElement instead.
  549. *
  550. * @param {Element} element The element whose content we are rendering.
  551. * @param {Function} template The Soy template defining the element's content.
  552. * @param {Object=} opt_templateData The data for the template.
  553. * @param {Object=} opt_injectedData The injected data for the template.
  554. */
  555. renderElement: function(
  556. element, template, opt_templateData, opt_injectedData) {
  557. element.innerHTML = template(opt_templateData, null, opt_injectedData);
  558. },
  559. data: {}
  560. };
  561. /**
  562. * A type of textual content.
  563. *
  564. * This is an enum of type Object so that these values are unforgeable.
  565. *
  566. * @enum {!Object}
  567. */
  568. goog.soy.data.SanitizedContentKind = {
  569. /**
  570. * A snippet of HTML that does not start or end inside a tag, comment, entity,
  571. * or DOCTYPE; and that does not contain any executable code
  572. * (JS, {@code <object>}s, etc.) from a different trust domain.
  573. */
  574. HTML: {},
  575. /**
  576. * Executable Javascript code or expression, safe for insertion in a
  577. * script-tag or event handler context, known to be free of any
  578. * attacker-controlled scripts. This can either be side-effect-free
  579. * Javascript (such as JSON) or Javascript that entirely under Google's
  580. * control.
  581. */
  582. JS: goog.DEBUG ? {sanitizedContentJsStrChars: true} : {},
  583. /**
  584. * A sequence of code units that can appear between quotes (either kind) in a
  585. * JS program without causing a parse error, and without causing any side
  586. * effects.
  587. * <p>
  588. * The content should not contain unescaped quotes, newlines, or anything else
  589. * that would cause parsing to fail or to cause a JS parser to finish the
  590. * string its parsing inside the content.
  591. * <p>
  592. * The content must also not end inside an escape sequence ; no partial octal
  593. * escape sequences or odd number of '{@code \}'s at the end.
  594. */
  595. JS_STR_CHARS: {},
  596. /** A properly encoded portion of a URI. */
  597. URI: {},
  598. /**
  599. * Repeated attribute names and values. For example,
  600. * {@code dir="ltr" foo="bar" onclick="trustedFunction()" checked}.
  601. */
  602. ATTRIBUTES: goog.DEBUG ? {sanitizedContentHtmlAttribute: true} : {},
  603. // TODO: Consider separating rules, declarations, and values into
  604. // separate types, but for simplicity, we'll treat explicitly blessed
  605. // SanitizedContent as allowed in all of these contexts.
  606. /**
  607. * A CSS3 declaration, property, value or group of semicolon separated
  608. * declarations.
  609. */
  610. CSS: {},
  611. /**
  612. * Unsanitized plain-text content.
  613. *
  614. * This is effectively the "null" entry of this enum, and is sometimes used
  615. * to explicitly mark content that should never be used unescaped. Since any
  616. * string is safe to use as text, being of ContentKind.TEXT makes no
  617. * guarantees about its safety in any other context such as HTML.
  618. */
  619. TEXT: {}
  620. };
  621. /**
  622. * A string-like object that carries a content-type.
  623. *
  624. * IMPORTANT! Do not create these directly, nor instantiate the subclasses.
  625. * Instead, use a trusted, centrally reviewed library as endorsed by your team
  626. * to generate these objects. Otherwise, you risk accidentally creating
  627. * SanitizedContent that is attacker-controlled and gets evaluated unescaped in
  628. * templates.
  629. *
  630. * @constructor
  631. */
  632. goog.soy.data.SanitizedContent = function() {
  633. throw Error('Do not instantiate directly');
  634. };
  635. /**
  636. * The context in which this content is safe from XSS attacks.
  637. * @type {goog.soy.data.SanitizedContentKind}
  638. */
  639. goog.soy.data.SanitizedContent.prototype.contentKind;
  640. /**
  641. * The already-safe content.
  642. * @type {string}
  643. */
  644. goog.soy.data.SanitizedContent.prototype.content;
  645. /** @override */
  646. goog.soy.data.SanitizedContent.prototype.toString = function() {
  647. return this.content;
  648. };
  649. var soy = { esc: {} };
  650. var soydata = {};
  651. soydata.VERY_UNSAFE = {};
  652. var soyshim = { $$DEFAULT_TEMPLATE_DATA_: {} };
  653. /**
  654. * Helper function to render a Soy template into a single node or a document
  655. * fragment. If the rendered HTML string represents a single node, then that
  656. * node is returned. Otherwise a document fragment is created and returned
  657. * (wrapped in a DIV element if #opt_singleNode is true).
  658. *
  659. * @param {Function} template The Soy template defining the element's content.
  660. * @param {Object=} opt_templateData The data for the template.
  661. * @param {(goog.dom.DomHelper|Document)=} opt_dom The context in which DOM
  662. * nodes will be created.
  663. * @param {boolean=} opt_asElement Whether to wrap the fragment in an
  664. * element if the template does not render a single element. If true,
  665. * result is always an Element.
  666. * @param {Object=} opt_injectedData The injected data for the template.
  667. * @return {!Node} The resulting node or document fragment.
  668. * @private
  669. */
  670. soyshim.$$renderWithWrapper_ = function(
  671. template, opt_templateData, opt_dom, opt_asElement, opt_injectedData) {
  672. var dom = opt_dom || document;
  673. var wrapper = dom.createElement('div');
  674. wrapper.innerHTML = template(
  675. opt_templateData || soyshim.$$DEFAULT_TEMPLATE_DATA_, undefined,
  676. opt_injectedData);
  677. // If the template renders as a single element, return it.
  678. if (wrapper.childNodes.length == 1) {
  679. var firstChild = wrapper.firstChild;
  680. if (!opt_asElement || firstChild.nodeType == 1 /* Element */) {
  681. return /** @type {!Node} */ (firstChild);
  682. }
  683. }
  684. // If we're forcing it to be a single element, return the wrapper DIV.
  685. if (opt_asElement) {
  686. return wrapper;
  687. }
  688. // Otherwise, create and return a fragment.
  689. var fragment = dom.createDocumentFragment();
  690. while (wrapper.firstChild) {
  691. fragment.appendChild(wrapper.firstChild);
  692. }
  693. return fragment;
  694. };
  695. /**
  696. * Returns a Unicode BiDi mark matching bidiGlobalDir (LRM or RLM) if the
  697. * directionality or the exit directionality of text are opposite to
  698. * bidiGlobalDir. Otherwise returns the empty string.
  699. * If opt_isHtml, makes sure to ignore the LTR nature of the mark-up and escapes
  700. * in text, making the logic suitable for HTML and HTML-escaped text.
  701. * @param {number} bidiGlobalDir The global directionality context: 1 if ltr, -1
  702. * if rtl, 0 if unknown.
  703. * @param {number} dir text's directionality: 1 if ltr, -1 if rtl, 0 if unknown.
  704. * @param {string} text The text whose directionality is to be estimated.
  705. * @param {boolean=} opt_isHtml Whether text is HTML/HTML-escaped.
  706. * Default: false.
  707. * @return {string} A Unicode bidi mark matching bidiGlobalDir, or
  708. * the empty string when text's overall and exit directionalities both match
  709. * bidiGlobalDir, or bidiGlobalDir is 0 (unknown).
  710. * @private
  711. */
  712. soyshim.$$bidiMarkAfterKnownDir_ = function(
  713. bidiGlobalDir, dir, text, opt_isHtml) {
  714. return (
  715. bidiGlobalDir > 0 && (dir < 0 ||
  716. soyshim.$$bidiIsRtlExitText_(text, opt_isHtml)) ? '\u200E' : // LRM
  717. bidiGlobalDir < 0 && (dir > 0 ||
  718. soyshim.$$bidiIsLtrExitText_(text, opt_isHtml)) ? '\u200F' : // RLM
  719. '');
  720. };
  721. /**
  722. * Strips str of any HTML mark-up and escapes. Imprecise in several ways, but
  723. * precision is not very important, since the result is only meant to be used
  724. * for directionality detection.
  725. * @param {string} str The string to be stripped.
  726. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped.
  727. * Default: false.
  728. * @return {string} The stripped string.
  729. * @private
  730. */
  731. soyshim.$$bidiStripHtmlIfNecessary_ = function(str, opt_isHtml) {
  732. return opt_isHtml ? str.replace(soyshim.$$BIDI_HTML_SKIP_RE_, ' ') : str;
  733. };
  734. /**
  735. * Simplified regular expression for am HTML tag (opening or closing) or an HTML
  736. * escape - the things we want to skip over in order to ignore their ltr
  737. * characters.
  738. * @type {RegExp}
  739. * @private
  740. */
  741. soyshim.$$BIDI_HTML_SKIP_RE_ = /<[^>]*>|&[^;]+;/g;
  742. /**
  743. * A practical pattern to identify strong LTR character. This pattern is not
  744. * theoretically correct according to unicode standard. It is simplified for
  745. * performance and small code size.
  746. * @type {string}
  747. * @private
  748. */
  749. soyshim.$$bidiLtrChars_ =
  750. 'A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02B8\u0300-\u0590\u0800-\u1FFF' +
  751. '\u2C00-\uFB1C\uFDFE-\uFE6F\uFEFD-\uFFFF';
  752. /**
  753. * A practical pattern to identify strong neutral and weak character. This
  754. * pattern is not theoretically correct according to unicode standard. It is
  755. * simplified for performance and small code size.
  756. * @type {string}
  757. * @private
  758. */
  759. soyshim.$$bidiNeutralChars_ =
  760. '\u0000-\u0020!-@[-`{-\u00BF\u00D7\u00F7\u02B9-\u02FF\u2000-\u2BFF';
  761. /**
  762. * A practical pattern to identify strong RTL character. This pattern is not
  763. * theoretically correct according to unicode standard. It is simplified for
  764. * performance and small code size.
  765. * @type {string}
  766. * @private
  767. */
  768. soyshim.$$bidiRtlChars_ = '\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC';
  769. /**
  770. * Regular expressions to check if a piece of text is of RTL directionality
  771. * on first character with strong directionality.
  772. * @type {RegExp}
  773. * @private
  774. */
  775. soyshim.$$bidiRtlDirCheckRe_ = new RegExp(
  776. '^[^' + soyshim.$$bidiLtrChars_ + ']*[' + soyshim.$$bidiRtlChars_ + ']');
  777. /**
  778. * Regular expressions to check if a piece of text is of neutral directionality.
  779. * Url are considered as neutral.
  780. * @type {RegExp}
  781. * @private
  782. */
  783. soyshim.$$bidiNeutralDirCheckRe_ = new RegExp(
  784. '^[' + soyshim.$$bidiNeutralChars_ + ']*$|^http://');
  785. /**
  786. * Check the directionality of the a piece of text based on the first character
  787. * with strong directionality.
  788. * @param {string} str string being checked.
  789. * @return {boolean} return true if rtl directionality is being detected.
  790. * @private
  791. */
  792. soyshim.$$bidiIsRtlText_ = function(str) {
  793. return soyshim.$$bidiRtlDirCheckRe_.test(str);
  794. };
  795. /**
  796. * Check the directionality of the a piece of text based on the first character
  797. * with strong directionality.
  798. * @param {string} str string being checked.
  799. * @return {boolean} true if all characters have neutral directionality.
  800. * @private
  801. */
  802. soyshim.$$bidiIsNeutralText_ = function(str) {
  803. return soyshim.$$bidiNeutralDirCheckRe_.test(str);
  804. };
  805. /**
  806. * This constant controls threshold of rtl directionality.
  807. * @type {number}
  808. * @private
  809. */
  810. soyshim.$$bidiRtlDetectionThreshold_ = 0.40;
  811. /**
  812. * Returns the RTL ratio based on word count.
  813. * @param {string} str the string that need to be checked.
  814. * @return {number} the ratio of RTL words among all words with directionality.
  815. * @private
  816. */
  817. soyshim.$$bidiRtlWordRatio_ = function(str) {
  818. var rtlCount = 0;
  819. var totalCount = 0;
  820. var tokens = str.split(' ');
  821. for (var i = 0; i < tokens.length; i++) {
  822. if (soyshim.$$bidiIsRtlText_(tokens[i])) {
  823. rtlCount++;
  824. totalCount++;
  825. } else if (!soyshim.$$bidiIsNeutralText_(tokens[i])) {
  826. totalCount++;
  827. }
  828. }
  829. return totalCount == 0 ? 0 : rtlCount / totalCount;
  830. };
  831. /**
  832. * Regular expressions to check if the last strongly-directional character in a
  833. * piece of text is LTR.
  834. * @type {RegExp}
  835. * @private
  836. */
  837. soyshim.$$bidiLtrExitDirCheckRe_ = new RegExp(
  838. '[' + soyshim.$$bidiLtrChars_ + '][^' + soyshim.$$bidiRtlChars_ + ']*$');
  839. /**
  840. * Regular expressions to check if the last strongly-directional character in a
  841. * piece of text is RTL.
  842. * @type {RegExp}
  843. * @private
  844. */
  845. soyshim.$$bidiRtlExitDirCheckRe_ = new RegExp(
  846. '[' + soyshim.$$bidiRtlChars_ + '][^' + soyshim.$$bidiLtrChars_ + ']*$');
  847. /**
  848. * Check if the exit directionality a piece of text is LTR, i.e. if the last
  849. * strongly-directional character in the string is LTR.
  850. * @param {string} str string being checked.
  851. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped.
  852. * Default: false.
  853. * @return {boolean} Whether LTR exit directionality was detected.
  854. * @private
  855. */
  856. soyshim.$$bidiIsLtrExitText_ = function(str, opt_isHtml) {
  857. str = soyshim.$$bidiStripHtmlIfNecessary_(str, opt_isHtml);
  858. return soyshim.$$bidiLtrExitDirCheckRe_.test(str);
  859. };
  860. /**
  861. * Check if the exit directionality a piece of text is RTL, i.e. if the last
  862. * strongly-directional character in the string is RTL.
  863. * @param {string} str string being checked.
  864. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped.
  865. * Default: false.
  866. * @return {boolean} Whether RTL exit directionality was detected.
  867. * @private
  868. */
  869. soyshim.$$bidiIsRtlExitText_ = function(str, opt_isHtml) {
  870. str = soyshim.$$bidiStripHtmlIfNecessary_(str, opt_isHtml);
  871. return soyshim.$$bidiRtlExitDirCheckRe_.test(str);
  872. };
  873. // =============================================================================
  874. // COPIED FROM soyutils_usegoog.js
  875. // -----------------------------------------------------------------------------
  876. // StringBuilder (compatible with the 'stringbuilder' code style).
  877. /**
  878. * Utility class to facilitate much faster string concatenation in IE,
  879. * using Array.join() rather than the '+' operator. For other browsers
  880. * we simply use the '+' operator.
  881. *
  882. * @param {Object} var_args Initial items to append,
  883. * e.g., new soy.StringBuilder('foo', 'bar').
  884. * @constructor
  885. */
  886. soy.StringBuilder = goog.string.StringBuffer;
  887. // -----------------------------------------------------------------------------
  888. // soydata: Defines typed strings, e.g. an HTML string {@code "a<b>c"} is
  889. // semantically distinct from the plain text string {@code "a<b>c"} and smart
  890. // templates can take that distinction into account.
  891. /**
  892. * A type of textual content.
  893. *
  894. * This is an enum of type Object so that these values are unforgeable.
  895. *
  896. * @enum {!Object}
  897. */
  898. soydata.SanitizedContentKind = goog.soy.data.SanitizedContentKind;
  899. /**
  900. * Content of type {@link soydata.SanitizedContentKind.HTML}.
  901. *
  902. * The content is a string of HTML that can safely be embedded in a PCDATA
  903. * context in your app. If you would be surprised to find that an HTML
  904. * sanitizer produced {@code s} (e.g. it runs code or fetches bad URLs) and
  905. * you wouldn't write a template that produces {@code s} on security or privacy
  906. * grounds, then don't pass {@code s} here.
  907. *
  908. * @constructor
  909. * @extends {goog.soy.data.SanitizedContent}
  910. */
  911. soydata.SanitizedHtml = function() {
  912. goog.soy.data.SanitizedContent.call(this); // Throws an exception.
  913. };
  914. goog.inherits(soydata.SanitizedHtml, goog.soy.data.SanitizedContent);
  915. /** @override */
  916. soydata.SanitizedHtml.prototype.contentKind = soydata.SanitizedContentKind.HTML;
  917. /**
  918. * Content of type {@link soydata.SanitizedContentKind.JS}.
  919. *
  920. * The content is Javascript source that when evaluated does not execute any
  921. * attacker-controlled scripts.
  922. *
  923. * @constructor
  924. * @extends {goog.soy.data.SanitizedContent}
  925. */
  926. soydata.SanitizedJs = function() {
  927. goog.soy.data.SanitizedContent.call(this); // Throws an exception.
  928. };
  929. goog.inherits(soydata.SanitizedJs, goog.soy.data.SanitizedContent);
  930. /** @override */
  931. soydata.SanitizedJs.prototype.contentKind =
  932. soydata.SanitizedContentKind.JS;
  933. /**
  934. * Content of type {@link soydata.SanitizedContentKind.JS_STR_CHARS}.
  935. *
  936. * The content can be safely inserted as part of a single- or double-quoted
  937. * string without terminating the string.
  938. *
  939. * @constructor
  940. * @extends {goog.soy.data.SanitizedContent}
  941. */
  942. soydata.SanitizedJsStrChars = function() {
  943. goog.soy.data.SanitizedContent.call(this); // Throws an exception.
  944. };
  945. goog.inherits(soydata.SanitizedJsStrChars, goog.soy.data.SanitizedContent);
  946. /** @override */
  947. soydata.SanitizedJsStrChars.prototype.contentKind =
  948. soydata.SanitizedContentKind.JS_STR_CHARS;
  949. /**
  950. * Content of type {@link soydata.SanitizedContentKind.URI}.
  951. *
  952. * The content is a URI chunk that the caller knows is safe to emit in a
  953. * template.
  954. *
  955. * @constructor
  956. * @extends {goog.soy.data.SanitizedContent}
  957. */
  958. soydata.SanitizedUri = function() {
  959. goog.soy.data.SanitizedContent.call(this); // Throws an exception.
  960. };
  961. goog.inherits(soydata.SanitizedUri, goog.soy.data.SanitizedContent);
  962. /** @override */
  963. soydata.SanitizedUri.prototype.contentKind = soydata.SanitizedContentKind.URI;
  964. /**
  965. * Content of type {@link soydata.SanitizedContentKind.ATTRIBUTES}.
  966. *
  967. * The content should be safely embeddable within an open tag, such as a
  968. * key="value" pair.
  969. *
  970. * @constructor
  971. * @extends {goog.soy.data.SanitizedContent}
  972. */
  973. soydata.SanitizedHtmlAttribute = function() {
  974. goog.soy.data.SanitizedContent.call(this); // Throws an exception.
  975. };
  976. goog.inherits(soydata.SanitizedHtmlAttribute, goog.soy.data.SanitizedContent);
  977. /** @override */
  978. soydata.SanitizedHtmlAttribute.prototype.contentKind =
  979. soydata.SanitizedContentKind.ATTRIBUTES;
  980. /**
  981. * Content of type {@link soydata.SanitizedContentKind.CSS}.
  982. *
  983. * The content is non-attacker-exploitable CSS, such as {@code color:#c3d9ff}.
  984. *
  985. * @constructor
  986. * @extends {goog.soy.data.SanitizedContent}
  987. */
  988. soydata.SanitizedCss = function() {
  989. goog.soy.data.SanitizedContent.call(this); // Throws an exception.
  990. };
  991. goog.inherits(soydata.SanitizedCss, goog.soy.data.SanitizedContent);
  992. /** @override */
  993. soydata.SanitizedCss.prototype.contentKind =
  994. soydata.SanitizedContentKind.CSS;
  995. /**
  996. * Unsanitized plain text string.
  997. *
  998. * While all strings are effectively safe to use as a plain text, there are no
  999. * guarantees about safety in any other context such as HTML. This is
  1000. * sometimes used to mark that should never be used unescaped.
  1001. *
  1002. * @param {*} content Plain text with no guarantees.
  1003. * @constructor
  1004. * @extends {goog.soy.data.SanitizedContent}
  1005. */
  1006. soydata.UnsanitizedText = function(content) {
  1007. /** @override */
  1008. this.content = String(content);
  1009. };
  1010. goog.inherits(soydata.UnsanitizedText, goog.soy.data.SanitizedContent);
  1011. /** @override */
  1012. soydata.UnsanitizedText.prototype.contentKind =
  1013. soydata.SanitizedContentKind.TEXT;
  1014. /**
  1015. * Creates a factory for SanitizedContent types.
  1016. *
  1017. * This is a hack so that the soydata.VERY_UNSAFE.ordainSanitized* can
  1018. * instantiate Sanitized* classes, without making the Sanitized* constructors
  1019. * publicly usable. Requiring all construction to use the VERY_UNSAFE names
  1020. * helps callers and their reviewers easily tell that creating SanitizedContent
  1021. * is not always safe and calls for careful review.
  1022. *
  1023. * @param {function(new: T, string)} ctor A constructor.
  1024. * @return {!function(*): T} A factory that takes content and returns a
  1025. * new instance.
  1026. * @template T
  1027. * @private
  1028. */
  1029. soydata.$$makeSanitizedContentFactory_ = function(ctor) {
  1030. /** @constructor */
  1031. function InstantiableCtor() {}
  1032. InstantiableCtor.prototype = ctor.prototype;
  1033. return function(content) {
  1034. var result = new InstantiableCtor();
  1035. result.content = String(content);
  1036. return result;
  1037. };
  1038. };
  1039. // -----------------------------------------------------------------------------
  1040. // Sanitized content ordainers. Please use these with extreme caution (with the
  1041. // exception of markUnsanitizedText). A good recommendation is to limit usage
  1042. // of these to just a handful of files in your source tree where usages can be
  1043. // carefully audited.
  1044. /**
  1045. * Protects a string from being used in an noAutoescaped context.
  1046. *
  1047. * This is useful for content where there is significant risk of accidental
  1048. * unescaped usage in a Soy template. A great case is for user-controlled
  1049. * data that has historically been a source of vulernabilities.
  1050. *
  1051. * @param {*} content Text to protect.
  1052. * @return {!soydata.UnsanitizedText} A wrapper that is rejected by the
  1053. * Soy noAutoescape print directive.
  1054. */
  1055. soydata.markUnsanitizedText = function(content) {
  1056. return new soydata.UnsanitizedText(content);
  1057. };
  1058. /**
  1059. * Takes a leap of faith that the provided content is "safe" HTML.
  1060. *
  1061. * @param {*} content A string of HTML that can safely be embedded in
  1062. * a PCDATA context in your app. If you would be surprised to find that an
  1063. * HTML sanitizer produced {@code s} (e.g. it runs code or fetches bad URLs)
  1064. * and you wouldn't write a template that produces {@code s} on security or
  1065. * privacy grounds, then don't pass {@code s} here.
  1066. * @return {!soydata.SanitizedHtml} Sanitized content wrapper that
  1067. * indicates to Soy not to escape when printed as HTML.
  1068. */
  1069. soydata.VERY_UNSAFE.ordainSanitizedHtml =
  1070. soydata.$$makeSanitizedContentFactory_(soydata.SanitizedHtml);
  1071. /**
  1072. * Takes a leap of faith that the provided content is "safe" (non-attacker-
  1073. * controlled, XSS-free) Javascript.
  1074. *
  1075. * @param {*} content Javascript source that when evaluated does not
  1076. * execute any attacker-controlled scripts.
  1077. * @return {!soydata.SanitizedJs} Sanitized content wrapper that indicates to
  1078. * Soy not to escape when printed as Javascript source.
  1079. */
  1080. soydata.VERY_UNSAFE.ordainSanitizedJs =
  1081. soydata.$$makeSanitizedContentFactory_(soydata.SanitizedJs);
  1082. // TODO: This function is probably necessary, either externally or internally
  1083. // as an implementation detail. Generally, plain text will always work here,
  1084. // as there's no harm to unescaping the string and then re-escaping when
  1085. // finally printed.
  1086. /**
  1087. * Takes a leap of faith that the provided content can be safely embedded in
  1088. * a Javascript string without re-esacping.
  1089. *
  1090. * @param {*} content Content that can be safely inserted as part of a
  1091. * single- or double-quoted string without terminating the string.
  1092. * @return {!soydata.SanitizedJsStrChars} Sanitized content wrapper that
  1093. * indicates to Soy not to escape when printed in a JS string.
  1094. */
  1095. soydata.VERY_UNSAFE.ordainSanitizedJsStrChars =
  1096. soydata.$$makeSanitizedContentFactory_(soydata.SanitizedJsStrChars);
  1097. /**
  1098. * Takes a leap of faith that the provided content is "safe" to use as a URI
  1099. * in a Soy template.
  1100. *
  1101. * This creates a Soy SanitizedContent object which indicates to Soy there is
  1102. * no need to escape it when printed as a URI (e.g. in an href or src
  1103. * attribute), such as if it's already been encoded or if it's a Javascript:
  1104. * URI.
  1105. *
  1106. * @param {*} content A chunk of URI that the caller knows is safe to
  1107. * emit in a template.
  1108. * @return {!soydata.SanitizedUri} Sanitized content wrapper that indicates to
  1109. * Soy not to escape or filter when printed in URI context.
  1110. */
  1111. soydata.VERY_UNSAFE.ordainSanitizedUri =
  1112. soydata.$$makeSanitizedContentFactory_(soydata.SanitizedUri);
  1113. /**
  1114. * Takes a leap of faith that the provided content is "safe" to use as an
  1115. * HTML attribute.
  1116. *
  1117. * @param {*} content An attribute name and value, such as
  1118. * {@code dir="ltr"}.
  1119. * @return {!soydata.SanitizedHtmlAttribute} Sanitized content wrapper that
  1120. * indicates to Soy not to escape when printed as an HTML attribute.
  1121. */
  1122. soydata.VERY_UNSAFE.ordainSanitizedHtmlAttribute =
  1123. soydata.$$makeSanitizedContentFactory_(soydata.SanitizedHtmlAttribute);
  1124. /**
  1125. * Takes a leap of faith that the provided content is "safe" to use as CSS
  1126. * in a style attribute or block.
  1127. *
  1128. * @param {*} content CSS, such as {@code color:#c3d9ff}.
  1129. * @return {!soydata.SanitizedCss} Sanitized CSS wrapper that indicates to
  1130. * Soy there is no need to escape or filter when printed in CSS context.
  1131. */
  1132. soydata.VERY_UNSAFE.ordainSanitizedCss =
  1133. soydata.$$makeSanitizedContentFactory_(soydata.SanitizedCss);
  1134. // -----------------------------------------------------------------------------
  1135. // Public utilities.
  1136. /**
  1137. * Helper function to render a Soy template and then set the output string as
  1138. * the innerHTML of an element. It is recommended to use this helper function
  1139. * instead of directly setting innerHTML in your hand-written code, so that it
  1140. * will be easier to audit the code for cross-site scripting vulnerabilities.
  1141. *
  1142. * NOTE: New code should consider using goog.soy.renderElement instead.
  1143. *
  1144. * @param {Element} element The element whose content we are rendering.
  1145. * @param {Function} template The Soy template defining the element's content.
  1146. * @param {Object=} opt_templateData The data for the template.
  1147. * @param {Object=} opt_injectedData The injected data for the template.
  1148. */
  1149. soy.renderElement = goog.soy.renderElement;
  1150. /**
  1151. * Helper function to render a Soy template into a single node or a document
  1152. * fragment. If the rendered HTML string represents a single node, then that
  1153. * node is returned (note that this is *not* a fragment, despite them name of
  1154. * the method). Otherwise a document fragment is returned containing the
  1155. * rendered nodes.
  1156. *
  1157. * NOTE: New code should consider using goog.soy.renderAsFragment
  1158. * instead (note that the arguments are different).
  1159. *
  1160. * @param {Function} template The Soy template defining the element's content.
  1161. * @param {Object=} opt_templateData The data for the template.
  1162. * @param {Document=} opt_document The document used to create DOM nodes. If not
  1163. * specified, global document object is used.
  1164. * @param {Object=} opt_injectedData The injected data for the template.
  1165. * @return {!Node} The resulting node or document fragment.
  1166. */
  1167. soy.renderAsFragment = function(
  1168. template, opt_templateData, opt_document, opt_injectedData) {
  1169. return goog.soy.renderAsFragment(
  1170. template, opt_templateData, opt_injectedData,
  1171. new goog.dom.DomHelper(opt_document));
  1172. };
  1173. /**
  1174. * Helper function to render a Soy template into a single node. If the rendered
  1175. * HTML string represents a single node, then that node is returned. Otherwise,
  1176. * a DIV element is returned containing the rendered nodes.
  1177. *
  1178. * NOTE: New code should consider using goog.soy.renderAsElement
  1179. * instead (note that the arguments are different).
  1180. *
  1181. * @param {Function} template The Soy template defining the element's content.
  1182. * @param {Object=} opt_templateData The data for the template.
  1183. * @param {Document=} opt_document The document used to create DOM nodes. If not
  1184. * specified, global document object is used.
  1185. * @param {Object=} opt_injectedData The injected data for the template.
  1186. * @return {!Element} Rendered template contents, wrapped in a parent DIV
  1187. * element if necessary.
  1188. */
  1189. soy.renderAsElement = function(
  1190. template, opt_templateData, opt_document, opt_injectedData) {
  1191. return goog.soy.renderAsElement(
  1192. template, opt_templateData, opt_injectedData,
  1193. new goog.dom.DomHelper(opt_document));
  1194. };
  1195. // -----------------------------------------------------------------------------
  1196. // Below are private utilities to be used by Soy-generated code only.
  1197. /**
  1198. * Builds an augmented map. The returned map will contain mappings from both
  1199. * the base map and the additional map. If the same key appears in both, then
  1200. * the value from the additional map will be visible, while the value from the
  1201. * base map will be hidden. The base map will be used, but not modified.
  1202. *
  1203. * @param {!Object} baseMap The original map to augment.
  1204. * @param {!Object} additionalMap A map containing the additional mappings.
  1205. * @return {!Object} An augmented map containing both the original and
  1206. * additional mappings.
  1207. */
  1208. soy.$$augmentMap = function(baseMap, additionalMap) {
  1209. // Create a new map whose '__proto__' field is set to baseMap.
  1210. /** @constructor */
  1211. function TempCtor() {}
  1212. TempCtor.prototype = baseMap;
  1213. var augmentedMap = new TempCtor();
  1214. // Add the additional mappings to the new map.
  1215. for (var key in additionalMap) {
  1216. augmentedMap[key] = additionalMap[key];
  1217. }
  1218. return augmentedMap;
  1219. };
  1220. /**
  1221. * Checks that the given map key is a string.
  1222. * @param {*} key Key to check.
  1223. * @return {string} The given key.
  1224. */
  1225. soy.$$checkMapKey = function(key) {
  1226. if ((typeof key) != 'string') {
  1227. throw Error(
  1228. 'Map literal\'s key expression must evaluate to string' +
  1229. ' (encountered type "' + (typeof key) + '").');
  1230. }
  1231. return key;
  1232. };
  1233. /**
  1234. * Gets the keys in a map as an array. There are no guarantees on the order.
  1235. * @param {Object} map The map to get the keys of.
  1236. * @return {Array.<string>} The array of keys in the given map.
  1237. */
  1238. soy.$$getMapKeys = function(map) {
  1239. var mapKeys = [];
  1240. for (var key in map) {
  1241. mapKeys.push(key);
  1242. }
  1243. return mapKeys;
  1244. };
  1245. /**
  1246. * Gets a consistent unique id for the given delegate template name. Two calls
  1247. * to this function will return the same id if and only if the input names are
  1248. * the same.
  1249. *
  1250. * <p> Important: This function must always be called with a string constant.
  1251. *
  1252. * <p> If Closure Compiler is not being used, then this is just this identity
  1253. * function. If Closure Compiler is being used, then each call to this function
  1254. * will be replaced with a short string constant, which will be consistent per
  1255. * input name.
  1256. *
  1257. * @param {string} delTemplateName The delegate template name for which to get a
  1258. * consistent unique id.
  1259. * @return {string} A unique id that is consistent per input name.
  1260. *
  1261. * @consistentIdGenerator
  1262. */
  1263. soy.$$getDelTemplateId = function(delTemplateName) {
  1264. return delTemplateName;
  1265. };
  1266. /**
  1267. * Map from registered delegate template key to the priority of the
  1268. * implementation.
  1269. * @type {Object}
  1270. * @private
  1271. */
  1272. soy.$$DELEGATE_REGISTRY_PRIORITIES_ = {};
  1273. /**
  1274. * Map from registered delegate template key to the implementation function.
  1275. * @type {Object}
  1276. * @private
  1277. */
  1278. soy.$$DELEGATE_REGISTRY_FUNCTIONS_ = {};
  1279. /**
  1280. * Registers a delegate implementation. If the same delegate template key (id
  1281. * and variant) has been registered previously, then priority values are
  1282. * compared and only the higher priority implementation is stored (if
  1283. * priorities are equal, an error is thrown).
  1284. *
  1285. * @param {string} delTemplateId The delegate template id.
  1286. * @param {string} delTemplateVariant The delegate template variant (can be
  1287. * empty string).
  1288. * @param {number} delPriority The implementation's priority value.
  1289. * @param {Function} delFn The implementation function.
  1290. */
  1291. soy.$$registerDelegateFn = function(
  1292. delTemplateId, delTemplateVariant, delPriority, delFn) {
  1293. var mapKey = 'key_' + delTemplateId + ':' + delTemplateVariant;
  1294. var currPriority = soy.$$DELEGATE_REGISTRY_PRIORITIES_[mapKey];
  1295. if (currPriority === undefined || delPriority > currPriority) {
  1296. // Registering new or higher-priority function: replace registry entry.
  1297. soy.$$DELEGATE_REGISTRY_PRIORITIES_[mapKey] = delPriority;
  1298. soy.$$DELEGATE_REGISTRY_FUNCTIONS_[mapKey] = delFn;
  1299. } else if (delPriority == currPriority) {
  1300. // Registering same-priority function: error.
  1301. throw Error(
  1302. 'Encountered two active delegates with the same priority ("' +
  1303. delTemplateId + ':' + delTemplateVariant + '").');
  1304. } else {
  1305. // Registering lower-priority function: do nothing.
  1306. }
  1307. };
  1308. /**
  1309. * Retrieves the (highest-priority) implementation that has been registered for
  1310. * a given delegate template key (id and variant). If no implementation has
  1311. * been registered for the key, then the fallback is the same id with empty
  1312. * variant. If the fallback is also not registered, and allowsEmptyDefault is
  1313. * true, then returns an implementation that is equivalent to an empty template
  1314. * (i.e. rendered output would be empty string).
  1315. *
  1316. * @param {string} delTemplateId The delegate template id.
  1317. * @param {string} delTemplateVariant The delegate template variant (can be
  1318. * empty string).
  1319. * @param {boolean} allowsEmptyDefault Whether to default to the empty template
  1320. * function if there's no active implementation.
  1321. * @return {Function} The retrieved implementation function.
  1322. */
  1323. soy.$$getDelegateFn = function(
  1324. delTemplateId, delTemplateVariant, allowsEmptyDefault) {
  1325. var delFn = soy.$$DELEGATE_REGISTRY_FUNCTIONS_[
  1326. 'key_' + delTemplateId + ':' + delTemplateVariant];
  1327. if (! delFn && delTemplateVariant != '') {
  1328. // Fallback to empty variant.
  1329. delFn = soy.$$DELEGATE_REGISTRY_FUNCTIONS_['key_' + delTemplateId + ':'];
  1330. }
  1331. if (delFn) {
  1332. return delFn;
  1333. } else if (allowsEmptyDefault) {
  1334. return soy.$$EMPTY_TEMPLATE_FN_;
  1335. } else {
  1336. throw Error(
  1337. 'Found no active impl for delegate call to "' + delTemplateId + ':' +
  1338. delTemplateVariant + '" (and not allowemptydefault="true").');
  1339. }
  1340. };
  1341. /**
  1342. * Private helper soy.$$getDelegateFn(). This is the empty template function
  1343. * that is returned whenever there's no delegate implementation found.
  1344. *
  1345. * @param {Object.<string, *>=} opt_data
  1346. * @param {soy.StringBuilder=} opt_sb
  1347. * @param {Object.<string, *>=} opt_ijData
  1348. * @return {string}
  1349. * @private
  1350. */
  1351. soy.$$EMPTY_TEMPLATE_FN_ = function(opt_data, opt_sb, opt_ijData) {
  1352. return '';
  1353. };
  1354. // -----------------------------------------------------------------------------
  1355. // Escape/filter/normalize.
  1356. /**
  1357. * Escapes HTML special characters in a string. Escapes double quote '"' in
  1358. * addition to '&', '<', and '>' so that a string can be included in an HTML
  1359. * tag attribute value within double quotes.
  1360. * Will emit known safe HTML as-is.
  1361. *
  1362. * @param {*} value The string-like value to be escaped. May not be a string,
  1363. * but the value will be coerced to a string.
  1364. * @return {string} An escaped version of value.
  1365. */
  1366. soy.$$escapeHtml = function(value) {
  1367. // TODO: Perhaps we should just ignore the contentKind property and instead
  1368. // look only at the constructor.
  1369. if (value && value.contentKind &&
  1370. value.contentKind === goog.soy.data.SanitizedContentKind.HTML) {
  1371. goog.asserts.assert(
  1372. value.constructor === soydata.SanitizedHtml);
  1373. return value.content;
  1374. }
  1375. return soy.esc.$$escapeHtmlHelper(value);
  1376. };
  1377. /**
  1378. * Strips unsafe tags to convert a string of untrusted HTML into HTML that
  1379. * is safe to embed.
  1380. *
  1381. * @param {*} value The string-like value to be escaped. May not be a string,
  1382. * but the value will be coerced to a string.
  1383. * @return {string} A sanitized and normalized version of value.
  1384. */
  1385. soy.$$cleanHtml = function(value) {
  1386. if (value && value.contentKind &&
  1387. value.contentKind === goog.soy.data.SanitizedContentKind.HTML) {
  1388. goog.asserts.assert(
  1389. value.constructor === soydata.SanitizedHtml);
  1390. return value.content;
  1391. }
  1392. return soy.$$stripHtmlTags(value, soy.esc.$$SAFE_TAG_WHITELIST_);
  1393. };
  1394. /**
  1395. * Escapes HTML special characters in a string so that it can be embedded in
  1396. * RCDATA.
  1397. * <p>
  1398. * Escapes HTML special characters so that the value will not prematurely end
  1399. * the body of a tag like {@code <textarea>} or {@code <title>}. RCDATA tags
  1400. * cannot contain other HTML entities, so it is not strictly necessary to escape
  1401. * HTML special characters except when part of that text looks like an HTML
  1402. * entity or like a close tag : {@code </textarea>}.
  1403. * <p>
  1404. * Will normalize known safe HTML to make sure that sanitized HTML (which could
  1405. * contain an innocuous {@code </textarea>} don't prematurely end an RCDATA
  1406. * element.
  1407. *
  1408. * @param {*} value The string-like value to be escaped. May not be a string,
  1409. * but the value will be coerced to a string.
  1410. * @return {string} An escaped version of value.
  1411. */
  1412. soy.$$escapeHtmlRcdata = function(value) {
  1413. if (value && value.contentKind &&
  1414. value.contentKind === goog.soy.data.SanitizedContentKind.HTML) {
  1415. goog.asserts.assert(
  1416. value.constructor === soydata.SanitizedHtml);
  1417. return soy.esc.$$normalizeHtmlHelper(value.content);
  1418. }
  1419. return soy.esc.$$escapeHtmlHelper(value);
  1420. };
  1421. /**
  1422. * Matches any/only HTML5 void elements' start tags.
  1423. * See http://www.w3.org/TR/html-markup/syntax.html#syntax-elements
  1424. * @type {RegExp}
  1425. * @private
  1426. */
  1427. soy.$$HTML5_VOID_ELEMENTS_ = new RegExp(
  1428. '^<(?:area|base|br|col|command|embed|hr|img|input' +
  1429. '|keygen|link|meta|param|source|track|wbr)\\b');
  1430. /**
  1431. * Removes HTML tags from a string of known safe HTML.
  1432. * If opt_tagWhitelist is not specified or is empty, then
  1433. * the result can be used as an attribute value.
  1434. *
  1435. * @param {*} value The HTML to be escaped. May not be a string, but the
  1436. * value will be coerced to a string.
  1437. * @param {Object.<string, number>=} opt_tagWhitelist Has an own property whose
  1438. * name is a lower-case tag name and whose value is {@code 1} for
  1439. * each element that is allowed in the output.
  1440. * @return {string} A representation of value without disallowed tags,
  1441. * HTML comments, or other non-text content.
  1442. */
  1443. soy.$$stripHtmlTags = function(value, opt_tagWhitelist) {
  1444. if (!opt_tagWhitelist) {
  1445. // If we have no white-list, then use a fast track which elides all tags.
  1446. return String(value).replace(soy.esc.$$HTML_TAG_REGEX_, '')
  1447. // This is just paranoia since callers should normalize the result
  1448. // anyway, but if they didn't, it would be necessary to ensure that
  1449. // after the first replace non-tag uses of < do not recombine into
  1450. // tags as in "<<foo>script>alert(1337)</<foo>script>".
  1451. .replace(soy.esc.$$LT_REGEX_, '&lt;');
  1452. }
  1453. // Escapes '[' so that we can use [123] below to mark places where tags
  1454. // have been removed.
  1455. var html = String(value).replace(/\[/g, '&#91;');
  1456. // Consider all uses of '<' and replace whitelisted tags with markers like
  1457. // [1] which are indices into a list of approved tag names.
  1458. // Replace all other uses of < and > with entities.
  1459. var tags = [];
  1460. html = html.replace(
  1461. soy.esc.$$HTML_TAG_REGEX_,
  1462. function(tok, tagName) {
  1463. if (tagName) {
  1464. tagName = tagName.toLowerCase();
  1465. if (opt_tagWhitelist.hasOwnProperty(tagName) &&
  1466. opt_tagWhitelist[tagName]) {
  1467. var start = tok.charAt(1) === '/' ? '</' : '<';
  1468. var index = tags.length;
  1469. tags[index] = start + tagName + '>';
  1470. return '[' + index + ']';
  1471. }
  1472. }
  1473. return '';
  1474. });
  1475. // Escape HTML special characters. Now there are no '<' in html that could
  1476. // start a tag.
  1477. html = soy.esc.$$normalizeHtmlHelper(html);
  1478. var finalCloseTags = soy.$$balanceTags_(tags);
  1479. // Now html contains no tags or less-than characters that could become
  1480. // part of a tag via a replacement operation and tags only contains
  1481. // approved tags.
  1482. // Reinsert the white-listed tags.
  1483. html = html.replace(
  1484. /\[(\d+)\]/g, function(_, index) { return tags[index]; });
  1485. // Close any still open tags.
  1486. // This prevents unclosed formatting elements like <ol> and <table> from
  1487. // breaking the layout of containing HTML.
  1488. return html + finalCloseTags;
  1489. };
  1490. /**
  1491. * Throw out any close tags that don't correspond to start tags.
  1492. * If {@code <table>} is used for formatting, embedded HTML shouldn't be able
  1493. * to use a mismatched {@code </table>} to break page layout.
  1494. *
  1495. * @param {Array.<string>} tags an array of tags that will be modified in place
  1496. * include tags, the empty string, or concatenations of empty tags.
  1497. * @return {string} zero or more closed tags that close all elements that are
  1498. * opened in tags but not closed.
  1499. * @private
  1500. */
  1501. soy.$$balanceTags_ = function(tags) {
  1502. var open = [];
  1503. for (var i = 0, n = tags.length; i < n; ++i) {
  1504. var tag = tags[i];
  1505. if (tag.charAt(1) === '/') {
  1506. var openTagIndex = open.length - 1;
  1507. // NOTE: This is essentially lastIndexOf, but it's not supported in IE.
  1508. while (openTagIndex >= 0 && open[openTagIndex] != tag) {
  1509. openTagIndex--;
  1510. }
  1511. if (openTagIndex < 0) {
  1512. tags[i] = ''; // Drop close tag.
  1513. } else {
  1514. tags[i] = open.slice(openTagIndex).reverse().join('');
  1515. open.length = openTagIndex;
  1516. }
  1517. } else if (!soy.$$HTML5_VOID_ELEMENTS_.test(tag)) {
  1518. open.push('</' + tag.substring(1));
  1519. }
  1520. }
  1521. return open.reverse().join('');
  1522. };
  1523. /**
  1524. * Escapes HTML special characters in an HTML attribute value.
  1525. *
  1526. * @param {*} value The HTML to be escaped. May not be a string, but the
  1527. * value will be coerced to a string.
  1528. * @return {string} An escaped version of value.
  1529. */
  1530. soy.$$escapeHtmlAttribute = function(value) {
  1531. if (value && value.contentKind) {
  1532. // NOTE: We don't accept ATTRIBUTES here because ATTRIBUTES is
  1533. // actually not the attribute value context, but instead k/v pairs.
  1534. if (value.contentKind === goog.soy.data.SanitizedContentKind.HTML) {
  1535. // NOTE: After removing tags, we also escape quotes ("normalize") so that
  1536. // the HTML can be embedded in attribute context.
  1537. goog.asserts.assert(
  1538. value.constructor === soydata.SanitizedHtml);
  1539. return soy.esc.$$normalizeHtmlHelper(soy.$$stripHtmlTags(value.content));
  1540. }
  1541. }
  1542. return soy.esc.$$escapeHtmlHelper(value);
  1543. };
  1544. /**
  1545. * Escapes HTML special characters in a string including space and other
  1546. * characters that can end an unquoted HTML attribute value.
  1547. *
  1548. * @param {*} value The HTML to be escaped. May not be a string, but the
  1549. * value will be coerced to a string.
  1550. * @return {string} An escaped version of value.
  1551. */
  1552. soy.$$escapeHtmlAttributeNospace = function(value) {
  1553. if (value && value.contentKind) {
  1554. if (value.contentKind === goog.soy.data.SanitizedContentKind.HTML) {
  1555. goog.asserts.assert(value.constructor ===
  1556. soydata.SanitizedHtml);
  1557. return soy.esc.$$normalizeHtmlNospaceHelper(
  1558. soy.$$stripHtmlTags(value.content));
  1559. }
  1560. }
  1561. return soy.esc.$$escapeHtmlNospaceHelper(value);
  1562. };
  1563. /**
  1564. * Filters out strings that cannot be a substring of a valid HTML attribute.
  1565. *
  1566. * Note the input is expected to be key=value pairs.
  1567. *
  1568. * @param {*} value The value to escape. May not be a string, but the value
  1569. * will be coerced to a string.
  1570. * @return {string} A valid HTML attribute name part or name/value pair.
  1571. * {@code "zSoyz"} if the input is invalid.
  1572. */
  1573. soy.$$filterHtmlAttributes = function(value) {
  1574. // NOTE: Explicitly no support for SanitizedContentKind.HTML, since that is
  1575. // meaningless in this context, which is generally *between* html attributes.
  1576. if (value &&
  1577. value.contentKind === goog.soy.data.SanitizedContentKind.ATTRIBUTES) {
  1578. goog.asserts.assert(value.constructor ===
  1579. soydata.SanitizedHtmlAttribute);
  1580. // Add a space at the end to ensure this won't get merged into following
  1581. // attributes, unless the interpretation is unambiguous (ending with quotes
  1582. // or a space).
  1583. return value.content.replace(/([^"'\s])$/, '$1 ');
  1584. }
  1585. // TODO: Dynamically inserting attributes that aren't marked as trusted is
  1586. // probably unnecessary. Any filtering done here will either be inadequate
  1587. // for security or not flexible enough. Having clients use kind="attributes"
  1588. // in parameters seems like a wiser idea.
  1589. return soy.esc.$$filterHtmlAttributesHelper(value);
  1590. };
  1591. /**
  1592. * Filters out strings that cannot be a substring of a valid HTML element name.
  1593. *
  1594. * @param {*} value The value to escape. May not be a string, but the value
  1595. * will be coerced to a string.
  1596. * @return {string} A valid HTML element name part.
  1597. * {@code "zSoyz"} if the input is invalid.
  1598. */
  1599. soy.$$filterHtmlElementName = function(value) {
  1600. // NOTE: We don't accept any SanitizedContent here. HTML indicates valid
  1601. // PCDATA, not tag names. A sloppy developer shouldn't be able to cause an
  1602. // exploit:
  1603. // ... {let userInput}script src=http://evil.com/evil.js{/let} ...
  1604. // ... {param tagName kind="html"}{$userInput}{/param} ...
  1605. // ... <{$tagName}>Hello World</{$tagName}>
  1606. return soy.esc.$$filterHtmlElementNameHelper(value);
  1607. };
  1608. /**
  1609. * Escapes characters in the value to make it valid content for a JS string
  1610. * literal.
  1611. *
  1612. * @param {*} value The value to escape. May not be a string, but the value
  1613. * will be coerced to a string.
  1614. * @return {string} An escaped version of value.
  1615. * @deprecated
  1616. */
  1617. soy.$$escapeJs = function(value) {
  1618. return soy.$$escapeJsString(value);
  1619. };
  1620. /**
  1621. * Escapes characters in the value to make it valid content for a JS string
  1622. * literal.
  1623. *
  1624. * @param {*} value The value to escape. May not be a string, but the value
  1625. * will be coerced to a string.
  1626. * @return {string} An escaped version of value.
  1627. */
  1628. soy.$$escapeJsString = function(value) {
  1629. if (value &&
  1630. value.contentKind === goog.soy.data.SanitizedContentKind.JS_STR_CHARS) {
  1631. // TODO: It might still be worthwhile to normalize it to remove
  1632. // unescaped quotes, null, etc: replace(/(?:^|[^\])['"]/g, '\\$
  1633. goog.asserts.assert(value.constructor ===
  1634. soydata.SanitizedJsStrChars);
  1635. return value.content;
  1636. }
  1637. return soy.esc.$$escapeJsStringHelper(value);
  1638. };
  1639. /**
  1640. * Encodes a value as a JavaScript literal.
  1641. *
  1642. * @param {*} value The value to escape. May not be a string, but the value
  1643. * will be coerced to a string.
  1644. * @return {string} A JavaScript code representation of the input.
  1645. */
  1646. soy.$$escapeJsValue = function(value) {
  1647. // We surround values with spaces so that they can't be interpolated into
  1648. // identifiers by accident.
  1649. // We could use parentheses but those might be interpreted as a function call.
  1650. if (value == null) { // Intentionally matches undefined.
  1651. // Java returns null from maps where there is no corresponding key while
  1652. // JS returns undefined.
  1653. // We always output null for compatibility with Java which does not have a
  1654. // distinct undefined value.
  1655. return ' null ';
  1656. }
  1657. if (value.contentKind == goog.soy.data.SanitizedContentKind.JS) {
  1658. goog.asserts.assert(value.constructor ===
  1659. soydata.SanitizedJs);
  1660. return value.content;
  1661. }
  1662. switch (typeof value) {
  1663. case 'boolean': case 'number':
  1664. return ' ' + value + ' ';
  1665. default:
  1666. return "'" + soy.esc.$$escapeJsStringHelper(String(value)) + "'";
  1667. }
  1668. };
  1669. /**
  1670. * Escapes characters in the string to make it valid content for a JS regular
  1671. * expression literal.
  1672. *
  1673. * @param {*} value The value to escape. May not be a string, but the value
  1674. * will be coerced to a string.
  1675. * @return {string} An escaped version of value.
  1676. */
  1677. soy.$$escapeJsRegex = function(value) {
  1678. return soy.esc.$$escapeJsRegexHelper(value);
  1679. };
  1680. /**
  1681. * Matches all URI mark characters that conflict with HTML attribute delimiters
  1682. * or that cannot appear in a CSS uri.
  1683. * From <a href="http://www.w3.org/TR/CSS2/grammar.html">G.2: CSS grammar</a>
  1684. * <pre>
  1685. * url ([!#$%&*-~]|{nonascii}|{escape})*
  1686. * </pre>
  1687. *
  1688. * @type {RegExp}
  1689. * @private
  1690. */
  1691. soy.$$problematicUriMarks_ = /['()]/g;
  1692. /**
  1693. * @param {string} ch A single character in {@link soy.$$problematicUriMarks_}.
  1694. * @return {string}
  1695. * @private
  1696. */
  1697. soy.$$pctEncode_ = function(ch) {
  1698. return '%' + ch.charCodeAt(0).toString(16);
  1699. };
  1700. /**
  1701. * Escapes a string so that it can be safely included in a URI.
  1702. *
  1703. * @param {*} value The value to escape. May not be a string, but the value
  1704. * will be coerced to a string.
  1705. * @return {string} An escaped version of value.
  1706. */
  1707. soy.$$escapeUri = function(value) {
  1708. if (value && value.contentKind === goog.soy.data.SanitizedContentKind.URI) {
  1709. goog.asserts.assert(value.constructor ===
  1710. soydata.SanitizedUri);
  1711. return soy.$$normalizeUri(value);
  1712. }
  1713. // Apostophes and parentheses are not matched by encodeURIComponent.
  1714. // They are technically special in URIs, but only appear in the obsolete mark
  1715. // production in Appendix D.2 of RFC 3986, so can be encoded without changing
  1716. // semantics.
  1717. var encoded = soy.esc.$$escapeUriHelper(value);
  1718. soy.$$problematicUriMarks_.lastIndex = 0;
  1719. if (soy.$$problematicUriMarks_.test(encoded)) {
  1720. return encoded.replace(soy.$$problematicUriMarks_, soy.$$pctEncode_);
  1721. }
  1722. return encoded;
  1723. };
  1724. /**
  1725. * Removes rough edges from a URI by escaping any raw HTML/JS string delimiters.
  1726. *
  1727. * @param {*} value The value to escape. May not be a string, but the value
  1728. * will be coerced to a string.
  1729. * @return {string} An escaped version of value.
  1730. */
  1731. soy.$$normalizeUri = function(value) {
  1732. return soy.esc.$$normalizeUriHelper(value);
  1733. };
  1734. /**
  1735. * Vets a URI's protocol and removes rough edges from a URI by escaping
  1736. * any raw HTML/JS string delimiters.
  1737. *
  1738. * @param {*} value The value to escape. May not be a string, but the value
  1739. * will be coerced to a string.
  1740. * @return {string} An escaped version of value.
  1741. */
  1742. soy.$$filterNormalizeUri = function(value) {
  1743. if (value && value.contentKind == goog.soy.data.SanitizedContentKind.URI) {
  1744. goog.asserts.assert(value.constructor ===
  1745. soydata.SanitizedUri);
  1746. return soy.$$normalizeUri(value);
  1747. }
  1748. return soy.esc.$$filterNormalizeUriHelper(value);
  1749. };
  1750. /**
  1751. * Escapes a string so it can safely be included inside a quoted CSS string.
  1752. *
  1753. * @param {*} value The value to escape. May not be a string, but the value
  1754. * will be coerced to a string.
  1755. * @return {string} An escaped version of value.
  1756. */
  1757. soy.$$escapeCssString = function(value) {
  1758. return soy.esc.$$escapeCssStringHelper(value);
  1759. };
  1760. /**
  1761. * Encodes a value as a CSS identifier part, keyword, or quantity.
  1762. *
  1763. * @param {*} value The value to escape. May not be a string, but the value
  1764. * will be coerced to a string.
  1765. * @return {string} A safe CSS identifier part, keyword, or quanitity.
  1766. */
  1767. soy.$$filterCssValue = function(value) {
  1768. if (value && value.contentKind === goog.soy.data.SanitizedContentKind.CSS) {
  1769. goog.asserts.assert(value.constructor ===
  1770. soydata.SanitizedCss);
  1771. return value.content;
  1772. }
  1773. // Uses == to intentionally match null and undefined for Java compatibility.
  1774. if (value == null) {
  1775. return '';
  1776. }
  1777. return soy.esc.$$filterCssValueHelper(value);
  1778. };
  1779. /**
  1780. * Sanity-checks noAutoescape input for explicitly tainted content.
  1781. *
  1782. * SanitizedContentKind.TEXT is used to explicitly mark input that was never
  1783. * meant to be used unescaped.
  1784. *
  1785. * @param {*} value The value to filter.
  1786. * @return {string} The value, that we dearly hope will not cause an attack.
  1787. */
  1788. soy.$$filterNoAutoescape = function(value) {
  1789. if (value && value.contentKind === goog.soy.data.SanitizedContentKind.TEXT) {
  1790. // Fail in development mode.
  1791. goog.asserts.fail(
  1792. 'Tainted SanitizedContentKind.TEXT for |noAutoescape: `%s`',
  1793. [value.content]);
  1794. // Return innocuous data in production.
  1795. return 'zSoyz';
  1796. }
  1797. return String(value);
  1798. };
  1799. // -----------------------------------------------------------------------------
  1800. // Basic directives/functions.
  1801. /**
  1802. * Converts \r\n, \r, and \n to <br>s
  1803. * @param {*} str The string in which to convert newlines.
  1804. * @return {string} A copy of {@code str} with converted newlines.
  1805. */
  1806. soy.$$changeNewlineToBr = function(str) {
  1807. return goog.string.newLineToBr(String(str), false);
  1808. };
  1809. /**
  1810. * Inserts word breaks ('wbr' tags) into a HTML string at a given interval. The
  1811. * counter is reset if a space is encountered. Word breaks aren't inserted into
  1812. * HTML tags or entities. Entites count towards the character count; HTML tags
  1813. * do not.
  1814. *
  1815. * @param {*} str The HTML string to insert word breaks into. Can be other
  1816. * types, but the value will be coerced to a string.
  1817. * @param {number} maxCharsBetweenWordBreaks Maximum number of non-space
  1818. * characters to allow before adding a word break.
  1819. * @return {string} The string including word breaks.
  1820. */
  1821. soy.$$insertWordBreaks = function(str, maxCharsBetweenWordBreaks) {
  1822. return goog.format.insertWordBreaks(String(str), maxCharsBetweenWordBreaks);
  1823. };
  1824. /**
  1825. * Truncates a string to a given max length (if it's currently longer),
  1826. * optionally adding ellipsis at the end.
  1827. *
  1828. * @param {*} str The string to truncate. Can be other types, but the value will
  1829. * be coerced to a string.
  1830. * @param {number} maxLen The maximum length of the string after truncation
  1831. * (including ellipsis, if applicable).
  1832. * @param {boolean} doAddEllipsis Whether to add ellipsis if the string needs
  1833. * truncation.
  1834. * @return {string} The string after truncation.
  1835. */
  1836. soy.$$truncate = function(str, maxLen, doAddEllipsis) {
  1837. str = String(str);
  1838. if (str.length <= maxLen) {
  1839. return str; // no need to truncate
  1840. }
  1841. // If doAddEllipsis, either reduce maxLen to compensate, or else if maxLen is
  1842. // too small, just turn off doAddEllipsis.
  1843. if (doAddEllipsis) {
  1844. if (maxLen > 3) {
  1845. maxLen -= 3;
  1846. } else {
  1847. doAddEllipsis = false;
  1848. }
  1849. }
  1850. // Make sure truncating at maxLen doesn't cut up a unicode surrogate pair.
  1851. if (soy.$$isHighSurrogate_(str.charAt(maxLen - 1)) &&
  1852. soy.$$isLowSurrogate_(str.charAt(maxLen))) {
  1853. maxLen -= 1;
  1854. }
  1855. // Truncate.
  1856. str = str.substring(0, maxLen);
  1857. // Add ellipsis.
  1858. if (doAddEllipsis) {
  1859. str += '...';
  1860. }
  1861. return str;
  1862. };
  1863. /**
  1864. * Private helper for $$truncate() to check whether a char is a high surrogate.
  1865. * @param {string} ch The char to check.
  1866. * @return {boolean} Whether the given char is a unicode high surrogate.
  1867. * @private
  1868. */
  1869. soy.$$isHighSurrogate_ = function(ch) {
  1870. return 0xD800 <= ch && ch <= 0xDBFF;
  1871. };
  1872. /**
  1873. * Private helper for $$truncate() to check whether a char is a low surrogate.
  1874. * @param {string} ch The char to check.
  1875. * @return {boolean} Whether the given char is a unicode low surrogate.
  1876. * @private
  1877. */
  1878. soy.$$isLowSurrogate_ = function(ch) {
  1879. return 0xDC00 <= ch && ch <= 0xDFFF;
  1880. };
  1881. // -----------------------------------------------------------------------------
  1882. // Bidi directives/functions.
  1883. /**
  1884. * Cache of bidi formatter by context directionality, so we don't keep on
  1885. * creating new objects.
  1886. * @type {!Object.<!goog.i18n.BidiFormatter>}
  1887. * @private
  1888. */
  1889. soy.$$bidiFormatterCache_ = {};
  1890. /**
  1891. * Returns cached bidi formatter for bidiGlobalDir, or creates a new one.
  1892. * @param {number} bidiGlobalDir The global directionality context: 1 if ltr, -1
  1893. * if rtl, 0 if unknown.
  1894. * @return {goog.i18n.BidiFormatter} A formatter for bidiGlobalDir.
  1895. * @private
  1896. */
  1897. soy.$$getBidiFormatterInstance_ = function(bidiGlobalDir) {
  1898. return soy.$$bidiFormatterCache_[bidiGlobalDir] ||
  1899. (soy.$$bidiFormatterCache_[bidiGlobalDir] =
  1900. new goog.i18n.BidiFormatter(bidiGlobalDir));
  1901. };
  1902. /**
  1903. * Estimate the overall directionality of text. If opt_isHtml, makes sure to
  1904. * ignore the LTR nature of the mark-up and escapes in text, making the logic
  1905. * suitable for HTML and HTML-escaped text.
  1906. * @param {string} text The text whose directionality is to be estimated.
  1907. * @param {boolean=} opt_isHtml Whether text is HTML/HTML-escaped.
  1908. * Default: false.
  1909. * @return {number} 1 if text is LTR, -1 if it is RTL, and 0 if it is neutral.
  1910. */
  1911. soy.$$bidiTextDir = function(text, opt_isHtml) {
  1912. if (!text) {
  1913. return 0;
  1914. }
  1915. return goog.i18n.bidi.detectRtlDirectionality(text, opt_isHtml) ? -1 : 1;
  1916. };
  1917. /**
  1918. * Returns 'dir="ltr"' or 'dir="rtl"', depending on text's estimated
  1919. * directionality, if it is not the same as bidiGlobalDir.
  1920. * Otherwise, returns the empty string.
  1921. * If opt_isHtml, makes sure to ignore the LTR nature of the mark-up and escapes
  1922. * in text, making the logic suitable for HTML and HTML-escaped text.
  1923. * @param {number} bidiGlobalDir The global directionality context: 1 if ltr, -1
  1924. * if rtl, 0 if unknown.
  1925. * @param {string} text The text whose directionality is to be estimated.
  1926. * @param {boolean=} opt_isHtml Whether text is HTML/HTML-escaped.
  1927. * Default: false.
  1928. * @return {soydata.SanitizedHtmlAttribute} 'dir="rtl"' for RTL text in non-RTL
  1929. * context; 'dir="ltr"' for LTR text in non-LTR context;
  1930. * else, the empty string.
  1931. */
  1932. soy.$$bidiDirAttr = function(bidiGlobalDir, text, opt_isHtml) {
  1933. return soydata.VERY_UNSAFE.ordainSanitizedHtmlAttribute(
  1934. soy.$$getBidiFormatterInstance_(bidiGlobalDir).dirAttr(text, opt_isHtml));
  1935. };
  1936. /**
  1937. * Returns a Unicode BiDi mark matching bidiGlobalDir (LRM or RLM) if the
  1938. * directionality or the exit directionality of text are opposite to
  1939. * bidiGlobalDir. Otherwise returns the empty string.
  1940. * If opt_isHtml, makes sure to ignore the LTR nature of the mark-up and escapes
  1941. * in text, making the logic suitable for HTML and HTML-escaped text.
  1942. * @param {number} bidiGlobalDir The global directionality context: 1 if ltr, -1
  1943. * if rtl, 0 if unknown.
  1944. * @param {string} text The text whose directionality is to be estimated.
  1945. * @param {boolean=} opt_isHtml Whether text is HTML/HTML-escaped.
  1946. * Default: false.
  1947. * @return {string} A Unicode bidi mark matching bidiGlobalDir, or the empty
  1948. * string when text's overall and exit directionalities both match
  1949. * bidiGlobalDir, or bidiGlobalDir is 0 (unknown).
  1950. */
  1951. soy.$$bidiMarkAfter = function(bidiGlobalDir, text, opt_isHtml) {
  1952. var formatter = soy.$$getBidiFormatterInstance_(bidiGlobalDir);
  1953. return formatter.markAfter(text, opt_isHtml);
  1954. };
  1955. /**
  1956. * Returns str wrapped in a <span dir="ltr|rtl"> according to its directionality
  1957. * - but only if that is neither neutral nor the same as the global context.
  1958. * Otherwise, returns str unchanged.
  1959. * Always treats str as HTML/HTML-escaped, i.e. ignores mark-up and escapes when
  1960. * estimating str's directionality.
  1961. * @param {number} bidiGlobalDir The global directionality context: 1 if ltr, -1
  1962. * if rtl, 0 if unknown.
  1963. * @param {*} str The string to be wrapped. Can be other types, but the value
  1964. * will be coerced to a string.
  1965. * @return {string} The wrapped string.
  1966. */
  1967. soy.$$bidiSpanWrap = function(bidiGlobalDir, str) {
  1968. var formatter = soy.$$getBidiFormatterInstance_(bidiGlobalDir);
  1969. return formatter.spanWrap(str + '', true);
  1970. };
  1971. /**
  1972. * Returns str wrapped in Unicode BiDi formatting characters according to its
  1973. * directionality, i.e. either LRE or RLE at the beginning and PDF at the end -
  1974. * but only if str's directionality is neither neutral nor the same as the
  1975. * global context. Otherwise, returns str unchanged.
  1976. * Always treats str as HTML/HTML-escaped, i.e. ignores mark-up and escapes when
  1977. * estimating str's directionality.
  1978. * @param {number} bidiGlobalDir The global directionality context: 1 if ltr, -1
  1979. * if rtl, 0 if unknown.
  1980. * @param {*} str The string to be wrapped. Can be other types, but the value
  1981. * will be coerced to a string.
  1982. * @return {string} The wrapped string.
  1983. */
  1984. soy.$$bidiUnicodeWrap = function(bidiGlobalDir, str) {
  1985. var formatter = soy.$$getBidiFormatterInstance_(bidiGlobalDir);
  1986. return formatter.unicodeWrap(str + '', true);
  1987. };
  1988. // -----------------------------------------------------------------------------
  1989. // Generated code.
  1990. // START GENERATED CODE FOR ESCAPERS.
  1991. /**
  1992. * @type {function (*) : string}
  1993. */
  1994. soy.esc.$$escapeUriHelper = function(v) {
  1995. return encodeURIComponent(String(v));
  1996. };
  1997. /**
  1998. * Maps charcters to the escaped versions for the named escape directives.
  1999. * @type {Object.<string, string>}
  2000. * @private
  2001. */
  2002. soy.esc.$$ESCAPE_MAP_FOR_ESCAPE_HTML__AND__NORMALIZE_HTML__AND__ESCAPE_HTML_NOSPACE__AND__NORMALIZE_HTML_NOSPACE_ = {
  2003. '\x00': '\x26#0;',
  2004. '\x22': '\x26quot;',
  2005. '\x26': '\x26amp;',
  2006. '\x27': '\x26#39;',
  2007. '\x3c': '\x26lt;',
  2008. '\x3e': '\x26gt;',
  2009. '\x09': '\x26#9;',
  2010. '\x0a': '\x26#10;',
  2011. '\x0b': '\x26#11;',
  2012. '\x0c': '\x26#12;',
  2013. '\x0d': '\x26#13;',
  2014. ' ': '\x26#32;',
  2015. '-': '\x26#45;',
  2016. '\/': '\x26#47;',
  2017. '\x3d': '\x26#61;',
  2018. '`': '\x26#96;',
  2019. '\x85': '\x26#133;',
  2020. '\xa0': '\x26#160;',
  2021. '\u2028': '\x26#8232;',
  2022. '\u2029': '\x26#8233;'
  2023. };
  2024. /**
  2025. * A function that can be used with String.replace..
  2026. * @param {string} ch A single character matched by a compatible matcher.
  2027. * @return {string} A token in the output language.
  2028. * @private
  2029. */
  2030. soy.esc.$$REPLACER_FOR_ESCAPE_HTML__AND__NORMALIZE_HTML__AND__ESCAPE_HTML_NOSPACE__AND__NORMALIZE_HTML_NOSPACE_ = function(ch) {
  2031. return soy.esc.$$ESCAPE_MAP_FOR_ESCAPE_HTML__AND__NORMALIZE_HTML__AND__ESCAPE_HTML_NOSPACE__AND__NORMALIZE_HTML_NOSPACE_[ch];
  2032. };
  2033. /**
  2034. * Maps charcters to the escaped versions for the named escape directives.
  2035. * @type {Object.<string, string>}
  2036. * @private
  2037. */
  2038. soy.esc.$$ESCAPE_MAP_FOR_ESCAPE_JS_STRING__AND__ESCAPE_JS_REGEX_ = {
  2039. '\x00': '\\x00',
  2040. '\x08': '\\x08',
  2041. '\x09': '\\t',
  2042. '\x0a': '\\n',
  2043. '\x0b': '\\x0b',
  2044. '\x0c': '\\f',
  2045. '\x0d': '\\r',
  2046. '\x22': '\\x22',
  2047. '\x26': '\\x26',
  2048. '\x27': '\\x27',
  2049. '\/': '\\\/',
  2050. '\x3c': '\\x3c',
  2051. '\x3d': '\\x3d',
  2052. '\x3e': '\\x3e',
  2053. '\\': '\\\\',
  2054. '\x85': '\\x85',
  2055. '\u2028': '\\u2028',
  2056. '\u2029': '\\u2029',
  2057. '$': '\\x24',
  2058. '(': '\\x28',
  2059. ')': '\\x29',
  2060. '*': '\\x2a',
  2061. '+': '\\x2b',
  2062. ',': '\\x2c',
  2063. '-': '\\x2d',
  2064. '.': '\\x2e',
  2065. ':': '\\x3a',
  2066. '?': '\\x3f',
  2067. '[': '\\x5b',
  2068. ']': '\\x5d',
  2069. '^': '\\x5e',
  2070. '{': '\\x7b',
  2071. '|': '\\x7c',
  2072. '}': '\\x7d'
  2073. };
  2074. /**
  2075. * A function that can be used with String.replace..
  2076. * @param {string} ch A single character matched by a compatible matcher.
  2077. * @return {string} A token in the output language.
  2078. * @private
  2079. */
  2080. soy.esc.$$REPLACER_FOR_ESCAPE_JS_STRING__AND__ESCAPE_JS_REGEX_ = function(ch) {
  2081. return soy.esc.$$ESCAPE_MAP_FOR_ESCAPE_JS_STRING__AND__ESCAPE_JS_REGEX_[ch];
  2082. };
  2083. /**
  2084. * Maps charcters to the escaped versions for the named escape directives.
  2085. * @type {Object.<string, string>}
  2086. * @private
  2087. */
  2088. soy.esc.$$ESCAPE_MAP_FOR_ESCAPE_CSS_STRING_ = {
  2089. '\x00': '\\0 ',
  2090. '\x08': '\\8 ',
  2091. '\x09': '\\9 ',
  2092. '\x0a': '\\a ',
  2093. '\x0b': '\\b ',
  2094. '\x0c': '\\c ',
  2095. '\x0d': '\\d ',
  2096. '\x22': '\\22 ',
  2097. '\x26': '\\26 ',
  2098. '\x27': '\\27 ',
  2099. '(': '\\28 ',
  2100. ')': '\\29 ',
  2101. '*': '\\2a ',
  2102. '\/': '\\2f ',
  2103. ':': '\\3a ',
  2104. ';': '\\3b ',
  2105. '\x3c': '\\3c ',
  2106. '\x3d': '\\3d ',
  2107. '\x3e': '\\3e ',
  2108. '@': '\\40 ',
  2109. '\\': '\\5c ',
  2110. '{': '\\7b ',
  2111. '}': '\\7d ',
  2112. '\x85': '\\85 ',
  2113. '\xa0': '\\a0 ',
  2114. '\u2028': '\\2028 ',
  2115. '\u2029': '\\2029 '
  2116. };
  2117. /**
  2118. * A function that can be used with String.replace..
  2119. * @param {string} ch A single character matched by a compatible matcher.
  2120. * @return {string} A token in the output language.
  2121. * @private
  2122. */
  2123. soy.esc.$$REPLACER_FOR_ESCAPE_CSS_STRING_ = function(ch) {
  2124. return soy.esc.$$ESCAPE_MAP_FOR_ESCAPE_CSS_STRING_[ch];
  2125. };
  2126. /**
  2127. * Maps charcters to the escaped versions for the named escape directives.
  2128. * @type {Object.<string, string>}
  2129. * @private
  2130. */
  2131. soy.esc.$$ESCAPE_MAP_FOR_NORMALIZE_URI__AND__FILTER_NORMALIZE_URI_ = {
  2132. '\x00': '%00',
  2133. '\x01': '%01',
  2134. '\x02': '%02',
  2135. '\x03': '%03',
  2136. '\x04': '%04',
  2137. '\x05': '%05',
  2138. '\x06': '%06',
  2139. '\x07': '%07',
  2140. '\x08': '%08',
  2141. '\x09': '%09',
  2142. '\x0a': '%0A',
  2143. '\x0b': '%0B',
  2144. '\x0c': '%0C',
  2145. '\x0d': '%0D',
  2146. '\x0e': '%0E',
  2147. '\x0f': '%0F',
  2148. '\x10': '%10',
  2149. '\x11': '%11',
  2150. '\x12': '%12',
  2151. '\x13': '%13',
  2152. '\x14': '%14',
  2153. '\x15': '%15',
  2154. '\x16': '%16',
  2155. '\x17': '%17',
  2156. '\x18': '%18',
  2157. '\x19': '%19',
  2158. '\x1a': '%1A',
  2159. '\x1b': '%1B',
  2160. '\x1c': '%1C',
  2161. '\x1d': '%1D',
  2162. '\x1e': '%1E',
  2163. '\x1f': '%1F',
  2164. ' ': '%20',
  2165. '\x22': '%22',
  2166. '\x27': '%27',
  2167. '(': '%28',
  2168. ')': '%29',
  2169. '\x3c': '%3C',
  2170. '\x3e': '%3E',
  2171. '\\': '%5C',
  2172. '{': '%7B',
  2173. '}': '%7D',
  2174. '\x7f': '%7F',
  2175. '\x85': '%C2%85',
  2176. '\xa0': '%C2%A0',
  2177. '\u2028': '%E2%80%A8',
  2178. '\u2029': '%E2%80%A9',
  2179. '\uff01': '%EF%BC%81',
  2180. '\uff03': '%EF%BC%83',
  2181. '\uff04': '%EF%BC%84',
  2182. '\uff06': '%EF%BC%86',
  2183. '\uff07': '%EF%BC%87',
  2184. '\uff08': '%EF%BC%88',
  2185. '\uff09': '%EF%BC%89',
  2186. '\uff0a': '%EF%BC%8A',
  2187. '\uff0b': '%EF%BC%8B',
  2188. '\uff0c': '%EF%BC%8C',
  2189. '\uff0f': '%EF%BC%8F',
  2190. '\uff1a': '%EF%BC%9A',
  2191. '\uff1b': '%EF%BC%9B',
  2192. '\uff1d': '%EF%BC%9D',
  2193. '\uff1f': '%EF%BC%9F',
  2194. '\uff20': '%EF%BC%A0',
  2195. '\uff3b': '%EF%BC%BB',
  2196. '\uff3d': '%EF%BC%BD'
  2197. };
  2198. /**
  2199. * A function that can be used with String.replace..
  2200. * @param {string} ch A single character matched by a compatible matcher.
  2201. * @return {string} A token in the output language.
  2202. * @private
  2203. */
  2204. soy.esc.$$REPLACER_FOR_NORMALIZE_URI__AND__FILTER_NORMALIZE_URI_ = function(ch) {
  2205. return soy.esc.$$ESCAPE_MAP_FOR_NORMALIZE_URI__AND__FILTER_NORMALIZE_URI_[ch];
  2206. };
  2207. /**
  2208. * Matches characters that need to be escaped for the named directives.
  2209. * @type RegExp
  2210. * @private
  2211. */
  2212. soy.esc.$$MATCHER_FOR_ESCAPE_HTML_ = /[\x00\x22\x26\x27\x3c\x3e]/g;
  2213. /**
  2214. * Matches characters that need to be escaped for the named directives.
  2215. * @type RegExp
  2216. * @private
  2217. */
  2218. soy.esc.$$MATCHER_FOR_NORMALIZE_HTML_ = /[\x00\x22\x27\x3c\x3e]/g;
  2219. /**
  2220. * Matches characters that need to be escaped for the named directives.
  2221. * @type RegExp
  2222. * @private
  2223. */
  2224. soy.esc.$$MATCHER_FOR_ESCAPE_HTML_NOSPACE_ = /[\x00\x09-\x0d \x22\x26\x27\x2d\/\x3c-\x3e`\x85\xa0\u2028\u2029]/g;
  2225. /**
  2226. * Matches characters that need to be escaped for the named directives.
  2227. * @type RegExp
  2228. * @private
  2229. */
  2230. soy.esc.$$MATCHER_FOR_NORMALIZE_HTML_NOSPACE_ = /[\x00\x09-\x0d \x22\x27\x2d\/\x3c-\x3e`\x85\xa0\u2028\u2029]/g;
  2231. /**
  2232. * Matches characters that need to be escaped for the named directives.
  2233. * @type RegExp
  2234. * @private
  2235. */
  2236. soy.esc.$$MATCHER_FOR_ESCAPE_JS_STRING_ = /[\x00\x08-\x0d\x22\x26\x27\/\x3c-\x3e\\\x85\u2028\u2029]/g;
  2237. /**
  2238. * Matches characters that need to be escaped for the named directives.
  2239. * @type RegExp
  2240. * @private
  2241. */
  2242. soy.esc.$$MATCHER_FOR_ESCAPE_JS_REGEX_ = /[\x00\x08-\x0d\x22\x24\x26-\/\x3a\x3c-\x3f\x5b-\x5e\x7b-\x7d\x85\u2028\u2029]/g;
  2243. /**
  2244. * Matches characters that need to be escaped for the named directives.
  2245. * @type RegExp
  2246. * @private
  2247. */
  2248. soy.esc.$$MATCHER_FOR_ESCAPE_CSS_STRING_ = /[\x00\x08-\x0d\x22\x26-\x2a\/\x3a-\x3e@\\\x7b\x7d\x85\xa0\u2028\u2029]/g;
  2249. /**
  2250. * Matches characters that need to be escaped for the named directives.
  2251. * @type RegExp
  2252. * @private
  2253. */
  2254. soy.esc.$$MATCHER_FOR_NORMALIZE_URI__AND__FILTER_NORMALIZE_URI_ = /[\x00- \x22\x27-\x29\x3c\x3e\\\x7b\x7d\x7f\x85\xa0\u2028\u2029\uff01\uff03\uff04\uff06-\uff0c\uff0f\uff1a\uff1b\uff1d\uff1f\uff20\uff3b\uff3d]/g;
  2255. /**
  2256. * A pattern that vets values produced by the named directives.
  2257. * @type RegExp
  2258. * @private
  2259. */
  2260. soy.esc.$$FILTER_FOR_FILTER_CSS_VALUE_ = /^(?!-*(?:expression|(?:moz-)?binding))(?:[.#]?-?(?:[_a-z0-9-]+)(?:-[_a-z0-9-]+)*-?|-?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[a-z]{1,2}|%)?|!important|)$/i;
  2261. /**
  2262. * A pattern that vets values produced by the named directives.
  2263. * @type RegExp
  2264. * @private
  2265. */
  2266. soy.esc.$$FILTER_FOR_FILTER_NORMALIZE_URI_ = /^(?:(?:https?|mailto):|[^&:\/?#]*(?:[\/?#]|$))/i;
  2267. /**
  2268. * A pattern that vets values produced by the named directives.
  2269. * @type RegExp
  2270. * @private
  2271. */
  2272. soy.esc.$$FILTER_FOR_FILTER_HTML_ATTRIBUTES_ = /^(?!style|on|action|archive|background|cite|classid|codebase|data|dsync|href|longdesc|src|usemap)(?:[a-z0-9_$:-]*)$/i;
  2273. /**
  2274. * A pattern that vets values produced by the named directives.
  2275. * @type RegExp
  2276. * @private
  2277. */
  2278. soy.esc.$$FILTER_FOR_FILTER_HTML_ELEMENT_NAME_ = /^(?!script|style|title|textarea|xmp|no)[a-z0-9_$:-]*$/i;
  2279. /**
  2280. * A helper for the Soy directive |escapeHtml
  2281. * @param {*} value Can be of any type but will be coerced to a string.
  2282. * @return {string} The escaped text.
  2283. */
  2284. soy.esc.$$escapeHtmlHelper = function(value) {
  2285. var str = String(value);
  2286. return str.replace(
  2287. soy.esc.$$MATCHER_FOR_ESCAPE_HTML_,
  2288. soy.esc.$$REPLACER_FOR_ESCAPE_HTML__AND__NORMALIZE_HTML__AND__ESCAPE_HTML_NOSPACE__AND__NORMALIZE_HTML_NOSPACE_);
  2289. };
  2290. /**
  2291. * A helper for the Soy directive |normalizeHtml
  2292. * @param {*} value Can be of any type but will be coerced to a string.
  2293. * @return {string} The escaped text.
  2294. */
  2295. soy.esc.$$normalizeHtmlHelper = function(value) {
  2296. var str = String(value);
  2297. return str.replace(
  2298. soy.esc.$$MATCHER_FOR_NORMALIZE_HTML_,
  2299. soy.esc.$$REPLACER_FOR_ESCAPE_HTML__AND__NORMALIZE_HTML__AND__ESCAPE_HTML_NOSPACE__AND__NORMALIZE_HTML_NOSPACE_);
  2300. };
  2301. /**
  2302. * A helper for the Soy directive |escapeHtmlNospace
  2303. * @param {*} value Can be of any type but will be coerced to a string.
  2304. * @return {string} The escaped text.
  2305. */
  2306. soy.esc.$$escapeHtmlNospaceHelper = function(value) {
  2307. var str = String(value);
  2308. return str.replace(
  2309. soy.esc.$$MATCHER_FOR_ESCAPE_HTML_NOSPACE_,
  2310. soy.esc.$$REPLACER_FOR_ESCAPE_HTML__AND__NORMALIZE_HTML__AND__ESCAPE_HTML_NOSPACE__AND__NORMALIZE_HTML_NOSPACE_);
  2311. };
  2312. /**
  2313. * A helper for the Soy directive |normalizeHtmlNospace
  2314. * @param {*} value Can be of any type but will be coerced to a string.
  2315. * @return {string} The escaped text.
  2316. */
  2317. soy.esc.$$normalizeHtmlNospaceHelper = function(value) {
  2318. var str = String(value);
  2319. return str.replace(
  2320. soy.esc.$$MATCHER_FOR_NORMALIZE_HTML_NOSPACE_,
  2321. soy.esc.$$REPLACER_FOR_ESCAPE_HTML__AND__NORMALIZE_HTML__AND__ESCAPE_HTML_NOSPACE__AND__NORMALIZE_HTML_NOSPACE_);
  2322. };
  2323. /**
  2324. * A helper for the Soy directive |escapeJsString
  2325. * @param {*} value Can be of any type but will be coerced to a string.
  2326. * @return {string} The escaped text.
  2327. */
  2328. soy.esc.$$escapeJsStringHelper = function(value) {
  2329. var str = String(value);
  2330. return str.replace(
  2331. soy.esc.$$MATCHER_FOR_ESCAPE_JS_STRING_,
  2332. soy.esc.$$REPLACER_FOR_ESCAPE_JS_STRING__AND__ESCAPE_JS_REGEX_);
  2333. };
  2334. /**
  2335. * A helper for the Soy directive |escapeJsRegex
  2336. * @param {*} value Can be of any type but will be coerced to a string.
  2337. * @return {string} The escaped text.
  2338. */
  2339. soy.esc.$$escapeJsRegexHelper = function(value) {
  2340. var str = String(value);
  2341. return str.replace(
  2342. soy.esc.$$MATCHER_FOR_ESCAPE_JS_REGEX_,
  2343. soy.esc.$$REPLACER_FOR_ESCAPE_JS_STRING__AND__ESCAPE_JS_REGEX_);
  2344. };
  2345. /**
  2346. * A helper for the Soy directive |escapeCssString
  2347. * @param {*} value Can be of any type but will be coerced to a string.
  2348. * @return {string} The escaped text.
  2349. */
  2350. soy.esc.$$escapeCssStringHelper = function(value) {
  2351. var str = String(value);
  2352. return str.replace(
  2353. soy.esc.$$MATCHER_FOR_ESCAPE_CSS_STRING_,
  2354. soy.esc.$$REPLACER_FOR_ESCAPE_CSS_STRING_);
  2355. };
  2356. /**
  2357. * A helper for the Soy directive |filterCssValue
  2358. * @param {*} value Can be of any type but will be coerced to a string.
  2359. * @return {string} The escaped text.
  2360. */
  2361. soy.esc.$$filterCssValueHelper = function(value) {
  2362. var str = String(value);
  2363. if (!soy.esc.$$FILTER_FOR_FILTER_CSS_VALUE_.test(str)) {
  2364. return 'zSoyz';
  2365. }
  2366. return str;
  2367. };
  2368. /**
  2369. * A helper for the Soy directive |normalizeUri
  2370. * @param {*} value Can be of any type but will be coerced to a string.
  2371. * @return {string} The escaped text.
  2372. */
  2373. soy.esc.$$normalizeUriHelper = function(value) {
  2374. var str = String(value);
  2375. return str.replace(
  2376. soy.esc.$$MATCHER_FOR_NORMALIZE_URI__AND__FILTER_NORMALIZE_URI_,
  2377. soy.esc.$$REPLACER_FOR_NORMALIZE_URI__AND__FILTER_NORMALIZE_URI_);
  2378. };
  2379. /**
  2380. * A helper for the Soy directive |filterNormalizeUri
  2381. * @param {*} value Can be of any type but will be coerced to a string.
  2382. * @return {string} The escaped text.
  2383. */
  2384. soy.esc.$$filterNormalizeUriHelper = function(value) {
  2385. var str = String(value);
  2386. if (!soy.esc.$$FILTER_FOR_FILTER_NORMALIZE_URI_.test(str)) {
  2387. return '#zSoyz';
  2388. }
  2389. return str.replace(
  2390. soy.esc.$$MATCHER_FOR_NORMALIZE_URI__AND__FILTER_NORMALIZE_URI_,
  2391. soy.esc.$$REPLACER_FOR_NORMALIZE_URI__AND__FILTER_NORMALIZE_URI_);
  2392. };
  2393. /**
  2394. * A helper for the Soy directive |filterHtmlAttributes
  2395. * @param {*} value Can be of any type but will be coerced to a string.
  2396. * @return {string} The escaped text.
  2397. */
  2398. soy.esc.$$filterHtmlAttributesHelper = function(value) {
  2399. var str = String(value);
  2400. if (!soy.esc.$$FILTER_FOR_FILTER_HTML_ATTRIBUTES_.test(str)) {
  2401. return 'zSoyz';
  2402. }
  2403. return str;
  2404. };
  2405. /**
  2406. * A helper for the Soy directive |filterHtmlElementName
  2407. * @param {*} value Can be of any type but will be coerced to a string.
  2408. * @return {string} The escaped text.
  2409. */
  2410. soy.esc.$$filterHtmlElementNameHelper = function(value) {
  2411. var str = String(value);
  2412. if (!soy.esc.$$FILTER_FOR_FILTER_HTML_ELEMENT_NAME_.test(str)) {
  2413. return 'zSoyz';
  2414. }
  2415. return str;
  2416. };
  2417. /**
  2418. * Matches all tags, HTML comments, and DOCTYPEs in tag soup HTML.
  2419. * By removing these, and replacing any '<' or '>' characters with
  2420. * entities we guarantee that the result can be embedded into a
  2421. * an attribute without introducing a tag boundary.
  2422. *
  2423. * @type {RegExp}
  2424. * @private
  2425. */
  2426. soy.esc.$$HTML_TAG_REGEX_ = /<(?:!|\/?([a-zA-Z][a-zA-Z0-9:\-]*))(?:[^>'"]|"[^"]*"|'[^']*')*>/g;
  2427. /**
  2428. * Matches all occurrences of '<'.
  2429. *
  2430. * @type {RegExp}
  2431. * @private
  2432. */
  2433. soy.esc.$$LT_REGEX_ = /</g;
  2434. /**
  2435. * Maps lower-case names of innocuous tags to 1.
  2436. *
  2437. * @type {Object.<string,number>}
  2438. * @private
  2439. */
  2440. soy.esc.$$SAFE_TAG_WHITELIST_ = {'b': 1, 'br': 1, 'em': 1, 'i': 1, 's': 1, 'sub': 1, 'sup': 1, 'u': 1};
  2441. // END GENERATED CODE