@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.mjs CHANGED
@@ -771,6 +771,18 @@ function generateCapabilities(input) {
771
771
  //#endregion
772
772
  //#region src/plugins/project/generators/cargo.ts
773
773
  /**
774
+ * The `tauri` crate floor. The `back` capability calls `exit()` and grants
775
+ * `core:app:allow-exit`, and both exist only since tauri 2.12.0. `tauri-build` versions
776
+ * on its own 2.x line, so its floor stays `"2"`.
777
+ */
778
+ const TAURI_VERSION_FLOOR = "2.12";
779
+ /**
780
+ * The dependencies only an iOS build compiles: the safe-area hook in the generated
781
+ * `lib.rs` reaches WKWebView through `objc2`. A target table, written for every target,
782
+ * so no other target ever builds the crate and the table adds no per-target difference.
783
+ */
784
+ const IOS_ONLY_DEPENDENCIES = [`[target.'cfg(target_os = "ios")'.dependencies]`, "objc2 = \"0.6\""];
785
+ /**
774
786
  * Derives a valid Cargo package name from the app's display name — lowercased,
775
787
  * non-alphanumeric runs collapsed to a single hyphen, and guaranteed to start with a
776
788
  * letter (Cargo package names must match `[a-z][a-z0-9_-]*`).
@@ -806,7 +818,8 @@ function crateIdent(packageName) {
806
818
  * Generates `src-tauri/Cargo.toml` — the package manifest, the `tauri` dependency with
807
819
  * every cargo feature the composed capabilities ask for (tray's `tray-icon`; without it
808
820
  * the tray API is not compiled in at all), plus one pinned dependency line per resolved
809
- * capability that ships a real crate. Feature-only rows contribute no dependency line.
821
+ * capability that ships a real crate. Feature-only and permission-only rows contribute
822
+ * no dependency line. The iOS-only `objc2` table closes the file on every target.
810
823
  *
811
824
  * @param input - Frozen global config + capabilities resolved for the target.
812
825
  * @returns A single-artifact array for `src-tauri/Cargo.toml`.
@@ -835,10 +848,12 @@ function generateCargo(input) {
835
848
  "tauri-build = { version = \"2\", features = [] }",
836
849
  "",
837
850
  "[dependencies]",
838
- `tauri = { version = "2", features = [${features}] }`,
851
+ `tauri = { version = "${TAURI_VERSION_FLOOR}", features = [${features}] }`,
839
852
  "serde = { version = \"1\", features = [\"derive\"] }",
840
853
  "serde_json = \"1\"",
841
854
  ...pinnedDeps,
855
+ "",
856
+ ...IOS_ONLY_DEPENDENCIES,
842
857
  ""
843
858
  ].join("\n")
844
859
  }];
@@ -956,14 +971,44 @@ function generateEntitlements(input) {
956
971
  //#endregion
957
972
  //#region src/plugins/project/generators/rust.ts
958
973
  /**
959
- * @file project plugin generator — main.rs/lib.rs with mobile entry point + plugin init lines.
960
- */
974
+ * @file project plugin generator — main.rs/lib.rs with mobile entry point, plugin init
975
+ * lines and the iOS safe-area setup hook.
976
+ */
977
+ /**
978
+ * `Manager` brings `get_webview_window` into scope. Only the iOS arm of the setup hook
979
+ * calls it, so the import is iOS-only too: anywhere else it would be an unused import.
980
+ */
981
+ const IOS_MANAGER_IMPORT = ["#[cfg(target_os = \"ios\")]", "use tauri::Manager;"];
982
+ /**
983
+ * The safe-area setup hook, as verified on the iOS 26.3 simulator. UIKit shrinks a
984
+ * WKWebView page by the safe area while its scroll view stays on `.automatic`; `.never`
985
+ * gives the page the whole screen, and CSS `env(safe-area-inset-*)` still reports the
986
+ * notch. The `cfg` makes it a no-op off iOS, so `lib.rs` does not differ per target. The
987
+ * window is tauri's default `main` label: the generated `app.windows` entry carries none.
988
+ */
989
+ const SAFE_AREA_SETUP = [
990
+ " .setup(|_app| {",
991
+ " // wry leaves WKWebView's scroll view on .automatic, which shrinks the page by the",
992
+ " // safe area (tauri-apps/tauri#8166). .never gives the page the full screen.",
993
+ " #[cfg(target_os = \"ios\")]",
994
+ " if let Some(window) = _app.get_webview_window(\"main\") {",
995
+ " window.with_webview(|webview| unsafe {",
996
+ " use objc2::{msg_send, runtime::AnyObject};",
997
+ " let wk = &*(webview.inner() as *mut AnyObject);",
998
+ " let scroll: *mut AnyObject = msg_send![wk, scrollView];",
999
+ " // UIScrollViewContentInsetAdjustmentNever = 2",
1000
+ " let _: () = msg_send![&*scroll, setContentInsetAdjustmentBehavior: 2isize];",
1001
+ " })?;",
1002
+ " }",
1003
+ " Ok(())",
1004
+ " })"
1005
+ ];
961
1006
  /**
962
1007
  * Generates `src-tauri/src/lib.rs` and `src-tauri/src/main.rs`. `lib.rs` carries the
963
1008
  * `#[cfg_attr(mobile, tauri::mobile_entry_point)]`-annotated `run()` with one
964
1009
  * `.plugin(...)` init line per resolved capability that has a real Rust init (rows
965
- * without one, e.g. tray's cargo-feature row, contribute no line); `main.rs` is a thin
966
- * entry point that calls into the lib crate.
1010
+ * without one, e.g. tray's cargo-feature row, contribute no line), then the iOS
1011
+ * safe-area `.setup` hook; `main.rs` is a thin entry point that calls into the lib crate.
967
1012
  *
968
1013
  * @param input - Frozen global config + capabilities resolved for the target.
969
1014
  * @returns Artifacts for `src-tauri/src/lib.rs` and `src-tauri/src/main.rs`.
@@ -974,11 +1019,15 @@ function generateEntitlements(input) {
974
1019
  */
975
1020
  function generateRust(input) {
976
1021
  const packageIdent = crateIdent(sanitizePackageName(input.global.app.name));
1022
+ const pluginLines = input.capabilities.filter((capability) => Boolean(capability.rustInit)).map((capability) => ` .plugin(${capability.rustInit})`).toSorted();
977
1023
  const library = [
1024
+ ...IOS_MANAGER_IMPORT,
1025
+ "",
978
1026
  "#[cfg_attr(mobile, tauri::mobile_entry_point)]",
979
1027
  "pub fn run() {",
980
1028
  " tauri::Builder::default()",
981
- ...input.capabilities.filter((capability) => Boolean(capability.rustInit)).map((capability) => ` .plugin(${capability.rustInit})`).toSorted(),
1029
+ ...pluginLines,
1030
+ ...SAFE_AREA_SETUP,
982
1031
  " .run(tauri::generate_context!())",
983
1032
  " .expect(\"error while running tauri application\");",
984
1033
  "}",
@@ -1001,25 +1050,172 @@ function generateRust(input) {
1001
1050
  }];
1002
1051
  }
1003
1052
  //#endregion
1053
+ //#region src/plugins/project/orientation.ts
1054
+ const PORTRAIT = "UIInterfaceOrientationPortrait";
1055
+ const PORTRAIT_UPSIDE_DOWN = "UIInterfaceOrientationPortraitUpsideDown";
1056
+ const LANDSCAPE_SIDES = ["UIInterfaceOrientationLandscapeLeft", "UIInterfaceOrientationLandscapeRight"];
1057
+ /**
1058
+ * The iOS orientation lists per lock: the iPhone key, then the `~ipad` override. An iPhone
1059
+ * held portrait never turns upside down; an iPad does, so its portrait list keeps both.
1060
+ */
1061
+ const IOS_ORIENTATIONS = {
1062
+ portrait: {
1063
+ iphone: [PORTRAIT],
1064
+ ipad: [PORTRAIT, PORTRAIT_UPSIDE_DOWN]
1065
+ },
1066
+ landscape: {
1067
+ iphone: LANDSCAPE_SIDES,
1068
+ ipad: LANDSCAPE_SIDES
1069
+ }
1070
+ };
1071
+ /**
1072
+ * The Android `screenOrientation` per lock, matching the iOS lists: `portrait` has no
1073
+ * upside-down side, `sensorLandscape` turns between both landscape sides. `any` maps to no
1074
+ * attribute at all, the template's default.
1075
+ */
1076
+ const ANDROID_SCREEN_ORIENTATION = {
1077
+ portrait: "portrait",
1078
+ landscape: "sensorLandscape",
1079
+ any: void 0
1080
+ };
1081
+ /**
1082
+ * Builds the `Info.ios.plist` entries that lock the iOS orientation. A locked app also
1083
+ * asks for `UIRequiresFullScreen`: App Store review refuses an iPad app that restricts its
1084
+ * orientations without it. `any` and unset add nothing, so the template's default list
1085
+ * (every orientation) stays.
1086
+ *
1087
+ * @param orientation - The configured `app.orientation`, or undefined when unset.
1088
+ * @returns The plist entries, empty when the orientation is not locked.
1089
+ * @example
1090
+ * ```ts
1091
+ * orientationPlist("portrait")[0];
1092
+ * // { key: "UISupportedInterfaceOrientations", value: ["UIInterfaceOrientationPortrait"] }
1093
+ * ```
1094
+ */
1095
+ function orientationPlist(orientation) {
1096
+ if (orientation === void 0 || orientation === "any") return [];
1097
+ const { iphone, ipad } = IOS_ORIENTATIONS[orientation];
1098
+ return [
1099
+ {
1100
+ key: "UISupportedInterfaceOrientations",
1101
+ value: iphone
1102
+ },
1103
+ {
1104
+ key: "UISupportedInterfaceOrientations~ipad",
1105
+ value: ipad
1106
+ },
1107
+ {
1108
+ key: "UIRequiresFullScreen",
1109
+ value: true
1110
+ }
1111
+ ];
1112
+ }
1113
+ /**
1114
+ * Builds the Android manifest entry for the orientation lock: `android:screenOrientation`
1115
+ * on the main activity. `any` and unset ask for the attribute to be ABSENT rather than
1116
+ * adding nothing, so a lock a previous build wrote into the gen/ tree is removed again.
1117
+ *
1118
+ * @param orientation - The configured `app.orientation`, or undefined when unset.
1119
+ * @returns Exactly one `activity-attribute` entry.
1120
+ * @example
1121
+ * ```ts
1122
+ * orientationManifest("landscape");
1123
+ * // [{ kind: "activity-attribute", name: "android:screenOrientation", value: "sensorLandscape" }]
1124
+ * ```
1125
+ */
1126
+ function orientationManifest(orientation) {
1127
+ return [{
1128
+ kind: "activity-attribute",
1129
+ name: "android:screenOrientation",
1130
+ value: ANDROID_SCREEN_ORIENTATION[orientation ?? "any"]
1131
+ }];
1132
+ }
1133
+ //#endregion
1134
+ //#region src/plugins/project/xml.ts
1135
+ /**
1136
+ * @file project plugin — XML text escaping, shared by the two XML files this plugin writes
1137
+ * into: the `Info.ios.plist` sidecar and the Android manifest.
1138
+ */
1139
+ /**
1140
+ * XML's five predefined entities. `&` goes first, so the ampersand of an entity written
1141
+ * by a later step is never escaped a second time.
1142
+ */
1143
+ const XML_ESCAPES = [
1144
+ [/&/g, "&"],
1145
+ [/</g, "&lt;"],
1146
+ [/>/g, "&gt;"],
1147
+ [/"/g, "&quot;"],
1148
+ [/'/g, "&apos;"]
1149
+ ];
1150
+ /**
1151
+ * Escapes text for an XML element body or a quoted attribute value. A value lands
1152
+ * verbatim in a generated file, where an unescaped `<` or `"` would end the element or
1153
+ * the attribute around it.
1154
+ *
1155
+ * @param text - The raw value.
1156
+ * @returns The value with `& < > " '` written as entities.
1157
+ * @example
1158
+ * ```ts
1159
+ * escapeXml(`Tom & "Jerry"`); // "Tom &amp; &quot;Jerry&quot;"
1160
+ * ```
1161
+ */
1162
+ function escapeXml(text) {
1163
+ let escaped = text;
1164
+ for (const [pattern, entity] of XML_ESCAPES) escaped = escaped.replace(pattern, entity);
1165
+ return escaped;
1166
+ }
1167
+ //#endregion
1004
1168
  //#region src/plugins/project/generators/sidecar.ts
1005
1169
  /**
1006
- * Generates the `Info.ios.plist` SIDECAR at the src-tauri root — a future-mechanism
1007
- * seam for iOS mobile-permission plist keys (D-012). Every v1 registry row carries an
1008
- * empty `sidecarPlist`, so this emits no artifact today; it stays pure and
1009
- * generator-shaped so a future row carrying `sidecarPlist` entries activates it with
1010
- * zero pipeline changes.
1170
+ * @file project plugin generator — Info.ios.plist sidecar (src-tauri root, outside gen/).
1171
+ */
1172
+ /**
1173
+ * Renders one plist value as the lines that follow its `<key>`: a `<string>`, a
1174
+ * `<true/>`/`<false/>`, or an `<array>` of strings. Every text is XML-escaped.
1175
+ *
1176
+ * @param value - The entry value.
1177
+ * @returns The value's lines, indented for the top-level `<dict>`.
1178
+ * @example
1179
+ * ```ts
1180
+ * renderPlistValue(["UIInterfaceOrientationPortrait"]);
1181
+ * // [" <array>", " <string>UIInterfaceOrientationPortrait</string>", " </array>"]
1182
+ * ```
1183
+ */
1184
+ function renderPlistValue(value) {
1185
+ if (typeof value === "boolean") return [value ? " <true/>" : " <false/>"];
1186
+ if (typeof value === "string") return [` <string>${escapeXml(value)}</string>`];
1187
+ return [
1188
+ " <array>",
1189
+ ...value.map((item) => ` <string>${escapeXml(item)}</string>`),
1190
+ " </array>"
1191
+ ];
1192
+ }
1193
+ /**
1194
+ * Generates the `Info.ios.plist` SIDECAR at the src-tauri root, which Tauri merges into the
1195
+ * app's Info.plist on every iOS build. Its entries are every resolved capability's
1196
+ * `sidecarPlist`, then the orientation lock (`app.orientation`); on a duplicate key the
1197
+ * later entry wins, so orientation beats a capability.
1198
+ *
1199
+ * On iOS the file is ALWAYS written, as an empty `<dict>` when nothing contributes a key:
1200
+ * the writer never deletes a file, and a portrait lock left in a stale sidecar would keep
1201
+ * being merged after the app went back to `any`. Every other target gets no artifact.
1011
1202
  *
1012
1203
  * @param input - Frozen global config + capabilities resolved for the target.
1013
- * @returns An artifact for `src-tauri/Info.ios.plist` when any resolved capability
1014
- * carries sidecar entries, otherwise an empty array.
1204
+ * @returns An artifact for `src-tauri/Info.ios.plist` on iOS, otherwise an empty array.
1015
1205
  * @example
1016
1206
  * ```ts
1017
- * generateSidecar({ global, target: "ios", capabilities: [] }); // []
1207
+ * // `config` is any full native Config
1208
+ * const global = { ...config, app: { name: "Demo", identifier: "com.acme.demo", orientation: "portrait" } };
1209
+ * generateSidecar({ global, target: "ios", capabilities: [] })[0]?.path; // "src-tauri/Info.ios.plist"
1210
+ * // its <dict>: UISupportedInterfaceOrientations, UISupportedInterfaceOrientations~ipad, UIRequiresFullScreen
1211
+ * generateSidecar({ global, target: "macos", capabilities: [] }); // []
1018
1212
  * ```
1019
1213
  */
1020
1214
  function generateSidecar(input) {
1021
- const entries = input.capabilities.flatMap((capability) => capability.sidecarPlist);
1022
- if (entries.length === 0) return [];
1215
+ if (input.target !== "ios") return [];
1216
+ const entries = /* @__PURE__ */ new Map();
1217
+ const contributed = [...input.capabilities.flatMap((capability) => capability.sidecarPlist), ...orientationPlist(input.global.app.orientation)];
1218
+ for (const entry of contributed) entries.set(entry.key, entry.value);
1023
1219
  return [{
1024
1220
  path: "src-tauri/Info.ios.plist",
1025
1221
  content: [
@@ -1027,7 +1223,7 @@ function generateSidecar(input) {
1027
1223
  "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">",
1028
1224
  "<plist version=\"1.0\">",
1029
1225
  "<dict>",
1030
- entries.map((entry) => ` <key>${entry.key}</key>\n <string>${entry.value}</string>`).join("\n"),
1226
+ ...[...entries].flatMap(([key, value]) => [` <key>${escapeXml(key)}</key>`, ...renderPlistValue(value)]),
1031
1227
  "</dict>",
1032
1228
  "</plist>",
1033
1229
  ""
@@ -1131,7 +1327,8 @@ function buildPlugins(capabilities) {
1131
1327
  }
1132
1328
  /**
1133
1329
  * Generates `src-tauri/tauri.conf.json` — app identity, the web build/dev wiring, the
1134
- * bundle/signing metadata, and a `plugins.<name>` block per CONFIGURED capability (see
1330
+ * main window (its title, plus `app.backgroundColor` when set), the bundle/signing
1331
+ * metadata, and a `plugins.<name>` block per CONFIGURED capability (see
1135
1332
  * {@link buildPlugins}; this is where deep-link's scheme rides — per D-011/D-012 the whole
1136
1333
  * v1 mobile-permission story is conf-only). Both path-shaped fields are rebased onto
1137
1334
  * `src-tauri`, which is where Tauri resolves them from, and the before-commands carry an
@@ -1163,7 +1360,10 @@ function generateTauriConf(input) {
1163
1360
  devUrl: global.web.devUrl,
1164
1361
  frontendDist: relativeToTauriRoot(global.projectDir, path.resolve(webRoot, global.web.dist))
1165
1362
  },
1166
- app: { windows: [{ title: global.app.name }] },
1363
+ app: { windows: [{
1364
+ title: global.app.name,
1365
+ ...compact([["backgroundColor", global.app.backgroundColor]])
1366
+ }] },
1167
1367
  bundle: buildBundle(input),
1168
1368
  plugins: buildPlugins(capabilities)
1169
1369
  };
@@ -1301,7 +1501,9 @@ function placeholderIconPng() {
1301
1501
  * @file project plugin — mobile gen/-tree required-file completeness gate.
1302
1502
  */
1303
1503
  /**
1304
- * Required top-level entries per mobile `gen/<platform>` tree (Tauri 2.9.x scaffolding).
1504
+ * Required top-level entries per mobile `gen/<platform>` tree. The android set is verified
1505
+ * against the tree `tauri android init` writes in tauri-cli 2.12.1: the settings file is
1506
+ * Groovy `settings.gradle`, not `settings.gradle.kts`.
1305
1507
  * A partial init (tauri#13902) can leave some of these absent — `completeness` checks
1306
1508
  * the required-file SET, not mere directory existence.
1307
1509
  */
@@ -1314,7 +1516,7 @@ const REQUIRED_FILES = {
1314
1516
  ],
1315
1517
  android: [
1316
1518
  "build.gradle.kts",
1317
- "settings.gradle.kts",
1519
+ "settings.gradle",
1318
1520
  "gradle.properties",
1319
1521
  "app/build.gradle.kts",
1320
1522
  "app/src/main/AndroidManifest.xml"
@@ -1328,7 +1530,7 @@ const REQUIRED_FILES = {
1328
1530
  * @returns The frozen list of required paths, relative to `src-tauri/gen/<platform>`.
1329
1531
  * @example
1330
1532
  * ```ts
1331
- * requiredFiles("android"); // ["build.gradle.kts", "settings.gradle.kts", ...]
1533
+ * requiredFiles("android"); // ["build.gradle.kts", "settings.gradle", ...]
1332
1534
  * ```
1333
1535
  */
1334
1536
  function requiredFiles(platform) {
@@ -1462,13 +1664,229 @@ async function writeIfChanged(filePath, content, projectDirectory) {
1462
1664
  return "written";
1463
1665
  }
1464
1666
  //#endregion
1667
+ //#region src/plugins/project/mobile/manifest.ts
1668
+ /**
1669
+ * @file project plugin — the Android manifest patch. Tauri has no config key for what the
1670
+ * main activity carries (`android:screenOrientation` among them), so the mobile patch pass
1671
+ * sets those attributes on the `<activity>` of the generated
1672
+ * `gen/android/app/src/main/AndroidManifest.xml` itself.
1673
+ *
1674
+ * The transform is a pure text function: only the touched attribute changes, every other
1675
+ * byte (line endings and indentation included) survives, and a second pass is a no-op.
1676
+ */
1677
+ /** Where `tauri android init` writes the app manifest, below `gen/android`. */
1678
+ const MANIFEST_PATH_SEGMENTS = [
1679
+ "app",
1680
+ "src",
1681
+ "main",
1682
+ "AndroidManifest.xml"
1683
+ ];
1684
+ /** The tag name an activity start tag opens with. */
1685
+ const ACTIVITY_OPEN = "<activity";
1686
+ /** The end tag that closes an activity's body. */
1687
+ const ACTIVITY_CLOSE = "</activity>";
1688
+ /** The intent action that marks the launcher activity. */
1689
+ const MAIN_ACTION = "android.intent.action.MAIN";
1690
+ /** Where an `<activity` start tag opens — `<activity-alias` is a different element. */
1691
+ const ACTIVITY_OPEN_PATTERN = /<activity(?=[\s/>])/g;
1692
+ /**
1693
+ * One attribute inside a start tag, from the whitespace character before it:
1694
+ * ` (name)="value"`. XML allows spaces around `=`, but no generated manifest writes them.
1695
+ */
1696
+ const ATTRIBUTE_PATTERN = /\s([\w:.-]+)=(?:"[^"]*"|'[^']*')/g;
1697
+ /** An XML comment — blanked before the scan, so a commented-out activity never counts. */
1698
+ const COMMENT_PATTERN = /<!--[\s\S]*?-->/g;
1699
+ /**
1700
+ * Builds the `[native]` error for a manifest whose main activity cannot be told apart.
1701
+ *
1702
+ * @param manifestPath - The manifest that was searched.
1703
+ * @returns A formatted `[native] ...` error.
1704
+ * @example
1705
+ * ```ts
1706
+ * throw mainActivityError("/repo/.moku/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml");
1707
+ * ```
1708
+ */
1709
+ function mainActivityError(manifestPath) {
1710
+ 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.`);
1711
+ }
1712
+ /**
1713
+ * Finds where a start tag ends. A quoted attribute value is skipped whole, so a `>` inside
1714
+ * one never ends the tag.
1715
+ *
1716
+ * @param text - The manifest content.
1717
+ * @param from - Offset just past the tag name.
1718
+ * @returns The offset just past the closing `>`, or undefined for a tag that never closes.
1719
+ * @example
1720
+ * ```ts
1721
+ * startTagEnd('<activity android:label="a > b">', 9); // 32
1722
+ * ```
1723
+ */
1724
+ function startTagEnd(text, from) {
1725
+ let quote;
1726
+ for (let index = from; index < text.length; index += 1) {
1727
+ const character = text[index];
1728
+ if (quote !== void 0) {
1729
+ if (character === quote) quote = void 0;
1730
+ continue;
1731
+ }
1732
+ if (character === "\"" || character === "'") {
1733
+ quote = character;
1734
+ continue;
1735
+ }
1736
+ if (character === ">") return index + 1;
1737
+ }
1738
+ }
1739
+ /**
1740
+ * Locates every `<activity>` start tag and records whether its body declares MAIN.
1741
+ * Comments are blanked out first (same length, so every offset still points into the real
1742
+ * text), which keeps a commented-out activity from being counted or patched. A start tag
1743
+ * that never closes is not counted at all.
1744
+ *
1745
+ * @param text - The manifest content.
1746
+ * @returns One entry per activity, in file order.
1747
+ * @example
1748
+ * ```ts
1749
+ * locateActivities('<activity android:name=".A" /><activity android:name=".B"><action android:name="android.intent.action.MAIN" /></activity>');
1750
+ * // [{ start: 0, end: 30, isMain: false }, { start: 30, end: 58, isMain: true }]
1751
+ * ```
1752
+ */
1753
+ function locateActivities(text) {
1754
+ const masked = text.replaceAll(COMMENT_PATTERN, (comment) => " ".repeat(comment.length));
1755
+ const activities = [];
1756
+ for (const match of masked.matchAll(ACTIVITY_OPEN_PATTERN)) {
1757
+ const start = match.index;
1758
+ const end = startTagEnd(masked, start + 9);
1759
+ if (end === void 0) continue;
1760
+ const body = masked.slice(start, end).endsWith("/>") ? "" : masked.slice(end, masked.indexOf(ACTIVITY_CLOSE, end));
1761
+ activities.push({
1762
+ start,
1763
+ end,
1764
+ isMain: body.includes(MAIN_ACTION)
1765
+ });
1766
+ }
1767
+ return activities;
1768
+ }
1769
+ /**
1770
+ * Picks the main activity: the one whose body declares MAIN. A manifest with a single
1771
+ * activity and no MAIN still has an obvious one; anything else is ambiguous.
1772
+ *
1773
+ * @param activities - Every activity in the manifest.
1774
+ * @returns The main activity, or undefined when none or several qualify.
1775
+ * @example
1776
+ * ```ts
1777
+ * mainActivity([{ start: 0, end: 30, isMain: false }, { start: 30, end: 58, isMain: true }]);
1778
+ * // { start: 30, end: 58, isMain: true }
1779
+ * mainActivity([{ start: 0, end: 30, isMain: false }, { start: 30, end: 58, isMain: false }]); // undefined
1780
+ * ```
1781
+ */
1782
+ function mainActivity(activities) {
1783
+ const mains = activities.filter((activity) => activity.isMain);
1784
+ if (mains.length === 1) return mains[0];
1785
+ if (mains.length === 0 && activities.length === 1) return activities[0];
1786
+ }
1787
+ /**
1788
+ * Applies one attribute entry to a start tag. A value replaces the attribute in place, or
1789
+ * is inserted right after `<activity` with the whitespace that already follows it — on the
1790
+ * template's one-attribute-per-line layout that is the line break plus the next
1791
+ * attribute's indentation, CRLF included. An `undefined` value removes the attribute
1792
+ * together with the whitespace before it, which on that layout is its whole line.
1793
+ *
1794
+ * @param tag - The activity start tag.
1795
+ * @param entry - The attribute to set or remove.
1796
+ * @returns The start tag with the entry applied.
1797
+ * @example
1798
+ * ```ts
1799
+ * applyAttribute('<activity android:name=".MainActivity">', portraitEntry);
1800
+ * // '<activity android:screenOrientation="portrait" android:name=".MainActivity">'
1801
+ * ```
1802
+ */
1803
+ function applyAttribute(tag, entry) {
1804
+ const rendered = entry.value === void 0 ? void 0 : `${entry.name}="${escapeXml(entry.value)}"`;
1805
+ const existing = [...tag.matchAll(ATTRIBUTE_PATTERN)].find((match) => match[1] === entry.name);
1806
+ if (existing) {
1807
+ const before = tag.slice(0, existing.index).trimEnd();
1808
+ const separator = tag.slice(before.length, existing.index + 1);
1809
+ const after = tag.slice(existing.index + existing[0].length);
1810
+ if (rendered === void 0) return `${before}${after}`;
1811
+ return `${before}${separator}${rendered}${after}`;
1812
+ }
1813
+ if (rendered === void 0) return tag;
1814
+ const rest = tag.slice(9);
1815
+ const separator = rest.slice(0, rest.length - rest.trimStart().length) || " ";
1816
+ return `${ACTIVITY_OPEN}${separator}${rendered}${rest}`;
1817
+ }
1818
+ /**
1819
+ * Applies the `activity-attribute` entries to the main activity of a manifest. `child`
1820
+ * entries are not applied: no registry row carries one, and the official plugins merge
1821
+ * their own manifest needs through build.rs. A pass that only removes attributes leaves a
1822
+ * manifest without a clear main activity as it is.
1823
+ *
1824
+ * @param existing - The current manifest content.
1825
+ * @param entries - The manifest entries to apply, in order (a later one wins).
1826
+ * @param manifestPath - The manifest's path, named in the error.
1827
+ * @returns The manifest with every attribute entry applied.
1828
+ * @throws {Error} `[native]` when an attribute is to be set and the main activity cannot
1829
+ * be told apart.
1830
+ * @example
1831
+ * ```ts
1832
+ * applyManifestEntries('<activity android:name=".Main">\n</activity>', orientationManifest("portrait"), "AndroidManifest.xml");
1833
+ * // '<activity android:screenOrientation="portrait" android:name=".Main">\n</activity>'
1834
+ * ```
1835
+ */
1836
+ function applyManifestEntries(existing, entries, manifestPath) {
1837
+ const attributes = entries.filter((entry) => entry.kind === "activity-attribute");
1838
+ if (attributes.length === 0) return existing;
1839
+ const activity = mainActivity(locateActivities(existing));
1840
+ if (!activity) {
1841
+ if (attributes.every((attribute) => attribute.value === void 0)) return existing;
1842
+ throw mainActivityError(manifestPath);
1843
+ }
1844
+ let tag = existing.slice(activity.start, activity.end);
1845
+ for (const attribute of attributes) tag = applyAttribute(tag, attribute);
1846
+ return `${existing.slice(0, activity.start)}${tag}${existing.slice(activity.end)}`;
1847
+ }
1848
+ /**
1849
+ * Patches the main activity of `gen/android/app/src/main/AndroidManifest.xml` with the
1850
+ * `activity-attribute` entries, through the write-if-changed writer. Idempotent: a second
1851
+ * pass reports the manifest unchanged. With no attribute entry there is nothing to apply,
1852
+ * and the manifest is not even read.
1853
+ *
1854
+ * @param projectDirectory - The Tauri project root.
1855
+ * @param genDirectory - The `src-tauri/gen/android` directory.
1856
+ * @param entries - The manifest entries to apply.
1857
+ * @returns The manifest path, patched or unchanged.
1858
+ * @throws {Error} `[native]` when the manifest is missing, or an attribute is to be set and
1859
+ * the manifest has no clear main activity.
1860
+ * @example
1861
+ * ```ts
1862
+ * // First pass on a manifest without the lock; a second pass lists it under `unchanged`.
1863
+ * await patchAndroidManifest(".moku/tauri", ".moku/tauri/src-tauri/gen/android", orientationManifest("portrait"));
1864
+ * // { patched: [".moku/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml"], unchanged: [] }
1865
+ * ```
1866
+ */
1867
+ async function patchAndroidManifest(projectDirectory, genDirectory, entries) {
1868
+ if (!entries.some((entry) => entry.kind === "activity-attribute")) return {
1869
+ patched: [],
1870
+ unchanged: []
1871
+ };
1872
+ const manifestPath = path.join(genDirectory, ...MANIFEST_PATH_SEGMENTS);
1873
+ if (!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.`);
1874
+ return await writeIfChanged(manifestPath, applyManifestEntries(await readFile(manifestPath, "utf8"), entries, manifestPath), projectDirectory) === "written" ? {
1875
+ patched: [manifestPath],
1876
+ unchanged: []
1877
+ } : {
1878
+ patched: [],
1879
+ unchanged: [manifestPath]
1880
+ };
1881
+ }
1882
+ //#endregion
1465
1883
  //#region src/plugins/project/mobile/files.ts
1466
1884
  /**
1467
1885
  * @file project plugin — the ONE owner of "which generated files a mobile patch pass may
1468
1886
  * touch". Both iOS patches (the runner-command rewrite and the Xcode build-settings patch)
1469
1887
  * read the same list from here, so neither can drift into a file the other does not know
1470
1888
  * about — and neither ever descends into `gen/apple/build` or `gen/android/build`, which
1471
- * belong to the toolchain.
1889
+ * belong to the toolchain. The Android status bar patch finds its MainActivity.kt here too.
1472
1890
  */
1473
1891
  /** Source extensions that can carry the Android runner command. */
1474
1892
  const ANDROID_SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
@@ -1476,6 +1894,15 @@ const ANDROID_SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
1476
1894
  ".kts",
1477
1895
  ".gradle"
1478
1896
  ]);
1897
+ /** The Kotlin file `tauri android init` writes the app's activity into. */
1898
+ const MAIN_ACTIVITY_FILE = "MainActivity.kt";
1899
+ /** Where `tauri android init` writes the app's Kotlin sources, below `gen/android`. */
1900
+ const ANDROID_JAVA_SEGMENTS = [
1901
+ "app",
1902
+ "src",
1903
+ "main",
1904
+ "java"
1905
+ ];
1479
1906
  /** Derived directories a patch scan never descends into — the toolchain owns them. */
1480
1907
  const SKIPPED_DIRECTORIES = /* @__PURE__ */ new Set([
1481
1908
  "build",
@@ -1546,6 +1973,186 @@ async function androidPatchFiles(genDirectory) {
1546
1973
  const gradleFiles = [path.join(genDirectory, "build.gradle.kts"), path.join(genDirectory, "app", "build.gradle.kts")].filter((file) => existsSync(file));
1547
1974
  return [...buildSource, ...gradleFiles];
1548
1975
  }
1976
+ /**
1977
+ * Returns the directory `tauri android init` writes the app's Kotlin sources into. The
1978
+ * MainActivity.kt sits below it, in a folder per segment of the app identifier.
1979
+ *
1980
+ * @param genDirectory - The `src-tauri/gen/android` directory.
1981
+ * @returns The `app/src/main/java` directory of that tree.
1982
+ * @example
1983
+ * ```ts
1984
+ * androidJavaDirectory("/repo/.moku/tauri/src-tauri/gen/android");
1985
+ * // "/repo/.moku/tauri/src-tauri/gen/android/app/src/main/java"
1986
+ * ```
1987
+ */
1988
+ function androidJavaDirectory(genDirectory) {
1989
+ return path.join(genDirectory, ...ANDROID_JAVA_SEGMENTS);
1990
+ }
1991
+ /**
1992
+ * Lists every `MainActivity.kt` below `app/src/main/java`, sorted by path. Build output is
1993
+ * never listed. A generated tree holds exactly one; the caller decides what more or fewer
1994
+ * means.
1995
+ *
1996
+ * @param genDirectory - The `src-tauri/gen/android` directory.
1997
+ * @returns The MainActivity.kt paths found, possibly none.
1998
+ * @example
1999
+ * ```ts
2000
+ * await androidMainActivityFiles("/repo/.moku/tauri/src-tauri/gen/android");
2001
+ * // ["/repo/.moku/tauri/src-tauri/gen/android/app/src/main/java/com/acme/demo/MainActivity.kt"]
2002
+ * ```
2003
+ */
2004
+ async function androidMainActivityFiles(genDirectory) {
2005
+ return (await collectFiles(androidJavaDirectory(genDirectory), (name) => name === MAIN_ACTIVITY_FILE)).toSorted();
2006
+ }
2007
+ //#endregion
2008
+ //#region src/plugins/project/mobile/signing.ts
2009
+ /**
2010
+ * @file project plugin — the Android release-signing block the mobile patch pass keeps in
2011
+ * `gen/android/app/build.gradle.kts`. Only env-var NAMES are ever written to disk: Gradle
2012
+ * reads the passwords itself, at build time.
2013
+ */
2014
+ const SIGNING_START = "// MOKU-SIGNING-START";
2015
+ const SIGNING_END = "// MOKU-SIGNING-END";
2016
+ /**
2017
+ * Characters that change the meaning of a Kotlin string literal: a backslash starts an
2018
+ * escape, a double quote closes the literal, a dollar sign starts a template expression,
2019
+ * and a raw newline ends the line outright.
2020
+ */
2021
+ const KOTLIN_ESCAPES = [
2022
+ [/\\/g, String.raw`\\`],
2023
+ [/"/g, String.raw`\"`],
2024
+ [/\$/g, String.raw`\$`],
2025
+ [/\r/g, String.raw`\r`],
2026
+ [/\n/g, String.raw`\n`]
2027
+ ];
2028
+ /**
2029
+ * Escapes a value for use inside a double-quoted Kotlin string literal. Config values land
2030
+ * verbatim in `build.gradle.kts` — an unescaped `"` would close the literal and an
2031
+ * unescaped `$` would interpolate a Gradle expression, so every one of them is escaped
2032
+ * here rather than trusted.
2033
+ *
2034
+ * @param value - The raw config value (keystore path, key alias, env-var name).
2035
+ * @returns The value, safe to place between double quotes in Kotlin source.
2036
+ * @example
2037
+ * ```ts
2038
+ * kotlinString('re"lease$HOME'); // 're\\"lease\\$HOME'
2039
+ * ```
2040
+ */
2041
+ function kotlinString(value) {
2042
+ let escaped = value;
2043
+ for (const [pattern, replacement] of KOTLIN_ESCAPES) escaped = escaped.replace(pattern, replacement);
2044
+ return escaped;
2045
+ }
2046
+ /**
2047
+ * Renders the moku-managed Gradle signing block. Passwords are read by Gradle itself from
2048
+ * the environment at build time — only env-var NAMES are ever written to disk, per the
2049
+ * `SigningConfig` invariant. `keyPasswordEnv` falls back to `keystorePasswordEnv`, which
2050
+ * is the common single-password keystore. Every interpolated value goes through
2051
+ * {@link kotlinString}, so a path or alias can never close the literal it sits in.
2052
+ *
2053
+ * @param signing - The Android signing config slice, with a keystore path already present.
2054
+ * @param keystorePath - The configured keystore path.
2055
+ * @returns The sentinel-delimited Gradle block.
2056
+ * @example
2057
+ * ```ts
2058
+ * renderSigningBlock({ keyAlias: "release" }, "release.jks");
2059
+ * ```
2060
+ */
2061
+ function renderSigningBlock(signing, keystorePath) {
2062
+ const storePasswordEnvironment = signing.keystorePasswordEnv ?? "";
2063
+ const keyPasswordEnvironment = signing.keyPasswordEnv ?? storePasswordEnvironment;
2064
+ return [
2065
+ SIGNING_START,
2066
+ "android {",
2067
+ " signingConfigs {",
2068
+ " maybeCreate(\"release\").apply {",
2069
+ ` storeFile = file("${kotlinString(keystorePath)}")`,
2070
+ ` keyAlias = "${kotlinString(signing.keyAlias ?? "")}"`,
2071
+ ` storePassword = System.getenv("${kotlinString(storePasswordEnvironment)}")`,
2072
+ ` keyPassword = System.getenv("${kotlinString(keyPasswordEnvironment)}")`,
2073
+ " }",
2074
+ " }",
2075
+ " buildTypes {",
2076
+ " getByName(\"release\") {",
2077
+ " signingConfig = signingConfigs.getByName(\"release\")",
2078
+ " }",
2079
+ " }",
2080
+ "}",
2081
+ SIGNING_END
2082
+ ].join("\n");
2083
+ }
2084
+ /**
2085
+ * Strips the moku-managed signing block (and the blank line it was inserted with) from
2086
+ * Gradle content, leaving content that never carried one untouched.
2087
+ *
2088
+ * @param existing - The current `build.gradle.kts` content.
2089
+ * @returns The content without a moku signing block.
2090
+ * @example
2091
+ * ```ts
2092
+ * removeSigningBlock(patchedGradleKts);
2093
+ * ```
2094
+ */
2095
+ function removeSigningBlock(existing) {
2096
+ const startIndex = existing.indexOf(SIGNING_START);
2097
+ const endIndex = existing.indexOf(SIGNING_END);
2098
+ if (startIndex === -1 || endIndex === -1) return existing;
2099
+ let before = existing.slice(0, startIndex);
2100
+ while (before.endsWith("\n")) before = before.slice(0, -1);
2101
+ let after = existing.slice(endIndex + 19);
2102
+ while (after.startsWith("\n")) after = after.slice(1);
2103
+ return before.length > 0 ? `${before}\n${after}` : after;
2104
+ }
2105
+ /**
2106
+ * Idempotently inserts, replaces or removes the moku-managed signing block inside an
2107
+ * existing `app/build.gradle.kts`. Re-applying to already-patched content is a text-level
2108
+ * no-op; an unconfigured keystore REMOVES a block a previous build left behind, so
2109
+ * dropping `signing.android.keystorePath` really does return to unsigned builds.
2110
+ *
2111
+ * @param existing - The current `build.gradle.kts` content.
2112
+ * @param signing - The Android signing config slice (empty object when unconfigured).
2113
+ * @returns The patched content with exactly one signing block, or none when unconfigured.
2114
+ * @example
2115
+ * ```ts
2116
+ * applySigningBlock(gradleKts, { keystorePath: "release.jks", keyAlias: "release" });
2117
+ * ```
2118
+ */
2119
+ function applySigningBlock(existing, signing) {
2120
+ if (!signing.keystorePath) return removeSigningBlock(existing);
2121
+ const block = renderSigningBlock(signing, signing.keystorePath);
2122
+ const startIndex = existing.indexOf(SIGNING_START);
2123
+ const endIndex = existing.indexOf(SIGNING_END);
2124
+ if (startIndex === -1 || endIndex === -1) return `${existing}${existing.endsWith("\n") ? "" : "\n"}\n${block}\n`;
2125
+ return `${existing.slice(0, startIndex)}${block}${existing.slice(endIndex + 19)}`;
2126
+ }
2127
+ /**
2128
+ * Patches Android release signing into `app/build.gradle.kts`, and clears the legacy
2129
+ * `keystore.properties` a previous version of this plugin wrote. Signing now lives in
2130
+ * Gradle only, so nothing ever re-creates that file.
2131
+ *
2132
+ * @param projectDirectory - The Tauri project root.
2133
+ * @param genDirectory - The `src-tauri/gen/android` directory.
2134
+ * @param signing - The Android signing config slice (empty object when unconfigured).
2135
+ * @returns The paths patched vs. left unchanged.
2136
+ * @example
2137
+ * ```ts
2138
+ * await patchAndroidSigning(projectDir, genDir, { keystorePath: "release.jks" });
2139
+ * ```
2140
+ */
2141
+ async function patchAndroidSigning(projectDirectory, genDirectory, signing) {
2142
+ const patched = [];
2143
+ const unchanged = [];
2144
+ const buildGradlePath = path.join(genDirectory, "app", "build.gradle.kts");
2145
+ (await writeIfChanged(buildGradlePath, applySigningBlock(await readFile(buildGradlePath, "utf8"), signing), projectDirectory) === "written" ? patched : unchanged).push(buildGradlePath);
2146
+ const keystorePropertiesPath = path.join(genDirectory, "keystore.properties");
2147
+ if (!signing.keystorePath && existsSync(keystorePropertiesPath)) {
2148
+ await rm(keystorePropertiesPath, { force: true });
2149
+ patched.push(keystorePropertiesPath);
2150
+ }
2151
+ return {
2152
+ patched,
2153
+ unchanged
2154
+ };
2155
+ }
1549
2156
  //#endregion
1550
2157
  //#region src/plugins/project/mobile/runner.ts
1551
2158
  /**
@@ -1554,6 +2161,11 @@ async function androidPatchFiles(genDirectory) {
1554
2161
  * generated Xcode/Android-Studio build phase, and none of those resolve inside those IDEs —
1555
2162
  * so an unpatched tree fails on its first build phase. Every occurrence becomes the
1556
2163
  * absolute `<node> <tauri.js>` pair the tauri plugin itself spawns with.
2164
+ *
2165
+ * Two shapes carry the runner. Xcode and older Android sources hold ONE command string
2166
+ * (`node tauri android android-studio-script`). The Android `BuildTask.kt` holds it as Kotlin
2167
+ * code instead: `val executable = """node""";` plus
2168
+ * `listOf("tauri", "android", "android-studio-script")`.
1557
2169
  */
1558
2170
  /** `tauri ios init` bakes `<detected-runner> ios xcode-script …` into the Xcode project. */
1559
2171
  const IOS_RUNNER_VERB = "ios xcode-script";
@@ -1572,16 +2184,47 @@ const WORD_SEPARATOR = String.raw`[ \t]+`;
1572
2184
  const WORD_BOUNDARY = String.raw`\b`;
1573
2185
  /** The already-patched form: the `<node> <tauri.js>` pair, each word quoted. */
1574
2186
  const ABSOLUTE_RUNNER_PAIR = `${QUOTED_RUNNER_WORD}${WORD_SEPARATOR}${QUOTED_RUNNER_WORD}`;
2187
+ /** Binaries Tauri may have detected the CLI behind, optionally through an absolute path. */
2188
+ const RUNNER_BINARIES = "node|bunx|bun|npx|yarn|pnpm|cargo";
2189
+ /**
2190
+ * The optional directory a detected runner is path-qualified with (`/opt/homebrew/bin/`).
2191
+ * It never contains a quote or a backslash: those belong to the string literal around the
2192
+ * command (`shellScript = "…`, a Kotlin `"…"`), and eating the opening quote leaves a
2193
+ * pbxproj Xcode refuses to open.
2194
+ */
2195
+ const RUNNER_PATH_PREFIX = String.raw`(?:[^\s"\\]*/)?`;
1575
2196
  /**
1576
2197
  * Every runner shape `tauri ios|android init` bakes in: `<binary> tauri`, npm's
1577
2198
  * `npm run tauri --` form, or a bare `tauri` — each optionally path-qualified. Longest
1578
2199
  * alternative first, so `npm run tauri --` is never truncated to its trailing `tauri`.
1579
2200
  */
1580
- const PACKAGE_RUNNER = String.raw`(?:\S*/)?npm run tauri --|(?:\S*/)?(?:${"node|bunx|bun|npx|yarn|pnpm|cargo"}) tauri|(?:\S*/)?tauri`;
2201
+ const PACKAGE_RUNNER = [
2202
+ `${RUNNER_PATH_PREFIX}npm run tauri --`,
2203
+ `${RUNNER_PATH_PREFIX}(?:${RUNNER_BINARIES}) tauri`,
2204
+ `${RUNNER_PATH_PREFIX}tauri`
2205
+ ].join("|");
1581
2206
  /** Characters that would break out of the double-quoted shell word a runner path lands in. */
1582
2207
  const SHELL_METACHARACTER_PATTERN = /[\\"$`]/g;
1583
2208
  /** A line break inside a runner path would split the generated build phase into two commands. */
1584
2209
  const LINE_BREAK_PATTERN = /[\n\r]/;
2210
+ /**
2211
+ * Characters a raw Kotlin string (`"""…"""`) cannot hold as they are. A raw string has no
2212
+ * backslash escapes, so `$` (a template) and `"` (part of the closing `"""`) are written as
2213
+ * `${'$'}` / `${'"'}` templates. A backslash is literal there and stays as it is.
2214
+ */
2215
+ const KOTLIN_RAW_STRING_SPECIAL_PATTERN = /["$]/g;
2216
+ /** The Android verb as `BuildTask.kt` passes it: two separate `listOf` arguments. */
2217
+ const KOTLIN_VERB_ARGUMENTS = String.raw`"android"\s*,\s*"android-studio-script"`;
2218
+ /** One plain Kotlin string literal on one line, backslash escapes included. */
2219
+ const KOTLIN_STRING_LITERAL = String.raw`"(?:[^"\\\n]|\\.)*"`;
2220
+ /**
2221
+ * The runner arguments of the `BuildTask.kt` `listOf(…)`: every string literal before the
2222
+ * verb pair (`"tauri"`, npm's `"run", "--", "tauri"`, an already-patched `"<tauri.js>"`).
2223
+ * Group 1 is the `listOf(` opener, kept as it is.
2224
+ */
2225
+ const KOTLIN_RUNNER_ARGUMENTS = String.raw`(listOf\(\s*)(?:${KOTLIN_STRING_LITERAL}\s*,\s*)*?(?=${KOTLIN_VERB_ARGUMENTS})`;
2226
+ /** The raw-string body of `val executable = """…"""`. Group 1 is everything up to the body. */
2227
+ const KOTLIN_EXECUTABLE = String.raw`(\bval\s+executable\s*=\s*""")[^\n]*?(?=""")`;
1585
2228
  /** Regex metacharacters, escaped before a caller-supplied verb is embedded in a pattern. */
1586
2229
  const REGEX_METACHARACTER_PATTERN = /[.*+?^${}()|[\]\\]/g;
1587
2230
  /**
@@ -1673,10 +2316,96 @@ function unknownRunnerError(verb, filePath) {
1673
2316
  * ```
1674
2317
  */
1675
2318
  function escapeRunnerPath(value) {
1676
- 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.`);
2319
+ assertSingleLine(value);
1677
2320
  return value.replaceAll(SHELL_METACHARACTER_PATTERN, (match) => `\\${match}`);
1678
2321
  }
1679
2322
  /**
2323
+ * Refuses a runner path with a line break. In a shell build phase it would split the command
2324
+ * in two; in a Kotlin literal it would end the line mid-string.
2325
+ *
2326
+ * @param value - The absolute path to check.
2327
+ * @throws {Error} `[native]` when the path contains a line break.
2328
+ * @example
2329
+ * ```ts
2330
+ * assertSingleLine("/opt/homebrew/bin/node"); // passes
2331
+ * ```
2332
+ */
2333
+ function assertSingleLine(value) {
2334
+ if (!LINE_BREAK_PATTERN.test(value)) return;
2335
+ 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.`);
2336
+ }
2337
+ /**
2338
+ * Escapes one runner path for a raw Kotlin string (`"""…"""`), which has no backslash
2339
+ * escapes: `$` and `"` become `${'$'}` / `${'"'}` templates, everything else stays as it is.
2340
+ *
2341
+ * @param value - The absolute path to escape.
2342
+ * @returns The raw string's body.
2343
+ * @throws {Error} `[native]` when the path contains a line break.
2344
+ * @example
2345
+ * ```ts
2346
+ * kotlinRawStringBody("/opt/node $HOME/bin/node"); // "/opt/node ${'$'}HOME/bin/node"
2347
+ * ```
2348
+ */
2349
+ function kotlinRawStringBody(value) {
2350
+ assertSingleLine(value);
2351
+ return value.replaceAll(KOTLIN_RAW_STRING_SPECIAL_PATTERN, (match) => `\${'${match}'}`);
2352
+ }
2353
+ /**
2354
+ * Tests whether a file passes the Android verb as Kotlin `listOf` arguments at all.
2355
+ *
2356
+ * @param content - The file content to search.
2357
+ * @returns Whether `"android", "android-studio-script"` appears.
2358
+ * @example
2359
+ * ```ts
2360
+ * mentionsKotlinVerb('listOf("tauri", "android", "android-studio-script")'); // true
2361
+ * ```
2362
+ */
2363
+ function mentionsKotlinVerb(content) {
2364
+ return new RegExp(KOTLIN_VERB_ARGUMENTS).test(content);
2365
+ }
2366
+ /**
2367
+ * Tests whether a file carries the full `BuildTask.kt` runner shape: the `listOf` arguments
2368
+ * AND the raw-string `executable`. Rewriting only one of them still leaves a broken runner.
2369
+ *
2370
+ * @param content - The file content to search.
2371
+ * @returns Whether both parts of the Kotlin runner are present.
2372
+ * @example
2373
+ * ```ts
2374
+ * hasKotlinRunner(buildTaskSource); // true for the tauri 2.12 template
2375
+ * ```
2376
+ */
2377
+ function hasKotlinRunner(content) {
2378
+ return new RegExp(KOTLIN_RUNNER_ARGUMENTS).test(content) && new RegExp(KOTLIN_EXECUTABLE).test(content);
2379
+ }
2380
+ /**
2381
+ * Rewrites the runner `tauri android init` bakes into `BuildTask.kt` as Kotlin code: the
2382
+ * raw-string `executable` becomes the absolute Node path, and the `listOf` arguments before
2383
+ * `"android", "android-studio-script"` become the one absolute `tauri.js` path. Gradle runs
2384
+ * the executable directly, with no shell, so each path is escaped for its Kotlin literal
2385
+ * only. Everything else is kept byte for byte. A file without that `listOf` is returned as
2386
+ * it is, executable included.
2387
+ *
2388
+ * @param existing - The file content to rewrite.
2389
+ * @param runner - The absolute Node and `tauri.js` paths.
2390
+ * @returns The rewritten content (a no-op once already rewritten onto this runner).
2391
+ * @throws {Error} `[native]` when a runner path contains a line break.
2392
+ * @example
2393
+ * ```ts
2394
+ * applyKotlinRunner('val executable = """node""";\nval args = listOf("tauri", "android", "android-studio-script");', {
2395
+ * nodePath: "/opt/homebrew/bin/node",
2396
+ * tauriJsPath: "/repo/node_modules/@tauri-apps/cli/tauri.js"
2397
+ * });
2398
+ * // 'val executable = """/opt/homebrew/bin/node""";\nval args = listOf("/repo/node_modules/@tauri-apps/cli/tauri.js", "android", "android-studio-script");'
2399
+ * ```
2400
+ */
2401
+ function applyKotlinRunner(existing, runner) {
2402
+ if (!new RegExp(KOTLIN_RUNNER_ARGUMENTS).test(existing)) return existing;
2403
+ const executable = kotlinRawStringBody(runner.nodePath);
2404
+ assertSingleLine(runner.tauriJsPath);
2405
+ const tauriJsArgument = `"${kotlinString(runner.tauriJsPath)}", `;
2406
+ return existing.replaceAll(new RegExp(KOTLIN_EXECUTABLE, "g"), (_match, open) => open + executable).replaceAll(new RegExp(KOTLIN_RUNNER_ARGUMENTS, "g"), (_match, open) => open + tauriJsArgument);
2407
+ }
2408
+ /**
1680
2409
  * Rewrites the runner Tauri baked into a generated build phase into an absolute
1681
2410
  * `<node> <tauri.js> <verb>` invocation. Only the runner-shaped token run directly before
1682
2411
  * the verb is replaced — anything else on the line (indentation, a `script:` key, a
@@ -1717,12 +2446,54 @@ function quoteFor(filePath) {
1717
2446
  return filePath.endsWith(".yml") ? "\"" : ESCAPED_QUOTE;
1718
2447
  }
1719
2448
  /**
2449
+ * Tests whether every runner a file carries is one this rewrite recognizes. A file that
2450
+ * never mentions the verb passes: it has no runner to rewrite.
2451
+ *
2452
+ * @param content - The file content to check.
2453
+ * @param verb - The Tauri verb the build phase invokes.
2454
+ * @returns Whether the rewrite can patch the file completely.
2455
+ * @example
2456
+ * ```ts
2457
+ * isRecognizedRunner('val command = "deno task tauri-cli android android-studio-script"', "android android-studio-script"); // false
2458
+ * ```
2459
+ */
2460
+ function isRecognizedRunner(content, verb) {
2461
+ if (mentionsRunnerVerb(content, verb) && !hasRunnerCommand(content, verb)) return false;
2462
+ return !(verb === ANDROID_RUNNER_VERB && mentionsKotlinVerb(content)) || hasKotlinRunner(content);
2463
+ }
2464
+ /**
2465
+ * Rewrites every runner shape a platform's file may carry: the one-string command, and on
2466
+ * Android also the Kotlin `BuildTask.kt` shape.
2467
+ *
2468
+ * @param existing - The file content to rewrite.
2469
+ * @param filePath - The file being patched, which picks the quote form.
2470
+ * @param options - How to rewrite the command.
2471
+ * @param options.runner - The absolute Node and `tauri.js` paths.
2472
+ * @param options.verb - The Tauri verb the build phase invokes.
2473
+ * @returns The rewritten content.
2474
+ * @example
2475
+ * ```ts
2476
+ * rewriteRunner(buildTaskSource, buildTaskPath, { runner, verb: "android android-studio-script" });
2477
+ * ```
2478
+ */
2479
+ function rewriteRunner(existing, filePath, options) {
2480
+ const { runner, verb } = options;
2481
+ const rewritten = applyRunnerCommand(existing, {
2482
+ runner,
2483
+ verb,
2484
+ quote: quoteFor(filePath)
2485
+ });
2486
+ if (verb !== ANDROID_RUNNER_VERB) return rewritten;
2487
+ return applyKotlinRunner(rewritten, runner);
2488
+ }
2489
+ /**
1720
2490
  * Applies the runner rewrite to every candidate file for a platform, reporting which
1721
2491
  * files actually changed. A second pass rewrites the absolute pair onto itself and
1722
2492
  * reports everything unchanged.
1723
2493
  *
1724
2494
  * A file that invokes the verb but carries a runner shape this rewrite does not recognize
1725
- * is an ERROR, not an "unchanged" file: Tauri baked in a command that will not resolve
2495
+ * (on Android also: a `listOf(…, "android", "android-studio-script")` without the
2496
+ * `val executable = """…"""` beside it) is an ERROR, not an "unchanged" file: Tauri baked in a command that will not resolve
1726
2497
  * inside Xcode/Android Studio, and reporting success there means the failure surfaces much
1727
2498
  * later, as an opaque build-phase exit. A file that never mentions the verb is simply
1728
2499
  * unchanged.
@@ -1746,11 +2517,10 @@ async function patchRunner(projectDirectory, genDirectory, opts) {
1746
2517
  const unchanged = [];
1747
2518
  for (const file of files) {
1748
2519
  const existing = await readFile(file, "utf8");
1749
- if (mentionsRunnerVerb(existing, verb) && !hasRunnerCommand(existing, verb)) throw unknownRunnerError(verb, file);
1750
- (await writeIfChanged(file, applyRunnerCommand(existing, {
2520
+ if (!isRecognizedRunner(existing, verb)) throw unknownRunnerError(verb, file);
2521
+ (await writeIfChanged(file, rewriteRunner(existing, file, {
1751
2522
  runner: opts.runner,
1752
- verb,
1753
- quote: quoteFor(file)
2523
+ verb
1754
2524
  }), projectDirectory) === "written" ? patched : unchanged).push(file);
1755
2525
  }
1756
2526
  return {
@@ -1759,152 +2529,268 @@ async function patchRunner(projectDirectory, genDirectory, opts) {
1759
2529
  };
1760
2530
  }
1761
2531
  //#endregion
1762
- //#region src/plugins/project/mobile/signing.ts
2532
+ //#region src/plugins/project/mobile/system-bars.ts
2533
+ /**
2534
+ * @file project plugin — the Android system bar patch. The generated MainActivity.kt
2535
+ * calls `enableEdgeToEdge()`, whose default `SystemBarStyle.auto` picks the status bar
2536
+ * icon colour from the SYSTEM night mode, not from the app. A dark app on a light-mode
2537
+ * phone then gets dark icons on a dark page. When `app.backgroundColor` is set, this patch
2538
+ * rewrites that one call so the icons follow the colour's luminance instead.
2539
+ *
2540
+ * The transform is a pure text function: only the call and the two imports it needs
2541
+ * change, every other byte (line endings included) survives, a second pass is a no-op, and
2542
+ * unsetting the colour restores the generated call.
2543
+ */
2544
+ /**
2545
+ * A background whose relative luminance is below this is dark, so it gets light icons.
2546
+ * Where white and black icons have equal WCAG contrast: sqrt(1.05 * 0.05) - 0.05.
2547
+ */
2548
+ const DARK_LUMINANCE_THRESHOLD = .179;
2549
+ /** `#rrggbb` or `#rrggbbaa`, the three colour channels captured; alpha is ignored. */
2550
+ const HEX_CHANNELS_PATTERN = /^#([\da-f]{2})([\da-f]{2})([\da-f]{2})(?:[\da-f]{2})?$/i;
2551
+ /** The Rec. 709 weights of red, green and blue in relative luminance. */
2552
+ const LUMINANCE_WEIGHTS = [
2553
+ .2126,
2554
+ .7152,
2555
+ .0722
2556
+ ];
2557
+ /** What marks the generated activity: it is the file that turns edge-to-edge on. */
2558
+ const EDGE_TO_EDGE_CALL = "enableEdgeToEdge(";
2559
+ /** The call exactly as `tauri android init` (cli 2.12) writes it. */
2560
+ const BARE_CALL = "enableEdgeToEdge()";
1763
2561
  /**
1764
- * @file project plugin — the Android release-signing block the mobile patch pass keeps in
1765
- * `gen/android/app/build.gradle.kts`. Only env-var NAMES are ever written to disk: Gradle
1766
- * reads the passwords itself, at build time.
2562
+ * Builds the styled call: both bars get the same style, with a transparent scrim so the
2563
+ * page still draws behind them.
2564
+ *
2565
+ * @param style - The Kotlin `SystemBarStyle` expression for both bars.
2566
+ * @returns The `enableEdgeToEdge(...)` call.
2567
+ * @example
2568
+ * ```ts
2569
+ * styledCall("SystemBarStyle.dark(Color.TRANSPARENT)");
2570
+ * // "enableEdgeToEdge(statusBarStyle = SystemBarStyle.dark(Color.TRANSPARENT), navigationBarStyle = SystemBarStyle.dark(Color.TRANSPARENT))"
2571
+ * ```
1767
2572
  */
1768
- const SIGNING_START = "// MOKU-SIGNING-START";
1769
- const SIGNING_END = "// MOKU-SIGNING-END";
2573
+ function styledCall(style) {
2574
+ return `enableEdgeToEdge(statusBarStyle = ${style}, navigationBarStyle = ${style})`;
2575
+ }
2576
+ /** The call this patch writes per tone: `dark()` draws light icons, `light()` dark ones. */
2577
+ const STYLED_CALLS = {
2578
+ dark: styledCall("SystemBarStyle.dark(Color.TRANSPARENT)"),
2579
+ light: styledCall("SystemBarStyle.light(Color.TRANSPARENT, Color.TRANSPARENT)")
2580
+ };
2581
+ /** Every call this patch may replace: the generated one and its own two rewrites. */
2582
+ const KNOWN_CALLS = [
2583
+ BARE_CALL,
2584
+ STYLED_CALLS.dark,
2585
+ STYLED_CALLS.light
2586
+ ];
2587
+ /** The imports the styled call needs, in the order they are added after the last import. */
2588
+ const STYLE_IMPORTS = [{
2589
+ line: "import androidx.activity.SystemBarStyle",
2590
+ usage: /\bSystemBarStyle\b/
2591
+ }, {
2592
+ line: "import android.graphics.Color",
2593
+ usage: /\bColor\b/
2594
+ }];
2595
+ /** One Kotlin import line, without its line ending. */
2596
+ const IMPORT_LINE_PATTERN = /^import [^\r\n]*/gm;
2597
+ /** The carriage return a CRLF line keeps after a split on `\n`. */
2598
+ const TRAILING_CARRIAGE_RETURN = /\r$/;
1770
2599
  /**
1771
- * Characters that change the meaning of a Kotlin string literal: a backslash starts an
1772
- * escape, a double quote closes the literal, a dollar sign starts a template expression,
1773
- * and a raw newline ends the line outright.
2600
+ * Builds the `[native]` error for a MainActivity.kt whose edge-to-edge call this patch
2601
+ * does not recognise.
2602
+ *
2603
+ * @param filePath - The MainActivity.kt that was read.
2604
+ * @returns A formatted `[native] ...` error.
2605
+ * @example
2606
+ * ```ts
2607
+ * throw unknownCallError("/repo/.moku/tauri/src-tauri/gen/android/app/src/main/java/com/acme/demo/MainActivity.kt");
2608
+ * ```
1774
2609
  */
1775
- const KOTLIN_ESCAPES = [
1776
- [/\\/g, String.raw`\\`],
1777
- [/"/g, String.raw`\"`],
1778
- [/\$/g, String.raw`\$`],
1779
- [/\r/g, String.raw`\r`],
1780
- [/\n/g, String.raw`\n`]
1781
- ];
2610
+ function unknownCallError(filePath) {
2611
+ 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.`);
2612
+ }
1782
2613
  /**
1783
- * Escapes a value for use inside a double-quoted Kotlin string literal. Config values land
1784
- * verbatim in `build.gradle.kts` — an unescaped `"` would close the literal and an
1785
- * unescaped `$` would interpolate a Gradle expression, so every one of them is escaped
1786
- * here rather than trusted.
2614
+ * Builds the `[native]` error for a MainActivity.kt with no import line, so the system bar
2615
+ * imports have no place to go.
1787
2616
  *
1788
- * @param value - The raw config value (keystore path, key alias, env-var name).
1789
- * @returns The value, safe to place between double quotes in Kotlin source.
2617
+ * @param filePath - The MainActivity.kt that was read.
2618
+ * @returns A formatted `[native] ...` error.
1790
2619
  * @example
1791
2620
  * ```ts
1792
- * kotlinString('re"lease$HOME'); // 're\\"lease\\$HOME'
2621
+ * throw noImportLineError("/repo/.moku/tauri/src-tauri/gen/android/app/src/main/java/com/acme/demo/MainActivity.kt");
1793
2622
  * ```
1794
2623
  */
1795
- function kotlinString(value) {
1796
- let escaped = value;
1797
- for (const [pattern, replacement] of KOTLIN_ESCAPES) escaped = escaped.replace(pattern, replacement);
1798
- return escaped;
2624
+ function noImportLineError(filePath) {
2625
+ 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.`);
1799
2626
  }
1800
2627
  /**
1801
- * Renders the moku-managed Gradle signing block. Passwords are read by Gradle itself from
1802
- * the environment at build time — only env-var NAMES are ever written to disk, per the
1803
- * `SigningConfig` invariant. `keyPasswordEnv` falls back to `keystorePasswordEnv`, which
1804
- * is the common single-password keystore. Every interpolated value goes through
1805
- * {@link kotlinString}, so a path or alias can never close the literal it sits in.
2628
+ * Builds the `[native]` error for a gen tree without exactly one MainActivity.kt that calls
2629
+ * `enableEdgeToEdge()`.
1806
2630
  *
1807
- * @param signing - The Android signing config slice, with a keystore path already present.
1808
- * @param keystorePath - The configured keystore path.
1809
- * @returns The sentinel-delimited Gradle block.
2631
+ * @param javaDirectory - The `app/src/main/java` directory that was searched.
2632
+ * @param found - The candidates found, sorted; empty when there were none.
2633
+ * @returns A formatted `[native] ...` error.
1810
2634
  * @example
1811
2635
  * ```ts
1812
- * renderSigningBlock({ keyAlias: "release" }, "release.jks");
2636
+ * throw notOneActivityError("/repo/.moku/tauri/src-tauri/gen/android/app/src/main/java", []);
1813
2637
  * ```
1814
2638
  */
1815
- function renderSigningBlock(signing, keystorePath) {
1816
- const storePasswordEnvironment = signing.keystorePasswordEnv ?? "";
1817
- const keyPasswordEnvironment = signing.keyPasswordEnv ?? storePasswordEnvironment;
1818
- return [
1819
- SIGNING_START,
1820
- "android {",
1821
- " signingConfigs {",
1822
- " maybeCreate(\"release\").apply {",
1823
- ` storeFile = file("${kotlinString(keystorePath)}")`,
1824
- ` keyAlias = "${kotlinString(signing.keyAlias ?? "")}"`,
1825
- ` storePassword = System.getenv("${kotlinString(storePasswordEnvironment)}")`,
1826
- ` keyPassword = System.getenv("${kotlinString(keyPasswordEnvironment)}")`,
1827
- " }",
1828
- " }",
1829
- " buildTypes {",
1830
- " getByName(\"release\") {",
1831
- " signingConfig = signingConfigs.getByName(\"release\")",
1832
- " }",
1833
- " }",
1834
- "}",
1835
- SIGNING_END
1836
- ].join("\n");
2639
+ function notOneActivityError(javaDirectory, found) {
2640
+ 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.`);
2641
+ 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).`);
1837
2642
  }
1838
2643
  /**
1839
- * Strips the moku-managed signing block (and the blank line it was inserted with) from
1840
- * Gradle content, leaving content that never carried one untouched.
2644
+ * Linearises one sRGB channel, the transfer curve relative luminance is defined on.
1841
2645
  *
1842
- * @param existing - The current `build.gradle.kts` content.
1843
- * @returns The content without a moku signing block.
2646
+ * @param hexPair - The channel as two hex digits.
2647
+ * @returns The linear channel value, 0 to 1.
1844
2648
  * @example
1845
2649
  * ```ts
1846
- * removeSigningBlock(patchedGradleKts);
2650
+ * linearChannel("ff"); // 1
2651
+ * linearChannel("00"); // 0
1847
2652
  * ```
1848
2653
  */
1849
- function removeSigningBlock(existing) {
1850
- const startIndex = existing.indexOf(SIGNING_START);
1851
- const endIndex = existing.indexOf(SIGNING_END);
1852
- if (startIndex === -1 || endIndex === -1) return existing;
1853
- let before = existing.slice(0, startIndex);
1854
- while (before.endsWith("\n")) before = before.slice(0, -1);
1855
- let after = existing.slice(endIndex + 19);
1856
- while (after.startsWith("\n")) after = after.slice(1);
1857
- return before.length > 0 ? `${before}\n${after}` : after;
2654
+ function linearChannel(hexPair) {
2655
+ const encoded = Number.parseInt(hexPair, 16) / 255;
2656
+ return encoded <= .04045 ? encoded / 12.92 : ((encoded + .055) / 1.055) ** 2.4;
1858
2657
  }
1859
2658
  /**
1860
- * Idempotently inserts, replaces or removes the moku-managed signing block inside an
1861
- * existing `app/build.gradle.kts`. Re-applying to already-patched content is a text-level
1862
- * no-op; an unconfigured keystore REMOVES a block a previous build left behind, so
1863
- * dropping `signing.android.keystorePath` really does return to unsigned builds.
2659
+ * Tells a dark background from a light one by its relative luminance (WCAG), alpha
2660
+ * ignored. Below {@link DARK_LUMINANCE_THRESHOLD} the background is dark.
1864
2661
  *
1865
- * @param existing - The current `build.gradle.kts` content.
1866
- * @param signing - The Android signing config slice (empty object when unconfigured).
1867
- * @returns The patched content with exactly one signing block, or none when unconfigured.
2662
+ * @param colour - The `app.backgroundColor` value, `#rrggbb` or `#rrggbbaa`.
2663
+ * @returns `"dark"` when the background wants light icons, `"light"` when it wants dark ones.
2664
+ * @throws {Error} `[native]` when the value is not a hex colour.
1868
2665
  * @example
1869
2666
  * ```ts
1870
- * applySigningBlock(gradleKts, { keystorePath: "release.jks", keyAlias: "release" });
2667
+ * backgroundTone("#10161d"); // "dark"
2668
+ * backgroundTone("#ffffffff"); // "light"
1871
2669
  * ```
1872
2670
  */
1873
- function applySigningBlock(existing, signing) {
1874
- if (!signing.keystorePath) return removeSigningBlock(existing);
1875
- const block = renderSigningBlock(signing, signing.keystorePath);
1876
- const startIndex = existing.indexOf(SIGNING_START);
1877
- const endIndex = existing.indexOf(SIGNING_END);
1878
- if (startIndex === -1 || endIndex === -1) return `${existing}${existing.endsWith("\n") ? "" : "\n"}\n${block}\n`;
1879
- return `${existing.slice(0, startIndex)}${block}${existing.slice(endIndex + 19)}`;
2671
+ function backgroundTone(colour) {
2672
+ const channels = HEX_CHANNELS_PATTERN.exec(colour)?.slice(1);
2673
+ if (!channels) throw new Error(`[native] app.backgroundColor "${colour}" is not a valid colour.\n Use a hex colour such as "#10161d".`);
2674
+ return channels.reduce((sum, channel, index) => sum + (LUMINANCE_WEIGHTS[index] ?? 0) * linearChannel(channel), 0) < DARK_LUMINANCE_THRESHOLD ? "dark" : "light";
1880
2675
  }
1881
2676
  /**
1882
- * Patches Android release signing into `app/build.gradle.kts`, and clears the legacy
1883
- * `keystore.properties` a previous version of this plugin wrote. Signing now lives in
1884
- * Gradle only, so nothing ever re-creates that file.
2677
+ * Adds the imports the styled call needs, each on its own line after the last import, in
2678
+ * the file's own line ending. An import already present is not added again.
2679
+ *
2680
+ * @param source - The MainActivity.kt content, call already styled.
2681
+ * @param filePath - The MainActivity.kt path, named in the error.
2682
+ * @returns The content with both imports present.
2683
+ * @throws {Error} `[native]` when the file has no import line to add them after.
2684
+ * @example
2685
+ * ```ts
2686
+ * addStyleImports("import android.os.Bundle\n\nclass A", "MainActivity.kt");
2687
+ * // "import android.os.Bundle\nimport androidx.activity.SystemBarStyle\nimport android.graphics.Color\n\nclass A"
2688
+ * ```
2689
+ */
2690
+ function addStyleImports(source, filePath) {
2691
+ const lineEnding = source.includes("\r\n") ? "\r\n" : "\n";
2692
+ let result = source;
2693
+ for (const styleImport of STYLE_IMPORTS) {
2694
+ if (result.split(/\r?\n/).includes(styleImport.line)) continue;
2695
+ const lastImport = [...result.matchAll(IMPORT_LINE_PATTERN)].at(-1);
2696
+ if (!lastImport) throw noImportLineError(filePath);
2697
+ const end = lastImport.index + lastImport[0].length;
2698
+ result = `${result.slice(0, end)}${lineEnding}${styleImport.line}${result.slice(end)}`;
2699
+ }
2700
+ return result;
2701
+ }
2702
+ /**
2703
+ * Removes the style imports nothing uses any more, each with its own line. An import that
2704
+ * other code still uses stays, so a file that imported `Color` itself keeps it.
2705
+ *
2706
+ * @param source - The MainActivity.kt content, call already restored to bare.
2707
+ * @returns The content without the unused style imports.
2708
+ * @example
2709
+ * ```ts
2710
+ * removeUnusedStyleImports("import android.os.Bundle\nimport android.graphics.Color\n\nclass A");
2711
+ * // "import android.os.Bundle\n\nclass A"
2712
+ * ```
2713
+ */
2714
+ function removeUnusedStyleImports(source) {
2715
+ let lines = source.split("\n");
2716
+ for (const styleImport of STYLE_IMPORTS) {
2717
+ if (lines.filter((line) => !line.startsWith("import ")).some((line) => styleImport.usage.test(line))) continue;
2718
+ lines = lines.filter((line) => line.replace(TRAILING_CARRIAGE_RETURN, "") !== styleImport.line);
2719
+ }
2720
+ return lines.join("\n");
2721
+ }
2722
+ /**
2723
+ * Sets the system bar style of a MainActivity.kt. A tone writes the styled call and adds
2724
+ * its imports; no tone restores the bare generated call and drops the imports nothing else
2725
+ * uses. Only a call this patch knows is touched: the generated one, or one of its own
2726
+ * rewrites.
2727
+ *
2728
+ * @param source - The MainActivity.kt content.
2729
+ * @param tone - The background's tone, or undefined when `app.backgroundColor` is unset.
2730
+ * @param filePath - The MainActivity.kt path, named in the error.
2731
+ * @returns The content with the style applied.
2732
+ * @throws {Error} `[native]` when a tone is set and the call is not one this patch knows.
2733
+ * @example
2734
+ * ```ts
2735
+ * applySystemBarStyle("import androidx.activity.enableEdgeToEdge\n\nenableEdgeToEdge()\n", "dark", "MainActivity.kt");
2736
+ * // "import androidx.activity.enableEdgeToEdge\nimport androidx.activity.SystemBarStyle\nimport android.graphics.Color\n\n"
2737
+ * // + "enableEdgeToEdge(statusBarStyle = SystemBarStyle.dark(Color.TRANSPARENT), navigationBarStyle = SystemBarStyle.dark(Color.TRANSPARENT))\n"
2738
+ * ```
2739
+ */
2740
+ function applySystemBarStyle(source, tone, filePath) {
2741
+ if (!KNOWN_CALLS.some((call) => source.includes(call))) {
2742
+ if (tone === void 0) return source;
2743
+ throw unknownCallError(filePath);
2744
+ }
2745
+ const wanted = tone === void 0 ? BARE_CALL : STYLED_CALLS[tone];
2746
+ let result = source;
2747
+ for (const call of KNOWN_CALLS) result = result.replaceAll(call, () => wanted);
2748
+ return tone === void 0 ? removeUnusedStyleImports(result) : addStyleImports(result, filePath);
2749
+ }
2750
+ /**
2751
+ * Styles the Android system bars from `app.backgroundColor`, through the write-if-changed
2752
+ * writer. The target is the one MainActivity.kt below `gen/android/app/src/main/java` that
2753
+ * calls `enableEdgeToEdge()`. Without a colour a missing or ambiguous activity is left
2754
+ * alone, so an app that never set one keeps building; with one it is an error.
1885
2755
  *
1886
2756
  * @param projectDirectory - The Tauri project root.
1887
2757
  * @param genDirectory - The `src-tauri/gen/android` directory.
1888
- * @param signing - The Android signing config slice (empty object when unconfigured).
1889
- * @returns The paths patched vs. left unchanged.
2758
+ * @param backgroundColor - `app.backgroundColor`, or undefined when unset.
2759
+ * @returns The MainActivity.kt path, patched or unchanged; empty when there was none to touch.
2760
+ * @throws {Error} `[native]` when a colour is set and there is not exactly one MainActivity.kt
2761
+ * calling `enableEdgeToEdge()`, or its call is not one this patch knows.
1890
2762
  * @example
1891
2763
  * ```ts
1892
- * await patchAndroidSigning(projectDir, genDir, { keystorePath: "release.jks" });
2764
+ * // First pass on the generated activity; a second pass lists it under `unchanged`.
2765
+ * await patchAndroidSystemBars(".moku/tauri", ".moku/tauri/src-tauri/gen/android", "#10161d");
2766
+ * // { patched: [".moku/tauri/src-tauri/gen/android/app/src/main/java/com/acme/demo/MainActivity.kt"], unchanged: [] }
1893
2767
  * ```
1894
2768
  */
1895
- async function patchAndroidSigning(projectDirectory, genDirectory, signing) {
1896
- const patched = [];
1897
- const unchanged = [];
1898
- const buildGradlePath = path.join(genDirectory, "app", "build.gradle.kts");
1899
- (await writeIfChanged(buildGradlePath, applySigningBlock(await readFile(buildGradlePath, "utf8"), signing), projectDirectory) === "written" ? patched : unchanged).push(buildGradlePath);
1900
- const keystorePropertiesPath = path.join(genDirectory, "keystore.properties");
1901
- if (!signing.keystorePath && existsSync(keystorePropertiesPath)) {
1902
- await rm(keystorePropertiesPath, { force: true });
1903
- patched.push(keystorePropertiesPath);
2769
+ async function patchAndroidSystemBars(projectDirectory, genDirectory, backgroundColor) {
2770
+ const tone = backgroundColor === void 0 ? void 0 : backgroundTone(backgroundColor);
2771
+ const activities = [];
2772
+ for (const file of await androidMainActivityFiles(genDirectory)) {
2773
+ const source = await readFile(file, "utf8");
2774
+ if (source.includes(EDGE_TO_EDGE_CALL)) activities.push({
2775
+ path: file,
2776
+ source
2777
+ });
1904
2778
  }
1905
- return {
1906
- patched,
1907
- unchanged
2779
+ const [activity] = activities;
2780
+ if (activities.length !== 1 || !activity) {
2781
+ if (tone === void 0) return {
2782
+ patched: [],
2783
+ unchanged: []
2784
+ };
2785
+ throw notOneActivityError(androidJavaDirectory(genDirectory), activities.map((candidate) => candidate.path));
2786
+ }
2787
+ const patchedSource = applySystemBarStyle(activity.source, tone, activity.path);
2788
+ return await writeIfChanged(activity.path, patchedSource, projectDirectory) === "written" ? {
2789
+ patched: [activity.path],
2790
+ unchanged: []
2791
+ } : {
2792
+ patched: [],
2793
+ unchanged: [activity.path]
1908
2794
  };
1909
2795
  }
1910
2796
  //#endregion
@@ -2226,7 +3112,9 @@ async function patchXcodeSettings(projectDirectory, genDirectory) {
2226
3112
  /**
2227
3113
  * @file project plugin — the post-init mobile patch pass: it decides WHICH patches a
2228
3114
  * platform needs and in which order. The patches themselves live next door, in
2229
- * `signing.ts` (the Android release-signing block), `runner.ts` (the Xcode /
3115
+ * `signing.ts` (the Android release-signing block), `manifest.ts` (the Android main
3116
+ * activity's attributes, such as the orientation lock), `system-bars.ts` (the Android
3117
+ * status bar icon style from `app.backgroundColor`), `runner.ts` (the Xcode /
2230
3118
  * Android-Studio runner command) and `xcode-settings.ts` (the iOS
2231
3119
  * entitlements-modification setting that makes a REBUILD work).
2232
3120
  */
@@ -2251,23 +3139,30 @@ function mergePatchResults(...results) {
2251
3139
  }
2252
3140
  /**
2253
3141
  * Deterministic, idempotent post-init patch pass over an existing complete gen/ tree.
2254
- * Android gets its release signing block; iOS gets the Xcode entitlements-modification
2255
- * setting (without it the SECOND build of the same tree fails); both platforms get the
2256
- * runner-command rewrite when the caller supplies a `runner` (omit it and the rewrite is
2257
- * skipped). iOS carries no mobile-permission plist mechanism in v1 (D-012), so signing is
2258
- * conf-only there.
3142
+ * Android gets, in this order, its release signing block, the main activity's manifest
3143
+ * attributes, the system bar style in MainActivity.kt, then the runner command. iOS gets
3144
+ * the Xcode entitlements-modification setting (without it the SECOND build of the same
3145
+ * tree fails), then the runner command. The runner rewrite runs only when the caller
3146
+ * supplies a `runner`. iOS takes no manifest entries and no background colour: its
3147
+ * orientation lock and signing travel through the generated `Info.ios.plist` sidecar and
3148
+ * tauri.conf.json, and its status bar adapts to the page on its own.
2259
3149
  *
2260
3150
  * @param projectDirectory - The Tauri project root.
2261
3151
  * @param opts - The mobile platform, and optionally the absolute Node/tauri.js runner pair.
2262
3152
  * @param signing - The full signing config (only `.android` is consulted).
2263
- * @returns The paths patched vs. left unchanged.
2264
- * @throws {Error} When the Android `gen/android` tree (or its `app/build.gradle.kts`) is missing.
3153
+ * @param manifest - Android manifest entries for the main activity (ignored on iOS).
3154
+ * @param backgroundColor - `app.backgroundColor`; the Android status bar icons follow it
3155
+ * (ignored on iOS).
3156
+ * @returns The paths patched vs. left unchanged, one merged report over every patch.
3157
+ * @throws {Error} When the Android `gen/android` tree (or its `app/build.gradle.kts`) is
3158
+ * missing, manifest entries meet a missing manifest or an unclear main activity, or a
3159
+ * background colour meets a tree without exactly one MainActivity.kt to style.
2265
3160
  * @example
2266
3161
  * ```ts
2267
- * await patchMobile("/repo/.moku/tauri", { target: "ios", runner }, {});
3162
+ * await patchMobile("/repo/.moku/tauri", { target: "android", runner }, {}, orientationManifest("portrait"), "#10161d");
2268
3163
  * ```
2269
3164
  */
2270
- async function patchMobile(projectDirectory, opts, signing) {
3165
+ async function patchMobile(projectDirectory, opts, signing, manifest = [], backgroundColor) {
2271
3166
  const genDirectory = genDirectoryPath(projectDirectory, opts.target);
2272
3167
  if (opts.target === "ios") {
2273
3168
  if (!existsSync(genDirectory)) return {
@@ -2283,9 +3178,11 @@ async function patchMobile(projectDirectory, opts, signing) {
2283
3178
  }
2284
3179
  const buildGradlePath = path.join(genDirectory, "app", "build.gradle.kts");
2285
3180
  if (!existsSync(genDirectory) || !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.`);
2286
- const result = await patchAndroidSigning(projectDirectory, genDirectory, signing.android ?? {});
2287
- if (!opts.runner) return result;
2288
- return mergePatchResults(result, await patchRunner(projectDirectory, genDirectory, {
3181
+ const signingResult = await patchAndroidSigning(projectDirectory, genDirectory, signing.android ?? {});
3182
+ const manifestResult = await patchAndroidManifest(projectDirectory, genDirectory, manifest);
3183
+ const systemBarsResult = await patchAndroidSystemBars(projectDirectory, genDirectory, backgroundColor);
3184
+ if (!opts.runner) return mergePatchResults(signingResult, manifestResult, systemBarsResult);
3185
+ return mergePatchResults(signingResult, manifestResult, systemBarsResult, await patchRunner(projectDirectory, genDirectory, {
2289
3186
  target: opts.target,
2290
3187
  runner: opts.runner
2291
3188
  }));
@@ -2293,11 +3190,12 @@ async function patchMobile(projectDirectory, opts, signing) {
2293
3190
  //#endregion
2294
3191
  //#region src/plugins/project/registry.ts
2295
3192
  /**
2296
- * The five v1 capability registry rows (spike (a), Tauri 2.9.x source-verified 2026-07-03).
2297
- * Four rows are backed by a real official Tauri plugin (crate + npm package + Rust init);
2298
- * `tray` is a core Tauri CARGO FEATURE — it carries no crate, no npm package and no Rust
2299
- * init, only `cargoFeatures: ["tray-icon"]`, and its `confidence: "low"` flags that
2300
- * divergence from the other four.
3193
+ * The seven capability registry rows (the first five spike (a), Tauri 2.9.x
3194
+ * source-verified 2026-07-03; `back` and `haptics` against Tauri 2.12.1). Five rows are
3195
+ * backed by a real official Tauri plugin (crate + npm package + Rust init). `tray` is a
3196
+ * core Tauri CARGO FEATURE — it carries no crate, no npm package and no Rust init, only
3197
+ * `cargoFeatures: ["tray-icon"]`, and its `confidence: "low"` flags that divergence.
3198
+ * `back` is core permissions alone: its whole API ships in `@tauri-apps/api/app`.
2301
3199
  */
2302
3200
  const REGISTRY = [
2303
3201
  {
@@ -2388,6 +3286,30 @@ const REGISTRY = [
2388
3286
  "android"
2389
3287
  ],
2390
3288
  confidence: "high"
3289
+ },
3290
+ {
3291
+ name: "back",
3292
+ cargoFeatures: [],
3293
+ permissions: ["core:app:allow-exit"],
3294
+ platforms: ["android"],
3295
+ confidence: "high"
3296
+ },
3297
+ {
3298
+ name: "haptics",
3299
+ npmPackage: "@tauri-apps/plugin-haptics",
3300
+ crate: "tauri-plugin-haptics",
3301
+ crateRange: "^2",
3302
+ npmRange: "^2",
3303
+ rustInit: "tauri_plugin_haptics::init()",
3304
+ cargoFeatures: [],
3305
+ permissions: [
3306
+ "haptics:allow-impact-feedback",
3307
+ "haptics:allow-notification-feedback",
3308
+ "haptics:allow-selection-feedback",
3309
+ "haptics:allow-vibrate"
3310
+ ],
3311
+ platforms: ["ios", "android"],
3312
+ confidence: "high"
2391
3313
  }
2392
3314
  ];
2393
3315
  const KNOWN_NAMES = REGISTRY.map((row) => row.name);
@@ -2464,8 +3386,8 @@ function buildConfFragment(row, config) {
2464
3386
  }
2465
3387
  /**
2466
3388
  * Typed registry lookup — resolves a capability row against optional consumer config,
2467
- * producing the full packaging contribution (conf fragment + the future-mechanism
2468
- * sidecar/manifest seams, both empty for every v1 row).
3389
+ * producing the full packaging contribution (conf fragment + the sidecar/manifest seams,
3390
+ * both empty for every row today).
2469
3391
  *
2470
3392
  * @param name - A capability name known at compile time (`keyof CapabilityConfigMap`).
2471
3393
  * @param config - Optional per-capability packaging parameters.
@@ -2493,7 +3415,8 @@ function resolve(name, config) {
2493
3415
  * @returns A fresh copy of every registry row — callers can never mutate the registry.
2494
3416
  * @example
2495
3417
  * ```ts
2496
- * registryRows().map(row => row.name); // ["store", "notification", ...]
3418
+ * registryRows().map(row => row.name);
3419
+ * // ["store", "notification", "clipboard-manager", "tray", "deep-link", "back", "haptics"]
2497
3420
  * ```
2498
3421
  */
2499
3422
  function registryRows() {
@@ -2529,6 +3452,25 @@ function resolveConfiguredCapabilities(global, target) {
2529
3452
  return resolved;
2530
3453
  }
2531
3454
  /**
3455
+ * Collects what the Android main activity must carry: the `activity-attribute` entries of
3456
+ * every capability resolved for android, then the orientation lock. Orientation comes
3457
+ * last so it wins a clash, the same order the iOS sidecar merges in. It is always present:
3458
+ * an unset orientation asks for `android:screenOrientation` to be absent, which removes a
3459
+ * lock a previous build left in the gen/ tree.
3460
+ *
3461
+ * @param global - Frozen global framework config.
3462
+ * @returns The manifest entries for `patchMobile`'s Android pass.
3463
+ * @example
3464
+ * ```ts
3465
+ * // `config` is any full native Config; no registry row carries a manifest entry today
3466
+ * androidManifestEntries({ ...config, app: { name: "Demo", identifier: "com.acme.demo", orientation: "portrait" } });
3467
+ * // [{ kind: "activity-attribute", name: "android:screenOrientation", value: "portrait" }]
3468
+ * ```
3469
+ */
3470
+ function androidManifestEntries(global) {
3471
+ return [...resolveConfiguredCapabilities(global, "android").flatMap((capability) => capability.manifest).filter((entry) => entry.kind === "activity-attribute"), ...orientationManifest(global.app.orientation)];
3472
+ }
3473
+ /**
2532
3474
  * Returns the required-file set a mobile `gen/<platform>` tree must carry — the options
2533
3475
  * object keeps every target-scoped API method reading the same way.
2534
3476
  *
@@ -2652,20 +3594,19 @@ function createProjectApi(ctx) {
2652
3594
  */
2653
3595
  const checkCompleteness = (opts) => completeness(ctx.global.projectDir, opts.target);
2654
3596
  /**
2655
- * Runs the idempotent mobile post-init patch pass — Android release signing, plus the
2656
- * Xcode/Android-Studio runner-command rewrite when a `runner` is supplied.
3597
+ * Implements {@link Api.patchMobile}: hands Android its manifest entries and
3598
+ * `app.backgroundColor` (the status bar icons follow it), then logs.
2657
3599
  *
2658
- * @param opts - The patch options.
2659
- * @param opts.target - The mobile platform to patch.
2660
- * @param opts.runner - The absolute Node/`tauri.js` pair from `tauri.runner()`.
2661
- * @returns The paths patched vs. left unchanged.
3600
+ * @param opts - See {@link Api.patchMobile}.
3601
+ * @returns See {@link Api.patchMobile}.
2662
3602
  * @example
2663
3603
  * ```ts
2664
- * await runPatchMobile({ target: "ios", runner: tauri.runner() });
3604
+ * await runPatchMobile({ target: "ios" }); // { patched: [], unchanged: [] } before `tauri ios init`
2665
3605
  * ```
2666
3606
  */
2667
3607
  const runPatchMobile = async (opts) => {
2668
- const result = await patchMobile(ctx.global.projectDir, opts, ctx.global.signing);
3608
+ const manifest = opts.target === "android" ? androidManifestEntries(ctx.global) : [];
3609
+ const result = await patchMobile(ctx.global.projectDir, opts, ctx.global.signing, manifest, ctx.global.app.backgroundColor);
2669
3610
  ctx.log.info("project:patchMobile", {
2670
3611
  target: opts.target,
2671
3612
  patched: result.patched.length
@@ -2766,6 +3707,10 @@ const BUILD_NUMBER_PATTERN = /^[\w.]+$/;
2766
3707
  const URL_SCHEME_PATTERN = /^[a-z][a-z\d+.-]*$/i;
2767
3708
  /** POSIX environment variable name — lands raw inside a Kotlin `System.getenv("…")` call. */
2768
3709
  const ENV_VAR_NAME_PATTERN = /^[a-z_][a-z\d_]*$/i;
3710
+ /** `#rrggbb` or `#rrggbbaa` — the hex forms Tauri parses a window colour from. */
3711
+ const HEX_COLOUR_PATTERN = /^#[0-9a-f]{6}([0-9a-f]{2})?$/i;
3712
+ /** The three `Orientation` values — plain-JS config can carry anything else. */
3713
+ const ORIENTATION_PATTERN = /^(?:portrait|landscape|any)$/;
2769
3714
  /**
2770
3715
  * Validates one free-text config value that is interpolated verbatim into a generated
2771
3716
  * file. Every generated format (TOML, Kotlin, plist, XML) has its own escape rules, so a
@@ -2826,13 +3771,14 @@ function assertDeliveryDirectory(value) {
2826
3771
  /**
2827
3772
  * Validates the global config at composition time — throws `[native]`-formatted errors
2828
3773
  * for missing app identity, missing web wiring, values that would break out of the
2829
- * generated file they are written into, a `projectDir` outside the project, an `outDir`
2830
- * this app must not deliver into, unknown `config.system` names, or a `deep-link`
2831
- * composition missing its scheme.
3774
+ * generated file they are written into, a window colour or orientation outside its
3775
+ * allowed shape, a `projectDir` outside the project, an `outDir` this app must not
3776
+ * deliver into, unknown `config.system` names, or a `deep-link` composition missing its
3777
+ * scheme.
2832
3778
  *
2833
3779
  * @param global - Frozen global framework config.
2834
- * @throws {Error} When identity, web wiring, interpolated values, derived directories,
2835
- * system names, or deep-link config are invalid.
3780
+ * @throws {Error} When identity, web wiring, interpolated values, presentation fields,
3781
+ * derived directories, system names, or deep-link config are invalid.
2836
3782
  * @example
2837
3783
  * ```ts
2838
3784
  * validateProjectConfig(ctx.global);
@@ -2847,6 +3793,8 @@ function validateProjectConfig(global) {
2847
3793
  if (!global.web.dist) throw new Error("[native] web.dist is required.\n Set config.web.dist to your web build's output directory.");
2848
3794
  assertShape("app.version", global.app.version, VERSION_PATTERN, "semantic version", "Use a MAJOR.MINOR.PATCH version such as \"1.0.0\".");
2849
3795
  assertShape("app.buildNumber", global.app.buildNumber, BUILD_NUMBER_PATTERN, "build number", "Use digits, letters, dots or underscores, such as \"42\" or \"1.0.3\".");
3796
+ assertShape("app.backgroundColor", global.app.backgroundColor, HEX_COLOUR_PATTERN, "colour", "Use a hex colour such as \"#10161d\".");
3797
+ assertShape("app.orientation", global.app.orientation, ORIENTATION_PATTERN, "orientation", "Use \"portrait\", \"landscape\" or \"any\".");
2850
3798
  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.");
2851
3799
  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.");
2852
3800
  assertDerivedDirectory(global.projectDir);
@@ -2861,8 +3809,9 @@ function validateProjectConfig(global) {
2861
3809
  //#region src/plugins/project/index.ts
2862
3810
  /**
2863
3811
  * Complex tier — capability registry + generators/ + write-if-changed writer + the mobile/
2864
- * sub-domain (completeness gate, Android signing block, runner-command rewrite) + the
2865
- * guarded clean.
3812
+ * sub-domain (completeness gate, Android signing block, Android manifest attributes,
3813
+ * Xcode settings, runner-command rewrite) + the build-time orientation lock + the guarded
3814
+ * clean.
2866
3815
  *
2867
3816
  * @see README.md
2868
3817
  * @example
@@ -4095,7 +5044,7 @@ function createTauriApi(ctx) {
4095
5044
  * ```
4096
5045
  */
4097
5046
  async function run(cmd, hooks) {
4098
- const startedAt = Date.now();
5047
+ const startedAt = performance.now();
4099
5048
  /**
4100
5049
  * Scrubs one output line, forwards it to the caller's hooks, and parses
4101
5050
  * any compile-progress tick out of it.
@@ -4118,7 +5067,7 @@ function createTauriApi(ctx) {
4118
5067
  cwd: runCwd(),
4119
5068
  onLine: handleLine
4120
5069
  });
4121
- const durationMs = Date.now() - startedAt;
5070
+ const durationMs = Math.round(performance.now() - startedAt);
4122
5071
  const scrubbedStdout = scrub(result.stdout);
4123
5072
  const scrubbedStderr = scrub(result.stderr);
4124
5073
  if (result.code !== 0) {
@@ -4853,7 +5802,7 @@ function emitPhase(ctx, target, phase, status, extra) {
4853
5802
  */
4854
5803
  async function runCompileAndBundle(ctx, deps, opts) {
4855
5804
  const { target } = opts;
4856
- const startedAt = Date.now();
5805
+ const startedAt = performance.now();
4857
5806
  let transitionAt;
4858
5807
  emitPhase(ctx, target, "compile", "start");
4859
5808
  try {
@@ -4892,8 +5841,8 @@ async function runCompileAndBundle(ctx, deps, opts) {
4892
5841
  onOutput: (line) => {
4893
5842
  if (transitionAt !== void 0) return;
4894
5843
  if (!BUNDLING_TRANSITION_PATTERN.test(line)) return;
4895
- transitionAt = Date.now();
4896
- emitPhase(ctx, target, "compile", "done", { durationMs: transitionAt - startedAt });
5844
+ transitionAt = performance.now();
5845
+ emitPhase(ctx, target, "compile", "done", { durationMs: Math.round(transitionAt - startedAt) });
4897
5846
  emitPhase(ctx, target, "bundle", "start");
4898
5847
  }
4899
5848
  });
@@ -4901,14 +5850,14 @@ async function runCompileAndBundle(ctx, deps, opts) {
4901
5850
  const openPhase = transitionAt === void 0 ? "compile" : "bundle";
4902
5851
  const detail = error instanceof Error ? error.message : String(error);
4903
5852
  emitPhase(ctx, target, openPhase, "error", {
4904
- durationMs: Date.now() - (transitionAt ?? startedAt),
5853
+ durationMs: Math.round(performance.now() - (transitionAt ?? startedAt)),
4905
5854
  detail
4906
5855
  });
4907
5856
  throw error;
4908
5857
  }
4909
- const endedAt = Date.now();
5858
+ const endedAt = performance.now();
4910
5859
  if (transitionAt === void 0) {
4911
- const compileDurationMs = endedAt - startedAt;
5860
+ const compileDurationMs = Math.round(endedAt - startedAt);
4912
5861
  emitPhase(ctx, target, "compile", "done", { durationMs: compileDurationMs });
4913
5862
  emitPhase(ctx, target, "bundle", "start");
4914
5863
  emitPhase(ctx, target, "bundle", "done", { durationMs: 0 });
@@ -4917,17 +5866,18 @@ async function runCompileAndBundle(ctx, deps, opts) {
4917
5866
  bundleDurationMs: 0
4918
5867
  };
4919
5868
  }
4920
- const bundleDurationMs = endedAt - transitionAt;
5869
+ const bundleDurationMs = Math.round(endedAt - transitionAt);
4921
5870
  emitPhase(ctx, target, "bundle", "done", { durationMs: bundleDurationMs });
4922
5871
  return {
4923
- compileDurationMs: transitionAt - startedAt,
5872
+ compileDurationMs: Math.round(transitionAt - startedAt),
4924
5873
  bundleDurationMs
4925
5874
  };
4926
5875
  }
4927
5876
  /**
4928
5877
  * Runs one phase generically: emits `native:phase` start/done/error and measures
4929
- * duration, rethrowing on failure so the caller stops the pipeline (no partial-continue,
4930
- * v1) — the phase after a failing one is never started.
5878
+ * duration (monotonic clock, whole milliseconds), rethrowing on failure so the caller
5879
+ * stops the pipeline (no partial-continue, v1) — the phase after a failing one is never
5880
+ * started.
4931
5881
  *
4932
5882
  * @param ctx - The build pipeline's domain context.
4933
5883
  * @param target - The packaging target the phase runs for.
@@ -4942,11 +5892,11 @@ async function runCompileAndBundle(ctx, deps, opts) {
4942
5892
  * ```
4943
5893
  */
4944
5894
  async function runPhase(ctx, target, phase, run, detailOf) {
4945
- const startedAt = Date.now();
5895
+ const startedAt = performance.now();
4946
5896
  emitPhase(ctx, target, phase, "start");
4947
5897
  try {
4948
5898
  const result = await run();
4949
- const durationMs = Date.now() - startedAt;
5899
+ const durationMs = Math.round(performance.now() - startedAt);
4950
5900
  const detail = detailOf?.(result);
4951
5901
  emitPhase(ctx, target, phase, "done", detail === void 0 ? { durationMs } : {
4952
5902
  durationMs,
@@ -4958,7 +5908,7 @@ async function runPhase(ctx, target, phase, run, detailOf) {
4958
5908
  };
4959
5909
  } catch (error) {
4960
5910
  emitPhase(ctx, target, phase, "error", {
4961
- durationMs: Date.now() - startedAt,
5911
+ durationMs: Math.round(performance.now() - startedAt),
4962
5912
  detail: error instanceof Error ? error.message : String(error)
4963
5913
  });
4964
5914
  throw error;
@@ -5015,7 +5965,7 @@ async function runPrepare(ctx, deps, target) {
5015
5965
  */
5016
5966
  async function runPipeline(ctx, deps, opts) {
5017
5967
  const { target } = opts;
5018
- const startedAt = Date.now();
5968
+ const startedAt = performance.now();
5019
5969
  const phases = [...await runPrepare(ctx, deps, target)];
5020
5970
  const { compileDurationMs, bundleDurationMs } = await runCompileAndBundle(ctx, deps, opts);
5021
5971
  phases.push({
@@ -5034,7 +5984,7 @@ async function runPipeline(ctx, deps, opts) {
5034
5984
  phase: "collect",
5035
5985
  durationMs: collect.durationMs
5036
5986
  });
5037
- const durationMs = Date.now() - startedAt;
5987
+ const durationMs = Math.round(performance.now() - startedAt);
5038
5988
  const { outPath, artifacts } = collect.result;
5039
5989
  ctx.emit("native:complete", {
5040
5990
  target,
@@ -7006,8 +7956,9 @@ function createCliHandlers(ctx) {
7006
7956
  * ```
7007
7957
  */
7008
7958
  "native:phase"(payload) {
7009
- if (payload.status === "start") ctx.state.progress = { startedAt: Date.now() };
7010
- const elapsedMs = ctx.state.progress.startedAt ? Date.now() - ctx.state.progress.startedAt : 0;
7959
+ if (payload.status === "start") ctx.state.progress = { startedAt: performance.now() };
7960
+ const { startedAt } = ctx.state.progress;
7961
+ const elapsedMs = startedAt === void 0 ? 0 : Math.round(performance.now() - startedAt);
7011
7962
  renderPhaseEvent(ui, payload, elapsedMs);
7012
7963
  if (payload.status === "done" || payload.status === "error") ctx.state.progress = { startedAt: void 0 };
7013
7964
  },
@@ -7159,10 +8110,10 @@ const cliPlugin = createPlugin$1("cli", {
7159
8110
  *
7160
8111
  * | Field | Type | Default |
7161
8112
  * |---|---|---|
7162
- * | `app` | `{ name; identifier; version?; icon?; category?; buildNumber? }` | `{ name: "", identifier: "" }` — both validated non-empty at composition |
8113
+ * | `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 |
7163
8114
  * | `web` | `{ build; devCommand; devUrl; dist; cwd? }` | `"bun run build"`, `"bun run dev"`, `"http://localhost:5173"`, `"dist"` |
7164
8115
  * | `system` | `ReadonlyArray<{ name: string }>` | `[]` — the composed `@moku-labs/system` plugins |
7165
- * | `capabilities` | `Partial<CapabilityConfigMap>` | `{}` |
8116
+ * | `capabilities` | `Partial<CapabilityConfigMap>` | `{}` — keys: `store`, `notification`, `clipboard-manager`, `tray`, `deep-link`, `back`, `haptics` |
7166
8117
  * | `targets` | `readonly Target[]` | `hostTargets(process.platform)` — one desktop target, mobile is opt-in |
7167
8118
  * | `projectDir` | `string` | `".moku/tauri"` — generated Tauri project (gitignored build output) |
7168
8119
  * | `outDir` | `string` | `"dist-native"` — installer delivery root |