portaki-cli 3.1.0

Portaki module CLI (portaki) — init, build, lint, test, and OCI publish
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
//! Collects module files into OCI layers for push.

use std::fs;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use oci_distribution::client::ImageLayer;
use serde::Deserialize;

pub const MANIFEST_MEDIA: &str = "application/vnd.portaki.manifest+json";
pub const SDK_MANIFEST_MEDIA: &str = "application/vnd.portaki.sdk.manifest+json";
const WASM_MEDIA: &str = "application/wasm";
const I18N_MEDIA: &str = "application/vnd.portaki.i18n+json";
const MIGRATIONS_BUNDLE_MEDIA: &str = "application/vnd.portaki.migrations+json";
pub const MIGRATIONS_BUNDLE: &str = "migrations.bundle.json";
const OPERATIONS_BUNDLE_MEDIA: &str = "application/vnd.portaki.operations+json";
pub const OPERATIONS_BUNDLE: &str = "operations.bundle.json";

/// OCI host-catalog layer (`portaki.module.json` freeze) — consumed by API / install.
pub const PUBLISH_MANIFEST: &str = "publish-manifest.json";
/// SDK emissions manifest (`target/portaki/manifest.json`) — wasm surfaces, capabilities, i18n keys.
pub const SDK_MANIFEST: &str = "manifest.json";

/// One blob to upload with its OCI media type.
#[derive(Debug, Clone)]
pub struct PushLayer {
    pub path: PathBuf,
    pub media_type: String,
}

/// Module coordinates read from the publish manifest.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModuleCoordinates {
    pub id: String,
    pub version: String,
}

/// Parsed publish / SDK manifest (`id` + `version` for OCI tag).
#[derive(Debug, Deserialize)]
struct ArtifactManifest {
    id: String,
    version: String,
}

/// Path to the frozen manifest produced by `portaki build`.
pub fn publish_manifest_path(artifact_dir: &Path) -> PathBuf {
    artifact_dir.join(PUBLISH_MANIFEST)
}

/// Assembles `target/portaki/publish-manifest.json` from sources (catalog + optional SDK build output).
pub fn assemble_publish_manifest(module_root: &Path, artifact_dir: &Path) -> Result<PathBuf> {
    fs::create_dir_all(artifact_dir).context("create artifact dir")?;
    let dest = publish_manifest_path(artifact_dir);
    let catalog_path = module_root.join("portaki.module.json");
    let sdk_path = artifact_dir.join("manifest.json");

    let source = if catalog_path.exists() {
        catalog_path
    } else if sdk_path.exists() {
        sdk_path
    } else {
        anyhow::bail!(
            "missing portaki.module.json or {} — run portaki build first",
            sdk_path.display()
        );
    };

    let raw = fs::read_to_string(&source).with_context(|| format!("read {}", source.display()))?;
    let stamped = stamp_sdk_version(&raw, resolved_sdk_version(module_root)?)?;
    fs::write(&dest, stamped).with_context(|| format!("write {}", dest.display()))?;
    Ok(dest)
}

/// Version de `portaki-sdk` <strong>réellement liée</strong>, lue dans le graphe résolu par cargo.
///
/// Pas celle déclarée : les modules dépendent du SDK par `workspace = true`, dont la contrainte
/// vaut `*`. Ce qui compte pour choisir un bundle de contrats est ce contre quoi le binaire a été
/// compilé, pas ce que quelqu'un a écrit à côté.
///
/// Rend `None` quand cargo ne répond pas ou que le SDK n'est pas dans le graphe — un module qui
/// n'en dépend pas ne se voit pas inventer une version.
pub(crate) fn resolved_sdk_version(module_root: &Path) -> Result<Option<String>> {
    let output = std::process::Command::new("cargo")
        .args(["metadata", "--format-version", "1"])
        .current_dir(module_root)
        .output();
    let output = match output {
        Ok(o) if o.status.success() => o,
        _ => return Ok(None),
    };
    let metadata: serde_json::Value =
        serde_json::from_slice(&output.stdout).context("parse cargo metadata")?;
    let found = metadata
        .get("packages")
        .and_then(|p| p.as_array())
        .into_iter()
        .flatten()
        .find(|p| p.get("name").and_then(|n| n.as_str()) == Some("portaki-sdk"))
        .and_then(|p| p.get("version"))
        .and_then(|v| v.as_str())
        .map(str::to_string);
    Ok(found)
}

/// Recopie ce que le build a emis dans le manifeste envoye a la sandbox : les surfaces, les
/// queries et les commands.
///
/// Deux manifestes coexistent et ne disent pas la meme chose. `portaki.module.json` decrit la
/// navigation du dashboard : ses `hostSurfaces` portent un `pathSegment`, qui est un morceau
/// d'URL. Le manifeste emis par le build decrit ce que le binaire exporte reellement :
/// `surfaces.host[].id` vaut `main`, et le symbole associe est `render_host_main`.
///
/// La sandbox ne recevait que le premier. Il en deduisait un identifiant de surface egal au
/// `pathSegment` — `access-guide` —, le runtime cherchait `render_host_access_guide`, et aucun
/// module ne l'exporte : les vingt modules qui declarent une surface hote echouaient sur
/// `wasm_handler_not_found`. La production, elle, marche parce que le dashboard envoie `main`.
///
/// Corriger les vingt manifestes ecrits a la main serait une seconde source de verite pour une
/// chose que le build sait deja. On transporte donc ce qu'il a emis.
///
/// Les operations suivent le meme chemin, pour la meme raison : `#[portaki_sdk::query]` et
/// `#[portaki_sdk::command]` n'existent que dans le manifeste emis, et un module wasm n'exporte
/// que `portaki_query` / `portaki_command` — le binaire ne sait pas dire ce qu'il sert. Sans
/// elles, la sandbox ne pouvait proposer aucune liste d'operations et retombait sur un champ
/// libre, ou une faute de frappe ne se decouvrait qu'au `handler_not_found`.
pub fn stamp_built_declarations(raw: &str, built_manifest: &str) -> Result<String> {
    let built: serde_json::Value =
        serde_json::from_str(built_manifest).context("parse built manifest")?;
    let carried: Vec<(&str, &serde_json::Value)> = BUILT_DECLARATIONS
        .iter()
        .filter_map(|key| built.get(*key).map(|value| (*key, value)))
        .collect();
    if carried.is_empty() {
        return Ok(raw.to_string());
    }
    let mut manifest: serde_json::Value =
        serde_json::from_str(raw).context("parse module manifest")?;
    if let Some(object) = manifest.as_object_mut() {
        for (key, value) in carried {
            object.insert(key.to_string(), value.clone());
        }
    }
    serde_json::to_string_pretty(&manifest).context("serialise module manifest")
}

/// Ce que seul le build sait dire, et que la sandbox doit donc recevoir de lui.
const BUILT_DECLARATIONS: [&str; 3] = ["surfaces", "queries", "commands"];

/// Inscrit `requiresModuleSdk` dans le manifeste, ou refuse si l'auteur en annonce un autre.
///
/// Le champ existe au schéma depuis longtemps et <strong>aucun module ne le remplissait</strong> :
/// la plateforme n'avait donc rien pour choisir le bon jeu de contrats. L'inscrire au build le
/// rend exact par construction plutôt que par discipline.
pub fn stamp_sdk_version(raw: &str, resolved: Option<String>) -> Result<String> {
    let Some(resolved) = resolved else {
        return Ok(raw.to_string());
    };
    let mut manifest: serde_json::Value =
        serde_json::from_str(raw).context("parse module manifest")?;
    match manifest.get("requiresModuleSdk").and_then(|v| v.as_str()) {
        Some(declared) if declared != resolved => anyhow::bail!(
            "portaki.module.json declares requiresModuleSdk {declared} but the build linked \
             portaki-sdk {resolved} — drop the field and let the build stamp it"
        ),
        _ => {}
    }
    if let Some(object) = manifest.as_object_mut() {
        object.insert(
            "requiresModuleSdk".to_string(),
            serde_json::Value::String(resolved),
        );
    }
    serde_json::to_string_pretty(&manifest).context("serialise module manifest")
}

/// Reads module id/version from `publish-manifest.json` under `artifact_dir`.
pub fn read_module_coordinates(
    _module_root: &Path,
    artifact_dir: &Path,
) -> Result<ModuleCoordinates> {
    let manifest_path = publish_manifest_path(artifact_dir);
    let raw = std::fs::read_to_string(&manifest_path)
        .with_context(|| format!("read {}", manifest_path.display()))?;
    let manifest: ArtifactManifest =
        serde_json::from_str(&raw).context("parse publish-manifest.json")?;
    Ok(ModuleCoordinates {
        id: manifest.id,
        version: manifest.version,
    })
}

/// Lit id/version dans `portaki.module.json`, sans passer par un build.
///
/// C'est ce qui permet d'annoncer au registre une version déjà présente sur GHCR : rien à
/// recompiler, rien à repousser, donc aucun jeton d'écriture nécessaire.
pub fn read_source_coordinates(module_root: &Path) -> Result<ModuleCoordinates> {
    let manifest_path = module_root.join("portaki.module.json");
    let raw = std::fs::read_to_string(&manifest_path)
        .with_context(|| format!("read {}", manifest_path.display()))?;
    let manifest: ArtifactManifest =
        serde_json::from_str(&raw).context("parse portaki.module.json")?;
    Ok(ModuleCoordinates {
        id: manifest.id,
        version: manifest.version,
    })
}

/// Builds the OCI image reference `registry/portaki-modules-{module_id}:version`.
pub fn image_reference(registry: &str, coords: &ModuleCoordinates) -> Result<String> {
    let registry = registry.trim_end_matches('/');
    if registry.is_empty() {
        anyhow::bail!("registry must not be empty");
    }
    let owner = registry
        .strip_suffix("/portaki-modules")
        .unwrap_or(registry);
    Ok(format!(
        "{}/portaki-modules-{}:{}",
        owner, coords.id, coords.version
    ))
}

/// Discovers wasm + publish manifest + optional SDK manifest + i18n layers.
pub fn collect_push_layers(module_root: &Path, artifact_dir: &Path) -> Result<Vec<PushLayer>> {
    let coords = read_module_coordinates(module_root, artifact_dir)?;
    let mut layers = Vec::new();

    let catalog_layer_path = publish_manifest_path(artifact_dir);
    if !catalog_layer_path.exists() {
        anyhow::bail!(
            "missing {} — run portaki build before publish",
            catalog_layer_path.display()
        );
    }
    layers.push(PushLayer {
        path: catalog_layer_path.clone(),
        media_type: MANIFEST_MEDIA.to_string(),
    });

    let sdk_layer_path = artifact_dir.join(SDK_MANIFEST);
    if sdk_layer_path.exists() && publish_layer_is_host_catalog_shape(&catalog_layer_path)? {
        layers.push(PushLayer {
            path: sdk_layer_path,
            media_type: SDK_MANIFEST_MEDIA.to_string(),
        });
    }

    let wasm_path = find_wasm_artifact(module_root, &coords.id)?;
    layers.push(PushLayer {
        path: wasm_path,
        media_type: WASM_MEDIA.to_string(),
    });

    let migrations_path = artifact_dir.join(MIGRATIONS_BUNDLE);
    if migrations_path.is_file() {
        layers.push(PushLayer {
            path: migrations_path,
            media_type: MIGRATIONS_BUNDLE_MEDIA.to_string(),
        });
    }

    let operations_path = artifact_dir.join(OPERATIONS_BUNDLE);
    if operations_path.is_file() {
        layers.push(PushLayer {
            path: operations_path,
            media_type: OPERATIONS_BUNDLE_MEDIA.to_string(),
        });
    }

    let i18n_dir = module_root.join("i18n");
    if i18n_dir.is_dir() {
        let mut entries: Vec<PathBuf> = std::fs::read_dir(&i18n_dir)?
            .filter_map(Result::ok)
            .map(|entry| entry.path())
            .filter(|path| path.extension().and_then(|e| e.to_str()) == Some("json"))
            .collect();
        entries.sort();
        for path in entries {
            layers.push(PushLayer {
                path,
                media_type: I18N_MEDIA.to_string(),
            });
        }
    }

    Ok(layers)
}

/// Host catalog is identified by localized `name` map without `manifestVersion`.
fn publish_layer_is_host_catalog_shape(path: &Path) -> Result<bool> {
    let raw = fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
    let root: serde_json::Value = serde_json::from_str(&raw).context("parse manifest json")?;
    if root.get("manifestVersion").is_some() {
        return Ok(false);
    }
    Ok(root
        .get("name")
        .and_then(|n| n.as_object())
        .is_some_and(|m| !m.is_empty()))
}

/// Converts push layers to `oci-distribution` image layers (reads bytes from disk).
pub fn layers_to_image_layers(layers: &[PushLayer]) -> Result<Vec<ImageLayer>> {
    let mut image_layers = Vec::with_capacity(layers.len());
    for layer in layers {
        let data = std::fs::read(&layer.path)
            .with_context(|| format!("read layer {}", layer.path.display()))?;
        image_layers.push(ImageLayer::new(data, layer.media_type.clone(), None));
    }
    Ok(image_layers)
}

/// Locates the wasm cargo just built for `module_id`.
///
/// Cargo names a library artifact after the *target*, not the package: `access-guide`
/// produces `access_guide.wasm`. Only hyphenated module ids differ, which is why this went
/// unnoticed — every single-word module resolves on the first candidate.
///
/// Shared with `commands::dev`, deliberately: the two paths diverged, `publish` grew a
/// directory scan that saved it and `dev` did not, so the same module built and deployed
/// from CI while failing on the author's machine.
pub(crate) fn find_wasm_artifact(module_root: &Path, module_id: &str) -> Result<PathBuf> {
    let release_dir = module_root.join("target/wasm32-unknown-unknown/release");
    let candidates = [
        release_dir.join(format!("{module_id}.wasm")),
        release_dir.join(format!("{}.wasm", module_id.replace('-', "_"))),
    ];
    for candidate in &candidates {
        if candidate.exists() {
            return Ok(candidate.clone());
        }
    }

    if release_dir.is_dir() {
        let mut wasm_files: Vec<PathBuf> = std::fs::read_dir(&release_dir)?
            .filter_map(Result::ok)
            .map(|entry| entry.path())
            .filter(|path| path.extension().and_then(|e| e.to_str()) == Some("wasm"))
            .collect();
        wasm_files.sort();
        if let Some(path) = wasm_files.into_iter().next() {
            return Ok(path);
        }
    }

    anyhow::bail!(
        "no wasm artifact under {} — run portaki build --release first",
        release_dir.display()
    );
}

#[cfg(test)]
mod tests {
    /// Reprendre un catalogue déjà publié suppose de lire id/version sans build : le
    /// publish-manifest n'existe pas tant que rien n'a été compilé.
    #[test]
    fn the_linked_sdk_version_is_stamped_into_the_manifest() {
        let stamped = stamp_sdk_version(
            r#"{"id":"weather","version":"0.3.24"}"#,
            Some("2.1.1".into()),
        )
        .unwrap();

        let parsed: serde_json::Value = serde_json::from_str(&stamped).unwrap();
        assert_eq!(parsed["requiresModuleSdk"], "2.1.1");
        assert_eq!(parsed["id"], "weather");
    }

    /// Un manifeste qui annonce une autre version ment sur ce qui a été compilé.
    #[test]
    fn a_declared_version_that_disagrees_is_refused() {
        let err = stamp_sdk_version(
            r#"{"id":"weather","version":"0.3.24","requiresModuleSdk":"1.0.0"}"#,
            Some("2.1.1".into()),
        )
        .unwrap_err();

        assert!(err.to_string().contains("1.0.0"));
        assert!(err.to_string().contains("2.1.1"));
    }

    /// Déclarée et liée d'accord : rien à signaler.
    #[test]
    fn a_declared_version_that_agrees_passes() {
        stamp_sdk_version(
            r#"{"id":"weather","requiresModuleSdk":"2.1.1"}"#,
            Some("2.1.1".into()),
        )
        .unwrap();
    }

    /// Un module qui ne dépend pas du SDK ne se voit pas inventer une version.
    #[test]
    fn without_a_resolved_sdk_the_manifest_is_untouched() {
        let raw = r#"{"id":"weather","version":"0.3.24"}"#;

        assert_eq!(stamp_sdk_version(raw, None).unwrap(), raw);
    }

    /// La sandbox reçoit le manifeste tamponné, comme la publication.
    ///
    /// Sans ce tampon, `requiresModuleSdk` manquait dans tout module déployé par `portaki dev`,
    /// et l'inspecteur SDUI refusait de typer — pour tous les modules, toujours. Le message
    /// conseillait alors « reconstruisez avec portaki build », qui écrit ailleurs et n'y
    /// changeait rien.
    #[test]
    fn the_sandbox_manifest_carries_the_linked_sdk_version() {
        let raw = r#"{"id":"access-guide","version":"0.3.2"}"#;

        let stamped = stamp_sdk_version(raw, Some("2.1.1".to_string())).unwrap();

        let parsed: serde_json::Value = serde_json::from_str(&stamped).unwrap();
        assert_eq!(parsed["requiresModuleSdk"], "2.1.1");
        assert_eq!(parsed["id"], "access-guide");
    }

    #[test]
    fn source_coordinates_are_read_without_a_build() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("portaki.module.json"),
            r#"{"id":"weather","version":"0.3.24"}"#,
        )
        .unwrap();

        let coords = read_source_coordinates(dir.path()).unwrap();

        assert_eq!(coords.id, "weather");
        assert_eq!(coords.version, "0.3.24");
    }

    use super::*;
    use std::fs;
    use tempfile::tempdir;

    #[test]
    fn assemble_publish_manifest_copies_catalog_source() {
        let root = tempdir().unwrap();
        fs::write(
            root.path().join("portaki.module.json"),
            r#"{"id":"weather","version":"1.3.2"}"#,
        )
        .unwrap();
        let artifact = root.path().join("target/portaki");
        let path = assemble_publish_manifest(root.path(), &artifact).unwrap();
        assert_eq!(path, artifact.join(PUBLISH_MANIFEST));
        let raw = fs::read_to_string(&path).unwrap();
        assert!(raw.contains("\"version\":\"1.3.2\""));
    }

    #[test]
    fn assemble_publish_manifest_copies_sdk_manifest_when_no_catalog() {
        let root = tempdir().unwrap();
        let artifact = root.path().join("target/portaki");
        fs::create_dir_all(&artifact).unwrap();
        fs::write(
            artifact.join("manifest.json"),
            r#"{"id":"weather","version":"0.2.0"}"#,
        )
        .unwrap();
        assemble_publish_manifest(root.path(), &artifact).unwrap();
        let raw = fs::read_to_string(artifact.join(PUBLISH_MANIFEST)).unwrap();
        assert!(raw.contains("\"version\":\"0.2.0\""));
    }

    #[test]
    fn read_module_coordinates_reads_publish_manifest_only() {
        let dir = tempdir().unwrap();
        let artifact = dir.path().join("target/portaki");
        fs::create_dir_all(&artifact).unwrap();
        fs::write(
            dir.path().join("portaki.module.json"),
            r#"{"id":"stale","version":"0.0.1"}"#,
        )
        .unwrap();
        fs::write(
            artifact.join(PUBLISH_MANIFEST),
            r#"{"id":"weather","version":"0.2.0"}"#,
        )
        .unwrap();
        let coords = read_module_coordinates(dir.path(), &artifact).unwrap();
        assert_eq!(
            coords,
            ModuleCoordinates {
                id: "weather".to_string(),
                version: "0.2.0".to_string(),
            }
        );
    }

    #[test]
    fn image_reference_formats_registry_tag() {
        let coords = ModuleCoordinates {
            id: "weather".into(),
            version: "0.2.0".into(),
        };
        let reference = image_reference("ghcr.io/portakiapp/portaki-modules", &coords).unwrap();
        assert_eq!(
            reference,
            "ghcr.io/portakiapp/portaki-modules-weather:0.2.0"
        );
        let reference = image_reference("ghcr.io/portakiapp", &coords).unwrap();
        assert_eq!(
            reference,
            "ghcr.io/portakiapp/portaki-modules-weather:0.2.0"
        );
    }

    #[test]
    fn collect_push_layers_uses_publish_manifest_not_repo_catalog() {
        let root = tempdir().unwrap();
        fs::write(
            root.path().join("portaki.module.json"),
            r#"{"id":"weather","version":"9.9.9"}"#,
        )
        .unwrap();
        let artifact = root.path().join("target/portaki");
        fs::create_dir_all(&artifact).unwrap();
        fs::write(
            artifact.join(PUBLISH_MANIFEST),
            r#"{"id":"weather","version":"0.1.0"}"#,
        )
        .unwrap();

        let wasm_dir = root.path().join("target/wasm32-unknown-unknown/release");
        fs::create_dir_all(&wasm_dir).unwrap();
        fs::write(wasm_dir.join("weather.wasm"), b"\0asm").unwrap();

        let layers = collect_push_layers(root.path(), &artifact).unwrap();
        assert_eq!(layers.len(), 2);
        assert_eq!(layers[0].path, artifact.join(PUBLISH_MANIFEST));
        assert_eq!(layers[0].media_type, MANIFEST_MEDIA);
    }

    /// Cargo nomme l'artefact d'après la cible : `access-guide` produit `access_guide.wasm`.
    /// `portaki dev` lisait le nom du paquet tel quel et échouait sur tout module au nom
    /// composé, alors que `publish` s'en sortait par son balayage de répertoire.
    #[test]
    fn find_wasm_artifact_accepts_the_underscored_target_name() {
        let root = tempdir().unwrap();
        let wasm_dir = root.path().join("target/wasm32-unknown-unknown/release");
        fs::create_dir_all(&wasm_dir).unwrap();
        fs::write(wasm_dir.join("access_guide.wasm"), b"\0asm").unwrap();

        let found = find_wasm_artifact(root.path(), "access-guide").unwrap();
        assert_eq!(found, wasm_dir.join("access_guide.wasm"));
    }

    /// Le nom exact l'emporte sur la normalisation : un répertoire qui porte les deux ne doit
    /// pas dépendre de l'ordre de lecture.
    #[test]
    fn find_wasm_artifact_prefers_the_exact_name() {
        let root = tempdir().unwrap();
        let wasm_dir = root.path().join("target/wasm32-unknown-unknown/release");
        fs::create_dir_all(&wasm_dir).unwrap();
        fs::write(wasm_dir.join("access_guide.wasm"), b"\0asm").unwrap();
        fs::write(wasm_dir.join("access-guide.wasm"), b"\0asm").unwrap();

        let found = find_wasm_artifact(root.path(), "access-guide").unwrap();
        assert_eq!(found, wasm_dir.join("access-guide.wasm"));
    }

    #[test]
    fn find_wasm_artifact_reports_the_directory_when_nothing_was_built() {
        let root = tempdir().unwrap();
        let error = find_wasm_artifact(root.path(), "access-guide").unwrap_err();
        assert!(error.to_string().contains("no wasm artifact"));
    }

    #[test]
    fn collect_push_layers_includes_sdk_when_host_catalog_present() {
        let root = tempdir().unwrap();
        fs::write(
            root.path().join("portaki.module.json"),
            r#"{"id":"weather","version":"1.3.2","name":{"fr":"Météo","en":"Weather"},"description":{"fr":"d","en":"d"}}"#,
        )
        .unwrap();
        let artifact = root.path().join("target/portaki");
        fs::create_dir_all(&artifact).unwrap();
        fs::write(
            artifact.join(PUBLISH_MANIFEST),
            r#"{"id":"weather","version":"1.3.2","name":{"fr":"Météo","en":"Weather"},"description":{"fr":"d","en":"d"}}"#,
        )
        .unwrap();
        fs::write(
            artifact.join(SDK_MANIFEST),
            r#"{"manifestVersion":"1","id":"weather","version":"0.2.1","displayName":"module.name"}"#,
        )
        .unwrap();
        let wasm_dir = root.path().join("target/wasm32-unknown-unknown/release");
        fs::create_dir_all(&wasm_dir).unwrap();
        fs::write(wasm_dir.join("weather.wasm"), b"\0asm").unwrap();

        let layers = collect_push_layers(root.path(), &artifact).unwrap();
        assert_eq!(layers.len(), 3);
        assert_eq!(layers[0].media_type, MANIFEST_MEDIA);
        assert_eq!(layers[1].media_type, SDK_MANIFEST_MEDIA);
        assert_eq!(layers[1].path, artifact.join(SDK_MANIFEST));
    }

    #[test]
    fn collect_push_layers_sdk_only_single_manifest_layer() {
        let root = tempdir().unwrap();
        let artifact = root.path().join("target/portaki");
        fs::create_dir_all(&artifact).unwrap();
        fs::write(
            artifact.join(PUBLISH_MANIFEST),
            r#"{"manifestVersion":"1","id":"weather","version":"0.2.1"}"#,
        )
        .unwrap();
        let wasm_dir = root.path().join("target/wasm32-unknown-unknown/release");
        fs::create_dir_all(&wasm_dir).unwrap();
        fs::write(wasm_dir.join("weather.wasm"), b"\0asm").unwrap();

        let layers = collect_push_layers(root.path(), &artifact).unwrap();
        assert_eq!(layers.len(), 2);
        assert_eq!(layers[0].media_type, MANIFEST_MEDIA);
        assert!(layers
            .iter()
            .all(|layer| layer.media_type != SDK_MANIFEST_MEDIA));
    }
}

#[cfg(test)]
mod stamp_built_declarations_tests {
    use super::stamp_built_declarations as stamp_surfaces;

    const BUILT: &str = r#"{"id":"access-guide","surfaces":{"host":[{"id":"main","render_fn":"render_host_main"}],"guest":[]}}"#;

    /// Le manifeste ecrit a la main ne dit pas quel symbole appeler ; le build, si.
    #[test]
    fn carries_the_built_surfaces_into_the_uploaded_manifest() {
        let raw = r#"{"id":"access-guide","hostSurfaces":[{"pathSegment":"access-guide"}]}"#;

        let stamped = stamp_surfaces(raw, BUILT).expect("stamp");
        let value: serde_json::Value = serde_json::from_str(&stamped).expect("parse");

        assert_eq!(value["surfaces"]["host"][0]["id"], "main");
        // Ce que le manifeste disait deja n'est pas efface : le pathSegment reste une donnee
        // de navigation, utile au dashboard.
        assert_eq!(value["hostSurfaces"][0]["pathSegment"], "access-guide");
    }

    /// Un build sans emission ne doit pas empecher un deploiement.
    #[test]
    fn leaves_the_manifest_alone_when_the_build_declares_no_surface() {
        let raw = r#"{"id":"access-guide"}"#;

        let stamped = stamp_surfaces(raw, r#"{"id":"access-guide"}"#).expect("stamp");

        assert_eq!(stamped, raw);
    }

    /// Les operations n'existent que dans le manifeste emis : sans elles, la sandbox ne peut
    /// proposer que la saisie libre d'un nom d'operation.
    #[test]
    fn carries_the_built_operations_into_the_uploaded_manifest() {
        let raw = r#"{"id":"ical-sync"}"#;
        let built = r#"{"id":"ical-sync","queries":[{"name":"listSources","fn":"list_sources"}],"commands":[{"name":"syncNow","fn":"sync_now"}]}"#;

        let stamped = stamp_surfaces(raw, built).expect("stamp");
        let value: serde_json::Value = serde_json::from_str(&stamped).expect("parse");

        assert_eq!(value["queries"][0]["name"], "listSources");
        assert_eq!(value["commands"][0]["fn"], "sync_now");
        // Une cle que le build n'a pas emise n'est pas inventee.
        assert!(value.get("surfaces").is_none());
    }

    /// Une liste vide est une reponse : elle dit que le build n'expose rien, et elle voyage.
    #[test]
    fn carries_an_empty_operation_list_as_such() {
        let stamped = stamp_surfaces(r#"{"id":"m"}"#, r#"{"id":"m","queries":[],"commands":[]}"#)
            .expect("stamp");
        let value: serde_json::Value = serde_json::from_str(&stamped).expect("parse");

        assert_eq!(value["queries"], serde_json::json!([]));
        assert_eq!(value["commands"], serde_json::json!([]));
    }

    /// Les surfaces emises font foi : elles decrivent les octets qui vont tourner.
    #[test]
    fn built_surfaces_win_over_anything_already_declared() {
        let raw = r#"{"surfaces":{"host":[{"id":"stale"}]}}"#;

        let stamped = stamp_surfaces(raw, BUILT).expect("stamp");
        let value: serde_json::Value = serde_json::from_str(&stamped).expect("parse");

        assert_eq!(value["surfaces"]["host"][0]["id"], "main");
    }
}