@moku-labs/native 0.2.2 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -798,6 +798,18 @@ function generateCapabilities(input) {
798
798
  //#endregion
799
799
  //#region src/plugins/project/generators/cargo.ts
800
800
  /**
801
+ * The `tauri` crate floor. The `back` capability calls `exit()` and grants
802
+ * `core:app:allow-exit`, and both exist only since tauri 2.12.0. `tauri-build` versions
803
+ * on its own 2.x line, so its floor stays `"2"`.
804
+ */
805
+ const TAURI_VERSION_FLOOR = "2.12";
806
+ /**
807
+ * The dependencies only an iOS build compiles: the safe-area hook in the generated
808
+ * `lib.rs` reaches WKWebView through `objc2`. A target table, written for every target,
809
+ * so no other target ever builds the crate and the table adds no per-target difference.
810
+ */
811
+ const IOS_ONLY_DEPENDENCIES = [`[target.'cfg(target_os = "ios")'.dependencies]`, "objc2 = \"0.6\""];
812
+ /**
801
813
  * Derives a valid Cargo package name from the app's display name — lowercased,
802
814
  * non-alphanumeric runs collapsed to a single hyphen, and guaranteed to start with a
803
815
  * letter (Cargo package names must match `[a-z][a-z0-9_-]*`).
@@ -833,7 +845,8 @@ function crateIdent(packageName) {
833
845
  * Generates `src-tauri/Cargo.toml` — the package manifest, the `tauri` dependency with
834
846
  * every cargo feature the composed capabilities ask for (tray's `tray-icon`; without it
835
847
  * the tray API is not compiled in at all), plus one pinned dependency line per resolved
836
- * capability that ships a real crate. Feature-only rows contribute no dependency line.
848
+ * capability that ships a real crate. Feature-only and permission-only rows contribute
849
+ * no dependency line. The iOS-only `objc2` table closes the file on every target.
837
850
  *
838
851
  * @param input - Frozen global config + capabilities resolved for the target.
839
852
  * @returns A single-artifact array for `src-tauri/Cargo.toml`.
@@ -862,10 +875,12 @@ function generateCargo(input) {
862
875
  "tauri-build = { version = \"2\", features = [] }",
863
876
  "",
864
877
  "[dependencies]",
865
- `tauri = { version = "2", features = [${features}] }`,
878
+ `tauri = { version = "${TAURI_VERSION_FLOOR}", features = [${features}] }`,
866
879
  "serde = { version = \"1\", features = [\"derive\"] }",
867
880
  "serde_json = \"1\"",
868
881
  ...pinnedDeps,
882
+ "",
883
+ ...IOS_ONLY_DEPENDENCIES,
869
884
  ""
870
885
  ].join("\n")
871
886
  }];
@@ -983,14 +998,44 @@ function generateEntitlements(input) {
983
998
  //#endregion
984
999
  //#region src/plugins/project/generators/rust.ts
985
1000
  /**
986
- * @file project plugin generator — main.rs/lib.rs with mobile entry point + plugin init lines.
987
- */
1001
+ * @file project plugin generator — main.rs/lib.rs with mobile entry point, plugin init
1002
+ * lines and the iOS safe-area setup hook.
1003
+ */
1004
+ /**
1005
+ * `Manager` brings `get_webview_window` into scope. Only the iOS arm of the setup hook
1006
+ * calls it, so the import is iOS-only too: anywhere else it would be an unused import.
1007
+ */
1008
+ const IOS_MANAGER_IMPORT = ["#[cfg(target_os = \"ios\")]", "use tauri::Manager;"];
1009
+ /**
1010
+ * The safe-area setup hook, as verified on the iOS 26.3 simulator. UIKit shrinks a
1011
+ * WKWebView page by the safe area while its scroll view stays on `.automatic`; `.never`
1012
+ * gives the page the whole screen, and CSS `env(safe-area-inset-*)` still reports the
1013
+ * notch. The `cfg` makes it a no-op off iOS, so `lib.rs` does not differ per target. The
1014
+ * window is tauri's default `main` label: the generated `app.windows` entry carries none.
1015
+ */
1016
+ const SAFE_AREA_SETUP = [
1017
+ " .setup(|_app| {",
1018
+ " // wry leaves WKWebView's scroll view on .automatic, which shrinks the page by the",
1019
+ " // safe area (tauri-apps/tauri#8166). .never gives the page the full screen.",
1020
+ " #[cfg(target_os = \"ios\")]",
1021
+ " if let Some(window) = _app.get_webview_window(\"main\") {",
1022
+ " window.with_webview(|webview| unsafe {",
1023
+ " use objc2::{msg_send, runtime::AnyObject};",
1024
+ " let wk = &*(webview.inner() as *mut AnyObject);",
1025
+ " let scroll: *mut AnyObject = msg_send![wk, scrollView];",
1026
+ " // UIScrollViewContentInsetAdjustmentNever = 2",
1027
+ " let _: () = msg_send![&*scroll, setContentInsetAdjustmentBehavior: 2isize];",
1028
+ " })?;",
1029
+ " }",
1030
+ " Ok(())",
1031
+ " })"
1032
+ ];
988
1033
  /**
989
1034
  * Generates `src-tauri/src/lib.rs` and `src-tauri/src/main.rs`. `lib.rs` carries the
990
1035
  * `#[cfg_attr(mobile, tauri::mobile_entry_point)]`-annotated `run()` with one
991
1036
  * `.plugin(...)` init line per resolved capability that has a real Rust init (rows
992
- * without one, e.g. tray's cargo-feature row, contribute no line); `main.rs` is a thin
993
- * entry point that calls into the lib crate.
1037
+ * without one, e.g. tray's cargo-feature row, contribute no line), then the iOS
1038
+ * safe-area `.setup` hook; `main.rs` is a thin entry point that calls into the lib crate.
994
1039
  *
995
1040
  * @param input - Frozen global config + capabilities resolved for the target.
996
1041
  * @returns Artifacts for `src-tauri/src/lib.rs` and `src-tauri/src/main.rs`.
@@ -1001,11 +1046,15 @@ function generateEntitlements(input) {
1001
1046
  */
1002
1047
  function generateRust(input) {
1003
1048
  const packageIdent = crateIdent(sanitizePackageName(input.global.app.name));
1049
+ const pluginLines = input.capabilities.filter((capability) => Boolean(capability.rustInit)).map((capability) => ` .plugin(${capability.rustInit})`).toSorted();
1004
1050
  const library = [
1051
+ ...IOS_MANAGER_IMPORT,
1052
+ "",
1005
1053
  "#[cfg_attr(mobile, tauri::mobile_entry_point)]",
1006
1054
  "pub fn run() {",
1007
1055
  " tauri::Builder::default()",
1008
- ...input.capabilities.filter((capability) => Boolean(capability.rustInit)).map((capability) => ` .plugin(${capability.rustInit})`).toSorted(),
1056
+ ...pluginLines,
1057
+ ...SAFE_AREA_SETUP,
1009
1058
  " .run(tauri::generate_context!())",
1010
1059
  " .expect(\"error while running tauri application\");",
1011
1060
  "}",
@@ -1028,25 +1077,172 @@ function generateRust(input) {
1028
1077
  }];
1029
1078
  }
1030
1079
  //#endregion
1080
+ //#region src/plugins/project/orientation.ts
1081
+ const PORTRAIT = "UIInterfaceOrientationPortrait";
1082
+ const PORTRAIT_UPSIDE_DOWN = "UIInterfaceOrientationPortraitUpsideDown";
1083
+ const LANDSCAPE_SIDES = ["UIInterfaceOrientationLandscapeLeft", "UIInterfaceOrientationLandscapeRight"];
1084
+ /**
1085
+ * The iOS orientation lists per lock: the iPhone key, then the `~ipad` override. An iPhone
1086
+ * held portrait never turns upside down; an iPad does, so its portrait list keeps both.
1087
+ */
1088
+ const IOS_ORIENTATIONS = {
1089
+ portrait: {
1090
+ iphone: [PORTRAIT],
1091
+ ipad: [PORTRAIT, PORTRAIT_UPSIDE_DOWN]
1092
+ },
1093
+ landscape: {
1094
+ iphone: LANDSCAPE_SIDES,
1095
+ ipad: LANDSCAPE_SIDES
1096
+ }
1097
+ };
1098
+ /**
1099
+ * The Android `screenOrientation` per lock, matching the iOS lists: `portrait` has no
1100
+ * upside-down side, `sensorLandscape` turns between both landscape sides. `any` maps to no
1101
+ * attribute at all, the template's default.
1102
+ */
1103
+ const ANDROID_SCREEN_ORIENTATION = {
1104
+ portrait: "portrait",
1105
+ landscape: "sensorLandscape",
1106
+ any: void 0
1107
+ };
1108
+ /**
1109
+ * Builds the `Info.ios.plist` entries that lock the iOS orientation. A locked app also
1110
+ * asks for `UIRequiresFullScreen`: App Store review refuses an iPad app that restricts its
1111
+ * orientations without it. `any` and unset add nothing, so the template's default list
1112
+ * (every orientation) stays.
1113
+ *
1114
+ * @param orientation - The configured `app.orientation`, or undefined when unset.
1115
+ * @returns The plist entries, empty when the orientation is not locked.
1116
+ * @example
1117
+ * ```ts
1118
+ * orientationPlist("portrait")[0];
1119
+ * // { key: "UISupportedInterfaceOrientations", value: ["UIInterfaceOrientationPortrait"] }
1120
+ * ```
1121
+ */
1122
+ function orientationPlist(orientation) {
1123
+ if (orientation === void 0 || orientation === "any") return [];
1124
+ const { iphone, ipad } = IOS_ORIENTATIONS[orientation];
1125
+ return [
1126
+ {
1127
+ key: "UISupportedInterfaceOrientations",
1128
+ value: iphone
1129
+ },
1130
+ {
1131
+ key: "UISupportedInterfaceOrientations~ipad",
1132
+ value: ipad
1133
+ },
1134
+ {
1135
+ key: "UIRequiresFullScreen",
1136
+ value: true
1137
+ }
1138
+ ];
1139
+ }
1140
+ /**
1141
+ * Builds the Android manifest entry for the orientation lock: `android:screenOrientation`
1142
+ * on the main activity. `any` and unset ask for the attribute to be ABSENT rather than
1143
+ * adding nothing, so a lock a previous build wrote into the gen/ tree is removed again.
1144
+ *
1145
+ * @param orientation - The configured `app.orientation`, or undefined when unset.
1146
+ * @returns Exactly one `activity-attribute` entry.
1147
+ * @example
1148
+ * ```ts
1149
+ * orientationManifest("landscape");
1150
+ * // [{ kind: "activity-attribute", name: "android:screenOrientation", value: "sensorLandscape" }]
1151
+ * ```
1152
+ */
1153
+ function orientationManifest(orientation) {
1154
+ return [{
1155
+ kind: "activity-attribute",
1156
+ name: "android:screenOrientation",
1157
+ value: ANDROID_SCREEN_ORIENTATION[orientation ?? "any"]
1158
+ }];
1159
+ }
1160
+ //#endregion
1161
+ //#region src/plugins/project/xml.ts
1162
+ /**
1163
+ * @file project plugin — XML text escaping, shared by the two XML files this plugin writes
1164
+ * into: the `Info.ios.plist` sidecar and the Android manifest.
1165
+ */
1166
+ /**
1167
+ * XML's five predefined entities. `&` goes first, so the ampersand of an entity written
1168
+ * by a later step is never escaped a second time.
1169
+ */
1170
+ const XML_ESCAPES = [
1171
+ [/&/g, "&"],
1172
+ [/</g, "&lt;"],
1173
+ [/>/g, "&gt;"],
1174
+ [/"/g, "&quot;"],
1175
+ [/'/g, "&apos;"]
1176
+ ];
1177
+ /**
1178
+ * Escapes text for an XML element body or a quoted attribute value. A value lands
1179
+ * verbatim in a generated file, where an unescaped `<` or `"` would end the element or
1180
+ * the attribute around it.
1181
+ *
1182
+ * @param text - The raw value.
1183
+ * @returns The value with `& < > " '` written as entities.
1184
+ * @example
1185
+ * ```ts
1186
+ * escapeXml(`Tom & "Jerry"`); // "Tom &amp; &quot;Jerry&quot;"
1187
+ * ```
1188
+ */
1189
+ function escapeXml(text) {
1190
+ let escaped = text;
1191
+ for (const [pattern, entity] of XML_ESCAPES) escaped = escaped.replace(pattern, entity);
1192
+ return escaped;
1193
+ }
1194
+ //#endregion
1031
1195
  //#region src/plugins/project/generators/sidecar.ts
1032
1196
  /**
1033
- * Generates the `Info.ios.plist` SIDECAR at the src-tauri root — a future-mechanism
1034
- * seam for iOS mobile-permission plist keys (D-012). Every v1 registry row carries an
1035
- * empty `sidecarPlist`, so this emits no artifact today; it stays pure and
1036
- * generator-shaped so a future row carrying `sidecarPlist` entries activates it with
1037
- * zero pipeline changes.
1197
+ * @file project plugin generator — Info.ios.plist sidecar (src-tauri root, outside gen/).
1198
+ */
1199
+ /**
1200
+ * Renders one plist value as the lines that follow its `<key>`: a `<string>`, a
1201
+ * `<true/>`/`<false/>`, or an `<array>` of strings. Every text is XML-escaped.
1202
+ *
1203
+ * @param value - The entry value.
1204
+ * @returns The value's lines, indented for the top-level `<dict>`.
1205
+ * @example
1206
+ * ```ts
1207
+ * renderPlistValue(["UIInterfaceOrientationPortrait"]);
1208
+ * // [" <array>", " <string>UIInterfaceOrientationPortrait</string>", " </array>"]
1209
+ * ```
1210
+ */
1211
+ function renderPlistValue(value) {
1212
+ if (typeof value === "boolean") return [value ? " <true/>" : " <false/>"];
1213
+ if (typeof value === "string") return [` <string>${escapeXml(value)}</string>`];
1214
+ return [
1215
+ " <array>",
1216
+ ...value.map((item) => ` <string>${escapeXml(item)}</string>`),
1217
+ " </array>"
1218
+ ];
1219
+ }
1220
+ /**
1221
+ * Generates the `Info.ios.plist` SIDECAR at the src-tauri root, which Tauri merges into the
1222
+ * app's Info.plist on every iOS build. Its entries are every resolved capability's
1223
+ * `sidecarPlist`, then the orientation lock (`app.orientation`); on a duplicate key the
1224
+ * later entry wins, so orientation beats a capability.
1225
+ *
1226
+ * On iOS the file is ALWAYS written, as an empty `<dict>` when nothing contributes a key:
1227
+ * the writer never deletes a file, and a portrait lock left in a stale sidecar would keep
1228
+ * being merged after the app went back to `any`. Every other target gets no artifact.
1038
1229
  *
1039
1230
  * @param input - Frozen global config + capabilities resolved for the target.
1040
- * @returns An artifact for `src-tauri/Info.ios.plist` when any resolved capability
1041
- * carries sidecar entries, otherwise an empty array.
1231
+ * @returns An artifact for `src-tauri/Info.ios.plist` on iOS, otherwise an empty array.
1042
1232
  * @example
1043
1233
  * ```ts
1044
- * generateSidecar({ global, target: "ios", capabilities: [] }); // []
1234
+ * // `config` is any full native Config
1235
+ * const global = { ...config, app: { name: "Demo", identifier: "com.acme.demo", orientation: "portrait" } };
1236
+ * generateSidecar({ global, target: "ios", capabilities: [] })[0]?.path; // "src-tauri/Info.ios.plist"
1237
+ * // its <dict>: UISupportedInterfaceOrientations, UISupportedInterfaceOrientations~ipad, UIRequiresFullScreen
1238
+ * generateSidecar({ global, target: "macos", capabilities: [] }); // []
1045
1239
  * ```
1046
1240
  */
1047
1241
  function generateSidecar(input) {
1048
- const entries = input.capabilities.flatMap((capability) => capability.sidecarPlist);
1049
- if (entries.length === 0) return [];
1242
+ if (input.target !== "ios") return [];
1243
+ const entries = /* @__PURE__ */ new Map();
1244
+ const contributed = [...input.capabilities.flatMap((capability) => capability.sidecarPlist), ...orientationPlist(input.global.app.orientation)];
1245
+ for (const entry of contributed) entries.set(entry.key, entry.value);
1050
1246
  return [{
1051
1247
  path: "src-tauri/Info.ios.plist",
1052
1248
  content: [
@@ -1054,7 +1250,7 @@ function generateSidecar(input) {
1054
1250
  "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">",
1055
1251
  "<plist version=\"1.0\">",
1056
1252
  "<dict>",
1057
- entries.map((entry) => ` <key>${entry.key}</key>\n <string>${entry.value}</string>`).join("\n"),
1253
+ ...[...entries].flatMap(([key, value]) => [` <key>${escapeXml(key)}</key>`, ...renderPlistValue(value)]),
1058
1254
  "</dict>",
1059
1255
  "</plist>",
1060
1256
  ""
@@ -1158,7 +1354,8 @@ function buildPlugins(capabilities) {
1158
1354
  }
1159
1355
  /**
1160
1356
  * Generates `src-tauri/tauri.conf.json` — app identity, the web build/dev wiring, the
1161
- * bundle/signing metadata, and a `plugins.<name>` block per CONFIGURED capability (see
1357
+ * main window (its title, plus `app.backgroundColor` when set), the bundle/signing
1358
+ * metadata, and a `plugins.<name>` block per CONFIGURED capability (see
1162
1359
  * {@link buildPlugins}; this is where deep-link's scheme rides — per D-011/D-012 the whole
1163
1360
  * v1 mobile-permission story is conf-only). Both path-shaped fields are rebased onto
1164
1361
  * `src-tauri`, which is where Tauri resolves them from, and the before-commands carry an
@@ -1190,7 +1387,10 @@ function generateTauriConf(input) {
1190
1387
  devUrl: global.web.devUrl,
1191
1388
  frontendDist: relativeToTauriRoot(global.projectDir, node_path.default.resolve(webRoot, global.web.dist))
1192
1389
  },
1193
- app: { windows: [{ title: global.app.name }] },
1390
+ app: { windows: [{
1391
+ title: global.app.name,
1392
+ ...compact([["backgroundColor", global.app.backgroundColor]])
1393
+ }] },
1194
1394
  bundle: buildBundle(input),
1195
1395
  plugins: buildPlugins(capabilities)
1196
1396
  };
@@ -1328,7 +1528,9 @@ function placeholderIconPng() {
1328
1528
  * @file project plugin — mobile gen/-tree required-file completeness gate.
1329
1529
  */
1330
1530
  /**
1331
- * Required top-level entries per mobile `gen/<platform>` tree (Tauri 2.9.x scaffolding).
1531
+ * Required top-level entries per mobile `gen/<platform>` tree. The android set is verified
1532
+ * against the tree `tauri android init` writes in tauri-cli 2.12.1: the settings file is
1533
+ * Groovy `settings.gradle`, not `settings.gradle.kts`.
1332
1534
  * A partial init (tauri#13902) can leave some of these absent — `completeness` checks
1333
1535
  * the required-file SET, not mere directory existence.
1334
1536
  */
@@ -1341,7 +1543,7 @@ const REQUIRED_FILES = {
1341
1543
  ],
1342
1544
  android: [
1343
1545
  "build.gradle.kts",
1344
- "settings.gradle.kts",
1546
+ "settings.gradle",
1345
1547
  "gradle.properties",
1346
1548
  "app/build.gradle.kts",
1347
1549
  "app/src/main/AndroidManifest.xml"
@@ -1355,7 +1557,7 @@ const REQUIRED_FILES = {
1355
1557
  * @returns The frozen list of required paths, relative to `src-tauri/gen/<platform>`.
1356
1558
  * @example
1357
1559
  * ```ts
1358
- * requiredFiles("android"); // ["build.gradle.kts", "settings.gradle.kts", ...]
1560
+ * requiredFiles("android"); // ["build.gradle.kts", "settings.gradle", ...]
1359
1561
  * ```
1360
1562
  */
1361
1563
  function requiredFiles(platform) {
@@ -1489,13 +1691,229 @@ async function writeIfChanged(filePath, content, projectDirectory) {
1489
1691
  return "written";
1490
1692
  }
1491
1693
  //#endregion
1694
+ //#region src/plugins/project/mobile/manifest.ts
1695
+ /**
1696
+ * @file project plugin — the Android manifest patch. Tauri has no config key for what the
1697
+ * main activity carries (`android:screenOrientation` among them), so the mobile patch pass
1698
+ * sets those attributes on the `<activity>` of the generated
1699
+ * `gen/android/app/src/main/AndroidManifest.xml` itself.
1700
+ *
1701
+ * The transform is a pure text function: only the touched attribute changes, every other
1702
+ * byte (line endings and indentation included) survives, and a second pass is a no-op.
1703
+ */
1704
+ /** Where `tauri android init` writes the app manifest, below `gen/android`. */
1705
+ const MANIFEST_PATH_SEGMENTS = [
1706
+ "app",
1707
+ "src",
1708
+ "main",
1709
+ "AndroidManifest.xml"
1710
+ ];
1711
+ /** The tag name an activity start tag opens with. */
1712
+ const ACTIVITY_OPEN = "<activity";
1713
+ /** The end tag that closes an activity's body. */
1714
+ const ACTIVITY_CLOSE = "</activity>";
1715
+ /** The intent action that marks the launcher activity. */
1716
+ const MAIN_ACTION = "android.intent.action.MAIN";
1717
+ /** Where an `<activity` start tag opens — `<activity-alias` is a different element. */
1718
+ const ACTIVITY_OPEN_PATTERN = /<activity(?=[\s/>])/g;
1719
+ /**
1720
+ * One attribute inside a start tag, from the whitespace character before it:
1721
+ * ` (name)="value"`. XML allows spaces around `=`, but no generated manifest writes them.
1722
+ */
1723
+ const ATTRIBUTE_PATTERN = /\s([\w:.-]+)=(?:"[^"]*"|'[^']*')/g;
1724
+ /** An XML comment — blanked before the scan, so a commented-out activity never counts. */
1725
+ const COMMENT_PATTERN = /<!--[\s\S]*?-->/g;
1726
+ /**
1727
+ * Builds the `[native]` error for a manifest whose main activity cannot be told apart.
1728
+ *
1729
+ * @param manifestPath - The manifest that was searched.
1730
+ * @returns A formatted `[native] ...` error.
1731
+ * @example
1732
+ * ```ts
1733
+ * throw mainActivityError("/repo/.moku/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml");
1734
+ * ```
1735
+ */
1736
+ function mainActivityError(manifestPath) {
1737
+ return /* @__PURE__ */ new Error(`[native] Could not find the main <activity> in ${manifestPath}.\n Re-run the mobile init pass (tauri android init) or report the manifest Tauri generated.`);
1738
+ }
1739
+ /**
1740
+ * Finds where a start tag ends. A quoted attribute value is skipped whole, so a `>` inside
1741
+ * one never ends the tag.
1742
+ *
1743
+ * @param text - The manifest content.
1744
+ * @param from - Offset just past the tag name.
1745
+ * @returns The offset just past the closing `>`, or undefined for a tag that never closes.
1746
+ * @example
1747
+ * ```ts
1748
+ * startTagEnd('<activity android:label="a > b">', 9); // 32
1749
+ * ```
1750
+ */
1751
+ function startTagEnd(text, from) {
1752
+ let quote;
1753
+ for (let index = from; index < text.length; index += 1) {
1754
+ const character = text[index];
1755
+ if (quote !== void 0) {
1756
+ if (character === quote) quote = void 0;
1757
+ continue;
1758
+ }
1759
+ if (character === "\"" || character === "'") {
1760
+ quote = character;
1761
+ continue;
1762
+ }
1763
+ if (character === ">") return index + 1;
1764
+ }
1765
+ }
1766
+ /**
1767
+ * Locates every `<activity>` start tag and records whether its body declares MAIN.
1768
+ * Comments are blanked out first (same length, so every offset still points into the real
1769
+ * text), which keeps a commented-out activity from being counted or patched. A start tag
1770
+ * that never closes is not counted at all.
1771
+ *
1772
+ * @param text - The manifest content.
1773
+ * @returns One entry per activity, in file order.
1774
+ * @example
1775
+ * ```ts
1776
+ * locateActivities('<activity android:name=".A" /><activity android:name=".B"><action android:name="android.intent.action.MAIN" /></activity>');
1777
+ * // [{ start: 0, end: 30, isMain: false }, { start: 30, end: 58, isMain: true }]
1778
+ * ```
1779
+ */
1780
+ function locateActivities(text) {
1781
+ const masked = text.replaceAll(COMMENT_PATTERN, (comment) => " ".repeat(comment.length));
1782
+ const activities = [];
1783
+ for (const match of masked.matchAll(ACTIVITY_OPEN_PATTERN)) {
1784
+ const start = match.index;
1785
+ const end = startTagEnd(masked, start + 9);
1786
+ if (end === void 0) continue;
1787
+ const body = masked.slice(start, end).endsWith("/>") ? "" : masked.slice(end, masked.indexOf(ACTIVITY_CLOSE, end));
1788
+ activities.push({
1789
+ start,
1790
+ end,
1791
+ isMain: body.includes(MAIN_ACTION)
1792
+ });
1793
+ }
1794
+ return activities;
1795
+ }
1796
+ /**
1797
+ * Picks the main activity: the one whose body declares MAIN. A manifest with a single
1798
+ * activity and no MAIN still has an obvious one; anything else is ambiguous.
1799
+ *
1800
+ * @param activities - Every activity in the manifest.
1801
+ * @returns The main activity, or undefined when none or several qualify.
1802
+ * @example
1803
+ * ```ts
1804
+ * mainActivity([{ start: 0, end: 30, isMain: false }, { start: 30, end: 58, isMain: true }]);
1805
+ * // { start: 30, end: 58, isMain: true }
1806
+ * mainActivity([{ start: 0, end: 30, isMain: false }, { start: 30, end: 58, isMain: false }]); // undefined
1807
+ * ```
1808
+ */
1809
+ function mainActivity(activities) {
1810
+ const mains = activities.filter((activity) => activity.isMain);
1811
+ if (mains.length === 1) return mains[0];
1812
+ if (mains.length === 0 && activities.length === 1) return activities[0];
1813
+ }
1814
+ /**
1815
+ * Applies one attribute entry to a start tag. A value replaces the attribute in place, or
1816
+ * is inserted right after `<activity` with the whitespace that already follows it — on the
1817
+ * template's one-attribute-per-line layout that is the line break plus the next
1818
+ * attribute's indentation, CRLF included. An `undefined` value removes the attribute
1819
+ * together with the whitespace before it, which on that layout is its whole line.
1820
+ *
1821
+ * @param tag - The activity start tag.
1822
+ * @param entry - The attribute to set or remove.
1823
+ * @returns The start tag with the entry applied.
1824
+ * @example
1825
+ * ```ts
1826
+ * applyAttribute('<activity android:name=".MainActivity">', portraitEntry);
1827
+ * // '<activity android:screenOrientation="portrait" android:name=".MainActivity">'
1828
+ * ```
1829
+ */
1830
+ function applyAttribute(tag, entry) {
1831
+ const rendered = entry.value === void 0 ? void 0 : `${entry.name}="${escapeXml(entry.value)}"`;
1832
+ const existing = [...tag.matchAll(ATTRIBUTE_PATTERN)].find((match) => match[1] === entry.name);
1833
+ if (existing) {
1834
+ const before = tag.slice(0, existing.index).trimEnd();
1835
+ const separator = tag.slice(before.length, existing.index + 1);
1836
+ const after = tag.slice(existing.index + existing[0].length);
1837
+ if (rendered === void 0) return `${before}${after}`;
1838
+ return `${before}${separator}${rendered}${after}`;
1839
+ }
1840
+ if (rendered === void 0) return tag;
1841
+ const rest = tag.slice(9);
1842
+ const separator = rest.slice(0, rest.length - rest.trimStart().length) || " ";
1843
+ return `${ACTIVITY_OPEN}${separator}${rendered}${rest}`;
1844
+ }
1845
+ /**
1846
+ * Applies the `activity-attribute` entries to the main activity of a manifest. `child`
1847
+ * entries are not applied: no registry row carries one, and the official plugins merge
1848
+ * their own manifest needs through build.rs. A pass that only removes attributes leaves a
1849
+ * manifest without a clear main activity as it is.
1850
+ *
1851
+ * @param existing - The current manifest content.
1852
+ * @param entries - The manifest entries to apply, in order (a later one wins).
1853
+ * @param manifestPath - The manifest's path, named in the error.
1854
+ * @returns The manifest with every attribute entry applied.
1855
+ * @throws {Error} `[native]` when an attribute is to be set and the main activity cannot
1856
+ * be told apart.
1857
+ * @example
1858
+ * ```ts
1859
+ * applyManifestEntries('<activity android:name=".Main">\n</activity>', orientationManifest("portrait"), "AndroidManifest.xml");
1860
+ * // '<activity android:screenOrientation="portrait" android:name=".Main">\n</activity>'
1861
+ * ```
1862
+ */
1863
+ function applyManifestEntries(existing, entries, manifestPath) {
1864
+ const attributes = entries.filter((entry) => entry.kind === "activity-attribute");
1865
+ if (attributes.length === 0) return existing;
1866
+ const activity = mainActivity(locateActivities(existing));
1867
+ if (!activity) {
1868
+ if (attributes.every((attribute) => attribute.value === void 0)) return existing;
1869
+ throw mainActivityError(manifestPath);
1870
+ }
1871
+ let tag = existing.slice(activity.start, activity.end);
1872
+ for (const attribute of attributes) tag = applyAttribute(tag, attribute);
1873
+ return `${existing.slice(0, activity.start)}${tag}${existing.slice(activity.end)}`;
1874
+ }
1875
+ /**
1876
+ * Patches the main activity of `gen/android/app/src/main/AndroidManifest.xml` with the
1877
+ * `activity-attribute` entries, through the write-if-changed writer. Idempotent: a second
1878
+ * pass reports the manifest unchanged. With no attribute entry there is nothing to apply,
1879
+ * and the manifest is not even read.
1880
+ *
1881
+ * @param projectDirectory - The Tauri project root.
1882
+ * @param genDirectory - The `src-tauri/gen/android` directory.
1883
+ * @param entries - The manifest entries to apply.
1884
+ * @returns The manifest path, patched or unchanged.
1885
+ * @throws {Error} `[native]` when the manifest is missing, or an attribute is to be set and
1886
+ * the manifest has no clear main activity.
1887
+ * @example
1888
+ * ```ts
1889
+ * // First pass on a manifest without the lock; a second pass lists it under `unchanged`.
1890
+ * await patchAndroidManifest(".moku/tauri", ".moku/tauri/src-tauri/gen/android", orientationManifest("portrait"));
1891
+ * // { patched: [".moku/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml"], unchanged: [] }
1892
+ * ```
1893
+ */
1894
+ async function patchAndroidManifest(projectDirectory, genDirectory, entries) {
1895
+ if (!entries.some((entry) => entry.kind === "activity-attribute")) return {
1896
+ patched: [],
1897
+ unchanged: []
1898
+ };
1899
+ const manifestPath = node_path.default.join(genDirectory, ...MANIFEST_PATH_SEGMENTS);
1900
+ if (!(0, node_fs.existsSync)(manifestPath)) throw new Error(`[native] AndroidManifest.xml not found at ${manifestPath}.\n Re-run the mobile init pass (tauri android init) before patching the manifest.`);
1901
+ return await writeIfChanged(manifestPath, applyManifestEntries(await (0, node_fs_promises.readFile)(manifestPath, "utf8"), entries, manifestPath), projectDirectory) === "written" ? {
1902
+ patched: [manifestPath],
1903
+ unchanged: []
1904
+ } : {
1905
+ patched: [],
1906
+ unchanged: [manifestPath]
1907
+ };
1908
+ }
1909
+ //#endregion
1492
1910
  //#region src/plugins/project/mobile/files.ts
1493
1911
  /**
1494
1912
  * @file project plugin — the ONE owner of "which generated files a mobile patch pass may
1495
1913
  * touch". Both iOS patches (the runner-command rewrite and the Xcode build-settings patch)
1496
1914
  * read the same list from here, so neither can drift into a file the other does not know
1497
1915
  * about — and neither ever descends into `gen/apple/build` or `gen/android/build`, which
1498
- * belong to the toolchain.
1916
+ * belong to the toolchain. The Android status bar patch finds its MainActivity.kt here too.
1499
1917
  */
1500
1918
  /** Source extensions that can carry the Android runner command. */
1501
1919
  const ANDROID_SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
@@ -1503,6 +1921,15 @@ const ANDROID_SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
1503
1921
  ".kts",
1504
1922
  ".gradle"
1505
1923
  ]);
1924
+ /** The Kotlin file `tauri android init` writes the app's activity into. */
1925
+ const MAIN_ACTIVITY_FILE = "MainActivity.kt";
1926
+ /** Where `tauri android init` writes the app's Kotlin sources, below `gen/android`. */
1927
+ const ANDROID_JAVA_SEGMENTS = [
1928
+ "app",
1929
+ "src",
1930
+ "main",
1931
+ "java"
1932
+ ];
1506
1933
  /** Derived directories a patch scan never descends into — the toolchain owns them. */
1507
1934
  const SKIPPED_DIRECTORIES = /* @__PURE__ */ new Set([
1508
1935
  "build",
@@ -1573,6 +2000,186 @@ async function androidPatchFiles(genDirectory) {
1573
2000
  const gradleFiles = [node_path.default.join(genDirectory, "build.gradle.kts"), node_path.default.join(genDirectory, "app", "build.gradle.kts")].filter((file) => (0, node_fs.existsSync)(file));
1574
2001
  return [...buildSource, ...gradleFiles];
1575
2002
  }
2003
+ /**
2004
+ * Returns the directory `tauri android init` writes the app's Kotlin sources into. The
2005
+ * MainActivity.kt sits below it, in a folder per segment of the app identifier.
2006
+ *
2007
+ * @param genDirectory - The `src-tauri/gen/android` directory.
2008
+ * @returns The `app/src/main/java` directory of that tree.
2009
+ * @example
2010
+ * ```ts
2011
+ * androidJavaDirectory("/repo/.moku/tauri/src-tauri/gen/android");
2012
+ * // "/repo/.moku/tauri/src-tauri/gen/android/app/src/main/java"
2013
+ * ```
2014
+ */
2015
+ function androidJavaDirectory(genDirectory) {
2016
+ return node_path.default.join(genDirectory, ...ANDROID_JAVA_SEGMENTS);
2017
+ }
2018
+ /**
2019
+ * Lists every `MainActivity.kt` below `app/src/main/java`, sorted by path. Build output is
2020
+ * never listed. A generated tree holds exactly one; the caller decides what more or fewer
2021
+ * means.
2022
+ *
2023
+ * @param genDirectory - The `src-tauri/gen/android` directory.
2024
+ * @returns The MainActivity.kt paths found, possibly none.
2025
+ * @example
2026
+ * ```ts
2027
+ * await androidMainActivityFiles("/repo/.moku/tauri/src-tauri/gen/android");
2028
+ * // ["/repo/.moku/tauri/src-tauri/gen/android/app/src/main/java/com/acme/demo/MainActivity.kt"]
2029
+ * ```
2030
+ */
2031
+ async function androidMainActivityFiles(genDirectory) {
2032
+ return (await collectFiles(androidJavaDirectory(genDirectory), (name) => name === MAIN_ACTIVITY_FILE)).toSorted();
2033
+ }
2034
+ //#endregion
2035
+ //#region src/plugins/project/mobile/signing.ts
2036
+ /**
2037
+ * @file project plugin — the Android release-signing block the mobile patch pass keeps in
2038
+ * `gen/android/app/build.gradle.kts`. Only env-var NAMES are ever written to disk: Gradle
2039
+ * reads the passwords itself, at build time.
2040
+ */
2041
+ const SIGNING_START = "// MOKU-SIGNING-START";
2042
+ const SIGNING_END = "// MOKU-SIGNING-END";
2043
+ /**
2044
+ * Characters that change the meaning of a Kotlin string literal: a backslash starts an
2045
+ * escape, a double quote closes the literal, a dollar sign starts a template expression,
2046
+ * and a raw newline ends the line outright.
2047
+ */
2048
+ const KOTLIN_ESCAPES = [
2049
+ [/\\/g, String.raw`\\`],
2050
+ [/"/g, String.raw`\"`],
2051
+ [/\$/g, String.raw`\$`],
2052
+ [/\r/g, String.raw`\r`],
2053
+ [/\n/g, String.raw`\n`]
2054
+ ];
2055
+ /**
2056
+ * Escapes a value for use inside a double-quoted Kotlin string literal. Config values land
2057
+ * verbatim in `build.gradle.kts` — an unescaped `"` would close the literal and an
2058
+ * unescaped `$` would interpolate a Gradle expression, so every one of them is escaped
2059
+ * here rather than trusted.
2060
+ *
2061
+ * @param value - The raw config value (keystore path, key alias, env-var name).
2062
+ * @returns The value, safe to place between double quotes in Kotlin source.
2063
+ * @example
2064
+ * ```ts
2065
+ * kotlinString('re"lease$HOME'); // 're\\"lease\\$HOME'
2066
+ * ```
2067
+ */
2068
+ function kotlinString(value) {
2069
+ let escaped = value;
2070
+ for (const [pattern, replacement] of KOTLIN_ESCAPES) escaped = escaped.replace(pattern, replacement);
2071
+ return escaped;
2072
+ }
2073
+ /**
2074
+ * Renders the moku-managed Gradle signing block. Passwords are read by Gradle itself from
2075
+ * the environment at build time — only env-var NAMES are ever written to disk, per the
2076
+ * `SigningConfig` invariant. `keyPasswordEnv` falls back to `keystorePasswordEnv`, which
2077
+ * is the common single-password keystore. Every interpolated value goes through
2078
+ * {@link kotlinString}, so a path or alias can never close the literal it sits in.
2079
+ *
2080
+ * @param signing - The Android signing config slice, with a keystore path already present.
2081
+ * @param keystorePath - The configured keystore path.
2082
+ * @returns The sentinel-delimited Gradle block.
2083
+ * @example
2084
+ * ```ts
2085
+ * renderSigningBlock({ keyAlias: "release" }, "release.jks");
2086
+ * ```
2087
+ */
2088
+ function renderSigningBlock(signing, keystorePath) {
2089
+ const storePasswordEnvironment = signing.keystorePasswordEnv ?? "";
2090
+ const keyPasswordEnvironment = signing.keyPasswordEnv ?? storePasswordEnvironment;
2091
+ return [
2092
+ SIGNING_START,
2093
+ "android {",
2094
+ " signingConfigs {",
2095
+ " maybeCreate(\"release\").apply {",
2096
+ ` storeFile = file("${kotlinString(keystorePath)}")`,
2097
+ ` keyAlias = "${kotlinString(signing.keyAlias ?? "")}"`,
2098
+ ` storePassword = System.getenv("${kotlinString(storePasswordEnvironment)}")`,
2099
+ ` keyPassword = System.getenv("${kotlinString(keyPasswordEnvironment)}")`,
2100
+ " }",
2101
+ " }",
2102
+ " buildTypes {",
2103
+ " getByName(\"release\") {",
2104
+ " signingConfig = signingConfigs.getByName(\"release\")",
2105
+ " }",
2106
+ " }",
2107
+ "}",
2108
+ SIGNING_END
2109
+ ].join("\n");
2110
+ }
2111
+ /**
2112
+ * Strips the moku-managed signing block (and the blank line it was inserted with) from
2113
+ * Gradle content, leaving content that never carried one untouched.
2114
+ *
2115
+ * @param existing - The current `build.gradle.kts` content.
2116
+ * @returns The content without a moku signing block.
2117
+ * @example
2118
+ * ```ts
2119
+ * removeSigningBlock(patchedGradleKts);
2120
+ * ```
2121
+ */
2122
+ function removeSigningBlock(existing) {
2123
+ const startIndex = existing.indexOf(SIGNING_START);
2124
+ const endIndex = existing.indexOf(SIGNING_END);
2125
+ if (startIndex === -1 || endIndex === -1) return existing;
2126
+ let before = existing.slice(0, startIndex);
2127
+ while (before.endsWith("\n")) before = before.slice(0, -1);
2128
+ let after = existing.slice(endIndex + 19);
2129
+ while (after.startsWith("\n")) after = after.slice(1);
2130
+ return before.length > 0 ? `${before}\n${after}` : after;
2131
+ }
2132
+ /**
2133
+ * Idempotently inserts, replaces or removes the moku-managed signing block inside an
2134
+ * existing `app/build.gradle.kts`. Re-applying to already-patched content is a text-level
2135
+ * no-op; an unconfigured keystore REMOVES a block a previous build left behind, so
2136
+ * dropping `signing.android.keystorePath` really does return to unsigned builds.
2137
+ *
2138
+ * @param existing - The current `build.gradle.kts` content.
2139
+ * @param signing - The Android signing config slice (empty object when unconfigured).
2140
+ * @returns The patched content with exactly one signing block, or none when unconfigured.
2141
+ * @example
2142
+ * ```ts
2143
+ * applySigningBlock(gradleKts, { keystorePath: "release.jks", keyAlias: "release" });
2144
+ * ```
2145
+ */
2146
+ function applySigningBlock(existing, signing) {
2147
+ if (!signing.keystorePath) return removeSigningBlock(existing);
2148
+ const block = renderSigningBlock(signing, signing.keystorePath);
2149
+ const startIndex = existing.indexOf(SIGNING_START);
2150
+ const endIndex = existing.indexOf(SIGNING_END);
2151
+ if (startIndex === -1 || endIndex === -1) return `${existing}${existing.endsWith("\n") ? "" : "\n"}\n${block}\n`;
2152
+ return `${existing.slice(0, startIndex)}${block}${existing.slice(endIndex + 19)}`;
2153
+ }
2154
+ /**
2155
+ * Patches Android release signing into `app/build.gradle.kts`, and clears the legacy
2156
+ * `keystore.properties` a previous version of this plugin wrote. Signing now lives in
2157
+ * Gradle only, so nothing ever re-creates that file.
2158
+ *
2159
+ * @param projectDirectory - The Tauri project root.
2160
+ * @param genDirectory - The `src-tauri/gen/android` directory.
2161
+ * @param signing - The Android signing config slice (empty object when unconfigured).
2162
+ * @returns The paths patched vs. left unchanged.
2163
+ * @example
2164
+ * ```ts
2165
+ * await patchAndroidSigning(projectDir, genDir, { keystorePath: "release.jks" });
2166
+ * ```
2167
+ */
2168
+ async function patchAndroidSigning(projectDirectory, genDirectory, signing) {
2169
+ const patched = [];
2170
+ const unchanged = [];
2171
+ const buildGradlePath = node_path.default.join(genDirectory, "app", "build.gradle.kts");
2172
+ (await writeIfChanged(buildGradlePath, applySigningBlock(await (0, node_fs_promises.readFile)(buildGradlePath, "utf8"), signing), projectDirectory) === "written" ? patched : unchanged).push(buildGradlePath);
2173
+ const keystorePropertiesPath = node_path.default.join(genDirectory, "keystore.properties");
2174
+ if (!signing.keystorePath && (0, node_fs.existsSync)(keystorePropertiesPath)) {
2175
+ await (0, node_fs_promises.rm)(keystorePropertiesPath, { force: true });
2176
+ patched.push(keystorePropertiesPath);
2177
+ }
2178
+ return {
2179
+ patched,
2180
+ unchanged
2181
+ };
2182
+ }
1576
2183
  //#endregion
1577
2184
  //#region src/plugins/project/mobile/runner.ts
1578
2185
  /**
@@ -1581,6 +2188,11 @@ async function androidPatchFiles(genDirectory) {
1581
2188
  * generated Xcode/Android-Studio build phase, and none of those resolve inside those IDEs —
1582
2189
  * so an unpatched tree fails on its first build phase. Every occurrence becomes the
1583
2190
  * absolute `<node> <tauri.js>` pair the tauri plugin itself spawns with.
2191
+ *
2192
+ * Two shapes carry the runner. Xcode and older Android sources hold ONE command string
2193
+ * (`node tauri android android-studio-script`). The Android `BuildTask.kt` holds it as Kotlin
2194
+ * code instead: `val executable = """node""";` plus
2195
+ * `listOf("tauri", "android", "android-studio-script")`.
1584
2196
  */
1585
2197
  /** `tauri ios init` bakes `<detected-runner> ios xcode-script …` into the Xcode project. */
1586
2198
  const IOS_RUNNER_VERB = "ios xcode-script";
@@ -1599,16 +2211,47 @@ const WORD_SEPARATOR = String.raw`[ \t]+`;
1599
2211
  const WORD_BOUNDARY = String.raw`\b`;
1600
2212
  /** The already-patched form: the `<node> <tauri.js>` pair, each word quoted. */
1601
2213
  const ABSOLUTE_RUNNER_PAIR = `${QUOTED_RUNNER_WORD}${WORD_SEPARATOR}${QUOTED_RUNNER_WORD}`;
2214
+ /** Binaries Tauri may have detected the CLI behind, optionally through an absolute path. */
2215
+ const RUNNER_BINARIES = "node|bunx|bun|npx|yarn|pnpm|cargo";
2216
+ /**
2217
+ * The optional directory a detected runner is path-qualified with (`/opt/homebrew/bin/`).
2218
+ * It never contains a quote or a backslash: those belong to the string literal around the
2219
+ * command (`shellScript = "…`, a Kotlin `"…"`), and eating the opening quote leaves a
2220
+ * pbxproj Xcode refuses to open.
2221
+ */
2222
+ const RUNNER_PATH_PREFIX = String.raw`(?:[^\s"\\]*/)?`;
1602
2223
  /**
1603
2224
  * Every runner shape `tauri ios|android init` bakes in: `<binary> tauri`, npm's
1604
2225
  * `npm run tauri --` form, or a bare `tauri` — each optionally path-qualified. Longest
1605
2226
  * alternative first, so `npm run tauri --` is never truncated to its trailing `tauri`.
1606
2227
  */
1607
- const PACKAGE_RUNNER = String.raw`(?:\S*/)?npm run tauri --|(?:\S*/)?(?:${"node|bunx|bun|npx|yarn|pnpm|cargo"}) tauri|(?:\S*/)?tauri`;
2228
+ const PACKAGE_RUNNER = [
2229
+ `${RUNNER_PATH_PREFIX}npm run tauri --`,
2230
+ `${RUNNER_PATH_PREFIX}(?:${RUNNER_BINARIES}) tauri`,
2231
+ `${RUNNER_PATH_PREFIX}tauri`
2232
+ ].join("|");
1608
2233
  /** Characters that would break out of the double-quoted shell word a runner path lands in. */
1609
2234
  const SHELL_METACHARACTER_PATTERN = /[\\"$`]/g;
1610
2235
  /** A line break inside a runner path would split the generated build phase into two commands. */
1611
2236
  const LINE_BREAK_PATTERN = /[\n\r]/;
2237
+ /**
2238
+ * Characters a raw Kotlin string (`"""…"""`) cannot hold as they are. A raw string has no
2239
+ * backslash escapes, so `$` (a template) and `"` (part of the closing `"""`) are written as
2240
+ * `${'$'}` / `${'"'}` templates. A backslash is literal there and stays as it is.
2241
+ */
2242
+ const KOTLIN_RAW_STRING_SPECIAL_PATTERN = /["$]/g;
2243
+ /** The Android verb as `BuildTask.kt` passes it: two separate `listOf` arguments. */
2244
+ const KOTLIN_VERB_ARGUMENTS = String.raw`"android"\s*,\s*"android-studio-script"`;
2245
+ /** One plain Kotlin string literal on one line, backslash escapes included. */
2246
+ const KOTLIN_STRING_LITERAL = String.raw`"(?:[^"\\\n]|\\.)*"`;
2247
+ /**
2248
+ * The runner arguments of the `BuildTask.kt` `listOf(…)`: every string literal before the
2249
+ * verb pair (`"tauri"`, npm's `"run", "--", "tauri"`, an already-patched `"<tauri.js>"`).
2250
+ * Group 1 is the `listOf(` opener, kept as it is.
2251
+ */
2252
+ const KOTLIN_RUNNER_ARGUMENTS = String.raw`(listOf\(\s*)(?:${KOTLIN_STRING_LITERAL}\s*,\s*)*?(?=${KOTLIN_VERB_ARGUMENTS})`;
2253
+ /** The raw-string body of `val executable = """…"""`. Group 1 is everything up to the body. */
2254
+ const KOTLIN_EXECUTABLE = String.raw`(\bval\s+executable\s*=\s*""")[^\n]*?(?=""")`;
1612
2255
  /** Regex metacharacters, escaped before a caller-supplied verb is embedded in a pattern. */
1613
2256
  const REGEX_METACHARACTER_PATTERN = /[.*+?^${}()|[\]\\]/g;
1614
2257
  /**
@@ -1700,10 +2343,96 @@ function unknownRunnerError(verb, filePath) {
1700
2343
  * ```
1701
2344
  */
1702
2345
  function escapeRunnerPath(value) {
1703
- if (LINE_BREAK_PATTERN.test(value)) throw new Error(`[native] Refusing to write a runner path containing a line break: ${JSON.stringify(value)}.\n Install Node and the Tauri CLI under a path without line breaks, or set pluginConfigs.tauri.nodePath.`);
2346
+ assertSingleLine(value);
1704
2347
  return value.replaceAll(SHELL_METACHARACTER_PATTERN, (match) => `\\${match}`);
1705
2348
  }
1706
2349
  /**
2350
+ * Refuses a runner path with a line break. In a shell build phase it would split the command
2351
+ * in two; in a Kotlin literal it would end the line mid-string.
2352
+ *
2353
+ * @param value - The absolute path to check.
2354
+ * @throws {Error} `[native]` when the path contains a line break.
2355
+ * @example
2356
+ * ```ts
2357
+ * assertSingleLine("/opt/homebrew/bin/node"); // passes
2358
+ * ```
2359
+ */
2360
+ function assertSingleLine(value) {
2361
+ if (!LINE_BREAK_PATTERN.test(value)) return;
2362
+ throw new Error(`[native] Refusing to write a runner path containing a line break: ${JSON.stringify(value)}.\n Install Node and the Tauri CLI under a path without line breaks, or set pluginConfigs.tauri.nodePath.`);
2363
+ }
2364
+ /**
2365
+ * Escapes one runner path for a raw Kotlin string (`"""…"""`), which has no backslash
2366
+ * escapes: `$` and `"` become `${'$'}` / `${'"'}` templates, everything else stays as it is.
2367
+ *
2368
+ * @param value - The absolute path to escape.
2369
+ * @returns The raw string's body.
2370
+ * @throws {Error} `[native]` when the path contains a line break.
2371
+ * @example
2372
+ * ```ts
2373
+ * kotlinRawStringBody("/opt/node $HOME/bin/node"); // "/opt/node ${'$'}HOME/bin/node"
2374
+ * ```
2375
+ */
2376
+ function kotlinRawStringBody(value) {
2377
+ assertSingleLine(value);
2378
+ return value.replaceAll(KOTLIN_RAW_STRING_SPECIAL_PATTERN, (match) => `\${'${match}'}`);
2379
+ }
2380
+ /**
2381
+ * Tests whether a file passes the Android verb as Kotlin `listOf` arguments at all.
2382
+ *
2383
+ * @param content - The file content to search.
2384
+ * @returns Whether `"android", "android-studio-script"` appears.
2385
+ * @example
2386
+ * ```ts
2387
+ * mentionsKotlinVerb('listOf("tauri", "android", "android-studio-script")'); // true
2388
+ * ```
2389
+ */
2390
+ function mentionsKotlinVerb(content) {
2391
+ return new RegExp(KOTLIN_VERB_ARGUMENTS).test(content);
2392
+ }
2393
+ /**
2394
+ * Tests whether a file carries the full `BuildTask.kt` runner shape: the `listOf` arguments
2395
+ * AND the raw-string `executable`. Rewriting only one of them still leaves a broken runner.
2396
+ *
2397
+ * @param content - The file content to search.
2398
+ * @returns Whether both parts of the Kotlin runner are present.
2399
+ * @example
2400
+ * ```ts
2401
+ * hasKotlinRunner(buildTaskSource); // true for the tauri 2.12 template
2402
+ * ```
2403
+ */
2404
+ function hasKotlinRunner(content) {
2405
+ return new RegExp(KOTLIN_RUNNER_ARGUMENTS).test(content) && new RegExp(KOTLIN_EXECUTABLE).test(content);
2406
+ }
2407
+ /**
2408
+ * Rewrites the runner `tauri android init` bakes into `BuildTask.kt` as Kotlin code: the
2409
+ * raw-string `executable` becomes the absolute Node path, and the `listOf` arguments before
2410
+ * `"android", "android-studio-script"` become the one absolute `tauri.js` path. Gradle runs
2411
+ * the executable directly, with no shell, so each path is escaped for its Kotlin literal
2412
+ * only. Everything else is kept byte for byte. A file without that `listOf` is returned as
2413
+ * it is, executable included.
2414
+ *
2415
+ * @param existing - The file content to rewrite.
2416
+ * @param runner - The absolute Node and `tauri.js` paths.
2417
+ * @returns The rewritten content (a no-op once already rewritten onto this runner).
2418
+ * @throws {Error} `[native]` when a runner path contains a line break.
2419
+ * @example
2420
+ * ```ts
2421
+ * applyKotlinRunner('val executable = """node""";\nval args = listOf("tauri", "android", "android-studio-script");', {
2422
+ * nodePath: "/opt/homebrew/bin/node",
2423
+ * tauriJsPath: "/repo/node_modules/@tauri-apps/cli/tauri.js"
2424
+ * });
2425
+ * // 'val executable = """/opt/homebrew/bin/node""";\nval args = listOf("/repo/node_modules/@tauri-apps/cli/tauri.js", "android", "android-studio-script");'
2426
+ * ```
2427
+ */
2428
+ function applyKotlinRunner(existing, runner) {
2429
+ if (!new RegExp(KOTLIN_RUNNER_ARGUMENTS).test(existing)) return existing;
2430
+ const executable = kotlinRawStringBody(runner.nodePath);
2431
+ assertSingleLine(runner.tauriJsPath);
2432
+ const tauriJsArgument = `"${kotlinString(runner.tauriJsPath)}", `;
2433
+ return existing.replaceAll(new RegExp(KOTLIN_EXECUTABLE, "g"), (_match, open) => open + executable).replaceAll(new RegExp(KOTLIN_RUNNER_ARGUMENTS, "g"), (_match, open) => open + tauriJsArgument);
2434
+ }
2435
+ /**
1707
2436
  * Rewrites the runner Tauri baked into a generated build phase into an absolute
1708
2437
  * `<node> <tauri.js> <verb>` invocation. Only the runner-shaped token run directly before
1709
2438
  * the verb is replaced — anything else on the line (indentation, a `script:` key, a
@@ -1744,12 +2473,54 @@ function quoteFor(filePath) {
1744
2473
  return filePath.endsWith(".yml") ? "\"" : ESCAPED_QUOTE;
1745
2474
  }
1746
2475
  /**
2476
+ * Tests whether every runner a file carries is one this rewrite recognizes. A file that
2477
+ * never mentions the verb passes: it has no runner to rewrite.
2478
+ *
2479
+ * @param content - The file content to check.
2480
+ * @param verb - The Tauri verb the build phase invokes.
2481
+ * @returns Whether the rewrite can patch the file completely.
2482
+ * @example
2483
+ * ```ts
2484
+ * isRecognizedRunner('val command = "deno task tauri-cli android android-studio-script"', "android android-studio-script"); // false
2485
+ * ```
2486
+ */
2487
+ function isRecognizedRunner(content, verb) {
2488
+ if (mentionsRunnerVerb(content, verb) && !hasRunnerCommand(content, verb)) return false;
2489
+ return !(verb === ANDROID_RUNNER_VERB && mentionsKotlinVerb(content)) || hasKotlinRunner(content);
2490
+ }
2491
+ /**
2492
+ * Rewrites every runner shape a platform's file may carry: the one-string command, and on
2493
+ * Android also the Kotlin `BuildTask.kt` shape.
2494
+ *
2495
+ * @param existing - The file content to rewrite.
2496
+ * @param filePath - The file being patched, which picks the quote form.
2497
+ * @param options - How to rewrite the command.
2498
+ * @param options.runner - The absolute Node and `tauri.js` paths.
2499
+ * @param options.verb - The Tauri verb the build phase invokes.
2500
+ * @returns The rewritten content.
2501
+ * @example
2502
+ * ```ts
2503
+ * rewriteRunner(buildTaskSource, buildTaskPath, { runner, verb: "android android-studio-script" });
2504
+ * ```
2505
+ */
2506
+ function rewriteRunner(existing, filePath, options) {
2507
+ const { runner, verb } = options;
2508
+ const rewritten = applyRunnerCommand(existing, {
2509
+ runner,
2510
+ verb,
2511
+ quote: quoteFor(filePath)
2512
+ });
2513
+ if (verb !== ANDROID_RUNNER_VERB) return rewritten;
2514
+ return applyKotlinRunner(rewritten, runner);
2515
+ }
2516
+ /**
1747
2517
  * Applies the runner rewrite to every candidate file for a platform, reporting which
1748
2518
  * files actually changed. A second pass rewrites the absolute pair onto itself and
1749
2519
  * reports everything unchanged.
1750
2520
  *
1751
2521
  * A file that invokes the verb but carries a runner shape this rewrite does not recognize
1752
- * is an ERROR, not an "unchanged" file: Tauri baked in a command that will not resolve
2522
+ * (on Android also: a `listOf(…, "android", "android-studio-script")` without the
2523
+ * `val executable = """…"""` beside it) is an ERROR, not an "unchanged" file: Tauri baked in a command that will not resolve
1753
2524
  * inside Xcode/Android Studio, and reporting success there means the failure surfaces much
1754
2525
  * later, as an opaque build-phase exit. A file that never mentions the verb is simply
1755
2526
  * unchanged.
@@ -1773,11 +2544,10 @@ async function patchRunner(projectDirectory, genDirectory, opts) {
1773
2544
  const unchanged = [];
1774
2545
  for (const file of files) {
1775
2546
  const existing = await (0, node_fs_promises.readFile)(file, "utf8");
1776
- if (mentionsRunnerVerb(existing, verb) && !hasRunnerCommand(existing, verb)) throw unknownRunnerError(verb, file);
1777
- (await writeIfChanged(file, applyRunnerCommand(existing, {
2547
+ if (!isRecognizedRunner(existing, verb)) throw unknownRunnerError(verb, file);
2548
+ (await writeIfChanged(file, rewriteRunner(existing, file, {
1778
2549
  runner: opts.runner,
1779
- verb,
1780
- quote: quoteFor(file)
2550
+ verb
1781
2551
  }), projectDirectory) === "written" ? patched : unchanged).push(file);
1782
2552
  }
1783
2553
  return {
@@ -1786,152 +2556,268 @@ async function patchRunner(projectDirectory, genDirectory, opts) {
1786
2556
  };
1787
2557
  }
1788
2558
  //#endregion
1789
- //#region src/plugins/project/mobile/signing.ts
2559
+ //#region src/plugins/project/mobile/system-bars.ts
2560
+ /**
2561
+ * @file project plugin — the Android system bar patch. The generated MainActivity.kt
2562
+ * calls `enableEdgeToEdge()`, whose default `SystemBarStyle.auto` picks the status bar
2563
+ * icon colour from the SYSTEM night mode, not from the app. A dark app on a light-mode
2564
+ * phone then gets dark icons on a dark page. When `app.backgroundColor` is set, this patch
2565
+ * rewrites that one call so the icons follow the colour's luminance instead.
2566
+ *
2567
+ * The transform is a pure text function: only the call and the two imports it needs
2568
+ * change, every other byte (line endings included) survives, a second pass is a no-op, and
2569
+ * unsetting the colour restores the generated call.
2570
+ */
2571
+ /**
2572
+ * A background whose relative luminance is below this is dark, so it gets light icons.
2573
+ * Where white and black icons have equal WCAG contrast: sqrt(1.05 * 0.05) - 0.05.
2574
+ */
2575
+ const DARK_LUMINANCE_THRESHOLD = .179;
2576
+ /** `#rrggbb` or `#rrggbbaa`, the three colour channels captured; alpha is ignored. */
2577
+ const HEX_CHANNELS_PATTERN = /^#([\da-f]{2})([\da-f]{2})([\da-f]{2})(?:[\da-f]{2})?$/i;
2578
+ /** The Rec. 709 weights of red, green and blue in relative luminance. */
2579
+ const LUMINANCE_WEIGHTS = [
2580
+ .2126,
2581
+ .7152,
2582
+ .0722
2583
+ ];
2584
+ /** What marks the generated activity: it is the file that turns edge-to-edge on. */
2585
+ const EDGE_TO_EDGE_CALL = "enableEdgeToEdge(";
2586
+ /** The call exactly as `tauri android init` (cli 2.12) writes it. */
2587
+ const BARE_CALL = "enableEdgeToEdge()";
1790
2588
  /**
1791
- * @file project plugin — the Android release-signing block the mobile patch pass keeps in
1792
- * `gen/android/app/build.gradle.kts`. Only env-var NAMES are ever written to disk: Gradle
1793
- * reads the passwords itself, at build time.
2589
+ * Builds the styled call: both bars get the same style, with a transparent scrim so the
2590
+ * page still draws behind them.
2591
+ *
2592
+ * @param style - The Kotlin `SystemBarStyle` expression for both bars.
2593
+ * @returns The `enableEdgeToEdge(...)` call.
2594
+ * @example
2595
+ * ```ts
2596
+ * styledCall("SystemBarStyle.dark(Color.TRANSPARENT)");
2597
+ * // "enableEdgeToEdge(statusBarStyle = SystemBarStyle.dark(Color.TRANSPARENT), navigationBarStyle = SystemBarStyle.dark(Color.TRANSPARENT))"
2598
+ * ```
1794
2599
  */
1795
- const SIGNING_START = "// MOKU-SIGNING-START";
1796
- const SIGNING_END = "// MOKU-SIGNING-END";
2600
+ function styledCall(style) {
2601
+ return `enableEdgeToEdge(statusBarStyle = ${style}, navigationBarStyle = ${style})`;
2602
+ }
2603
+ /** The call this patch writes per tone: `dark()` draws light icons, `light()` dark ones. */
2604
+ const STYLED_CALLS = {
2605
+ dark: styledCall("SystemBarStyle.dark(Color.TRANSPARENT)"),
2606
+ light: styledCall("SystemBarStyle.light(Color.TRANSPARENT, Color.TRANSPARENT)")
2607
+ };
2608
+ /** Every call this patch may replace: the generated one and its own two rewrites. */
2609
+ const KNOWN_CALLS = [
2610
+ BARE_CALL,
2611
+ STYLED_CALLS.dark,
2612
+ STYLED_CALLS.light
2613
+ ];
2614
+ /** The imports the styled call needs, in the order they are added after the last import. */
2615
+ const STYLE_IMPORTS = [{
2616
+ line: "import androidx.activity.SystemBarStyle",
2617
+ usage: /\bSystemBarStyle\b/
2618
+ }, {
2619
+ line: "import android.graphics.Color",
2620
+ usage: /\bColor\b/
2621
+ }];
2622
+ /** One Kotlin import line, without its line ending. */
2623
+ const IMPORT_LINE_PATTERN = /^import [^\r\n]*/gm;
2624
+ /** The carriage return a CRLF line keeps after a split on `\n`. */
2625
+ const TRAILING_CARRIAGE_RETURN = /\r$/;
1797
2626
  /**
1798
- * Characters that change the meaning of a Kotlin string literal: a backslash starts an
1799
- * escape, a double quote closes the literal, a dollar sign starts a template expression,
1800
- * and a raw newline ends the line outright.
2627
+ * Builds the `[native]` error for a MainActivity.kt whose edge-to-edge call this patch
2628
+ * does not recognise.
2629
+ *
2630
+ * @param filePath - The MainActivity.kt that was read.
2631
+ * @returns A formatted `[native] ...` error.
2632
+ * @example
2633
+ * ```ts
2634
+ * throw unknownCallError("/repo/.moku/tauri/src-tauri/gen/android/app/src/main/java/com/acme/demo/MainActivity.kt");
2635
+ * ```
1801
2636
  */
1802
- const KOTLIN_ESCAPES = [
1803
- [/\\/g, String.raw`\\`],
1804
- [/"/g, String.raw`\"`],
1805
- [/\$/g, String.raw`\$`],
1806
- [/\r/g, String.raw`\r`],
1807
- [/\n/g, String.raw`\n`]
1808
- ];
2637
+ function unknownCallError(filePath) {
2638
+ return /* @__PURE__ */ new Error(`[native] The enableEdgeToEdge() call in ${filePath} is not the one tauri android init generates.\n Re-run the mobile init pass (tauri android init) to restore it, or unset app.backgroundColor.`);
2639
+ }
1809
2640
  /**
1810
- * Escapes a value for use inside a double-quoted Kotlin string literal. Config values land
1811
- * verbatim in `build.gradle.kts` — an unescaped `"` would close the literal and an
1812
- * unescaped `$` would interpolate a Gradle expression, so every one of them is escaped
1813
- * here rather than trusted.
2641
+ * Builds the `[native]` error for a MainActivity.kt with no import line, so the system bar
2642
+ * imports have no place to go.
1814
2643
  *
1815
- * @param value - The raw config value (keystore path, key alias, env-var name).
1816
- * @returns The value, safe to place between double quotes in Kotlin source.
2644
+ * @param filePath - The MainActivity.kt that was read.
2645
+ * @returns A formatted `[native] ...` error.
1817
2646
  * @example
1818
2647
  * ```ts
1819
- * kotlinString('re"lease$HOME'); // 're\\"lease\\$HOME'
2648
+ * throw noImportLineError("/repo/.moku/tauri/src-tauri/gen/android/app/src/main/java/com/acme/demo/MainActivity.kt");
1820
2649
  * ```
1821
2650
  */
1822
- function kotlinString(value) {
1823
- let escaped = value;
1824
- for (const [pattern, replacement] of KOTLIN_ESCAPES) escaped = escaped.replace(pattern, replacement);
1825
- return escaped;
2651
+ function noImportLineError(filePath) {
2652
+ return /* @__PURE__ */ new Error(`[native] ${filePath} has no import line to add the system bar imports after.\n Re-run the mobile init pass (tauri android init), or unset app.backgroundColor.`);
1826
2653
  }
1827
2654
  /**
1828
- * Renders the moku-managed Gradle signing block. Passwords are read by Gradle itself from
1829
- * the environment at build time — only env-var NAMES are ever written to disk, per the
1830
- * `SigningConfig` invariant. `keyPasswordEnv` falls back to `keystorePasswordEnv`, which
1831
- * is the common single-password keystore. Every interpolated value goes through
1832
- * {@link kotlinString}, so a path or alias can never close the literal it sits in.
2655
+ * Builds the `[native]` error for a gen tree without exactly one MainActivity.kt that calls
2656
+ * `enableEdgeToEdge()`.
1833
2657
  *
1834
- * @param signing - The Android signing config slice, with a keystore path already present.
1835
- * @param keystorePath - The configured keystore path.
1836
- * @returns The sentinel-delimited Gradle block.
2658
+ * @param javaDirectory - The `app/src/main/java` directory that was searched.
2659
+ * @param found - The candidates found, sorted; empty when there were none.
2660
+ * @returns A formatted `[native] ...` error.
1837
2661
  * @example
1838
2662
  * ```ts
1839
- * renderSigningBlock({ keyAlias: "release" }, "release.jks");
2663
+ * throw notOneActivityError("/repo/.moku/tauri/src-tauri/gen/android/app/src/main/java", []);
1840
2664
  * ```
1841
2665
  */
1842
- function renderSigningBlock(signing, keystorePath) {
1843
- const storePasswordEnvironment = signing.keystorePasswordEnv ?? "";
1844
- const keyPasswordEnvironment = signing.keyPasswordEnv ?? storePasswordEnvironment;
1845
- return [
1846
- SIGNING_START,
1847
- "android {",
1848
- " signingConfigs {",
1849
- " maybeCreate(\"release\").apply {",
1850
- ` storeFile = file("${kotlinString(keystorePath)}")`,
1851
- ` keyAlias = "${kotlinString(signing.keyAlias ?? "")}"`,
1852
- ` storePassword = System.getenv("${kotlinString(storePasswordEnvironment)}")`,
1853
- ` keyPassword = System.getenv("${kotlinString(keyPasswordEnvironment)}")`,
1854
- " }",
1855
- " }",
1856
- " buildTypes {",
1857
- " getByName(\"release\") {",
1858
- " signingConfig = signingConfigs.getByName(\"release\")",
1859
- " }",
1860
- " }",
1861
- "}",
1862
- SIGNING_END
1863
- ].join("\n");
2666
+ function notOneActivityError(javaDirectory, found) {
2667
+ if (found.length === 0) return /* @__PURE__ */ new Error(`[native] Could not find the MainActivity.kt that calls enableEdgeToEdge() under ${javaDirectory}.\n Re-run the mobile init pass (tauri android init), or unset app.backgroundColor.`);
2668
+ return /* @__PURE__ */ new Error(`[native] Found ${found.length} MainActivity.kt files that call enableEdgeToEdge() under ${javaDirectory}: ${found.join(", ")}.\n Keep the one tauri android init generated, or re-run the mobile init pass (tauri android init).`);
1864
2669
  }
1865
2670
  /**
1866
- * Strips the moku-managed signing block (and the blank line it was inserted with) from
1867
- * Gradle content, leaving content that never carried one untouched.
2671
+ * Linearises one sRGB channel, the transfer curve relative luminance is defined on.
1868
2672
  *
1869
- * @param existing - The current `build.gradle.kts` content.
1870
- * @returns The content without a moku signing block.
2673
+ * @param hexPair - The channel as two hex digits.
2674
+ * @returns The linear channel value, 0 to 1.
1871
2675
  * @example
1872
2676
  * ```ts
1873
- * removeSigningBlock(patchedGradleKts);
2677
+ * linearChannel("ff"); // 1
2678
+ * linearChannel("00"); // 0
1874
2679
  * ```
1875
2680
  */
1876
- function removeSigningBlock(existing) {
1877
- const startIndex = existing.indexOf(SIGNING_START);
1878
- const endIndex = existing.indexOf(SIGNING_END);
1879
- if (startIndex === -1 || endIndex === -1) return existing;
1880
- let before = existing.slice(0, startIndex);
1881
- while (before.endsWith("\n")) before = before.slice(0, -1);
1882
- let after = existing.slice(endIndex + 19);
1883
- while (after.startsWith("\n")) after = after.slice(1);
1884
- return before.length > 0 ? `${before}\n${after}` : after;
2681
+ function linearChannel(hexPair) {
2682
+ const encoded = Number.parseInt(hexPair, 16) / 255;
2683
+ return encoded <= .04045 ? encoded / 12.92 : ((encoded + .055) / 1.055) ** 2.4;
1885
2684
  }
1886
2685
  /**
1887
- * Idempotently inserts, replaces or removes the moku-managed signing block inside an
1888
- * existing `app/build.gradle.kts`. Re-applying to already-patched content is a text-level
1889
- * no-op; an unconfigured keystore REMOVES a block a previous build left behind, so
1890
- * dropping `signing.android.keystorePath` really does return to unsigned builds.
2686
+ * Tells a dark background from a light one by its relative luminance (WCAG), alpha
2687
+ * ignored. Below {@link DARK_LUMINANCE_THRESHOLD} the background is dark.
1891
2688
  *
1892
- * @param existing - The current `build.gradle.kts` content.
1893
- * @param signing - The Android signing config slice (empty object when unconfigured).
1894
- * @returns The patched content with exactly one signing block, or none when unconfigured.
2689
+ * @param colour - The `app.backgroundColor` value, `#rrggbb` or `#rrggbbaa`.
2690
+ * @returns `"dark"` when the background wants light icons, `"light"` when it wants dark ones.
2691
+ * @throws {Error} `[native]` when the value is not a hex colour.
1895
2692
  * @example
1896
2693
  * ```ts
1897
- * applySigningBlock(gradleKts, { keystorePath: "release.jks", keyAlias: "release" });
2694
+ * backgroundTone("#10161d"); // "dark"
2695
+ * backgroundTone("#ffffffff"); // "light"
1898
2696
  * ```
1899
2697
  */
1900
- function applySigningBlock(existing, signing) {
1901
- if (!signing.keystorePath) return removeSigningBlock(existing);
1902
- const block = renderSigningBlock(signing, signing.keystorePath);
1903
- const startIndex = existing.indexOf(SIGNING_START);
1904
- const endIndex = existing.indexOf(SIGNING_END);
1905
- if (startIndex === -1 || endIndex === -1) return `${existing}${existing.endsWith("\n") ? "" : "\n"}\n${block}\n`;
1906
- return `${existing.slice(0, startIndex)}${block}${existing.slice(endIndex + 19)}`;
2698
+ function backgroundTone(colour) {
2699
+ const channels = HEX_CHANNELS_PATTERN.exec(colour)?.slice(1);
2700
+ if (!channels) throw new Error(`[native] app.backgroundColor "${colour}" is not a valid colour.\n Use a hex colour such as "#10161d".`);
2701
+ return channels.reduce((sum, channel, index) => sum + (LUMINANCE_WEIGHTS[index] ?? 0) * linearChannel(channel), 0) < DARK_LUMINANCE_THRESHOLD ? "dark" : "light";
1907
2702
  }
1908
2703
  /**
1909
- * Patches Android release signing into `app/build.gradle.kts`, and clears the legacy
1910
- * `keystore.properties` a previous version of this plugin wrote. Signing now lives in
1911
- * Gradle only, so nothing ever re-creates that file.
2704
+ * Adds the imports the styled call needs, each on its own line after the last import, in
2705
+ * the file's own line ending. An import already present is not added again.
2706
+ *
2707
+ * @param source - The MainActivity.kt content, call already styled.
2708
+ * @param filePath - The MainActivity.kt path, named in the error.
2709
+ * @returns The content with both imports present.
2710
+ * @throws {Error} `[native]` when the file has no import line to add them after.
2711
+ * @example
2712
+ * ```ts
2713
+ * addStyleImports("import android.os.Bundle\n\nclass A", "MainActivity.kt");
2714
+ * // "import android.os.Bundle\nimport androidx.activity.SystemBarStyle\nimport android.graphics.Color\n\nclass A"
2715
+ * ```
2716
+ */
2717
+ function addStyleImports(source, filePath) {
2718
+ const lineEnding = source.includes("\r\n") ? "\r\n" : "\n";
2719
+ let result = source;
2720
+ for (const styleImport of STYLE_IMPORTS) {
2721
+ if (result.split(/\r?\n/).includes(styleImport.line)) continue;
2722
+ const lastImport = [...result.matchAll(IMPORT_LINE_PATTERN)].at(-1);
2723
+ if (!lastImport) throw noImportLineError(filePath);
2724
+ const end = lastImport.index + lastImport[0].length;
2725
+ result = `${result.slice(0, end)}${lineEnding}${styleImport.line}${result.slice(end)}`;
2726
+ }
2727
+ return result;
2728
+ }
2729
+ /**
2730
+ * Removes the style imports nothing uses any more, each with its own line. An import that
2731
+ * other code still uses stays, so a file that imported `Color` itself keeps it.
2732
+ *
2733
+ * @param source - The MainActivity.kt content, call already restored to bare.
2734
+ * @returns The content without the unused style imports.
2735
+ * @example
2736
+ * ```ts
2737
+ * removeUnusedStyleImports("import android.os.Bundle\nimport android.graphics.Color\n\nclass A");
2738
+ * // "import android.os.Bundle\n\nclass A"
2739
+ * ```
2740
+ */
2741
+ function removeUnusedStyleImports(source) {
2742
+ let lines = source.split("\n");
2743
+ for (const styleImport of STYLE_IMPORTS) {
2744
+ if (lines.filter((line) => !line.startsWith("import ")).some((line) => styleImport.usage.test(line))) continue;
2745
+ lines = lines.filter((line) => line.replace(TRAILING_CARRIAGE_RETURN, "") !== styleImport.line);
2746
+ }
2747
+ return lines.join("\n");
2748
+ }
2749
+ /**
2750
+ * Sets the system bar style of a MainActivity.kt. A tone writes the styled call and adds
2751
+ * its imports; no tone restores the bare generated call and drops the imports nothing else
2752
+ * uses. Only a call this patch knows is touched: the generated one, or one of its own
2753
+ * rewrites.
2754
+ *
2755
+ * @param source - The MainActivity.kt content.
2756
+ * @param tone - The background's tone, or undefined when `app.backgroundColor` is unset.
2757
+ * @param filePath - The MainActivity.kt path, named in the error.
2758
+ * @returns The content with the style applied.
2759
+ * @throws {Error} `[native]` when a tone is set and the call is not one this patch knows.
2760
+ * @example
2761
+ * ```ts
2762
+ * applySystemBarStyle("import androidx.activity.enableEdgeToEdge\n\nenableEdgeToEdge()\n", "dark", "MainActivity.kt");
2763
+ * // "import androidx.activity.enableEdgeToEdge\nimport androidx.activity.SystemBarStyle\nimport android.graphics.Color\n\n"
2764
+ * // + "enableEdgeToEdge(statusBarStyle = SystemBarStyle.dark(Color.TRANSPARENT), navigationBarStyle = SystemBarStyle.dark(Color.TRANSPARENT))\n"
2765
+ * ```
2766
+ */
2767
+ function applySystemBarStyle(source, tone, filePath) {
2768
+ if (!KNOWN_CALLS.some((call) => source.includes(call))) {
2769
+ if (tone === void 0) return source;
2770
+ throw unknownCallError(filePath);
2771
+ }
2772
+ const wanted = tone === void 0 ? BARE_CALL : STYLED_CALLS[tone];
2773
+ let result = source;
2774
+ for (const call of KNOWN_CALLS) result = result.replaceAll(call, () => wanted);
2775
+ return tone === void 0 ? removeUnusedStyleImports(result) : addStyleImports(result, filePath);
2776
+ }
2777
+ /**
2778
+ * Styles the Android system bars from `app.backgroundColor`, through the write-if-changed
2779
+ * writer. The target is the one MainActivity.kt below `gen/android/app/src/main/java` that
2780
+ * calls `enableEdgeToEdge()`. Without a colour a missing or ambiguous activity is left
2781
+ * alone, so an app that never set one keeps building; with one it is an error.
1912
2782
  *
1913
2783
  * @param projectDirectory - The Tauri project root.
1914
2784
  * @param genDirectory - The `src-tauri/gen/android` directory.
1915
- * @param signing - The Android signing config slice (empty object when unconfigured).
1916
- * @returns The paths patched vs. left unchanged.
2785
+ * @param backgroundColor - `app.backgroundColor`, or undefined when unset.
2786
+ * @returns The MainActivity.kt path, patched or unchanged; empty when there was none to touch.
2787
+ * @throws {Error} `[native]` when a colour is set and there is not exactly one MainActivity.kt
2788
+ * calling `enableEdgeToEdge()`, or its call is not one this patch knows.
1917
2789
  * @example
1918
2790
  * ```ts
1919
- * await patchAndroidSigning(projectDir, genDir, { keystorePath: "release.jks" });
2791
+ * // First pass on the generated activity; a second pass lists it under `unchanged`.
2792
+ * await patchAndroidSystemBars(".moku/tauri", ".moku/tauri/src-tauri/gen/android", "#10161d");
2793
+ * // { patched: [".moku/tauri/src-tauri/gen/android/app/src/main/java/com/acme/demo/MainActivity.kt"], unchanged: [] }
1920
2794
  * ```
1921
2795
  */
1922
- async function patchAndroidSigning(projectDirectory, genDirectory, signing) {
1923
- const patched = [];
1924
- const unchanged = [];
1925
- const buildGradlePath = node_path.default.join(genDirectory, "app", "build.gradle.kts");
1926
- (await writeIfChanged(buildGradlePath, applySigningBlock(await (0, node_fs_promises.readFile)(buildGradlePath, "utf8"), signing), projectDirectory) === "written" ? patched : unchanged).push(buildGradlePath);
1927
- const keystorePropertiesPath = node_path.default.join(genDirectory, "keystore.properties");
1928
- if (!signing.keystorePath && (0, node_fs.existsSync)(keystorePropertiesPath)) {
1929
- await (0, node_fs_promises.rm)(keystorePropertiesPath, { force: true });
1930
- patched.push(keystorePropertiesPath);
2796
+ async function patchAndroidSystemBars(projectDirectory, genDirectory, backgroundColor) {
2797
+ const tone = backgroundColor === void 0 ? void 0 : backgroundTone(backgroundColor);
2798
+ const activities = [];
2799
+ for (const file of await androidMainActivityFiles(genDirectory)) {
2800
+ const source = await (0, node_fs_promises.readFile)(file, "utf8");
2801
+ if (source.includes(EDGE_TO_EDGE_CALL)) activities.push({
2802
+ path: file,
2803
+ source
2804
+ });
1931
2805
  }
1932
- return {
1933
- patched,
1934
- unchanged
2806
+ const [activity] = activities;
2807
+ if (activities.length !== 1 || !activity) {
2808
+ if (tone === void 0) return {
2809
+ patched: [],
2810
+ unchanged: []
2811
+ };
2812
+ throw notOneActivityError(androidJavaDirectory(genDirectory), activities.map((candidate) => candidate.path));
2813
+ }
2814
+ const patchedSource = applySystemBarStyle(activity.source, tone, activity.path);
2815
+ return await writeIfChanged(activity.path, patchedSource, projectDirectory) === "written" ? {
2816
+ patched: [activity.path],
2817
+ unchanged: []
2818
+ } : {
2819
+ patched: [],
2820
+ unchanged: [activity.path]
1935
2821
  };
1936
2822
  }
1937
2823
  //#endregion
@@ -2253,7 +3139,9 @@ async function patchXcodeSettings(projectDirectory, genDirectory) {
2253
3139
  /**
2254
3140
  * @file project plugin — the post-init mobile patch pass: it decides WHICH patches a
2255
3141
  * platform needs and in which order. The patches themselves live next door, in
2256
- * `signing.ts` (the Android release-signing block), `runner.ts` (the Xcode /
3142
+ * `signing.ts` (the Android release-signing block), `manifest.ts` (the Android main
3143
+ * activity's attributes, such as the orientation lock), `system-bars.ts` (the Android
3144
+ * status bar icon style from `app.backgroundColor`), `runner.ts` (the Xcode /
2257
3145
  * Android-Studio runner command) and `xcode-settings.ts` (the iOS
2258
3146
  * entitlements-modification setting that makes a REBUILD work).
2259
3147
  */
@@ -2278,23 +3166,30 @@ function mergePatchResults(...results) {
2278
3166
  }
2279
3167
  /**
2280
3168
  * Deterministic, idempotent post-init patch pass over an existing complete gen/ tree.
2281
- * Android gets its release signing block; iOS gets the Xcode entitlements-modification
2282
- * setting (without it the SECOND build of the same tree fails); both platforms get the
2283
- * runner-command rewrite when the caller supplies a `runner` (omit it and the rewrite is
2284
- * skipped). iOS carries no mobile-permission plist mechanism in v1 (D-012), so signing is
2285
- * conf-only there.
3169
+ * Android gets, in this order, its release signing block, the main activity's manifest
3170
+ * attributes, the system bar style in MainActivity.kt, then the runner command. iOS gets
3171
+ * the Xcode entitlements-modification setting (without it the SECOND build of the same
3172
+ * tree fails), then the runner command. The runner rewrite runs only when the caller
3173
+ * supplies a `runner`. iOS takes no manifest entries and no background colour: its
3174
+ * orientation lock and signing travel through the generated `Info.ios.plist` sidecar and
3175
+ * tauri.conf.json, and its status bar adapts to the page on its own.
2286
3176
  *
2287
3177
  * @param projectDirectory - The Tauri project root.
2288
3178
  * @param opts - The mobile platform, and optionally the absolute Node/tauri.js runner pair.
2289
3179
  * @param signing - The full signing config (only `.android` is consulted).
2290
- * @returns The paths patched vs. left unchanged.
2291
- * @throws {Error} When the Android `gen/android` tree (or its `app/build.gradle.kts`) is missing.
3180
+ * @param manifest - Android manifest entries for the main activity (ignored on iOS).
3181
+ * @param backgroundColor - `app.backgroundColor`; the Android status bar icons follow it
3182
+ * (ignored on iOS).
3183
+ * @returns The paths patched vs. left unchanged, one merged report over every patch.
3184
+ * @throws {Error} When the Android `gen/android` tree (or its `app/build.gradle.kts`) is
3185
+ * missing, manifest entries meet a missing manifest or an unclear main activity, or a
3186
+ * background colour meets a tree without exactly one MainActivity.kt to style.
2292
3187
  * @example
2293
3188
  * ```ts
2294
- * await patchMobile("/repo/.moku/tauri", { target: "ios", runner }, {});
3189
+ * await patchMobile("/repo/.moku/tauri", { target: "android", runner }, {}, orientationManifest("portrait"), "#10161d");
2295
3190
  * ```
2296
3191
  */
2297
- async function patchMobile(projectDirectory, opts, signing) {
3192
+ async function patchMobile(projectDirectory, opts, signing, manifest = [], backgroundColor) {
2298
3193
  const genDirectory = genDirectoryPath(projectDirectory, opts.target);
2299
3194
  if (opts.target === "ios") {
2300
3195
  if (!(0, node_fs.existsSync)(genDirectory)) return {
@@ -2310,9 +3205,11 @@ async function patchMobile(projectDirectory, opts, signing) {
2310
3205
  }
2311
3206
  const buildGradlePath = node_path.default.join(genDirectory, "app", "build.gradle.kts");
2312
3207
  if (!(0, node_fs.existsSync)(genDirectory) || !(0, node_fs.existsSync)(buildGradlePath)) throw new Error(`[native] Android gen/ tree not found or incomplete at ${genDirectory}.\n Run the mobile init pass (tauri android init) before patching signing state.`);
2313
- const result = await patchAndroidSigning(projectDirectory, genDirectory, signing.android ?? {});
2314
- if (!opts.runner) return result;
2315
- return mergePatchResults(result, await patchRunner(projectDirectory, genDirectory, {
3208
+ const signingResult = await patchAndroidSigning(projectDirectory, genDirectory, signing.android ?? {});
3209
+ const manifestResult = await patchAndroidManifest(projectDirectory, genDirectory, manifest);
3210
+ const systemBarsResult = await patchAndroidSystemBars(projectDirectory, genDirectory, backgroundColor);
3211
+ if (!opts.runner) return mergePatchResults(signingResult, manifestResult, systemBarsResult);
3212
+ return mergePatchResults(signingResult, manifestResult, systemBarsResult, await patchRunner(projectDirectory, genDirectory, {
2316
3213
  target: opts.target,
2317
3214
  runner: opts.runner
2318
3215
  }));
@@ -2320,11 +3217,12 @@ async function patchMobile(projectDirectory, opts, signing) {
2320
3217
  //#endregion
2321
3218
  //#region src/plugins/project/registry.ts
2322
3219
  /**
2323
- * The five v1 capability registry rows (spike (a), Tauri 2.9.x source-verified 2026-07-03).
2324
- * Four rows are backed by a real official Tauri plugin (crate + npm package + Rust init);
2325
- * `tray` is a core Tauri CARGO FEATURE — it carries no crate, no npm package and no Rust
2326
- * init, only `cargoFeatures: ["tray-icon"]`, and its `confidence: "low"` flags that
2327
- * divergence from the other four.
3220
+ * The seven capability registry rows (the first five spike (a), Tauri 2.9.x
3221
+ * source-verified 2026-07-03; `back` and `haptics` against Tauri 2.12.1). Five rows are
3222
+ * backed by a real official Tauri plugin (crate + npm package + Rust init). `tray` is a
3223
+ * core Tauri CARGO FEATURE — it carries no crate, no npm package and no Rust init, only
3224
+ * `cargoFeatures: ["tray-icon"]`, and its `confidence: "low"` flags that divergence.
3225
+ * `back` is core permissions alone: its whole API ships in `@tauri-apps/api/app`.
2328
3226
  */
2329
3227
  const REGISTRY = [
2330
3228
  {
@@ -2415,6 +3313,30 @@ const REGISTRY = [
2415
3313
  "android"
2416
3314
  ],
2417
3315
  confidence: "high"
3316
+ },
3317
+ {
3318
+ name: "back",
3319
+ cargoFeatures: [],
3320
+ permissions: ["core:app:allow-exit"],
3321
+ platforms: ["android"],
3322
+ confidence: "high"
3323
+ },
3324
+ {
3325
+ name: "haptics",
3326
+ npmPackage: "@tauri-apps/plugin-haptics",
3327
+ crate: "tauri-plugin-haptics",
3328
+ crateRange: "^2",
3329
+ npmRange: "^2",
3330
+ rustInit: "tauri_plugin_haptics::init()",
3331
+ cargoFeatures: [],
3332
+ permissions: [
3333
+ "haptics:allow-impact-feedback",
3334
+ "haptics:allow-notification-feedback",
3335
+ "haptics:allow-selection-feedback",
3336
+ "haptics:allow-vibrate"
3337
+ ],
3338
+ platforms: ["ios", "android"],
3339
+ confidence: "high"
2418
3340
  }
2419
3341
  ];
2420
3342
  const KNOWN_NAMES = REGISTRY.map((row) => row.name);
@@ -2491,8 +3413,8 @@ function buildConfFragment(row, config) {
2491
3413
  }
2492
3414
  /**
2493
3415
  * Typed registry lookup — resolves a capability row against optional consumer config,
2494
- * producing the full packaging contribution (conf fragment + the future-mechanism
2495
- * sidecar/manifest seams, both empty for every v1 row).
3416
+ * producing the full packaging contribution (conf fragment + the sidecar/manifest seams,
3417
+ * both empty for every row today).
2496
3418
  *
2497
3419
  * @param name - A capability name known at compile time (`keyof CapabilityConfigMap`).
2498
3420
  * @param config - Optional per-capability packaging parameters.
@@ -2520,7 +3442,8 @@ function resolve(name, config) {
2520
3442
  * @returns A fresh copy of every registry row — callers can never mutate the registry.
2521
3443
  * @example
2522
3444
  * ```ts
2523
- * registryRows().map(row => row.name); // ["store", "notification", ...]
3445
+ * registryRows().map(row => row.name);
3446
+ * // ["store", "notification", "clipboard-manager", "tray", "deep-link", "back", "haptics"]
2524
3447
  * ```
2525
3448
  */
2526
3449
  function registryRows() {
@@ -2556,6 +3479,25 @@ function resolveConfiguredCapabilities(global, target) {
2556
3479
  return resolved;
2557
3480
  }
2558
3481
  /**
3482
+ * Collects what the Android main activity must carry: the `activity-attribute` entries of
3483
+ * every capability resolved for android, then the orientation lock. Orientation comes
3484
+ * last so it wins a clash, the same order the iOS sidecar merges in. It is always present:
3485
+ * an unset orientation asks for `android:screenOrientation` to be absent, which removes a
3486
+ * lock a previous build left in the gen/ tree.
3487
+ *
3488
+ * @param global - Frozen global framework config.
3489
+ * @returns The manifest entries for `patchMobile`'s Android pass.
3490
+ * @example
3491
+ * ```ts
3492
+ * // `config` is any full native Config; no registry row carries a manifest entry today
3493
+ * androidManifestEntries({ ...config, app: { name: "Demo", identifier: "com.acme.demo", orientation: "portrait" } });
3494
+ * // [{ kind: "activity-attribute", name: "android:screenOrientation", value: "portrait" }]
3495
+ * ```
3496
+ */
3497
+ function androidManifestEntries(global) {
3498
+ return [...resolveConfiguredCapabilities(global, "android").flatMap((capability) => capability.manifest).filter((entry) => entry.kind === "activity-attribute"), ...orientationManifest(global.app.orientation)];
3499
+ }
3500
+ /**
2559
3501
  * Returns the required-file set a mobile `gen/<platform>` tree must carry — the options
2560
3502
  * object keeps every target-scoped API method reading the same way.
2561
3503
  *
@@ -2679,20 +3621,19 @@ function createProjectApi(ctx) {
2679
3621
  */
2680
3622
  const checkCompleteness = (opts) => completeness(ctx.global.projectDir, opts.target);
2681
3623
  /**
2682
- * Runs the idempotent mobile post-init patch pass — Android release signing, plus the
2683
- * Xcode/Android-Studio runner-command rewrite when a `runner` is supplied.
3624
+ * Implements {@link Api.patchMobile}: hands Android its manifest entries and
3625
+ * `app.backgroundColor` (the status bar icons follow it), then logs.
2684
3626
  *
2685
- * @param opts - The patch options.
2686
- * @param opts.target - The mobile platform to patch.
2687
- * @param opts.runner - The absolute Node/`tauri.js` pair from `tauri.runner()`.
2688
- * @returns The paths patched vs. left unchanged.
3627
+ * @param opts - See {@link Api.patchMobile}.
3628
+ * @returns See {@link Api.patchMobile}.
2689
3629
  * @example
2690
3630
  * ```ts
2691
- * await runPatchMobile({ target: "ios", runner: tauri.runner() });
3631
+ * await runPatchMobile({ target: "ios" }); // { patched: [], unchanged: [] } before `tauri ios init`
2692
3632
  * ```
2693
3633
  */
2694
3634
  const runPatchMobile = async (opts) => {
2695
- const result = await patchMobile(ctx.global.projectDir, opts, ctx.global.signing);
3635
+ const manifest = opts.target === "android" ? androidManifestEntries(ctx.global) : [];
3636
+ const result = await patchMobile(ctx.global.projectDir, opts, ctx.global.signing, manifest, ctx.global.app.backgroundColor);
2696
3637
  ctx.log.info("project:patchMobile", {
2697
3638
  target: opts.target,
2698
3639
  patched: result.patched.length
@@ -2793,6 +3734,10 @@ const BUILD_NUMBER_PATTERN = /^[\w.]+$/;
2793
3734
  const URL_SCHEME_PATTERN = /^[a-z][a-z\d+.-]*$/i;
2794
3735
  /** POSIX environment variable name — lands raw inside a Kotlin `System.getenv("…")` call. */
2795
3736
  const ENV_VAR_NAME_PATTERN = /^[a-z_][a-z\d_]*$/i;
3737
+ /** `#rrggbb` or `#rrggbbaa` — the hex forms Tauri parses a window colour from. */
3738
+ const HEX_COLOUR_PATTERN = /^#[0-9a-f]{6}([0-9a-f]{2})?$/i;
3739
+ /** The three `Orientation` values — plain-JS config can carry anything else. */
3740
+ const ORIENTATION_PATTERN = /^(?:portrait|landscape|any)$/;
2796
3741
  /**
2797
3742
  * Validates one free-text config value that is interpolated verbatim into a generated
2798
3743
  * file. Every generated format (TOML, Kotlin, plist, XML) has its own escape rules, so a
@@ -2853,13 +3798,14 @@ function assertDeliveryDirectory(value) {
2853
3798
  /**
2854
3799
  * Validates the global config at composition time — throws `[native]`-formatted errors
2855
3800
  * for missing app identity, missing web wiring, values that would break out of the
2856
- * generated file they are written into, a `projectDir` outside the project, an `outDir`
2857
- * this app must not deliver into, unknown `config.system` names, or a `deep-link`
2858
- * composition missing its scheme.
3801
+ * generated file they are written into, a window colour or orientation outside its
3802
+ * allowed shape, a `projectDir` outside the project, an `outDir` this app must not
3803
+ * deliver into, unknown `config.system` names, or a `deep-link` composition missing its
3804
+ * scheme.
2859
3805
  *
2860
3806
  * @param global - Frozen global framework config.
2861
- * @throws {Error} When identity, web wiring, interpolated values, derived directories,
2862
- * system names, or deep-link config are invalid.
3807
+ * @throws {Error} When identity, web wiring, interpolated values, presentation fields,
3808
+ * derived directories, system names, or deep-link config are invalid.
2863
3809
  * @example
2864
3810
  * ```ts
2865
3811
  * validateProjectConfig(ctx.global);
@@ -2874,6 +3820,8 @@ function validateProjectConfig(global) {
2874
3820
  if (!global.web.dist) throw new Error("[native] web.dist is required.\n Set config.web.dist to your web build's output directory.");
2875
3821
  assertShape("app.version", global.app.version, VERSION_PATTERN, "semantic version", "Use a MAJOR.MINOR.PATCH version such as \"1.0.0\".");
2876
3822
  assertShape("app.buildNumber", global.app.buildNumber, BUILD_NUMBER_PATTERN, "build number", "Use digits, letters, dots or underscores, such as \"42\" or \"1.0.3\".");
3823
+ assertShape("app.backgroundColor", global.app.backgroundColor, HEX_COLOUR_PATTERN, "colour", "Use a hex colour such as \"#10161d\".");
3824
+ assertShape("app.orientation", global.app.orientation, ORIENTATION_PATTERN, "orientation", "Use \"portrait\", \"landscape\" or \"any\".");
2877
3825
  assertShape("signing.android.keystorePasswordEnv", global.signing.android?.keystorePasswordEnv, ENV_VAR_NAME_PATTERN, "environment variable name", "Reference the password by variable NAME, such as \"ANDROID_KEYSTORE_PASSWORD\" — never the password itself.");
2878
3826
  assertShape("signing.android.keyPasswordEnv", global.signing.android?.keyPasswordEnv, ENV_VAR_NAME_PATTERN, "environment variable name", "Reference the password by variable NAME, such as \"ANDROID_KEY_PASSWORD\" — never the password itself.");
2879
3827
  assertDerivedDirectory(global.projectDir);
@@ -2888,8 +3836,9 @@ function validateProjectConfig(global) {
2888
3836
  //#region src/plugins/project/index.ts
2889
3837
  /**
2890
3838
  * Complex tier — capability registry + generators/ + write-if-changed writer + the mobile/
2891
- * sub-domain (completeness gate, Android signing block, runner-command rewrite) + the
2892
- * guarded clean.
3839
+ * sub-domain (completeness gate, Android signing block, Android manifest attributes,
3840
+ * Xcode settings, runner-command rewrite) + the build-time orientation lock + the guarded
3841
+ * clean.
2893
3842
  *
2894
3843
  * @see README.md
2895
3844
  * @example
@@ -4122,7 +5071,7 @@ function createTauriApi(ctx) {
4122
5071
  * ```
4123
5072
  */
4124
5073
  async function run(cmd, hooks) {
4125
- const startedAt = Date.now();
5074
+ const startedAt = performance.now();
4126
5075
  /**
4127
5076
  * Scrubs one output line, forwards it to the caller's hooks, and parses
4128
5077
  * any compile-progress tick out of it.
@@ -4145,7 +5094,7 @@ function createTauriApi(ctx) {
4145
5094
  cwd: runCwd(),
4146
5095
  onLine: handleLine
4147
5096
  });
4148
- const durationMs = Date.now() - startedAt;
5097
+ const durationMs = Math.round(performance.now() - startedAt);
4149
5098
  const scrubbedStdout = scrub(result.stdout);
4150
5099
  const scrubbedStderr = scrub(result.stderr);
4151
5100
  if (result.code !== 0) {
@@ -4880,7 +5829,7 @@ function emitPhase(ctx, target, phase, status, extra) {
4880
5829
  */
4881
5830
  async function runCompileAndBundle(ctx, deps, opts) {
4882
5831
  const { target } = opts;
4883
- const startedAt = Date.now();
5832
+ const startedAt = performance.now();
4884
5833
  let transitionAt;
4885
5834
  emitPhase(ctx, target, "compile", "start");
4886
5835
  try {
@@ -4919,8 +5868,8 @@ async function runCompileAndBundle(ctx, deps, opts) {
4919
5868
  onOutput: (line) => {
4920
5869
  if (transitionAt !== void 0) return;
4921
5870
  if (!BUNDLING_TRANSITION_PATTERN.test(line)) return;
4922
- transitionAt = Date.now();
4923
- emitPhase(ctx, target, "compile", "done", { durationMs: transitionAt - startedAt });
5871
+ transitionAt = performance.now();
5872
+ emitPhase(ctx, target, "compile", "done", { durationMs: Math.round(transitionAt - startedAt) });
4924
5873
  emitPhase(ctx, target, "bundle", "start");
4925
5874
  }
4926
5875
  });
@@ -4928,14 +5877,14 @@ async function runCompileAndBundle(ctx, deps, opts) {
4928
5877
  const openPhase = transitionAt === void 0 ? "compile" : "bundle";
4929
5878
  const detail = error instanceof Error ? error.message : String(error);
4930
5879
  emitPhase(ctx, target, openPhase, "error", {
4931
- durationMs: Date.now() - (transitionAt ?? startedAt),
5880
+ durationMs: Math.round(performance.now() - (transitionAt ?? startedAt)),
4932
5881
  detail
4933
5882
  });
4934
5883
  throw error;
4935
5884
  }
4936
- const endedAt = Date.now();
5885
+ const endedAt = performance.now();
4937
5886
  if (transitionAt === void 0) {
4938
- const compileDurationMs = endedAt - startedAt;
5887
+ const compileDurationMs = Math.round(endedAt - startedAt);
4939
5888
  emitPhase(ctx, target, "compile", "done", { durationMs: compileDurationMs });
4940
5889
  emitPhase(ctx, target, "bundle", "start");
4941
5890
  emitPhase(ctx, target, "bundle", "done", { durationMs: 0 });
@@ -4944,17 +5893,18 @@ async function runCompileAndBundle(ctx, deps, opts) {
4944
5893
  bundleDurationMs: 0
4945
5894
  };
4946
5895
  }
4947
- const bundleDurationMs = endedAt - transitionAt;
5896
+ const bundleDurationMs = Math.round(endedAt - transitionAt);
4948
5897
  emitPhase(ctx, target, "bundle", "done", { durationMs: bundleDurationMs });
4949
5898
  return {
4950
- compileDurationMs: transitionAt - startedAt,
5899
+ compileDurationMs: Math.round(transitionAt - startedAt),
4951
5900
  bundleDurationMs
4952
5901
  };
4953
5902
  }
4954
5903
  /**
4955
5904
  * Runs one phase generically: emits `native:phase` start/done/error and measures
4956
- * duration, rethrowing on failure so the caller stops the pipeline (no partial-continue,
4957
- * v1) — the phase after a failing one is never started.
5905
+ * duration (monotonic clock, whole milliseconds), rethrowing on failure so the caller
5906
+ * stops the pipeline (no partial-continue, v1) — the phase after a failing one is never
5907
+ * started.
4958
5908
  *
4959
5909
  * @param ctx - The build pipeline's domain context.
4960
5910
  * @param target - The packaging target the phase runs for.
@@ -4969,11 +5919,11 @@ async function runCompileAndBundle(ctx, deps, opts) {
4969
5919
  * ```
4970
5920
  */
4971
5921
  async function runPhase(ctx, target, phase, run, detailOf) {
4972
- const startedAt = Date.now();
5922
+ const startedAt = performance.now();
4973
5923
  emitPhase(ctx, target, phase, "start");
4974
5924
  try {
4975
5925
  const result = await run();
4976
- const durationMs = Date.now() - startedAt;
5926
+ const durationMs = Math.round(performance.now() - startedAt);
4977
5927
  const detail = detailOf?.(result);
4978
5928
  emitPhase(ctx, target, phase, "done", detail === void 0 ? { durationMs } : {
4979
5929
  durationMs,
@@ -4985,7 +5935,7 @@ async function runPhase(ctx, target, phase, run, detailOf) {
4985
5935
  };
4986
5936
  } catch (error) {
4987
5937
  emitPhase(ctx, target, phase, "error", {
4988
- durationMs: Date.now() - startedAt,
5938
+ durationMs: Math.round(performance.now() - startedAt),
4989
5939
  detail: error instanceof Error ? error.message : String(error)
4990
5940
  });
4991
5941
  throw error;
@@ -5042,7 +5992,7 @@ async function runPrepare(ctx, deps, target) {
5042
5992
  */
5043
5993
  async function runPipeline(ctx, deps, opts) {
5044
5994
  const { target } = opts;
5045
- const startedAt = Date.now();
5995
+ const startedAt = performance.now();
5046
5996
  const phases = [...await runPrepare(ctx, deps, target)];
5047
5997
  const { compileDurationMs, bundleDurationMs } = await runCompileAndBundle(ctx, deps, opts);
5048
5998
  phases.push({
@@ -5061,7 +6011,7 @@ async function runPipeline(ctx, deps, opts) {
5061
6011
  phase: "collect",
5062
6012
  durationMs: collect.durationMs
5063
6013
  });
5064
- const durationMs = Date.now() - startedAt;
6014
+ const durationMs = Math.round(performance.now() - startedAt);
5065
6015
  const { outPath, artifacts } = collect.result;
5066
6016
  ctx.emit("native:complete", {
5067
6017
  target,
@@ -7033,8 +7983,9 @@ function createCliHandlers(ctx) {
7033
7983
  * ```
7034
7984
  */
7035
7985
  "native:phase"(payload) {
7036
- if (payload.status === "start") ctx.state.progress = { startedAt: Date.now() };
7037
- const elapsedMs = ctx.state.progress.startedAt ? Date.now() - ctx.state.progress.startedAt : 0;
7986
+ if (payload.status === "start") ctx.state.progress = { startedAt: performance.now() };
7987
+ const { startedAt } = ctx.state.progress;
7988
+ const elapsedMs = startedAt === void 0 ? 0 : Math.round(performance.now() - startedAt);
7038
7989
  renderPhaseEvent(ui, payload, elapsedMs);
7039
7990
  if (payload.status === "done" || payload.status === "error") ctx.state.progress = { startedAt: void 0 };
7040
7991
  },
@@ -7186,10 +8137,10 @@ const cliPlugin = createPlugin$1("cli", {
7186
8137
  *
7187
8138
  * | Field | Type | Default |
7188
8139
  * |---|---|---|
7189
- * | `app` | `{ name; identifier; version?; icon?; category?; buildNumber? }` | `{ name: "", identifier: "" }` — both validated non-empty at composition |
8140
+ * | `app` | `{ name; identifier; version?; icon?; category?; buildNumber?; orientation?; backgroundColor? }` | `{ name: "", identifier: "" }` — both validated non-empty at composition; `orientation` (`"portrait" \| "landscape" \| "any"`) is a build-time mobile lock, `backgroundColor` a hex window colour |
7190
8141
  * | `web` | `{ build; devCommand; devUrl; dist; cwd? }` | `"bun run build"`, `"bun run dev"`, `"http://localhost:5173"`, `"dist"` |
7191
8142
  * | `system` | `ReadonlyArray<{ name: string }>` | `[]` — the composed `@moku-labs/system` plugins |
7192
- * | `capabilities` | `Partial<CapabilityConfigMap>` | `{}` |
8143
+ * | `capabilities` | `Partial<CapabilityConfigMap>` | `{}` — keys: `store`, `notification`, `clipboard-manager`, `tray`, `deep-link`, `back`, `haptics` |
7193
8144
  * | `targets` | `readonly Target[]` | `hostTargets(process.platform)` — one desktop target, mobile is opt-in |
7194
8145
  * | `projectDir` | `string` | `".moku/tauri"` — generated Tauri project (gitignored build output) |
7195
8146
  * | `outDir` | `string` | `"dist-native"` — installer delivery root |