@moku-labs/native 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -501,9 +501,8 @@ function isDeliveryPath(candidate, boundaries = {}) {
501
501
  }
502
502
  //#endregion
503
503
  //#region src/plugins/project/clean.ts
504
- /**
505
- * @file project plugin — target-scoped destructive cleanup (pure path computation + guarded rm).
506
- */
504
+ /** Directory `xcodebuild` writes an iOS build into, below `gen/apple`. */
505
+ const IOS_BUILD_OUTPUT_DIRECTORY = "build";
507
506
  /**
508
507
  * Computes the absolute path(s) a clean pass would delete for a given scope, without
509
508
  * touching the filesystem. Mobile targets scope to `gen/<platform>` only; desktop
@@ -611,6 +610,129 @@ async function clean(projectDirectory, target) {
611
610
  }
612
611
  return { removed };
613
612
  }
613
+ /**
614
+ * Computes the directory one mobile target's PREVIOUS build output sits in, without
615
+ * touching the filesystem. iOS builds into `gen/apple/build` (`xcodebuild`'s own output
616
+ * root, read from `layout.ts`); Android has no such path here, because Gradle manages its
617
+ * `app/build` tree itself and reuses it correctly across builds.
618
+ *
619
+ * @param projectDirectory - The Tauri project root.
620
+ * @param target - The mobile packaging target.
621
+ * @returns The absolute build-output directory, or undefined when the platform has none.
622
+ * @example
623
+ * ```ts
624
+ * mobileBuildOutputPath("/repo/.moku/tauri", "ios"); // ".../src-tauri/gen/apple/build"
625
+ * ```
626
+ */
627
+ function mobileBuildOutputPath(projectDirectory, target) {
628
+ if (target !== "ios") return void 0;
629
+ return node_path.default.join(genDirectoryPath(projectDirectory, target), IOS_BUILD_OUTPUT_DIRECTORY);
630
+ }
631
+ /**
632
+ * Decides whether a build-output directory may be removed — the pure predicate in front of
633
+ * the only other recursive delete in this plugin. Two conditions, both borrowed from the
634
+ * guards that already exist: `root` must be derived state this app owns
635
+ * ({@link isDerivedPath}, the same rule {@link assertCleanableRoot} applies), and the
636
+ * candidate's REAL path must sit strictly inside `root`'s real path. Symlinks are resolved
637
+ * first, so a `build` link pointing at somebody else's directory is refused rather than
638
+ * followed.
639
+ *
640
+ * Pure by design — it is tested by calling it with unsafe paths directly, never by letting
641
+ * {@link clearMobileBuildOutput} loose on one.
642
+ *
643
+ * @param root - The configured `projectDir`.
644
+ * @param candidate - The build-output directory a clear pass wants to remove.
645
+ * @param boundaries - Overrides for cwd/home/tmp/platform/anchor; each defaults to the real value.
646
+ * @returns Whether the candidate may be removed.
647
+ * @example
648
+ * ```ts
649
+ * isClearableBuildOutput("/repo/.moku/tauri", "/repo/.moku/tauri/src-tauri/gen/apple/build"); // true
650
+ * ```
651
+ */
652
+ function isClearableBuildOutput(root, candidate, boundaries = {}) {
653
+ if (!isDerivedPath(root, boundaries)) return false;
654
+ const platform = boundaries.platform ?? node_process.default.platform;
655
+ return isStrictlyInside$1(realResolve(root), realResolve(candidate), platform);
656
+ }
657
+ /**
658
+ * Refuses to remove anything but a build-output directory nested inside a derived
659
+ * `projectDir` — the last gate before the recursive delete.
660
+ *
661
+ * @param root - The configured `projectDir`.
662
+ * @param candidate - The build-output directory a clear pass wants to remove.
663
+ * @param isRealDirectory - Whether the candidate is a real directory rather than a link or a
664
+ * file (default `true` — callers that have not looked at the entry assert containment only).
665
+ * @throws {Error} When `projectDir` is not derived state, when the candidate is not a real
666
+ * directory, or when its real path is not strictly inside `projectDir`.
667
+ * @example
668
+ * ```ts
669
+ * assertClearableBuildOutput("/repo/.moku/tauri", "/repo/.moku/tauri/src-tauri/gen/apple/build");
670
+ * ```
671
+ */
672
+ function assertClearableBuildOutput(root, candidate, isRealDirectory = true) {
673
+ assertCleanableRoot(root);
674
+ if (isRealDirectory && isClearableBuildOutput(root, candidate)) return;
675
+ throw new Error(`[native] Refusing to remove build output outside projectDir: ${realResolve(candidate)}.\n Remove that link by hand — "${candidate}" must be a real directory inside ${realResolve(root)}.`);
676
+ }
677
+ /**
678
+ * Reads a directory entry WITHOUT following it — the link itself, never its target — and
679
+ * reports an absent path as "no entry" rather than as a failure.
680
+ *
681
+ * `existsSync` and every other stat that follows links answers "no" for a DANGLING link, so
682
+ * a `build` symlink whose target is gone would look like a missing directory and skip the
683
+ * guard that exists to refuse it. `lstat` sees the link.
684
+ *
685
+ * @param target - The path to inspect.
686
+ * @returns The entry's own stats, or undefined when nothing is there.
687
+ * @example
688
+ * ```ts
689
+ * (await lstatSafe("/repo/.moku/tauri/src-tauri/gen/apple/build"))?.isDirectory();
690
+ * ```
691
+ */
692
+ async function lstatSafe(target) {
693
+ try {
694
+ return await (0, node_fs_promises.lstat)(target);
695
+ } catch (error) {
696
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return void 0;
697
+ throw error;
698
+ }
699
+ }
700
+ /**
701
+ * Removes a mobile target's PREVIOUS build output, so the next build writes into an empty
702
+ * tree. iOS needs it: `tauri ios build` renames its freshly built `.app` into the existing
703
+ * `gen/apple/build/<app>.xcarchive`, and a second build fails there with
704
+ * `Directory not empty (os error 66)`. Android removes nothing — Gradle owns its `build`
705
+ * tree and reuses it correctly.
706
+ *
707
+ * A missing directory is fine (nothing removed). Everything that IS there goes through
708
+ * {@link assertClearableBuildOutput} first, so a symlinked `build` is refused instead of
709
+ * followed out of the project. The entry is read with {@link lstatSafe}: a dangling link is
710
+ * an entry like any other here, and reaches the guard rather than passing for a missing
711
+ * directory.
712
+ *
713
+ * @param projectDirectory - The Tauri project root.
714
+ * @param target - The mobile packaging target.
715
+ * @returns The paths actually removed — empty when there was nothing to remove.
716
+ * @throws {Error} When `projectDir` is not derived state, or the build output resolves
717
+ * outside it.
718
+ * @example
719
+ * ```ts
720
+ * await clearMobileBuildOutput("/repo/.moku/tauri", "ios");
721
+ * ```
722
+ */
723
+ async function clearMobileBuildOutput(projectDirectory, target) {
724
+ const root = node_path.default.resolve(projectDirectory);
725
+ const buildOutput = mobileBuildOutputPath(root, target);
726
+ if (!buildOutput) return { removed: [] };
727
+ const entry = await lstatSafe(buildOutput);
728
+ if (!entry) return { removed: [] };
729
+ assertClearableBuildOutput(root, buildOutput, entry.isDirectory());
730
+ await (0, node_fs_promises.rm)(buildOutput, {
731
+ recursive: true,
732
+ force: true
733
+ });
734
+ return { removed: [buildOutput] };
735
+ }
614
736
  //#endregion
615
737
  //#region src/plugins/project/generators/build-script.ts
616
738
  /**
@@ -1367,6 +1489,91 @@ async function writeIfChanged(filePath, content, projectDirectory) {
1367
1489
  return "written";
1368
1490
  }
1369
1491
  //#endregion
1492
+ //#region src/plugins/project/mobile/files.ts
1493
+ /**
1494
+ * @file project plugin — the ONE owner of "which generated files a mobile patch pass may
1495
+ * touch". Both iOS patches (the runner-command rewrite and the Xcode build-settings patch)
1496
+ * read the same list from here, so neither can drift into a file the other does not know
1497
+ * about — and neither ever descends into `gen/apple/build` or `gen/android/build`, which
1498
+ * belong to the toolchain.
1499
+ */
1500
+ /** Source extensions that can carry the Android runner command. */
1501
+ const ANDROID_SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
1502
+ ".kt",
1503
+ ".kts",
1504
+ ".gradle"
1505
+ ]);
1506
+ /** Derived directories a patch scan never descends into — the toolchain owns them. */
1507
+ const SKIPPED_DIRECTORIES = /* @__PURE__ */ new Set([
1508
+ "build",
1509
+ ".gradle",
1510
+ ".idea"
1511
+ ]);
1512
+ /**
1513
+ * Lists the generated iOS files a patch pass may rewrite: `project.yml` plus the
1514
+ * `project.pbxproj` of every generated Xcode project. `gen/apple/build` is never listed —
1515
+ * that tree is `xcodebuild` output, not project source.
1516
+ *
1517
+ * @param genDirectory - The `src-tauri/gen/apple` directory.
1518
+ * @returns The existing files to patch.
1519
+ * @example
1520
+ * ```ts
1521
+ * await iosPatchFiles("/repo/.moku/tauri/src-tauri/gen/apple");
1522
+ * ```
1523
+ */
1524
+ async function iosPatchFiles(genDirectory) {
1525
+ const files = [];
1526
+ const projectYml = node_path.default.join(genDirectory, "project.yml");
1527
+ if ((0, node_fs.existsSync)(projectYml)) files.push(projectYml);
1528
+ for (const entry of await (0, node_fs_promises.readdir)(genDirectory, { withFileTypes: true })) {
1529
+ if (!entry.isDirectory() || !entry.name.endsWith(".xcodeproj")) continue;
1530
+ const pbxproj = node_path.default.join(genDirectory, entry.name, "project.pbxproj");
1531
+ if ((0, node_fs.existsSync)(pbxproj)) files.push(pbxproj);
1532
+ }
1533
+ return files;
1534
+ }
1535
+ /**
1536
+ * Walks a directory tree collecting accepted files, skipping derived build output.
1537
+ *
1538
+ * @param directory - The directory to walk (a missing directory yields nothing).
1539
+ * @param accept - Predicate over the file name.
1540
+ * @returns Every accepted file path below `directory`.
1541
+ * @example
1542
+ * ```ts
1543
+ * await collectFiles(buildSrcDirectory, name => name.endsWith(".kt"));
1544
+ * ```
1545
+ */
1546
+ async function collectFiles(directory, accept) {
1547
+ if (!(0, node_fs.existsSync)(directory)) return [];
1548
+ const found = [];
1549
+ for (const entry of await (0, node_fs_promises.readdir)(directory, { withFileTypes: true })) {
1550
+ const full = node_path.default.join(directory, entry.name);
1551
+ if (entry.isDirectory()) {
1552
+ if (SKIPPED_DIRECTORIES.has(entry.name)) continue;
1553
+ found.push(...await collectFiles(full, accept));
1554
+ continue;
1555
+ }
1556
+ if (accept(entry.name)) found.push(full);
1557
+ }
1558
+ return found;
1559
+ }
1560
+ /**
1561
+ * Lists the generated Android files a patch pass may rewrite: every Kotlin/Gradle source
1562
+ * under `buildSrc`, plus the two top-level Gradle build files.
1563
+ *
1564
+ * @param genDirectory - The `src-tauri/gen/android` directory.
1565
+ * @returns The existing files to patch.
1566
+ * @example
1567
+ * ```ts
1568
+ * await androidPatchFiles("/repo/.moku/tauri/src-tauri/gen/android");
1569
+ * ```
1570
+ */
1571
+ async function androidPatchFiles(genDirectory) {
1572
+ const buildSource = await collectFiles(node_path.default.join(genDirectory, "buildSrc"), (name) => ANDROID_SOURCE_EXTENSIONS.has(node_path.default.extname(name)));
1573
+ const gradleFiles = [node_path.default.join(genDirectory, "build.gradle.kts"), node_path.default.join(genDirectory, "app", "build.gradle.kts")].filter((file) => (0, node_fs.existsSync)(file));
1574
+ return [...buildSource, ...gradleFiles];
1575
+ }
1576
+ //#endregion
1370
1577
  //#region src/plugins/project/mobile/runner.ts
1371
1578
  /**
1372
1579
  * @file project plugin — the runner-command rewrite. `tauri ios|android init` bakes
@@ -1379,20 +1586,8 @@ async function writeIfChanged(filePath, content, projectDirectory) {
1379
1586
  const IOS_RUNNER_VERB = "ios xcode-script";
1380
1587
  /** The Android equivalent, written into buildSrc/gradle sources by `tauri android init`. */
1381
1588
  const ANDROID_RUNNER_VERB = "android android-studio-script";
1382
- /** Source extensions that can carry the Android runner command. */
1383
- const ANDROID_RUNNER_EXTENSIONS = /* @__PURE__ */ new Set([
1384
- ".kt",
1385
- ".kts",
1386
- ".gradle"
1387
- ]);
1388
1589
  /** A quote inside a pbxproj/Kotlin/Gradle string literal is backslash-escaped. */
1389
1590
  const ESCAPED_QUOTE = String.raw`\"`;
1390
- /** Derived directories a runner-command scan never descends into. */
1391
- const SKIPPED_DIRECTORIES = /* @__PURE__ */ new Set([
1392
- "build",
1393
- ".gradle",
1394
- ".idea"
1395
- ]);
1396
1591
  /**
1397
1592
  * One quoted shell word, with or without the backslash a source string literal escapes its
1398
1593
  * quotes with — how an already-patched absolute runner path appears in every file we touch.
@@ -1549,69 +1744,6 @@ function quoteFor(filePath) {
1549
1744
  return filePath.endsWith(".yml") ? "\"" : ESCAPED_QUOTE;
1550
1745
  }
1551
1746
  /**
1552
- * Lists the iOS files that carry the runner command: `project.yml` plus the
1553
- * `project.pbxproj` of every generated Xcode project.
1554
- *
1555
- * @param genDirectory - The `src-tauri/gen/apple` directory.
1556
- * @returns The existing files to patch.
1557
- * @example
1558
- * ```ts
1559
- * await iosRunnerFiles("/repo/.moku/tauri/src-tauri/gen/apple");
1560
- * ```
1561
- */
1562
- async function iosRunnerFiles(genDirectory) {
1563
- const files = [];
1564
- const projectYml = node_path.default.join(genDirectory, "project.yml");
1565
- if ((0, node_fs.existsSync)(projectYml)) files.push(projectYml);
1566
- for (const entry of await (0, node_fs_promises.readdir)(genDirectory, { withFileTypes: true })) {
1567
- if (!entry.isDirectory() || !entry.name.endsWith(".xcodeproj")) continue;
1568
- const pbxproj = node_path.default.join(genDirectory, entry.name, "project.pbxproj");
1569
- if ((0, node_fs.existsSync)(pbxproj)) files.push(pbxproj);
1570
- }
1571
- return files;
1572
- }
1573
- /**
1574
- * Walks a directory tree collecting accepted files, skipping derived build output.
1575
- *
1576
- * @param directory - The directory to walk (a missing directory yields nothing).
1577
- * @param accept - Predicate over the file name.
1578
- * @returns Every accepted file path below `directory`.
1579
- * @example
1580
- * ```ts
1581
- * await collectFiles(buildSrcDirectory, name => name.endsWith(".kt"));
1582
- * ```
1583
- */
1584
- async function collectFiles(directory, accept) {
1585
- if (!(0, node_fs.existsSync)(directory)) return [];
1586
- const found = [];
1587
- for (const entry of await (0, node_fs_promises.readdir)(directory, { withFileTypes: true })) {
1588
- const full = node_path.default.join(directory, entry.name);
1589
- if (entry.isDirectory()) {
1590
- if (SKIPPED_DIRECTORIES.has(entry.name)) continue;
1591
- found.push(...await collectFiles(full, accept));
1592
- continue;
1593
- }
1594
- if (accept(entry.name)) found.push(full);
1595
- }
1596
- return found;
1597
- }
1598
- /**
1599
- * Lists the Android files that can carry the runner command: every Kotlin/Gradle source
1600
- * under `buildSrc`, plus the two top-level Gradle build files.
1601
- *
1602
- * @param genDirectory - The `src-tauri/gen/android` directory.
1603
- * @returns The existing files to patch.
1604
- * @example
1605
- * ```ts
1606
- * await androidRunnerFiles("/repo/.moku/tauri/src-tauri/gen/android");
1607
- * ```
1608
- */
1609
- async function androidRunnerFiles(genDirectory) {
1610
- const buildSource = await collectFiles(node_path.default.join(genDirectory, "buildSrc"), (name) => ANDROID_RUNNER_EXTENSIONS.has(node_path.default.extname(name)));
1611
- const gradleFiles = [node_path.default.join(genDirectory, "build.gradle.kts"), node_path.default.join(genDirectory, "app", "build.gradle.kts")].filter((file) => (0, node_fs.existsSync)(file));
1612
- return [...buildSource, ...gradleFiles];
1613
- }
1614
- /**
1615
1747
  * Applies the runner rewrite to every candidate file for a platform, reporting which
1616
1748
  * files actually changed. A second pass rewrites the absolute pair onto itself and
1617
1749
  * reports everything unchanged.
@@ -1636,7 +1768,7 @@ async function androidRunnerFiles(genDirectory) {
1636
1768
  */
1637
1769
  async function patchRunner(projectDirectory, genDirectory, opts) {
1638
1770
  const verb = opts.target === "ios" ? IOS_RUNNER_VERB : ANDROID_RUNNER_VERB;
1639
- const files = opts.target === "ios" ? await iosRunnerFiles(genDirectory) : await androidRunnerFiles(genDirectory);
1771
+ const files = opts.target === "ios" ? await iosPatchFiles(genDirectory) : await androidPatchFiles(genDirectory);
1640
1772
  const patched = [];
1641
1773
  const unchanged = [];
1642
1774
  for (const file of files) {
@@ -1803,18 +1935,354 @@ async function patchAndroidSigning(projectDirectory, genDirectory, signing) {
1803
1935
  };
1804
1936
  }
1805
1937
  //#endregion
1938
+ //#region src/plugins/project/mobile/xcode-settings.ts
1939
+ /**
1940
+ * @file project plugin — the Xcode build-settings patch that makes an iOS REBUILD work.
1941
+ *
1942
+ * A capability plugin's build script rewrites the generated `<app>_iOS.entitlements` file
1943
+ * while Xcode is compiling, and Xcode fails the second build on that:
1944
+ * `Entitlements file "<app>_iOS.entitlements" was modified during the build, which is not
1945
+ * supported`. Xcode names the way out itself — `CODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION`
1946
+ * — so every `buildSettings` block of the generated `project.pbxproj` carries it, and the
1947
+ * `project.yml` target carries it too, so a later xcodegen regeneration keeps it.
1948
+ *
1949
+ * Both transforms are pure text functions over the real generated shapes: line endings,
1950
+ * indentation and every neighbouring line survive byte for byte, and a second pass is a
1951
+ * no-op.
1952
+ */
1953
+ /** The Xcode build setting that permits a build script to rewrite the entitlements file. */
1954
+ const ENTITLEMENTS_MODIFICATION_KEY = "CODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION";
1955
+ /** The pbxproj value form — Xcode writes booleans as `YES`/`NO`. */
1956
+ const PBXPROJ_ENABLED_VALUE = "YES";
1957
+ /**
1958
+ * The project.yml value form. xcodegen renders a YAML boolean as `YES` in the pbxproj it
1959
+ * generates, which is why the target's sibling settings read `true`/`false` there.
1960
+ */
1961
+ const YML_ENABLED_VALUE = "true";
1962
+ /** Opens one settings block inside a `XCBuildConfiguration` section. */
1963
+ const BUILD_SETTINGS_OPEN_PATTERN = /^([ \t]*)buildSettings = \{[ \t]*$/;
1964
+ /** The setting, already present as a pbxproj assignment (whatever its value). */
1965
+ const PBXPROJ_SETTING_PATTERN = new RegExp(`^[ \t]*${ENTITLEMENTS_MODIFICATION_KEY}[ \t]*=`);
1966
+ /** The setting, already present as a YAML key (whatever its value). */
1967
+ const YML_SETTING_PATTERN = new RegExp(`^[ \t]*${ENTITLEMENTS_MODIFICATION_KEY}[ \t]*:`);
1968
+ /** Opens a target's `settings:` mapping in `project.yml`. */
1969
+ const YML_SETTINGS_PATTERN = /^([ \t]*)settings:[ \t]*$/;
1970
+ /** Opens the `base:` mapping a `settings:` block carries its own build settings in. */
1971
+ const YML_BASE_PATTERN = /^([ \t]*)base:[ \t]*$/;
1972
+ /** The leading whitespace of a line — never matches a line break. */
1973
+ const INDENT_PATTERN = /^[ \t]*/;
1974
+ /** Splits text into lines, keeping each line's own terminator attached to it. */
1975
+ const LINE_SPLIT_PATTERN = /(?<=\n)/;
1976
+ /** A line's terminator (LF or CRLF), stripped to compare the line's text alone. */
1977
+ const LINE_ENDING_PATTERN = /\r?\n$/;
1978
+ /** One indentation step inside a pbxproj — the generated file is tab-indented. */
1979
+ const PBXPROJ_NESTED_INDENT = " ";
1980
+ /** One indentation step inside a project.yml — YAML mappings never indent with tabs. */
1981
+ const YML_NESTED_INDENT = " ";
1982
+ /**
1983
+ * Splits text into lines that each remember their own terminator, so a file mixing (or
1984
+ * using) CRLF comes back out exactly as it went in.
1985
+ *
1986
+ * @param text - The file content.
1987
+ * @returns One entry per line, in order.
1988
+ * @example
1989
+ * ```ts
1990
+ * splitLines("a\r\nb"); // [{ body: "a", ending: "\r\n" }, { body: "b", ending: "" }]
1991
+ * ```
1992
+ */
1993
+ function splitLines$1(text) {
1994
+ return text.split(LINE_SPLIT_PATTERN).map((chunk) => {
1995
+ const body = chunk.replace(LINE_ENDING_PATTERN, "");
1996
+ return {
1997
+ body,
1998
+ ending: chunk.slice(body.length)
1999
+ };
2000
+ });
2001
+ }
2002
+ /**
2003
+ * Joins lines back into file content.
2004
+ *
2005
+ * @param lines - The lines to join.
2006
+ * @returns The file content.
2007
+ * @example
2008
+ * ```ts
2009
+ * joinLines([{ body: "a", ending: "\n" }]); // "a\n"
2010
+ * ```
2011
+ */
2012
+ function joinLines(lines) {
2013
+ return lines.map((line) => line.body + line.ending).join("");
2014
+ }
2015
+ /**
2016
+ * Reads a line's leading whitespace — the indentation a new sibling line has to match.
2017
+ *
2018
+ * @param body - The line's text.
2019
+ * @returns The leading spaces/tabs, possibly empty.
2020
+ * @example
2021
+ * ```ts
2022
+ * indentOf("\t\t\tisa = XCBuildConfiguration;"); // "\t\t\t"
2023
+ * ```
2024
+ */
2025
+ function indentOf(body) {
2026
+ return INDENT_PATTERN.exec(body)?.[0] ?? "";
2027
+ }
2028
+ /**
2029
+ * Returns a block that carries the setting exactly once: an assignment already there is
2030
+ * rewritten in place (a block that turned the setting OFF would still break the rebuild),
2031
+ * and an absent one is inserted as the block's first entry, at its siblings' indentation.
2032
+ *
2033
+ * @param block - The lines inside the block, without its opening and closing line.
2034
+ * @param options - How to place the setting.
2035
+ * @param options.present - Matches an assignment of the setting already in the block.
2036
+ * @param options.render - Renders the setting line at a given indentation.
2037
+ * @param options.fallbackIndent - Indentation used when the block carries no line to match.
2038
+ * @param options.fallbackEnding - Terminator used when the block carries no line to match.
2039
+ * @returns The block's lines, with the setting present exactly once.
2040
+ * @example
2041
+ * ```ts
2042
+ * placeSetting(block, { present: PBXPROJ_SETTING_PATTERN, render, fallbackIndent, fallbackEnding });
2043
+ * ```
2044
+ */
2045
+ function placeSetting(block, options) {
2046
+ const { present, render, fallbackIndent, fallbackEnding } = options;
2047
+ const existingIndex = block.findIndex((line) => present.test(line.body));
2048
+ if (existingIndex !== -1) return block.map((line, index) => index === existingIndex ? {
2049
+ body: render(indentOf(line.body)),
2050
+ ending: line.ending
2051
+ } : line);
2052
+ const sibling = block.find((line) => line.body.trim().length > 0);
2053
+ return [{
2054
+ body: render(sibling ? indentOf(sibling.body) : fallbackIndent),
2055
+ ending: sibling?.ending ?? fallbackEnding
2056
+ }, ...block];
2057
+ }
2058
+ /**
2059
+ * Collects the lines of one block, starting at `start` and stopping at the first line the
2060
+ * block does not own.
2061
+ *
2062
+ * @param lines - Every line of the file.
2063
+ * @param start - Index of the block's first line.
2064
+ * @param isMember - Whether a line still belongs to the block.
2065
+ * @returns The block's lines, and the index of the first line after it.
2066
+ * @example
2067
+ * ```ts
2068
+ * const { block, next } = collectBlock(lines, index, line => line.body !== "\t\t\t};");
2069
+ * ```
2070
+ */
2071
+ function collectBlock(lines, start, isMember) {
2072
+ const block = [];
2073
+ let index = start;
2074
+ while (index < lines.length) {
2075
+ const line = lines[index];
2076
+ if (!line || !isMember(line)) break;
2077
+ block.push(line);
2078
+ index += 1;
2079
+ }
2080
+ return {
2081
+ block,
2082
+ next: index
2083
+ };
2084
+ }
2085
+ /**
2086
+ * Renders the setting as a pbxproj assignment.
2087
+ *
2088
+ * @param indent - The indentation its sibling settings use.
2089
+ * @returns The assignment line.
2090
+ * @example
2091
+ * ```ts
2092
+ * renderPbxprojSetting("\t\t\t\t"); // "\t\t\t\tCODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION = YES;"
2093
+ * ```
2094
+ */
2095
+ function renderPbxprojSetting(indent) {
2096
+ return `${indent}${ENTITLEMENTS_MODIFICATION_KEY} = ${PBXPROJ_ENABLED_VALUE};`;
2097
+ }
2098
+ /**
2099
+ * Renders the setting as a YAML mapping entry.
2100
+ *
2101
+ * @param indent - The indentation its sibling entries use.
2102
+ * @returns The entry line.
2103
+ * @example
2104
+ * ```ts
2105
+ * renderYmlSetting(" "); // " CODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION: true"
2106
+ * ```
2107
+ */
2108
+ function renderYmlSetting(indent) {
2109
+ return `${indent}${ENTITLEMENTS_MODIFICATION_KEY}: ${YML_ENABLED_VALUE}`;
2110
+ }
2111
+ /**
2112
+ * Reads the `base:` mapping a target's `settings:` line opens — the one block in
2113
+ * `project.yml` that holds build settings.
2114
+ *
2115
+ * The block is walked, not peeked at: `base:` is a direct child of `settings:`, but not
2116
+ * necessarily the FIRST one — xcodegen is equally happy with `settings:` followed by
2117
+ * `groups: [app]` and `base:` below it. So every line indented deeper than `settings:` is
2118
+ * scanned until the block dedents, and the first `base:` sitting at the direct-child level
2119
+ * wins; a nested `base:` deeper inside somebody else's sub-mapping does not. A `settings:`
2120
+ * block carrying no `base:` at all owns no such block and is left alone.
2121
+ *
2122
+ * @param lines - Every line of the file.
2123
+ * @param settingsIndex - Index of the candidate `settings:` line.
2124
+ * @returns The `base:` line, its index and its indentation, or undefined when there is none.
2125
+ * @example
2126
+ * ```ts
2127
+ * baseMappingAt(splitLines(" settings:\n groups: [app]\n base:\n"), 0);
2128
+ * ```
2129
+ */
2130
+ function baseMappingAt(lines, settingsIndex) {
2131
+ const settingsLine = lines[settingsIndex];
2132
+ const settings = settingsLine && YML_SETTINGS_PATTERN.exec(settingsLine.body);
2133
+ if (!settings) return void 0;
2134
+ const settingsIndent = (settings[1] ?? "").length;
2135
+ let childIndent;
2136
+ for (let index = settingsIndex + 1; index < lines.length; index += 1) {
2137
+ const line = lines[index];
2138
+ if (!line) break;
2139
+ if (line.body.trim().length === 0) continue;
2140
+ const indent = indentOf(line.body);
2141
+ if (indent.length <= settingsIndent) break;
2142
+ childIndent ??= indent.length;
2143
+ if (indent.length !== childIndent) continue;
2144
+ if (YML_BASE_PATTERN.test(line.body)) return {
2145
+ line,
2146
+ index,
2147
+ indent
2148
+ };
2149
+ }
2150
+ }
2151
+ /**
2152
+ * Adds `CODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION = YES;` to every `buildSettings` block of
2153
+ * a generated `project.pbxproj`, exactly once per block and at the indentation its sibling
2154
+ * settings use. Content outside those blocks — the shell-script build phase included — is
2155
+ * returned byte for byte, and a file that already carries the setting comes back unchanged.
2156
+ *
2157
+ * @param existing - The current `project.pbxproj` content.
2158
+ * @returns The content with the setting in every settings block.
2159
+ * @example
2160
+ * ```ts
2161
+ * applyPbxprojEntitlementsSetting(await readFile(pbxprojPath, "utf8"));
2162
+ * ```
2163
+ */
2164
+ function applyPbxprojEntitlementsSetting(existing) {
2165
+ const lines = splitLines$1(existing);
2166
+ const patched = [];
2167
+ let index = 0;
2168
+ while (index < lines.length) {
2169
+ const line = lines[index];
2170
+ if (!line) break;
2171
+ patched.push(line);
2172
+ index += 1;
2173
+ const opening = BUILD_SETTINGS_OPEN_PATTERN.exec(line.body);
2174
+ if (!opening) continue;
2175
+ const blockIndent = opening[1] ?? "";
2176
+ const closing = `${blockIndent}};`;
2177
+ const { block, next } = collectBlock(lines, index, (inner) => inner.body !== closing);
2178
+ index = next;
2179
+ patched.push(...placeSetting(block, {
2180
+ present: PBXPROJ_SETTING_PATTERN,
2181
+ render: renderPbxprojSetting,
2182
+ fallbackIndent: `${blockIndent}${PBXPROJ_NESTED_INDENT}`,
2183
+ fallbackEnding: line.ending
2184
+ }));
2185
+ }
2186
+ return joinLines(patched);
2187
+ }
2188
+ /**
2189
+ * Adds the setting to every target's `settings.base` block in a generated `project.yml`, so
2190
+ * an xcodegen regeneration writes it back into the pbxproj. Only a `base:` mapping that is a
2191
+ * direct child of a `settings:` mapping is touched — a `settingGroups:` block is somebody
2192
+ * else's. A blank line inside the block does not end it: YAML mappings end at a dedent, so
2193
+ * an entry printed below an empty line is still seen and never duplicated.
2194
+ *
2195
+ * @param existing - The current `project.yml` content.
2196
+ * @returns The content with the setting under each target's `settings.base`.
2197
+ * @example
2198
+ * ```ts
2199
+ * applyProjectYmlEntitlementsSetting(await readFile(projectYmlPath, "utf8"));
2200
+ * ```
2201
+ */
2202
+ function applyProjectYmlEntitlementsSetting(existing) {
2203
+ const lines = splitLines$1(existing);
2204
+ const patched = [];
2205
+ let index = 0;
2206
+ while (index < lines.length) {
2207
+ const line = lines[index];
2208
+ if (!line) break;
2209
+ const base = baseMappingAt(lines, index);
2210
+ patched.push(line);
2211
+ index += 1;
2212
+ if (!base) continue;
2213
+ patched.push(...lines.slice(index, base.index + 1));
2214
+ index = base.index + 1;
2215
+ const { block, next } = collectBlock(lines, index, (entry) => entry.body.trim().length === 0 || indentOf(entry.body).length > base.indent.length);
2216
+ index = next;
2217
+ patched.push(...placeSetting(block, {
2218
+ present: YML_SETTING_PATTERN,
2219
+ render: renderYmlSetting,
2220
+ fallbackIndent: `${base.indent}${YML_NESTED_INDENT}`,
2221
+ fallbackEnding: base.line.ending
2222
+ }));
2223
+ }
2224
+ return joinLines(patched);
2225
+ }
2226
+ /**
2227
+ * Applies the entitlements-modification setting to every generated iOS project file —
2228
+ * `project.yml` and each `*.xcodeproj/project.pbxproj`. Idempotent: a second pass reports
2229
+ * every file unchanged. Nothing under `gen/apple/build` is ever read or written.
2230
+ *
2231
+ * @param projectDirectory - The Tauri project root.
2232
+ * @param genDirectory - The `src-tauri/gen/apple` directory.
2233
+ * @returns The paths patched vs. left unchanged.
2234
+ * @example
2235
+ * ```ts
2236
+ * await patchXcodeSettings(projectDir, path.join(projectDir, "src-tauri/gen/apple"));
2237
+ * ```
2238
+ */
2239
+ async function patchXcodeSettings(projectDirectory, genDirectory) {
2240
+ const patched = [];
2241
+ const unchanged = [];
2242
+ for (const file of await iosPatchFiles(genDirectory)) {
2243
+ const existing = await (0, node_fs_promises.readFile)(file, "utf8");
2244
+ (await writeIfChanged(file, file.endsWith(".yml") ? applyProjectYmlEntitlementsSetting(existing) : applyPbxprojEntitlementsSetting(existing), projectDirectory) === "written" ? patched : unchanged).push(file);
2245
+ }
2246
+ return {
2247
+ patched,
2248
+ unchanged
2249
+ };
2250
+ }
2251
+ //#endregion
1806
2252
  //#region src/plugins/project/mobile/patch.ts
1807
2253
  /**
1808
2254
  * @file project plugin — the post-init mobile patch pass: it decides WHICH patches a
1809
- * platform needs and in which order. The two patches themselves live next door, in
1810
- * `signing.ts` (the Android release-signing block) and `runner.ts` (the Xcode /
1811
- * Android-Studio runner command).
2255
+ * platform needs and in which order. The patches themselves live next door, in
2256
+ * `signing.ts` (the Android release-signing block), `runner.ts` (the Xcode /
2257
+ * Android-Studio runner command) and `xcode-settings.ts` (the iOS
2258
+ * entitlements-modification setting that makes a REBUILD work).
2259
+ */
2260
+ /**
2261
+ * Merges the results of several patches over an overlapping file set into one report. A
2262
+ * file both patches touched is PATCHED — it appears once, and never in both lists.
2263
+ *
2264
+ * @param results - One result per patch, in the order the patches ran.
2265
+ * @returns The merged report.
2266
+ * @example
2267
+ * ```ts
2268
+ * mergePatchResults(settingsResult, runnerResult);
2269
+ * ```
1812
2270
  */
2271
+ function mergePatchResults(...results) {
2272
+ const patched = new Set(results.flatMap((result) => [...result.patched]));
2273
+ const unchanged = new Set(results.flatMap((result) => result.unchanged.filter((file) => !patched.has(file))));
2274
+ return {
2275
+ patched: [...patched],
2276
+ unchanged: [...unchanged]
2277
+ };
2278
+ }
1813
2279
  /**
1814
2280
  * Deterministic, idempotent post-init patch pass over an existing complete gen/ tree.
1815
- * Android gets its release signing block; both platforms get the runner-command rewrite
1816
- * when the caller supplies a `runner` (omit it and the rewrite is skipped). iOS carries no
1817
- * mobile-permission plist mechanism in v1 (D-012), so signing is conf-only there.
2281
+ * Android gets its release signing block; iOS gets the Xcode entitlements-modification
2282
+ * setting (without it the SECOND build of the same tree fails); both platforms get the
2283
+ * runner-command rewrite when the caller supplies a `runner` (omit it and the rewrite is
2284
+ * skipped). iOS carries no mobile-permission plist mechanism in v1 (D-012), so signing is
2285
+ * conf-only there.
1818
2286
  *
1819
2287
  * @param projectDirectory - The Tauri project root.
1820
2288
  * @param opts - The mobile platform, and optionally the absolute Node/tauri.js runner pair.
@@ -1829,27 +2297,25 @@ async function patchAndroidSigning(projectDirectory, genDirectory, signing) {
1829
2297
  async function patchMobile(projectDirectory, opts, signing) {
1830
2298
  const genDirectory = genDirectoryPath(projectDirectory, opts.target);
1831
2299
  if (opts.target === "ios") {
1832
- if (!opts.runner || !(0, node_fs.existsSync)(genDirectory)) return {
2300
+ if (!(0, node_fs.existsSync)(genDirectory)) return {
1833
2301
  patched: [],
1834
2302
  unchanged: []
1835
2303
  };
1836
- return patchRunner(projectDirectory, genDirectory, {
2304
+ const settingsResult = await patchXcodeSettings(projectDirectory, genDirectory);
2305
+ if (!opts.runner) return settingsResult;
2306
+ return mergePatchResults(settingsResult, await patchRunner(projectDirectory, genDirectory, {
1837
2307
  target: opts.target,
1838
2308
  runner: opts.runner
1839
- });
2309
+ }));
1840
2310
  }
1841
2311
  const buildGradlePath = node_path.default.join(genDirectory, "app", "build.gradle.kts");
1842
2312
  if (!(0, node_fs.existsSync)(genDirectory) || !(0, node_fs.existsSync)(buildGradlePath)) throw new Error(`[native] Android gen/ tree not found or incomplete at ${genDirectory}.\n Run the mobile init pass (tauri android init) before patching signing state.`);
1843
2313
  const result = await patchAndroidSigning(projectDirectory, genDirectory, signing.android ?? {});
1844
2314
  if (!opts.runner) return result;
1845
- const runnerResult = await patchRunner(projectDirectory, genDirectory, {
2315
+ return mergePatchResults(result, await patchRunner(projectDirectory, genDirectory, {
1846
2316
  target: opts.target,
1847
2317
  runner: opts.runner
1848
- });
1849
- return {
1850
- patched: [...result.patched, ...runnerResult.patched],
1851
- unchanged: [...result.unchanged, ...runnerResult.unchanged]
1852
- };
2318
+ }));
1853
2319
  }
1854
2320
  //#endregion
1855
2321
  //#region src/plugins/project/registry.ts
@@ -2280,12 +2746,34 @@ function createProjectApi(ctx) {
2280
2746
  });
2281
2747
  return result;
2282
2748
  };
2749
+ /**
2750
+ * Removes the previous build output of a mobile target, so the next compile writes into
2751
+ * an empty tree — iOS only (Gradle manages Android's own `build` tree). Guarded by the
2752
+ * same derived-path rule as {@link runClean}.
2753
+ *
2754
+ * @param opts - The clear options.
2755
+ * @param opts.target - The mobile platform whose previous build output to remove.
2756
+ * @returns The paths actually removed — empty when there was nothing to remove.
2757
+ * @example
2758
+ * ```ts
2759
+ * await runClearMobileBuildOutput({ target: "ios" });
2760
+ * ```
2761
+ */
2762
+ const runClearMobileBuildOutput = async (opts) => {
2763
+ const result = await clearMobileBuildOutput(ctx.global.projectDir, opts.target);
2764
+ ctx.log.debug("project:clearMobileBuildOutput", {
2765
+ target: opts.target,
2766
+ removed: result.removed.length
2767
+ });
2768
+ return result;
2769
+ };
2283
2770
  return {
2284
2771
  generate: generateArtifacts,
2285
2772
  getBundleLayout,
2286
2773
  getCompleteness: checkCompleteness,
2287
2774
  patchMobile: runPatchMobile,
2288
2775
  clean: runClean,
2776
+ clearMobileBuildOutput: runClearMobileBuildOutput,
2289
2777
  resolveDerivedPath,
2290
2778
  ensureIconSource,
2291
2779
  resolve,
@@ -4321,6 +4809,8 @@ async function runIcons(ctx, deps, opts) {
4321
4809
  }
4322
4810
  /** Matches a tauri build output line signalling the compile→bundle transition. */
4323
4811
  const BUNDLING_TRANSITION_PATTERN = /bundling/i;
4812
+ /** Compile-phase detail reported when a previous build's output had to be removed first. */
4813
+ const CLEARED_BUILD_OUTPUT_DETAIL = "cleared previous build output";
4324
4814
  /**
4325
4815
  * Formats a compile tick into the `native:phase` "progress" detail string — real crate
4326
4816
  * counts, never a fake percentage.
@@ -4372,6 +4862,12 @@ function emitPhase(ctx, target, phase, status, extra) {
4372
4862
  * transition line ever appears, `compile` closes at exit and `bundle` is reported as a
4373
4863
  * zero-duration pass. A failure is attributed to whichever phase is open.
4374
4864
  *
4865
+ * iOS opens with one extra step: the previous build's output is removed before the
4866
+ * compiler starts. `tauri ios build` renames its fresh `.app` into the existing
4867
+ * `gen/apple/build` archive and fails the SECOND build of the same tree with
4868
+ * `Directory not empty`. Removing it is part of compile, so a refusal from the guarded
4869
+ * remove surfaces as a compile error rather than an unattributed throw.
4870
+ *
4375
4871
  * @param ctx - The build pipeline's domain context.
4376
4872
  * @param deps - The resolved project/tauri APIs.
4377
4873
  * @param opts - The target plus the platform build flags to forward.
@@ -4388,6 +4884,9 @@ async function runCompileAndBundle(ctx, deps, opts) {
4388
4884
  let transitionAt;
4389
4885
  emitPhase(ctx, target, "compile", "start");
4390
4886
  try {
4887
+ if (target === "ios") {
4888
+ if ((await deps.project.clearMobileBuildOutput({ target })).removed.length > 0) emitPhase(ctx, target, "compile", "progress", { detail: CLEARED_BUILD_OUTPUT_DETAIL });
4889
+ }
4391
4890
  await deps.tauri.build({
4392
4891
  target,
4393
4892
  simulator: opts.simulator,
@@ -6268,28 +6767,35 @@ const BOX_CHROME_COLUMNS = 6;
6268
6767
  */
6269
6768
  const MIN_TAIL_LINE_LENGTH = 40;
6270
6769
  /**
6271
- * Widest tail line the failure box keeps, derived from the branded console's own width —
6272
- * which {@link terminalWidth} bound to the terminal, so the box follows the real terminal
6273
- * instead of a fixed guess. A single Rust/xcodebuild diagnostic can run thousands of
6274
- * characters; unbounded, it wraps the branded box into unreadable noise, and a fixed bound
6275
- * wide enough to matter (160) wrapped every ordinary 80-column terminal just the same.
6770
+ * Decides how wide a tail line may be — or that it may be any width at all.
6771
+ *
6772
+ * With a terminal attached, the bound follows the real terminal ({@link terminalWidth}
6773
+ * clamps it) minus the box chrome: a single Rust/xcodebuild diagnostic can run thousands of
6774
+ * characters and would wrap the branded box into unreadable noise.
6276
6775
  *
6277
- * @param consoleWidth - The branded console's width (`ui.width`).
6278
- * @returns The maximum tail line length for that width.
6776
+ * With no terminal — CI, `native build > build.log`, a piped run — there is nothing to wrap
6777
+ * against, and the output is READ afterwards: truncating there deletes the one copy of the
6778
+ * toolchain's own error text. So a stream without columns gets no bound at all.
6779
+ *
6780
+ * @param columns - The stream's column count (`process.stdout.columns`), undefined when piped.
6781
+ * @returns The maximum tail line length, or undefined when lines must be kept whole.
6279
6782
  * @example
6280
6783
  * ```ts
6281
- * maxTailLineLength(66); // 60
6282
- * maxTailLineLength(120); // 114
6784
+ * tailLineBound(120); // 114
6785
+ * tailLineBound(40); // 54 — clamped up to 60, minus the chrome
6786
+ * tailLineBound(undefined); // undefined — piped: keep the full line
6283
6787
  * ```
6284
6788
  */
6285
- function maxTailLineLength(consoleWidth) {
6286
- return Math.max(MIN_TAIL_LINE_LENGTH, consoleWidth - BOX_CHROME_COLUMNS);
6789
+ function tailLineBound(columns) {
6790
+ if (columns === void 0) return void 0;
6791
+ return Math.max(MIN_TAIL_LINE_LENGTH, terminalWidth(columns) - BOX_CHROME_COLUMNS);
6287
6792
  }
6288
6793
  /**
6289
- * Truncates one tail line to `budget`, marking the cut with an ellipsis.
6794
+ * Truncates one tail line to `budget`, marking the cut with an ellipsis. An undefined
6795
+ * budget keeps the line whole.
6290
6796
  *
6291
6797
  * @param line - One line of the scrubbed stderr tail.
6292
- * @param budget - The maximum length, from {@link maxTailLineLength}.
6798
+ * @param budget - The maximum length, from {@link tailLineBound}.
6293
6799
  * @returns The line, at most `budget` characters long.
6294
6800
  * @example
6295
6801
  * ```ts
@@ -6297,26 +6803,38 @@ function maxTailLineLength(consoleWidth) {
6297
6803
  * ```
6298
6804
  */
6299
6805
  function truncateLine(line, budget) {
6300
- if (line.length <= budget) return line;
6806
+ if (budget === void 0 || line.length <= budget) return line;
6301
6807
  return `${line.slice(0, budget - 1)}…`;
6302
6808
  }
6303
6809
  /**
6304
- * Renders a failed build: the classified {@link TauriError}'s scrubbed stderr tail framed
6305
- * in a branded box, then the `[native]` error line. Cause first, verdict second —
6306
- * the tail is the only place the real toolchain diagnostic survives. A non-`TauriError`
6307
- * failure (or an empty tail) prints the error line alone.
6810
+ * Renders a failed build: the classified {@link TauriError}'s scrubbed stderr tail first,
6811
+ * then the `[native]` error line. Cause first, verdict second — the tail is the only place
6812
+ * the real toolchain diagnostic survives. A non-`TauriError` failure (or an empty tail)
6813
+ * prints the error line alone.
6814
+ *
6815
+ * How the tail is framed follows the stream, for the same reason its lines are (or are not)
6816
+ * truncated ({@link tailLineBound}). With a terminal attached it is a branded box, cut to
6817
+ * the terminal's width. With none — CI, `native build > build.log`, a pipe — every line is
6818
+ * printed plainly, in order: the box pads each line to the widest one, so a single
6819
+ * 5000-character Rust diagnostic would pad the entire tail to 5000 columns and bloat the
6820
+ * very log the lines were kept whole for.
6308
6821
  *
6309
6822
  * @param ui - The branded console to render through.
6310
6823
  * @param error - The failure thrown by `build.run`/`build.runAll`.
6824
+ * @param columns - The stream's column count (default: `process.stdout.columns`).
6311
6825
  * @example
6312
6826
  * ```ts
6313
6827
  * try { await build.run({ target: "macos" }); } catch (error) { renderBuildFailure(ui, error); throw error; }
6314
6828
  * ```
6315
6829
  */
6316
- function renderBuildFailure(ui, error) {
6830
+ function renderBuildFailure(ui, error, columns = process.stdout.columns) {
6317
6831
  const stderrTail = error instanceof TauriError ? error.stderrTail.trim() : "";
6318
- const budget = maxTailLineLength(ui.width);
6319
- if (stderrTail) ui.box(stderrTail.split(/\r?\n/).map((line) => truncateLine(line, budget)));
6832
+ const budget = tailLineBound(columns);
6833
+ if (stderrTail) {
6834
+ const tailLines = stderrTail.split(/\r?\n/);
6835
+ if (budget === void 0) for (const line of tailLines) ui.line(line);
6836
+ else ui.box(tailLines.map((line) => truncateLine(line, budget)));
6837
+ }
6320
6838
  ui.error(error instanceof Error ? error.message : String(error));
6321
6839
  }
6322
6840
  //#endregion