day-cli 0.1.4

Declarative app development API using native UI toolkits
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
//! Standalone-piece backend discovery (docs/extending.md). External piece crates (e.g.
//! `day-piece-searchfield`) declare their per-toolkit backend contributions in `Cargo.toml` under
//! `[package.metadata.day.<toolkit>]`; the Day CLI reads them from `cargo metadata` and folds them
//! into the native build — so a piece carries BOTH its front-end (Rust) and its backend (Java /
//! Gradle deps / …) without touching the core Day crates.
//!
//! Android contract (`[package.metadata.day.android]`):
//! ```toml
//! java = ["android/java"]                 # dirs (rel. to the crate) → Gradle java srcDirs
//! res = ["android/res"]                   # dirs (rel. to the crate) → Gradle res srcDirs
//! gradle-dependencies = ["g:a:v", …]      # → the app module's dependencies { }
//! gradle-repositories = ["https://…", …]  # → extra Maven repos
//! permissions = ["android.permission.INTERNET", …]  # → <uses-permission>s merged into the manifest
//! proguard = ["android/proguard-rules.pro"]  # → R8 keep rules for classes native code reaches by name
//! ```
//! The resolved contributions are written to `build/day/android/day-pieces.json`, which the app's
//! `build.gradle.kts` reads generically (loops over the lists — no per-piece Gradle edits, ever).
//! Permissions additionally go into a generated manifest overlay (`day-pieces-manifest.xml`) that the
//! scaffold points its debug+release source-set manifests at, so AGP merges them into the app manifest.
//!
//! iOS contract (`[package.metadata.day.ios]`):
//! ```toml
//! swift = ["ios/swift"]                 # dirs (rel. to the crate) of Swift shim sources
//! swift-packages = [                    # SwiftPM package dependencies to link
//!   { url = "https://…", from = "1.0.0", products = ["Foo"] },
//! ]
//! ```
//! Xcode is not script-driven like Gradle, so instead the CLI generates a LOCAL SwiftPM package at
//! `build/day/ios/DayPieces` — its `Package.swift` lists every piece's `swift-packages` as
//! dependencies and compiles every piece's staged Swift shims. The app's checked-in `.xcodeproj`
//! depends on that one local package (the iOS analog of the Gradle scaffold), so adding an iOS piece
//! is pure `Cargo.toml` data — no `.xcodeproj` edits, ever.
//!
//! HarmonyOS contract (`[package.metadata.day.ohos]`):
//! ```toml
//! ets = ["ohos/ets"]                    # dirs (rel. to the crate) of ArkTS sources
//! ```
//! For components that exist ONLY in ArkTS — the ArkUI C node API cannot construct a `Web` at all.
//! Hvigor compiles ArkTS only from inside the module, so these stage into the project itself
//! (`entry/src/main/ets/daypieces/<crate>/`, gitignored) beside a generated `DayPieces.ets` whose
//! `registerDayPieces(uiContext)` the checked-in host page calls once — so adding an ArkTS piece is
//! pure `Cargo.toml` data too. Each declared dir needs an `Index.ets` exporting a `DayPieceModule`.

use std::collections::HashSet;
use std::path::Path;
use std::process::Command;

use serde::{Deserialize, Serialize};

use crate::meta::Project;

/// `[package.metadata.day.permissions]` — a library declaring which PORTABLE permissions it needs
/// (docs/permissions.md). Machine-facing only: a library cannot write the user-facing reason, which
/// is why that lives in the app's Day.toml and why a contribution without one is a build error on
/// the platforms that show it.
#[derive(Debug, Default, Deserialize)]
struct PermissionsMeta {
    #[serde(default)]
    uses: Vec<String>,
}

/// The build-side contribution list handed to Gradle (serialized to day-pieces.json).
#[derive(Debug, Default, Serialize)]
pub struct AndroidPieces {
    /// The day-android framework Java shim (DayActivity, DayBridge, …), resolved from the
    /// `day-android` crate the app depends on — wherever cargo has it (workspace path, git
    /// checkout, or registry source). Without this dir in the dex, the APK installs and then
    /// crashes with ClassNotFoundException at launch; the Gradle scaffold hard-fails instead.
    #[serde(rename = "dayJavaSrcDir")]
    pub day_java_src_dir: Option<String>,
    /// The day-android framework's own R8/ProGuard keep rules (bridge classes + native methods),
    /// resolved from the day-android crate. Applied to every release build so minification never
    /// renames the JNI-reached bridge (docs/extending.md).
    #[serde(rename = "dayProguardFile")]
    pub day_proguard_file: Option<String>,
    /// Absolute Java/Kotlin source dirs to add as Gradle `java.srcDir`s.
    #[serde(rename = "javaSrcDirs")]
    pub java_src_dirs: Vec<String>,
    /// Absolute Android resource dirs to add as Gradle `res.srcDir`s — a piece can ship its own
    /// styles/drawables (e.g. a theme overlay its dialog needs) without touching the scaffold.
    #[serde(rename = "resSrcDirs")]
    pub res_src_dirs: Vec<String>,
    /// Gradle dependency coordinates (`group:artifact:version`).
    pub dependencies: Vec<String>,
    /// Extra Maven repository URLs.
    pub repositories: Vec<String>,
    /// Android `<uses-permission>` names to merge into the app manifest.
    pub permissions: Vec<String>,
    /// Absolute R8/ProGuard rule files contributed by the app and its pieces/parts — every
    /// component that hands Java classes to native code by name (JNI FindClass, `dcall_static`,
    /// reflection) ships one and declares it in `[package.metadata.day.android].proguard`. Folded
    /// into the release build's proguard configuration so those names survive minification.
    #[serde(rename = "proguardFiles")]
    pub proguard_files: Vec<String>,
}

// --- `cargo metadata` JSON (only the fields we need) ---

#[derive(Deserialize)]
pub(crate) struct Metadata {
    pub(crate) packages: Vec<Package>,
    resolve: Option<Resolve>,
}
#[derive(Deserialize)]
pub(crate) struct Package {
    id: String,
    pub(crate) name: String,
    manifest_path: String,
    #[serde(default)]
    pub(crate) metadata: Option<serde_json::Value>,
}
#[derive(Deserialize)]
struct Resolve {
    root: Option<String>,
    nodes: Vec<Node>,
}
#[derive(Deserialize)]
struct Node {
    id: String,
    #[serde(default)]
    deps: Vec<Dep>,
}
#[derive(Deserialize)]
struct Dep {
    pkg: String,
}

/// The `[package.metadata.day.android]` table, as declared by a piece crate.
#[derive(Deserialize, Default)]
struct AndroidMeta {
    #[serde(default)]
    java: StringOrVec,
    #[serde(default)]
    res: StringOrVec,
    #[serde(default, rename = "gradle-dependencies")]
    gradle_dependencies: Vec<String>,
    #[serde(default, rename = "gradle-repositories")]
    gradle_repositories: Vec<String>,
    #[serde(default)]
    permissions: Vec<String>,
    /// R8/ProGuard rule files (relative to the crate) — one per component that needs its Java
    /// classes kept by name under release minification.
    #[serde(default)]
    proguard: StringOrVec,
}

/// Accept `java = "android/java"` or `java = ["a", "b"]`.
#[derive(Default)]
struct StringOrVec(Vec<String>);
impl<'de> Deserialize<'de> for StringOrVec {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum V {
            One(String),
            Many(Vec<String>),
        }
        Ok(StringOrVec(match V::deserialize(d)? {
            V::One(s) => vec![s],
            V::Many(v) => v,
        }))
    }
}

/// The `[package.metadata.day.piece]` marker a standalone piece declares to name the backends it
/// carries a native-renderer *feature* for. The Day CLI unions `<pkg>/<backend>` into the app build
/// (see [`feature_union`]) so the app need only depend on the piece — never re-list its per-backend
/// features. COMPOSE pieces (built from core pieces, no per-backend feature) omit this table and so
/// contribute nothing.
#[derive(Deserialize, Default)]
struct PieceMeta {
    /// Backend toolkit names (`appkit`, `gtk`, `qt`, `uikit`, `mdc`, `xaml`, `mock`) this piece
    /// declares a `[features]` entry for. Only these get `<pkg>/<backend>` unioned in.
    #[serde(default)]
    backends: Vec<String>,
}

/// Compute the extra `--features` entries that wire each standalone piece's per-backend renderer into
/// a build whose toolkit is `backend`. Scans the app's dependency closure for pieces declaring
/// `[package.metadata.day.piece].backends` that INCLUDE `backend` and returns one `<pkg>/<backend>`
/// per match (deduped, sorted). This lets the app depend on a piece with a plain `{ workspace = true }`
/// and no per-backend feature fan-out — the CLI derives them here.
///
/// Robustness: only pieces that ACTUALLY declare `backend` contribute (so `cargo`'s "feature does not
/// exist" / "not a direct dependency" errors can't fire), and a metadata failure degrades to an empty
/// list (warn, don't fail) so the app still builds with whatever features it lists itself. Because the
/// union is additive, an app that still lists the per-piece features stays correct (dupes are fine).
pub fn feature_union(project: &Project, backend: &str) -> Vec<String> {
    let meta = match cargo_metadata(project, &[backend]) {
        Ok(m) => m,
        Err(e) => {
            eprintln!(
                "day: piece feature discovery failed ({e}); \
                 building with the app's declared features only"
            );
            return Vec::new();
        }
    };
    let in_closure = closure(&meta);
    let mut feats = Vec::new();
    for pkg in &meta.packages {
        if !in_closure.contains(&pkg.id) {
            continue;
        }
        let Some(piece) = piece_meta::<PieceMeta>(pkg, "piece") else {
            continue;
        };
        if piece.backends.iter().any(|b| b == backend) {
            feats.push(format!("{}/{backend}", pkg.name));
        }
    }
    feats.sort();
    feats.dedup();
    feats
}

/// Run `cargo metadata` for the app with a specific feature selection (no default features), so only
/// pieces actually pulled in by that backend's features are considered.
pub(crate) fn cargo_metadata(project: &Project, features: &[&str]) -> Result<Metadata, String> {
    cargo_metadata_inner(project, features, false)
}

/// `cargo metadata --all-features` — the form external-toolkit discovery needs: a toolkit crate
/// is an OPTIONAL dependency (behind the very feature its declaration names), and cargo omits
/// unactivated optional deps from `packages` under any narrower flag set (verified empirically:
/// only `--all-features` lists them). Feature-closure consumers keep the precise form above.
pub(crate) fn cargo_metadata_all_features(project: &Project) -> Result<Metadata, String> {
    cargo_metadata_inner(project, &[], true)
}

fn cargo_metadata_inner(
    project: &Project,
    features: &[&str],
    all_features: bool,
) -> Result<Metadata, String> {
    let manifest = project.root.join("Cargo.toml");
    let mut cmd = Command::new("cargo");
    cmd.args(["metadata", "--format-version", "1"])
        .arg("--manifest-path")
        .arg(&manifest);
    if all_features {
        cmd.arg("--all-features");
    } else {
        cmd.arg("--no-default-features");
    }
    if !features.is_empty() {
        cmd.arg("--features").arg(features.join(","));
    }
    let out = cmd.output().map_err(|e| format!("cargo metadata: {e}"))?;
    if !out.status.success() {
        return Err(format!(
            "cargo metadata failed: {}",
            String::from_utf8_lossy(&out.stderr)
                .lines()
                .next_back()
                .unwrap_or("")
        ));
    }
    serde_json::from_slice(&out.stdout).map_err(|e| format!("cargo metadata parse: {e}"))
}

/// Deserialize a piece's `[package.metadata.day.<toolkit>]` table, warning (not failing) on a
/// malformed one. Returns `None` when the piece declares no such table.
pub(crate) fn piece_meta<T: serde::de::DeserializeOwned>(
    pkg: &Package,
    toolkit: &str,
) -> Option<T> {
    let table = pkg
        .metadata
        .as_ref()
        .and_then(|m| m.get("day")) // Cargo.toml `[package.metadata.day.*]` — lowercase key
        .and_then(|d| d.get(toolkit))?;
    match serde_json::from_value(table.clone()) {
        Ok(v) => Some(v),
        Err(e) => {
            eprintln!(
                "day: {} has malformed [package.metadata.day.{toolkit}]: {e}",
                pkg.manifest_path
            );
            None
        }
    }
}

/// Resolve every piece in the app's Android dependency closure and collect its contributions.
/// The `features` are the ones the Android build compiles with (so only pieces actually pulled in
/// by that feature set contribute) — currently `["mdc"]`, no default features.
pub fn resolve_android(project: &Project, features: &[&str]) -> Result<AndroidPieces, String> {
    let meta = cargo_metadata(project, features)?;

    // Transitive closure of package ids reachable from the resolve root (the app).
    let in_closure = closure(&meta);

    let mut pieces = AndroidPieces::default();
    let mut seen_java = HashSet::new();
    for pkg in &meta.packages {
        if !in_closure.contains(&pkg.id) {
            continue;
        }
        // The framework's own Java shim rides with the day-android crate (§17.1) — resolve it
        // from wherever cargo checked the crate out instead of assuming a day repo layout.
        if pkg.name == "day-android" {
            let java = Path::new(&pkg.manifest_path)
                .parent()
                .unwrap_or(Path::new("."))
                .join("java");
            if !java.is_dir() {
                return Err(format!(
                    "day-android crate at {:?} has no java/ dir — the Android Java shim is \
                     missing from this day checkout",
                    pkg.manifest_path
                ));
            }
            pieces.day_java_src_dir = Some(java.to_string_lossy().into_owned());
            // The framework's own R8 keep rules ride alongside the Java shim (optional — an older
            // day-android checkout without the file simply contributes none).
            let rules = Path::new(&pkg.manifest_path)
                .parent()
                .unwrap_or(Path::new("."))
                .join("proguard-rules.pro");
            if rules.is_file() {
                pieces.day_proguard_file = Some(rules.to_string_lossy().into_owned());
            }
        }
        let Some(android) = piece_meta::<AndroidMeta>(pkg, "android") else {
            continue;
        };
        let crate_dir = Path::new(&pkg.manifest_path)
            .parent()
            .unwrap_or(Path::new("."));
        for rel in &android.java.0 {
            let dir = crate_dir.join(rel);
            if !dir.is_dir() {
                eprintln!("day: {} java dir {:?} not found — skipping", pkg.id, dir);
                continue;
            }
            let abs = dir.to_string_lossy().into_owned();
            if seen_java.insert(abs.clone()) {
                pieces.java_src_dirs.push(abs);
            }
        }
        for rel in &android.res.0 {
            let dir = crate_dir.join(rel);
            if !dir.is_dir() {
                eprintln!("day: {} res dir {:?} not found — skipping", pkg.id, dir);
                continue;
            }
            let abs = dir.to_string_lossy().into_owned();
            if !pieces.res_src_dirs.contains(&abs) {
                pieces.res_src_dirs.push(abs);
            }
        }
        for dep in android.gradle_dependencies {
            if !pieces.dependencies.contains(&dep) {
                pieces.dependencies.push(dep);
            }
        }
        for repo in android.gradle_repositories {
            if !pieces.repositories.contains(&repo) {
                pieces.repositories.push(repo);
            }
        }
        for perm in android.permissions {
            if !pieces.permissions.contains(&perm) {
                pieces.permissions.push(perm);
            }
        }
        for rel in &android.proguard.0 {
            let file = crate_dir.join(rel);
            if !file.is_file() {
                eprintln!(
                    "day: {} proguard file {:?} not found — skipping",
                    pkg.id, file
                );
                continue;
            }
            let abs = file.to_string_lossy().into_owned();
            if !pieces.proguard_files.contains(&abs) {
                pieces.proguard_files.push(abs);
            }
        }
    }
    Ok(pieces)
}

/// Package ids transitively reachable from the resolve root (falls back to "all resolved" if the
/// root is a virtual workspace with no single root).
fn closure(meta: &Metadata) -> HashSet<String> {
    let Some(resolve) = &meta.resolve else {
        return meta.packages.iter().map(|p| p.id.clone()).collect();
    };
    let by_id: std::collections::HashMap<&str, &Node> =
        resolve.nodes.iter().map(|n| (n.id.as_str(), n)).collect();
    let Some(root) = &resolve.root else {
        return resolve.nodes.iter().map(|n| n.id.clone()).collect();
    };
    let mut seen = HashSet::new();
    let mut stack = vec![root.clone()];
    while let Some(id) = stack.pop() {
        if !seen.insert(id.clone()) {
            continue;
        }
        if let Some(node) = by_id.get(id.as_str()) {
            for d in &node.deps {
                stack.push(d.pkg.clone());
            }
        }
    }
    seen
}

/// Every `[package.metadata.day.permissions].uses` in the app's dependency closure, as
/// `(crate_name, permission)`. The app package itself participates (the closure starts at the
/// resolve root), so an app may use the same key instead of Day.toml when it has no reason to give.
pub fn contributed_permissions(project: &Project, backends: &[&str]) -> Vec<(String, String)> {
    let Ok(meta) = cargo_metadata(project, backends) else {
        return Vec::new();
    };
    let reachable = closure(&meta);
    let mut out = Vec::new();
    for pkg in meta.packages.iter().filter(|p| reachable.contains(&p.id)) {
        if let Some(m) = piece_meta::<PermissionsMeta>(pkg, "permissions") {
            for perm in m.uses {
                out.push((pkg.name.clone(), perm));
            }
        }
    }
    out.sort();
    out.dedup();
    out
}

/// Write the resolved contributions to `build/day/android/day-pieces.json` for Gradle to read (and,
/// when pieces contribute Android permissions, a `day-pieces-manifest.xml` overlay the scaffold
/// merges). Always writes (an empty manifest when there are no pieces) so a stale file never lingers.
pub fn write_android_manifest(project: &Project) -> Result<(), String> {
    let mut pieces = resolve_android(project, &["mdc"]).unwrap_or_else(|e| {
        eprintln!("day: piece discovery failed ({e}); building with framework pieces only");
        AndroidPieces::default()
    });
    let dir = project.root.join("build/day/android");
    std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;

    // Day.toml's [permissions] joins the pieces' raw contributions here, so BOTH reach the overlay
    // through one path. `pieces.permissions` must carry every name: the scaffold's build.gradle.kts
    // gates the overlay on that list being non-empty.
    let contributed = contributed_permissions(project, &["mdc"]);
    let declared = crate::permissions::resolve(&project.manifest, "android", &contributed)
        .map_err(|e| format!("Day.toml: {e}"))?;
    let mut entries = crate::permissions::android_entries(&declared);
    for name in &pieces.permissions {
        if !entries.iter().any(|e| &e.name == name) {
            entries.push(crate::permissions::AndroidRaw {
                name: name.clone(),
                max_sdk: None,
            });
        }
    }
    entries.sort_by(|a, b| a.name.cmp(&b.name));
    pieces.permissions = entries.iter().map(|e| e.name.clone()).collect();

    // day-pieces.json is written AFTER the merge so Gradle sees the full list.
    let json = serde_json::to_string_pretty(&pieces).map_err(|e| e.to_string())?;
    std::fs::write(dir.join("day-pieces.json"), json).map_err(|e| e.to_string())?;

    // Permissions → a manifest overlay AGP merges into the app manifest (the scaffold points its
    // debug+release source-set manifests here). Remove any stale overlay when there are none.
    //
    // The FILENAME is a compatibility surface: it is baked into every scaffold `day new` has ever
    // generated, and a source set has exactly one manifest slot (debug and release are both already
    // claimed). Widen what this file contains; never move or split it, or permission merging breaks
    // silently in every checked-out app.
    let overlay = dir.join("day-pieces-manifest.xml");
    if entries.is_empty() {
        let _ = std::fs::remove_file(&overlay);
    } else {
        std::fs::write(&overlay, permissions_manifest(&entries)).map_err(|e| e.to_string())?;
    }
    Ok(())
}

/// A minimal manifest carrying only the `<uses-permission>`s — merged into the app manifest by AGP's
/// manifest merger (which also dedups against any the app already declares).
fn permissions_manifest(permissions: &[crate::permissions::AndroidRaw]) -> String {
    let mut s = String::from(
        "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\
         <!-- Generated by `day build` from Day.toml [permissions] and \
         [package.metadata.day.*] contributions. Do not edit. -->\n\
         <manifest xmlns:android=\"http://schemas.android.com/apk/res/android\">\n",
    );
    for perm in permissions {
        match perm.max_sdk {
            // The cap matters: an uncapped legacy storage permission makes stores flag the app for
            // requesting broad access that API 33+ replaced with the granular READ_MEDIA_* set.
            Some(max) => s.push_str(&format!(
                "    <uses-permission android:name=\"{}\" android:maxSdkVersion=\"{max}\" />\n",
                perm.name
            )),
            None => s.push_str(&format!(
                "    <uses-permission android:name=\"{}\" />\n",
                perm.name
            )),
        }
    }
    s.push_str("</manifest>\n");
    s
}

// ===========================================================================
// iOS — a piece's Swift shims + SwiftPM package dependencies
// ===========================================================================

/// A SwiftPM package dependency declared by a piece (`[package.metadata.day.ios].swift-packages`).
#[derive(Debug, Clone, Deserialize)]
struct SwiftPackage {
    url: String,
    #[serde(default)]
    from: Option<String>,
    #[serde(default)]
    exact: Option<String>,
    #[serde(default)]
    branch: Option<String>,
    #[serde(default)]
    revision: Option<String>,
    #[serde(default)]
    products: Vec<String>,
}

impl SwiftPackage {
    /// SwiftPM derives a package's identity from the last path component of its URL (sans `.git`).
    fn identity(&self) -> String {
        self.url
            .trim_end_matches('/')
            .rsplit('/')
            .next()
            .unwrap_or(&self.url)
            .trim_end_matches(".git")
            .to_string()
    }
    /// The version requirement clause for `.package(url:, …)`.
    fn requirement(&self) -> String {
        if let Some(v) = &self.exact {
            format!("exact: \"{v}\"")
        } else if let Some(b) = &self.branch {
            format!("branch: \"{b}\"")
        } else if let Some(r) = &self.revision {
            format!("revision: \"{r}\"")
        } else {
            // Default to `from:` (allows compatible newer versions); fall back to any version.
            format!("from: \"{}\"", self.from.as_deref().unwrap_or("0.0.0"))
        }
    }
}

/// The `[package.metadata.day.ios]` table, as declared by a piece crate.
#[derive(Deserialize, Default)]
struct IosMeta {
    #[serde(default)]
    swift: StringOrVec,
    #[serde(default, rename = "swift-packages")]
    swift_packages: Vec<SwiftPackage>,
    /// System frameworks to link (e.g. `["WebKit"]`) — so a piece needn't `dlopen` or hand-`#[link]`.
    #[serde(default)]
    frameworks: Vec<String>,
}

/// The resolved iOS contributions across all pieces in the app's dependency closure.
#[derive(Default)]
struct IosPieces {
    /// `(namespace, absolute dir)` Swift source dirs to compile — the namespace (the piece's crate
    /// name) subfolders the staged shims so two pieces' files can't collide.
    swift_dirs: Vec<(String, String)>,
    /// SwiftPM package dependencies (deduped by identity).
    packages: Vec<SwiftPackage>,
    /// System frameworks the app links (deduped).
    frameworks: Vec<String>,
}

/// Resolve every piece in the app's iOS dependency closure (features = `["uikit"]`) and collect its
/// Swift shim dirs + SwiftPM package dependencies.
fn resolve_ios(project: &Project, features: &[&str]) -> Result<IosPieces, String> {
    let meta = cargo_metadata(project, features)?;
    let in_closure = closure(&meta);

    let mut pieces = IosPieces::default();
    let mut seen_dirs = HashSet::new();
    let mut seen_pkgs = HashSet::new();
    for pkg in &meta.packages {
        if !in_closure.contains(&pkg.id) {
            continue;
        }
        let Some(ios) = piece_meta::<IosMeta>(pkg, "ios") else {
            continue;
        };
        let crate_dir = Path::new(&pkg.manifest_path)
            .parent()
            .unwrap_or(Path::new("."));
        let namespace = crate_dir
            .file_name()
            .map(|s| s.to_string_lossy().into_owned())
            .unwrap_or_else(|| "piece".into());
        for rel in &ios.swift.0 {
            let dir = crate_dir.join(rel);
            if !dir.is_dir() {
                eprintln!("day: {} swift dir {:?} not found — skipping", pkg.id, dir);
                continue;
            }
            let abs = dir.to_string_lossy().into_owned();
            if seen_dirs.insert(abs.clone()) {
                pieces.swift_dirs.push((namespace.clone(), abs));
            }
        }
        for spkg in ios.swift_packages {
            if seen_pkgs.insert(spkg.identity()) {
                pieces.packages.push(spkg);
            }
        }
        for fw in ios.frameworks {
            if !pieces.frameworks.contains(&fw) {
                pieces.frameworks.push(fw);
            }
        }
    }
    Ok(pieces)
}

/// Generate the local `DayPieces` SwiftPM package (Package.swift + staged Swift shims) under
/// `build/day/ios/DayPieces`, from every piece's `[package.metadata.day.ios]`. The app's `.xcodeproj`
/// depends on this local package, so `day build` (ios) calls this before `xcodebuild`. Always writes
/// a VALID package (an empty target with a placeholder source when no pieces contribute), so the
/// project's local-package reference always resolves.
pub fn write_ios_pieces(project: &Project) -> Result<(), String> {
    let pieces = resolve_ios(project, &["uikit"]).unwrap_or_else(|e| {
        eprintln!("day: iOS piece discovery failed ({e}); building with framework pieces only");
        IosPieces::default()
    });

    let pkg_dir = project.root.join("build/day/ios/DayPieces");
    let sources = pkg_dir.join("Sources/DayPieces");
    // Regenerate the staged sources fresh so a removed piece never leaves a stale shim behind.
    let _ = std::fs::remove_dir_all(&sources);
    std::fs::create_dir_all(&sources).map_err(|e| e.to_string())?;

    // A placeholder keeps the target valid (≥1 source) even with no piece shims.
    std::fs::write(
        sources.join("_DayPieces.swift"),
        "// Generated by `day build`. The DayPieces local package aggregates every standalone piece's\n\
         // iOS Swift shims and SwiftPM package dependencies (docs/extending.md). Do not edit.\n\
         enum _DayPieces {}\n",
    )
    .map_err(|e| e.to_string())?;

    // Stage every piece's Swift shim files under a per-crate subdir so they can't collide.
    for (namespace, dir) in &pieces.swift_dirs {
        stage_swift_dir(Path::new(dir), &sources.join(namespace))?;
    }

    // Processed images (§18.3): generate a Media.xcassets from the project's images/ into the target
    // so SwiftPM `.process` compiles it (actool) into the package's Assets.car.
    let images = crate::resources::ResourceSet::scan(project).images;
    let has_resources = crate::resources::apple::write_media_xcassets(&sources, &images)?;

    // Bundled fonts (§18.4): copied VERBATIM into the target so SwiftPM `.copy`s the directory
    // into the DayPieces bundle (`DayPieces_DayPieces.bundle/fonts/…` — fonts must not be
    // `.process`ed). day-uikit registers every file in there with CoreText at launch, and
    // build_ios lists the same paths in the app Info.plist's UIAppFonts.
    let fonts = crate::resources::scan_fonts(project)?;
    if !fonts.is_empty() {
        let fdir = sources.join("fonts");
        std::fs::create_dir_all(&fdir).map_err(|e| e.to_string())?;
        for f in &fonts {
            let name = f.path.file_name().ok_or("font file name")?;
            std::fs::copy(&f.path, fdir.join(name)).map_err(|e| e.to_string())?;
        }
    }

    std::fs::write(
        pkg_dir.join("Package.swift"),
        package_swift(&pieces, has_resources, !fonts.is_empty()),
    )
    .map_err(|e| e.to_string())?;
    Ok(())
}

/// Copy every `.swift` file under `src` into `dest` (recursively), so a piece's shims join the
/// DayPieces target's sources.
/// The `[package.metadata.day.ohos]` table, as declared by a piece crate.
#[derive(Deserialize, Default)]
struct OhosMeta {
    /// Dirs (relative to the crate) of ArkTS sources staged into the app's hvigor project. Each
    /// dir must carry an `Index.ets` exporting `dayPiece: DayPieceModule` (docs/extending.md).
    #[serde(default)]
    ets: StringOrVec,
}

/// The resolved HarmonyOS contributions across all pieces in the app's dependency closure.
#[derive(Default)]
struct OhosPieces {
    /// `(namespace, absolute dir)` ArkTS dirs to stage — the namespace (the piece's crate name)
    /// subfolders them so two pieces' files can't collide, as on iOS.
    ets_dirs: Vec<(String, String)>,
}

/// Resolve every piece in the app's HarmonyOS dependency closure (features = `["arkui"]`) and
/// collect its ArkTS dirs.
fn resolve_ohos(project: &Project, features: &[&str]) -> Result<OhosPieces, String> {
    let meta = cargo_metadata(project, features)?;
    let in_closure = closure(&meta);

    let mut pieces = OhosPieces::default();
    let mut seen = HashSet::new();
    for pkg in &meta.packages {
        if !in_closure.contains(&pkg.id) {
            continue;
        }
        let Some(ohos) = piece_meta::<OhosMeta>(pkg, "ohos") else {
            continue;
        };
        let crate_dir = Path::new(&pkg.manifest_path)
            .parent()
            .unwrap_or(Path::new("."));
        let namespace = crate_dir
            .file_name()
            .map(|s| s.to_string_lossy().into_owned())
            .unwrap_or_else(|| "piece".into());
        for rel in &ohos.ets.0 {
            let dir = crate_dir.join(rel);
            if !dir.is_dir() {
                eprintln!("day: {} ets dir {:?} not found — skipping", pkg.id, dir);
                continue;
            }
            if !dir.join("Index.ets").is_file() {
                eprintln!(
                    "day: {} ets dir {:?} has no Index.ets (the `dayPiece` entry module) — skipping",
                    pkg.id, dir
                );
                continue;
            }
            let abs = dir.to_string_lossy().into_owned();
            if seen.insert(abs.clone()) {
                pieces.ets_dirs.push((namespace.clone(), abs));
            }
        }
    }
    pieces.ets_dirs.sort();
    Ok(pieces)
}

/// Stage every piece's ArkTS into the hvigor project's `entry/src/main/ets/daypieces/` and generate
/// the two files the host page leans on: `DayPiece.ets` (the `DayPieceModule` interface both sides
/// implement) and `DayPieces.ets` (the aggregator whose `registerDayPieces(uiContext)` hands the
/// native shim one factory + command sink + disposer for ALL pieces). Hvigor compiles ArkTS only
/// from inside the module, so unlike the android/iOS legs these land in the project — the scaffold
/// gitignores the directory. Always writes both generated files, even with no contributing piece,
/// because the host page imports them unconditionally.
pub fn write_ohos_pieces(project: &Project, harmony: &Path) -> Result<(), String> {
    let pieces = resolve_ohos(project, &["arkui"]).unwrap_or_else(|e| {
        eprintln!(
            "day: HarmonyOS piece discovery failed ({e}); building with framework pieces only"
        );
        OhosPieces::default()
    });

    let dir = harmony.join("entry/src/main/ets/daypieces");
    // Regenerate fresh so a removed piece never leaves a stale module the aggregator won't import
    // but hvigor would still compile.
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;

    std::fs::write(dir.join("DayPiece.ets"), DAY_PIECE_ETS).map_err(|e| e.to_string())?;
    for (namespace, src) in &pieces.ets_dirs {
        stage_ets_dir(Path::new(src), &dir.join(namespace))?;
    }
    std::fs::write(dir.join("DayPieces.ets"), day_pieces_ets(&pieces))
        .map_err(|e| e.to_string())?;
    Ok(())
}

/// The generated `DayPieceModule` contract — the seam between a piece's ArkTS and the aggregator.
/// Written verbatim every build so the two generated files always agree.
const DAY_PIECE_ETS: &str = r#"// Generated by `day build`. The contract between a standalone piece's ArkTS and the generated
// aggregator (docs/extending.md). Do not edit.
import { FrameNode, UIContext } from '@kit.ArkUI';

export interface DayPieceModule {
  // The piece kind this module renders, matching the Rust `KIND` (e.g. 'day.piece.webview').
  kind: string;
  // Build the component and return its FrameNode; undefined declines the node (Day then renders
  // its placeholder leaf). `props` is whatever the piece's Rust renderer encoded.
  make: (ui: UIContext, id: number, props: string) => FrameNode | undefined;
  // A command from the piece's Rust renderer. `cmd`/`arg` are the piece's own vocabulary.
  update: (id: number, cmd: string, arg: string) => void;
  // Release everything held for `id` — Day disposed the node.
  dispose: (id: number) => void;
}
"#;

/// Render the aggregator for the resolved pieces.
fn day_pieces_ets(pieces: &OhosPieces) -> String {
    let mut imports = String::new();
    let mut entries = String::new();
    for (i, (namespace, _)) in pieces.ets_dirs.iter().enumerate() {
        imports.push_str(&format!(
            "import {{ dayPiece as dayPiece{i} }} from './{namespace}/Index';\n"
        ));
        entries.push_str(&format!("  dayPiece{i},\n"));
    }
    format!(
        r#"// Generated by `day build`. Registers every standalone piece's ArkTS component with the native
// shim (docs/extending.md): one factory, one command sink, one disposer for all of them. Do not edit.
import nativeEntry from 'libentry.so';
import {{ FrameNode, UIContext }} from '@kit.ArkUI';
import {{ DayPieceModule }} from './DayPiece';
{imports}
const dayPieces: DayPieceModule[] = [
{entries}];

// Which module owns a live node, so commands and disposal reach the right piece.
const dayPieceOwners: Map<number, DayPieceModule> = new Map();

// Call once, before `start()`: a piece node can be realized during the first tree build.
export function registerDayPieces(ui: UIContext): void {{
  nativeEntry.registerPiece(
    (kind: string, id: number, props: string): FrameNode | undefined => {{
      for (const m of dayPieces) {{
        if (m.kind === kind) {{
          const node: FrameNode | undefined = m.make(ui, id, props);
          if (node !== undefined) {{
            dayPieceOwners.set(id, m);
          }}
          return node;
        }}
      }}
      return undefined;
    }},
    (id: number, cmd: string, arg: string): void => {{
      dayPieceOwners.get(id)?.update(id, cmd, arg);
    }},
    (id: number): void => {{
      const m: DayPieceModule | undefined = dayPieceOwners.get(id);
      if (m !== undefined) {{
        dayPieceOwners.delete(id);
        m.dispose(id);
      }}
    }}
  );
}}
"#
    )
}

/// Copy a piece's ArkTS sources (`.ets`) into the project, recursively — the HarmonyOS counterpart
/// of [`stage_swift_dir`].
fn stage_ets_dir(src: &Path, dest: &Path) -> Result<(), String> {
    std::fs::create_dir_all(dest).map_err(|e| e.to_string())?;
    let rd = std::fs::read_dir(src).map_err(|e| format!("{}: {e}", src.display()))?;
    for entry in rd.flatten() {
        let path = entry.path();
        if path.is_dir() {
            stage_ets_dir(&path, &dest.join(entry.file_name()))?;
        } else if path.extension().and_then(|e| e.to_str()) == Some("ets") {
            std::fs::copy(&path, dest.join(entry.file_name())).map_err(|e| e.to_string())?;
        }
    }
    Ok(())
}

fn stage_swift_dir(src: &Path, dest: &Path) -> Result<(), String> {
    std::fs::create_dir_all(dest).map_err(|e| e.to_string())?;
    let rd = std::fs::read_dir(src).map_err(|e| format!("{}: {e}", src.display()))?;
    for entry in rd.flatten() {
        let path = entry.path();
        if path.is_dir() {
            stage_swift_dir(&path, &dest.join(entry.file_name()))?;
        } else if path.extension().and_then(|e| e.to_str()) == Some("swift") {
            std::fs::copy(&path, dest.join(entry.file_name())).map_err(|e| e.to_string())?;
        }
    }
    Ok(())
}

/// Render the generated `DayPieces/Package.swift`. When `has_resources`, the target processes the
/// generated `Media.xcassets` (§18.3) — SwiftPM runs `actool` → an optimized `Assets.car` in the
/// package's resource bundle, which `day-uikit` loads images from by name. When `has_fonts`, the
/// staged `fonts/` directory is `.copy`d verbatim into the same bundle (§18.4).
fn package_swift(pieces: &IosPieces, has_resources: bool, has_fonts: bool) -> String {
    let deps: String = pieces
        .packages
        .iter()
        .map(|p| {
            format!(
                "        .package(url: \"{}\", {}),\n",
                p.url,
                p.requirement()
            )
        })
        .collect();
    let products: String = pieces
        .packages
        .iter()
        .flat_map(|p| {
            let id = p.identity();
            p.products.iter().map(move |prod| {
                format!("            .product(name: \"{prod}\", package: \"{id}\"),\n")
            })
        })
        .collect();
    // System frameworks link on the target (`.linkedFramework`), so a piece can declare `frameworks =
    // ["WebKit"]` instead of `dlopen`ing or hand-`#[link]`ing them; they reach the app via DayPieces.
    let linker: String = if pieces.frameworks.is_empty() {
        String::new()
    } else {
        let fws: String = pieces
            .frameworks
            .iter()
            .map(|f| format!(".linkedFramework(\"{f}\"), "))
            .collect();
        format!(", linkerSettings: [{fws}]")
    };
    // App images (§18.3) staged as a `.process`ed asset catalog next to the shims; app fonts
    // (§18.4) as a `.copy`d directory (font files must reach the bundle byte-identical).
    let mut entries: Vec<&str> = Vec::new();
    if has_resources {
        entries.push(".process(\"Media.xcassets\")");
    }
    if has_fonts {
        entries.push(".copy(\"fonts\")");
    }
    let resources = if entries.is_empty() {
        String::new()
    } else {
        format!(", resources: [{}]", entries.join(", "))
    };
    format!(
        "// swift-tools-version:5.9\n\
         // Generated by `day build` from standalone pieces' [package.metadata.day.ios]. Do not edit.\n\
         import PackageDescription\n\n\
         let package = Package(\n\
         \x20   name: \"DayPieces\",\n\
         \x20   platforms: [.iOS(.v15)],\n\
         \x20   products: [.library(name: \"DayPieces\", targets: [\"DayPieces\"])],\n\
         \x20   dependencies: [\n{deps}    ],\n\
         \x20   targets: [\n\
         \x20       .target(name: \"DayPieces\", dependencies: [\n{products}        ], path: \"Sources/DayPieces\"{resources}{linker}),\n\
         \x20   ]\n\
         )\n"
    )
}