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