vastlint-core 0.3.3

VAST XML validator core — checks tags against IAB VAST 2.0 through 4.3
Documentation
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
//! Value-validation rules.
//!
//! These rules inspect the actual content of elements and attributes — not just
//! whether they are present, but whether their values conform to the spec.
//! Duration formats, delivery enums, tracking event names, skipoffset patterns,
//! adType enums, renderingMode enums.
//!
//! Rules that are version-dependent gate on version.best().

use super::emit;
use crate::parse::{Node, VastDocument};
use crate::{DetectedVersion, Issue, Severity, ValidationContext, VastVersion};

pub fn check(
    doc: &VastDocument,
    version: &DetectedVersion,
    ctx: &ValidationContext,
    issues: &mut Vec<Issue>,
) {
    let Some(vast) = doc.vast_root() else { return };
    let v = version.best();

    // VAST-4.1-adtype-value: Ad.adType must be video/audio/hybrid (4.1+).
    if v.map(|x| x.at_least(&VastVersion::V4_1)).unwrap_or(false) {
        for (ad_idx, ad) in vast.children_named("Ad").enumerate() {
            if let Some(ad_type) = ad.attr("adType") {
                if !matches!(ad_type, "video" | "audio" | "hybrid") {
                    emit(
                        ctx, issues,
                        "VAST-4.1-adtype-value",
                        Severity::Warning,
                        "Ad adType attribute value is not in the allowed set (video, audio, hybrid)",
                        Some(format!("/VAST/Ad[{}][@adType]", ad_idx)),
                        "IAB VAST 4.1 §2.2.1",
            Some(ad),
        )
                }
            }
        }
    }

    for (ad_idx, ad) in vast.children_named("Ad").enumerate() {
        let ad_path = format!("/VAST/Ad[{}]", ad_idx);

        if let Some(inline) = ad.child("InLine") {
            check_ad_content(inline, &format!("{}/InLine", ad_path), v, ctx, issues);
        }
        if let Some(wrapper) = ad.child("Wrapper") {
            check_ad_content(wrapper, &format!("{}/Wrapper", ad_path), v, ctx, issues);
        }
    }
}

fn check_ad_content(
    node: &Node,
    path: &str,
    v: Option<&VastVersion>,
    ctx: &ValidationContext,
    issues: &mut Vec<Issue>,
) {
    if let Some(creatives) = node.child("Creatives") {
        for (ci, creative) in creatives.children_named("Creative").enumerate() {
            let cp = format!("{}/Creatives/Creative[{}]", path, ci);
            check_creative(creative, &cp, v, ctx, issues);
        }
    }

    // Pricing value checks (3.0+).
    check_pricing_values(node, path, v, ctx, issues);
}

fn check_creative(
    node: &Node,
    path: &str,
    v: Option<&VastVersion>,
    ctx: &ValidationContext,
    issues: &mut Vec<Issue>,
) {
    if let Some(linear) = node.child("Linear") {
        check_linear(linear, &format!("{}/Linear", path), v, ctx, issues);
    }

    if let Some(companion_ads) = node.child("CompanionAds") {
        // VAST-3.0-companion-required-attr: required attribute enum check.
        if let Some(req) = companion_ads.attr("required") {
            if !matches!(req, "all" | "any" | "none") {
                emit(
                    ctx,
                    issues,
                    "VAST-3.0-companion-required-attr",
                    Severity::Warning,
                    "<CompanionAds> required attribute must be \"all\", \"any\", or \"none\"",
                    Some(format!("{}/CompanionAds[@required]", path)),
                    "IAB VAST 3.0 §2.3.8",
                    Some(companion_ads),
                )
            }
        }

        for (ci, companion) in companion_ads.children_named("Companion").enumerate() {
            check_companion(
                companion,
                &format!("{}/CompanionAds/Companion[{}]", path, ci),
                v,
                ctx,
                issues,
            );
        }
    }
}

fn check_linear(
    node: &Node,
    path: &str,
    v: Option<&VastVersion>,
    ctx: &ValidationContext,
    issues: &mut Vec<Issue>,
) {
    // VAST-2.0-duration-format: Duration text must match HH:MM:SS[.mmm].
    if let Some(dur) = node.child("Duration") {
        let text = dur.text.trim();
        if !text.is_empty() && !is_valid_duration(text) {
            emit(
                ctx,
                issues,
                "VAST-2.0-duration-format",
                Severity::Error,
                "<Duration> value does not match required format HH:MM:SS or HH:MM:SS.mmm",
                Some(format!("{}/Duration", path)),
                "IAB VAST 2.0 §2.3.5.1",
                Some(dur),
            )
        }
    }

    // VAST-3.0-skipoffset-format: skipoffset must be HH:MM:SS[.mmm] or n%.
    if let Some(offset) = node.attr("skipoffset") {
        if !is_valid_time_or_percent(offset) {
            emit(
                ctx,
                issues,
                "VAST-3.0-skipoffset-format",
                Severity::Warning,
                "Linear skipoffset attribute does not match required format (HH:MM:SS[.mmm] or n%)",
                Some(format!("{}[@skipoffset]", path)),
                "IAB VAST 3.0 §2.3.6",
                Some(node),
            )
        }
    }

    // VAST-3.0-skip-event-no-skipoffset: skip tracking event with no skipoffset.
    if node.attr("skipoffset").is_none() {
        if let Some(events) = node.child("TrackingEvents") {
            let has_skip = events
                .children_named("Tracking")
                .any(|t| t.attr("event").map(|e| e == "skip").unwrap_or(false));
            if has_skip {
                emit(
                    ctx,
                    issues,
                    "VAST-3.0-skip-event-no-skipoffset",
                    Severity::Warning,
                    "<Tracking event=\"skip\"> present but <Linear> has no skipoffset attribute",
                    Some(format!("{}/TrackingEvents", path)),
                    "IAB VAST 3.0 §2.3.6",
                    Some(node),
                )
            }
        }
    }

    // VAST-3.0-progress-offset-format: progress offset format check.
    if let Some(events) = node.child("TrackingEvents") {
        for (ti, tracking) in events.children_named("Tracking").enumerate() {
            let tp = format!("{}/TrackingEvents/Tracking[{}]", path, ti);
            check_tracking_value(tracking, &tp, v, ctx, issues);
        }
    }

    // VAST-3.0-minmaxbitrate-pair and VAST-3.0-bitrate-conflict on MediaFile.
    if let Some(mf_container) = node.child("MediaFiles") {
        for (mi, mf) in mf_container.children_named("MediaFile").enumerate() {
            let mp = format!("{}/MediaFiles/MediaFile[{}]", path, mi);
            check_mediafile_values(mf, &mp, ctx, issues);
        }
    }
}

fn check_tracking_value(
    tracking: &Node,
    path: &str,
    v: Option<&VastVersion>,
    ctx: &ValidationContext,
    issues: &mut Vec<Issue>,
) {
    let Some(event) = tracking.attr("event") else {
        return;
    };

    // VAST-3.0-progress-offset-format
    if event == "progress" {
        if let Some(offset) = tracking.attr("offset") {
            if !is_valid_time_or_percent(offset) {
                emit(
                    ctx, issues,
                    "VAST-3.0-progress-offset-format",
                    Severity::Warning,
                    "<Tracking event=\"progress\"> offset attribute does not match required format (HH:MM:SS[.mmm] or n%)",
                    Some(format!("{}[@offset]", path)),
                    "IAB VAST 3.0 §2.3.6",
            Some(tracking),
        )
            }
        }
    }

    // VAST-4.1-tracking-event-value: version-aware event name validation.
    // Only fires when we know the version. Uses the correct enum for that version.
    if let Some(ver) = v {
        let valid = valid_tracking_events(ver);
        if !valid.contains(&event) {
            // For 4.0 specifically, fullscreen/exitFullscreen were removed —
            // give a more targeted message.
            if ver.at_least(&VastVersion::V4_0)
                && (event == "fullscreen" || event == "exitFullscreen")
            {
                emit(
                    ctx, issues,
                    "VAST-4.0-tracking-event-removed",
                    Severity::Warning,
                    "Tracking event \"fullscreen\"/\"exitFullscreen\" was removed in VAST 4.0 — use playerExpand/playerCollapse",
                    Some(format!("{}[@event]", path)),
                    "IAB VAST 4.0 §2.3.6",
            Some(tracking),
        )
            } else {
                emit(
                    ctx,
                    issues,
                    "VAST-4.1-tracking-event-value",
                    Severity::Error,
                    "Tracking event attribute value is not in the VAST spec enum for this version",
                    Some(format!("{}[@event]", path)),
                    "IAB VAST 4.2 §2.3.6",
                    Some(tracking),
                )
            }
        }
    }
}

fn check_mediafile_values(mf: &Node, path: &str, ctx: &ValidationContext, issues: &mut Vec<Issue>) {
    // VAST-2.0-mediafile-delivery-enum
    if let Some(delivery) = mf.attr("delivery") {
        if delivery != "progressive" && delivery != "streaming" {
            emit(
                ctx,
                issues,
                "VAST-2.0-mediafile-delivery-enum",
                Severity::Error,
                "<MediaFile> delivery attribute must be \"progressive\" or \"streaming\"",
                Some(format!("{}[@delivery]", path)),
                "IAB VAST 2.0 §2.3.5.2",
                Some(mf),
            )
        }
    }

    // VAST-3.0-minmaxbitrate-pair
    let has_min = mf.attr("minBitrate").is_some();
    let has_max = mf.attr("maxBitrate").is_some();
    if has_min != has_max {
        emit(
            ctx,
            issues,
            "VAST-3.0-minmaxbitrate-pair",
            Severity::Error,
            "<MediaFile> must have both minBitrate and maxBitrate, or neither",
            Some(path.to_owned()),
            "IAB VAST 3.0 §2.3.5.2",
            Some(mf),
        )
    }

    // VAST-3.0-bitrate-conflict
    if mf.attr("bitrate").is_some() && (has_min || has_max) {
        emit(
            ctx,
            issues,
            "VAST-3.0-bitrate-conflict",
            Severity::Warning,
            "<MediaFile> should not specify both bitrate and minBitrate/maxBitrate",
            Some(path.to_owned()),
            "IAB VAST 3.0 §2.3.5.2",
            Some(mf),
        )
    }
}

fn check_companion(
    node: &Node,
    path: &str,
    _v: Option<&VastVersion>,
    ctx: &ValidationContext,
    issues: &mut Vec<Issue>,
) {
    // VAST-4.1-companion-renderingmode-value
    if let Some(mode) = node.attr("renderingMode") {
        if !matches!(mode, "default" | "end-card" | "concurrent") {
            emit(
                ctx, issues,
                "VAST-4.1-companion-renderingmode-value",
                Severity::Warning,
                "Companion renderingMode attribute value is not in allowed set (default, end-card, concurrent)",
                Some(format!("{}[@renderingMode]", path)),
                "IAB VAST 4.1 §2.3.8",
            Some(node),
        )
        }
    }
}

fn check_pricing_values(
    node: &Node, // InLine or Wrapper
    path: &str,
    v: Option<&VastVersion>,
    ctx: &ValidationContext,
    issues: &mut Vec<Issue>,
) {
    let Some(pricing) = node.child("Pricing") else {
        return;
    };
    let pricing_path = format!("{}/Pricing", path);

    // VAST-3.0-pricing-currency-format: currency must be exactly 3 ASCII letters.
    if let Some(currency) = pricing.attr("currency") {
        let valid = currency.len() == 3 && currency.chars().all(|c| c.is_ascii_alphabetic());
        if !valid {
            emit(
                ctx,
                issues,
                "VAST-3.0-pricing-currency-format",
                Severity::Warning,
                "<Pricing> currency attribute must be a 3-letter ISO-4217 code (e.g. \"USD\")",
                Some(format!("{}[@currency]", pricing_path)),
                "IAB VAST 3.0 §2.3.10",
                Some(pricing),
            )
        }
    }

    // VAST-3.0-pricing-model-case: model value should be lowercase in 3.0.
    // VAST 4.0 XSD explicitly accepts both cases, so only warn for 3.0 docs.
    if let Some(model) = pricing.attr("model") {
        let is_3_0_only = v
            .map(|ver| ver.at_least(&VastVersion::V3_0) && !ver.at_least(&VastVersion::V4_0))
            .unwrap_or(false);
        if is_3_0_only && model.chars().any(|c| c.is_uppercase()) {
            emit(
                ctx, issues,
                "VAST-3.0-pricing-model-case",
                Severity::Warning,
                "<Pricing> model attribute value should be lowercase in VAST 3.0 (XSD enumerates cpm/cpc/cpe/cpv)",
                Some(format!("{}[@model]", pricing_path)),
                "IAB VAST 3.0 §2.3.10",
            Some(pricing),
        )
        }
    }
}

// ── Helpers ───────────────────────────────────────────────────────────────────

/// Returns true if `s` matches `HH:MM:SS` or `HH:MM:SS.mmm`.
fn is_valid_duration(s: &str) -> bool {
    is_hhmmss(s)
}

/// Returns true if `s` matches the time-or-percent pattern used for
/// `skipoffset` and progress `offset`: `HH:MM:SS[.mmm]` or `n%` (0–100%).
fn is_valid_time_or_percent(s: &str) -> bool {
    if let Some(num) = s.strip_suffix('%') {
        return num
            .parse::<f64>()
            .map(|v| (0.0..=100.0).contains(&v))
            .unwrap_or(false);
    }
    is_hhmmss(s)
}

/// Validates `HH:MM:SS` or `HH:MM:SS.mmm` without regex.
fn is_hhmmss(s: &str) -> bool {
    // Split on the first dot for optional milliseconds.
    let (time_part, ms_part) = match s.find('.') {
        Some(dot) => (&s[..dot], Some(&s[dot + 1..])),
        None => (s, None),
    };

    let parts: Vec<&str> = time_part.split(':').collect();
    if parts.len() != 3 {
        return false;
    }
    let ok_part = |p: &str, max: u32| {
        p.len() == 2
            && p.chars().all(|c| c.is_ascii_digit())
            && p.parse::<u32>().map(|v| v <= max).unwrap_or(false)
    };
    if !parts[0].chars().all(|c| c.is_ascii_digit()) || parts[0].len() < 2 {
        return false;
    }
    if !ok_part(parts[1], 59) || !ok_part(parts[2], 59) {
        return false;
    }
    if let Some(ms) = ms_part {
        if ms.len() != 3 || !ms.chars().all(|c| c.is_ascii_digit()) {
            return false;
        }
    }
    true
}

/// Returns the set of valid tracking event names for the given spec version.
/// The set is spec-version-specific — 2.0/3.0 have different events than 4.x.
fn valid_tracking_events(v: &VastVersion) -> &'static [&'static str] {
    if v.at_least(&VastVersion::V4_1) {
        // 4.1 / 4.2 / 4.3 — interactiveStart added in 4.2 but included here
        // since 4.1 docs with that event are just ahead-of-spec, not wrong.
        &[
            "mute",
            "unmute",
            "pause",
            "resume",
            "rewind",
            "skip",
            "playerExpand",
            "playerCollapse",
            "loaded",
            "start",
            "firstQuartile",
            "midpoint",
            "thirdQuartile",
            "complete",
            "progress",
            "closeLinear",
            "creativeView",
            "acceptInvitation",
            "adExpand",
            "adCollapse",
            "minimize",
            "close",
            "overlayViewDuration",
            "otherAdInteraction",
            "interactiveStart",
        ]
    } else if v.at_least(&VastVersion::V4_0) {
        // 4.0: fullscreen/exitFullscreen removed, playerExpand/playerCollapse added.
        &[
            "mute",
            "unmute",
            "pause",
            "resume",
            "rewind",
            "skip",
            "playerExpand",
            "playerCollapse",
            "start",
            "firstQuartile",
            "midpoint",
            "thirdQuartile",
            "complete",
            "progress",
            "creativeView",
            "acceptInvitationLinear",
            "timeSpentViewing",
            "acceptInvitation",
            "adExpand",
            "adCollapse",
            "minimize",
            "close",
            "overlayViewDuration",
            "otherAdInteraction",
        ]
    } else if v.at_least(&VastVersion::V3_0) {
        // 3.0: added skip, progress, exitFullscreen, acceptInvitationLinear, closeLinear.
        &[
            "creativeView",
            "start",
            "midpoint",
            "firstQuartile",
            "thirdQuartile",
            "complete",
            "mute",
            "unmute",
            "pause",
            "rewind",
            "resume",
            "fullscreen",
            "exitFullscreen",
            "expand",
            "collapse",
            "acceptInvitation",
            "close",
            "skip",
            "progress",
            "acceptInvitationLinear",
            "closeLinear",
        ]
    } else {
        // 2.0 base set.
        &[
            "creativeView",
            "start",
            "midpoint",
            "firstQuartile",
            "thirdQuartile",
            "complete",
            "mute",
            "unmute",
            "pause",
            "rewind",
            "resume",
            "fullscreen",
            "expand",
            "collapse",
            "acceptInvitation",
            "close",
        ]
    }
}