-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathvalidator.js
6511 lines (6065 loc) · 216 KB
/
validator.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
/**
* @license DEDUPE_ON_MINIFY
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* 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.
*/
goog.provide('amp.validator.CssLength'); // Only for testing.
goog.provide('amp.validator.Terminal');
goog.provide('amp.validator.ValidationHandler');
goog.provide('amp.validator.isSeverityWarning');
goog.provide('amp.validator.renderErrorMessage');
goog.provide('amp.validator.renderValidationResult');
goog.provide('amp.validator.sortAndUniquify');
goog.provide('amp.validator.subtractDiff');
goog.provide('amp.validator.validateSaxEvents');
goog.provide('amp.validator.validateString');
goog.require('amp.htmlparser.HtmlParser');
goog.require('amp.htmlparser.HtmlSaxHandlerWithLocation');
goog.require('amp.htmlparser.ParsedHtmlTag');
goog.require('amp.validator.AmpLayout');
goog.require('amp.validator.AncestorMarker');
goog.require('amp.validator.AtRuleSpec');
goog.require('amp.validator.AtRuleSpec.BlockType');
goog.require('amp.validator.AttrSpec');
goog.require('amp.validator.CdataSpec');
goog.require('amp.validator.CssDeclaration');
goog.require('amp.validator.CssSpec');
goog.require('amp.validator.ErrorCategory');
goog.require('amp.validator.ExtensionSpec');
goog.require('amp.validator.PropertySpecList');
goog.require('amp.validator.ReferencePoint');
goog.require('amp.validator.TagSpec');
goog.require('amp.validator.VALIDATE_CSS');
goog.require('amp.validator.ValidationError');
goog.require('amp.validator.ValidationError.Code');
goog.require('amp.validator.ValidationError.Severity');
goog.require('amp.validator.ValidationResult');
goog.require('amp.validator.ValidationResult.Status');
goog.require('amp.validator.ValidatorRules');
goog.require('amp.validator.ValueSetProvision');
goog.require('amp.validator.ValueSetRequirement');
goog.require('amp.validator.createRules');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.string');
goog.require('goog.uri.utils');
goog.require('parse_css.BlockType');
goog.require('parse_css.ErrorToken');
goog.require('parse_css.ParsedCssUrl');
goog.require('parse_css.RuleVisitor');
goog.require('parse_css.extractUrls');
goog.require('parse_css.parseAStylesheet');
goog.require('parse_css.parseInlineStyle');
goog.require('parse_css.parseMediaQueries');
goog.require('parse_css.stripMinMax');
goog.require('parse_css.stripVendorPrefix');
goog.require('parse_css.tokenize');
goog.require('parse_css.validateAmp4AdsCss');
goog.require('parse_css.validateKeyframesCss');
goog.require('parse_srcset.SrcsetParsingResult');
goog.require('parse_srcset.parseSrcset');
goog.require('parse_url.URL');
/**
* Sorts and eliminates duplicates in |arrayValue|. Modifies the input in place.
*
* WARNING: This is exported; interface changes may break downstream users like
* https://www.npmjs.com/package/amphtml-validator and
* https://validator.amp.dev/.
*
* @param {!Array<T>} arrayValue
* @template T
* @export
*/
function sortAndUniquify(arrayValue) {
if (arrayValue.length < 2) {return;}
goog.array.sort(arrayValue);
let uniqIdx = 0;
for (let i = 1; i < arrayValue.length; ++i) {
if (arrayValue[i] === arrayValue[uniqIdx]) {continue;}
uniqIdx++;
if (uniqIdx !== i) {arrayValue[uniqIdx] = arrayValue[i];}
}
arrayValue.splice(uniqIdx + 1);
}
/**
* Computes the difference set |left| - |right|, assuming |left| and
* |right| are sorted and uniquified.
*
* WARNING: This is exported; interface changes may break downstream users like
* https://www.npmjs.com/package/amphtml-validator and
* https://validator.amp.dev/.
*
* @param {!Array<T>} left
* @param {!Array<T>} right
* @return {!Array<T>} Computed difference of left - right.
* @template T
* @export
*/
function subtractDiff(left, right) {
let l = 0;
let r = 0;
const diff = [];
while (l < left.length) {
if (r >= right.length) {
diff.push(left[l]);
l++;
} else if (right[r] > left[l]) {
diff.push(left[l]);
l++;
} else if (right[r] < left[l]) {
r++;
} else {
goog.asserts.assert(right[r] === left[l]);
l++;
r++;
}
}
return diff;
}
/**
* A line / column pair.
* @private
*/
class LineCol {
/**
* @param {number} line
* @param {number} col
*/
constructor(line, col) {
this.line_ = line;
this.col_ = col;
}
/** @return {number} */
getLine() {
return this.line_;
}
/** @return {number} */
getCol() {
return this.col_;
}
}
/**
* Construct a ValidationError object from the given argument list.
* @param {!amp.validator.ValidationError.Severity} severity
* @param {!amp.validator.ValidationError.Code} validationErrorCode Error code
* @param {!LineCol} lineCol a line / column pair.
* @param {!Array<string>} params
* @param {?string} specUrl a link (URL) to the amphtml spec
* @return {!amp.validator.ValidationError}
*/
function populateError(
severity, validationErrorCode, lineCol, params, specUrl) {
const error = new amp.validator.ValidationError();
error.severity = severity;
error.code = validationErrorCode;
error.params = params;
error.line = lineCol.getLine();
error.col = lineCol.getCol();
error.specUrl = (specUrl === null ? '' : specUrl);
return error;
}
/**
* ParsedUrlSpec is used for both ParsedAttrSpec and ParsedCdataSpec, to
* check URLs. The main logic is in ParsedUrlSpec.ValidateUrlAndProtocol,
* which gets instantiated with two different adapter classes, which
* emit errors either for URLs in attribute values or URLs in templates.
* @private
*/
class ParsedUrlSpec {
/**
* Note that the spec can be null.
* @param {amp.validator.UrlSpec} spec
*/
constructor(spec) {
/**
* @type {amp.validator.UrlSpec}
* @private
*/
this.spec_ = spec;
/**
* @type {!Object<string, number>}
* @private
*/
this.allowedProtocols_ = Object.create(null);
if (this.spec_ !== null) {
for (const protocol of this.spec_.protocol) {
this.allowedProtocols_[protocol] = 0;
}
}
}
/** @return {amp.validator.UrlSpec} */
getSpec() {
return this.spec_;
}
/**
* @param {string} protocol
* @return {boolean}
*/
isAllowedProtocol(protocol) {
return protocol in this.allowedProtocols_;
}
}
/** @private */
class ParsedValueProperties {
/** @param {!amp.validator.PropertySpecList} spec */
constructor(spec) {
/**
* @type {!Object<string, !amp.validator.PropertySpec>}
* @private
*/
this.valuePropertyByName_ = Object.create(null);
/**
* @type {!Array<string>}
* @private
*/
this.mandatoryValuePropertyNames_ = [];
for (const propertySpec of spec.properties) {
this.valuePropertyByName_[propertySpec.name] = propertySpec;
if (propertySpec.mandatory) {
this.mandatoryValuePropertyNames_.push(propertySpec.name);
}
}
goog.array.sort(this.mandatoryValuePropertyNames_);
}
/** @return {!Object<string, amp.validator.PropertySpec>} */
getValuePropertyByName() {
return this.valuePropertyByName_;
}
/** @return {!Array<string>} */
getMandatoryValuePropertyNames() {
return this.mandatoryValuePropertyNames_;
}
}
/**
* This wrapper class provides access to an AttrSpec and
* an attribute id which is unique within its context
* (e.g., it's unique within the ParsedTagSpec).
* @private
*/
class ParsedAttrSpec {
/**
* @param {!amp.validator.AttrSpec} attrSpec
* @param {number} attrId
*/
constructor(attrSpec, attrId) {
/**
* JSON Attribute Spec dictionary.
* @type {!amp.validator.AttrSpec}
* @private
*/
this.spec_ = attrSpec;
/**
* Globally unique attribute rule id.
* @type {number}
* @private
*/
this.id_ = attrId;
/**
* @type {ParsedUrlSpec}
* @private
*/
this.valueUrlSpec_ = null;
/**
* @type {ParsedValueProperties}
* @private
*/
this.valueProperties_ = null;
/**
* @type {!Object<string, !amp.validator.CssDeclaration>}
* @private
*/
this.cssDeclarationByName_ = Object.create(null);
for (const cssDeclaration of attrSpec.cssDeclaration) {
if (cssDeclaration.name) {
this.cssDeclarationByName_[cssDeclaration.name] = cssDeclaration;
}
}
}
/**
* @return {number} unique for this attr spec.
*/
getId() {
return this.id_;
}
/**
* @return {!amp.validator.AttrSpec}
*/
getSpec() {
return this.spec_;
}
/**
* @return {!ParsedUrlSpec}
*/
getValueUrlSpec() {
if (this.valueUrlSpec_ === null) {
this.valueUrlSpec_ = new ParsedUrlSpec(this.spec_.valueUrl);
}
return this.valueUrlSpec_;
}
/**
* @return {ParsedValueProperties}
*/
getValuePropertiesOrNull() {
if (this.spec_.valueProperties === null) {return null;}
if (this.valueProperties_ === null) {
this.valueProperties_ =
new ParsedValueProperties(this.spec_.valueProperties);
}
return this.valueProperties_;
}
/**
* @return {!Object<string, !amp.validator.CssDeclaration>}
*/
getCssDeclarationByName() {
return this.cssDeclarationByName_;
}
/**
* Returns true if this AttrSpec should be used for the given type identifiers
* based on the AttrSpec's disabled_by or enabled_by fields.
* @param {!Array<string>} typeIdentifiers
* @return {boolean}
*/
isUsedForTypeIdentifiers(typeIdentifiers) {
return isUsedForTypeIdentifiers(
typeIdentifiers, this.spec_.enabledBy, this.spec_.disabledBy);
}
}
/**
* For creating error messages, we either find the specName in the tag spec or
* fall back to the tagName.
* @param {amp.validator.TagSpec} tagSpec TagSpec instance from the
* validator.protoscii file.
* @return {string}
* @private
*/
function getTagSpecName(tagSpec) {
return (tagSpec.specName !== null) ? tagSpec.specName :
tagSpec.tagName.toLowerCase();
}
/**
* For creating error URLs, we either find the specUrl in the tag spec or fall
* back to the extension spec URL if available.
* @param {amp.validator.TagSpec|ParsedTagSpec} tagSpec
* @return {string}
* @private
*/
function getTagSpecUrl(tagSpec) {
// Handle a ParsedTagSpec as well as a tag spec.
// TODO(gregable): This is a bit hacky, we should improve on this approach
// in the future.
if (tagSpec.getSpec !== undefined) {return getTagSpecUrl(tagSpec.getSpec());}
if (tagSpec.specUrl !== null) {return tagSpec.specUrl;}
const extensionSpecUrlPrefix = 'https://amp.dev/documentation/components/';
if (tagSpec.extensionSpec !== null && tagSpec.extensionSpec.name !== null)
{return extensionSpecUrlPrefix + tagSpec.extensionSpec.name;}
if (tagSpec.requiresExtension.length > 0) {
// Return the first |requires_extension|, which should be the most
// representitive.
return extensionSpecUrlPrefix + tagSpec.requiresExtension[0];
}
return '';
}
/**
* Returns true if this spec should be used for the given type identifiers
* based on the spec's disabled_by or enabled_by fields.
* @param {!Array<string>} typeIdentifiers
* @param {!Array<string>} enabledBys
* @param {!Array<string>} disabledBys
* @return {boolean}
*/
function isUsedForTypeIdentifiers(typeIdentifiers, enabledBys, disabledBys) {
if (enabledBys.length > 0) {
for (const enabledBy of enabledBys) {
// Is enabled by a given type identifier, use.
if (typeIdentifiers.includes(enabledBy)) {
return true;
}
}
// Is not enabled for these type identifiers, do not use.
return false;
} else if (disabledBys.length > 0) {
for (const disabledBy of disabledBys) {
// Is disabled by a given type identifier, do not use.
if (typeIdentifiers.includes(disabledBy)) {
return false;
}
}
// Is not disabled for these type identifiers, use.
return true;
}
// Is not enabled nor disabled for any type identifiers, use.
return true;
}
/**
* Holds the reference points for a particular parent tag spec, including
* their resolved tagspec ids.
* @private
*/
class ParsedReferencePoints {
/**
* @param {!amp.validator.TagSpec} parentTagSpec
*/
constructor(parentTagSpec) {
/**
* @type {!amp.validator.TagSpec}
* @private
*/
this.parentTagSpec_ = parentTagSpec;
}
/** @return {!Array<!amp.validator.ReferencePoint>} */
iterate() {
return this.parentTagSpec_.referencePoints;
}
/** @return {boolean} */
empty() {
return this.size() === 0;
}
/** @return {number} */
size() {
return this.parentTagSpec_.referencePoints.length;
}
/** @return {?string} */
parentSpecUrl() {
return getTagSpecUrl(this.parentTagSpec_);
}
/** @return {string} */
parentTagSpecName() {
return getTagSpecName(this.parentTagSpec_);
}
}
/**
* TagSpecs specify attributes that are valid for a particular tag.
* They can also reference lists of attributes (AttrLists), thereby
* sharing those definitions. This abstraction instantiates
* ParsedAttrSpec for each AttrSpec (from validator-*.protoascii, our
* specification file) exactly once, and provides quick access to the
* attr spec names as well, including for simple attr specs (those
* which only have a name but no specification for their value).
* @private
*/
class ParsedAttrSpecs {
/**
* @param {!amp.validator.ValidatorRules} rules
*/
constructor(rules) {
/** @type {!Array<!Array<number>>} */
this.attrLists = rules.directAttrLists;
/** @type {!Array<number>} */
this.globalAttrs = rules.globalAttrs;
/** @type {!Array<number>} */
this.ampLayoutAttrs = rules.ampLayoutAttrs;
/**
* The AttrSpec instances, indexed by attr spec ids.
* @private @type {!Array<!amp.validator.AttrSpec>}
*/
this.attrSpecs_ = rules.attrs;
/**
* @private @type {!Array<!string>}
*/
this.internedStrings_ = rules.internedStrings;
/**
* The already instantiated ParsedAttrSpec instances, indexed by
* attr spec ids.
* @private @type {!Array<!ParsedAttrSpec>}
*/
this.parsedAttrSpecs_ = new Array(rules.attrs.length);
}
/**
* @param {number} id
* @return {!ParsedAttrSpec}
*/
getByAttrSpecId(id) {
if (this.parsedAttrSpecs_.hasOwnProperty(id)) {
return this.parsedAttrSpecs_[id];
}
const parsed = new ParsedAttrSpec(this.attrSpecs_[id], id);
this.parsedAttrSpecs_[id] = parsed;
return parsed;
}
/**
* @param {number} id
* @return {string}
*/
getNameByAttrSpecId(id) {
if (id < 0) {
return this.internedStrings_[-1 - id];
}
return this.attrSpecs_[id].name;
}
}
/** @enum {string} */
const RecordValidated = {
ALWAYS: 'ALWAYS',
NEVER: 'NEVER',
IF_PASSING: 'IF_PASSING'
};
/**
* We only track (that is, add them to Context.RecordTagspecValidated) validated
* tagspecs as necessary. That is, if it's needed for document scope validation:
* - Mandatory tags
* - Unique tags
* - Tags (identified by their TagSpecName() that are required by other tags.
* @param {!amp.validator.TagSpec} tag
* @param {number} tagSpecId
* @param {!Array<boolean>} tagSpecIdsToTrack
* @return {!RecordValidated}
*/
function shouldRecordTagspecValidated(tag, tagSpecId, tagSpecIdsToTrack) {
// Always update from TagSpec if the tag is passing. If it's failing we
// typically want to update from the best match as it can satisfy
// requirements which otherwise can confuse the user later. The exception is
// tagspecs which introduce requirements but satisfy none, such as unique.
// https://github.com/ampproject/amphtml/issues/24359
// Mandatory and tagSpecIdsToTrack only satisfy requirements, making the
// output less verbose even if the tag is failing.
if (tag.mandatory || tagSpecIdsToTrack.hasOwnProperty(tagSpecId))
return RecordValidated.ALWAYS;
// Unique and similar can introduce requirements, ie: there cannot be another
// such tag. We don't want to introduce requirements for failing tags.
if (tag.unique || tag.requires.length > 0 || tag.uniqueWarning)
return RecordValidated.IF_PASSING;
return RecordValidated.NEVER;
}
/**
* This wrapper class provides access to a TagSpec and a tag id
* which is unique within its context, the ParsedValidatorRules.
* @private
*/
class ParsedTagSpec {
/**
* @param {!ParsedAttrSpecs} parsedAttrSpecs
* @param {!RecordValidated} shouldRecordTagspecValidated
* @param {!amp.validator.TagSpec} tagSpec
* @param {number} id
*/
constructor(parsedAttrSpecs, shouldRecordTagspecValidated, tagSpec, id) {
/**
* @type {!amp.validator.TagSpec}
* @private
*/
this.spec_ = tagSpec;
/**
* @type {number}
* @private
*/
this.id_ = id;
/**
* @type {!ParsedReferencePoints}
* @private
*/
this.referencePoints_ = new ParsedReferencePoints(tagSpec);
/**
* @type {boolean}
* @private
*/
this.isReferencePoint_ = (tagSpec.tagName === '$REFERENCE_POINT');
/**
* @type {boolean}
* @private
*/
this.isTypeJson_ = false;
/**
* @type {!RecordValidated}
* @private
*/
this.shouldRecordTagspecValidated_ = shouldRecordTagspecValidated;
/**
* @type {boolean}
* @private
*/
this.attrsCanSatisfyExtension_ = false;
/**
* ParsedAttributes keyed by name.
* @type {!Object<string, number>}
* @private
*/
this.attrsByName_ = Object.create(null);
/**
* Attribute ids that are mandatory for this tag to legally validate.
* @type {!Array<number>}
* @private
*/
this.mandatoryAttrIds_ = [];
/**
* @type {!Array<number>}
* @private
*/
this.mandatoryOneofs_ = [];
/**
* @type {!Array<number>}
* @private
*/
this.mandatoryAnyofs_ = [];
/**
* @type {!Array<number>}
* @private
*/
this.implicitAttrspecs_ = [];
/**
* @type {boolean}
* @private
*/
this.containsUrl_ = false;
// Collect the attr spec ids for a given |tagspec|.
// There are four ways to specify attributes:
// (1) implicitly by a tag spec, if the tag spec has the amp_layout field
// set - in this case, the AMP_LAYOUT_ATTRS are assumed;
// (2) within a TagSpec::attrs;
// (3) via TagSpec::attr_lists which references lists by key;
// (4) within the $GLOBAL_ATTRS TagSpec::attr_list.
// It's possible to provide multiple specifications for the same attribute
// name, but for any given tag only one such specification can be active.
// The precedence is (1), (2), (3), (4)
// If tagSpec.explicitAttrsOnly is true then only collect the attributes
// from (2) and (3).
// (1) layout attrs (except when explicitAttrsOnly is true).
if (!tagSpec.explicitAttrsOnly && tagSpec.ampLayout !== null &&
!this.isReferencePoint_) {
this.mergeAttrs(parsedAttrSpecs.ampLayoutAttrs, parsedAttrSpecs);
}
// (2) attributes specified within |tagSpec|.
this.mergeAttrs(tagSpec.attrs, parsedAttrSpecs);
// (3) attributes specified via reference to an attr_list.
for (const id of tagSpec.attrLists) {
this.mergeAttrs(parsedAttrSpecs.attrLists[id], parsedAttrSpecs);
}
// (4) attributes specified in the global_attr list (except when
// explicitAttrsOnly is true).
if (!tagSpec.explicitAttrsOnly && !this.isReferencePoint_) {
this.mergeAttrs(parsedAttrSpecs.globalAttrs, parsedAttrSpecs);
}
sortAndUniquify(this.mandatoryOneofs_);
sortAndUniquify(this.mandatoryAnyofs_);
sortAndUniquify(this.mandatoryAttrIds_);
}
/**
* Merges the list of attrs into attrsByName, avoiding to merge in attrs
* with names that are already in attrsByName.
* @param {!Array<number>} attrs
* @param {!ParsedAttrSpecs} parsedAttrSpecs
*/
mergeAttrs(attrs, parsedAttrSpecs) {
for (const attrId of attrs) {
const name = parsedAttrSpecs.getNameByAttrSpecId(attrId);
if (name in this.attrsByName_) {
continue;
}
this.attrsByName_[name] = attrId;
if (attrId < 0) { // negative attr ids are simple attrs (only name set).
continue;
}
const attr = parsedAttrSpecs.getByAttrSpecId(attrId);
const spec = attr.getSpec();
if (spec.mandatory) {
this.mandatoryAttrIds_.push(attrId);
}
if (spec.mandatoryOneof !== null) {
this.mandatoryOneofs_.push(spec.mandatoryOneof);
}
if (spec.mandatoryAnyof !== null) {
this.mandatoryAnyofs_.push(spec.mandatoryAnyof);
}
for (const altName of spec.alternativeNames) {
this.attrsByName_[altName] = attrId;
}
if (spec.implicit) {
this.implicitAttrspecs_.push(attrId);
}
if (spec.name === 'type' && spec.valueCasei.length > 0) {
for (const v of spec.valueCasei) {
if ('application/json' === v) {
this.isTypeJson_ = true;
break;
}
}
}
if (spec.valueUrl) {
this.containsUrl_ = true;
}
if (spec.requiresExtension.length > 0) {
this.attrsCanSatisfyExtension_ = true;
}
}
}
/**
* Return the numerical id.
* @return {number}
*/
id() {
return this.id_;
}
/**
* Return the original tag spec. This is the json object representation from
* amp.validator.rules_.
* @return {!amp.validator.TagSpec}
*/
getSpec() {
return this.spec_;
}
/**
* If tag has a cdata spec, returns a CdataMatcher, else null.
* @param {!LineCol} lineCol
* @return {?CdataMatcher}
*/
cdataMatcher(lineCol) {
if (this.spec_.cdata !== null) {
return new CdataMatcher(this.spec_, lineCol);
}
return null;
}
/**
* If tag has a child_tag spec, returns a ChildTagMatcher, else null.
* @param {!LineCol} lineCol
* @return {?ChildTagMatcher}
*/
childTagMatcher(lineCol) {
if (this.spec_.childTags !== null)
{return new ChildTagMatcher(this.spec_, lineCol);}
return null;
}
/**
* If tag has a reference_point spec, returns a ReferencePointMatcher,
* else null.
* @param {!ParsedValidatorRules} rules
* @param {!LineCol} lineCol
* @return {?ReferencePointMatcher}
*/
referencePointMatcher(rules, lineCol) {
if (this.hasReferencePoints())
{return new ReferencePointMatcher(rules, this.referencePoints_, lineCol);}
return null;
}
/**
* Returns true if this tagSpec contains an attribute of name "type" and value
* "application/json".
* @return {boolean}
*/
isTypeJson() {
return this.isTypeJson_;
}
/**
* Returns true if this tagSpec contains a value_url field.
* @return {boolean}
*/
containsUrl() {
return this.containsUrl_;
}
/**
* Returns true if this TagSpec should be used for the given type identifiers
* based on the TagSpec's disabled_by or enabled_by fields.
* @param {!Array<string>} typeIdentifiers
* @return {boolean}
*/
isUsedForTypeIdentifiers(typeIdentifiers) {
return isUsedForTypeIdentifiers(
typeIdentifiers, this.spec_.enabledBy, this.spec_.disabledBy);
}
/**
* A TagSpec may specify other tags to be required as well, when that
* tag is used. This accessor returns the IDs for the tagspecs that
* are also required if |this| tag occurs in the document, but where
* such requirement is currently only a warning.
* @return {!Array<number>}
*/
getAlsoRequiresTagWarning() {
return this.spec_.alsoRequiresTagWarning;
}
/**
* A TagSpec may specify generic conditions which are required if the
* tag is present. This accessor returns the list of those conditions.
* @return {!Array<number>}
*/
requires() {
return this.spec_.requires;
}
/**
* A TagSpec may specify that another tag is excluded. This accessor returns
* the list of those tags.
* @return {!Array<number>}
*/
excludes() {
return this.spec_.excludes;
}
/**
* Whether or not the tag should be recorded via
* Context.recordTagspecValidated_ if it was validated
* successfullly. For performance, this is only done for tags that are
* mandatory, unique, or possibly required by some other tag.
* @return {!RecordValidated}
*/
shouldRecordTagspecValidated() {
return this.shouldRecordTagspecValidated_;
}
/** @return {boolean} */
isReferencePoint() {
return this.isReferencePoint_;
}
/** @return {boolean} */
hasReferencePoints() {
return !this.referencePoints_.empty();
}
/** @return {!ParsedReferencePoints} */
getReferencePoints() {
return this.referencePoints_;
}
/** @return {boolean} */
attrsCanSatisfyExtension() {
return this.attrsCanSatisfyExtension_;
}
/**
* @param {string} name
* @return {boolean}
*/
hasAttrWithName(name) {
return name in this.attrsByName_;
}
/**
* @return {!Array<number>}
*/
getImplicitAttrspecs() {
return this.implicitAttrspecs_;
}
/**
* @return {!Object<string, number>}
*/
getAttrsByName() {
return this.attrsByName_;
}
/**
* @return {!Array<number>}
*/
getMandatoryOneofs() {
return this.mandatoryOneofs_;
}
/**
* @return {!Array<number>}
*/
getMandatoryAnyofs() {
return this.mandatoryAnyofs_;
}
/**
* @return {!Array<number>}
*/
getMandatoryAttrIds() {
return this.mandatoryAttrIds_;
}
}
/**
* Attempts to URI decode an attribute value. If URI decoding fails, it falls
* back to calling unescape. We want to minimize the scope of this try/catch
* to allow v8 to optimize more code.
* @param {string} attrValue
* @return {string}
*/
function decodeAttrValue(attrValue) {
let decodedAttrValue;
try {
decodedAttrValue = decodeURIComponent(attrValue);
} catch (e) {
// This branch is best effort, since unescape is deprecated.
// However unescape appears to work even if the value is not a
// properly encoded attribute.
// TODO(powdercloud): We're currently using this to prohibit
// __amp_source_origin for URLs. We may want to introduce a
// global bad url functionality with patterns or similar, as opposed
// to applying this to every attribute that has a blacklisted value
// regex.
decodedAttrValue = unescape(attrValue);
}
return decodedAttrValue;
}
/**
* Merge results from another ValidationResult while dealing with the UNKNOWN
* status.
* @param {!amp.validator.ValidationResult} other
*/
amp.validator.ValidationResult.prototype.mergeFrom = function(other) {
goog.asserts.assert(this.status !== null);
goog.asserts.assert(other.status !== null);
// Copy status only if fail. Failing is a terminal state.
if (other.status === amp.validator.ValidationResult.Status.FAIL)
{this.status = amp.validator.ValidationResult.Status.FAIL;}
Array.prototype.push.apply(this.errors, other.errors);
};
/**
* The child tag matcher evaluates ChildTagSpec. The constructor
* provides the enclosing TagSpec for the parent tag so that we can
* produce error messages mentioning the parent.
* @private
*/
class ChildTagMatcher {
/**
* @param {!amp.validator.TagSpec} parentSpec
* @param {!LineCol} lineCol
*/
constructor(parentSpec, lineCol) {
/**
* @type {amp.validator.TagSpec}
* @private
*/
this.parentSpec_ = parentSpec;
/**
* @type {!LineCol}
* @private
*/
this.lineCol_ = lineCol;
goog.asserts.assert(this.parentSpec_.childTags !== null);
}