euv-cli 0.50.0

Cross-platform CLI tool for the euv native UI framework supporting run, build, check, fmt, doctor, new, and Hyperlane SSE dynamic updates across all supported platforms.
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
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
use super::*;

/// Renders the universal iOS and iPadOS `Info.plist` with dynamic version and bundle identifier.
///
/// # Arguments
///
/// - `&str` - Semantic version written to `CFBundleShortVersionString`.
/// - `&str` - Monotonic build number written to `CFBundleVersion`.
/// - `&str` - Application `CFBundleIdentifier` (for example `vip.ltpp.euv.showcase`).
///
/// # Returns
///
/// - `String` - Complete XML `Info.plist` contents.
#[must_use]
pub fn render_ios_info_plist(version: &str, build_number: &str, bundle_id: &str) -> String {
    format!(
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n\
<plist version=\"1.0\">\n\
<dict>\n\
    <key>CFBundleDevelopmentRegion</key><string>en</string>\n\
    <key>CFBundleDisplayName</key><string>Euv Studio</string>\n\
    <key>CFBundleExecutable</key><string>EuvShowcase</string>\n\
    <key>CFBundleIconFiles</key>\n\
    <array>\n\
        <string>AppIcon60x60@2x.png</string>\n\
        <string>AppIcon60x60@3x.png</string>\n\
        <string>AppIcon.png</string>\n\
    </array>\n\
    <key>CFBundleIcons</key>\n\
    <dict>\n\
        <key>CFBundlePrimaryIcon</key>\n\
        <dict>\n\
            <key>CFBundleIconFiles</key>\n\
            <array>\n\
                <string>AppIcon60x60</string>\n\
            </array>\n\
        </dict>\n\
    </dict>\n\
    <key>CFBundleIdentifier</key><string>{bundle_id}</string>\n\
    <key>CFBundleInfoDictionaryVersion</key><string>6.0</string>\n\
    <key>CFBundleName</key><string>Euv Studio</string>\n\
    <key>CFBundlePackageType</key><string>APPL</string>\n\
    <key>CFBundleShortVersionString</key><string>{version}</string>\n\
    <key>CFBundleVersion</key><string>{build_number}</string>\n\
    <key>CFBundleURLTypes</key>\n\
    <array>\n\
        <dict>\n\
            <key>CFBundleURLName</key><string>{bundle_id}</string>\n\
            <key>CFBundleURLSchemes</key>\n\
            <array>\n\
                <string>euv</string>\n\
            </array>\n\
        </dict>\n\
    </array>\n\
    <key>CADisableMinimumFrameDurationOnPhone</key><true/>\n\
    <key>LSRequiresIPhoneOS</key><true/>\n\
    <key>NSAppTransportSecurity</key>\n\
    <dict>\n\
        <key>NSAllowsArbitraryLoads</key><true/>\n\
        <key>NSAllowsLocalNetworking</key><true/>\n\
    </dict>\n\
    <key>UIApplicationSceneManifest</key>\n\
    <dict>\n\
        <key>UIApplicationSupportsMultipleScenes</key><true/>\n\
        <key>UISceneConfigurations</key>\n\
        <dict>\n\
            <key>UIWindowSceneSessionRoleApplication</key>\n\
            <array>\n\
                <dict>\n\
                    <key>UISceneConfigurationName</key><string>Default Configuration</string>\n\
                    <key>UISceneDelegateClassName</key><string>EuvSceneDelegate</string>\n\
                </dict>\n\
            </array>\n\
        </dict>\n\
    </dict>\n\
    <key>UIApplicationSupportsIndirectInputEvents</key><true/>\n\
    <key>NSMotionUsageDescription</key><string>Motion sensors drive physically accurate liquid water gravity and sloshing simulation.</string>\n\
    <key>UIDeviceFamily</key>\n\
    <array>\n\
        <integer>1</integer>\n\
        <integer>2</integer>\n\
    </array>\n\
    <key>UIRequiresFullScreen</key><false/>\n\
    <key>UILaunchScreen</key><dict/>\n\
    <key>UISupportedInterfaceOrientations</key>\n\
    <array>\n\
        <string>UIInterfaceOrientationPortrait</string>\n\
        <string>UIInterfaceOrientationLandscapeLeft</string>\n\
        <string>UIInterfaceOrientationLandscapeRight</string>\n\
    </array>\n\
    <key>UISupportedInterfaceOrientations~ipad</key>\n\
    <array>\n\
        <string>UIInterfaceOrientationPortrait</string>\n\
        <string>UIInterfaceOrientationPortraitUpsideDown</string>\n\
        <string>UIInterfaceOrientationLandscapeLeft</string>\n\
        <string>UIInterfaceOrientationLandscapeRight</string>\n\
    </array>\n\
</dict>\n\
</plist>\n"
    )
}

/// Renders the standalone Apple watchOS `Info.plist` with dynamic version and bundle identifier.
///
/// # Arguments
///
/// - `&str` - Semantic version written to `CFBundleShortVersionString`.
/// - `&str` - Monotonic build number written to `CFBundleVersion`.
/// - `&str` - Application `CFBundleIdentifier`.
///
/// # Returns
///
/// - `String` - Complete XML `Info.plist` contents for watchOS.
#[must_use]
pub fn render_watchos_info_plist(version: &str, build_number: &str, bundle_id: &str) -> String {
    format!(
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n\
<plist version=\"1.0\">\n\
<dict>\n\
  <key>CFBundleExecutable</key>\n\
  <string>EuvWatch</string>\n\
  <key>CFBundleIdentifier</key>\n\
  <string>{bundle_id}</string>\n\
  <key>CFBundleDisplayName</key>\n\
  <string>Euv Watch</string>\n\
  <key>CFBundleShortVersionString</key>\n\
  <string>{version}</string>\n\
  <key>CFBundleVersion</key>\n\
  <string>{build_number}</string>\n\
  <key>WKApplication</key>\n\
  <true/>\n\
  <key>WKRunsIndependentlyOfCompanionApp</key>\n\
  <true/>\n\
</dict>\n\
</plist>\n"
    )
}

/// Generates the standalone Apple host crate (`staticlib`), Objective-C/Swift entry files, `Info.plist`, and icons.
///
/// # Arguments
///
/// - `&AppleBuildConfig` - Apple build configuration specifying target kind, workspace root, and output paths.
/// - `Option<&MobileIconWriter<'_>>` - Optional callback writing PNG app icons.
///
/// # Returns
///
/// - `io::Result<AppleBuildReport>` - Summary of generated host files and bundle destination.
pub fn generate_apple_host_project(
    config: &AppleBuildConfig,
    icon_writer: Option<&MobileIconWriter<'_>>,
) -> io::Result<AppleBuildReport> {
    let workspace_root: PathBuf = resolve_absolute_path(config.get_workspace_root());
    let target_kind: AppleTargetKind = config.get_target_kind();
    let version: String = config
        .try_get_app_version()
        .clone()
        .unwrap_or_else(|| resolve_workspace_semver(&workspace_root));
    let build_num: u32 = config
        .try_get_build_number()
        .unwrap_or_else(|| compute_semver_version_code(&version));
    let build_number: String = build_num.to_string();
    let bundle_id: String = config
        .try_get_bundle_id()
        .clone()
        .unwrap_or_else(|| target_kind.default_bundle_id().to_string());
    let build_dir: PathBuf = config.try_get_build_dir().clone().unwrap_or_else(|| {
        workspace_root
            .join(MOBILE_HOSTS_SUBDIR)
            .join(target_kind.host_dir_name())
    });
    let out_dir: PathBuf = config.try_get_out_dir().clone().unwrap_or_else(|| {
        workspace_root
            .join(MOBILE_DIST_DIR_NAME)
            .join(target_kind.default_out_subdir())
    });
    let app_bundle: PathBuf = out_dir.join(target_kind.default_bundle_name());
    fs::create_dir_all(build_dir.join(MOBILE_DIR_SRC))?;
    fs::create_dir_all(&out_dir)?;
    let report: AppleBuildReport = AppleBuildReport {
        target_kind: target_kind.as_label().to_string(),
        rust_triple: target_kind.rust_triple().to_string(),
        version,
        build_number,
        build_dir,
        app_bundle_path: app_bundle,
        archive_path: config.try_get_archive_path().clone(),
        binary_bytes: 0,
        ai_schema_clean: true,
        launched: false,
    };
    if target_kind.is_watchos() {
        generate_watchos_host_files(&workspace_root, &out_dir, &bundle_id, &report, icon_writer)?;
    } else {
        generate_ios_host_files(
            &workspace_root,
            config.get_render_mode(),
            &bundle_id,
            &report,
            icon_writer,
        )?;
    }
    Ok(report)
}

/// Builds, strips, signs, verifies, optionally archives, and optionally launches an Apple `.app` bundle.
///
/// # Arguments
///
/// - `&AppleBuildConfig` - Complete Apple build, signing, archiving, and Simulator launch config.
/// - `Option<&MobileIconWriter<'_>>` - Optional callback writing PNG app icons.
///
/// # Returns
///
/// - `io::Result<AppleBuildReport>` - Detailed build report including compiled binary size and archive path.
pub fn build_apple_bundle(
    config: &AppleBuildConfig,
    icon_writer: Option<&MobileIconWriter<'_>>,
) -> io::Result<AppleBuildReport> {
    let generated: AppleBuildReport = generate_apple_host_project(config, icon_writer)?;
    if config.get_shell_only() {
        return Ok(generated);
    }
    if consts::OS != MOBILE_HOST_OS_MACOS {
        return Err(Error::new(ErrorKind::Unsupported, ERR_APPLE_REQUIRES_MACOS));
    }
    let target_kind: AppleTargetKind = config.get_target_kind();
    let sdk_path: String = resolve_xcode_sdk_path(target_kind.xcode_sdk())?;
    let build_dir: &Path = generated.get_build_dir();
    let app_bundle: &Path = generated.get_app_bundle_path();
    let exec_path: PathBuf = app_bundle.join(target_kind.default_executable_name());
    if target_kind.is_watchos() {
        compile_and_link_watchos(config, &sdk_path, build_dir, app_bundle, &exec_path)?;
    } else {
        compile_and_link_ios(config, &sdk_path, build_dir, app_bundle, &exec_path)?;
    }
    if config.get_release() {
        assert_release_binary_ai_schema_clean(&exec_path)?;
    }
    let binary_bytes: u64 = fs::metadata(&exec_path)?.len();
    let archive_path: Option<PathBuf> = config.try_get_archive_path().clone();
    if let Some(archive_dst) = archive_path.as_deref() {
        archive_apple_bundle_tar_gz(app_bundle, archive_dst)?;
    }
    let skip_env: bool = env::var(ENV_EUV_IOS_SKIP_LAUNCH)
        .map(|val: String| val.trim() == "1")
        .unwrap_or(false);
    let launched: bool = if !config.get_no_launch()
        && !skip_env
        && target_kind.is_simulator()
        && !target_kind.is_watchos()
    {
        let bundle_id: String = config
            .try_get_bundle_id()
            .clone()
            .unwrap_or_else(|| target_kind.default_bundle_id().to_string());
        launch_ios_simulator_bundle(config, app_bundle, &bundle_id)?;
        true
    } else {
        false
    };
    Ok(AppleBuildReport {
        target_kind: generated.get_target_kind().clone(),
        rust_triple: generated.get_rust_triple().clone(),
        version: generated.get_version().clone(),
        build_number: generated.get_build_number().clone(),
        build_dir: generated.get_build_dir().clone(),
        app_bundle_path: app_bundle.to_path_buf(),
        archive_path,
        binary_bytes,
        ai_schema_clean: true,
        launched,
    })
}

/// Writes the standalone iOS/iPadOS host crate, `main.m`, `Info.plist`, and bundle icons.
///
/// # Arguments
///
/// - `&Path` - Absolute workspace root path.
/// - `RenderArg` - Selected default render pipeline mode.
/// - `&str` - Bundle identifier string.
/// - `&AppleBuildReport` - Resolved build directories, version, and build number metadata.
/// - `Option<&MobileIconWriter<'_>>` - Optional icon writer callback.
///
/// # Returns
///
/// - `io::Result<()>` - Host generation outcome.
fn generate_ios_host_files(
    workspace_root: &Path,
    render_mode: RenderArg,
    bundle_id: &str,
    report: &AppleBuildReport,
    icon_writer: Option<&MobileIconWriter<'_>>,
) -> io::Result<()> {
    let build_dir: &Path = report.get_build_dir();
    let app_bundle: &Path = report.get_app_bundle_path();
    let version: &str = report.get_version();
    let build_number: &str = report.get_build_number();
    let render_expr: &str = render_mode_const_expr(render_mode);
    let host_config: String = format!(
        "use euv::RenderMode;\n\n\
pub const HOST_RENDER_MODE: RenderMode = {render_expr};\n"
    );
    let root_escaped: String = escape_toml_path(workspace_root);
    let example_escaped: String = escape_toml_path(&workspace_root.join(MOBILE_DIR_EXAMPLE));
    let cargo_toml: String = format!(
        "[workspace]\n\n\
[package]\n\
name = \"euv-ios-host\"\n\
version = \"{version}\"\n\
edition = \"2024\"\n\n\
[lib]\n\
crate-type = [\"staticlib\"]\n\n\
[dependencies]\n\
euv = {{ path = \"{root_escaped}\" }}\n\
euv-example = {{ path = \"{example_escaped}\" }}\n\n\
[profile.release]\n\
opt-level = 3\n\
lto = \"thin\"\n\
codegen-units = 1\n\
panic = \"abort\"\n"
    );
    let info_plist: String = render_ios_info_plist(version, build_number, bundle_id);
    fs::write(
        build_dir
            .join(MOBILE_DIR_SRC)
            .join(MOBILE_FILE_HOST_CONFIG_RS),
        host_config,
    )?;
    fs::write(build_dir.join(MOBILE_FILE_CARGO_TOML), cargo_toml)?;
    fs::write(
        build_dir.join(MOBILE_DIR_SRC).join(MOBILE_FILE_LIB_RS),
        APPLE_IOS_HOST_LIB_RS_TEMPLATE,
    )?;
    fs::write(
        build_dir.join(APPLE_IOS_MAIN_M_FILE),
        APPLE_IOS_MAIN_M_TEMPLATE,
    )?;
    fs::write(build_dir.join(APPLE_INFO_PLIST_FILE), &info_plist)?;
    if app_bundle.exists() {
        fs::remove_dir_all(app_bundle)?;
    }
    fs::create_dir_all(app_bundle)?;
    fs::write(app_bundle.join(APPLE_INFO_PLIST_FILE), info_plist)?;
    for (icon_name, size_px) in APPLE_IOS_ICON_FILES.iter().copied() {
        let icon_path: PathBuf = app_bundle.join(icon_name);
        write_icon_or_fallback(icon_writer, &icon_path, size_px)?;
    }
    Ok(())
}

/// Writes the standalone Apple watchOS host crate, SwiftUI app, bridging header, `Info.plist`, and AppIcon.
///
/// # Arguments
///
/// - `&Path` - Absolute workspace root path.
/// - `&Path` - Destination watchOS project output directory.
/// - `&str` - Bundle identifier string.
/// - `&AppleBuildReport` - Resolved build directories, version, and build number metadata.
/// - `Option<&MobileIconWriter<'_>>` - Optional icon writer callback.
///
/// # Returns
///
/// - `io::Result<()>` - Host generation outcome.
fn generate_watchos_host_files(
    workspace_root: &Path,
    out_dir: &Path,
    bundle_id: &str,
    report: &AppleBuildReport,
    icon_writer: Option<&MobileIconWriter<'_>>,
) -> io::Result<()> {
    let build_dir: &Path = report.get_build_dir();
    let version: &str = report.get_version();
    let build_number: &str = report.get_build_number();
    let app_src_dir: PathBuf = out_dir.join(APPLE_WATCHOS_APP_SRC_DIR);
    let iconset_dir: PathBuf = out_dir.join(APPLE_WATCHOS_ICONSET_REL);
    fs::create_dir_all(&app_src_dir)?;
    fs::create_dir_all(&iconset_dir)?;
    fs::create_dir_all(out_dir.join(APPLE_LIBS_DIR_NAME))?;
    let root_escaped: String = escape_toml_path(workspace_root);
    let example_escaped: String = escape_toml_path(&workspace_root.join(MOBILE_DIR_EXAMPLE));
    let cargo_toml: String = format!(
        "[package]\n\
name = \"euv-watchos-host\"\n\
version = \"{version}\"\n\
edition = \"2024\"\n\n\
[workspace]\n\n\
[lib]\n\
crate-type = [\"staticlib\"]\n\n\
[dependencies]\n\
euv = {{ path = \"{root_escaped}\" }}\n\
euv-example = {{ path = \"{example_escaped}\" }}\n\n\
[profile.release]\n\
opt-level = \"s\"\n\
lto = \"thin\"\n\
codegen-units = 1\n\
panic = \"abort\"\n"
    );
    let info_plist: String = render_watchos_info_plist(version, build_number, bundle_id);
    fs::write(build_dir.join(MOBILE_FILE_CARGO_TOML), cargo_toml)?;
    fs::write(
        build_dir.join(MOBILE_DIR_SRC).join(MOBILE_FILE_LIB_RS),
        APPLE_WATCHOS_HOST_LIB_RS_TEMPLATE,
    )?;
    fs::write(
        app_src_dir.join(APPLE_WATCHOS_BRIDGE_H_FILE),
        APPLE_WATCHOS_BRIDGE_H_TEMPLATE,
    )?;
    fs::write(
        app_src_dir.join(APPLE_WATCHOS_SWIFT_FILE),
        APPLE_WATCHOS_APP_SWIFT_TEMPLATE,
    )?;
    fs::write(app_src_dir.join(APPLE_INFO_PLIST_FILE), info_plist)?;
    fs::write(
        iconset_dir.join(APPLE_CONTENTS_JSON_FILE),
        APPLE_WATCHOS_ICONSET_JSON,
    )?;
    write_icon_or_fallback(
        icon_writer,
        &iconset_dir.join(APPLE_APP_ICON_PNG_FILE),
        APPLE_WATCHOS_ICON_SIZE,
    )
}

/// Compiles the iOS Rust staticlib, links Objective-C `main.m` with all 10 frameworks, strips, and signs.
///
/// # Arguments
///
/// - `&AppleBuildConfig` - Apple build configuration.
/// - `&str` - Resolved Xcode SDK path.
/// - `&Path` - iOS host build directory.
/// - `&Path` - Destination `.app` bundle directory.
/// - `&Path` - Destination executable path inside `app_bundle`.
///
/// # Returns
///
/// - `io::Result<()>` - Compilation, linking, and signing outcome.
fn compile_and_link_ios(
    config: &AppleBuildConfig,
    sdk_path: &str,
    build_dir: &Path,
    app_bundle: &Path,
    exec_path: &Path,
) -> io::Result<()> {
    let target_kind: AppleTargetKind = config.get_target_kind();
    let triple: &str = target_kind.rust_triple();
    let mut cargo_args: Vec<&OsStr> = vec![OsStr::new(MOBILE_ARG_BUILD)];
    if config.get_release() {
        cargo_args.push(OsStr::new(MOBILE_ARG_RELEASE));
    }
    cargo_args.push(OsStr::new(MOBILE_ARG_TARGET));
    cargo_args.push(OsStr::new(triple));
    run_checked_command(
        Path::new(MOBILE_CMD_CARGO),
        &cargo_args,
        Some(build_dir),
        &[],
    )?;
    let profile_dir: &str = if config.get_release() {
        MOBILE_DIR_RELEASE
    } else {
        MOBILE_DIR_DEBUG
    };
    let static_lib: PathBuf = build_dir
        .join(MOBILE_DIR_TARGET)
        .join(triple)
        .join(profile_dir)
        .join(APPLE_IOS_STATICLIB_NAME);
    let clang_out: Output = run_checked_command(
        Path::new(CMD_XCRUN),
        &[
            OsStr::new(ARG_XCRUN_SDK),
            OsStr::new(target_kind.xcode_sdk()),
            OsStr::new(ARG_XCRUN_FIND),
            OsStr::new(TOOL_CLANG),
        ],
        None,
        &[],
    )?;
    let clang_bin: PathBuf = PathBuf::from(String::from_utf8_lossy(&clang_out.stdout).trim());
    let min_ver_flag: &str = if target_kind.is_simulator() {
        ARG_MIN_IOS_SIM
    } else {
        ARG_MIN_IOS_DEVICE
    };
    let main_m: PathBuf = build_dir.join(APPLE_IOS_MAIN_M_FILE);
    let mut link_args: Vec<&OsStr> = vec![
        OsStr::new(ARG_ARCH),
        OsStr::new(ARG_ARM64),
        OsStr::new(ARG_ISYSROOT),
        OsStr::new(sdk_path),
        OsStr::new(min_ver_flag),
        OsStr::new(ARG_FOBJC_ARC),
        main_m.as_os_str(),
        static_lib.as_os_str(),
    ];
    for framework in APPLE_IOS_FRAMEWORKS.iter().copied() {
        link_args.push(OsStr::new(ARG_FRAMEWORK));
        link_args.push(OsStr::new(framework));
    }
    link_args.push(OsStr::new("-o"));
    link_args.push(exec_path.as_os_str());
    run_checked_command(&clang_bin, &link_args, None, &[])?;
    run_checked_command(
        Path::new(CMD_STRIP),
        &[OsStr::new("-x"), exec_path.as_os_str()],
        None,
        &[],
    )?;
    let identity: &str = config.try_get_codesign_identity().as_deref().unwrap_or("-");
    run_checked_command(
        Path::new(CMD_CODESIGN),
        &[
            OsStr::new(ARG_CODESIGN_FORCE),
            OsStr::new(ARG_CODESIGN_SIGN),
            OsStr::new(identity),
            app_bundle.as_os_str(),
        ],
        None,
        &[],
    )?;
    Ok(())
}

/// Compiles the watchOS Rust staticlib and links the SwiftUI host binary via `xcrun swiftc`.
///
/// # Arguments
///
/// - `&AppleBuildConfig` - Apple build configuration.
/// - `&str` - Resolved watchOS Xcode SDK path.
/// - `&Path` - watchOS host build directory.
/// - `&Path` - Destination `EuvWatch.app` bundle directory.
/// - `&Path` - Destination `EuvWatch` executable path.
///
/// # Returns
///
/// - `io::Result<()>` - Compilation, linking, and signing outcome.
fn compile_and_link_watchos(
    config: &AppleBuildConfig,
    sdk_path: &str,
    build_dir: &Path,
    app_bundle: &Path,
    exec_path: &Path,
) -> io::Result<()> {
    let target_kind: AppleTargetKind = config.get_target_kind();
    let triple: &str = target_kind.rust_triple();
    let mut cargo_args: Vec<&OsStr> = vec![OsStr::new(MOBILE_ARG_BUILD)];
    if config.get_release() {
        cargo_args.push(OsStr::new(MOBILE_ARG_RELEASE));
    }
    cargo_args.push(OsStr::new(MOBILE_ARG_TARGET));
    cargo_args.push(OsStr::new(triple));
    let envs: [(&str, &OsStr); 1] = [(ENV_SDKROOT, OsStr::new(sdk_path))];
    run_checked_command(
        Path::new(MOBILE_CMD_CARGO),
        &cargo_args,
        Some(build_dir),
        &envs,
    )?;
    let profile_dir: &str = if config.get_release() {
        MOBILE_DIR_RELEASE
    } else {
        MOBILE_DIR_DEBUG
    };
    let static_lib: PathBuf = build_dir
        .join(MOBILE_DIR_TARGET)
        .join(triple)
        .join(profile_dir)
        .join(APPLE_WATCHOS_STATICLIB_NAME);
    let out_dir: PathBuf = app_bundle
        .parent()
        .map(Path::to_path_buf)
        .unwrap_or_else(|| PathBuf::from("."));
    let lib_dest_dir: PathBuf = out_dir.join(APPLE_LIBS_DIR_NAME).join(triple);
    fs::create_dir_all(&lib_dest_dir)?;
    fs::create_dir_all(app_bundle)?;
    let _: u64 = fs::copy(&static_lib, lib_dest_dir.join(APPLE_WATCHOS_STATICLIB_NAME))?;
    let app_src_dir: PathBuf = out_dir.join(APPLE_WATCHOS_APP_SRC_DIR);
    let _: u64 = fs::copy(
        app_src_dir.join(APPLE_INFO_PLIST_FILE),
        app_bundle.join(APPLE_INFO_PLIST_FILE),
    )?;
    let swift_target: &str = if target_kind.is_simulator() {
        ARG_WATCHOS_SIM_TRIPLE
    } else {
        ARG_WATCHOS_DEVICE_TRIPLE
    };
    let bridge_h: PathBuf = app_src_dir.join(APPLE_WATCHOS_BRIDGE_H_FILE);
    let swift_src: PathBuf = app_src_dir.join(APPLE_WATCHOS_SWIFT_FILE);
    let mut swift_args: Vec<&OsStr> = vec![
        OsStr::new(ARG_XCRUN_SDK),
        OsStr::new(target_kind.xcode_sdk()),
        OsStr::new(TOOL_SWIFTC),
        OsStr::new(ARG_PARSE_AS_LIBRARY),
        OsStr::new(ARG_SWIFTC_TARGET),
        OsStr::new(swift_target),
        OsStr::new(ARG_SWIFTC_SDK),
        OsStr::new(sdk_path),
        OsStr::new("-O"),
        OsStr::new(ARG_IMPORT_OBJC_HEADER),
        bridge_h.as_os_str(),
        swift_src.as_os_str(),
        static_lib.as_os_str(),
    ];
    for framework in APPLE_WATCHOS_FRAMEWORKS.iter().copied() {
        swift_args.push(OsStr::new(ARG_FRAMEWORK));
        swift_args.push(OsStr::new(framework));
    }
    swift_args.push(OsStr::new("-o"));
    swift_args.push(exec_path.as_os_str());
    run_checked_command(Path::new(CMD_XCRUN), &swift_args, None, &[])?;
    let identity: &str = config.try_get_codesign_identity().as_deref().unwrap_or("-");
    run_checked_command(
        Path::new(CMD_CODESIGN),
        &[
            OsStr::new(ARG_CODESIGN_FORCE),
            OsStr::new(ARG_CODESIGN_SIGN),
            OsStr::new(identity),
            app_bundle.as_os_str(),
        ],
        None,
        &[],
    )?;
    Ok(())
}

/// Resolves the Xcode SDK filesystem path for the given SDK name via `xcrun`.
///
/// # Arguments
///
/// - `&str` - Xcode SDK identifier such as `iphonesimulator` or `watchsimulator`.
///
/// # Returns
///
/// - `io::Result<String>` - Trimmed SDK directory path.
fn resolve_xcode_sdk_path(sdk_name: &str) -> io::Result<String> {
    let output: Output = run_checked_command(
        Path::new(CMD_XCRUN),
        &[
            OsStr::new(ARG_XCRUN_SDK),
            OsStr::new(sdk_name),
            OsStr::new(ARG_XCRUN_SHOW_SDK_PATH),
        ],
        None,
        &[],
    )?;
    let path_str: String = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if path_str.is_empty() {
        return Err(Error::new(
            ErrorKind::NotFound,
            format!("xcrun returned empty SDK path for '{sdk_name}'"),
        ));
    }
    Ok(path_str)
}

/// Archives a compiled Apple `.app` bundle into a compressed `.tar.gz` file.
///
/// # Arguments
///
/// - `&Path` - Source `.app` bundle directory.
/// - `&Path` - Destination `.tar.gz` file path.
///
/// # Returns
///
/// - `io::Result<()>` - Archiving outcome.
fn archive_apple_bundle_tar_gz(app_bundle: &Path, archive_dst: &Path) -> io::Result<()> {
    if let Some(archive_parent) = archive_dst.parent() {
        fs::create_dir_all(archive_parent)?;
    }
    let bundle_parent: &Path = app_bundle.parent().unwrap_or_else(|| Path::new("."));
    let bundle_name: &OsStr = app_bundle
        .file_name()
        .unwrap_or_else(|| OsStr::new(APPLE_IOS_BUNDLE_NAME));
    run_checked_command(
        Path::new(APPLE_CMD_TAR),
        &[
            OsStr::new(ARG_TAR_CZF),
            archive_dst.as_os_str(),
            OsStr::new("-C"),
            bundle_parent.as_os_str(),
            bundle_name,
        ],
        None,
        &[],
    )?;
    Ok(())
}

/// Boots, installs, and launches the `.app` bundle in an iOS/iPadOS Simulator while forwarding OTA env vars.
///
/// # Arguments
///
/// - `&AppleBuildConfig` - Apple build configuration.
/// - `&Path` - Compiled and signed `.app` bundle path.
/// - `&str` - Bundle identifier launched via `xcrun simctl launch`.
///
/// # Returns
///
/// - `io::Result<()>` - Simulator install and launch outcome.
fn launch_ios_simulator_bundle(
    config: &AppleBuildConfig,
    app_bundle: &Path,
    bundle_id: &str,
) -> io::Result<()> {
    let sim_udid: String = resolve_ios_simulator_udid(config)?;
    let _: io::Result<Output> = Command::new(CMD_XCRUN)
        .args([TOOL_SIMCTL, ARG_SIMCTL_BOOT, &sim_udid])
        .output();
    let _: io::Result<Output> = Command::new(CMD_XCRUN)
        .args([TOOL_SIMCTL, ARG_SIMCTL_TERMINATE, &sim_udid, bundle_id])
        .output();
    run_checked_command(
        Path::new(CMD_XCRUN),
        &[
            OsStr::new(TOOL_SIMCTL),
            OsStr::new(ARG_SIMCTL_INSTALL),
            OsStr::new(&sim_udid),
            app_bundle.as_os_str(),
        ],
        None,
        &[],
    )?;
    let mut forwarded_owned: Vec<(String, OsString)> = Vec::new();
    for env_key in [
        ENV_EUV_UPDATE_URL,
        ENV_EUV_PROXY_URL,
        ENV_EUV_UPDATE_CHANNEL,
    ] {
        if let Ok(env_val) = env::var(env_key)
            && !env_val.trim().is_empty()
        {
            forwarded_owned.push((
                format!("{ENV_SIMCTL_CHILD_PREFIX}{env_key}"),
                OsString::from(env_val),
            ));
        }
    }
    let forwarded_refs: Vec<(&str, &OsStr)> = forwarded_owned
        .iter()
        .map(|(env_k, env_v): &(String, OsString)| (env_k.as_str(), env_v.as_os_str()))
        .collect();
    run_checked_command(
        Path::new(CMD_XCRUN),
        &[
            OsStr::new(TOOL_SIMCTL),
            OsStr::new(ARG_SIMCTL_LAUNCH),
            OsStr::new(&sim_udid),
            OsStr::new(bundle_id),
        ],
        None,
        &forwarded_refs,
    )?;
    Ok(())
}

/// Resolves an active or available iOS/iPadOS Simulator UDID from config, env, or `xcrun simctl`.
///
/// # Arguments
///
/// - `&AppleBuildConfig` - Apple build configuration.
///
/// # Returns
///
/// - `io::Result<String>` - Resolved 36-character Simulator UUID.
fn resolve_ios_simulator_udid(config: &AppleBuildConfig) -> io::Result<String> {
    if let Some(custom) = config.try_get_sim_udid() {
        return Ok(custom.clone());
    }
    if let Ok(env_udid) = env::var(ENV_EUV_IOS_SIM_UDID) {
        let trimmed: &str = env_udid.trim();
        if !trimmed.is_empty() {
            return Ok(trimmed.to_string());
        }
    }
    let booted_out: Output = Command::new(CMD_XCRUN)
        .args([
            TOOL_SIMCTL,
            ARG_SIMCTL_LIST,
            ARG_SIMCTL_DEVICES,
            ARG_SIMCTL_BOOTED,
        ])
        .output()?;
    let booted_text: Cow<'_, str> = String::from_utf8_lossy(&booted_out.stdout);
    if let Some(udid) = extract_first_sim_uuid(&booted_text, None) {
        return Ok(udid);
    }
    let avail_out: Output = Command::new(CMD_XCRUN)
        .args([
            TOOL_SIMCTL,
            ARG_SIMCTL_LIST,
            ARG_SIMCTL_DEVICES,
            ARG_SIMCTL_AVAILABLE,
        ])
        .output()?;
    let avail_text: Cow<'_, str> = String::from_utf8_lossy(&avail_out.stdout);
    let device_filter: &str = if config.get_target_kind().is_ipad() {
        SIM_DEVICE_IPAD
    } else {
        SIM_DEVICE_IPHONE
    };
    if let Some(udid) = extract_first_sim_uuid(&avail_text, Some(device_filter)) {
        return Ok(udid);
    }
    Err(Error::new(ErrorKind::NotFound, ERR_APPLE_NO_SIMULATOR))
}

/// Extracts the first 36-character uppercase UUID from `xcrun simctl list devices` output.
///
/// # Arguments
///
/// - `&str` - Multiline `simctl` text output.
/// - `Option<&str>` - Optional device label substring filter such as `"iPhone"` or `"iPad"`.
///
/// # Returns
///
/// - `Option<String>` - First matching UUID string when found.
fn extract_first_sim_uuid(simctl_output: &str, line_filter: Option<&str>) -> Option<String> {
    for raw_line in simctl_output.lines() {
        if let Some(filter) = line_filter
            && !raw_line.contains(filter)
        {
            continue;
        }
        let mut search_from: usize = 0;
        while let Some(open_rel) = raw_line[search_from..].find('(') {
            let start_idx: usize = search_from + open_rel + 1;
            let Some(close_rel) = raw_line[start_idx..].find(')') else {
                break;
            };
            let candidate: &str = &raw_line[start_idx..start_idx + close_rel];
            if is_sim_uuid(candidate) {
                return Some(candidate.to_string());
            }
            search_from = start_idx + close_rel + 1;
        }
    }
    None
}

/// Validates whether a candidate string matches the 36-character `8-4-4-4-12` Simulator UUID format.
///
/// # Arguments
///
/// - `&str` - Candidate token inside parentheses.
///
/// # Returns
///
/// - `bool` - `true` when `candidate` is a valid uppercase/hex UUID.
fn is_sim_uuid(candidate: &str) -> bool {
    if candidate.len() != APPLE_UUID_LEN {
        return false;
    }
    for (idx, byte_val) in candidate.bytes().enumerate() {
        let expect_dash: bool = idx == 8 || idx == 13 || idx == 18 || idx == 23;
        if expect_dash {
            if byte_val != b'-' {
                return false;
            }
        } else if !byte_val.is_ascii_hexdigit() {
            return false;
        }
    }
    true
}