@moku-labs/native 0.1.0

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 ADDED
@@ -0,0 +1,4127 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __exportAll = (all, no_symbols) => {
10
+ let target = {};
11
+ for (var name in all) __defProp(target, name, {
12
+ get: all[name],
13
+ enumerable: true
14
+ });
15
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
16
+ return target;
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
20
+ key = keys[i];
21
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
22
+ get: ((k) => from[k]).bind(null, key),
23
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
24
+ });
25
+ }
26
+ return to;
27
+ };
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
29
+ value: mod,
30
+ enumerable: true
31
+ }) : target, mod));
32
+ //#endregion
33
+ let _moku_labs_common = require("@moku-labs/common");
34
+ let _moku_labs_core = require("@moku-labs/core");
35
+ let node_path = require("node:path");
36
+ node_path = __toESM(node_path, 1);
37
+ let node_fs = require("node:fs");
38
+ let node_fs_promises = require("node:fs/promises");
39
+ let node_crypto = require("node:crypto");
40
+ let node_module = require("node:module");
41
+ let node_child_process = require("node:child_process");
42
+ let node_process = require("node:process");
43
+ node_process = __toESM(node_process, 1);
44
+ let _moku_labs_common_cli = require("@moku-labs/common/cli");
45
+ //#region src/config.ts
46
+ /**
47
+ * @file Framework configuration — Config + Events types, shared constants, core plugin registration.
48
+ */
49
+ /** The five packaging targets (D1 — all five in v1). */
50
+ const TARGETS = [
51
+ "macos",
52
+ "windows",
53
+ "linux",
54
+ "ios",
55
+ "android"
56
+ ];
57
+ /** Pipeline phases in execution order — drives NativePhase and progress rendering (mirrors web's PHASE_ORDER). */
58
+ const PHASE_ORDER = [
59
+ "scaffold",
60
+ "codegen",
61
+ "icons",
62
+ "compile",
63
+ "bundle",
64
+ "collect"
65
+ ];
66
+ const defaultConfig$3 = {
67
+ app: {
68
+ name: "",
69
+ identifier: ""
70
+ },
71
+ web: {
72
+ build: "bun run build",
73
+ dev: {
74
+ command: "bun run dev",
75
+ url: "http://localhost:5173"
76
+ },
77
+ dist: "dist"
78
+ },
79
+ system: [],
80
+ capabilities: {},
81
+ targets: TARGETS,
82
+ projectDir: ".moku/tauri",
83
+ outDir: "dist-native",
84
+ signing: {}
85
+ };
86
+ const coreConfig = (0, _moku_labs_core.createCoreConfig)("native", {
87
+ config: defaultConfig$3,
88
+ plugins: [_moku_labs_common.logPlugin, _moku_labs_common.envPlugin]
89
+ });
90
+ /**
91
+ * Creates a plugin bound to this framework's Config/Events chain.
92
+ *
93
+ * @example
94
+ * ```ts
95
+ * export const xxxPlugin = createPlugin("xxx", { api: createXxxApi });
96
+ * ```
97
+ */
98
+ const createPlugin$1 = coreConfig.createPlugin;
99
+ /**
100
+ * Creates the framework core from this config (Layer 2 step 2).
101
+ *
102
+ * @example
103
+ * ```ts
104
+ * const framework = createCore(coreConfig, { plugins: [...] });
105
+ * ```
106
+ */
107
+ const createCore = coreConfig.createCore;
108
+ //#endregion
109
+ //#region src/plugins/project/clean.ts
110
+ /**
111
+ * @file project plugin — target-scoped destructive cleanup (pure path computation + guarded rm).
112
+ */
113
+ /**
114
+ * Tauri's bundle output directories are FORMAT-named, not target-named
115
+ * (`bundle/dmg`, `bundle/nsis`, …) — one desktop target maps to several
116
+ * format directories (same table spec 03-build's collect phase reads).
117
+ */
118
+ const DESKTOP_BUNDLE_FORMATS = {
119
+ macos: ["dmg", "macos"],
120
+ windows: ["nsis", "msi"],
121
+ linux: [
122
+ "appimage",
123
+ "deb",
124
+ "rpm"
125
+ ]
126
+ };
127
+ /**
128
+ * Computes the absolute path(s) a clean pass would delete for a given scope, without
129
+ * touching the filesystem. Mobile targets scope to `gen/<platform>` only; desktop
130
+ * targets scope to that target's bundle-FORMAT output directories under Cargo's
131
+ * `target/` (Tauri names bundle dirs by format — dmg/nsis/appimage/… — never by
132
+ * target); omitting `target` scopes to the whole project root (D-006: project owns
133
+ * this destructive filesystem knowledge — `cli.clean` is a thin delegate).
134
+ *
135
+ * @param projectDirectory - The Tauri project root.
136
+ * @param target - The optional packaging target to scope the clean to.
137
+ * @returns The list of absolute paths this clean pass would remove.
138
+ * @example
139
+ * ```ts
140
+ * cleanTargets("/repo/.moku/tauri", "android"); // ["/repo/.moku/tauri/src-tauri/gen/android"]
141
+ * cleanTargets("/repo/.moku/tauri", "windows"); // [...bundle/nsis, ...bundle/msi]
142
+ * ```
143
+ */
144
+ function cleanTargets(projectDirectory, target) {
145
+ const root = node_path.default.resolve(projectDirectory);
146
+ if (!target) return [root];
147
+ if (target === "ios" || target === "android") {
148
+ const platform = target === "ios" ? "apple" : "android";
149
+ return [node_path.default.resolve(root, "src-tauri", "gen", platform)];
150
+ }
151
+ return DESKTOP_BUNDLE_FORMATS[target].map((format) => node_path.default.resolve(root, "src-tauri", "target", "release", "bundle", format));
152
+ }
153
+ /**
154
+ * Refuses to operate on a path outside `root` — the last line of defense before any
155
+ * destructive filesystem call in this plugin.
156
+ *
157
+ * @param root - The resolved project root that every clean target must stay within.
158
+ * @param candidate - The resolved path a clean pass wants to remove.
159
+ * @throws {Error} When `candidate` is not `root` itself and not nested under it.
160
+ * @example
161
+ * ```ts
162
+ * assertWithinRoot("/repo/.moku/tauri", "/repo/.moku/tauri/src-tauri/gen/android"); // ok
163
+ * assertWithinRoot("/repo/.moku/tauri", "/etc/passwd"); // throws
164
+ * ```
165
+ */
166
+ function assertWithinRoot(root, candidate) {
167
+ if (candidate !== root && !candidate.startsWith(root + node_path.default.sep)) throw new Error(`[native] Refusing to clean path outside projectDir: ${candidate}.\n Check the projectDir/target configuration before retrying.`);
168
+ }
169
+ /**
170
+ * Deletes derived state for the given scope. `target` omitted removes the whole
171
+ * `projectDir`; a mobile `target` removes `gen/<platform>` only; a desktop `target`
172
+ * removes that target's bundle output. Every candidate path is validated against
173
+ * `projectDir` before deletion, and only paths that actually exist are removed/reported.
174
+ *
175
+ * @param projectDirectory - The Tauri project root.
176
+ * @param target - The optional packaging target to scope the clean to.
177
+ * @returns The list of paths actually removed.
178
+ * @example
179
+ * ```ts
180
+ * await clean("/repo/.moku/tauri", "android");
181
+ * ```
182
+ */
183
+ async function clean(projectDirectory, target) {
184
+ const root = node_path.default.resolve(projectDirectory);
185
+ const removed = [];
186
+ for (const candidate of cleanTargets(projectDirectory, target)) {
187
+ assertWithinRoot(root, candidate);
188
+ if ((0, node_fs.existsSync)(candidate)) {
189
+ await (0, node_fs_promises.rm)(candidate, {
190
+ recursive: true,
191
+ force: true
192
+ });
193
+ removed.push(candidate);
194
+ }
195
+ }
196
+ return { removed };
197
+ }
198
+ //#endregion
199
+ //#region src/plugins/project/completeness.ts
200
+ /**
201
+ * @file project plugin — mobile gen/-tree required-file completeness gate.
202
+ */
203
+ /**
204
+ * Required top-level entries per mobile `gen/<platform>` tree (Tauri 2.9.x scaffolding).
205
+ * A partial init (tauri#13902) can leave some of these absent — `completeness` checks
206
+ * the required-file SET, not mere directory existence.
207
+ */
208
+ const REQUIRED_FILES = {
209
+ ios: [
210
+ "project.yml",
211
+ "Assets.xcassets",
212
+ "Sources",
213
+ "ExportOptions.plist"
214
+ ],
215
+ android: [
216
+ "build.gradle.kts",
217
+ "settings.gradle.kts",
218
+ "gradle.properties",
219
+ "app/build.gradle.kts",
220
+ "app/src/main/AndroidManifest.xml"
221
+ ]
222
+ };
223
+ /**
224
+ * The `gen/<platform>` subdirectory name Tauri uses for a mobile target (`"apple"` for iOS).
225
+ *
226
+ * @param target - A mobile packaging target.
227
+ * @returns The `gen/<platform>` directory name.
228
+ * @example
229
+ * ```ts
230
+ * genPlatformDirectoryName("ios"); // "apple"
231
+ * ```
232
+ */
233
+ function genPlatformDirectoryName(target) {
234
+ return target === "ios" ? "apple" : "android";
235
+ }
236
+ /**
237
+ * Returns the required-file set for a mobile platform — consumed by `doctor` and by
238
+ * `completeness` itself.
239
+ *
240
+ * @param platform - The mobile platform.
241
+ * @returns The frozen list of required paths, relative to `src-tauri/gen/<platform>`.
242
+ * @example
243
+ * ```ts
244
+ * requiredFiles("android"); // ["build.gradle.kts", "settings.gradle.kts", ...]
245
+ * ```
246
+ */
247
+ function requiredFiles(platform) {
248
+ return REQUIRED_FILES[platform];
249
+ }
250
+ /**
251
+ * Checks the mobile `gen/<platform>` tree against its required-file set. Desktop
252
+ * targets are not-applicable (no gen/ tree). Returns "not-initialized" when the gen/
253
+ * directory itself is absent, "incomplete" with the missing subset for a partial init,
254
+ * or "complete" when every required file/directory is present.
255
+ *
256
+ * @param projectDirectory - The Tauri project root (contains `src-tauri/`).
257
+ * @param target - The packaging target being checked.
258
+ * @returns The completeness verdict.
259
+ * @example
260
+ * ```ts
261
+ * completeness("/repo/.moku/tauri", "android"); // { status: "complete" }
262
+ * ```
263
+ */
264
+ function completeness(projectDirectory, target) {
265
+ if (target !== "ios" && target !== "android") return { status: "not-applicable" };
266
+ const genDirectory = node_path.default.join(projectDirectory, "src-tauri", "gen", genPlatformDirectoryName(target));
267
+ if (!(0, node_fs.existsSync)(genDirectory)) return { status: "not-initialized" };
268
+ const missing = REQUIRED_FILES[target].filter((file) => !(0, node_fs.existsSync)(node_path.default.join(genDirectory, file)));
269
+ if (missing.length > 0) return {
270
+ status: "incomplete",
271
+ missing
272
+ };
273
+ return { status: "complete" };
274
+ }
275
+ //#endregion
276
+ //#region src/plugins/project/generators/capabilities.ts
277
+ /**
278
+ * Generates `src-tauri/capabilities/default.json` — the permission ids contributed by
279
+ * every capability resolved for this target. Capabilities are pre-filtered (by
280
+ * `resolveConfiguredCapabilities` in `api.ts`) to rows whose `platforms` include the
281
+ * target, so a desktop-only row like tray is naturally absent from a mobile target-set.
282
+ *
283
+ * @param input - Frozen global config + capabilities resolved for the target.
284
+ * @returns A single-artifact array for `src-tauri/capabilities/default.json`.
285
+ * @example
286
+ * ```ts
287
+ * generateCapabilities({ global, target: "ios", capabilities: [] });
288
+ * ```
289
+ */
290
+ function generateCapabilities(input) {
291
+ const permissions = input.capabilities.flatMap((capability) => capability.permissions);
292
+ const doc = {
293
+ identifier: "default",
294
+ description: "Auto-generated capability set for the composed system plugins.",
295
+ windows: ["main"],
296
+ platforms: [input.target],
297
+ permissions
298
+ };
299
+ return [{
300
+ path: "src-tauri/capabilities/default.json",
301
+ content: `${JSON.stringify(doc, void 0, 2)}\n`
302
+ }];
303
+ }
304
+ //#endregion
305
+ //#region src/plugins/project/generators/cargo.ts
306
+ /**
307
+ * Derives a valid Cargo package name from the app's display name — lowercased,
308
+ * non-alphanumeric runs collapsed to a single hyphen, and guaranteed to start with a
309
+ * letter (Cargo package names must match `[a-z][a-z0-9_-]*`).
310
+ *
311
+ * @param appName - The consumer app's display name (`Config["app"]["name"]`).
312
+ * @returns A Cargo-safe package name; falls back to `"moku-native-app"` when empty.
313
+ * @example
314
+ * ```ts
315
+ * sanitizePackageName("My Cool App!"); // "my-cool-app"
316
+ * ```
317
+ */
318
+ function sanitizePackageName(appName) {
319
+ const slug = appName.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-").split("-").filter(Boolean).join("-");
320
+ if (slug.length === 0) return "moku-native-app";
321
+ return /^[a-z]/.test(slug) ? slug : `app-${slug}`;
322
+ }
323
+ /**
324
+ * Converts a Cargo package name (may contain hyphens) into the underscored Rust crate
325
+ * identifier used in `[lib] name` and in `use`/path expressions — Cargo package names
326
+ * may hyphenate, but Rust identifiers may not.
327
+ *
328
+ * @param packageName - A Cargo-safe package name, e.g. from `sanitizePackageName`.
329
+ * @returns The underscored Rust identifier form.
330
+ * @example
331
+ * ```ts
332
+ * crateIdent("my-cool-app"); // "my_cool_app"
333
+ * ```
334
+ */
335
+ function crateIdent(packageName) {
336
+ return packageName.replaceAll("-", "_");
337
+ }
338
+ /**
339
+ * Generates `src-tauri/Cargo.toml` — the package manifest plus one pinned dependency
340
+ * line per resolved capability that carries a real Rust plugin init (rows with an
341
+ * empty `rustInit`, e.g. tray's core-feature row, contribute no crate dependency).
342
+ *
343
+ * @param input - Frozen global config + capabilities resolved for the target.
344
+ * @returns A single-artifact array for `src-tauri/Cargo.toml`.
345
+ * @example
346
+ * ```ts
347
+ * generateCargo({ global, target: "macos", capabilities: [] });
348
+ * ```
349
+ */
350
+ function generateCargo(input) {
351
+ const packageName = sanitizePackageName(input.global.app.name);
352
+ const pinnedDeps = input.capabilities.filter((capability) => capability.rustInit !== "").map((capability) => `${capability.crate} = "${capability.crateRange}"`).toSorted();
353
+ return [{
354
+ path: "src-tauri/Cargo.toml",
355
+ content: [
356
+ "[package]",
357
+ `name = "${packageName}"`,
358
+ `version = "${input.global.app.version ?? "0.1.0"}"`,
359
+ "edition = \"2021\"",
360
+ "",
361
+ "[lib]",
362
+ `name = "${crateIdent(packageName)}_lib"`,
363
+ "crate-type = [\"staticlib\", \"cdylib\", \"rlib\"]",
364
+ "",
365
+ "[build-dependencies]",
366
+ "tauri-build = { version = \"2\", features = [] }",
367
+ "",
368
+ "[dependencies]",
369
+ "tauri = { version = \"2\", features = [] }",
370
+ "serde = { version = \"1\", features = [\"derive\"] }",
371
+ "serde_json = \"1\"",
372
+ ...pinnedDeps,
373
+ ""
374
+ ].join("\n")
375
+ }];
376
+ }
377
+ //#endregion
378
+ //#region src/plugins/project/generators/rust.ts
379
+ /**
380
+ * @file project plugin generator — main.rs/lib.rs with mobile entry point + plugin init lines.
381
+ */
382
+ /**
383
+ * Generates `src-tauri/src/lib.rs` and `src-tauri/src/main.rs`. `lib.rs` carries the
384
+ * `#[cfg_attr(mobile, tauri::mobile_entry_point)]`-annotated `run()` with one
385
+ * `.plugin(...)` init line per resolved capability that has a real Rust init (empty
386
+ * `rustInit` rows, e.g. tray, contribute no line); `main.rs` is a thin entry point that
387
+ * calls into the lib crate.
388
+ *
389
+ * @param input - Frozen global config + capabilities resolved for the target.
390
+ * @returns Artifacts for `src-tauri/src/lib.rs` and `src-tauri/src/main.rs`.
391
+ * @example
392
+ * ```ts
393
+ * generateRust({ global, target: "android", capabilities: [] });
394
+ * ```
395
+ */
396
+ function generateRust(input) {
397
+ const packageIdent = crateIdent(sanitizePackageName(input.global.app.name));
398
+ const library = [
399
+ "#[cfg_attr(mobile, tauri::mobile_entry_point)]",
400
+ "pub fn run() {",
401
+ " tauri::Builder::default()",
402
+ ...input.capabilities.filter((capability) => capability.rustInit !== "").map((capability) => ` .plugin(${capability.rustInit})`).toSorted(),
403
+ " .run(tauri::generate_context!())",
404
+ " .expect(\"error while running tauri application\");",
405
+ "}",
406
+ ""
407
+ ].join("\n");
408
+ const main = [
409
+ "#![cfg_attr(all(not(debug_assertions), target_os = \"windows\"), windows_subsystem = \"windows\")]",
410
+ "",
411
+ "fn main() {",
412
+ ` ${packageIdent}_lib::run();`,
413
+ "}",
414
+ ""
415
+ ].join("\n");
416
+ return [{
417
+ path: "src-tauri/src/lib.rs",
418
+ content: library
419
+ }, {
420
+ path: "src-tauri/src/main.rs",
421
+ content: main
422
+ }];
423
+ }
424
+ //#endregion
425
+ //#region src/plugins/project/generators/sidecar.ts
426
+ /**
427
+ * Generates the `Info.ios.plist` SIDECAR at the src-tauri root — a future-mechanism
428
+ * seam for iOS mobile-permission plist keys (D-012). Every v1 registry row carries an
429
+ * empty `sidecarPlist`, so this emits no artifact today; it stays pure and
430
+ * generator-shaped so a future row carrying `sidecarPlist` entries activates it with
431
+ * zero pipeline changes.
432
+ *
433
+ * @param input - Frozen global config + capabilities resolved for the target.
434
+ * @returns An artifact for `src-tauri/Info.ios.plist` when any resolved capability
435
+ * carries sidecar entries, otherwise an empty array.
436
+ * @example
437
+ * ```ts
438
+ * generateSidecar({ global, target: "ios", capabilities: [] }); // []
439
+ * ```
440
+ */
441
+ function generateSidecar(input) {
442
+ const entries = input.capabilities.flatMap((capability) => capability.sidecarPlist);
443
+ if (entries.length === 0) return [];
444
+ return [{
445
+ path: "src-tauri/Info.ios.plist",
446
+ content: [
447
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
448
+ "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">",
449
+ "<plist version=\"1.0\">",
450
+ "<dict>",
451
+ entries.map((entry) => ` <key>${entry.key}</key>\n <string>${entry.value}</string>`).join("\n"),
452
+ "</dict>",
453
+ "</plist>",
454
+ ""
455
+ ].join("\n")
456
+ }];
457
+ }
458
+ //#endregion
459
+ //#region src/plugins/project/generators/tauri-conf.ts
460
+ /**
461
+ * Generates `src-tauri/tauri.conf.json` — app identity, the web build/dev wiring, and
462
+ * one `plugins.<name>` block per resolved capability (this is where deep-link's scheme
463
+ * rides — per D-011/D-012 the whole v1 mobile-permission story is conf-only).
464
+ *
465
+ * @param input - Frozen global config + capabilities resolved for the target.
466
+ * @returns A single-artifact array for `src-tauri/tauri.conf.json`.
467
+ * @example
468
+ * ```ts
469
+ * generateTauriConf({ global, target: "ios", capabilities: [] });
470
+ * ```
471
+ */
472
+ function generateTauriConf(input) {
473
+ const { global, capabilities } = input;
474
+ const plugins = {};
475
+ for (const capability of capabilities) plugins[capability.name] = capability.conf;
476
+ const conf = {
477
+ productName: global.app.name,
478
+ identifier: global.app.identifier,
479
+ version: global.app.version ?? "0.1.0",
480
+ build: {
481
+ beforeDevCommand: global.web.dev.command,
482
+ beforeBuildCommand: global.web.build,
483
+ devUrl: global.web.dev.url,
484
+ frontendDist: global.web.dist
485
+ },
486
+ app: { windows: [{ title: global.app.name }] },
487
+ bundle: {
488
+ active: true,
489
+ targets: "all",
490
+ iOS: {},
491
+ android: {}
492
+ },
493
+ plugins
494
+ };
495
+ return [{
496
+ path: "src-tauri/tauri.conf.json",
497
+ content: `${JSON.stringify(conf, void 0, 2)}\n`
498
+ }];
499
+ }
500
+ //#endregion
501
+ //#region src/plugins/project/writer.ts
502
+ /**
503
+ * @file project plugin — write-if-changed content-hash writer.
504
+ */
505
+ const FORBIDDEN_SEGMENTS = /* @__PURE__ */ new Set([
506
+ "target",
507
+ ".gradle",
508
+ "DerivedData",
509
+ "Pods"
510
+ ]);
511
+ /**
512
+ * Guards codegen writes against derived/build-output directories that generators must
513
+ * never touch — Cargo's `target/`, Gradle's `.gradle/`, Xcode's `DerivedData`, and
514
+ * CocoaPods' `Pods` are all managed by `tauri build` (the `tauri` plugin), not by this
515
+ * write-if-changed writer.
516
+ *
517
+ * @param filePath - The path a generator wants to write.
518
+ * @throws {Error} When the path contains a forbidden derived-output segment.
519
+ * @example
520
+ * ```ts
521
+ * assertWritablePath("/repo/.moku/tauri/src-tauri/tauri.conf.json"); // ok
522
+ * assertWritablePath("/repo/.moku/tauri/src-tauri/target/debug/x"); // throws
523
+ * ```
524
+ */
525
+ function assertWritablePath(filePath) {
526
+ const segments = new Set(filePath.split(node_path.default.sep));
527
+ const hit = [...FORBIDDEN_SEGMENTS].find((segment) => segments.has(segment));
528
+ if (hit) throw new Error(`[native] Refusing to write generated content into derived directory "${hit}".\n Generators only own pure project files — "tauri build" owns ${hit}/.`);
529
+ }
530
+ /**
531
+ * Hashes UTF-8 text content with SHA-256 for stateless content-equality comparison.
532
+ *
533
+ * @param content - The text to hash.
534
+ * @returns A hex-encoded SHA-256 digest.
535
+ * @example
536
+ * ```ts
537
+ * hashOf("hello"); // a 64-char hex SHA-256 digest
538
+ * ```
539
+ */
540
+ function hashOf(content) {
541
+ return (0, node_crypto.createHash)("sha256").update(content, "utf8").digest("hex");
542
+ }
543
+ /**
544
+ * Reads a file's content, treating a missing file as "no existing content" rather
545
+ * than a thrown error.
546
+ *
547
+ * @param filePath - The path to read.
548
+ * @returns The file content, or undefined when the file does not exist.
549
+ * @example
550
+ * ```ts
551
+ * const existing = await readExisting("/repo/.moku/tauri/src-tauri/tauri.conf.json");
552
+ * ```
553
+ */
554
+ async function readExisting(filePath) {
555
+ try {
556
+ return await (0, node_fs_promises.readFile)(filePath, "utf8");
557
+ } catch {
558
+ return;
559
+ }
560
+ }
561
+ /**
562
+ * Writes `content` to `filePath` only when it differs from the file already on disk.
563
+ * The on-disk file is hashed at write time (stateless diff — no in-memory hash cache),
564
+ * and unchanged content is never rewritten, which preserves mtime and keeps Cargo's
565
+ * incremental build cache warm.
566
+ *
567
+ * @param filePath - The absolute path to write.
568
+ * @param content - The desired file content.
569
+ * @returns `"written"` when the file was created/updated, `"unchanged"` when identical
570
+ * content was already on disk.
571
+ * @throws {Error} When `filePath` targets a derived/build-output directory.
572
+ * @example
573
+ * ```ts
574
+ * const action = await writeIfChanged("/repo/.moku/tauri/src-tauri/tauri.conf.json", json);
575
+ * ```
576
+ */
577
+ async function writeIfChanged(filePath, content) {
578
+ assertWritablePath(filePath);
579
+ const existing = await readExisting(filePath);
580
+ if (existing !== void 0 && hashOf(existing) === hashOf(content)) return "unchanged";
581
+ await (0, node_fs_promises.mkdir)(node_path.default.dirname(filePath), { recursive: true });
582
+ await (0, node_fs_promises.writeFile)(filePath, content, "utf8");
583
+ return "written";
584
+ }
585
+ //#endregion
586
+ //#region src/plugins/project/patch.ts
587
+ /**
588
+ * @file project plugin — Android signing state patch (the ONLY v1 mobile patch domain).
589
+ */
590
+ const SIGNING_START = "// MOKU-SIGNING-START";
591
+ const SIGNING_END = "// MOKU-SIGNING-END";
592
+ /**
593
+ * Renders the `keystore.properties` content Gradle reads for release signing. Values
594
+ * are env-var REFERENCES and config-safe identifiers only — never raw secrets, per the
595
+ * `SigningConfig` invariant.
596
+ *
597
+ * @param signing - The Android signing config slice (empty object when unconfigured).
598
+ * @returns The `keystore.properties` file content.
599
+ * @example
600
+ * ```ts
601
+ * renderKeystoreProperties({ keystorePath: "keystore.jks", keystorePasswordEnv: "KS_PASSWORD", keyAlias: "release" });
602
+ * ```
603
+ */
604
+ function renderKeystoreProperties(signing) {
605
+ return [
606
+ `storeFile=${signing.keystorePath ?? ""}`,
607
+ `storePasswordEnvVar=${signing.keystorePasswordEnv ?? ""}`,
608
+ `keyAlias=${signing.keyAlias ?? ""}`,
609
+ `keyPasswordEnvVar=${signing.keystorePasswordEnv ?? ""}`,
610
+ ""
611
+ ].join("\n");
612
+ }
613
+ /**
614
+ * Idempotently inserts or replaces the moku-managed signing block inside an existing
615
+ * `app/build.gradle.kts`. Re-applying to already-patched content is a text-level no-op:
616
+ * `applySigningBlock(applySigningBlock(x, s), s) === applySigningBlock(x, s)`.
617
+ *
618
+ * @param existing - The current `build.gradle.kts` content.
619
+ * @param signing - The Android signing config slice (empty object when unconfigured).
620
+ * @returns The patched content with exactly one signing block, sentinel-delimited.
621
+ * @example
622
+ * ```ts
623
+ * applySigningBlock(gradleKts, { keyAlias: "release" });
624
+ * ```
625
+ */
626
+ function applySigningBlock(existing, signing) {
627
+ const block = [
628
+ SIGNING_START,
629
+ "android {",
630
+ " signingConfigs {",
631
+ " create(\"release\") {",
632
+ ` storeFile = file(project.property("MOKU_KEYSTORE_PATH") as? String ?: "${signing.keystorePath ?? ""}")`,
633
+ ` keyAlias = "${signing.keyAlias ?? ""}"`,
634
+ " }",
635
+ " }",
636
+ "}",
637
+ SIGNING_END
638
+ ].join("\n");
639
+ const startIndex = existing.indexOf(SIGNING_START);
640
+ const endIndex = existing.indexOf(SIGNING_END);
641
+ if (startIndex === -1 || endIndex === -1) return `${existing}${existing.endsWith("\n") ? "" : "\n"}\n${block}\n`;
642
+ return `${existing.slice(0, startIndex)}${block}${existing.slice(endIndex + 19)}`;
643
+ }
644
+ /**
645
+ * Deterministic, idempotent post-init patch pass over an existing complete gen/ tree.
646
+ * v1 scope (spike a): Android signing state only (`keystore.properties` +
647
+ * `build.gradle.kts` signing block). iOS has zero mobile-permission plist mechanism to
648
+ * patch in v1 (D-012) — it is a documented no-op, kept in the signature for pipeline
649
+ * uniformity.
650
+ *
651
+ * @param projectDirectory - The Tauri project root.
652
+ * @param target - The mobile platform to patch.
653
+ * @param signing - The full signing config (only `.android` is consulted).
654
+ * @returns The paths patched vs. left unchanged.
655
+ * @throws {Error} When the Android `gen/android` tree (or its `app/build.gradle.kts`) is missing.
656
+ * @example
657
+ * ```ts
658
+ * await patchMobile("/repo/.moku/tauri", "android", { android: { keyAlias: "release" } });
659
+ * ```
660
+ */
661
+ async function patchMobile(projectDirectory, target, signing) {
662
+ if (target === "ios") return {
663
+ patched: [],
664
+ unchanged: []
665
+ };
666
+ const genDirectory = node_path.default.join(projectDirectory, "src-tauri", "gen", "android");
667
+ const buildGradlePath = node_path.default.join(genDirectory, "app", "build.gradle.kts");
668
+ 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.`);
669
+ const android = signing.android ?? {};
670
+ const patched = [];
671
+ const unchanged = [];
672
+ const keystorePropertiesPath = node_path.default.join(genDirectory, "keystore.properties");
673
+ (await writeIfChanged(keystorePropertiesPath, renderKeystoreProperties(android)) === "written" ? patched : unchanged).push(keystorePropertiesPath);
674
+ (await writeIfChanged(buildGradlePath, applySigningBlock(await (0, node_fs_promises.readFile)(buildGradlePath, "utf8"), android)) === "written" ? patched : unchanged).push(buildGradlePath);
675
+ return {
676
+ patched,
677
+ unchanged
678
+ };
679
+ }
680
+ //#endregion
681
+ //#region src/plugins/project/registry.ts
682
+ /**
683
+ * The five v1 capability registry rows (spike (a), Tauri 2.9.x source-verified 2026-07-03).
684
+ * `tray` ships as a core Tauri capability (no dedicated plugin crate/package) — it is
685
+ * modeled here as a plugin-shaped row for registry uniformity across the pipeline; its
686
+ * `confidence: "low"` flags that divergence from the other four real official plugins.
687
+ */
688
+ const REGISTRY = [
689
+ {
690
+ name: "store",
691
+ npmPackage: "@tauri-apps/plugin-store",
692
+ crate: "tauri-plugin-store",
693
+ crateRange: "^2",
694
+ npmRange: "^2",
695
+ rustInit: "tauri_plugin_store::Builder::default().build()",
696
+ permissions: ["store:default"],
697
+ platforms: [
698
+ "macos",
699
+ "windows",
700
+ "linux",
701
+ "ios",
702
+ "android"
703
+ ],
704
+ confidence: "high"
705
+ },
706
+ {
707
+ name: "notification",
708
+ npmPackage: "@tauri-apps/plugin-notification",
709
+ crate: "tauri-plugin-notification",
710
+ crateRange: "^2",
711
+ npmRange: "^2",
712
+ rustInit: "tauri_plugin_notification::init()",
713
+ permissions: ["notification:default"],
714
+ platforms: [
715
+ "macos",
716
+ "windows",
717
+ "linux",
718
+ "ios",
719
+ "android"
720
+ ],
721
+ confidence: "high"
722
+ },
723
+ {
724
+ name: "clipboard-manager",
725
+ npmPackage: "@tauri-apps/plugin-clipboard-manager",
726
+ crate: "tauri-plugin-clipboard-manager",
727
+ crateRange: "^2",
728
+ npmRange: "^2",
729
+ rustInit: "tauri_plugin_clipboard_manager::init()",
730
+ permissions: ["clipboard-manager:allow-read-text", "clipboard-manager:allow-write-text"],
731
+ platforms: [
732
+ "macos",
733
+ "windows",
734
+ "linux",
735
+ "ios",
736
+ "android"
737
+ ],
738
+ confidence: "high"
739
+ },
740
+ {
741
+ name: "tray",
742
+ npmPackage: "@tauri-apps/plugin-tray",
743
+ crate: "tauri-plugin-tray",
744
+ crateRange: "^2",
745
+ npmRange: "^2",
746
+ rustInit: "",
747
+ permissions: ["core:tray:default"],
748
+ platforms: [
749
+ "macos",
750
+ "windows",
751
+ "linux"
752
+ ],
753
+ confidence: "low"
754
+ },
755
+ {
756
+ name: "deep-link",
757
+ npmPackage: "@tauri-apps/plugin-deep-link",
758
+ crate: "tauri-plugin-deep-link",
759
+ crateRange: "^2",
760
+ npmRange: "^2",
761
+ rustInit: "tauri_plugin_deep_link::init()",
762
+ permissions: ["deep-link:default"],
763
+ platforms: [
764
+ "macos",
765
+ "windows",
766
+ "linux",
767
+ "ios",
768
+ "android"
769
+ ],
770
+ confidence: "high"
771
+ }
772
+ ];
773
+ const KNOWN_NAMES = REGISTRY.map((row) => row.name);
774
+ /**
775
+ * Runtime narrowing guard for capability names arriving from `config.system` (plain
776
+ * strings at compile time). Call this before passing a config-sourced name to `resolve`.
777
+ *
778
+ * @param name - A capability name to test against the registry.
779
+ * @returns True (narrowing `name` to `keyof CapabilityConfigMap`) if the registry knows it.
780
+ * @example
781
+ * ```ts
782
+ * if (isKnownCapability(entry.name)) resolve(entry.name);
783
+ * ```
784
+ */
785
+ function isKnownCapability(name) {
786
+ return KNOWN_NAMES.includes(name);
787
+ }
788
+ /**
789
+ * Builds the `[native]`-formatted "unknown capability" error, listing every known
790
+ * capability name so a composition-time failure is immediately actionable.
791
+ *
792
+ * @param name - The unrecognized capability name from `config.system`.
793
+ * @returns A formatted, throw-ready Error.
794
+ * @example
795
+ * ```ts
796
+ * if (!isKnownCapability(name)) throw unknownCapabilityError(name);
797
+ * ```
798
+ */
799
+ function unknownCapabilityError(name) {
800
+ return /* @__PURE__ */ new Error(`[native] Unknown capability "${name}" in config.system.\n Known capabilities: ${KNOWN_NAMES.join(", ")}.`);
801
+ }
802
+ /**
803
+ * Validates every `config.system` entry against the registry, throwing the
804
+ * `unknown-capability` error (with the full known-capability list) at the first
805
+ * unrecognized name. Used at composition time by `onInit`.
806
+ *
807
+ * @param system - The composed `@moku-labs/system` plugin list from global config.
808
+ * @throws {Error} When any entry name is not a known capability.
809
+ * @example
810
+ * ```ts
811
+ * assertKnownCapabilities(ctx.global.system);
812
+ * ```
813
+ */
814
+ function assertKnownCapabilities(system) {
815
+ for (const entry of system) if (!isKnownCapability(entry.name)) throw unknownCapabilityError(entry.name);
816
+ }
817
+ /**
818
+ * Builds the tauri.conf.json `plugins.<name>` contribution for a resolved row. Only
819
+ * deep-link carries consumer-supplied config in v1 (D-011: custom-scheme-only); every
820
+ * other row contributes an empty config block.
821
+ *
822
+ * @param row - The registry row being resolved.
823
+ * @param config - Optional per-capability packaging parameters from `Config["capabilities"]`.
824
+ * @returns The plugin config fragment to place under `plugins.<name>` in tauri.conf.json.
825
+ * @throws {Error} When resolving deep-link without a non-empty `scheme`.
826
+ * @example
827
+ * ```ts
828
+ * buildConfFragment(deepLinkRow, { mode: "scheme", scheme: "myapp" }); // { schemes: ["myapp"] }
829
+ * ```
830
+ */
831
+ function buildConfFragment(row, config) {
832
+ if (row.name !== "deep-link") return {};
833
+ const scheme = config && "scheme" in config ? config.scheme : void 0;
834
+ if (!scheme) throw new Error("[native] deep-link capability requires a non-empty scheme.\n Set capabilities[\"deep-link\"] = { mode: \"scheme\", scheme: \"yourscheme\" }.");
835
+ return { schemes: [scheme] };
836
+ }
837
+ /**
838
+ * Typed registry lookup — resolves a capability row against optional consumer config,
839
+ * producing the full packaging contribution (conf fragment + the future-mechanism
840
+ * sidecar/manifest seams, both empty for every v1 row).
841
+ *
842
+ * @param name - A capability name known at compile time (`keyof CapabilityConfigMap`).
843
+ * @param config - Optional per-capability packaging parameters.
844
+ * @returns The resolved capability (registry row + conf/sidecarPlist/manifest).
845
+ * @throws {Error} When `name` is not in the registry, or deep-link is missing a scheme.
846
+ * @example
847
+ * ```ts
848
+ * resolve("deep-link", { mode: "scheme", scheme: "myapp" });
849
+ * ```
850
+ */
851
+ function resolve(name, config) {
852
+ const row = REGISTRY.find((candidate) => candidate.name === name);
853
+ if (!row) throw unknownCapabilityError(name);
854
+ return {
855
+ ...row,
856
+ conf: buildConfFragment(row, config),
857
+ sidecarPlist: [],
858
+ manifest: []
859
+ };
860
+ }
861
+ /**
862
+ * Registry data consumed by `doctor`: pinned crate/npm ranges, mobile required-file
863
+ * sets (via `requiredFiles`), and per-row confidence markers.
864
+ *
865
+ * @returns A frozen copy of every registry row.
866
+ * @example
867
+ * ```ts
868
+ * registryRows().map(row => row.name); // ["store", "notification", ...]
869
+ * ```
870
+ */
871
+ function registryRows() {
872
+ return REGISTRY;
873
+ }
874
+ //#endregion
875
+ //#region src/plugins/project/api.ts
876
+ /**
877
+ * @file project plugin — API factory + config validation + capability resolution orchestration.
878
+ */
879
+ const IDENTIFIER_PATTERN = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$/i;
880
+ /**
881
+ * Validates the global config at composition time — throws `[native]`-formatted errors
882
+ * for missing app identity, missing web wiring, unknown `config.system` names, or a
883
+ * `deep-link` composition missing its required scheme.
884
+ *
885
+ * @param global - Frozen global framework config.
886
+ * @throws {Error} When app identity, web wiring, system names, or deep-link config are invalid.
887
+ * @example
888
+ * ```ts
889
+ * validateProjectConfig(ctx.global);
890
+ * ```
891
+ */
892
+ function validateProjectConfig(global) {
893
+ if (!global.app.name) throw new Error("[native] app.name is required.\n Set config.app.name to your app's display name.");
894
+ if (!IDENTIFIER_PATTERN.test(global.app.identifier)) throw new Error(`[native] app.identifier "${global.app.identifier}" is not a valid reverse-DNS identifier.\n Use a reverse-DNS identifier such as "com.example.myapp".`);
895
+ if (!global.web.build) throw new Error("[native] web.build is required.\n Set config.web.build to the command that builds your web assets.");
896
+ if (!global.web.dev.command) throw new Error("[native] web.dev.command is required.\n Set config.web.dev.command to the command that starts your dev server.");
897
+ if (!global.web.dev.url) throw new Error("[native] web.dev.url is required.\n Set config.web.dev.url to your dev server's URL.");
898
+ if (!global.web.dist) throw new Error("[native] web.dist is required.\n Set config.web.dist to your web build's output directory.");
899
+ assertKnownCapabilities(global.system);
900
+ if (global.system.some((entry) => entry.name === "deep-link") && !global.capabilities["deep-link"]?.scheme) throw new Error("[native] deep-link is composed in config.system but capabilities[\"deep-link\"].scheme is missing.\n Set capabilities[\"deep-link\"] = { mode: \"scheme\", scheme: \"yourscheme\" }.");
901
+ }
902
+ /**
903
+ * Resolves every capability configured on `config.system` against the registry, scoped
904
+ * to rows whose `platforms` include the target (D-012: the whole packaging composition
905
+ * is data-driven from this one pass).
906
+ *
907
+ * @param global - Frozen global framework config.
908
+ * @param target - The packaging target being generated for.
909
+ * @returns The resolved capabilities applicable to this target.
910
+ * @throws {Error} When `config.system` names a capability the registry doesn't know.
911
+ * @example
912
+ * ```ts
913
+ * resolveConfiguredCapabilities(ctx.global, "ios");
914
+ * ```
915
+ */
916
+ function resolveConfiguredCapabilities(global, target) {
917
+ const resolved = [];
918
+ for (const entry of global.system) {
919
+ if (!isKnownCapability(entry.name)) throw unknownCapabilityError(entry.name);
920
+ const capability = resolve(entry.name, global.capabilities[entry.name]);
921
+ if (capability.platforms.includes(target)) resolved.push(capability);
922
+ }
923
+ return resolved;
924
+ }
925
+ /**
926
+ * Creates the project plugin API surface — capability registry + `.moku/tauri`
927
+ * generators + write-if-changed writer + mobile completeness/patch/clean.
928
+ *
929
+ * @param ctx - Plugin context (global config, log).
930
+ * @returns The `project` plugin's public API.
931
+ * @example
932
+ * ```ts
933
+ * const api = createProjectApi(ctx);
934
+ * await api.generate({ target: "macos" });
935
+ * ```
936
+ */
937
+ function createProjectApi(ctx) {
938
+ /**
939
+ * Write/refresh every pure artifact for `opts.target` into `projectDir` via
940
+ * write-if-changed.
941
+ *
942
+ * @param opts - The generate options.
943
+ * @param opts.target - The packaging target to generate for.
944
+ * @returns Which paths were written, left unchanged, or skipped.
945
+ * @example
946
+ * ```ts
947
+ * await generateArtifacts({ target: "macos" });
948
+ * ```
949
+ */
950
+ const generateArtifacts = async (opts) => {
951
+ const capabilities = resolveConfiguredCapabilities(ctx.global, opts.target);
952
+ const input = {
953
+ global: ctx.global,
954
+ target: opts.target,
955
+ capabilities
956
+ };
957
+ const artifacts = [
958
+ ...generateTauriConf(input),
959
+ ...generateCargo(input),
960
+ ...generateRust(input),
961
+ ...generateCapabilities(input),
962
+ ...generateSidecar(input)
963
+ ];
964
+ const result = {
965
+ written: [],
966
+ unchanged: [],
967
+ skipped: []
968
+ };
969
+ for (const artifact of artifacts) {
970
+ const fullPath = node_path.default.join(ctx.global.projectDir, artifact.path);
971
+ const action = await writeIfChanged(fullPath, artifact.content);
972
+ result[action].push(fullPath);
973
+ ctx.log.debug("project:generate:artifact", {
974
+ path: fullPath,
975
+ action
976
+ });
977
+ }
978
+ ctx.log.info("project:generate", {
979
+ target: opts.target,
980
+ written: result.written.length,
981
+ unchanged: result.unchanged.length
982
+ });
983
+ return result;
984
+ };
985
+ /**
986
+ * Checks the mobile `gen/<platform>` required-file completeness gate for `opts.target`.
987
+ *
988
+ * @param opts - The completeness check options.
989
+ * @param opts.target - The packaging target to check.
990
+ * @returns The completeness verdict.
991
+ * @example
992
+ * ```ts
993
+ * checkCompleteness({ target: "android" });
994
+ * ```
995
+ */
996
+ const checkCompleteness = (opts) => completeness(ctx.global.projectDir, opts.target);
997
+ /**
998
+ * Runs the idempotent mobile post-init patch pass (v1: Android signing state only).
999
+ *
1000
+ * @param opts - The patch options.
1001
+ * @param opts.target - The mobile platform to patch.
1002
+ * @returns The paths patched vs. left unchanged.
1003
+ * @example
1004
+ * ```ts
1005
+ * await runPatchMobile({ target: "android" });
1006
+ * ```
1007
+ */
1008
+ const runPatchMobile = async (opts) => {
1009
+ const result = await patchMobile(ctx.global.projectDir, opts.target, ctx.global.signing);
1010
+ ctx.log.info("project:patchMobile", {
1011
+ target: opts.target,
1012
+ patched: result.patched.length
1013
+ });
1014
+ return result;
1015
+ };
1016
+ /**
1017
+ * Deletes derived state for the given scope (whole projectDir, a mobile gen/ tree, or
1018
+ * a desktop bundle output).
1019
+ *
1020
+ * @param opts - The clean options.
1021
+ * @param opts.target - The optional packaging target to scope the clean to.
1022
+ * @returns The list of paths actually removed.
1023
+ * @example
1024
+ * ```ts
1025
+ * await runClean({ target: "android" });
1026
+ * ```
1027
+ */
1028
+ const runClean = async (opts = {}) => {
1029
+ const result = await clean(ctx.global.projectDir, opts.target);
1030
+ ctx.log.info("project:clean", {
1031
+ target: opts.target,
1032
+ removed: result.removed.length
1033
+ });
1034
+ return result;
1035
+ };
1036
+ return {
1037
+ generate: generateArtifacts,
1038
+ completeness: checkCompleteness,
1039
+ patchMobile: runPatchMobile,
1040
+ clean: runClean,
1041
+ resolve,
1042
+ isKnownCapability,
1043
+ registryRows,
1044
+ requiredFiles
1045
+ };
1046
+ }
1047
+ //#endregion
1048
+ //#region src/plugins/project/index.ts
1049
+ /**
1050
+ * Complex tier — capability registry + .moku/tauri generators + write-if-changed writer +
1051
+ * mobile init-once-then-patch (Android signing only in v1) + clean.
1052
+ *
1053
+ * @see README.md
1054
+ * @example
1055
+ * ```ts
1056
+ * const app = createApp({ plugins: [projectPlugin] });
1057
+ * ```
1058
+ */
1059
+ const projectPlugin = createPlugin$1("project", {
1060
+ api: createProjectApi,
1061
+ /**
1062
+ * Validates consumer config at composition time (spec/11 Part 3).
1063
+ *
1064
+ * @param ctx - Plugin context carrying the frozen global config.
1065
+ * @example
1066
+ * ```ts
1067
+ * onInit: ctx => validateProjectConfig(ctx.global)
1068
+ * ```
1069
+ */
1070
+ onInit: (ctx) => {
1071
+ validateProjectConfig(ctx.global);
1072
+ }
1073
+ });
1074
+ //#endregion
1075
+ //#region src/plugins/tauri/argv.ts
1076
+ /**
1077
+ * Builds the argv for `tauri build` / `tauri ios|android build`.
1078
+ *
1079
+ * Android defaults to `--apk` (directly installable artifact) rather than
1080
+ * `--aab` (store-submission bundle) — callers needing an AAB compose their
1081
+ * own build-plugin option; this seam stays a pure function of `target`.
1082
+ *
1083
+ * @param nodePath - Resolved `node` binary path.
1084
+ * @param tauriJsPath - Resolved `@tauri-apps/cli/tauri.js` entry path.
1085
+ * @param target - Packaging target.
1086
+ * @returns The full `[nodePath, tauriJsPath, ...]` argv tuple.
1087
+ * @example
1088
+ * ```ts
1089
+ * buildArgv("/usr/bin/node", "/.../tauri.js", "ios"); // [..., "ios", "build", "--ci"]
1090
+ * ```
1091
+ */
1092
+ function buildArgv(nodePath, tauriJsPath, target) {
1093
+ const prefix = [nodePath, tauriJsPath];
1094
+ if (target === "ios") return [
1095
+ ...prefix,
1096
+ "ios",
1097
+ "build",
1098
+ "--ci"
1099
+ ];
1100
+ if (target === "android") return [
1101
+ ...prefix,
1102
+ "android",
1103
+ "build",
1104
+ "--ci",
1105
+ "--apk"
1106
+ ];
1107
+ return [
1108
+ ...prefix,
1109
+ "build",
1110
+ "--ci"
1111
+ ];
1112
+ }
1113
+ /**
1114
+ * Builds the argv for the long-lived dev verb: `tauri dev` / `tauri ios|android dev`.
1115
+ * Mobile dev omits `--ci` (the CLI drives `TAURI_DEV_HOST` itself for device pairing).
1116
+ *
1117
+ * @param nodePath - Resolved `node` binary path.
1118
+ * @param tauriJsPath - Resolved `@tauri-apps/cli/tauri.js` entry path.
1119
+ * @param target - Packaging target (desktop targets and `undefined` are target-uniform).
1120
+ * @returns The full `[nodePath, tauriJsPath, ...]` argv tuple.
1121
+ * @example
1122
+ * ```ts
1123
+ * devArgv("/usr/bin/node", "/.../tauri.js", "android"); // [..., "android", "dev"]
1124
+ * ```
1125
+ */
1126
+ function devArgv(nodePath, tauriJsPath, target) {
1127
+ const prefix = [nodePath, tauriJsPath];
1128
+ if (target === "ios" || target === "android") return [
1129
+ ...prefix,
1130
+ target,
1131
+ "dev"
1132
+ ];
1133
+ return [
1134
+ ...prefix,
1135
+ "dev",
1136
+ "--ci"
1137
+ ];
1138
+ }
1139
+ /**
1140
+ * Builds the argv for `tauri icon` (regenerates the icon set from a source image).
1141
+ *
1142
+ * @param nodePath - Resolved `node` binary path.
1143
+ * @param tauriJsPath - Resolved `@tauri-apps/cli/tauri.js` entry path.
1144
+ * @param source - Path to the source icon image.
1145
+ * @returns The full `[nodePath, tauriJsPath, ...]` argv tuple.
1146
+ * @example
1147
+ * ```ts
1148
+ * iconArgv("/usr/bin/node", "/.../tauri.js", "icon.png"); // [..., "icon", "icon.png"]
1149
+ * ```
1150
+ */
1151
+ function iconArgv(nodePath, tauriJsPath, source) {
1152
+ return [
1153
+ nodePath,
1154
+ tauriJsPath,
1155
+ "icon",
1156
+ source
1157
+ ];
1158
+ }
1159
+ /**
1160
+ * Builds the argv for `tauri ios|android init` — the ONLY init verbs (D-013);
1161
+ * plain `tauri init` is never used since the desktop tree is project-generated.
1162
+ *
1163
+ * @param nodePath - Resolved `node` binary path.
1164
+ * @param tauriJsPath - Resolved `@tauri-apps/cli/tauri.js` entry path.
1165
+ * @param platform - Mobile platform to initialize.
1166
+ * @returns The full `[nodePath, tauriJsPath, ...]` argv tuple.
1167
+ * @example
1168
+ * ```ts
1169
+ * mobileInitArgv("/usr/bin/node", "/.../tauri.js", "ios"); // [..., "ios", "init", "--ci"]
1170
+ * ```
1171
+ */
1172
+ function mobileInitArgv(nodePath, tauriJsPath, platform) {
1173
+ return [
1174
+ nodePath,
1175
+ tauriJsPath,
1176
+ platform,
1177
+ "init",
1178
+ "--ci"
1179
+ ];
1180
+ }
1181
+ /**
1182
+ * Builds the argv for `tauri info` — the CLI presence/version probe used by `doctor`.
1183
+ *
1184
+ * @param nodePath - Resolved `node` binary path.
1185
+ * @param tauriJsPath - Resolved `@tauri-apps/cli/tauri.js` entry path.
1186
+ * @returns The full `[nodePath, tauriJsPath, ...]` argv tuple.
1187
+ * @example
1188
+ * ```ts
1189
+ * infoArgv("/usr/bin/node", "/.../tauri.js"); // [..., "info"]
1190
+ * ```
1191
+ */
1192
+ function infoArgv(nodePath, tauriJsPath) {
1193
+ return [
1194
+ nodePath,
1195
+ tauriJsPath,
1196
+ "info"
1197
+ ];
1198
+ }
1199
+ //#endregion
1200
+ //#region src/plugins/tauri/dev.ts
1201
+ /**
1202
+ * Default readiness probe — resolves `true` as soon as `fetch(url)` settles
1203
+ * (any response, even non-2xx, means the dev server is up); `false` on a
1204
+ * network-level failure (connection refused, DNS, etc.).
1205
+ *
1206
+ * @param url - The dev URL to probe.
1207
+ * @returns Whether the dev server responded.
1208
+ * @example
1209
+ * ```ts
1210
+ * await fetchReadinessProbe("http://localhost:5173");
1211
+ * ```
1212
+ */
1213
+ const fetchReadinessProbe = async (url) => {
1214
+ try {
1215
+ await fetch(url);
1216
+ return true;
1217
+ } catch {
1218
+ return false;
1219
+ }
1220
+ };
1221
+ /**
1222
+ * Starts a long-lived dev session: spawns the process group (detached),
1223
+ * installs SIGINT/SIGTERM handlers that group-kill and remove themselves on
1224
+ * exit, and polls `url` for readiness. A readiness timeout rejects `ready`
1225
+ * AND reaps the process group (`stop()`) — the CLI never signals readiness itself.
1226
+ *
1227
+ * @param opts - The argv/cwd/url and injectable orchestration dependencies.
1228
+ * @returns The live {@link DevHandle} — returns immediately, never awaits `exited`.
1229
+ * @example
1230
+ * ```ts
1231
+ * const handle = startDev({ cmd, cwd, url, deps });
1232
+ * await handle.ready;
1233
+ * ```
1234
+ */
1235
+ function startDev(opts) {
1236
+ const controller = new AbortController();
1237
+ let stopRequested = false;
1238
+ const exitedPromise = opts.deps.spawn({
1239
+ cmd: opts.cmd,
1240
+ cwd: opts.cwd,
1241
+ detached: true,
1242
+ onLine: opts.onLine,
1243
+ signal: controller.signal
1244
+ }).then((result) => ({
1245
+ code: result.code,
1246
+ signal: result.signal
1247
+ }));
1248
+ /**
1249
+ * SIGINT/SIGTERM handler — stops the dev session (group-kill) the same way
1250
+ * an explicit `handle.stop()` call would.
1251
+ *
1252
+ * @example
1253
+ * ```ts
1254
+ * process.on("SIGINT", handleSignal);
1255
+ * ```
1256
+ */
1257
+ const handleSignal = () => {
1258
+ stop().catch(() => {});
1259
+ };
1260
+ opts.deps.onSignal("SIGINT", handleSignal);
1261
+ opts.deps.onSignal("SIGTERM", handleSignal);
1262
+ const exited = exitedPromise.finally(() => {
1263
+ opts.deps.offSignal("SIGINT", handleSignal);
1264
+ opts.deps.offSignal("SIGTERM", handleSignal);
1265
+ });
1266
+ /**
1267
+ * Stops the dev session: aborts the spawn signal (real impl group-kills)
1268
+ * and waits for the process group to exit. Idempotent.
1269
+ *
1270
+ * @returns Resolves once the process group has exited.
1271
+ * @example
1272
+ * ```ts
1273
+ * await handle.stop();
1274
+ * ```
1275
+ */
1276
+ async function stop() {
1277
+ if (!stopRequested) {
1278
+ stopRequested = true;
1279
+ controller.abort();
1280
+ }
1281
+ await exited;
1282
+ }
1283
+ const ready = pollUntilReady(opts.url, opts.deps).catch(async (error) => {
1284
+ await stop();
1285
+ throw error;
1286
+ });
1287
+ return {
1288
+ url: opts.url,
1289
+ ready,
1290
+ exited,
1291
+ stop
1292
+ };
1293
+ }
1294
+ /**
1295
+ * Polls `url` until the readiness probe succeeds or `deps.timeoutMs` elapses.
1296
+ *
1297
+ * @param url - The dev URL to poll.
1298
+ * @param deps - Orchestration dependencies (probe, interval/timeout, clock).
1299
+ * @returns Resolves once the probe succeeds.
1300
+ * @throws {Error} `[native]` when the timeout elapses before readiness.
1301
+ * @example
1302
+ * ```ts
1303
+ * await pollUntilReady("http://localhost:5173", deps);
1304
+ * ```
1305
+ */
1306
+ async function pollUntilReady(url, deps) {
1307
+ const clock = deps.now ?? Date.now;
1308
+ const deadline = clock() + deps.timeoutMs;
1309
+ for (;;) {
1310
+ if (await deps.probeReady(url)) return;
1311
+ if (clock() >= deadline) throw new Error(`[native] dev server at ${url} did not become ready within ${deps.timeoutMs}ms.\n Check the dev server logs; the process group has been terminated.`);
1312
+ await delay(deps.intervalMs);
1313
+ }
1314
+ }
1315
+ /**
1316
+ * Resolves after `ms` milliseconds — the readiness poll's tick interval.
1317
+ *
1318
+ * @param ms - Milliseconds to wait.
1319
+ * @returns Resolves after the delay.
1320
+ * @example
1321
+ * ```ts
1322
+ * await delay(250);
1323
+ * ```
1324
+ */
1325
+ function delay(ms) {
1326
+ return new Promise((resolve) => setTimeout(resolve, ms));
1327
+ }
1328
+ //#endregion
1329
+ //#region src/plugins/tauri/types.ts
1330
+ var types_exports$4 = /* @__PURE__ */ __exportAll({ TauriError: () => TauriError });
1331
+ /**
1332
+ * Thrown by every one-shot verb (`icon`/`build`/`mobileInit`) on a non-zero exit.
1333
+ * Carries a classified {@link TauriErrorKind} and the scrubbed stderr tail so
1334
+ * callers (`build`, `doctor`, `cli`) can render an actionable message without
1335
+ * re-deriving the taxonomy or re-scrubbing raw output.
1336
+ */
1337
+ var TauriError = class extends Error {
1338
+ kind;
1339
+ exitCode;
1340
+ stderrTail;
1341
+ /**
1342
+ * Constructs a classified `TauriError`.
1343
+ *
1344
+ * @param kind - Taxonomy bucket.
1345
+ * @param message - Fully formatted `[native] ...` message.
1346
+ * @param details - Exit code + scrubbed stderr tail.
1347
+ * @param details.exitCode - Raw process exit code (`null` when signal-terminated).
1348
+ * @param details.stderrTail - Scrubbed tail of stderr — already safe to log/display.
1349
+ * @example
1350
+ * ```ts
1351
+ * throw new TauriError("compile-failed", "[native] tauri compile failed.\n See stderr.", {
1352
+ * exitCode: 101,
1353
+ * stderrTail: "error[E0432]: unresolved import `foo`",
1354
+ * });
1355
+ * ```
1356
+ */
1357
+ constructor(kind, message, details) {
1358
+ super(message);
1359
+ this.name = "TauriError";
1360
+ this.kind = kind;
1361
+ this.exitCode = details.exitCode;
1362
+ this.stderrTail = details.stderrTail;
1363
+ }
1364
+ };
1365
+ //#endregion
1366
+ //#region src/plugins/tauri/errors.ts
1367
+ /**
1368
+ * @file tauri plugin — exit-code/stderr error taxonomy (pure classifier).
1369
+ *
1370
+ * `classify` never touches raw (unscrubbed) stderr — callers must scrub first
1371
+ * (scrub.ts) so a classified {@link TauriError}'s `stderrTail` is always safe
1372
+ * to log/display.
1373
+ */
1374
+ /** How many trailing lines of scrubbed stderr are kept on a classified error. */
1375
+ const STDERR_TAIL_LINES = 20;
1376
+ /** Ordered (most-specific-first) taxonomy patterns matched against scrubbed stderr. */
1377
+ const TAXONOMY_PATTERNS = [
1378
+ {
1379
+ kind: "signing-failed",
1380
+ test: /codesign|provisioning profile|keychain|signtool|jarsigner|keystore/i
1381
+ },
1382
+ {
1383
+ kind: "toolchain-missing",
1384
+ test: /command not found|xcode-select|android_home|ndk (not found|is not installed)|rustup|cargo: not found/i
1385
+ },
1386
+ {
1387
+ kind: "device-unavailable",
1388
+ test: /no devices found|device not found|simulator (not booted|not found)|no emulators found|adb: no devices/i
1389
+ },
1390
+ {
1391
+ kind: "config-invalid",
1392
+ test: /tauri\.conf|failed to parse .*config|invalid config|schema validation failed/i
1393
+ },
1394
+ {
1395
+ kind: "compile-failed",
1396
+ test: /error\[e\d+\]|could not compile|compilation failed/i
1397
+ }
1398
+ ];
1399
+ /** Actionable suggestion text per taxonomy bucket (second line of the `[native]` message). */
1400
+ const ADVICE = {
1401
+ "signing-failed": "Check your signing configuration (certificates/keystore/keychain) and run `native doctor`.",
1402
+ "toolchain-missing": "Install the missing platform toolchain, then run `native doctor` to confirm.",
1403
+ "device-unavailable": "Connect a device or start a simulator/emulator, then retry.",
1404
+ "config-invalid": "Check the generated `tauri.conf.json` for syntax/schema errors.",
1405
+ "compile-failed": "Inspect the compile errors above; fix the source and retry.",
1406
+ cancelled: "The command was cancelled or terminated before completion.",
1407
+ unknown: "Inspect the stderr tail above; run `native doctor` if the cause is unclear."
1408
+ };
1409
+ /**
1410
+ * Classifies a non-zero tauri CLI exit into a {@link TauriError}.
1411
+ *
1412
+ * @param code - Process exit code (`null` when signal-terminated).
1413
+ * @param scrubbedStderr - Already-scrubbed stderr (see scrub.ts) — never raw output.
1414
+ * @returns A {@link TauriError} carrying the taxonomy bucket and a scrubbed stderr tail.
1415
+ * @example
1416
+ * ```ts
1417
+ * throw classify(101, scrub(rawStderr));
1418
+ * ```
1419
+ */
1420
+ function classify(code, scrubbedStderr) {
1421
+ const kind = TAXONOMY_PATTERNS.find(({ test }) => test.test(scrubbedStderr))?.kind ?? (code === null ? "cancelled" : "unknown");
1422
+ const stderrTail = tailLines(scrubbedStderr, STDERR_TAIL_LINES);
1423
+ return new TauriError(kind, `[native] tauri ${kind.replaceAll("-", " ")}.\n ${ADVICE[kind]}`, {
1424
+ exitCode: code,
1425
+ stderrTail
1426
+ });
1427
+ }
1428
+ /**
1429
+ * Keeps only the last `maxLines` non-empty lines of `text`.
1430
+ *
1431
+ * @param text - Full (already-scrubbed) text.
1432
+ * @param maxLines - Maximum number of trailing lines to keep.
1433
+ * @returns The trailing lines, joined with `\n`.
1434
+ * @example
1435
+ * ```ts
1436
+ * tailLines(scrubbedStderr, 20);
1437
+ * ```
1438
+ */
1439
+ function tailLines(text, maxLines) {
1440
+ return text.split(/\r?\n/).filter((line) => line.length > 0).slice(-maxLines).join("\n");
1441
+ }
1442
+ //#endregion
1443
+ //#region src/plugins/tauri/resolve.ts
1444
+ /**
1445
+ * @file tauri plugin — nodePath / tauriJsPath resolution (D-013 invocation shape).
1446
+ *
1447
+ * Pure-ish and injectable: callers pass the PATH string and a `fileExists` probe
1448
+ * instead of this module reading the environment/filesystem directly, so tests
1449
+ * never touch a real PATH or a real filesystem.
1450
+ */
1451
+ /**
1452
+ * Resolves the real `node` binary to invoke the tauri CLI with — a PATH walk,
1453
+ * NEVER `process.execPath` (that's bun here). Never shells out to `which`/`where`.
1454
+ *
1455
+ * @param opts - Resolution options (override, PATH string, platform, fs probe).
1456
+ * @returns The resolved `node` binary path.
1457
+ * @throws {Error} `[native]` when no `node` binary is found on PATH.
1458
+ * @example
1459
+ * ```ts
1460
+ * resolveNodePath({ pathEnv: ctx.env.get("PATH") });
1461
+ * ```
1462
+ */
1463
+ function resolveNodePath(opts = {}) {
1464
+ const { nodePath, pathEnv: pathEnvironment = "", platform = process.platform, fileExists = node_fs.existsSync } = opts;
1465
+ if (nodePath) return nodePath;
1466
+ const isWindows = platform === "win32";
1467
+ const delimiter = isWindows ? ";" : ":";
1468
+ const separator = isWindows ? "\\" : "/";
1469
+ const binaryName = isWindows ? "node.exe" : "node";
1470
+ const directories = pathEnvironment.split(delimiter).filter((entry) => entry.length > 0);
1471
+ for (const directory of directories) {
1472
+ const candidate = `${directory.endsWith(separator) ? directory.slice(0, -1) : directory}${separator}${binaryName}`;
1473
+ if (fileExists(candidate)) return candidate;
1474
+ }
1475
+ throw new Error("[native] Could not locate a `node` binary on PATH.\n Install Node.js (or make sure your version manager — volta/fnm/nvm — has shimmed `node` onto PATH), then run `native doctor`.");
1476
+ }
1477
+ /**
1478
+ * Resolves `@tauri-apps/cli/tauri.js` via `require.resolve` (never a hardcoded
1479
+ * relative path) — the framework declares `@tauri-apps/cli` as a real dependency.
1480
+ *
1481
+ * @param opts - Resolution options (injectable resolver for tests).
1482
+ * @returns The resolved path to the CLI's JS entry.
1483
+ * @throws {Error} `[native]` when the package cannot be resolved.
1484
+ * @example
1485
+ * ```ts
1486
+ * const tauriJsPath = resolveTauriJsPath();
1487
+ * ```
1488
+ */
1489
+ function resolveTauriJsPath(opts = {}) {
1490
+ const requireResolve = opts.requireResolve ?? defaultRequireResolve;
1491
+ try {
1492
+ return requireResolve("@tauri-apps/cli/tauri.js");
1493
+ } catch (error) {
1494
+ throw new Error("[native] Could not resolve `@tauri-apps/cli/tauri.js`.\n Ensure `@tauri-apps/cli` is installed as a dependency, then run `native doctor`.", { cause: error });
1495
+ }
1496
+ }
1497
+ /**
1498
+ * Default `require.resolve`-shaped resolver, bound to this module's URL.
1499
+ *
1500
+ * @param id - Module specifier to resolve.
1501
+ * @returns The resolved absolute path.
1502
+ * @example
1503
+ * ```ts
1504
+ * defaultRequireResolve("@tauri-apps/cli/tauri.js");
1505
+ * ```
1506
+ */
1507
+ function defaultRequireResolve(id) {
1508
+ return (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href).resolve(id);
1509
+ }
1510
+ //#endregion
1511
+ //#region src/plugins/tauri/scrub.ts
1512
+ /**
1513
+ * @file tauri plugin — entropy-gated secret scrubbing for subprocess output.
1514
+ *
1515
+ * Every stdout/stderr line the plugin touches (build ticks, dev output, error
1516
+ * tails) is routed through {@link scrub} before it reaches a log, a callback,
1517
+ * or a thrown {@link TauriError} — never the raw process output.
1518
+ */
1519
+ /** Replacement text for a masked secret. */
1520
+ const MASK = "[native:scrubbed]";
1521
+ /** Tokens shorter than this are never entropy-evaluated (avoids masking normal words/paths). */
1522
+ const MIN_ENTROPY_TOKEN_LENGTH = 20;
1523
+ /** Shannon-entropy threshold (bits/char) above which a long token is masked. */
1524
+ const ENTROPY_THRESHOLD_BITS_PER_CHAR = 4;
1525
+ /**
1526
+ * Env-var name prefixes that are ALWAYS masked when found as `NAME=value` /
1527
+ * `NAME: value`, regardless of the value's entropy (short passwords included).
1528
+ */
1529
+ const KNOWN_SECRET_ENV_PREFIXES = [
1530
+ "APPLE_PASSWORD",
1531
+ "APPLE_CERTIFICATE",
1532
+ "APPLE_API_KEY",
1533
+ "APPLE_API_ISSUER",
1534
+ "TAURI_SIGNING_",
1535
+ "ANDROID_KEYSTORE_PASSWORD",
1536
+ "ANDROID_KEY_PASSWORD"
1537
+ ];
1538
+ /**
1539
+ * Scrubs a line (or block) of subprocess output: known secret env-var
1540
+ * assignments are always masked, then any remaining high-entropy token is masked.
1541
+ *
1542
+ * @param text - Raw subprocess output.
1543
+ * @returns The scrubbed text, safe to log/display/embed in an error message.
1544
+ * @example
1545
+ * ```ts
1546
+ * scrub("APPLE_PASSWORD=hunter2"); // "APPLE_PASSWORD=[native:scrubbed]"
1547
+ * ```
1548
+ */
1549
+ function scrub(text) {
1550
+ return maskHighEntropyTokens(maskKnownSecretAssignments(text));
1551
+ }
1552
+ /**
1553
+ * Masks known secret env-var assignments (`NAME=value` / `NAME: value`),
1554
+ * regardless of the value's entropy — short passwords included.
1555
+ *
1556
+ * @param text - Raw subprocess output.
1557
+ * @returns Text with every known secret assignment masked.
1558
+ * @example
1559
+ * ```ts
1560
+ * maskKnownSecretAssignments("APPLE_PASSWORD=hunter2");
1561
+ * ```
1562
+ */
1563
+ function maskKnownSecretAssignments(text) {
1564
+ let result = text;
1565
+ for (const prefix of KNOWN_SECRET_ENV_PREFIXES) {
1566
+ const pattern = new RegExp(String.raw`\b(${prefix}\w*)(\s*[=:]\s*)(\S+)`, "g");
1567
+ result = result.replaceAll(pattern, (_match, key, separator) => `${key}${separator}${MASK}`);
1568
+ }
1569
+ return result;
1570
+ }
1571
+ /**
1572
+ * Masks any remaining whitespace-delimited token whose Shannon entropy
1573
+ * exceeds {@link ENTROPY_THRESHOLD_BITS_PER_CHAR}.
1574
+ *
1575
+ * @param text - Text already passed through {@link maskKnownSecretAssignments}.
1576
+ * @returns Text with every high-entropy token masked.
1577
+ * @example
1578
+ * ```ts
1579
+ * maskHighEntropyTokens("token: Tr0ub4dor&3Zx9Qm7Lp2Vy8Wn5Rk1Bc6Ds4Fg");
1580
+ * ```
1581
+ */
1582
+ function maskHighEntropyTokens(text) {
1583
+ return text.replaceAll(/\S+/g, (token) => isHighEntropy(token) ? MASK : token);
1584
+ }
1585
+ /**
1586
+ * Tests whether a single token is long AND high-entropy enough to mask.
1587
+ *
1588
+ * @param token - A single whitespace-delimited token.
1589
+ * @returns Whether the token should be masked.
1590
+ * @example
1591
+ * ```ts
1592
+ * isHighEntropy("Tr0ub4dor&3Zx9Qm7Lp2Vy8Wn5Rk1Bc6Ds4Fg"); // true
1593
+ * ```
1594
+ */
1595
+ function isHighEntropy(token) {
1596
+ if (token.includes(MASK)) return false;
1597
+ if (token.length < MIN_ENTROPY_TOKEN_LENGTH) return false;
1598
+ return shannonEntropyBitsPerChar(token) >= ENTROPY_THRESHOLD_BITS_PER_CHAR;
1599
+ }
1600
+ /**
1601
+ * Computes Shannon entropy (bits per character) of `input`.
1602
+ *
1603
+ * @param input - The string to measure.
1604
+ * @returns Bits of entropy per character.
1605
+ * @example
1606
+ * ```ts
1607
+ * shannonEntropyBitsPerChar("aaaaaaaa"); // 0
1608
+ * ```
1609
+ */
1610
+ function shannonEntropyBitsPerChar(input) {
1611
+ const counts = /* @__PURE__ */ new Map();
1612
+ for (const character of input) counts.set(character, (counts.get(character) ?? 0) + 1);
1613
+ let entropy = 0;
1614
+ for (const count of counts.values()) {
1615
+ const probability = count / input.length;
1616
+ entropy -= probability * Math.log2(probability);
1617
+ }
1618
+ return entropy;
1619
+ }
1620
+ //#endregion
1621
+ //#region src/plugins/tauri/stream.ts
1622
+ /**
1623
+ * Splits a streamed chunk into complete lines, carrying over a trailing
1624
+ * partial line for the next call. Pure — the caller owns the buffer state.
1625
+ *
1626
+ * @param buffer - Leftover partial line from the previous chunk (`""` initially).
1627
+ * @param chunk - Newly received chunk of subprocess output.
1628
+ * @returns The complete lines found, plus the new trailing buffer.
1629
+ * @example
1630
+ * ```ts
1631
+ * let buffer = "";
1632
+ * const { lines, buffer: next } = splitLines(buffer, "Compiling foo\nCompi");
1633
+ * // lines: ["Compiling foo"], next: "Compi"
1634
+ * buffer = next;
1635
+ * ```
1636
+ */
1637
+ function splitLines(buffer, chunk) {
1638
+ const parts = (buffer + chunk).split(/\r?\n/);
1639
+ return {
1640
+ lines: parts,
1641
+ buffer: parts.pop() ?? ""
1642
+ };
1643
+ }
1644
+ const COMPILING_PATTERN = /Compiling\s+(\S+)(?:\s+v[\w.+-]+)?/;
1645
+ const PROGRESS_PATTERN = /^\s*\[\s*(\d+)\/(\d+)\s*\]/;
1646
+ /**
1647
+ * Parses a single output line into a {@link CompileTick} — real crate counts
1648
+ * (`"Compiling <crate> vX"`, optionally prefixed with cargo `[N/M]` unit
1649
+ * progress) — never a fake/synthesized percentage.
1650
+ *
1651
+ * @param line - A single, already-split output line.
1652
+ * @returns The parsed tick, or `undefined` when the line isn't compile progress.
1653
+ * @example
1654
+ * ```ts
1655
+ * parseCompileTick(" Compiling serde v1.0.190"); // { crate: "serde" }
1656
+ * parseCompileTick("[3/50] Compiling tauri v2.0.0"); // { crate: "tauri", index: 3, total: 50 }
1657
+ * ```
1658
+ */
1659
+ function parseCompileTick(line) {
1660
+ const crate = COMPILING_PATTERN.exec(line)?.[1];
1661
+ if (!crate) return void 0;
1662
+ const progressMatch = PROGRESS_PATTERN.exec(line);
1663
+ if (progressMatch?.[1] !== void 0 && progressMatch[2] !== void 0) return {
1664
+ crate,
1665
+ index: Number(progressMatch[1]),
1666
+ total: Number(progressMatch[2])
1667
+ };
1668
+ return { crate };
1669
+ }
1670
+ //#endregion
1671
+ //#region src/plugins/tauri/spawn.ts
1672
+ /**
1673
+ * @file tauri plugin — real subprocess spawn (process-group) + group-kill escalation.
1674
+ *
1675
+ * `realSpawn` is the ONLY place in this framework that opens a real OS process
1676
+ * (D-013 invocation shape: `[nodePath, tauriJsPath, verb, ...args]`). Every
1677
+ * other call site goes through the injectable `SpawnFn` seam.
1678
+ */
1679
+ const DEFAULT_GRACE_MS = 2e3;
1680
+ /**
1681
+ * Appends `text` to `existing`, keeping only the last {@link MAX_BUFFERED_STREAM_CHARS}
1682
+ * characters — a bounded tail buffer for long-lived spawns.
1683
+ *
1684
+ * @param existing - The buffered stream content so far.
1685
+ * @param text - The newly received chunk.
1686
+ * @returns The bounded combined buffer.
1687
+ * @example
1688
+ * ```ts
1689
+ * stdout = appendBounded(stdout, chunk.toString("utf8"));
1690
+ * ```
1691
+ */
1692
+ function appendBounded(existing, text) {
1693
+ const combined = existing + text;
1694
+ if (combined.length <= 262144) return combined;
1695
+ return combined.slice(-262144);
1696
+ }
1697
+ /**
1698
+ * Kills a process group with an escalation ladder: POSIX sends SIGTERM to the
1699
+ * negated pid (the whole group), waits `graceMs` for a natural exit, then
1700
+ * escalates to SIGKILL. Windows has no group-signal concept, so it shells out
1701
+ * to `taskkill /PID <pid> /T /F` instead. Idempotent — resolves immediately
1702
+ * when the process has no pid or already exited.
1703
+ *
1704
+ * @param proc - The process (or fake) to terminate.
1705
+ * @param opts - Grace period, platform, and injectable signal senders.
1706
+ * @returns A promise that resolves once the group is confirmed dead (or termination was requested).
1707
+ * @example
1708
+ * ```ts
1709
+ * await killProcessGroup(child, { graceMs: 2000 });
1710
+ * ```
1711
+ */
1712
+ function killProcessGroup(proc, opts = {}) {
1713
+ const { graceMs = DEFAULT_GRACE_MS, platform = process.platform, sendSignal = defaultSendSignal, taskkill = defaultTaskkill } = opts;
1714
+ return new Promise((resolve) => {
1715
+ if (proc.pid === void 0 || proc.exited) {
1716
+ resolve();
1717
+ return;
1718
+ }
1719
+ const pid = proc.pid;
1720
+ if (platform === "win32") {
1721
+ taskkill(pid);
1722
+ resolve();
1723
+ return;
1724
+ }
1725
+ let settled = false;
1726
+ /**
1727
+ * Marks the group as dead (natural exit or SIGKILL escalation) and
1728
+ * resolves the outer promise exactly once.
1729
+ *
1730
+ * @example
1731
+ * ```ts
1732
+ * proc.onExit(finish);
1733
+ * ```
1734
+ */
1735
+ const finish = () => {
1736
+ if (settled) return;
1737
+ settled = true;
1738
+ clearTimeout(timer);
1739
+ resolve();
1740
+ };
1741
+ proc.onExit(finish);
1742
+ sendSignal(-pid, "SIGTERM");
1743
+ const timer = setTimeout(() => {
1744
+ if (settled) return;
1745
+ settled = true;
1746
+ sendSignal(-pid, "SIGKILL");
1747
+ resolve();
1748
+ }, graceMs);
1749
+ });
1750
+ }
1751
+ /**
1752
+ * Real POSIX signal sender — `process.kill(pid, signal)`.
1753
+ *
1754
+ * @param pid - Target pid (negative = process group).
1755
+ * @param signal - Signal to send.
1756
+ * @example
1757
+ * ```ts
1758
+ * defaultSendSignal(-1234, "SIGTERM");
1759
+ * ```
1760
+ */
1761
+ function defaultSendSignal(pid, signal) {
1762
+ process.kill(pid, signal);
1763
+ }
1764
+ /**
1765
+ * Real Windows termination — shells out to `taskkill /PID <pid> /T /F`.
1766
+ *
1767
+ * @param pid - Target pid.
1768
+ * @example
1769
+ * ```ts
1770
+ * defaultTaskkill(1234);
1771
+ * ```
1772
+ */
1773
+ function defaultTaskkill(pid) {
1774
+ (0, node_child_process.execFile)("taskkill", [
1775
+ "/PID",
1776
+ String(pid),
1777
+ "/T",
1778
+ "/F"
1779
+ ]);
1780
+ }
1781
+ /**
1782
+ * Returns the parent process's environment — the base the spawned tauri CLI
1783
+ * subprocess inherits (PATH, cargo/toolchain vars, signing overrides).
1784
+ *
1785
+ * @returns The parent environment.
1786
+ * @example
1787
+ * ```ts
1788
+ * const environment = inheritedEnvironment();
1789
+ * ```
1790
+ */
1791
+ function inheritedEnvironment() {
1792
+ return process.env;
1793
+ }
1794
+ /**
1795
+ * Real `SpawnFn` implementation — spawns a detached process (group leader on
1796
+ * POSIX), streams stdout/stderr line-by-line to `onLine`, and resolves with
1797
+ * the full buffered output once the process exits. Honors `opts.signal` by
1798
+ * group-killing the spawned process on abort.
1799
+ *
1800
+ * @param opts - Spawn options (cmd, cwd, env, detached, onLine, signal).
1801
+ * @returns The process result once it exits.
1802
+ * @example
1803
+ * ```ts
1804
+ * const result = await realSpawn({ cmd: [nodePath, tauriJsPath, "info"], cwd: projectDir });
1805
+ * ```
1806
+ */
1807
+ const realSpawn = (opts) => new Promise((resolve, reject) => {
1808
+ const [command, ...arguments_] = opts.cmd;
1809
+ if (!command) {
1810
+ reject(/* @__PURE__ */ new Error("[native] Cannot spawn an empty argv.\n This is a tauri plugin bug — please report it."));
1811
+ return;
1812
+ }
1813
+ const parentEnvironment = inheritedEnvironment();
1814
+ const child = (0, node_child_process.spawn)(command, arguments_, {
1815
+ cwd: opts.cwd,
1816
+ env: opts.env ? {
1817
+ ...parentEnvironment,
1818
+ ...opts.env
1819
+ } : parentEnvironment,
1820
+ detached: opts.detached ?? false
1821
+ });
1822
+ let stdout = "";
1823
+ let stderr = "";
1824
+ let stdoutBuffer = "";
1825
+ let stderrBuffer = "";
1826
+ child.stdout?.on("data", (chunk) => {
1827
+ const text = chunk.toString("utf8");
1828
+ stdout = appendBounded(stdout, text);
1829
+ const split = splitLines(stdoutBuffer, text);
1830
+ stdoutBuffer = split.buffer;
1831
+ for (const line of split.lines) opts.onLine?.(line);
1832
+ });
1833
+ child.stderr?.on("data", (chunk) => {
1834
+ const text = chunk.toString("utf8");
1835
+ stderr = appendBounded(stderr, text);
1836
+ const split = splitLines(stderrBuffer, text);
1837
+ stderrBuffer = split.buffer;
1838
+ for (const line of split.lines) opts.onLine?.(line);
1839
+ });
1840
+ let hasExited = false;
1841
+ const fakeable = {
1842
+ /**
1843
+ * The real child process's pid.
1844
+ *
1845
+ * @returns The pid, or `undefined` before spawn assigns one.
1846
+ */
1847
+ get pid() {
1848
+ return child.pid;
1849
+ },
1850
+ /**
1851
+ * Whether the child process has already exited.
1852
+ *
1853
+ * @returns `true` once the `"exit"` event has fired.
1854
+ */
1855
+ get exited() {
1856
+ return hasExited;
1857
+ },
1858
+ /**
1859
+ * Registers a one-time listener for the child process's `"exit"` event.
1860
+ *
1861
+ * @param listener - Called once when the process exits.
1862
+ * @example
1863
+ * ```ts
1864
+ * fakeable.onExit(() => {});
1865
+ * ```
1866
+ */
1867
+ onExit(listener) {
1868
+ child.once("exit", listener);
1869
+ }
1870
+ };
1871
+ if (opts.signal) if (opts.signal.aborted) killProcessGroup(fakeable);
1872
+ else opts.signal.addEventListener("abort", () => void killProcessGroup(fakeable));
1873
+ child.on("error", reject);
1874
+ child.on("exit", (code, signal) => {
1875
+ hasExited = true;
1876
+ resolve({
1877
+ code,
1878
+ signal,
1879
+ stdout,
1880
+ stderr
1881
+ });
1882
+ });
1883
+ });
1884
+ //#endregion
1885
+ //#region src/plugins/tauri/api.ts
1886
+ /**
1887
+ * @file tauri plugin — API factory: composes resolve + argv + spawn + stream + errors + scrub + dev.
1888
+ */
1889
+ const CLI_VERSION_PATTERN = /tauri[- ]cli[^\d]*(\d+\.\d+\.\d+)/i;
1890
+ /**
1891
+ * Creates the tauri subprocess-seam API ([node, tauri.js, verb, ...] invocation — D-013).
1892
+ *
1893
+ * @param ctx - Plugin context (config seams, state, global config, log, env).
1894
+ * @returns The tauri plugin's public API.
1895
+ * @example
1896
+ * ```ts
1897
+ * const api = createTauriApi(ctx);
1898
+ * const result = await api.icon({ source: "icon.png" });
1899
+ * ```
1900
+ */
1901
+ function createTauriApi(ctx) {
1902
+ const spawnFn = ctx.config.spawnImpl ?? realSpawn;
1903
+ /**
1904
+ * Resolves the `[nodePath, tauriJsPath]` prefix shared by every verb's argv (D-013).
1905
+ *
1906
+ * @returns The resolved node binary path and tauri CLI entry path.
1907
+ * @example
1908
+ * ```ts
1909
+ * const { nodePath, tauriJsPath } = resolvePaths();
1910
+ * ```
1911
+ */
1912
+ function resolvePaths() {
1913
+ return {
1914
+ nodePath: resolveNodePath({
1915
+ nodePath: ctx.config.nodePath,
1916
+ pathEnv: ctx.env.get("PATH")
1917
+ }),
1918
+ tauriJsPath: resolveTauriJsPath()
1919
+ };
1920
+ }
1921
+ /**
1922
+ * Runs a one-shot tauri CLI verb to completion: spawns, scrubs every output
1923
+ * line before it reaches a log/callback, and classifies a non-zero exit.
1924
+ *
1925
+ * @param cmd - The full `[nodePath, tauriJsPath, ...]` argv to spawn.
1926
+ * @param hooks - Optional per-line output/compile-tick callbacks (already scrubbed).
1927
+ * @param hooks.onOutput - Called with each scrubbed output line.
1928
+ * @param hooks.onTick - Called with each parsed compile-progress tick.
1929
+ * @returns The completed run's result.
1930
+ * @throws {Error} A classified `TauriError` on a non-zero exit.
1931
+ * @example
1932
+ * ```ts
1933
+ * await run(infoArgv(nodePath, tauriJsPath));
1934
+ * ```
1935
+ */
1936
+ async function run(cmd, hooks) {
1937
+ const startedAt = Date.now();
1938
+ /**
1939
+ * Scrubs one output line, forwards it to the caller's hooks, and parses
1940
+ * any compile-progress tick out of it.
1941
+ *
1942
+ * @param line - A single raw (unscrubbed) output line.
1943
+ * @example
1944
+ * ```ts
1945
+ * handleLine("Compiling serde v1.0.190");
1946
+ * ```
1947
+ */
1948
+ const handleLine = (line) => {
1949
+ const scrubbedLine = scrub(line);
1950
+ ctx.log.debug("tauri:output", { line: scrubbedLine });
1951
+ hooks?.onOutput?.(scrubbedLine);
1952
+ const tick = parseCompileTick(scrubbedLine);
1953
+ if (tick) hooks?.onTick?.(tick);
1954
+ };
1955
+ const result = await spawnFn({
1956
+ cmd,
1957
+ cwd: ctx.global.projectDir,
1958
+ onLine: handleLine
1959
+ });
1960
+ const durationMs = Date.now() - startedAt;
1961
+ const scrubbedStdout = scrub(result.stdout);
1962
+ const scrubbedStderr = scrub(result.stderr);
1963
+ if (result.code !== 0) throw classify(result.code, scrubbedStderr);
1964
+ return {
1965
+ code: 0,
1966
+ stdout: scrubbedStdout,
1967
+ stderr: scrubbedStderr,
1968
+ durationMs
1969
+ };
1970
+ }
1971
+ return {
1972
+ /**
1973
+ * Regenerates the icon set from a source image (`tauri icon`).
1974
+ *
1975
+ * @param opts - Icon options.
1976
+ * @param opts.source - Path to the source icon image.
1977
+ * @returns The completed run's result.
1978
+ * @example
1979
+ * ```ts
1980
+ * await app.tauri.icon({ source: "assets/icon.png" });
1981
+ * ```
1982
+ */
1983
+ async icon(opts) {
1984
+ const { nodePath, tauriJsPath } = resolvePaths();
1985
+ return run(iconArgv(nodePath, tauriJsPath, opts.source));
1986
+ },
1987
+ /**
1988
+ * Runs `tauri build` / `tauri ios|android build` for the given target,
1989
+ * streaming scrubbed output and parsed compile ticks through the callbacks.
1990
+ *
1991
+ * @param opts - Build options (target + optional progress callbacks).
1992
+ * @param opts.target - Packaging target.
1993
+ * @param opts.onTick - Called with parsed compile progress ("Compiling crate N/M").
1994
+ * @param opts.onOutput - Called with each scrubbed output line.
1995
+ * @returns The completed run's result.
1996
+ * @example
1997
+ * ```ts
1998
+ * await app.tauri.build({ target: "macos", onTick: (t) => ctx.log.info("tick", t) });
1999
+ * ```
2000
+ */
2001
+ async build(opts) {
2002
+ const { nodePath, tauriJsPath } = resolvePaths();
2003
+ return run(buildArgv(nodePath, tauriJsPath, opts.target), {
2004
+ onOutput: opts.onOutput,
2005
+ onTick: opts.onTick
2006
+ });
2007
+ },
2008
+ /**
2009
+ * Runs `tauri ios|android init` — the ONLY init verbs (D-013). Callers must
2010
+ * check `project.completeness()` is `"not-initialized"` before calling this.
2011
+ *
2012
+ * @param opts - Mobile init options.
2013
+ * @param opts.platform - Mobile platform to initialize.
2014
+ * @returns The completed run's result.
2015
+ * @example
2016
+ * ```ts
2017
+ * await app.tauri.mobileInit({ platform: "ios" });
2018
+ * ```
2019
+ */
2020
+ async mobileInit(opts) {
2021
+ const { nodePath, tauriJsPath } = resolvePaths();
2022
+ return run(mobileInitArgv(nodePath, tauriJsPath, opts.platform));
2023
+ },
2024
+ /**
2025
+ * Starts the long-lived dev verb (`tauri dev` / `tauri ios|android dev`).
2026
+ * Returns immediately with a live handle — never awaits `exited` itself.
2027
+ *
2028
+ * @param opts - Dev options.
2029
+ * @param opts.target - Optional packaging target (desktop-uniform when omitted).
2030
+ * @param opts.onOutput - Called with each scrubbed output line (cli renders these; defaults to log-only).
2031
+ * @returns The live dev handle.
2032
+ * @throws {Error} `[native]` when a dev session is already running.
2033
+ * @example
2034
+ * ```ts
2035
+ * const handle = await app.tauri.dev({ target: "ios" });
2036
+ * await handle.ready;
2037
+ * ```
2038
+ */
2039
+ dev(opts) {
2040
+ if (ctx.state.dev) return Promise.reject(/* @__PURE__ */ new Error("[native] tauri dev already running.\n Call stop() on the existing dev handle before starting another."));
2041
+ const { nodePath, tauriJsPath } = resolvePaths();
2042
+ const url = ctx.global.web.dev.url;
2043
+ /**
2044
+ * Scrubs one raw dev-process output line before it can reach any log or
2045
+ * consumer callback — the SAME pipeline posture as `run()`'s one-shot verbs.
2046
+ *
2047
+ * @param line - A single raw (unscrubbed) output line.
2048
+ * @example
2049
+ * ```ts
2050
+ * handleDevLine("Compiling app v0.1.0");
2051
+ * ```
2052
+ */
2053
+ const handleDevLine = (line) => {
2054
+ const scrubbedLine = scrub(line);
2055
+ ctx.log.debug("tauri:dev:output", { line: scrubbedLine });
2056
+ opts.onOutput?.(scrubbedLine);
2057
+ };
2058
+ const handle = startDev({
2059
+ cmd: devArgv(nodePath, tauriJsPath, opts.target),
2060
+ cwd: ctx.global.projectDir,
2061
+ url,
2062
+ onLine: handleDevLine,
2063
+ deps: {
2064
+ spawn: spawnFn,
2065
+ probeReady: fetchReadinessProbe,
2066
+ intervalMs: ctx.config.readiness.intervalMs,
2067
+ timeoutMs: ctx.config.readiness.timeoutMs,
2068
+ /**
2069
+ * Installs a real process signal handler (`process.on`).
2070
+ *
2071
+ * @param event - Signal name (`SIGINT`/`SIGTERM`).
2072
+ * @param handler - Handler to install.
2073
+ * @returns The Node.js `process` object (from `process.on`).
2074
+ * @example
2075
+ * ```ts
2076
+ * onSignal("SIGINT", () => {});
2077
+ * ```
2078
+ */
2079
+ onSignal: (event, handler) => process.on(event, handler),
2080
+ /**
2081
+ * Removes a previously installed process signal handler (`process.off`).
2082
+ *
2083
+ * @param event - Signal name (`SIGINT`/`SIGTERM`).
2084
+ * @param handler - Handler to remove.
2085
+ * @returns The Node.js `process` object (from `process.off`).
2086
+ * @example
2087
+ * ```ts
2088
+ * offSignal("SIGINT", handler);
2089
+ * ```
2090
+ */
2091
+ offSignal: (event, handler) => process.off(event, handler)
2092
+ }
2093
+ });
2094
+ ctx.state.dev = handle;
2095
+ handle.exited.finally(() => {
2096
+ if (ctx.state.dev === handle) ctx.state.dev = void 0;
2097
+ }).catch(() => {});
2098
+ return Promise.resolve(handle);
2099
+ },
2100
+ /**
2101
+ * Probes CLI presence/version via `tauri info` — used by `doctor`.
2102
+ *
2103
+ * @returns The parsed CLI version, or `null` when the CLI can't be invoked.
2104
+ * @example
2105
+ * ```ts
2106
+ * const version = await app.tauri.version();
2107
+ * ```
2108
+ */
2109
+ async version() {
2110
+ try {
2111
+ const { nodePath, tauriJsPath } = resolvePaths();
2112
+ const result = await run(infoArgv(nodePath, tauriJsPath));
2113
+ return { cliVersion: CLI_VERSION_PATTERN.exec(result.stdout)?.[1] ?? result.stdout.trim() };
2114
+ } catch {
2115
+ return null;
2116
+ }
2117
+ }
2118
+ };
2119
+ }
2120
+ //#endregion
2121
+ //#region src/plugins/tauri/state.ts
2122
+ /**
2123
+ * Creates initial tauri plugin state (no live dev session).
2124
+ *
2125
+ * @returns Fresh state with no live dev handle.
2126
+ * @example
2127
+ * ```ts
2128
+ * const state = createTauriState();
2129
+ * ```
2130
+ */
2131
+ function createTauriState() {
2132
+ return { dev: void 0 };
2133
+ }
2134
+ /**
2135
+ * Standard tier — `@tauri-apps/cli` subprocess seam: argv builders, injectable spawn,
2136
+ * process-group dev lifecycle, stream parsing, error taxonomy, secret scrubbing.
2137
+ *
2138
+ * NO onStop by design (D-002): spec/08 §2 TeardownContext = { global } — a regular plugin's
2139
+ * onStop cannot reach ctx.state, so dev teardown is owned by the dev seam's own control flow
2140
+ * (signal handlers + DevHandle.stop()), which also covers Ctrl-C where onStop never fires.
2141
+ *
2142
+ * @see README.md
2143
+ * @example
2144
+ * ```ts
2145
+ * const app = createApp({ plugins: [tauriPlugin] });
2146
+ * ```
2147
+ */
2148
+ const tauriPlugin = createPlugin$1("tauri", {
2149
+ config: {
2150
+ spawnImpl: void 0,
2151
+ nodePath: void 0,
2152
+ readiness: {
2153
+ intervalMs: 250,
2154
+ timeoutMs: 6e4
2155
+ }
2156
+ },
2157
+ createState: createTauriState,
2158
+ api: createTauriApi
2159
+ });
2160
+ //#endregion
2161
+ //#region src/plugins/build/collect.ts
2162
+ /**
2163
+ * @file build plugin — pure per-target bundle-location table + artifact collection.
2164
+ */
2165
+ /**
2166
+ * Per-target glob patterns locating Tauri's finished installer(s), relative to each
2167
+ * target's {@link bundleRoot}. Desktop patterns are relative to `src-tauri/target/release/`
2168
+ * (Cargo's release profile output); mobile patterns are relative to `src-tauri/` (the
2169
+ * `gen/<platform>` tree `tauri ios|android build` produces).
2170
+ */
2171
+ const BUNDLE_LOCATIONS = {
2172
+ macos: ["bundle/dmg/*.dmg", "bundle/macos/*.app"],
2173
+ windows: ["bundle/nsis/*-setup.exe", "bundle/msi/*.msi"],
2174
+ linux: [
2175
+ "bundle/appimage/*.AppImage",
2176
+ "bundle/deb/*.deb",
2177
+ "bundle/rpm/*.rpm"
2178
+ ],
2179
+ ios: ["gen/apple/build/**/*.ipa"],
2180
+ android: ["gen/android/app/build/outputs/**/*.{aab,apk}"]
2181
+ };
2182
+ /**
2183
+ * Resolves Tauri's per-target output root that {@link BUNDLE_LOCATIONS} globs are
2184
+ * relative to — desktop bundles land under Cargo's `target/release/`; mobile installers
2185
+ * land under the mobile `gen/<platform>/` tree. Both roots live inside `src-tauri/`.
2186
+ *
2187
+ * @param projectDirectory - The generated Tauri project root (contains `src-tauri/`).
2188
+ * @param target - The packaging target.
2189
+ * @returns The absolute output root to glob {@link BUNDLE_LOCATIONS} patterns against.
2190
+ * @example
2191
+ * ```ts
2192
+ * bundleRoot("/repo/.moku/tauri", "macos"); // "/repo/.moku/tauri/src-tauri/target/release"
2193
+ * ```
2194
+ */
2195
+ function bundleRoot(projectDirectory, target) {
2196
+ const srcTauriDirectory = node_path.default.join(projectDirectory, "src-tauri");
2197
+ if (target === "ios" || target === "android") return srcTauriDirectory;
2198
+ return node_path.default.join(srcTauriDirectory, "target", "release");
2199
+ }
2200
+ /**
2201
+ * Locates the finished installer(s) for `target` via {@link BUNDLE_LOCATIONS} and copies
2202
+ * them into `outDir/<target>/` — the stable delivery location `native:complete` reports.
2203
+ * Copies with `recursive: true` so a macOS `.app` bundle (a directory) and single-file
2204
+ * installers (`.dmg`/`.exe`/`.msi`/`.AppImage`/`.deb`/`.rpm`/`.ipa`/`.aab`/`.apk`) both
2205
+ * work through the same call. Zero matches is an error, never a silent empty success —
2206
+ * a shippable artifact is the whole point of this phase.
2207
+ *
2208
+ * @param projectDirectory - The generated Tauri project root (contains `src-tauri/`).
2209
+ * @param target - The packaging target being collected.
2210
+ * @param outputDirectory - The installer delivery root (`config.outDir`).
2211
+ * @returns The delivery directory and the copied artifact paths.
2212
+ * @throws {Error} When no glob pattern for `target` matches any file.
2213
+ * @example
2214
+ * ```ts
2215
+ * const { outPath, artifacts } = await collectArtifacts("/repo/.moku/tauri", "macos", "dist-native");
2216
+ * ```
2217
+ */
2218
+ async function collectArtifacts(projectDirectory, target, outputDirectory) {
2219
+ const root = bundleRoot(projectDirectory, target);
2220
+ const patterns = BUNDLE_LOCATIONS[target];
2221
+ const matches = [];
2222
+ for (const pattern of patterns) for await (const match of (0, node_fs_promises.glob)(pattern, { cwd: root })) matches.push(match);
2223
+ if (matches.length === 0) {
2224
+ const globbedRoots = patterns.map((pattern) => node_path.default.join(root, pattern)).join(", ");
2225
+ throw new Error(`[native] No ${target} installer artifacts found.\n Checked ${globbedRoots} — run \`native doctor\` to diagnose the build output.`);
2226
+ }
2227
+ const outPath = node_path.default.join(outputDirectory, target);
2228
+ await (0, node_fs_promises.mkdir)(outPath, { recursive: true });
2229
+ const artifacts = [];
2230
+ for (const match of matches) {
2231
+ const source = node_path.default.join(root, match);
2232
+ const destination = node_path.default.join(outPath, node_path.default.basename(match));
2233
+ await (0, node_fs_promises.cp)(source, destination, { recursive: true });
2234
+ artifacts.push(destination);
2235
+ }
2236
+ return {
2237
+ outPath,
2238
+ artifacts
2239
+ };
2240
+ }
2241
+ //#endregion
2242
+ //#region src/plugins/build/pipeline.ts
2243
+ /**
2244
+ * @file build plugin — per-target phase pipeline: scaffold → codegen → icons → compile →
2245
+ * bundle → collect, with timing, native:phase/native:complete emission, the mobile
2246
+ * scaffold gate, and the compile/bundle single-subprocess split (spec/03 §Phase semantics).
2247
+ */
2248
+ /** Mobile packaging targets — the only two with a `gen/<platform>` scaffold gate. */
2249
+ const MOBILE_TARGETS = /* @__PURE__ */ new Set(["ios", "android"]);
2250
+ /**
2251
+ * Narrows a packaging target to a mobile platform.
2252
+ *
2253
+ * @param target - The packaging target to check.
2254
+ * @returns Whether `target` is a mobile platform (`ios` or `android`).
2255
+ * @example
2256
+ * ```ts
2257
+ * isMobileTarget("android"); // true
2258
+ * ```
2259
+ */
2260
+ function isMobileTarget(target) {
2261
+ return MOBILE_TARGETS.has(target);
2262
+ }
2263
+ /**
2264
+ * Builds the `[native]`-formatted fix-it error for a partial mobile `gen/` tree — the
2265
+ * scaffold gate never re-initializes a partial tree, so this points at diagnosis/reset
2266
+ * instead (S4 refinement: `tauri#13902` can leave a partial init).
2267
+ *
2268
+ * @param target - The mobile target whose tree is incomplete.
2269
+ * @param missing - The required files/directories that are absent.
2270
+ * @returns A formatted `[native] ...` error.
2271
+ * @example
2272
+ * ```ts
2273
+ * throw incompleteMobileTreeError("android", ["build.gradle.kts"]);
2274
+ * ```
2275
+ */
2276
+ function incompleteMobileTreeError(target, missing) {
2277
+ return /* @__PURE__ */ new Error(`[native] ${target} project tree is incomplete.\n Missing ${missing.join(", ")} — run \`native doctor\` to diagnose, or \`native clean --target ${target}\` to reset before rebuilding.`);
2278
+ }
2279
+ /**
2280
+ * Runs the `scaffold` phase. Desktop targets only ensure `projectDir` exists; mobile
2281
+ * targets gate on `project.completeness()` — a `"not-initialized"` tree is initialized
2282
+ * once via `tauri.mobileInit()` and re-checked, but a partial (`"incomplete"`) tree fails
2283
+ * fast, before any further subprocess runs, rather than being silently re-initialized.
2284
+ *
2285
+ * @param ctx - The build pipeline's domain context.
2286
+ * @param target - The packaging target being scaffolded.
2287
+ * @returns Nothing.
2288
+ * @throws {Error} When a mobile target's `gen/` tree is present but incomplete.
2289
+ * @example
2290
+ * ```ts
2291
+ * await runScaffold(ctx, "android");
2292
+ * ```
2293
+ */
2294
+ async function runScaffold(ctx, target) {
2295
+ if (!isMobileTarget(target)) {
2296
+ await (0, node_fs_promises.mkdir)(ctx.global.projectDir, { recursive: true });
2297
+ return;
2298
+ }
2299
+ const project = ctx.require(projectPlugin);
2300
+ let status = project.completeness({ target });
2301
+ if (status.status === "not-initialized") {
2302
+ await ctx.require(tauriPlugin).mobileInit({ platform: target });
2303
+ status = project.completeness({ target });
2304
+ }
2305
+ if (status.status === "incomplete") throw incompleteMobileTreeError(target, status.missing);
2306
+ }
2307
+ /**
2308
+ * Runs the `codegen` phase — `project.generate()`, plus the idempotent
2309
+ * `project.patchMobile()` pass (Android signing state only, re-applied every build; D-012)
2310
+ * for mobile targets.
2311
+ *
2312
+ * @param ctx - The build pipeline's domain context.
2313
+ * @param target - The packaging target being generated for.
2314
+ * @returns Nothing.
2315
+ * @example
2316
+ * ```ts
2317
+ * await runCodegen(ctx, "macos");
2318
+ * ```
2319
+ */
2320
+ async function runCodegen(ctx, target) {
2321
+ const project = ctx.require(projectPlugin);
2322
+ await project.generate({ target });
2323
+ if (isMobileTarget(target)) await project.patchMobile({ target });
2324
+ }
2325
+ /**
2326
+ * Runs the `icons` phase. v1 wires no icon-source config field on any plugin's `Config`,
2327
+ * so there is nothing to regenerate `tauri icon` from — always reports `"skipped"` rather
2328
+ * than guessing a source path or invoking the CLI without one.
2329
+ *
2330
+ * @returns The phase detail to attach to the `native:phase` "done" event.
2331
+ * @example
2332
+ * ```ts
2333
+ * const { detail } = await runIcons();
2334
+ * ```
2335
+ */
2336
+ function runIcons() {
2337
+ return Promise.resolve({ detail: "skipped" });
2338
+ }
2339
+ /** Matches a tauri build output line signalling the compile→bundle transition. */
2340
+ const BUNDLING_TRANSITION_PATTERN = /bundling/i;
2341
+ /**
2342
+ * Formats a compile tick into the `native:phase` "progress" detail string — real crate
2343
+ * counts, never a fake percentage.
2344
+ *
2345
+ * @param tick - The parsed compile tick.
2346
+ * @param tick.crate - The crate currently compiling.
2347
+ * @param tick.index - The crate's position in the current compile unit count, if known.
2348
+ * @param tick.total - The total compile unit count, if known.
2349
+ * @returns The human-readable progress detail.
2350
+ * @example
2351
+ * ```ts
2352
+ * formatCompileTickDetail({ crate: "tauri", index: 3, total: 50 }); // "Compiling tauri 3/50"
2353
+ * ```
2354
+ */
2355
+ function formatCompileTickDetail(tick) {
2356
+ const counter = tick.index !== void 0 && tick.total !== void 0 ? ` ${tick.index}/${tick.total}` : "";
2357
+ return `Compiling ${tick.crate}${counter}`;
2358
+ }
2359
+ /**
2360
+ * Emits one `native:phase` event, omitting `durationMs`/`detail` when absent rather than
2361
+ * assigning `undefined` (D-014, `exactOptionalPropertyTypes`).
2362
+ *
2363
+ * @param ctx - The build pipeline's domain context.
2364
+ * @param target - The packaging target the phase runs for.
2365
+ * @param phase - Which pipeline phase this event reports on.
2366
+ * @param status - The phase's current status.
2367
+ * @param extra - Optional duration/detail to attach.
2368
+ * @param extra.durationMs - Elapsed time for a "done"/"error" event.
2369
+ * @param extra.detail - Human-readable detail (progress ticks, skip reasons, error text).
2370
+ * @example
2371
+ * ```ts
2372
+ * emitPhase(ctx, "macos", "scaffold", "start");
2373
+ * ```
2374
+ */
2375
+ function emitPhase(ctx, target, phase, status, extra) {
2376
+ ctx.emit("native:phase", {
2377
+ target,
2378
+ phase,
2379
+ status,
2380
+ ...extra?.durationMs === void 0 ? {} : { durationMs: extra.durationMs },
2381
+ ...extra?.detail === void 0 ? {} : { detail: extra.detail }
2382
+ });
2383
+ }
2384
+ /**
2385
+ * Runs the shared `tauri build` subprocess that covers BOTH the `compile` and `bundle`
2386
+ * phases (one process — D-013). `compile` carries the live `onTick` progress stream;
2387
+ * `bundle`'s duration is derived from the first scrubbed output line matching the
2388
+ * compile→bundle transition, with a zero-duration fallback when no such line appears.
2389
+ * A failure is always attributed to `compile` (the phase that always starts first) and
2390
+ * `bundle` is never emitted at all — the same "error skips the next phase" contract the
2391
+ * generic phase runner gives every other phase.
2392
+ *
2393
+ * @param ctx - The build pipeline's domain context.
2394
+ * @param target - The packaging target being compiled/bundled.
2395
+ * @returns The measured `compile` and `bundle` phase durations.
2396
+ * @throws {Error} Whatever `tauri.build()` throws (already reported via native:phase).
2397
+ * @example
2398
+ * ```ts
2399
+ * const { compileDurationMs, bundleDurationMs } = await runCompileAndBundle(ctx, "macos");
2400
+ * ```
2401
+ */
2402
+ async function runCompileAndBundle(ctx, target) {
2403
+ const startedAt = Date.now();
2404
+ let transitionAt;
2405
+ emitPhase(ctx, target, "compile", "start");
2406
+ try {
2407
+ await ctx.require(tauriPlugin).build({
2408
+ target,
2409
+ /**
2410
+ * Forwards one parsed compile tick as a `native:phase` "progress" event.
2411
+ *
2412
+ * @param tick - The parsed compile tick.
2413
+ * @example
2414
+ * ```ts
2415
+ * onTick({ crate: "tauri", index: 3, total: 50 });
2416
+ * ```
2417
+ */
2418
+ onTick: (tick) => {
2419
+ emitPhase(ctx, target, "compile", "progress", { detail: formatCompileTickDetail(tick) });
2420
+ },
2421
+ /**
2422
+ * Records the first moment a scrubbed output line signals the compile→bundle
2423
+ * transition, so `bundle`'s duration can be derived after the subprocess exits.
2424
+ *
2425
+ * @param line - A single scrubbed output line.
2426
+ * @example
2427
+ * ```ts
2428
+ * onOutput("Bundling application (App.dmg)");
2429
+ * ```
2430
+ */
2431
+ onOutput: (line) => {
2432
+ if (transitionAt === void 0 && BUNDLING_TRANSITION_PATTERN.test(line)) transitionAt = Date.now();
2433
+ }
2434
+ });
2435
+ } catch (error) {
2436
+ emitPhase(ctx, target, "compile", "error", {
2437
+ durationMs: Date.now() - startedAt,
2438
+ detail: error instanceof Error ? error.message : String(error)
2439
+ });
2440
+ throw error;
2441
+ }
2442
+ const endedAt = Date.now();
2443
+ const bundleStartedAt = transitionAt ?? endedAt;
2444
+ const compileDurationMs = bundleStartedAt - startedAt;
2445
+ const bundleDurationMs = endedAt - bundleStartedAt;
2446
+ emitPhase(ctx, target, "compile", "done", { durationMs: compileDurationMs });
2447
+ emitPhase(ctx, target, "bundle", "start");
2448
+ emitPhase(ctx, target, "bundle", "done", { durationMs: bundleDurationMs });
2449
+ return {
2450
+ compileDurationMs,
2451
+ bundleDurationMs
2452
+ };
2453
+ }
2454
+ /**
2455
+ * Runs one phase generically: emits `native:phase` start/done/error and measures
2456
+ * duration, rethrowing on failure so the caller stops the pipeline (no partial-continue,
2457
+ * v1) — the phase after a failing one is never started.
2458
+ *
2459
+ * @param ctx - The build pipeline's domain context.
2460
+ * @param target - The packaging target the phase runs for.
2461
+ * @param phase - Which pipeline phase this is.
2462
+ * @param run - The phase's work.
2463
+ * @param detailOf - Optional: derives the "done" event's `detail` from the phase's result.
2464
+ * @returns The measured phase duration and the phase's own return value.
2465
+ * @throws {Error} Rethrows whatever `run` throws, after emitting the error event.
2466
+ * @example
2467
+ * ```ts
2468
+ * const { durationMs } = await runPhase(ctx, "macos", "scaffold", () => runScaffold(ctx, "macos"));
2469
+ * ```
2470
+ */
2471
+ async function runPhase(ctx, target, phase, run, detailOf) {
2472
+ const startedAt = Date.now();
2473
+ emitPhase(ctx, target, phase, "start");
2474
+ try {
2475
+ const result = await run();
2476
+ const durationMs = Date.now() - startedAt;
2477
+ const detail = detailOf?.(result);
2478
+ emitPhase(ctx, target, phase, "done", detail === void 0 ? { durationMs } : {
2479
+ durationMs,
2480
+ detail
2481
+ });
2482
+ return {
2483
+ durationMs,
2484
+ result
2485
+ };
2486
+ } catch (error) {
2487
+ emitPhase(ctx, target, phase, "error", {
2488
+ durationMs: Date.now() - startedAt,
2489
+ detail: error instanceof Error ? error.message : String(error)
2490
+ });
2491
+ throw error;
2492
+ }
2493
+ }
2494
+ /**
2495
+ * Runs the full `scaffold → codegen → icons → compile → bundle → collect` pipeline for
2496
+ * ONE target — sequential phases, each timed and reported via `native:phase`, stopping at
2497
+ * the first failing phase. Emits `native:complete` on success.
2498
+ *
2499
+ * @param ctx - The build pipeline's domain context.
2500
+ * @param target - The packaging target to build.
2501
+ * @returns The completed pipeline's result.
2502
+ * @throws {Error} Whatever the failing phase throws (already reported via native:phase).
2503
+ * @example
2504
+ * ```ts
2505
+ * const result = await runPipeline(ctx, "macos");
2506
+ * ```
2507
+ */
2508
+ async function runPipeline(ctx, target) {
2509
+ const startedAt = Date.now();
2510
+ const phases = [];
2511
+ const scaffold = await runPhase(ctx, target, "scaffold", () => runScaffold(ctx, target));
2512
+ phases.push({
2513
+ phase: "scaffold",
2514
+ durationMs: scaffold.durationMs
2515
+ });
2516
+ const codegen = await runPhase(ctx, target, "codegen", () => runCodegen(ctx, target));
2517
+ phases.push({
2518
+ phase: "codegen",
2519
+ durationMs: codegen.durationMs
2520
+ });
2521
+ const icons = await runPhase(ctx, target, "icons", runIcons, (result) => result.detail);
2522
+ phases.push({
2523
+ phase: "icons",
2524
+ durationMs: icons.durationMs
2525
+ });
2526
+ const { compileDurationMs, bundleDurationMs } = await runCompileAndBundle(ctx, target);
2527
+ phases.push({
2528
+ phase: "compile",
2529
+ durationMs: compileDurationMs
2530
+ }, {
2531
+ phase: "bundle",
2532
+ durationMs: bundleDurationMs
2533
+ });
2534
+ const collect = await runPhase(ctx, target, "collect", () => collectArtifacts(ctx.global.projectDir, target, ctx.global.outDir));
2535
+ phases.push({
2536
+ phase: "collect",
2537
+ durationMs: collect.durationMs
2538
+ });
2539
+ const durationMs = Date.now() - startedAt;
2540
+ const { outPath, artifacts } = collect.result;
2541
+ ctx.emit("native:complete", {
2542
+ target,
2543
+ outPath,
2544
+ artifacts,
2545
+ durationMs
2546
+ });
2547
+ return {
2548
+ target,
2549
+ outPath,
2550
+ artifacts,
2551
+ durationMs,
2552
+ phases
2553
+ };
2554
+ }
2555
+ //#endregion
2556
+ //#region src/plugins/build/api.ts
2557
+ /**
2558
+ * @file build plugin — API factory: run (one target) / runAll (sequential multi-target).
2559
+ */
2560
+ /**
2561
+ * Creates the build pipeline API — `run` executes the full
2562
+ * scaffold→codegen→icons→compile→bundle→collect pipeline for one target; `runAll` repeats
2563
+ * it sequentially across targets (never `Promise.all` — all five share one Cargo
2564
+ * `target/` lock, so parallelism would only contend) and stops at the first failing
2565
+ * target (no partial-continue in v1).
2566
+ *
2567
+ * @param ctx - Plugin context (`require`s project/tauri, emits native:phase/native:complete).
2568
+ * @returns The `build` plugin's public API.
2569
+ * @example
2570
+ * ```ts
2571
+ * const api = createBuildApi(ctx);
2572
+ * const result = await api.run({ target: "macos" });
2573
+ * ```
2574
+ */
2575
+ function createBuildApi(ctx) {
2576
+ return {
2577
+ /**
2578
+ * Runs the full per-target pipeline once.
2579
+ *
2580
+ * @param opts - Run options.
2581
+ * @param opts.target - The packaging target to build.
2582
+ * @returns The completed pipeline's result.
2583
+ * @example
2584
+ * ```ts
2585
+ * await app.build.run({ target: "android" });
2586
+ * ```
2587
+ */
2588
+ run(opts) {
2589
+ return runPipeline(ctx, opts.target);
2590
+ },
2591
+ /**
2592
+ * Runs the pipeline sequentially for every target in `opts.targets` (default:
2593
+ * `ctx.global.targets`), stopping at the first failure.
2594
+ *
2595
+ * @param opts - Run-all options.
2596
+ * @param opts.targets - The targets to build (default: every configured target).
2597
+ * @returns Every completed target's result, in target order.
2598
+ * @throws {Error} Whatever the first failing target's pipeline throws.
2599
+ * @example
2600
+ * ```ts
2601
+ * await app.build.runAll();
2602
+ * ```
2603
+ */
2604
+ async runAll(opts = {}) {
2605
+ const targets = opts.targets ?? ctx.global.targets;
2606
+ const results = [];
2607
+ for (const target of targets) results.push(await runPipeline(ctx, target));
2608
+ return results;
2609
+ }
2610
+ };
2611
+ }
2612
+ //#endregion
2613
+ //#region src/plugins/build/index.ts
2614
+ /**
2615
+ * Standard tier — sequential per-target pipeline emitting global native:phase/native:complete;
2616
+ * owns the collect phase (bundle-location table → dist-native/<target>/).
2617
+ *
2618
+ * @see README.md
2619
+ * @example
2620
+ * ```ts
2621
+ * const app = createApp({ plugins: [projectPlugin, tauriPlugin, buildPlugin] });
2622
+ * ```
2623
+ */
2624
+ const buildPlugin = createPlugin$1("build", {
2625
+ depends: [projectPlugin, tauriPlugin],
2626
+ api: createBuildApi
2627
+ });
2628
+ //#endregion
2629
+ //#region src/plugins/doctor/checks/android.ts
2630
+ /**
2631
+ * Confirms the Android SDK home, NDK home, and a real `java` binary are all present.
2632
+ *
2633
+ * @param input - The check input, scoped to the "android" target.
2634
+ * @returns The check result.
2635
+ * @example
2636
+ * ```ts
2637
+ * await run({ target: "android", env, probe, ... });
2638
+ * ```
2639
+ */
2640
+ async function run$8(input) {
2641
+ const missing = [];
2642
+ if (!input.env.has("ANDROID_HOME") && !input.env.has("ANDROID_SDK_ROOT")) missing.push("ANDROID_HOME (or ANDROID_SDK_ROOT)");
2643
+ if (!input.env.has("ANDROID_NDK_HOME")) missing.push("ANDROID_NDK_HOME");
2644
+ if ((await input.probe("java", ["-version"])).code !== 0) missing.push("a working JDK (`java` on PATH)");
2645
+ if (missing.length > 0) return {
2646
+ id: "android-toolchain",
2647
+ target: "android",
2648
+ status: "fail",
2649
+ message: `[native] Android toolchain incomplete — missing: ${missing.join(", ")}.`,
2650
+ fixIt: "install Android Studio + NDK, then set ANDROID_HOME and ANDROID_NDK_HOME"
2651
+ };
2652
+ return {
2653
+ id: "android-toolchain",
2654
+ target: "android",
2655
+ status: "pass",
2656
+ message: "[native] Android SDK, NDK, and JDK are all present."
2657
+ };
2658
+ }
2659
+ /** Android SDK/NDK/JDK presence — android only. */
2660
+ const androidCheck = {
2661
+ id: "android-toolchain",
2662
+ /**
2663
+ * Whether this check applies — android only.
2664
+ *
2665
+ * @param target - The candidate scope.
2666
+ * @returns Whether `android-toolchain` applies to `target`.
2667
+ * @example
2668
+ * ```ts
2669
+ * androidCheck.appliesTo("android", global); // true
2670
+ * ```
2671
+ */
2672
+ appliesTo: (target) => target === "android",
2673
+ run: run$8
2674
+ };
2675
+ //#endregion
2676
+ //#region src/plugins/doctor/checks/completeness.ts
2677
+ /**
2678
+ * Runs the mobile gen/ completeness gate for one target via `project.completeness()` +
2679
+ * `project.requiredFiles()`. A missing gen/ tree is "will init on first build" (pass, not
2680
+ * fail) — only a PARTIAL init (tauri#13902) is a fail, and its fix-it is always the same
2681
+ * one command.
2682
+ *
2683
+ * @param input - The check input, scoped to "ios" or "android".
2684
+ * @returns The check result.
2685
+ * @example
2686
+ * ```ts
2687
+ * await run({ target: "android", project, ... });
2688
+ * ```
2689
+ */
2690
+ async function run$7(input) {
2691
+ if (input.target !== "ios" && input.target !== "android") throw new Error(`[native] completeness check does not apply to target "${input.target}".`);
2692
+ const { target } = input;
2693
+ const id = `gen-completeness-${target}`;
2694
+ const result = input.project.completeness({ target });
2695
+ if (result.status === "incomplete") return {
2696
+ id,
2697
+ target,
2698
+ status: "fail",
2699
+ message: `[native] ${target} gen/ tree is missing required files: ${result.missing.join(", ")}.`,
2700
+ fixIt: `native clean --target ${target}`
2701
+ };
2702
+ if (result.status === "not-initialized") return {
2703
+ id,
2704
+ target,
2705
+ status: "pass",
2706
+ message: `[native] ${target} gen/ tree is not initialized yet — will init on first build.`
2707
+ };
2708
+ if (result.status === "complete") return {
2709
+ id,
2710
+ target,
2711
+ status: "pass",
2712
+ message: `[native] ${target} gen/ tree is complete (${input.project.requiredFiles(target).length} required files present).`
2713
+ };
2714
+ return {
2715
+ id,
2716
+ target,
2717
+ status: "pass",
2718
+ message: `[native] ${target} has no gen/ tree (not applicable).`
2719
+ };
2720
+ }
2721
+ /** Mobile gen/ tree completeness — ios/android only. */
2722
+ const completenessCheck = {
2723
+ id: "gen-completeness",
2724
+ /**
2725
+ * Whether this check applies — only the mobile targets have a gen/ tree.
2726
+ *
2727
+ * @param target - The candidate scope.
2728
+ * @returns Whether `gen-completeness` applies to `target`.
2729
+ * @example
2730
+ * ```ts
2731
+ * completenessCheck.appliesTo("android", global); // true
2732
+ * ```
2733
+ */
2734
+ appliesTo: (target) => target === "ios" || target === "android",
2735
+ run: run$7
2736
+ };
2737
+ //#endregion
2738
+ //#region src/plugins/doctor/checks/cross-repo.ts
2739
+ /**
2740
+ * Always-fires pointer: packaged-app API calls originate from the Tauri webview origins,
2741
+ * which the worker's CORS allowlist must include.
2742
+ *
2743
+ * @param _input - Unused — this pointer's message never depends on config.
2744
+ * @returns The check result — always "warn".
2745
+ * @example
2746
+ * ```ts
2747
+ * await runCors(input);
2748
+ * ```
2749
+ */
2750
+ async function runCors(_input) {
2751
+ return {
2752
+ id: "cross-repo-cors",
2753
+ target: "host",
2754
+ status: "warn",
2755
+ message: "[native] packaged-app API calls originate from \"tauri://localhost\" / \"http://tauri.localhost\" — verify the worker's CORS allowlist includes both origins.",
2756
+ fixIt: "add \"tauri://localhost\" and \"http://tauri.localhost\" to the worker CORS allowlist"
2757
+ };
2758
+ }
2759
+ /** Worker CORS allowlist pointer — always fires (host-scoped). */
2760
+ const crossRepoCorsCheck = {
2761
+ id: "cross-repo-cors",
2762
+ /**
2763
+ * Whether this check applies — host-scoped, always fires.
2764
+ *
2765
+ * @param target - The candidate scope.
2766
+ * @returns Whether `cross-repo-cors` applies to `target`.
2767
+ * @example
2768
+ * ```ts
2769
+ * crossRepoCorsCheck.appliesTo("host", global); // true
2770
+ * ```
2771
+ */
2772
+ appliesTo: (target) => target === "host",
2773
+ run: runCors
2774
+ };
2775
+ /**
2776
+ * Fires only when `deep-link` is composed: universal/app links are deferred post-v1
2777
+ * (D-011), and moving to universal mode will additionally need worker/CDN `.well-known`
2778
+ * files.
2779
+ *
2780
+ * @param _input - Unused — this pointer's message never depends on config beyond appliesTo's own filter.
2781
+ * @returns The check result — always "warn".
2782
+ * @example
2783
+ * ```ts
2784
+ * await runDeepLinkWellKnown(input);
2785
+ * ```
2786
+ */
2787
+ async function runDeepLinkWellKnown(_input) {
2788
+ return {
2789
+ id: "cross-repo-deep-link-well-known",
2790
+ target: "host",
2791
+ status: "warn",
2792
+ message: "[native] deep-link is composed in scheme mode (universal/app links deferred, D-011) — moving to universal mode will additionally need worker/CDN .well-known/apple-app-site-association and .well-known/assetlinks.json.",
2793
+ fixIt: "track universal/app-link .well-known files as a follow-up when deep-link mode moves beyond \"scheme\""
2794
+ };
2795
+ }
2796
+ /** deep-link .well-known pointer — fires only when deep-link is composed (host-scoped). */
2797
+ const crossRepoDeepLinkCheck = {
2798
+ id: "cross-repo-deep-link-well-known",
2799
+ /**
2800
+ * Whether this check applies — host-scoped, and only when deep-link is composed.
2801
+ *
2802
+ * @param target - The candidate scope.
2803
+ * @param global - Frozen global framework config.
2804
+ * @returns Whether `cross-repo-deep-link-well-known` applies to `target`/`global`.
2805
+ * @example
2806
+ * ```ts
2807
+ * crossRepoDeepLinkCheck.appliesTo("host", global); // true when deep-link is composed
2808
+ * ```
2809
+ */
2810
+ appliesTo: (target, global) => target === "host" && global.system.some((entry) => entry.name === "deep-link"),
2811
+ run: runDeepLinkWellKnown
2812
+ };
2813
+ //#endregion
2814
+ //#region src/plugins/doctor/checks/node.ts
2815
+ /**
2816
+ * Confirms a real `node` binary is invokable — distinct from bun, since the
2817
+ * `@tauri-apps/cli` shebang requires Node.js (tauri#9939, D-013).
2818
+ *
2819
+ * @param input - The check input (host-scoped).
2820
+ * @returns The check result.
2821
+ * @example
2822
+ * ```ts
2823
+ * await run({ target: "host", probe, ... });
2824
+ * ```
2825
+ */
2826
+ async function run$6(input) {
2827
+ const result = await input.probe("node", ["--version"]);
2828
+ if (result.code !== 0) return {
2829
+ id: "node-binary",
2830
+ target: "host",
2831
+ status: "fail",
2832
+ message: "[native] a real \"node\" binary was not found on PATH — the @tauri-apps/cli shebang requires Node.js, not bun (tauri#9939).",
2833
+ fixIt: "install Node.js and ensure it resolves on PATH ahead of any bun shim"
2834
+ };
2835
+ return {
2836
+ id: "node-binary",
2837
+ target: "host",
2838
+ status: "pass",
2839
+ message: `[native] node ${result.stdout.trim()} detected.`
2840
+ };
2841
+ }
2842
+ /** Real `node` binary presence — a hard prerequisite for every tauri verb (D-013). */
2843
+ const nodeCheck = {
2844
+ id: "node-binary",
2845
+ /**
2846
+ * Whether this check applies — host-scoped only.
2847
+ *
2848
+ * @param target - The candidate scope.
2849
+ * @returns Whether `node-binary` applies to `target`.
2850
+ * @example
2851
+ * ```ts
2852
+ * nodeCheck.appliesTo("host", global); // true
2853
+ * ```
2854
+ */
2855
+ appliesTo: (target) => target === "host",
2856
+ run: run$6
2857
+ };
2858
+ //#endregion
2859
+ //#region src/plugins/doctor/checks/rustup.ts
2860
+ /** Rust target triple required per packaging Target (`rustup target add <triple>`). */
2861
+ const RUST_TARGET_TRIPLES = {
2862
+ macos: "aarch64-apple-darwin",
2863
+ windows: "x86_64-pc-windows-msvc",
2864
+ linux: "x86_64-unknown-linux-gnu",
2865
+ ios: "aarch64-apple-ios",
2866
+ android: "aarch64-linux-android"
2867
+ };
2868
+ /**
2869
+ * Checks that rustup is on PATH and the packaging target's required rust triple is
2870
+ * installed, via `rustup target list --installed`.
2871
+ *
2872
+ * @param input - The check input for one real packaging target.
2873
+ * @returns The check result.
2874
+ * @example
2875
+ * ```ts
2876
+ * await run({ target: "ios", probe, ... });
2877
+ * ```
2878
+ */
2879
+ async function run$5(input) {
2880
+ const { target } = input;
2881
+ if (target === "host") throw new Error("[native] rustup check invoked without a packaging target (\"host\").");
2882
+ const triple = RUST_TARGET_TRIPLES[target];
2883
+ const probeResult = await input.probe("rustup", [
2884
+ "target",
2885
+ "list",
2886
+ "--installed"
2887
+ ]);
2888
+ if (probeResult.code !== 0) return {
2889
+ id: "rustup-targets",
2890
+ target,
2891
+ status: "fail",
2892
+ message: `[native] rustup was not found on PATH (required for "${target}").`,
2893
+ fixIt: "install rustup: https://rustup.rs"
2894
+ };
2895
+ if (!probeResult.stdout.includes(triple)) return {
2896
+ id: "rustup-targets",
2897
+ target,
2898
+ status: "fail",
2899
+ message: `[native] rust target "${triple}" is not installed (required for "${target}").`,
2900
+ fixIt: `rustup target add ${triple}`
2901
+ };
2902
+ return {
2903
+ id: "rustup-targets",
2904
+ target,
2905
+ status: "pass",
2906
+ message: `[native] rustup target "${triple}" is installed.`
2907
+ };
2908
+ }
2909
+ /**
2910
+ * rustup presence + required rust target triple — applies to every real packaging target.
2911
+ * Membership in `RUST_TARGET_TRIPLES` (rather than a bare `!== "host"` check) keeps this
2912
+ * robust against an unrecognized target string reaching `appliesTo` at runtime.
2913
+ */
2914
+ const rustupCheck = {
2915
+ id: "rustup-targets",
2916
+ /**
2917
+ * Whether this check applies — every real packaging target has a required rust triple.
2918
+ *
2919
+ * @param target - The candidate scope.
2920
+ * @returns Whether `rustup-targets` applies to `target`.
2921
+ * @example
2922
+ * ```ts
2923
+ * rustupCheck.appliesTo("ios", global); // true
2924
+ * ```
2925
+ */
2926
+ appliesTo: (target) => target in RUST_TARGET_TRIPLES,
2927
+ run: run$5
2928
+ };
2929
+ //#endregion
2930
+ //#region src/plugins/doctor/checks/signing.ts
2931
+ /** Apple signing env var names doctor checks for presence — values are never read into messages. */
2932
+ const APPLE_SIGNING_ENV_VARS = [
2933
+ "APPLE_ID",
2934
+ "APPLE_PASSWORD",
2935
+ "APPLE_TEAM_ID"
2936
+ ];
2937
+ /**
2938
+ * Checks Apple signing env var presence for an ios/macos target — every var, some, or none set.
2939
+ *
2940
+ * @param input - The check input, scoped to "ios" or "macos".
2941
+ * @returns The check result — "pass" or "warn", never "fail".
2942
+ * @example
2943
+ * ```ts
2944
+ * checkAppleSigning({ target: "macos", env, ... });
2945
+ * ```
2946
+ */
2947
+ function checkAppleSigning(input) {
2948
+ const { target } = input;
2949
+ const missing = APPLE_SIGNING_ENV_VARS.filter((name) => !input.env.has(name));
2950
+ if (missing.length === APPLE_SIGNING_ENV_VARS.length) return {
2951
+ id: `signing-${target}`,
2952
+ target,
2953
+ status: "warn",
2954
+ message: `[native] no Apple signing env vars are set for "${target}" — unsigned dev builds are legal.`,
2955
+ fixIt: `set ${APPLE_SIGNING_ENV_VARS.join(", ")} to sign release builds`
2956
+ };
2957
+ if (missing.length > 0) return {
2958
+ id: `signing-${target}`,
2959
+ target,
2960
+ status: "warn",
2961
+ message: `[native] Apple signing env vars partially set for "${target}" — missing: ${missing.join(", ")}.`,
2962
+ fixIt: `set ${missing.join(", ")} to complete Apple signing`
2963
+ };
2964
+ return {
2965
+ id: `signing-${target}`,
2966
+ target,
2967
+ status: "pass",
2968
+ message: `[native] Apple signing env vars are set for "${target}".`
2969
+ };
2970
+ }
2971
+ /**
2972
+ * Checks the android signing env var (`signing.android.keystorePasswordEnv`) for presence.
2973
+ *
2974
+ * @param input - The check input, scoped to "android".
2975
+ * @returns The check result — "pass" or "warn", never "fail".
2976
+ * @example
2977
+ * ```ts
2978
+ * checkAndroidSigning({ target: "android", env, global, ... });
2979
+ * ```
2980
+ */
2981
+ function checkAndroidSigning(input) {
2982
+ const envName = input.global.signing.android?.keystorePasswordEnv;
2983
+ if (!envName) return {
2984
+ id: "signing-android",
2985
+ target: "android",
2986
+ status: "warn",
2987
+ message: "[native] no android signing configured — unsigned dev builds are legal.",
2988
+ fixIt: "set signing.android.keystorePasswordEnv to sign release builds"
2989
+ };
2990
+ if (!input.env.has(envName)) return {
2991
+ id: "signing-android",
2992
+ target: "android",
2993
+ status: "warn",
2994
+ message: `[native] android signing env var "${envName}" is not set.`,
2995
+ fixIt: `export ${envName} before building a signed android release`
2996
+ };
2997
+ return {
2998
+ id: "signing-android",
2999
+ target: "android",
3000
+ status: "pass",
3001
+ message: `[native] android signing env var "${envName}" is set.`
3002
+ };
3003
+ }
3004
+ /**
3005
+ * Dispatches to the Apple or Android signing presence check by target.
3006
+ *
3007
+ * @param input - The check input, scoped to "ios", "macos", or "android".
3008
+ * @returns The check result.
3009
+ * @example
3010
+ * ```ts
3011
+ * await run({ target: "ios", env, ... });
3012
+ * ```
3013
+ */
3014
+ async function run$4(input) {
3015
+ if (input.target === "android") return checkAndroidSigning(input);
3016
+ if (input.target === "ios" || input.target === "macos") return checkAppleSigning(input);
3017
+ throw new Error(`[native] signing check does not apply to target "${input.target}".`);
3018
+ }
3019
+ /** Signing env-var presence (never values) — ios/macos/android, warn-only posture. */
3020
+ const signingCheck = {
3021
+ id: "signing",
3022
+ /**
3023
+ * Whether this check applies — ios, macos, and android carry signing env var refs.
3024
+ *
3025
+ * @param target - The candidate scope.
3026
+ * @returns Whether `signing` applies to `target`.
3027
+ * @example
3028
+ * ```ts
3029
+ * signingCheck.appliesTo("android", global); // true
3030
+ * ```
3031
+ */
3032
+ appliesTo: (target) => target === "ios" || target === "macos" || target === "android",
3033
+ run: run$4
3034
+ };
3035
+ //#endregion
3036
+ //#region src/plugins/doctor/checks/tauri-cli.ts
3037
+ /**
3038
+ * Confirms the tauri CLI is invokable via the tauri plugin's own `version()` probe.
3039
+ *
3040
+ * @param input - The check input (host-scoped).
3041
+ * @returns The check result.
3042
+ * @example
3043
+ * ```ts
3044
+ * await run({ target: "host", tauri, ... });
3045
+ * ```
3046
+ */
3047
+ async function run$3(input) {
3048
+ const version = await input.tauri.version();
3049
+ if (!version) return {
3050
+ id: "tauri-cli",
3051
+ target: "host",
3052
+ status: "fail",
3053
+ message: "[native] the tauri CLI is not invokable (`tauri info` failed).",
3054
+ fixIt: "ensure @tauri-apps/cli is installed and a real node binary is on PATH (tauri#9939)"
3055
+ };
3056
+ return {
3057
+ id: "tauri-cli",
3058
+ target: "host",
3059
+ status: "pass",
3060
+ message: `[native] tauri CLI ${version.cliVersion} detected.`
3061
+ };
3062
+ }
3063
+ /** tauri CLI invokability — host-scoped, the one probe routed through the tauri plugin. */
3064
+ const tauriCliCheck = {
3065
+ id: "tauri-cli",
3066
+ /**
3067
+ * Whether this check applies — host-scoped only (one CLI invocation, not per target).
3068
+ *
3069
+ * @param target - The candidate scope.
3070
+ * @returns Whether `tauri-cli` applies to `target`.
3071
+ * @example
3072
+ * ```ts
3073
+ * tauriCliCheck.appliesTo("host", global); // true
3074
+ * ```
3075
+ */
3076
+ appliesTo: (target) => target === "host",
3077
+ run: run$3
3078
+ };
3079
+ //#endregion
3080
+ //#region src/plugins/doctor/checks/versions.ts
3081
+ /**
3082
+ * @file doctor plugin check — `@tauri-apps/*` JS package versions vs registry-pinned crate
3083
+ * ranges (major-version skew only). Warn-only: a version skew is often still buildable.
3084
+ */
3085
+ /**
3086
+ * Parses the leading major version number out of a version/range string (`"^2.1.0"`,
3087
+ * `"2"`, `"~2.3"` all yield `2`).
3088
+ *
3089
+ * @param input - A version or semver-range string.
3090
+ * @returns The leading major version number, or `undefined` if none is found.
3091
+ * @example
3092
+ * ```ts
3093
+ * parseMajor("^2.1.0"); // 2
3094
+ * ```
3095
+ */
3096
+ function parseMajor(input) {
3097
+ const match = /(\d+)/.exec(input);
3098
+ return match?.[1] === void 0 ? void 0 : Number(match[1]);
3099
+ }
3100
+ /**
3101
+ * Compares each composed capability's declared `@tauri-apps/*` npm version against the
3102
+ * registry-pinned Rust crate range's major version — a mismatch is cross-language skew,
3103
+ * which is often still buildable, so this check only ever warns.
3104
+ *
3105
+ * @param input - The check input (host-scoped).
3106
+ * @returns The check result — "pass" or "warn", never "fail".
3107
+ * @example
3108
+ * ```ts
3109
+ * await run({ target: "host", fs, project, ... });
3110
+ * ```
3111
+ */
3112
+ async function run$2(input) {
3113
+ const packageJsonPath = node_path.default.join(node_process.default.cwd(), "package.json");
3114
+ let raw;
3115
+ try {
3116
+ raw = await input.fs.readFile(packageJsonPath);
3117
+ } catch {
3118
+ return {
3119
+ id: "tauri-version-skew",
3120
+ target: "host",
3121
+ status: "warn",
3122
+ message: `[native] could not read ${packageJsonPath} to check @tauri-apps/* version skew.`
3123
+ };
3124
+ }
3125
+ let pkg;
3126
+ try {
3127
+ pkg = JSON.parse(raw);
3128
+ } catch {
3129
+ return {
3130
+ id: "tauri-version-skew",
3131
+ target: "host",
3132
+ status: "warn",
3133
+ message: `[native] ${packageJsonPath} is not valid JSON — skipped @tauri-apps/* version skew check.`
3134
+ };
3135
+ }
3136
+ const declared = {
3137
+ ...pkg.dependencies,
3138
+ ...pkg.devDependencies
3139
+ };
3140
+ const skewed = [];
3141
+ for (const row of input.project.registryRows()) {
3142
+ const declaredVersion = declared[row.npmPackage];
3143
+ if (!declaredVersion) continue;
3144
+ const declaredMajor = parseMajor(declaredVersion);
3145
+ const crateMajor = parseMajor(row.crateRange);
3146
+ if (declaredMajor !== void 0 && crateMajor !== void 0 && declaredMajor !== crateMajor) skewed.push(`${row.npmPackage}@${declaredVersion} vs crate ${row.crate}${row.crateRange}`);
3147
+ }
3148
+ if (skewed.length > 0) return {
3149
+ id: "tauri-version-skew",
3150
+ target: "host",
3151
+ status: "warn",
3152
+ message: `[native] @tauri-apps/* version skew detected: ${skewed.join("; ")}.`,
3153
+ fixIt: "align the npm package major version with the pinned Rust crate range, or re-run `native doctor` after upgrading"
3154
+ };
3155
+ return {
3156
+ id: "tauri-version-skew",
3157
+ target: "host",
3158
+ status: "pass",
3159
+ message: "[native] no @tauri-apps/* version skew detected."
3160
+ };
3161
+ }
3162
+ /** `@tauri-apps/*` npm-vs-crate version skew — warn only, never fail (host-scoped). */
3163
+ const versionsCheck = {
3164
+ id: "tauri-version-skew",
3165
+ /**
3166
+ * Whether this check applies — host-scoped only (one repo-wide package.json).
3167
+ *
3168
+ * @param target - The candidate scope.
3169
+ * @returns Whether `tauri-version-skew` applies to `target`.
3170
+ * @example
3171
+ * ```ts
3172
+ * versionsCheck.appliesTo("host", global); // true
3173
+ * ```
3174
+ */
3175
+ appliesTo: (target) => target === "host",
3176
+ run: run$2
3177
+ };
3178
+ //#endregion
3179
+ //#region src/plugins/doctor/checks/web-script.ts
3180
+ /**
3181
+ * @file doctor plugin check — web.build/web.dev.command scripts exist, resolved from the
3182
+ * SAME cwd Tauri will use (web.cwd override honored). Necessary-not-sufficient (documented):
3183
+ * this never executes the script, only confirms package.json declares it.
3184
+ */
3185
+ /**
3186
+ * Resolves the cwd Tauri will run `beforeBuildCommand`/`beforeDevCommand` from — the
3187
+ * `web.cwd` override when set (monorepo layouts), else the directory containing the
3188
+ * generated `tauri.conf.json` (`<projectDir>/src-tauri`).
3189
+ *
3190
+ * @param global - Frozen global framework config.
3191
+ * @returns The resolved absolute cwd.
3192
+ * @example
3193
+ * ```ts
3194
+ * resolveWebCwd(ctx.global); // "/repo/apps/web" or "/repo/.moku/tauri/src-tauri"
3195
+ * ```
3196
+ */
3197
+ function resolveWebCwd(global) {
3198
+ return global.web.cwd ? node_path.default.resolve(global.web.cwd) : node_path.default.join(global.projectDir, "src-tauri");
3199
+ }
3200
+ /**
3201
+ * Extracts the package.json script name a command invokes (`"bun run build"` → `"build"`,
3202
+ * `"npm test"` → `"test"`). Best-effort — the command may not follow this shape.
3203
+ *
3204
+ * @param command - The configured shell command.
3205
+ * @returns The extracted script name, or `undefined` if it can't be determined.
3206
+ * @example
3207
+ * ```ts
3208
+ * extractScriptName("bun run build"); // "build"
3209
+ * ```
3210
+ */
3211
+ function extractScriptName(command) {
3212
+ const tokens = command.trim().split(/\s+/);
3213
+ const runIndex = tokens.indexOf("run");
3214
+ return runIndex === -1 ? tokens[1] : tokens[runIndex + 1];
3215
+ }
3216
+ /**
3217
+ * Confirms `web.build`/`web.dev.command` name scripts present in the resolved cwd's
3218
+ * `package.json`. Presence is necessary but not sufficient — the script itself is never
3219
+ * executed by this check.
3220
+ *
3221
+ * @param input - The check input (host-scoped).
3222
+ * @returns The check result.
3223
+ * @example
3224
+ * ```ts
3225
+ * await run({ target: "host", fs, global, ... });
3226
+ * ```
3227
+ */
3228
+ async function run$1(input) {
3229
+ const cwd = resolveWebCwd(input.global);
3230
+ const packageJsonPath = node_path.default.join(cwd, "package.json");
3231
+ let raw;
3232
+ try {
3233
+ raw = await input.fs.readFile(packageJsonPath);
3234
+ } catch {
3235
+ return {
3236
+ id: "web-script",
3237
+ target: "host",
3238
+ status: "fail",
3239
+ message: `[native] could not read ${packageJsonPath} (resolved web.cwd).`,
3240
+ fixIt: "set config.web.cwd to your frontend project root"
3241
+ };
3242
+ }
3243
+ let scripts;
3244
+ try {
3245
+ scripts = JSON.parse(raw).scripts ?? {};
3246
+ } catch {
3247
+ return {
3248
+ id: "web-script",
3249
+ target: "host",
3250
+ status: "fail",
3251
+ message: `[native] ${packageJsonPath} is not valid JSON.`,
3252
+ fixIt: `fix ${packageJsonPath}`
3253
+ };
3254
+ }
3255
+ const buildScript = extractScriptName(input.global.web.build);
3256
+ const devScript = extractScriptName(input.global.web.dev.command);
3257
+ const missing = [];
3258
+ if (!buildScript || !(buildScript in scripts)) missing.push(`web.build ("${input.global.web.build}")`);
3259
+ if (!devScript || !(devScript in scripts)) missing.push(`web.dev.command ("${input.global.web.dev.command}")`);
3260
+ if (missing.length > 0) return {
3261
+ id: "web-script",
3262
+ target: "host",
3263
+ status: "fail",
3264
+ message: `[native] script(s) not found in ${packageJsonPath}: ${missing.join(", ")}. Presence is necessary but not sufficient — this does not run the script.`,
3265
+ fixIt: `add the missing script(s) to ${packageJsonPath}, or update config.web to match existing scripts`
3266
+ };
3267
+ return {
3268
+ id: "web-script",
3269
+ target: "host",
3270
+ status: "pass",
3271
+ message: `[native] web.build/web.dev.command scripts resolved in ${packageJsonPath} (not executed).`
3272
+ };
3273
+ }
3274
+ /** web.build/web.dev.command script presence — resolved from Tauri's own cwd. */
3275
+ const webScriptCheck = {
3276
+ id: "web-script",
3277
+ /**
3278
+ * Whether this check applies — host-scoped only (one web build, not per target).
3279
+ *
3280
+ * @param target - The candidate scope.
3281
+ * @returns Whether `web-script` applies to `target`.
3282
+ * @example
3283
+ * ```ts
3284
+ * webScriptCheck.appliesTo("host", global); // true
3285
+ * ```
3286
+ */
3287
+ appliesTo: (target) => target === "host",
3288
+ run: run$1
3289
+ };
3290
+ //#endregion
3291
+ //#region src/plugins/doctor/checks/xcode.ts
3292
+ /**
3293
+ * @file doctor plugin check — Xcode + xcodebuild + queryable simulators (ios; macOS host only).
3294
+ */
3295
+ /**
3296
+ * Confirms Xcode's command-line tools are present and iOS simulators are queryable.
3297
+ *
3298
+ * @param input - The check input, scoped to the "ios" target.
3299
+ * @returns The check result.
3300
+ * @example
3301
+ * ```ts
3302
+ * await run({ target: "ios", probe, ... });
3303
+ * ```
3304
+ */
3305
+ async function run(input) {
3306
+ if ((await input.probe("xcodebuild", ["-version"])).code !== 0) return {
3307
+ id: "xcode-toolchain",
3308
+ target: "ios",
3309
+ status: "fail",
3310
+ message: "[native] Xcode / xcodebuild was not found.",
3311
+ fixIt: "install Xcode from the App Store, then run `xcode-select --install`"
3312
+ };
3313
+ if ((await input.probe("xcrun", [
3314
+ "simctl",
3315
+ "list",
3316
+ "devices"
3317
+ ])).code !== 0) return {
3318
+ id: "xcode-toolchain",
3319
+ target: "ios",
3320
+ status: "fail",
3321
+ message: "[native] Xcode is installed but iOS simulators are not queryable.",
3322
+ fixIt: "open Xcode once to finish installing simulator runtimes"
3323
+ };
3324
+ return {
3325
+ id: "xcode-toolchain",
3326
+ target: "ios",
3327
+ status: "pass",
3328
+ message: "[native] Xcode / xcodebuild is present and simulators are queryable."
3329
+ };
3330
+ }
3331
+ //#endregion
3332
+ //#region src/plugins/doctor/checks/index.ts
3333
+ /**
3334
+ * @file doctor plugin — checks/ registry barrel: every Check the doctor API iterates over
3335
+ * (the providers pattern, spec/15 §1).
3336
+ */
3337
+ /**
3338
+ * Every registered check, in a stable order (drives report/emission order when multiple
3339
+ * checks apply to the same scope). One module per concern, added here and nowhere else.
3340
+ */
3341
+ const CHECKS = [
3342
+ nodeCheck,
3343
+ tauriCliCheck,
3344
+ rustupCheck,
3345
+ {
3346
+ id: "xcode-toolchain",
3347
+ /**
3348
+ * Whether this check applies — ios only, and only on a macOS host.
3349
+ *
3350
+ * @param target - The candidate scope.
3351
+ * @returns Whether `xcode-toolchain` applies to `target`.
3352
+ * @example
3353
+ * ```ts
3354
+ * xcodeCheck.appliesTo("ios", global); // true on a macOS host
3355
+ * ```
3356
+ */
3357
+ appliesTo: (target) => target === "ios" && node_process.default.platform === "darwin",
3358
+ run
3359
+ },
3360
+ androidCheck,
3361
+ signingCheck,
3362
+ completenessCheck,
3363
+ versionsCheck,
3364
+ webScriptCheck,
3365
+ crossRepoCorsCheck,
3366
+ crossRepoDeepLinkCheck
3367
+ ];
3368
+ //#endregion
3369
+ //#region src/plugins/doctor/report.ts
3370
+ /**
3371
+ * Converts one `Promise.allSettled` outcome into a `CheckResult`, mapping a genuine
3372
+ * rejection (a check that threw instead of resolving with a status) into a synthetic
3373
+ * "fail" result — so a single broken check can never sink the whole report.
3374
+ *
3375
+ * @param outcome - The settled outcome for one check run.
3376
+ * @param fallback - The id/target to attach when the check rejected (it never produced its own result).
3377
+ * @param fallback.id - The check's stable id.
3378
+ * @param fallback.target - The scope (a real target, or "host") the check ran against.
3379
+ * @returns The check's real result, or a synthetic internal-error "fail" result.
3380
+ * @example
3381
+ * ```ts
3382
+ * const [outcome] = await Promise.allSettled([check.run(input)]);
3383
+ * toCheckResult(outcome, { id: check.id, target: "host" });
3384
+ * ```
3385
+ */
3386
+ function toCheckResult(outcome, fallback) {
3387
+ if (outcome.status === "fulfilled") return outcome.value;
3388
+ const detail = outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason);
3389
+ return {
3390
+ id: fallback.id,
3391
+ target: fallback.target,
3392
+ status: "fail",
3393
+ message: `[native] doctor check "${fallback.id}" failed internally: ${detail}.`
3394
+ };
3395
+ }
3396
+ /**
3397
+ * Assembles the final report from every completed check result. A `"warn"` status
3398
+ * never flips `ok`; any `"fail"` status does.
3399
+ *
3400
+ * @param checks - Every completed check result, in emission order.
3401
+ * @returns The aggregated report.
3402
+ * @example
3403
+ * ```ts
3404
+ * assembleReport([{ id: "node-binary", target: "host", status: "pass", message: "node v22.1.0" }]);
3405
+ * ```
3406
+ */
3407
+ function assembleReport(checks) {
3408
+ return {
3409
+ ok: checks.every((result) => result.status !== "fail"),
3410
+ checks
3411
+ };
3412
+ }
3413
+ //#endregion
3414
+ //#region src/plugins/doctor/api.ts
3415
+ /**
3416
+ * @file doctor plugin — API factory: builds fresh CheckInput per (check, scope), runs every
3417
+ * applicable check in parallel (Promise.allSettled), emits doctor:check per completed result.
3418
+ */
3419
+ /**
3420
+ * Real (non-injected) probe seam — spawns the binary and merges stdout+stderr into one
3421
+ * buffer (presence/version parsing never needs them separated).
3422
+ *
3423
+ * @param cmd - Binary to spawn.
3424
+ * @param args - Arguments to pass.
3425
+ * @returns The exit code and merged output.
3426
+ * @example
3427
+ * ```ts
3428
+ * await realProbe("node", ["--version"]);
3429
+ * ```
3430
+ */
3431
+ const realProbe = (cmd, args) => new Promise((resolve) => {
3432
+ const child = (0, node_child_process.spawn)(cmd, args, { stdio: [
3433
+ "ignore",
3434
+ "pipe",
3435
+ "pipe"
3436
+ ] });
3437
+ let output = "";
3438
+ child.stdout?.on("data", (chunk) => {
3439
+ output += chunk.toString();
3440
+ });
3441
+ child.stderr?.on("data", (chunk) => {
3442
+ output += chunk.toString();
3443
+ });
3444
+ child.on("error", () => resolve({
3445
+ code: 1,
3446
+ stdout: output
3447
+ }));
3448
+ child.on("close", (code) => resolve({
3449
+ code: code ?? 1,
3450
+ stdout: output
3451
+ }));
3452
+ });
3453
+ /** Real (non-injected) fs facade — UTF-8 text reads only (every check only reads package.json). */
3454
+ const realFs = {
3455
+ /**
3456
+ * Reads a file as UTF-8 text.
3457
+ *
3458
+ * @param path - Absolute or relative file path.
3459
+ * @returns The file's text content.
3460
+ * @example
3461
+ * ```ts
3462
+ * await realFs.readFile("/repo/package.json");
3463
+ * ```
3464
+ */
3465
+ readFile: (path) => (0, node_fs_promises.readFile)(path, "utf8") };
3466
+ /**
3467
+ * Creates the doctor API — parallel check registry (Promise.allSettled), emits doctor:check per result.
3468
+ *
3469
+ * @param ctx - Plugin context (require project/tauri — D-007; emit doctor:check; probe seam config).
3470
+ * @returns The `doctor` plugin's public API.
3471
+ * @example
3472
+ * ```ts
3473
+ * const api = createDoctorApi(ctx);
3474
+ * const report = await api.run({ target: "ios" });
3475
+ * ```
3476
+ */
3477
+ function createDoctorApi(ctx) {
3478
+ const project = ctx.require(projectPlugin);
3479
+ const tauri = ctx.require(tauriPlugin);
3480
+ const probe = ctx.config.probeImpl ?? realProbe;
3481
+ /**
3482
+ * Builds fresh `CheckInput` for one `(check, scope)` pair and runs it.
3483
+ *
3484
+ * @param check - The check to run.
3485
+ * @param scope - The real packaging target, or "host" for host-scoped checks.
3486
+ * @returns The completed check result (rejects if the check itself throws).
3487
+ * @example
3488
+ * ```ts
3489
+ * await runCheck(nodeCheck, "host");
3490
+ * ```
3491
+ */
3492
+ const runCheck = (check, scope) => {
3493
+ const input = {
3494
+ target: scope,
3495
+ global: ctx.global,
3496
+ probe,
3497
+ fs: realFs,
3498
+ env: ctx.env,
3499
+ project: {
3500
+ requiredFiles: project.requiredFiles,
3501
+ completeness: project.completeness,
3502
+ registryRows: project.registryRows
3503
+ },
3504
+ tauri: { version: tauri.version }
3505
+ };
3506
+ return check.run(input);
3507
+ };
3508
+ return {
3509
+ /**
3510
+ * Runs every check applicable to `opts.target` (or every configured target + host
3511
+ * checks when omitted), in parallel via `Promise.allSettled`. Never throws on check
3512
+ * failures — a rejected check becomes an internal-error "fail" result instead;
3513
+ * `run()` only throws on a genuine internal bug in this orchestration itself.
3514
+ *
3515
+ * @param opts - Optional scoping.
3516
+ * @param opts.target - A single real packaging target to diagnose, or every configured
3517
+ * target + host checks when omitted.
3518
+ * @returns The aggregated report.
3519
+ * @example
3520
+ * ```ts
3521
+ * const report = await app.doctor.run({ target: "ios" });
3522
+ * if (!report.ok) process.exitCode = 1;
3523
+ * ```
3524
+ */
3525
+ async run(opts) {
3526
+ const scopes = opts?.target ? [opts.target] : [...ctx.global.targets, "host"];
3527
+ const scheduled = [];
3528
+ for (const scope of scopes) for (const check of CHECKS) if (check.appliesTo(scope, ctx.global)) scheduled.push({
3529
+ check,
3530
+ scope
3531
+ });
3532
+ const results = (await Promise.allSettled(scheduled.map((entry) => runCheck(entry.check, entry.scope)))).map((outcome, index) => {
3533
+ const entry = scheduled[index];
3534
+ const result = toCheckResult(outcome, {
3535
+ id: entry?.check.id ?? "unknown",
3536
+ target: entry?.scope ?? "host"
3537
+ });
3538
+ ctx.emit("doctor:check", result);
3539
+ return result;
3540
+ });
3541
+ const report = assembleReport(results);
3542
+ ctx.log.info("doctor:run", {
3543
+ ok: report.ok,
3544
+ checkCount: results.length
3545
+ });
3546
+ return report;
3547
+ } };
3548
+ }
3549
+ /**
3550
+ * Complex tier — per-target toolchain/completeness/version-skew diagnosis via a checks/ registry.
3551
+ * Emits `doctor:check` per completed check (cli renders these live).
3552
+ *
3553
+ * @see README.md
3554
+ * @example
3555
+ * ```ts
3556
+ * const app = createApp({ plugins: [projectPlugin, tauriPlugin, doctorPlugin] });
3557
+ * ```
3558
+ */
3559
+ const doctorPlugin = createPlugin$1("doctor", {
3560
+ depends: [projectPlugin, tauriPlugin],
3561
+ config: { probeImpl: void 0 },
3562
+ events: (register) => ({ "doctor:check": register("A diagnosis check completed (cli renders these live)") }),
3563
+ /**
3564
+ * Wires the real plugin context into `createDoctorApi` (not a direct factory reference —
3565
+ * `DoctorContext`'s narrow `emit`/`require` types need this call's own contextual
3566
+ * inference to correctly merge this plugin's declared `events` into its own ctx type).
3567
+ *
3568
+ * @param ctx - The real plugin context (global/config/log/env/emit/require).
3569
+ * @returns The `doctor` plugin's public API.
3570
+ * @example
3571
+ * ```ts
3572
+ * api: ctx => createDoctorApi(ctx)
3573
+ * ```
3574
+ */
3575
+ api: (ctx) => createDoctorApi(ctx)
3576
+ });
3577
+ //#endregion
3578
+ //#region src/plugins/cli/render.ts
3579
+ /**
3580
+ * Creates the branded console bound to the injected render seam. When `renderImpl` is
3581
+ * provided every line flows through it (both the normal and error sinks) instead of the
3582
+ * branded kit's own `console.log`/`console.error` default — the seam tests inject to
3583
+ * capture output deterministically and assert zero raw `console.*` calls (MC1).
3584
+ *
3585
+ * @param renderImpl - Injected line sink (default: undefined → branded console default).
3586
+ * @returns A branded console writing every line through the render seam.
3587
+ * @example
3588
+ * ```ts
3589
+ * const ui = createRenderConsole(ctx.config.renderImpl);
3590
+ * ui.info("ready");
3591
+ * ```
3592
+ */
3593
+ function createRenderConsole(renderImpl) {
3594
+ return renderImpl ? (0, _moku_labs_common_cli.createBrandConsole)({
3595
+ write: renderImpl,
3596
+ writeError: renderImpl
3597
+ }) : (0, _moku_labs_common_cli.createBrandConsole)();
3598
+ }
3599
+ /**
3600
+ * Resolves the confirm seam: the injected `confirmImpl`, or a styled y/N prompt from the
3601
+ * branded kit.
3602
+ *
3603
+ * @param confirmImpl - Injected confirm seam (default: undefined → branded prompt).
3604
+ * @returns The resolved confirm function.
3605
+ * @example
3606
+ * ```ts
3607
+ * const confirm = resolveConfirm(ctx.config.confirmImpl);
3608
+ * await confirm("Wipe the project directory?");
3609
+ * ```
3610
+ */
3611
+ function resolveConfirm(confirmImpl) {
3612
+ return confirmImpl ?? ((question) => (0, _moku_labs_common_cli.createBrandPrompts)().confirm(question));
3613
+ }
3614
+ /**
3615
+ * Renders one `native:phase` status line: a spinner line on `start`, a detail line on
3616
+ * `progress` (real ticks only — silent when `detail` is absent), and a pass/fail
3617
+ * diagnostic line with duration on `done`/`error`. The v1 icons no-op (D-015) renders as an
3618
+ * ordinary `done` line whose detail happens to read `"skipped"`.
3619
+ *
3620
+ * @param ui - The branded console to render through.
3621
+ * @param payload - The phase event payload.
3622
+ * @param elapsedMs - Milliseconds since the phase started (drives the spinner frame).
3623
+ * @example
3624
+ * ```ts
3625
+ * renderPhaseEvent(ui, { target: "macos", phase: "compile", status: "start" }, 0);
3626
+ * ```
3627
+ */
3628
+ function renderPhaseEvent(ui, payload, elapsedMs) {
3629
+ const label = `${payload.target} · ${payload.phase}`;
3630
+ if (payload.status === "start") {
3631
+ ui.line(` ${(0, _moku_labs_common_cli.spinnerFrameAt)(elapsedMs)} ${label}…`);
3632
+ return;
3633
+ }
3634
+ if (payload.status === "progress") {
3635
+ if (payload.detail) ui.line(` ${(0, _moku_labs_common_cli.spinnerFrameAt)(elapsedMs)} ${label} — ${payload.detail}`);
3636
+ return;
3637
+ }
3638
+ if (payload.status === "done") {
3639
+ const durationLabel = `${payload.durationMs ?? 0}ms`;
3640
+ ui.check(true, label, payload.detail ? `${payload.detail} (${durationLabel})` : durationLabel);
3641
+ return;
3642
+ }
3643
+ ui.check(false, label, payload.detail);
3644
+ }
3645
+ /**
3646
+ * Renders the `native:complete` summary panel — app name, target, artifact paths, and
3647
+ * total duration — as a branded box (`app.name` is the panel header, per config's
3648
+ * "Global fields consumed").
3649
+ *
3650
+ * @param ui - The branded console to render through.
3651
+ * @param payload - The completion event payload.
3652
+ * @param appName - The composed app's display name.
3653
+ * @example
3654
+ * ```ts
3655
+ * renderCompleteEvent(ui, { target: "macos", outPath: "dist-native/macos", artifacts: [], durationMs: 42000 }, "Demo");
3656
+ * ```
3657
+ */
3658
+ function renderCompleteEvent(ui, payload, appName) {
3659
+ const lines = [
3660
+ `${appName} — ${payload.target} build complete`,
3661
+ `Target ${payload.target}`,
3662
+ `Output ${payload.outPath}`,
3663
+ ...payload.artifacts.map((artifact) => `Artifact ${artifact}`),
3664
+ `Duration ${payload.durationMs}ms`
3665
+ ];
3666
+ ui.box(lines);
3667
+ }
3668
+ /**
3669
+ * Renders one live `doctor:check` row — pass/warn/fail symbol, message, and an indented
3670
+ * fix-it when present. `warn` gets its own dim `~` marker (never flips to fail styling);
3671
+ * `pass`/`fail` reuse the branded console's own `check` diagnostic line.
3672
+ *
3673
+ * @param ui - The branded console to render through.
3674
+ * @param result - The completed check result.
3675
+ * @example
3676
+ * ```ts
3677
+ * renderCheckEvent(ui, { id: "node-binary", target: "host", status: "pass", message: "node found" });
3678
+ * ```
3679
+ */
3680
+ function renderCheckEvent(ui, result) {
3681
+ const label = `${result.target} · ${result.id} — ${result.message}`;
3682
+ if (result.status === "warn") {
3683
+ ui.line(` ${ui.palette.yellow("~")} ${label}`);
3684
+ if (result.fixIt) ui.line(` ${ui.palette.dim(result.fixIt)}`);
3685
+ return;
3686
+ }
3687
+ ui.check(result.status === "pass", label, result.fixIt);
3688
+ }
3689
+ /**
3690
+ * Renders the final doctor summary once the full report has resolved: a heading, one row
3691
+ * per check (reusing {@link renderCheckEvent}), and an overall pass/fail line.
3692
+ *
3693
+ * @param ui - The branded console to render through.
3694
+ * @param report - The aggregated diagnosis report.
3695
+ * @example
3696
+ * ```ts
3697
+ * renderDoctorSummary(ui, await app.doctor.run());
3698
+ * ```
3699
+ */
3700
+ function renderDoctorSummary(ui, report) {
3701
+ ui.heading("Doctor summary");
3702
+ for (const result of report.checks) renderCheckEvent(ui, result);
3703
+ ui.line();
3704
+ ui.check(report.ok, report.ok ? "All checks passed" : "One or more checks failed");
3705
+ }
3706
+ //#endregion
3707
+ //#region src/plugins/cli/api.ts
3708
+ /**
3709
+ * @file cli plugin — API factory: typed verbs over project/tauri/build/doctor (D-007).
3710
+ */
3711
+ /** Host platforms this plugin can resolve to a default packaging target. */
3712
+ const HOST_TARGETS = {
3713
+ darwin: "macos",
3714
+ win32: "windows",
3715
+ linux: "linux"
3716
+ };
3717
+ /**
3718
+ * Resolves the default packaging target from the host platform (darwin→macos,
3719
+ * win32→windows, linux→linux). Mobile targets are never inferred — callers must pass
3720
+ * `{ target: "ios" | "android" }` explicitly.
3721
+ *
3722
+ * @param platform - `process.platform`-shaped value (injectable for cross-platform tests).
3723
+ * @returns The resolved host target.
3724
+ * @throws {Error} `[native]` when the host platform has no default target.
3725
+ * @example
3726
+ * ```ts
3727
+ * hostTarget(); // "macos" on darwin
3728
+ * ```
3729
+ */
3730
+ function hostTarget(platform = node_process.default.platform) {
3731
+ const target = HOST_TARGETS[platform];
3732
+ if (!target) throw new Error(`[native] No default packaging target for host platform "${platform}".\n Pass an explicit target, e.g. { target: "macos" }.`);
3733
+ return target;
3734
+ }
3735
+ /**
3736
+ * Creates the cli verb surface — build/dev/doctor/clean. All output flows through the
3737
+ * branded kit (MC1); build/doctor progress additionally renders live via this plugin's
3738
+ * `native:phase`/`native:complete`/`doctor:check` hooks (see `handlers.ts`).
3739
+ *
3740
+ * @param ctx - Plugin context (require project/tauri/build/doctor — D-007; render/confirm seams).
3741
+ * @returns The `cli` plugin's public API.
3742
+ * @example
3743
+ * ```ts
3744
+ * const api = createCliApi(ctx);
3745
+ * await api.build({ target: "macos" });
3746
+ * ```
3747
+ */
3748
+ function createCliApi(ctx) {
3749
+ const project = ctx.require(projectPlugin);
3750
+ const tauri = ctx.require(tauriPlugin);
3751
+ const build = ctx.require(buildPlugin);
3752
+ const doctor = ctx.require(doctorPlugin);
3753
+ const ui = createRenderConsole(ctx.config.renderImpl);
3754
+ const confirm = resolveConfirm(ctx.config.confirmImpl);
3755
+ /**
3756
+ * Forwards one scrubbed dev-process output line to the render seam (D-014: the scrubbed
3757
+ * render seam tauri's `dev()` exposes specifically for cli).
3758
+ *
3759
+ * @param line - A single scrubbed output line.
3760
+ * @example
3761
+ * ```ts
3762
+ * forwardDevOutput("Local: http://localhost:5173/");
3763
+ * ```
3764
+ */
3765
+ function forwardDevOutput(line) {
3766
+ ui.line(line);
3767
+ }
3768
+ return {
3769
+ /**
3770
+ * Builds one target (default: the host target) or every configured target with
3771
+ * `{ all: true }` (which ignores any given `target`). Progress renders live through
3772
+ * the plugin's `native:phase`/`native:complete` hooks.
3773
+ *
3774
+ * @param opts - Build options.
3775
+ * @param opts.target - The packaging target (default: the resolved host target).
3776
+ * @param opts.all - Build every configured target instead of one (ignores `target`).
3777
+ * @returns Resolves once the build (or all builds) complete.
3778
+ * @example
3779
+ * ```ts
3780
+ * await app.cli.build({ target: "macos" });
3781
+ * await app.cli.build({ all: true });
3782
+ * ```
3783
+ */
3784
+ async build(opts = {}) {
3785
+ if (opts.all) {
3786
+ await build.runAll();
3787
+ return;
3788
+ }
3789
+ await build.run({ target: opts.target ?? hostTarget() });
3790
+ },
3791
+ /**
3792
+ * Runs the dev loop. Awaits the tauri dev handle's `ready` then `exited` — it NEVER
3793
+ * stores the handle and NEVER calls `stop()` itself (D-002); teardown is owned entirely
3794
+ * by the tauri seam's own control flow (signal handlers, process-group kill).
3795
+ *
3796
+ * @param opts - Dev options.
3797
+ * @param opts.target - Optional packaging target (desktop-uniform when omitted).
3798
+ * @returns Resolves once the dev session exits cleanly.
3799
+ * @throws {Error} `[native]` when the dev session exits with a non-zero code.
3800
+ * @example
3801
+ * ```ts
3802
+ * await app.cli.dev({ target: "ios" });
3803
+ * ```
3804
+ */
3805
+ async dev(opts = {}) {
3806
+ const handle = await tauri.dev({
3807
+ ...opts.target ? { target: opts.target } : {},
3808
+ onOutput: forwardDevOutput
3809
+ });
3810
+ await handle.ready;
3811
+ const exit = await handle.exited;
3812
+ if (typeof exit.code === "number" && exit.code !== 0) throw new Error(`[native] tauri dev exited with code ${exit.code}.\n Check the rendered output above for the underlying error.`);
3813
+ },
3814
+ /**
3815
+ * Runs diagnosis, renders the summary table (plus fix-its), and returns whether every
3816
+ * check passed. Live `doctor:check` rows render as they complete via this plugin's
3817
+ * `doctor:check` hook; this method renders only the final summary.
3818
+ *
3819
+ * @param opts - Optional scoping.
3820
+ * @param opts.target - A single target to diagnose (default: every configured target + host).
3821
+ * @returns Whether the report is `ok` (no failing check) — the caller sets `process.exitCode`.
3822
+ * @example
3823
+ * ```ts
3824
+ * if (!(await app.cli.doctor())) process.exitCode = 1;
3825
+ * ```
3826
+ */
3827
+ async doctor(opts = {}) {
3828
+ const report = await doctor.run(opts.target ? { target: opts.target } : {});
3829
+ renderDoctorSummary(ui, report);
3830
+ return report.ok;
3831
+ },
3832
+ /**
3833
+ * Cleans derived state. Without a `target`, this wipes the ENTIRE project directory —
3834
+ * gated behind a styled confirm — before delegating to `project.clean` (D-006: project
3835
+ * owns the destructive filesystem knowledge, cli is a thin delegate).
3836
+ *
3837
+ * @param opts - Clean options.
3838
+ * @param opts.target - A single target to clean (default: confirm, then wipe everything).
3839
+ * @returns Resolves once cleaning completes (or immediately, if the user declines).
3840
+ * @example
3841
+ * ```ts
3842
+ * await app.cli.clean({ target: "android" });
3843
+ * ```
3844
+ */
3845
+ async clean(opts = {}) {
3846
+ if (!opts.target) {
3847
+ if (!await confirm(`Delete the entire native project directory (${ctx.global.projectDir})? This removes every target's generated state.`)) return;
3848
+ }
3849
+ await project.clean(opts.target ? { target: opts.target } : {});
3850
+ }
3851
+ };
3852
+ }
3853
+ //#endregion
3854
+ //#region src/plugins/cli/handlers.ts
3855
+ /**
3856
+ * Creates the cli hook map. Each handler renders through one branded console bound to the
3857
+ * configured render seam, and `native:phase` additionally maintains
3858
+ * `ctx.state.progress` — the live phase/spinner-tick/start-time bookkeeping for the
3859
+ * CURRENT verb invocation — across each phase's start → progress → done/error cycle.
3860
+ *
3861
+ * @param ctx - Plugin context (state bookkeeping, render seam via config).
3862
+ * @returns The hook map wired onto the cli plugin.
3863
+ * @example
3864
+ * ```ts
3865
+ * hooks: ctx => createCliHandlers(ctx)
3866
+ * ```
3867
+ */
3868
+ function createCliHandlers(ctx) {
3869
+ const ui = createRenderConsole(ctx.config.renderImpl);
3870
+ return {
3871
+ /**
3872
+ * Handles one `native:phase` event: updates `ctx.state.progress` bookkeeping across
3873
+ * the start → progress → done/error cycle, then renders the corresponding status line.
3874
+ *
3875
+ * @param payload - The phase event payload.
3876
+ * @example
3877
+ * ```ts
3878
+ * handlers["native:phase"]({ target: "macos", phase: "compile", status: "start" });
3879
+ * ```
3880
+ */
3881
+ "native:phase"(payload) {
3882
+ if (payload.status === "start") ctx.state.progress = {
3883
+ phase: payload.phase,
3884
+ startedAt: Date.now(),
3885
+ ticks: 0
3886
+ };
3887
+ else if (payload.status === "progress") ctx.state.progress = {
3888
+ ...ctx.state.progress,
3889
+ ticks: ctx.state.progress.ticks + 1
3890
+ };
3891
+ const elapsedMs = ctx.state.progress.startedAt ? Date.now() - ctx.state.progress.startedAt : 0;
3892
+ renderPhaseEvent(ui, payload, elapsedMs);
3893
+ if (payload.status === "done" || payload.status === "error") ctx.state.progress = {
3894
+ phase: void 0,
3895
+ startedAt: void 0,
3896
+ ticks: 0
3897
+ };
3898
+ },
3899
+ /**
3900
+ * Handles one `native:complete` event: renders the completion summary panel.
3901
+ *
3902
+ * @param payload - The completion event payload.
3903
+ * @example
3904
+ * ```ts
3905
+ * handlers["native:complete"]({ target: "macos", outPath: "dist-native/macos", artifacts: [], durationMs: 1 });
3906
+ * ```
3907
+ */
3908
+ "native:complete"(payload) {
3909
+ renderCompleteEvent(ui, payload, ctx.global.app.name);
3910
+ },
3911
+ /**
3912
+ * Handles one `doctor:check` event: renders the live pass/warn/fail row.
3913
+ *
3914
+ * @param payload - The completed check result.
3915
+ * @example
3916
+ * ```ts
3917
+ * handlers["doctor:check"]({ id: "node-binary", target: "host", status: "pass", message: "ok" });
3918
+ * ```
3919
+ */
3920
+ "doctor:check"(payload) {
3921
+ renderCheckEvent(ui, payload);
3922
+ }
3923
+ };
3924
+ }
3925
+ //#endregion
3926
+ //#region src/plugins/cli/state.ts
3927
+ /**
3928
+ * Creates initial cli render-progress state.
3929
+ *
3930
+ * @returns Fresh progress bookkeeping with no active phase.
3931
+ * @example
3932
+ * ```ts
3933
+ * const state = createCliState();
3934
+ * ```
3935
+ */
3936
+ function createCliState() {
3937
+ return { progress: {
3938
+ phase: void 0,
3939
+ startedAt: void 0,
3940
+ ticks: 0
3941
+ } };
3942
+ }
3943
+ /**
3944
+ * Standard tier — typed verb surface (build/dev/doctor/clean), branded rendering (MC1),
3945
+ * live progress via hooks. dev() awaits tauri's DevHandle but never holds it (D-002).
3946
+ * `api`/`hooks` use the wrapper-call form (not a bare factory reference) so this call's
3947
+ * own contextual inference merges the doctor depends edge's `doctor:check` event into ctx
3948
+ * (mirrors doctor/index.ts's `api: ctx => createDoctorApi(ctx)` precedent).
3949
+ *
3950
+ * @see README.md
3951
+ * @example
3952
+ * ```ts
3953
+ * const app = createApp({ plugins: [projectPlugin, tauriPlugin, buildPlugin, doctorPlugin, cliPlugin] });
3954
+ * ```
3955
+ */
3956
+ const cliPlugin = createPlugin$1("cli", {
3957
+ depends: [
3958
+ projectPlugin,
3959
+ tauriPlugin,
3960
+ buildPlugin,
3961
+ doctorPlugin
3962
+ ],
3963
+ config: {
3964
+ renderImpl: void 0,
3965
+ confirmImpl: void 0
3966
+ },
3967
+ createState: createCliState,
3968
+ /**
3969
+ * Wires the real plugin context into `createCliApi` (wrapper form — see the plugin
3970
+ * JSDoc above).
3971
+ *
3972
+ * @param ctx - The real plugin context (global/config/state/require).
3973
+ * @returns The `cli` plugin's public API.
3974
+ * @example
3975
+ * ```ts
3976
+ * api: ctx => createCliApi(ctx)
3977
+ * ```
3978
+ */
3979
+ api: (ctx) => createCliApi(ctx),
3980
+ /**
3981
+ * Wires the real plugin context into `createCliHandlers` (wrapper form — see the plugin
3982
+ * JSDoc above).
3983
+ *
3984
+ * @param ctx - The real plugin context (global/config/state).
3985
+ * @returns The `cli` plugin's hook map.
3986
+ * @example
3987
+ * ```ts
3988
+ * hooks: ctx => createCliHandlers(ctx)
3989
+ * ```
3990
+ */
3991
+ hooks: (ctx) => createCliHandlers(ctx)
3992
+ });
3993
+ //#endregion
3994
+ //#region src/plugins/build/types.ts
3995
+ var types_exports = /* @__PURE__ */ __exportAll({});
3996
+ //#endregion
3997
+ //#region src/plugins/cli/types.ts
3998
+ var types_exports$1 = /* @__PURE__ */ __exportAll({});
3999
+ //#endregion
4000
+ //#region src/plugins/doctor/types.ts
4001
+ var types_exports$2 = /* @__PURE__ */ __exportAll({});
4002
+ //#endregion
4003
+ //#region src/plugins/project/types.ts
4004
+ var types_exports$3 = /* @__PURE__ */ __exportAll({});
4005
+ //#endregion
4006
+ //#region src/index.ts
4007
+ /**
4008
+ * @file `@moku-labs/native` — node-only native packager framework for Moku (Tauri 2).
4009
+ */
4010
+ const framework = createCore(coreConfig, {
4011
+ plugins: [
4012
+ projectPlugin,
4013
+ tauriPlugin,
4014
+ buildPlugin,
4015
+ doctorPlugin,
4016
+ cliPlugin
4017
+ ],
4018
+ pluginConfigs: {
4019
+ /**
4020
+ * tauri — the `@tauri-apps/cli` subprocess seam.
4021
+ * - `spawnImpl`: injectable spawn for tests; `undefined` → real detached process-group spawn.
4022
+ * - `nodePath`: explicit `node` binary path; `undefined` → PATH-walk resolution (never
4023
+ * `process.execPath`, which is bun here).
4024
+ * - `readiness`: `tauri.dev()`'s devUrl poll cadence — no stdout "ready" marker exists
4025
+ * (tauri#4740), so polling is the only readiness signal.
4026
+ *
4027
+ * @example
4028
+ * ```ts
4029
+ * createApp({ pluginConfigs: { tauri: { readiness: { intervalMs: 100, timeoutMs: 30_000 } } } });
4030
+ * ```
4031
+ */
4032
+ tauri: {
4033
+ spawnImpl: void 0,
4034
+ nodePath: void 0,
4035
+ readiness: {
4036
+ intervalMs: 250,
4037
+ timeoutMs: 6e4
4038
+ }
4039
+ },
4040
+ /**
4041
+ * doctor — the diagnosis probe seam.
4042
+ * - `probeImpl`: injectable probe runner for tests; `undefined` → real `which`/`--version`
4043
+ * subprocess probes. The one tauri-CLI probe goes through `tauri.version()` instead
4044
+ * (subprocess-seam ownership stays with the tauri plugin — D-013).
4045
+ *
4046
+ * @example
4047
+ * ```ts
4048
+ * createApp({ pluginConfigs: { doctor: { probeImpl: fakeProbe } } });
4049
+ * ```
4050
+ */
4051
+ doctor: { probeImpl: void 0 },
4052
+ /**
4053
+ * cli — the branded-output render/confirm seams (MC1).
4054
+ * - `renderImpl`: injectable render sink for tests; `undefined` → branded console
4055
+ * (`@moku-labs/common/cli` `createBrandConsole`).
4056
+ * - `confirmImpl`: injectable confirm for tests; `undefined` → styled branded confirm
4057
+ * (gates `cli.clean()` without a target — full projectDir wipe).
4058
+ *
4059
+ * @example
4060
+ * ```ts
4061
+ * createApp({ pluginConfigs: { cli: { renderImpl: line => lines.push(line) } } });
4062
+ * ```
4063
+ */
4064
+ cli: {
4065
+ renderImpl: void 0,
4066
+ confirmImpl: void 0
4067
+ }
4068
+ }
4069
+ });
4070
+ /**
4071
+ * Creates a native consumer app (Layer 3) from this framework.
4072
+ *
4073
+ * @example
4074
+ * ```ts
4075
+ * export const native = createApp({ config: { app: { name: "MyApp", identifier: "com.example.myapp" } } });
4076
+ * ```
4077
+ */
4078
+ const createApp = framework.createApp;
4079
+ /**
4080
+ * Creates a consumer-authored plugin bound to this framework's chain.
4081
+ *
4082
+ * @example
4083
+ * ```ts
4084
+ * const myPlugin = createPlugin("my", { api: () => ({}) });
4085
+ * ```
4086
+ */
4087
+ const createPlugin = framework.createPlugin;
4088
+ //#endregion
4089
+ Object.defineProperty(exports, "Build", {
4090
+ enumerable: true,
4091
+ get: function() {
4092
+ return types_exports;
4093
+ }
4094
+ });
4095
+ Object.defineProperty(exports, "Cli", {
4096
+ enumerable: true,
4097
+ get: function() {
4098
+ return types_exports$1;
4099
+ }
4100
+ });
4101
+ Object.defineProperty(exports, "Doctor", {
4102
+ enumerable: true,
4103
+ get: function() {
4104
+ return types_exports$2;
4105
+ }
4106
+ });
4107
+ exports.PHASE_ORDER = PHASE_ORDER;
4108
+ Object.defineProperty(exports, "Project", {
4109
+ enumerable: true,
4110
+ get: function() {
4111
+ return types_exports$3;
4112
+ }
4113
+ });
4114
+ exports.TARGETS = TARGETS;
4115
+ Object.defineProperty(exports, "Tauri", {
4116
+ enumerable: true,
4117
+ get: function() {
4118
+ return types_exports$4;
4119
+ }
4120
+ });
4121
+ exports.buildPlugin = buildPlugin;
4122
+ exports.cliPlugin = cliPlugin;
4123
+ exports.createApp = createApp;
4124
+ exports.createPlugin = createPlugin;
4125
+ exports.doctorPlugin = doctorPlugin;
4126
+ exports.projectPlugin = projectPlugin;
4127
+ exports.tauriPlugin = tauriPlugin;