microsoft-webui-protocol 0.0.25

Core protocol definitions for WebUI framework
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
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

//! Shared state-projection manifest schema and structural validation.

use serde::de::{MapAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::fmt;
use std::marker::PhantomData;
use std::path::{Component, Path};
use thiserror::Error;

/// Stable manifest diagnostic codes shared by all hosts.
pub mod codes {
    pub const UNSUPPORTED_SCHEMA: &str = "PROJ-M002";
    pub const BUILD_ID_MISMATCH: &str = "PROJ-M005";
    pub const INVALID_JSON: &str = "PROJ-M008";
    pub const INVALID_FIELD: &str = "PROJ-M009";
    pub const TOO_MANY_COMPONENTS: &str = "PROJ-S002";
    pub const PATH_TRAVERSAL: &str = "PROJ-S003";
    pub const INVALID_HASH_FORMAT: &str = "PROJ-S004";
}

/// Current projection manifest schema identifier.
pub const SCHEMA_ID: &str = "webui.state-projection/v1";
/// Required producer identity.
pub const PRODUCER_NAME: &str = "@microsoft/webui/projection.js";
/// Maximum component entries in one fragment.
pub const MAX_COMPONENT_COUNT: usize = 65_535;
/// Maximum parent segments in `root`.
pub const MAX_ROOT_PARENTS: usize = 32;

/// A structurally invalid projection manifest.
#[derive(Debug, Error)]
#[error("{message}")]
pub struct ProjectionManifestError {
    code: &'static str,
    message: String,
}

impl ProjectionManifestError {
    #[must_use]
    pub const fn code(&self) -> &'static str {
        self.code
    }
}

/// Versioned projection manifest fragment.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ProjectionManifest {
    /// Versioned schema identifier.
    pub schema: String,
    /// Producer package identity.
    pub producer: ProjectionProducer,
    /// Adapter and bundler identity.
    pub adapter: ProjectionAdapter,
    /// Build root relative to the manifest directory.
    pub root: String,
    /// Hash of normalized graph edges and output membership.
    pub analysis_hash: String,
    /// Deterministic hash of the complete manifest proof.
    pub build_id: String,
    /// Emitted output path/virtual ID to content hash.
    #[serde(deserialize_with = "deserialize_unique_map")]
    pub outputs: BTreeMap<String, String>,
    /// Input path/virtual ID to content hash.
    #[serde(deserialize_with = "deserialize_unique_map")]
    pub inputs: BTreeMap<String, String>,
    /// Exact component surfaces keyed by custom-element tag.
    #[serde(deserialize_with = "deserialize_unique_map")]
    pub components: BTreeMap<String, ProjectionComponent>,
    /// Per-entry static import closure, keyed by entry output.
    ///
    /// Each value lists the **other** outputs an entry pulls in through static
    /// `import` statements, transitively, ordered largest-first. Dynamic
    /// `import()` edges are excluded: those are meant to cost a round trip.
    ///
    /// The bundler is the only party that knows output sizes, so it sorts.
    /// Consumers use the order as given rather than re-deriving it.
    ///
    /// Optional so manifests produced before this field existed still validate
    /// and still reproduce their original [`build_id`](Self::build_id).
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    #[serde(deserialize_with = "deserialize_unique_map")]
    pub entry_closures: BTreeMap<String, Vec<String>>,
}

/// Manifest producer identity.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProjectionProducer {
    /// Producer package name.
    pub name: String,
    /// Producer package version.
    pub version: String,
}

/// Bundler adapter identity.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProjectionAdapter {
    /// Adapter name.
    pub name: String,
    /// Bundler name and version.
    pub bundler: String,
}

/// One shipped component's exact state surfaces.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ProjectionComponent {
    /// Defining input module key.
    pub module: String,
    /// Output keys containing the component.
    pub outputs: Vec<String>,
    /// Exact initial `@observable` keys.
    pub hydration_keys: Vec<String>,
    /// Exact navigation `@observable + @attr` keys.
    pub navigation_keys: Vec<String>,
}

impl ProjectionManifest {
    /// Parse and structurally validate one JSON manifest.
    pub fn from_slice(bytes: &[u8]) -> Result<Self, ProjectionManifestError> {
        let manifest: Self = serde_json::from_slice(bytes).map_err(parse_error)?;
        manifest.validate()?;
        Ok(manifest)
    }

    /// Validate schema, hashes, references, ordering, and deterministic ID.
    pub fn validate(&self) -> Result<(), ProjectionManifestError> {
        if self.schema != SCHEMA_ID {
            return Err(error(
                codes::UNSUPPORTED_SCHEMA,
                format!("unsupported projection schema '{}'", self.schema),
            ));
        }
        if self.producer.name != PRODUCER_NAME || self.producer.version.is_empty() {
            return Err(invalid_field(
                "producer must identify @microsoft/webui/projection.js with a non-empty version",
            ));
        }
        if self.adapter.name.is_empty() || self.adapter.bundler.is_empty() {
            return Err(invalid_field(
                "adapter.name and adapter.bundler must be non-empty",
            ));
        }
        if !is_canonical_root(&self.root) {
            return Err(error(
                codes::PATH_TRAVERSAL,
                "root must be '.' or at most 32 parent-only segments",
            ));
        }
        if !is_sha256(&self.analysis_hash) || !is_sha256(&self.build_id) {
            return Err(error(
                codes::INVALID_HASH_FORMAT,
                "analysisHash and buildId must be lowercase SHA-256 values",
            ));
        }
        if self.components.len() > MAX_COMPONENT_COUNT {
            return Err(error(
                codes::TOO_MANY_COMPONENTS,
                format!(
                    "manifest declares {} components, exceeding {}",
                    self.components.len(),
                    MAX_COMPONENT_COUNT
                ),
            ));
        }
        validate_hash_map(&self.inputs)?;
        validate_hash_map(&self.outputs)?;
        validate_components(self)?;
        validate_entry_closures(self)?;
        if self.compute_build_id() != self.build_id {
            return Err(error(
                codes::BUILD_ID_MISMATCH,
                "buildId does not match the canonical manifest contents",
            ));
        }
        Ok(())
    }

    /// Recompute the deterministic cross-language build ID.
    #[must_use]
    pub fn compute_build_id(&self) -> String {
        let mut canonical = String::with_capacity(512);
        append_record(&mut canonical, "schema", &[SCHEMA_ID]);
        append_record(
            &mut canonical,
            "producer",
            &[&self.producer.name, &self.producer.version],
        );
        append_record(
            &mut canonical,
            "adapter",
            &[&self.adapter.name, &self.adapter.bundler],
        );
        append_record(&mut canonical, "root", &[&self.root]);
        append_record(&mut canonical, "analysis", &[&self.analysis_hash]);

        let input_count = self.inputs.len().to_string();
        append_record(&mut canonical, "inputs", &[&input_count]);
        for (path, hash) in &self.inputs {
            append_record(&mut canonical, "input", &[path, hash]);
        }

        let output_count = self.outputs.len().to_string();
        append_record(&mut canonical, "outputs", &[&output_count]);
        for (path, hash) in &self.outputs {
            append_record(&mut canonical, "output", &[path, hash]);
        }

        let component_count = self.components.len().to_string();
        append_record(&mut canonical, "components", &[&component_count]);
        for (tag, component) in &self.components {
            let output_count = component.outputs.len().to_string();
            let hydration_count = component.hydration_keys.len().to_string();
            let navigation_count = component.navigation_keys.len().to_string();
            let mut fields = Vec::with_capacity(
                5 + component.outputs.len()
                    + component.hydration_keys.len()
                    + component.navigation_keys.len(),
            );
            fields.push(tag.as_str());
            fields.push(component.module.as_str());
            fields.push(output_count.as_str());
            fields.extend(component.outputs.iter().map(String::as_str));
            fields.push(hydration_count.as_str());
            fields.extend(component.hydration_keys.iter().map(String::as_str));
            fields.push(navigation_count.as_str());
            fields.extend(component.navigation_keys.iter().map(String::as_str));
            append_record(&mut canonical, "component", &fields);
        }

        // Appended only when present so manifests produced before this field
        // existed keep reproducing their original build ID.
        if !self.entry_closures.is_empty() {
            let closure_count = self.entry_closures.len().to_string();
            append_record(&mut canonical, "entryClosures", &[&closure_count]);
            for (entry, closure) in &self.entry_closures {
                let member_count = closure.len().to_string();
                let mut fields = Vec::with_capacity(2 + closure.len());
                fields.push(entry.as_str());
                fields.push(member_count.as_str());
                fields.extend(closure.iter().map(String::as_str));
                append_record(&mut canonical, "entryClosure", &fields);
            }
        }
        hash_bytes(canonical.as_bytes())
    }
}

/// Validate that every entry closure references declared, distinct outputs.
///
/// Closure order is meaningful (largest-first) and therefore deliberately not
/// required to be sorted — only to be free of duplicates and self-references.
fn validate_entry_closures(manifest: &ProjectionManifest) -> Result<(), ProjectionManifestError> {
    for (entry, closure) in &manifest.entry_closures {
        if !manifest.outputs.contains_key(entry) {
            return Err(invalid_field(&format!(
                "entry closure key '{entry}' is absent from outputs"
            )));
        }
        for member in closure {
            if member == entry {
                return Err(invalid_field(&format!(
                    "entry closure '{entry}' includes itself"
                )));
            }
            if !manifest.outputs.contains_key(member) {
                return Err(invalid_field(&format!(
                    "entry closure '{entry}' references undeclared output '{member}'"
                )));
            }
        }
        if has_duplicate(closure) {
            return Err(invalid_field(&format!(
                "entry closure '{entry}' repeats an output"
            )));
        }
    }
    Ok(())
}

/// Duplicate check that preserves a meaningful, non-sorted order.
///
/// Closures are O(1-10) members, so the quadratic scan avoids allocating a set
/// for what is almost always a two-element list.
fn has_duplicate(values: &[String]) -> bool {
    for (index, value) in values.iter().enumerate() {
        if values[index + 1..].contains(value) {
            return true;
        }
    }
    false
}

fn validate_hash_map(values: &BTreeMap<String, String>) -> Result<(), ProjectionManifestError> {
    for (path, hash) in values {
        if is_virtual_key(path) {
            if !is_canonical_virtual_key(path) || hash != "virtual" {
                return Err(error(
                    codes::INVALID_HASH_FORMAT,
                    format!("invalid virtual/hash pairing for '{path}'"),
                ));
            }
        } else {
            if !is_canonical_file_key(path) {
                return Err(error(
                    codes::PATH_TRAVERSAL,
                    format!("unsafe or non-canonical manifest path '{path}'"),
                ));
            }
            if !is_sha256(hash) {
                return Err(error(
                    codes::INVALID_HASH_FORMAT,
                    format!("invalid physical-file hash for '{path}'"),
                ));
            }
        }
    }
    Ok(())
}

fn validate_components(manifest: &ProjectionManifest) -> Result<(), ProjectionManifestError> {
    for (tag, component) in &manifest.components {
        if !is_component_tag(tag) {
            return Err(invalid_field(&format!(
                "component tag '{tag}' is not lowercase custom-element syntax"
            )));
        }
        if !manifest.inputs.contains_key(&component.module) {
            return Err(invalid_field(&format!(
                "component <{tag}> module '{}' is absent from inputs",
                component.module
            )));
        }
        if component.outputs.is_empty() || !is_sorted_unique(&component.outputs) {
            return Err(invalid_field(&format!(
                "component <{tag}> outputs must be non-empty, sorted, and unique"
            )));
        }
        if component
            .outputs
            .iter()
            .any(|output| !manifest.outputs.contains_key(output))
        {
            return Err(invalid_field(&format!(
                "component <{tag}> references an undeclared output"
            )));
        }
        if !valid_keys(&component.hydration_keys)
            || !valid_keys(&component.navigation_keys)
            || component
                .hydration_keys
                .iter()
                .any(|key| component.navigation_keys.binary_search(key).is_err())
        {
            return Err(invalid_field(&format!(
                "component <{tag}> key surfaces are invalid or navigation is not a hydration superset"
            )));
        }
    }
    Ok(())
}

fn valid_keys(values: &[String]) -> bool {
    is_sorted_unique(values)
        && values
            .iter()
            .all(|value| !value.is_empty() && !has_control(value))
}

fn deserialize_unique_map<'de, D, T>(deserializer: D) -> Result<BTreeMap<String, T>, D::Error>
where
    D: Deserializer<'de>,
    T: Deserialize<'de>,
{
    deserializer.deserialize_map(UniqueMapVisitor(PhantomData))
}

struct UniqueMapVisitor<T>(PhantomData<T>);

impl<'de, T> Visitor<'de> for UniqueMapVisitor<T>
where
    T: Deserialize<'de>,
{
    type Value = BTreeMap<String, T>;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("an object with unique string keys")
    }

    fn visit_map<A>(self, mut access: A) -> Result<Self::Value, A::Error>
    where
        A: MapAccess<'de>,
    {
        let mut values = BTreeMap::new();
        while let Some((key, value)) = access.next_entry::<String, T>()? {
            if values.insert(key.clone(), value).is_some() {
                return Err(serde::de::Error::custom(format!(
                    "duplicate object key '{key}'"
                )));
            }
        }
        Ok(values)
    }
}

fn parse_error(source: serde_json::Error) -> ProjectionManifestError {
    let code = if source.classify() == serde_json::error::Category::Syntax
        || source.classify() == serde_json::error::Category::Eof
    {
        codes::INVALID_JSON
    } else {
        codes::INVALID_FIELD
    };
    error(
        code,
        format!("projection manifest could not be parsed: {source}"),
    )
}

fn invalid_field(message: &str) -> ProjectionManifestError {
    error(codes::INVALID_FIELD, message)
}

fn error(code: &'static str, message: impl Into<String>) -> ProjectionManifestError {
    ProjectionManifestError {
        code,
        message: message.into(),
    }
}

fn append_record(output: &mut String, label: &str, fields: &[&str]) {
    output.push_str(label);
    for field in fields {
        output.push_str(&field.len().to_string());
        output.push(':');
        output.push_str(field);
    }
    output.push('\n');
}

fn hash_bytes(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let digest = Sha256::digest(bytes);
    let mut output = String::with_capacity(71);
    output.push_str("sha256:");
    for byte in digest {
        output.push(char::from(HEX[usize::from(byte >> 4)]));
        output.push(char::from(HEX[usize::from(byte & 0x0f)]));
    }
    output
}

/// Whether a value is exactly `sha256:` plus 64 lowercase hex characters.
#[must_use]
pub fn is_sha256(value: &str) -> bool {
    let Some(hex) = value.strip_prefix("sha256:") else {
        return false;
    };
    hex.len() == 64 && hex.bytes().all(is_lower_hex)
}

fn is_lower_hex(byte: u8) -> bool {
    byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)
}

/// Whether a manifest key identifies a virtual module/output.
#[must_use]
pub fn is_virtual_key(value: &str) -> bool {
    value.starts_with("virtual:")
}

fn is_canonical_virtual_key(value: &str) -> bool {
    let Some(hex) = value.strip_prefix("virtual:") else {
        return false;
    };
    !hex.is_empty() && hex.len().is_multiple_of(2) && hex.bytes().all(is_lower_hex)
}

/// Whether a physical manifest key is safe and canonical.
#[must_use]
pub fn is_canonical_file_key(value: &str) -> bool {
    if value.is_empty()
        || value.starts_with('/')
        || value.starts_with("./")
        || value.contains('\\')
        || has_control(value)
    {
        return false;
    }
    let mut saw_segment = false;
    for component in Path::new(value).components() {
        match component {
            Component::Normal(segment) if !segment.is_empty() => saw_segment = true,
            _ => return false,
        }
    }
    saw_segment && value.split('/').all(|segment| !segment.is_empty())
}

fn is_canonical_root(value: &str) -> bool {
    if value == "." {
        return true;
    }
    let segments: Vec<&str> = value.split('/').collect();
    !segments.is_empty()
        && segments.len() <= MAX_ROOT_PARENTS
        && segments.iter().all(|segment| *segment == "..")
}

fn has_control(value: &str) -> bool {
    value.chars().any(char::is_control)
}

fn is_component_tag(value: &str) -> bool {
    let bytes = value.as_bytes();
    if bytes.len() < 3 || !bytes.contains(&b'-') || !bytes[0].is_ascii_lowercase() {
        return false;
    }
    bytes.iter().all(|byte| {
        byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(*byte, b'-' | b'.' | b'_')
    })
}

fn is_sorted_unique(values: &[String]) -> bool {
    values
        .windows(2)
        .all(|pair| pair[0].as_bytes() < pair[1].as_bytes())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn cross_language_build_id_matches() {
        let mut manifest = ProjectionManifest {
            schema: SCHEMA_ID.to_string(),
            producer: ProjectionProducer {
                name: PRODUCER_NAME.to_string(),
                version: "0.0.18".to_string(),
            },
            adapter: ProjectionAdapter {
                name: "esbuild".to_string(),
                bundler: "esbuild@0.28.1".to_string(),
            },
            root: "..".to_string(),
            analysis_hash: format!("sha256:{}", "1".repeat(64)),
            build_id: String::new(),
            outputs: BTreeMap::from([(
                "dist/a.js".to_string(),
                format!("sha256:{}", "3".repeat(64)),
            )]),
            inputs: BTreeMap::from([(
                "src/a.ts".to_string(),
                format!("sha256:{}", "2".repeat(64)),
            )]),
            components: BTreeMap::from([(
                "a-card".to_string(),
                ProjectionComponent {
                    module: "src/a.ts".to_string(),
                    outputs: vec!["dist/a.js".to_string()],
                    hydration_keys: vec!["displayValue".to_string()],
                    navigation_keys: vec!["displayValue".to_string(), "é".to_string()],
                },
            )]),
            entry_closures: BTreeMap::new(),
        };
        manifest.build_id = manifest.compute_build_id();
        assert_eq!(
            manifest.build_id,
            "sha256:8319202a060626c39cce76df50197c92dee27aab29d601161183c188204d7c18"
        );
        assert!(manifest.validate().is_ok());
    }

    #[test]
    fn duplicate_json_key_is_rejected() {
        let error = ProjectionManifest::from_slice(
            br#"{"schema":"webui.state-projection/v1","schema":"duplicate"}"#,
        )
        .unwrap_err();
        assert_eq!(error.code(), codes::INVALID_FIELD);
    }

    /// Build a two-output manifest so entry-closure cases have somewhere to point.
    fn manifest_with_closures(closures: BTreeMap<String, Vec<String>>) -> ProjectionManifest {
        let mut manifest = ProjectionManifest {
            schema: SCHEMA_ID.to_string(),
            producer: ProjectionProducer {
                name: PRODUCER_NAME.to_string(),
                version: "0.0.19".to_string(),
            },
            adapter: ProjectionAdapter {
                name: "esbuild".to_string(),
                bundler: "esbuild@0.28.1".to_string(),
            },
            root: "..".to_string(),
            analysis_hash: format!("sha256:{}", "1".repeat(64)),
            build_id: String::new(),
            outputs: BTreeMap::from([
                (
                    "dist/index.js".to_string(),
                    format!("sha256:{}", "3".repeat(64)),
                ),
                (
                    "dist/chunk.js".to_string(),
                    format!("sha256:{}", "4".repeat(64)),
                ),
            ]),
            inputs: BTreeMap::from([(
                "src/a.ts".to_string(),
                format!("sha256:{}", "2".repeat(64)),
            )]),
            components: BTreeMap::new(),
            entry_closures: closures,
        };
        manifest.build_id = manifest.compute_build_id();
        manifest
    }

    #[test]
    fn entry_closure_accepts_declared_outputs() {
        let manifest = manifest_with_closures(BTreeMap::from([(
            "dist/index.js".to_string(),
            vec!["dist/chunk.js".to_string()],
        )]));
        assert!(manifest.validate().is_ok());
    }

    #[test]
    fn entry_closure_rejects_undeclared_key() {
        let manifest = manifest_with_closures(BTreeMap::from([(
            "dist/missing.js".to_string(),
            vec!["dist/chunk.js".to_string()],
        )]));
        let error = manifest.validate().unwrap_err();
        assert_eq!(error.code(), codes::INVALID_FIELD);
    }

    #[test]
    fn entry_closure_rejects_undeclared_member() {
        let manifest = manifest_with_closures(BTreeMap::from([(
            "dist/index.js".to_string(),
            vec!["dist/absent.js".to_string()],
        )]));
        let error = manifest.validate().unwrap_err();
        assert_eq!(error.code(), codes::INVALID_FIELD);
    }

    #[test]
    fn entry_closure_rejects_self_reference() {
        let manifest = manifest_with_closures(BTreeMap::from([(
            "dist/index.js".to_string(),
            vec!["dist/index.js".to_string()],
        )]));
        let error = manifest.validate().unwrap_err();
        assert_eq!(error.code(), codes::INVALID_FIELD);
    }

    #[test]
    fn entry_closure_rejects_repeated_member() {
        let manifest = manifest_with_closures(BTreeMap::from([(
            "dist/index.js".to_string(),
            vec!["dist/chunk.js".to_string(), "dist/chunk.js".to_string()],
        )]));
        let error = manifest.validate().unwrap_err();
        assert_eq!(error.code(), codes::INVALID_FIELD);
    }

    #[test]
    fn entry_closure_order_changes_build_id() {
        let unordered = manifest_with_closures(BTreeMap::new());
        let one = manifest_with_closures(BTreeMap::from([(
            "dist/index.js".to_string(),
            vec!["dist/chunk.js".to_string()],
        )]));
        assert_ne!(unordered.compute_build_id(), one.compute_build_id());

        // Closures are largest-first, so member order is load order and must be
        // covered by the build ID rather than normalized away. Both arms are
        // kept valid, so this proves the property for closures a real build can
        // emit rather than for self-referential ones `validate` rejects.
        let mut a = manifest_with_closures(BTreeMap::new());
        a.outputs.insert(
            "dist/shared.js".to_string(),
            format!("sha256:{}", "5".repeat(64)),
        );
        let mut b = a.clone();
        a.entry_closures = BTreeMap::from([(
            "dist/index.js".to_string(),
            vec!["dist/chunk.js".to_string(), "dist/shared.js".to_string()],
        )]);
        b.entry_closures = BTreeMap::from([(
            "dist/index.js".to_string(),
            vec!["dist/shared.js".to_string(), "dist/chunk.js".to_string()],
        )]);
        assert_ne!(a.compute_build_id(), b.compute_build_id());

        a.build_id = a.compute_build_id();
        b.build_id = b.compute_build_id();
        assert!(a.validate().is_ok());
        assert!(b.validate().is_ok());
    }

    #[test]
    fn entry_closure_round_trips_as_camel_case() {
        let manifest = manifest_with_closures(BTreeMap::from([(
            "dist/index.js".to_string(),
            vec!["dist/chunk.js".to_string()],
        )]));
        let json = serde_json::to_vec(&manifest).expect("manifest serializes");
        assert!(String::from_utf8_lossy(&json).contains("\"entryClosures\""));

        let parsed = ProjectionManifest::from_slice(&json).expect("manifest parses");
        assert_eq!(
            parsed.entry_closures.get("dist/index.js"),
            Some(&vec!["dist/chunk.js".to_string()])
        );
    }

    #[test]
    fn absent_entry_closures_parse_as_empty() {
        let mut manifest = manifest_with_closures(BTreeMap::new());
        manifest.build_id = manifest.compute_build_id();
        let json = serde_json::to_vec(&manifest).expect("manifest serializes");
        assert!(!String::from_utf8_lossy(&json).contains("entryClosures"));
        assert!(ProjectionManifest::from_slice(&json).is_ok());
    }
}