-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathsoyutils_usegoog.js
2590 lines (2326 loc) · 85.7 KB
/
soyutils_usegoog.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview
* Utility functions and classes for Soy gencode
*
* <p>
* This file contains utilities that should only be called by Soy-generated
* JS code. Please do not use these functions directly from
* your hand-written code. Their names all start with '$$', or exist within the
* soydata.VERY_UNSAFE namespace.
*
* <p>TODO(lukes): ensure that the above pattern is actually followed
* consistently.
*
*/
goog.provide('soy');
goog.provide('soy.asserts');
goog.provide('soy.esc');
goog.provide('soydata');
goog.provide('soydata.SanitizedHtml');
goog.provide('soydata.VERY_UNSAFE');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.debug');
goog.require('goog.format');
goog.require('goog.html.SafeHtml');
goog.require('goog.html.SafeScript');
goog.require('goog.html.SafeStyle');
goog.require('goog.html.SafeStyleSheet');
goog.require('goog.html.SafeUrl');
goog.require('goog.html.TrustedResourceUrl');
goog.require('goog.html.uncheckedconversions');
goog.require('goog.i18n.BidiFormatter');
goog.require('goog.i18n.bidi');
goog.require('goog.object');
goog.require('goog.soy.data.SanitizedContent');
goog.require('goog.soy.data.SanitizedContentKind');
goog.require('goog.soy.data.SanitizedCss');
goog.require('goog.soy.data.SanitizedHtml');
goog.require('goog.soy.data.SanitizedHtmlAttribute');
goog.require('goog.soy.data.SanitizedJs');
goog.require('goog.soy.data.SanitizedTrustedResourceUri');
goog.require('goog.soy.data.SanitizedUri');
goog.require('goog.string');
goog.require('goog.string.Const');
goog.require('soy.checks');
goog.require('goog.soy');
// -----------------------------------------------------------------------------
// soydata: Defines typed strings, e.g. an HTML string `"a<b>c"` is
// semantically distinct from the plain text string `"a<b>c"` and smart
// templates can take that distinction into account.
/**
* Properties added to all idom HTML / Attributes functions. The TypeScript type
* inherits this and adds a call signature (which is not really possible here).
* @typedef {{
* toString: function(),
* contentKind: !goog.soy.data.SanitizedContentKind
* }}
*/
soydata.IdomFunctionMembers;
/** @typedef {!soydata.IdomFunctionMembers|!Function} */
soydata.IdomFunction;
/**
* Checks whether a given value is of a given content kind.
*
* @param {?} value The value to be examined.
* @param {!goog.soy.data.SanitizedContentKind} contentKind The desired content
* kind.
* @return {boolean} Whether the given value is of the given kind.
* @private
*/
soydata.isContentKind_ = function(value, contentKind) {
// TODO(user): This function should really include the assert on
// value.constructor that is currently sprinkled at most of the call sites.
// Unfortunately, that would require a (debug-mode-only) switch statement.
// TODO(user): Perhaps we should get rid of the contentKind property
// altogether and only at the constructor.
return value != null && value.contentKind === contentKind;
};
/**
* Returns a given value's contentDir property, constrained to a
* goog.i18n.bidi.Dir value or null. Returns null if the value is null,
* undefined, a primitive or does not have a contentDir property, or the
* property's value is not 1 (for LTR), -1 (for RTL), or 0 (for neutral).
*
* @param {?} value The value whose contentDir property, if any, is to
* be returned.
* @return {?goog.i18n.bidi.Dir} The contentDir property.
*/
soydata.getContentDir = function(value) {
if (value != null) {
switch (value.contentDir) {
case goog.i18n.bidi.Dir.LTR:
return goog.i18n.bidi.Dir.LTR;
case goog.i18n.bidi.Dir.RTL:
return goog.i18n.bidi.Dir.RTL;
case goog.i18n.bidi.Dir.NEUTRAL:
return goog.i18n.bidi.Dir.NEUTRAL;
}
}
return null;
};
/**
* This class is only a holder for `soydata.SanitizedHtml.from`. Do not
* instantiate or extend it. Use `goog.soy.data.SanitizedHtml` instead.
*
* @constructor
* @extends {goog.soy.data.SanitizedHtml}
* @abstract
*/
soydata.SanitizedHtml = function() {
soydata.SanitizedHtml.base(this, 'constructor'); // Throws an exception.
};
goog.inherits(soydata.SanitizedHtml, goog.soy.data.SanitizedHtml);
/**
* Returns a SanitizedHtml object for a particular value. The content direction
* is preserved.
*
* This HTML-escapes the value unless it is already SanitizedHtml or SafeHtml.
*
* @param {?} value The value to convert. If it is already a SanitizedHtml
* object, it is left alone.
* @return {!goog.soy.data.SanitizedHtml} A SanitizedHtml object derived from
* the stringified value. It is escaped unless the input is SanitizedHtml or
* SafeHtml.
*/
soydata.SanitizedHtml.from = function(value) {
// The check is soydata.isContentKind_() inlined for performance.
if (soy.checks.isHtml(value)) {
return /** @type {!goog.soy.data.SanitizedHtml} */ (value);
}
if (value instanceof goog.html.SafeHtml) {
return soydata.VERY_UNSAFE.ordainSanitizedHtml(
goog.html.SafeHtml.unwrap(value), value.getDirection());
}
return soydata.VERY_UNSAFE.ordainSanitizedHtml(
soy.esc.$$escapeHtmlHelper(String(value)), soydata.getContentDir(value));
};
/**
* Empty string, used as a type in Soy templates.
* @enum {string}
* @private
*/
soydata.$$EMPTY_STRING_ = {
VALUE: ''
};
/**
* Creates a factory for SanitizedContent types.
*
* This is a hack so that the soydata.VERY_UNSAFE.ordainSanitized* can
* instantiate Sanitized* classes, without making the Sanitized* constructors
* publicly usable. Requiring all construction to use the VERY_UNSAFE names
* helps callers and their reviewers easily tell that creating SanitizedContent
* is not always safe and calls for careful review.
*
* @param {function(new: T)} ctor A constructor.
* @return {function(*, ?goog.i18n.bidi.Dir=): T} A factory that takes
* content and an optional content direction and returns a new instance. If
* the content direction is undefined, ctor.prototype.contentDir is used.
* @template T
* @private
*/
soydata.$$makeSanitizedContentFactory_ = function(ctor) {
/**
* @param {string} content
* @constructor
* @extends {goog.soy.data.SanitizedContent}
*/
function InstantiableCtor(content) {
/** @override */
this.content = content;
}
InstantiableCtor.prototype = ctor.prototype;
/**
* Creates a ctor-type SanitizedContent instance.
*
* @param {?} content The content to put in the instance.
* @param {?goog.i18n.bidi.Dir=} opt_contentDir The content direction. If
* undefined, ctor.prototype.contentDir is used.
* @return {!goog.soy.data.SanitizedContent} The new instance. It is actually
* of type T above (ctor's type, a descendant of SanitizedContent), but
* there is no way to express that here.
*/
function sanitizedContentFactory(content, opt_contentDir) {
var result = new InstantiableCtor(String(content));
if (opt_contentDir !== undefined) {
result.contentDir = opt_contentDir;
}
return result;
}
return sanitizedContentFactory;
};
/**
* Creates a factory for SanitizedContent types that should always have their
* default directionality.
*
* This is a hack so that the soydata.VERY_UNSAFE.ordainSanitized* can
* instantiate Sanitized* classes, without making the Sanitized* constructors
* publicly usable. Requiring all construction to use the VERY_UNSAFE names
* helps callers and their reviewers easily tell that creating SanitizedContent
* is not always safe and calls for careful review.
*
* @param {function(new: T, string)} ctor A constructor.
* @return {function(*): T} A factory that takes content and returns a new
* instance (with default directionality, i.e. ctor.prototype.contentDir).
* @template T
* @private
*/
soydata.$$makeSanitizedContentFactoryWithDefaultDirOnly_ = function(ctor) {
/**
* @param {string} content
* @constructor
* @extends {goog.soy.data.SanitizedContent}
*/
function InstantiableCtor(content) {
/** @override */
this.content = content;
}
InstantiableCtor.prototype = ctor.prototype;
/**
* Creates a ctor-type SanitizedContent instance.
*
* @param {?} content The content to put in the instance.
* @return {!goog.soy.data.SanitizedContent} The new instance. It is actually
* of type T above (ctor's type, a descendant of SanitizedContent), but
* there is no way to express that here.
*/
function sanitizedContentFactory(content) {
var result = new InstantiableCtor(String(content));
return result;
}
return sanitizedContentFactory;
};
// -----------------------------------------------------------------------------
// Sanitized content ordainers. Please use these with extreme caution. A good
// recommendation is to limit usage of these to just a handful of files in your
// source tree where usages can be carefully audited.
/**
* Takes a leap of faith that the provided content is "safe" HTML.
*
* @param {?} content A string of HTML that can safely be embedded in
* a PCDATA context in your app. If you would be surprised to find that an
* HTML sanitizer produced `s` (e.g. it runs code or fetches bad URLs)
* and you wouldn't write a template that produces `s` on security or
* privacy grounds, then don't pass `s` here.
* @param {?goog.i18n.bidi.Dir=} opt_contentDir The content direction; null if
* unknown and thus to be estimated when necessary. Default: null.
* @return {!goog.soy.data.SanitizedHtml} Sanitized content wrapper that
* indicates to Soy not to escape when printed as HTML.
*/
soydata.VERY_UNSAFE.ordainSanitizedHtml =
soydata.$$makeSanitizedContentFactory_(goog.soy.data.SanitizedHtml);
/**
* Takes a leap of faith that the provided content is "safe" (non-attacker-
* controlled, XSS-free) Javascript.
*
* @param {?} content Javascript source that when evaluated does not
* execute any attacker-controlled scripts.
* @return {!goog.soy.data.SanitizedJs} Sanitized content wrapper that indicates
* to Soy not to escape when printed as Javascript source.
*/
soydata.VERY_UNSAFE.ordainSanitizedJs =
soydata.$$makeSanitizedContentFactoryWithDefaultDirOnly_(
goog.soy.data.SanitizedJs);
/**
* Takes a leap of faith that the provided content is "safe" to use as a URI
* in a Soy template.
*
* This creates a Soy SanitizedContent object which indicates to Soy there is
* no need to escape it when printed as a URI (e.g. in an href or src
* attribute), such as if it's already been encoded or if it's a Javascript:
* URI.
*
* @param {?} content A chunk of URI that the caller knows is safe to
* emit in a template.
* @return {!goog.soy.data.SanitizedUri} Sanitized content wrapper that
* indicates to Soy not to escape or filter when printed in URI context.
*/
soydata.VERY_UNSAFE.ordainSanitizedUri =
soydata.$$makeSanitizedContentFactoryWithDefaultDirOnly_(
goog.soy.data.SanitizedUri);
/**
* Takes a leap of faith that the provided content is "safe" to use as a
* TrustedResourceUri in a Soy template.
*
* This creates a Soy SanitizedContent object which indicates to Soy there is
* no need to filter it when printed as a TrustedResourceUri.
*
* @param {?} content A chunk of TrustedResourceUri such as that the caller
* knows is safe to emit in a template.
* @return {!goog.soy.data.SanitizedTrustedResourceUri} Sanitized content
* wrapper that indicates to Soy not to escape or filter when printed in
* TrustedResourceUri context.
*/
soydata.VERY_UNSAFE.ordainSanitizedTrustedResourceUri =
soydata.$$makeSanitizedContentFactoryWithDefaultDirOnly_(
goog.soy.data.SanitizedTrustedResourceUri);
/**
* Takes a leap of faith that the provided content is "safe" to use as an
* HTML attribute.
*
* @param {?} content An attribute name and value, such as
* `dir="ltr"`.
* @return {!goog.soy.data.SanitizedHtmlAttribute} Sanitized content wrapper
* that indicates to Soy not to escape when printed as an HTML attribute.
*/
soydata.VERY_UNSAFE.ordainSanitizedHtmlAttribute =
soydata.$$makeSanitizedContentFactoryWithDefaultDirOnly_(
goog.soy.data.SanitizedHtmlAttribute);
/**
* Takes a leap of faith that the provided content is "safe" to use as CSS
* in a style block.
*
* @param {?} content CSS, such as `color:#c3d9ff`.
* @return {!goog.soy.data.SanitizedCss} Sanitized CSS wrapper that indicates to
* Soy there is no need to escape or filter when printed in CSS context.
*/
soydata.VERY_UNSAFE.ordainSanitizedCss =
soydata.$$makeSanitizedContentFactoryWithDefaultDirOnly_(
goog.soy.data.SanitizedCss);
// -----------------------------------------------------------------------------
// Soy-generated utilities in the soy namespace. Contains implementations for
// common soyfunctions (e.g. keys()) and escaping/print directives.
/**
* Whether the locale is right-to-left.
*
* @type {boolean}
*/
soy.$$IS_LOCALE_RTL = goog.i18n.bidi.IS_RTL;
/**
* Builds an augmented map. The returned map will contain mappings from both
* the base map and the additional map. If the same key appears in both, then
* the value from the additional map will be visible, while the value from the
* base map will be hidden. The base map will be used, but not modified.
*
* @param {!Object} baseMap The original map to augment.
* @param {!Object} additionalMap A map containing the additional mappings.
* @return {!Object} An augmented map containing both the original and
* additional mappings.
*/
soy.$$augmentMap = function(baseMap, additionalMap) {
return soy.$$assignDefaults(soy.$$assignDefaults({}, additionalMap), baseMap);
};
/**
* Copies extra properties into an object if they do not already exist. The
* destination object is mutated in the process.
*
* @param {?} obj The destination object to update.
* @param {?} defaults An object with default properties to apply.
* @return {?} The destination object for convenience.
*/
soy.$$assignDefaults = function(obj, defaults) {
for (var key in defaults) {
if (!(key in obj)) {
obj[key] = defaults[key];
}
}
return obj;
};
/**
* Gets the keys in a map as an array. There are no guarantees on the order.
* @param {!Object} map The map to get the keys of.
* @return {!Array<string>} The array of keys in the given map.
*/
soy.$$getMapKeys = function(map) {
var mapKeys = [];
for (var key in map) {
mapKeys.push(key);
}
return mapKeys;
};
/**
* Returns the argument if it is not null.
*
* @param {T} val The value to check
* @return {T} val if is isn't null
* @template T
*/
soy.$$checkNotNull = function(val) {
if (val == null) {
throw Error('unexpected null value');
}
return val;
};
/**
* Parses the given string into a base 10 integer. Returns null if parse is
* unsuccessful.
* @param {?string} str The string to parse
* @return {?number} The string parsed as a base 10 integer, or null if
* unsuccessful
*/
soy.$$parseInt = function(str) {
var parsed = parseInt(String(str), 10);
return isNaN(parsed) ? null : parsed;
};
/**
* When equals comparison cannot be expressed using JS runtime semantics for ==,
* bail out to a runtime function. In practice, this only means comparisons
* of boolean, string and number are valid for equals, and everything else needs
* this function. Some sanitized content may be functions or objects that need
* to be coerced to a string.
* @param {?} valueOne
* @param {?} valueTwo
* @return {boolean}
*/
soy.$$equals = function(valueOne, valueTwo) {
// Incremental DOM functions have to be coerced to a string. At runtime
// they are tagged with a type for ATTR or HTML. They both need to be
// the same to be considered structurally equal. Beware, as this is a
// very expensive function.
if (goog.isFunction(valueOne) && goog.isFunction(valueTwo)) {
if ((/** @type {?} */ (valueOne)).contentKind !==
(/** @type {?} */ (valueTwo)).contentKind) {
return false;
} else {
return valueOne.toString() === valueTwo.toString();
}
}
// Likewise for sanitized content.
if (valueOne instanceof goog.soy.data.SanitizedContent &&
valueTwo instanceof goog.soy.data.SanitizedContent) {
if (valueOne.contentKind != valueTwo.contentKind) {
return false;
} else {
return valueOne.toString() == valueTwo.toString();
}
}
// Rely on javascript semantics for comparing two objects.
return valueOne == valueTwo;
};
/**
* Parses the given string into a float. Returns null if parse is unsuccessful.
* @param {?string} str The string to parse
* @return {?number} The string parsed as a float, or null if unsuccessful.
*/
soy.$$parseFloat = function(str) {
var parsed = parseFloat(str);
return isNaN(parsed) ? null : parsed;
};
/**
* Returns a random integer.
* @return {number} a random integer between 0 and num
*/
soy.$$randomInt = function(/** number */ num) {
return Math.floor(Math.random() * num);
};
/**
* Rounds the given value to the closest decimal point left (negative numbers)
* or right (positive numbers) of the decimal point
*
* TODO(b/112835292): This is probably not something that anyone should use,
* instead they should use an i18n friendly number formatting routine.
*
* @return {number} the rounded value
*/
soy.$$round = function(/** number */ num, /** number */ numDigitsAfterPt) {
const shift = Math.pow(10, numDigitsAfterPt);
return Math.round(num * shift) / shift;
};
/** @return {boolean} returns whether the needle was found in the haystack */
soy.$$strContains = function(/** string */ haystack, /** string */ needle) {
return haystack.indexOf(needle) != -1;
};
/**
* Coerce the given value into a bool.
*
* For objects of type `SanitizedContent`, the contents are used to determine
* the boolean value; this is because the outer `SanitizedContent` object
* instance is always truthy (unless it's null).
*
* @param {*} arg The argument to coerce.
* @return {boolean}
*/
soy.$$coerceToBoolean = function(arg) {
if (arg instanceof goog.soy.data.SanitizedContent) {
return !!arg.getContent();
}
return !!arg;
};
/**
* Gets a consistent unique id for the given delegate template name. Two calls
* to this function will return the same id if and only if the input names are
* the same.
*
* <p> Important: This function must always be called with a string constant.
*
* <p> If Closure Compiler is not being used, then this is just this identity
* function. If Closure Compiler is being used, then each call to this function
* will be replaced with a short string constant, which will be consistent per
* input name.
*
* @param {string} delTemplateName The delegate template name for which to get a
* consistent unique id.
* @return {string} A unique id that is consistent per input name.
*
* @idGenerator {consistent}
*/
soy.$$getDelTemplateId = function(delTemplateName) {
return delTemplateName;
};
/**
* Map from registered delegate template key to the priority of the
* implementation.
* @const {!Object<number>}
* @private
*/
soy.$$DELEGATE_REGISTRY_PRIORITIES_ = {};
/**
* Map from registered delegate template key to the implementation function.
* @const {!Object<!Function>}
* @private
*/
soy.$$DELEGATE_REGISTRY_FUNCTIONS_ = {};
/**
* Registers a delegate implementation. If the same delegate template key (id
* and variant) has been registered previously, then priority values are
* compared and only the higher priority implementation is stored (if
* priorities are equal, an error is thrown).
*
* @param {string} delTemplateId The delegate template id.
* @param {string} delTemplateVariant The delegate template variant (can be
* empty string).
* @param {number} delPriority The implementation's priority value.
* @param {!Function} delFn The implementation function.
*/
soy.$$registerDelegateFn = function(
delTemplateId, delTemplateVariant, delPriority, delFn) {
var mapKey = 'key_' + delTemplateId + ':' + delTemplateVariant;
var currPriority = soy.$$DELEGATE_REGISTRY_PRIORITIES_[mapKey];
if (currPriority === undefined || delPriority > currPriority) {
// Registering new or higher-priority function: replace registry entry.
soy.$$DELEGATE_REGISTRY_PRIORITIES_[mapKey] = delPriority;
soy.$$DELEGATE_REGISTRY_FUNCTIONS_[mapKey] = delFn;
} else if (delPriority == currPriority) {
// Registering same-priority function: error.
throw Error(
'Encountered two active delegates with the same priority ("' +
delTemplateId + ':' + delTemplateVariant + '").');
} else {
// Registering lower-priority function: do nothing.
}
};
/**
* Retrieves the (highest-priority) implementation that has been registered for
* a given delegate template key (id and variant). If no implementation has
* been registered for the key, then the fallback is the same id with empty
* variant. If the fallback is also not registered, and allowsEmptyDefault is
* true, then returns an implementation that is equivalent to an empty template
* (i.e. rendered output would be empty string).
*
* @param {string} delTemplateId The delegate template id.
* @param {string} delTemplateVariant The delegate template variant (can be
* empty string).
* @param {boolean} allowsEmptyDefault Whether to default to the empty template
* function if there's no active implementation.
* @return {!Function} The retrieved implementation function.
*/
soy.$$getDelegateFn = function(
delTemplateId, delTemplateVariant, allowsEmptyDefault) {
var delFn = soy.$$DELEGATE_REGISTRY_FUNCTIONS_[
'key_' + delTemplateId + ':' + delTemplateVariant];
if (! delFn && delTemplateVariant != '') {
// Fallback to empty variant.
delFn = soy.$$DELEGATE_REGISTRY_FUNCTIONS_['key_' + delTemplateId + ':'];
}
if (delFn) {
return delFn;
} else if (allowsEmptyDefault) {
return soy.$$EMPTY_TEMPLATE_FN_;
} else {
throw Error(
'Found no active impl for delegate call to "' + delTemplateId +
(delTemplateVariant ? ':' + delTemplateVariant : '') +
'" (and delcall does not set allowemptydefault="true").');
}
};
/**
* Private helper soy.$$getDelegateFn(). This is the empty template function
* that is returned whenever there's no delegate implementation found.
*
* Note: This is also used for idom.
*
* @return {string}
* @private
*/
soy.$$EMPTY_TEMPLATE_FN_ = function() {
return '';
};
// -----------------------------------------------------------------------------
// Internal sanitized content wrappers.
/**
* Creates a SanitizedContent factory for SanitizedContent types for internal
* Soy let and param blocks.
*
* This is a hack within Soy so that SanitizedContent objects created via let
* and param blocks will truth-test as false if they are empty string.
* Tricking the Javascript runtime to treat empty SanitizedContent as falsey is
* not possible, and changing the Soy compiler to wrap every boolean statement
* for just this purpose is impractical. Instead, we just avoid wrapping empty
* string as SanitizedContent, since it's a no-op for empty strings anyways.
*
* @param {function(new: T)} ctor A constructor.
* @return {function(*, ?goog.i18n.bidi.Dir=): (T|!soydata.$$EMPTY_STRING_)}
* A factory that takes content and an optional content direction and
* returns a new instance, or an empty string. If the content direction is
* undefined, ctor.prototype.contentDir is used.
* @template T
* @private
*/
soydata.$$makeSanitizedContentFactoryForInternalBlocks_ = function(ctor) {
/**
* @param {string} content
* @constructor
* @extends {goog.soy.data.SanitizedContent}
*/
function InstantiableCtor(content) {
/** @override */
this.content = content;
}
InstantiableCtor.prototype = ctor.prototype;
/**
* Creates a ctor-type SanitizedContent instance.
*
* @param {?} content The content to put in the instance.
* @param {?goog.i18n.bidi.Dir=} opt_contentDir The content direction. If
* undefined, ctor.prototype.contentDir is used.
* @return {!goog.soy.data.SanitizedContent|!soydata.$$EMPTY_STRING_} The new
* instance, or an empty string. A new instance is actually of type T
* above (ctor's type, a descendant of SanitizedContent), but there's no
* way to express that here.
*/
function sanitizedContentFactory(content, opt_contentDir) {
var contentString = String(content);
if (!contentString) {
return soydata.$$EMPTY_STRING_.VALUE;
}
var result = new InstantiableCtor(contentString);
if (opt_contentDir !== undefined) {
result.contentDir = opt_contentDir;
}
return result;
}
return sanitizedContentFactory;
};
/**
* Creates a SanitizedContent factory for SanitizedContent types that should
* always have their default directionality for internal Soy let and param
* blocks.
*
* This is a hack within Soy so that SanitizedContent objects created via let
* and param blocks will truth-test as false if they are empty string.
* Tricking the Javascript runtime to treat empty SanitizedContent as falsey is
* not possible, and changing the Soy compiler to wrap every boolean statement
* for just this purpose is impractical. Instead, we just avoid wrapping empty
* string as SanitizedContent, since it's a no-op for empty strings anyways.
*
* @param {function(new: T)} ctor A constructor.
* @return {function(*): (T|!soydata.$$EMPTY_STRING_)} A
* factory that takes content and returns a
* new instance (with default directionality, i.e.
* ctor.prototype.contentDir), or an empty string.
* @template T
* @private
*/
soydata.$$makeSanitizedContentFactoryWithDefaultDirOnlyForInternalBlocks_ =
function(ctor) {
/**
* @param {string} content
* @constructor
* @extends {goog.soy.data.SanitizedContent}
*/
function InstantiableCtor(content) {
/** @override */
this.content = content;
}
InstantiableCtor.prototype = ctor.prototype;
/**
* Creates a ctor-type SanitizedContent instance.
*
* @param {?} content The content to put in the instance.
* @return {!goog.soy.data.SanitizedContent|!soydata.$$EMPTY_STRING_} The new
* instance, or an empty string. A new instance is actually of type T
* above (ctor's type, a descendant of SanitizedContent), but there's no
* way to express that here.
*/
function sanitizedContentFactory(content) {
var contentString = String(content);
if (!contentString) {
return soydata.$$EMPTY_STRING_.VALUE;
}
var result = new InstantiableCtor(contentString);
return result;
}
return sanitizedContentFactory;
};
/**
* Creates kind="html" block contents (internal use only).
*
* @param {?} content Text.
* @param {?goog.i18n.bidi.Dir=} opt_contentDir The content direction; null if
* unknown and thus to be estimated when necessary. Default: null.
* @return {!goog.soy.data.SanitizedHtml|!soydata.$$EMPTY_STRING_} Wrapped
* result.
*/
soydata.VERY_UNSAFE.$$ordainSanitizedHtmlForInternalBlocks =
soydata.$$makeSanitizedContentFactoryForInternalBlocks_(
goog.soy.data.SanitizedHtml);
/**
* Creates kind="js" block contents (internal use only).
*
* @param {?} content Text.
* @return {!goog.soy.data.SanitizedJs|!soydata.$$EMPTY_STRING_} Wrapped result.
*/
soydata.VERY_UNSAFE.$$ordainSanitizedJsForInternalBlocks =
soydata.$$makeSanitizedContentFactoryWithDefaultDirOnlyForInternalBlocks_(
goog.soy.data.SanitizedJs);
/**
* Creates kind="trustedResourceUri" block contents (internal use only).
*
* @param {?} content Text.
* @return {!goog.soy.data.SanitizedTrustedResourceUri|!soydata.$$EMPTY_STRING_}
* Wrapped result.
*/
soydata.VERY_UNSAFE.$$ordainSanitizedTrustedResourceUriForInternalBlocks =
soydata.$$makeSanitizedContentFactoryWithDefaultDirOnlyForInternalBlocks_(
goog.soy.data.SanitizedTrustedResourceUri);
/**
* Creates kind="uri" block contents (internal use only).
*
* @param {?} content Text.
* @return {!goog.soy.data.SanitizedUri|!soydata.$$EMPTY_STRING_} Wrapped
* result.
*/
soydata.VERY_UNSAFE.$$ordainSanitizedUriForInternalBlocks =
soydata.$$makeSanitizedContentFactoryWithDefaultDirOnlyForInternalBlocks_(
goog.soy.data.SanitizedUri);
/**
* Creates kind="attributes" block contents (internal use only).
*
* @param {?} content Text.
* @return {!goog.soy.data.SanitizedHtmlAttribute|!soydata.$$EMPTY_STRING_}
* Wrapped result.
*/
soydata.VERY_UNSAFE.$$ordainSanitizedAttributesForInternalBlocks =
soydata.$$makeSanitizedContentFactoryWithDefaultDirOnlyForInternalBlocks_(
goog.soy.data.SanitizedHtmlAttribute);
/**
* Creates kind="css" block contents (internal use only).
*
* @param {?} content Text.
* @return {!goog.soy.data.SanitizedCss|!soydata.$$EMPTY_STRING_} Wrapped
* result.
*/
soydata.VERY_UNSAFE.$$ordainSanitizedCssForInternalBlocks =
soydata.$$makeSanitizedContentFactoryWithDefaultDirOnlyForInternalBlocks_(
goog.soy.data.SanitizedCss);
// -----------------------------------------------------------------------------
// Escape/filter/normalize.
/**
* Returns a SanitizedHtml object for a particular value. The content direction
* is preserved.
*
* This HTML-escapes the value unless it is already SanitizedHtml. Escapes
* double quote '"' in addition to '&', '<', and '>' so that a string can be
* included in an HTML tag attribute value within double quotes.
*
* @param {?} value The value to convert. If it is already a SanitizedHtml
* object, it is left alone.
* @return {!goog.soy.data.SanitizedHtml} An escaped version of value.
*/
soy.$$escapeHtml = function(value) {
return soydata.SanitizedHtml.from(value);
};
/**
* Strips unsafe tags to convert a string of untrusted HTML into HTML that
* is safe to embed. The content direction is preserved.
*
* @param {?} value The string-like value to be escaped. May not be a string,
* but the value will be coerced to a string.
* @param {?Array<string>=} opt_safeTags Additional tag names to whitelist.
* @return {!goog.soy.data.SanitizedHtml} A sanitized and normalized version of
* value.
*/
soy.$$cleanHtml = function(value, opt_safeTags) {
if (soy.checks.isHtml(value)) {
return /** @type {!goog.soy.data.SanitizedHtml} */ (value);
}
var tagWhitelist;
if (opt_safeTags) {
tagWhitelist = goog.object.createSet(opt_safeTags);
goog.object.extend(tagWhitelist, soy.esc.$$SAFE_TAG_WHITELIST_);
} else {
tagWhitelist = soy.esc.$$SAFE_TAG_WHITELIST_;
}
return soydata.VERY_UNSAFE.ordainSanitizedHtml(
soy.$$stripHtmlTags(value, tagWhitelist), soydata.getContentDir(value));
};
// LINT.IfChange(htmlToText)
/**
* Converts HTML to plain text by removing tags, normalizing spaces and
* converting entities.
*
* The last two parameters are idom functions.
* @param {string|?goog.soy.data.SanitizedHtml|?soydata.IdomFunction|?Function|
* undefined} value
* @return {string}
*/
soy.$$htmlToText = function(value) {
if (value == null) {
return '';
}
if (!soydata.isContentKind_(value, goog.soy.data.SanitizedContentKind.HTML)) {
return goog.asserts.assertString(value);
}
var html = value.toString();
var text = '';
var start = 0;
// Tag name to stop removing contents, e.g. '/script'.
var removingUntil = '';
// Tag name to stop preserving whitespace, e.g. '/pre'.
var wsPreservingUntil = '';
var tagRe =
/<(?:!--.*?--|(?:!|(\/?[a-z][\w:-]*))(?:[^>'"]|"[^"]*"|'[^']*')*)>|$/gi;
for (var match; match = tagRe.exec(html);) {
var tag = match[1];
var offset = match.index;
if (!removingUntil) {
var chunk = html.substring(start, offset);
chunk = goog.string.unescapeEntities(chunk);
if (!wsPreservingUntil) {
// We are not inside <pre>, normalize spaces.
chunk = chunk.replace(/\s+/g, ' ');
if (!/\S$/.test(text)) {
// Strip leading space unless after non-whitespace.
chunk = chunk.replace(/^ /, '');
}
}
text += chunk;
if (/^(script|style|textarea|title)$/i.test(tag)) {
removingUntil = '/' + tag.toLowerCase();
} else if (/^br$/i.test(tag)) {
// <br> adds newline even after newline.
text += '\n';
} else if (soy.BLOCK_TAGS_RE_.test(tag)) {
if (/[^\n]$/.test(text)) {
// Block tags don't add more consecutive newlines.
text += '\n';
}
if (/^pre$/i.test(tag)) {
wsPreservingUntil = '/' + tag.toLowerCase();
} else if (tag.toLowerCase() == wsPreservingUntil) {
wsPreservingUntil = '';
}
} else if (/^(td|th)$/i.test(tag)) {
// We add \t even after newline to support more leading <td>.
text += '\t';
}
} else if (removingUntil == tag.toLowerCase()) {
removingUntil = '';
}
if (!match[0]) {
break;
}
start = offset + match[0].length;
}
return text;
};
/** @private @const */
soy.BLOCK_TAGS_RE_ =
/^\/?(address|blockquote|dd|div|dl|dt|h[1-6]|hr|li|ol|p|pre|table|tr|ul)$/i;
// LINT.ThenChange(
// ../../../third_party/java_src/soy/java/com/google/template/soy/basicfunctions/HtmlToText.java,
// ../../../third_party/java_src/soy/python/runtime/sanitize.py:htmlToText)
/**
* Escapes HTML, except preserves entities.
*
* Used mainly internally for escaping message strings in attribute and rcdata
* context, where we explicitly want to preserve any existing entities.
*
* @param {?} value Value to normalize.
* @return {string} A value safe to insert in HTML without any quotes or angle
* brackets.
*/
soy.$$normalizeHtml = function(value) {
return soy.esc.$$normalizeHtmlHelper(value);
};