@rightkit/release 0.6.39 → 0.6.42

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.
Files changed (86) hide show
  1. package/README.md +110 -11
  2. package/admission-files.mjs +40 -0
  3. package/admission-host.mjs +2 -1
  4. package/app-check.mjs +303 -16
  5. package/app-closure.mjs +6 -4
  6. package/bin/rightkit-gate.mjs +177 -32
  7. package/cargo-contract.mjs +17 -31
  8. package/cargo-license-notices.mjs +129 -19
  9. package/cargo-target-shim.mjs +14 -0
  10. package/carried-cargo.mjs +2 -4
  11. package/cli/right-release.mjs +24 -2
  12. package/cross-targets.mjs +24 -0
  13. package/deterministic-scans.mjs +167 -58
  14. package/development-signing.mjs +25 -2
  15. package/development.mjs +34 -1
  16. package/direct-release-command.mjs +154 -0
  17. package/disk-policy.mjs +16 -0
  18. package/feature-coverage.mjs +134 -0
  19. package/gate-coverage.mjs +38 -0
  20. package/gate-stages.mjs +1 -0
  21. package/ghsa-audit.mjs +95 -0
  22. package/install-app.mjs +33 -5
  23. package/install-channels.mjs +301 -0
  24. package/interactive-session-run.mjs +105 -0
  25. package/legal-contract.mjs +10 -1
  26. package/legion-freeze-consumer.mjs +241 -0
  27. package/linux-publish.mjs +136 -0
  28. package/local-publish.mjs +31 -7
  29. package/nsis-pack.mjs +95 -0
  30. package/nsis-upgrade-template.mjs +93 -0
  31. package/outdated-command.mjs +19 -0
  32. package/ownership-class-rules.mjs +32 -10
  33. package/ownership-mandatory-set.json +23 -0
  34. package/ownership-mandatory-set.mjs +66 -8
  35. package/package-recipe-targets.mjs +54 -19
  36. package/package.json +1 -1
  37. package/payload-root-install.mjs +123 -0
  38. package/plugin-delivery.mjs +141 -0
  39. package/prebuild-gates.mjs +8 -4
  40. package/preflight.mjs +6 -1
  41. package/provision-model-bundle.mjs +172 -0
  42. package/pub-upload.mjs +1 -1
  43. package/publish-local-npm.mjs +34 -9
  44. package/publish-retention.mjs +106 -0
  45. package/publish-update.mjs +15 -8
  46. package/qa-build-features.mjs +24 -15
  47. package/qa-contract.mjs +5 -6
  48. package/qa-control-scan.mjs +14 -0
  49. package/qa-web-pairing.mjs +76 -0
  50. package/r2-s3-multipart.mjs +190 -0
  51. package/r2-verified-upload.mjs +28 -16
  52. package/recipe-build.mjs +53 -3
  53. package/release-checks.mjs +53 -2
  54. package/release-config.mjs +8 -3
  55. package/release-invocation.mjs +12 -2
  56. package/release-pin-floor.mjs +44 -0
  57. package/release-qa-audit.mjs +18 -2
  58. package/release-qa-command.mjs +17 -1
  59. package/release-qa-policy.mjs +30 -3
  60. package/release-switch-cfg.mjs +271 -0
  61. package/release-switch-registry.json +60 -1
  62. package/release-switch-scan.mjs +398 -23
  63. package/release.mjs +97 -6
  64. package/render-views.mjs +141 -0
  65. package/rightkit-registry-resolver.mjs +1 -1
  66. package/rightkit-versions.json +568 -491
  67. package/runtime-artifact-manifest.mjs +9 -0
  68. package/runtime-manifest-refresh.mjs +88 -0
  69. package/rustright-stage.mjs +197 -0
  70. package/scan-digest.mjs +15 -9
  71. package/scan-tool-enrolment.mjs +1 -1
  72. package/security-policy.mjs +196 -0
  73. package/shell-contract.mjs +32 -0
  74. package/snapshot-broker.mjs +8 -1
  75. package/snapshot-check.mjs +58 -0
  76. package/snapshot-request.mjs +25 -2
  77. package/stage-commands.mjs +33 -4
  78. package/stage-ledger.mjs +6 -1
  79. package/stage-receipt.mjs +115 -0
  80. package/stage-sidecar.mjs +188 -17
  81. package/stage-xcframework.mjs +118 -0
  82. package/suite-api.generated.mjs +16 -1
  83. package/unit-gate.mjs +14 -2
  84. package/upload-large.mjs +4 -4
  85. package/upload-release.mjs +6 -0
  86. package/win-package-recipe.mjs +26 -4
@@ -36,18 +36,30 @@
36
36
  // "channel": "env", // env | argv | settings | preference | frontend
37
37
  // "anchor": "src/test_mode.rs:97", // where it is read (informational)
38
38
  // "compiledOut": "feature:test-mode", // required for S1-S4: feature:<name> | cfg:test |
39
- // // cfg:debug_assertions | swift:DEBUG (read exists only there)
39
+ // // cfg:debug_assertions | swift:<CONDITION> (every read sits inside
40
+ // // a matching `#if <CONDITION>` branch, checked; #1169)
41
+ // "releasePresence": { "mechanism": "scrub", "owner": "app", "anchor": "src/env.rs:54" }, // optional (S1-S4): the
42
+ // // name stays in release binaries only because release code scrubs,
43
+ // // clears or sets it; see `releasePresenceFindings` (#937)
40
44
  // "valueType": "bool", // required for S6: bool | int | enum
41
45
  // "userGesture": true, // required for S5: chosen by a user gesture
42
46
  // "note": "free text" } ],
43
- // "dynamicReads": [ { "file": "src/x.rs", "reason": "..." } ] // optional: files allowed a non-literal read
47
+ // "dynamicReads": [ { "file": "src/x.rs", "reason": "..." } ], // optional: files allowed a non-literal read
48
+ // "buildConstants": [ { "name": "CUTRIGHT_LICENSE_PUBLIC_KEY_HEX", "channel": "option_env", "buildTimeOnly": true } ]
49
+ // // optional: builder-supplied compile-time constants that stay in
50
+ // // release (`option_env!`/`env!`/`import.meta.env.VITE_*`), never read
51
+ // // at run time (#1009)
44
52
  // }
53
+ //
54
+ // Names the operating system or Cargo supply (`osProvided` and Cargo's own variables in the registry) are not selectors and
55
+ // need no entry (#1045).
45
56
  import { createHash } from "node:crypto";
46
57
  import { closeSync, existsSync, lstatSync, openSync, readFileSync, readSync, readdirSync } from "node:fs";
47
58
  import path from "node:path";
48
59
  import { spawnSync } from "./background-process.mjs";
49
60
  import { featuresInTokens, resolveCargoManifestPath, scriptTarget, tokenize } from "./qa-build-features.mjs";
50
- import { isNativeBinaryHeader } from "./qa-control-scan.mjs";
61
+ import { QA_CONTROL_MARKER, isNativeBinaryHeader } from "./qa-control-scan.mjs";
62
+ import { buildScriptRefs, cfgPredicateOf, rustCfgGatedRanges, rustFileGates, cfgImplies, swiftConditionEnclosed } from "./release-switch-cfg.mjs";
51
63
  import { nodeHostTriple } from "./stage-sidecar-command.mjs";
52
64
  import { WIN_PACKAGE_DEFAULT_TRIPLE } from "./win-package-recipe.mjs";
53
65
 
@@ -56,10 +68,18 @@ const CHUNK = 4 * 1024 * 1024;
56
68
  const FORBIDDEN_CLASSES = new Set(["S1", "S2", "S3", "S4"]);
57
69
  const CLASSES = new Set(["S1", "S2", "S3", "S4", "S5", "S6"]);
58
70
  const CHANNELS = new Set(["env", "argv", "settings", "preference", "frontend"]);
59
- // `swift:DEBUG`: the read sits inside `#if DEBUG`, which an Xcode Release configuration compiles out.
60
- const COMPILED_OUT = /^(feature:[A-Za-z0-9_-]+|cfg:test|cfg:debug_assertions|swift:DEBUG)$/;
71
+ // `swift:<CONDITION>`: the read sits inside `#if <CONDITION>`, a Swift compilation condition the Release build does not define
72
+ // (`DEBUG`, or the app's own, e.g. `PULSE_QA`); the source walk confirms the enclosure and the project's Release settings.
73
+ const COMPILED_OUT = /^(feature:[A-Za-z0-9_-]+|cfg:test|cfg:debug_assertions|swift:[A-Za-z_][A-Za-z0-9_]*)$/;
74
+ const SWIFT_COMPILED_OUT = /^swift:([A-Za-z_][A-Za-z0-9_]*)$/;
75
+ const PRESENCE_MECHANISMS = new Set(["scrub", "clear", "set"]);
76
+ const PRESENCE_OWNERS = new Set(["crate", "app"]);
77
+ const BUILD_CONSTANT_CHANNELS = new Set(["option_env", "env", "vite-define"]);
61
78
 
62
79
  export const REGISTRY = JSON.parse(readFileSync(new URL("./release-switch-registry.json", import.meta.url), "utf8"));
80
+ // The web QA define and its retired spellings are deny names in every native binary too (the web bundle has its own scan, qa-control-scan.mjs).
81
+ REGISTRY.denyNames = [...REGISTRY.denyNames, ...[REGISTRY.webQa.define, ...REGISTRY.webQa.retired].map((name) => ({ name, class: "S1" }))];
82
+ const OS_PROVIDED = new Set(REGISTRY.osProvided);
63
83
 
64
84
  // ---------------------------------------------------------------------------------------------------------------------
65
85
  // Layer 1: feature closure.
@@ -318,13 +338,40 @@ export function parseInventory(text, label = "switches.json") {
318
338
  if (!CHANNELS.has(entry.channel)) bad(`${where}: \`channel\` must be one of ${[...CHANNELS].join(", ")}`);
319
339
  if (FORBIDDEN_CLASSES.has(entry.class)) {
320
340
  if (typeof entry.compiledOut !== "string" || !COMPILED_OUT.test(entry.compiledOut)) {
321
- issues.push({ layer: "inventory", rule: "not-compiled-out", file: label, reason: `not-compiled-out: ${where} is class ${entry.class} and must declare \`compiledOut\` as feature:<name>, cfg:test, cfg:debug_assertions or swift:DEBUG (release builds may not contain it)` });
341
+ issues.push({ layer: "inventory", rule: "not-compiled-out", file: label, reason: `not-compiled-out: ${where} is class ${entry.class} and must declare \`compiledOut\` as feature:<name>, cfg:test, cfg:debug_assertions or swift:<CONDITION> (release builds may not contain it)` });
342
+ }
343
+ if (entry.releasePresence !== undefined) {
344
+ const presence = entry.releasePresence;
345
+ if (!presence || typeof presence !== "object" || Array.isArray(presence)) bad(`${where}: \`releasePresence\` must be { mechanism, owner, anchor }`);
346
+ else {
347
+ if (!PRESENCE_MECHANISMS.has(presence.mechanism)) bad(`${where}: releasePresence.mechanism must be one of ${[...PRESENCE_MECHANISMS].join(", ")}`);
348
+ if (!PRESENCE_OWNERS.has(presence.owner)) bad(`${where}: releasePresence.owner must be crate or app`);
349
+ if (presence.owner === "app" && !/^[^:\s][^:]*:[1-9][0-9]*$/.test(presence.anchor ?? "")) bad(`${where}: releasePresence.anchor must be <path>:<line> where release code scrubs, clears or sets the name (owner app)`);
350
+ if (SWIFT_COMPILED_OUT.test(entry.compiledOut ?? "")) bad(`${where}: releasePresence is proven for Rust cfg/feature enclosures only; a swift:<CONDITION> entry cannot carry it`);
351
+ }
322
352
  }
323
353
  } else if (entry.class === "S6") {
324
354
  if (!["bool", "int", "enum"].includes(entry.valueType)) bad(`${where}: class S6 needs a bounded \`valueType\` (bool, int or enum)`);
325
355
  } else if (entry.class === "S5") {
326
356
  if (entry.userGesture !== true) bad(`${where}: class S5 needs \`userGesture: true\` (chosen by a picker, saved preference or the user's own argument)`);
327
357
  }
358
+ if (entry.releasePresence !== undefined && !FORBIDDEN_CLASSES.has(entry.class)) bad(`${where}: releasePresence applies to S1-S4 entries only`);
359
+ }
360
+ if (doc.buildConstants !== undefined) {
361
+ if (!Array.isArray(doc.buildConstants)) bad("`buildConstants` must be an array");
362
+ else {
363
+ const denied = new Set(REGISTRY.denyNames.map((d) => d.name));
364
+ for (const constant of doc.buildConstants) {
365
+ const where = `build constant \`${constant?.name}\``;
366
+ if (typeof constant?.name !== "string" || !constant.name) { bad("every build constant needs a `name`"); continue; }
367
+ if (names.has(constant.name)) bad(`${where} is also listed under switches (a name is either a switch or a build constant)`);
368
+ names.add(constant.name);
369
+ if (!BUILD_CONSTANT_CHANNELS.has(constant.channel)) bad(`${where}: \`channel\` must be one of ${[...BUILD_CONSTANT_CHANNELS].join(", ")}`);
370
+ if (constant.buildTimeOnly !== true) bad(`${where}: \`buildTimeOnly: true\` is required (the builder supplies it when compiling and no caller can supply it at run time)`);
371
+ if (constant.channel === "vite-define" && !/^VITE_/.test(constant.name)) bad(`${where}: a vite-define constant is a \`VITE_*\` name`);
372
+ if (denied.has(constant.name)) bad(`${where} is a deny-listed selector name; a selector cannot be declared a build constant`);
373
+ }
374
+ }
328
375
  }
329
376
  return { doc, issues };
330
377
  }
@@ -340,6 +387,13 @@ const TEST_FILE = /(\.test\.|\.spec\.|_tests?\.rs$|^tests?\.rs$)/;
340
387
  const CARGO_COMPILE_TIME = /\b(?:option_)?env!\(\s*"([^"]+)"/g;
341
388
  // Variables Cargo sets for every build script and crate compilation (the Cargo book, "Environment variables Cargo sets for crates").
342
389
  const CARGO_SET = /^(CARGO|CARGO_(PKG_[A-Z_]+|MANIFEST_DIR|MANIFEST_PATH|CRATE_NAME|BIN_NAME|BIN_EXE_[A-Za-z0-9_-]+|PRIMARY_PACKAGE|TARGET_TMPDIR|RUSTC_CURRENT_DIR)|OUT_DIR)$/;
390
+ // Variables Cargo sets only for a build script (the Cargo book, "Environment variables Cargo sets for build scripts"): not selectors
391
+ // when read by `build.rs` with `env::var`/`var_os`, whatever the build is (#1045). Anywhere else these names are ordinary reads.
392
+ const CARGO_BUILD_SCRIPT_SET = /^(OUT_DIR|TARGET|HOST|PROFILE|DEBUG|OPT_LEVEL|NUM_JOBS|RUSTC|RUSTC_WRAPPER|RUSTC_WORKSPACE_WRAPPER|RUSTC_LINKER|RUSTDOC|CARGO_ENCODED_RUSTFLAGS|CARGO_MAKEFLAGS|CARGO_CFG_[A-Z0-9_]+|CARGO_FEATURE_[A-Z0-9_]+|CARGO_MANIFEST_LINKS|DEP_[A-Z0-9_]+)$/;
393
+ // Vite inlines `import.meta.env.VITE_*` while building: a compile-time channel, like `env!`/`option_env!`.
394
+ const IMPORT_META_ENV_DOT = /import\.meta\.env\.([A-Za-z_][A-Za-z0-9_]*)/g;
395
+ const IMPORT_META_ENV_INDEX = /import\.meta\.env\[\s*["']([^"']+)["']\s*\]/g;
396
+ const COMPILE_TIME_READS = new Set([CARGO_COMPILE_TIME, IMPORT_META_ENV_DOT, IMPORT_META_ENV_INDEX]);
343
397
  // Reads of a literal name; group 1 is the name.
344
398
  const LITERAL_READS = [
345
399
  /\b(?:std::)?env::var(?:_os)?\(\s*"([^"]+)"\s*\)/g,
@@ -347,8 +401,8 @@ const LITERAL_READS = [
347
401
  /\bgetenv\(\s*"([^"]+)"\s*\)/g,
348
402
  /process\.env\.([A-Za-z_][A-Za-z0-9_]*)/g,
349
403
  /process\.env\[\s*["']([^"']+)["']\s*\]/g,
350
- /import\.meta\.env\.([A-Za-z_][A-Za-z0-9_]*)/g,
351
- /import\.meta\.env\[\s*["']([^"']+)["']\s*\]/g,
404
+ IMPORT_META_ENV_DOT,
405
+ IMPORT_META_ENV_INDEX,
352
406
  /environment\[\s*"([^"]+)"\s*\]/g,
353
407
  // clap: `#[arg(env = "X")]`, `#[clap(env = "X")]`, `Arg::new(..).env("X")`.
354
408
  /\benv\s*=\s*"([^"]+)"/g,
@@ -385,14 +439,88 @@ function* walkSource(root, skipAbs = new Set()) {
385
439
  }
386
440
  }
387
441
 
442
+ // `releaseSwitches.envHelpers`: macros or functions whose first literal argument is an environment variable name (`dev_var!("X")`,
443
+ // `env_string("X")`). A literal first argument is a read of that name; any other first argument is a non-literal (dynamic) read.
444
+ // The definition (`fn env_string(name: &str)`) is not a call.
445
+ export function envHelperPatterns(envHelpers, problems = []) {
446
+ if (envHelpers === undefined) return { literal: [], dynamic: [] };
447
+ if (!Array.isArray(envHelpers) || !envHelpers.every((name) => typeof name === "string" && /^[A-Za-z_][A-Za-z0-9_]*$/.test(name))) {
448
+ problems.push({ layer: "inventory", rule: "inventory-invalid", file: "releaseSwitches.envHelpers", reason: "inventory-invalid: releaseSwitches.envHelpers must be an array of macro or function names ([A-Za-z_][A-Za-z0-9_]*)" });
449
+ return { literal: [], dynamic: [] };
450
+ }
451
+ return {
452
+ literal: envHelpers.map((name) => new RegExp(`(?<![\\w$])${name}\\s*!?\\s*\\(\\s*"([^"]+)"`, "g")),
453
+ dynamic: envHelpers.map((name) => new RegExp(`(?<!\\bfn\\s+)(?<![\\w$])${name}\\s*!?\\s*\\(\\s*[^")\\s]`, "g")),
454
+ };
455
+ }
456
+
457
+ // Xcode and SwiftPM project files, for the Swift Release-configuration check.
458
+ function* walkProjectFiles(root, skipAbs = new Set()) {
459
+ const stack = [root];
460
+ while (stack.length) {
461
+ const dir = stack.pop();
462
+ let entries;
463
+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { continue; }
464
+ for (const entry of entries) {
465
+ const full = path.join(dir, entry.name);
466
+ if (entry.isSymbolicLink()) continue;
467
+ if (entry.isDirectory()) { if (!skipDir(entry.name) && !skipAbs.has(full)) stack.push(full); continue; }
468
+ if (entry.isFile() && (entry.name === "project.pbxproj" || entry.name === "Package.swift" || /\.xcconfig$/.test(entry.name))) yield full;
469
+ }
470
+ }
471
+ }
472
+
473
+ const settingTokens = (value) => String(value).split(/[\s,()"']+/).filter(Boolean);
474
+
475
+ // `swift:<CONDITION>` is a claim that a Release build does not define CONDITION. The source walk confirms every read is inside
476
+ // `#if CONDITION`; this confirms the project does not define CONDITION for Release: an Xcode `buildSettings` block of a
477
+ // configuration named like Release (or an .xcconfig line for it, or one that names no configuration), or a SwiftPM `.define("X")`
478
+ // that is not limited to `.when(configuration: .debug)`. A condition that only a separate QA build adds on the command line
479
+ // (`xcodebuild SWIFT_ACTIVE_COMPILATION_CONDITIONS='$(inherited) PULSE_QA'`) is not in any project file and passes.
480
+ function swiftReleaseConditionFindings(walkRoots, skipAbs, sourceRoot, conditions) {
481
+ if (conditions.size === 0) return [];
482
+ const out = [];
483
+ const flag = (file, condition, what) => out.push({ layer: "inventory", rule: "not-compiled-out", file: path.relative(sourceRoot, file), reason: `not-compiled-out: swift:${condition} is declared compiled out of release builds, but ${what}` });
484
+ for (const file of walkRoots.flatMap((root) => [...walkProjectFiles(root, skipAbs)])) {
485
+ let text;
486
+ try { text = readFileSync(file, "utf8"); } catch { continue; }
487
+ const base = path.basename(file);
488
+ if (base === "project.pbxproj") {
489
+ for (const block of text.matchAll(/buildSettings = \{([\s\S]*?)\n\s*\};\s*name = ([^;\n]+);/g)) {
490
+ if (!/release/i.test(block[2])) continue;
491
+ for (const setting of block[1].matchAll(/SWIFT_ACTIVE_COMPILATION_CONDITIONS(?:\[[^\]]*\])?\s*=\s*(\([^)]*\)|"[^"]*"|[^;]+);/g)) {
492
+ const tokens = settingTokens(setting[1]);
493
+ for (const condition of conditions) if (tokens.includes(condition)) flag(file, condition, `the ${block[2].trim()} build configuration defines it in SWIFT_ACTIVE_COMPILATION_CONDITIONS`);
494
+ }
495
+ }
496
+ } else if (base === "Package.swift") {
497
+ for (const call of text.matchAll(/\.define\(\s*"([A-Za-z_][A-Za-z0-9_]*)"([^\n]*)\)/g)) {
498
+ if (conditions.has(call[1]) && !/\.debug\b/.test(call[2])) flag(file, call[1], "Package.swift defines it for every configuration (limit it with `.when(configuration: .debug)`)");
499
+ }
500
+ } else {
501
+ for (const setting of text.matchAll(/^\s*SWIFT_ACTIVE_COMPILATION_CONDITIONS(\[[^\]]*\])?\s*=\s*([^\n]*)/gm)) {
502
+ const applies = setting[1] ? /release/i.test(setting[1]) : !/debug/i.test(base);
503
+ if (!applies) continue;
504
+ const tokens = settingTokens(setting[2]);
505
+ for (const condition of conditions) if (tokens.includes(condition)) flag(file, condition, `${base} defines it in SWIFT_ACTIVE_COMPILATION_CONDITIONS for Release`);
506
+ }
507
+ }
508
+ }
509
+ return out;
510
+ }
511
+
388
512
  function lineOf(text, index) { let n = 1; for (let i = 0; i < index; i += 1) if (text.charCodeAt(i) === 10) n += 1; return n; }
389
513
 
390
514
  // inventoryText: contents of switches.json. Returns findings only.
391
- export function sourceSwitchFindings({ sourceRoot, sourceRoots, inventoryText, inventoryLabel = "switches.json", extraDeny = [], skipRoots = [] }) {
515
+ export function sourceSwitchFindings({ sourceRoot, sourceRoots, inventoryText, inventoryLabel = "switches.json", extraDeny = [], skipRoots = [], envHelpers }) {
392
516
  const { doc, issues } = parseInventory(inventoryText, inventoryLabel);
393
517
  const findings = [...issues];
518
+ const helpers = envHelperPatterns(envHelpers, findings);
394
519
  if (!doc || !Array.isArray(doc.switches)) return findings;
395
520
  const registered = new Set(doc.switches.map((s) => s.name));
521
+ const entries = new Map(doc.switches.filter((s) => typeof s?.name === "string").map((s) => [s.name, s]));
522
+ const constants = new Set((Array.isArray(doc.buildConstants) ? doc.buildConstants : []).filter((c) => typeof c?.name === "string").map((c) => c.name));
523
+ const swiftConditions = new Set();
396
524
  const dynamicAllowed = new Set((doc.dynamicReads ?? []).map((d) => path.normalize(d.file)));
397
525
  const reads = new Set();
398
526
  const denyFlags = [...REGISTRY.denyNames, ...extraDeny.map((n) => ({ name: typeof n === "string" ? n : n.name }))].map((d) => d.name).filter((n) => n.startsWith("-"));
@@ -405,7 +533,8 @@ export function sourceSwitchFindings({ sourceRoot, sourceRoots, inventoryText, i
405
533
  try { text = readFileSync(file, "utf8"); } catch { continue; }
406
534
  const rel = path.relative(sourceRoot, file);
407
535
  const bare = BARE_IMPORT.test(text) && /\.rs$/.test(file);
408
- for (const pattern of bare ? [...LITERAL_READS, BARE_LITERAL] : LITERAL_READS) {
536
+ const buildScript = path.basename(file) === "build.rs";
537
+ for (const pattern of [...LITERAL_READS, ...helpers.literal, ...(bare ? [BARE_LITERAL] : [])]) {
409
538
  pattern.lastIndex = 0;
410
539
  for (let m = pattern.exec(text); m; m = pattern.exec(text)) {
411
540
  const name = m[1];
@@ -413,12 +542,28 @@ export function sourceSwitchFindings({ sourceRoot, sourceRoots, inventoryText, i
413
542
  // `env!`/`option_env!` of a name Cargo itself sets at compile time (CARGO_PKG_VERSION, CARGO_MANIFEST_DIR, ...) is
414
543
  // not a switch: no caller can choose it. Any other compile-time name is still a read the builder could set.
415
544
  if (pattern === CARGO_COMPILE_TIME && CARGO_SET.test(name)) continue;
545
+ // A build script reads what Cargo sets for it (OUT_DIR, TARGET, PROFILE, CARGO_CFG_*, CARGO_FEATURE_*): not a selector either (#1045).
546
+ if (buildScript && (CARGO_SET.test(name) || CARGO_BUILD_SCRIPT_SET.test(name))) continue;
547
+ // The operating system's own variables (HOME, APPDATA, LOCALAPPDATA, PATH, ...; registry `osProvided`) select nothing the app can be told.
548
+ if (OS_PROVIDED.has(name) && !registered.has(name)) continue;
549
+ // A builder-supplied build-time constant is read only through a compile-time channel; a run-time read of it is a switch (#1009).
550
+ if (constants.has(name)) {
551
+ reads.add(name);
552
+ if (!COMPILE_TIME_READS.has(pattern)) findings.push({ layer: "inventory", rule: "build-constant-runtime-read", file: `${rel}:${lineOf(text, m.index)}`, reason: `build-constant-runtime-read: \`${name}\` is declared a builder-supplied build-time constant (buildConstants) but is read at run time here; read it with option_env!/env! or import.meta.env, or register it as a switch` });
553
+ continue;
554
+ }
416
555
  reads.add(name);
556
+ const entry = entries.get(name);
557
+ const swift = entry && FORBIDDEN_CLASSES.has(entry.class) ? SWIFT_COMPILED_OUT.exec(entry.compiledOut ?? "") : null;
558
+ if (swift) {
559
+ if (!/\.swift$/.test(file)) findings.push({ layer: "inventory", rule: "not-compiled-out", file: `${rel}:${lineOf(text, m.index)}`, reason: `not-compiled-out: \`${name}\` is declared compiledOut ${entry.compiledOut} (a Swift condition) but is read in a file that is not Swift` });
560
+ else if (!swiftConditionEnclosed(text, m.index, swift[1])) findings.push({ layer: "inventory", rule: "not-compiled-out", file: `${rel}:${lineOf(text, m.index)}`, reason: `not-compiled-out: \`${name}\` is declared compiledOut ${entry.compiledOut} but this read is not inside an \`#if ${swift[1]}\` branch (\`#else\`, \`||\` and \`!\` do not count)` });
561
+ }
417
562
  if (!registered.has(name)) findings.push({ layer: "inventory", rule: "unregistered-read", file: `${rel}:${lineOf(text, m.index)}`, reason: `unregistered-read: \`${name}\` is read here but is not listed in ${inventoryLabel}` });
418
563
  }
419
564
  }
420
565
  if (!dynamicAllowed.has(path.normalize(rel))) {
421
- for (const pattern of bare ? [...DYNAMIC_READS, BARE_DYNAMIC] : DYNAMIC_READS) {
566
+ for (const pattern of [...DYNAMIC_READS, ...helpers.dynamic, ...(bare ? [BARE_DYNAMIC] : [])]) {
422
567
  pattern.lastIndex = 0;
423
568
  for (let m = pattern.exec(text); m; m = pattern.exec(text)) {
424
569
  findings.push({ layer: "inventory", rule: "dynamic-read", file: `${rel}:${lineOf(text, m.index)}`, reason: `dynamic-read: an environment read with a non-literal name cannot be inventoried; list the file under \`dynamicReads\` in ${inventoryLabel} with a reason, or use a literal name` });
@@ -433,9 +578,114 @@ export function sourceSwitchFindings({ sourceRoot, sourceRoots, inventoryText, i
433
578
  }
434
579
  }
435
580
  }
581
+ // Every swift:<CONDITION> entry is checked against the project's Release settings whether or not a read was found (a declaration that
582
+ // nothing in the tree reads is still a claim about the build).
583
+ for (const entry of doc.switches) {
584
+ const swift = FORBIDDEN_CLASSES.has(entry?.class) ? SWIFT_COMPILED_OUT.exec(entry.compiledOut ?? "") : null;
585
+ if (swift) swiftConditions.add(swift[1]);
586
+ }
587
+ findings.push(...swiftReleaseConditionFindings(walkRoots, skipAbs, sourceRoot, swiftConditions));
436
588
  return findings;
437
589
  }
438
590
 
591
+ // ---------------------------------------------------------------------------------------------------------------------
592
+ // Release presence (#937): a name that release code only scrubs, clears or sets.
593
+
594
+ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
595
+ const ownerNameMatches = (pattern, name) => (pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : pattern === name);
596
+ const treeHasCrate = (treeText, crate) => typeof treeText === "string" && new RegExp(`(^|[^A-Za-z0-9_-])${escapeRegExp(crate)} v[0-9]`, "m").test(treeText);
597
+ const PRESENCE_CALL = { scrub: /(?:env_remove|remove_var|env_clear|scrub\w*|clear\w*|retain)/, clear: /(?:env_remove|remove_var|env_clear|scrub\w*|clear\w*|retain)/, set: /(?:set_var|\.envs?\s*\(|\bset\w*\s*\()/ };
598
+
599
+ // Does the app anchor `<path>:<line>` show the name inside a call of the claimed mechanism (a window of two lines either side)?
600
+ function presenceAnchorProblem(sourceRoot, entry) {
601
+ const presence = entry.releasePresence;
602
+ if (!sourceRoot) return "has no source root to read its anchor from";
603
+ const [rel, line] = [presence.anchor.slice(0, presence.anchor.lastIndexOf(":")), Number(presence.anchor.slice(presence.anchor.lastIndexOf(":") + 1))];
604
+ const base = path.resolve(sourceRoot);
605
+ const abs = path.resolve(base, rel);
606
+ if (!within(base, abs)) return `anchor ${presence.anchor} escapes the app root`;
607
+ let lines;
608
+ try { lines = readFileSync(abs, "utf8").split(/\r?\n/); } catch { return `anchor ${presence.anchor}: the file does not exist`; }
609
+ if (line > lines.length) return `anchor ${presence.anchor}: the file has only ${lines.length} lines`;
610
+ const window = lines.slice(Math.max(0, line - 3), line + 2).join("\n");
611
+ if (!window.includes(`"${entry.name}"`)) return `anchor ${presence.anchor} does not show the literal "${entry.name}" within two lines`;
612
+ if (!PRESENCE_CALL[presence.mechanism].test(window)) return `anchor ${presence.anchor} shows the name but no ${presence.mechanism} call (${PRESENCE_CALL[presence.mechanism].source})`;
613
+ return null;
614
+ }
615
+
616
+ /**
617
+ * `enclosingCfgFindings`: for each { name, compiledOut } (feature:<n>, cfg:test or cfg:debug_assertions), every literal read of
618
+ * the name in the scanned source must sit inside an item or statement under an attribute `#[cfg(<predicate>)]` (or inside a file
619
+ * its parent declares `#[cfg(<predicate>)] mod x;`). `cfg!()`, a runtime `if`, a read in a TypeScript or other file and a read the
620
+ * attribute does not reach are `read-not-gated`. Findings carry `name`.
621
+ */
622
+ export function enclosingCfgFindings({ sourceRoot, sourceRoots, skipRoots = [], entries, envHelpers }) {
623
+ const findings = [];
624
+ const wanted = new Map(entries.map((entry) => [entry.name, entry]));
625
+ if (wanted.size === 0) return findings;
626
+ const helpers = envHelperPatterns(envHelpers);
627
+ const walkRoots = Array.isArray(sourceRoots) && sourceRoots.length ? sourceRoots : [sourceRoot];
628
+ const skipAbs = new Set((skipRoots ?? []).map((dir) => path.resolve(sourceRoot, dir)));
629
+ const files = walkRoots.flatMap((root) => [...walkSource(root, skipAbs)]).map((file) => { try { return { file, text: readFileSync(file, "utf8") }; } catch { return null; } }).filter(Boolean);
630
+ const gates = rustFileGates(files.filter(({ file }) => /\.rs$/.test(file)));
631
+ for (const { file, text } of files) {
632
+ const rust = /\.rs$/.test(file);
633
+ const rel = path.relative(sourceRoot, file);
634
+ const ranges = new Map();
635
+ for (const pattern of [...LITERAL_READS, ...helpers.literal, ...(rust && BARE_IMPORT.test(text) ? [BARE_LITERAL] : [])]) {
636
+ pattern.lastIndex = 0;
637
+ for (let m = pattern.exec(text); m; m = pattern.exec(text)) {
638
+ const entry = wanted.get(m[1]);
639
+ if (!entry) continue;
640
+ const predicate = cfgPredicateOf(entry.compiledOut);
641
+ let gated = false;
642
+ if (rust && predicate) {
643
+ if (!ranges.has(predicate)) ranges.set(predicate, rustCfgGatedRanges(text, predicate));
644
+ gated = ranges.get(predicate).some(([start, end]) => m.index >= start && m.index < end) || (gates.get(file) ?? []).some((expr) => cfgImplies(expr, predicate));
645
+ }
646
+ if (!gated) findings.push({ layer: "binary", rule: "read-not-gated", name: entry.name, file: `${rel}:${lineOf(text, m.index)}`, reason: `read-not-gated: \`${entry.name}\` is declared with releasePresence, but this read is not inside an item under \`#[cfg(${predicate ?? entry.compiledOut})]\` (\`cfg!()\`, a runtime branch and non-Rust files are not enclosures), so release code can read it` });
647
+ }
648
+ }
649
+ }
650
+ return findings;
651
+ }
652
+
653
+ /**
654
+ * The S1-S4 names whose `releasePresence` claim holds, so the binary layer may let them stay in a release binary, plus the
655
+ * findings for the claims that do not. A claim holds when (1) its owner is in the tree (`owner: crate`: the registry
656
+ * `presenceOwners` entry for the name and mechanism names a crate the resolved `cargo tree` contains) or the app's own anchor
657
+ * shows the name in a scrub, clear or set call (`owner: app`), AND (2) `enclosingCfgFindings` finds no read of it outside a
658
+ * `#[cfg(<compiledOut>)]` enclosure. Anything else keeps the name in the deny set.
659
+ */
660
+ export function releasePresenceFindings({ inventoryText, treeText, sourceRoot, sourceRoots, skipRoots, envHelpers }) {
661
+ const accepted = new Set(); const findings = [];
662
+ const { doc, issues } = parseInventory(inventoryText);
663
+ if (!doc || issues.length || !Array.isArray(doc.switches)) return { accepted, findings };
664
+ const claims = doc.switches.filter((entry) => FORBIDDEN_CLASSES.has(entry.class) && entry.releasePresence && COMPILED_OUT.test(entry.compiledOut ?? ""));
665
+ if (claims.length === 0) return { accepted, findings };
666
+ const unproven = (entry, why) => findings.push({ layer: "binary", rule: "release-presence-unproven", file: "switches.json", reason: `release-presence-unproven: \`${entry.name}\` ${why}; its name stays denied in release binaries` });
667
+ const proven = [];
668
+ for (const entry of claims) {
669
+ const presence = entry.releasePresence;
670
+ if (presence.owner === "crate") {
671
+ const owner = REGISTRY.presenceOwners.find((candidate) => ownerNameMatches(candidate.name, entry.name) && candidate.mechanism === presence.mechanism);
672
+ if (!owner) unproven(entry, `claims owner crate but the registry names no presenceOwners entry that ${presence.mechanism}s it`);
673
+ else if (!treeHasCrate(treeText, owner.crate)) unproven(entry, `claims owner crate \`${owner.crate}\`, which is not in the resolved cargo tree`);
674
+ else proven.push(entry);
675
+ } else {
676
+ const problem = presenceAnchorProblem(sourceRoot, entry);
677
+ if (problem) unproven(entry, problem); else proven.push(entry);
678
+ }
679
+ }
680
+ if (proven.length === 0) return { accepted, findings };
681
+ if (!sourceRoot) { for (const entry of proven) unproven(entry, "has no source root to prove its reads are cfg-gated"); return { accepted, findings }; }
682
+ const gate = enclosingCfgFindings({ sourceRoot, sourceRoots, skipRoots, entries: proven, envHelpers });
683
+ const ungated = new Set(gate.map((finding) => finding.name));
684
+ for (const entry of proven) if (!ungated.has(entry.name)) accepted.add(entry.name);
685
+ findings.push(...gate);
686
+ return { accepted, findings };
687
+ }
688
+
439
689
  // ---------------------------------------------------------------------------------------------------------------------
440
690
  // Layer 3: binary layer.
441
691
 
@@ -523,16 +773,77 @@ export function scanSwitchPaths(paths, { denyMap = denyNamesFor() } = {}) {
523
773
  return { findings, receipt: { files, binaries: files.length } };
524
774
  }
525
775
 
776
+ // Which of `names` occur (Latin-1 or UTF-16LE) in at least one native binary under `paths`. Same matcher as the release scan.
777
+ export function binaryNamesPresent(paths, names) {
778
+ const present = new Set(); let binaries = 0;
779
+ const visit = (target) => {
780
+ let st;
781
+ try { st = lstatSync(target); } catch { return; }
782
+ if (st.isSymbolicLink()) return;
783
+ if (st.isDirectory()) { for (const name of readdirSync(target).sort()) visit(path.join(target, name)); return; }
784
+ if (!st.isFile()) return;
785
+ const fd = openSync(target, "r");
786
+ try {
787
+ const head = Buffer.alloc(4);
788
+ const got = readSync(fd, head, 0, 4, 0);
789
+ if (!isNativeBinaryHeader(head.subarray(0, got))) return;
790
+ binaries += 1;
791
+ const scanner = new SwitchScanner(new Map(names.map((name) => [name, "S1"])));
792
+ const buffer = Buffer.alloc(CHUNK);
793
+ for (;;) {
794
+ const read = readSync(fd, buffer, 0, CHUNK, null);
795
+ if (read === 0) break;
796
+ scanner.push(buffer.subarray(0, read));
797
+ }
798
+ for (const name of names) if (scanner.hits.has(name)) present.add(name);
799
+ } finally { closeSync(fd); }
800
+ };
801
+ for (const target of paths) visit(target);
802
+ return { present, binaries };
803
+ }
804
+
805
+ /**
806
+ * The dev-build self-check (the `--expect-present` of ViewRight's retired scan, #397): a dev binary is built WITH the QA surface, so
807
+ * the strings the release scan refuses must be there. If the dev binary lacks one (a renamed or stripped marker), the release scan
808
+ * could not see it in a release binary either, and would pass silently. `expect` defaults to the QA control marker, which every dev
809
+ * copy carries (GATE-CONTRACT GC-A07); an app lists more with `releaseSwitches.devSelfCheck.expectPresent`.
810
+ */
811
+ export function devExpectPresentFindings({ binaryPaths, expect = [QA_CONTROL_MARKER] }) {
812
+ const { present, binaries } = binaryNamesPresent(binaryPaths, expect);
813
+ if (binaries === 0) return [{ layer: "binary", rule: "unscannable", file: binaryPaths.join(", "), reason: "unscannable: no Mach-O, PE or ELF file found in the dev build; the dev self-check cannot run" }];
814
+ return expect.filter((name) => !present.has(name)).map((name) => ({ layer: "binary", rule: "dev-expect-absent", file: binaryPaths.join(", "), reason: `dev-expect-absent: the dev binary does not contain \`${name}\`; a scan for it in a release binary could not tell a clean build from a renamed or stripped marker` }));
815
+ }
816
+
817
+ /**
818
+ * `releaseSwitches.devSelfCheck`: absent means the default (the QA control marker must be in the dev binary); `{ expectPresent: [names] }` adds
819
+ * names; `{ optOut: "<reason>" }` skips the check for an app whose dev build has no QA control server (a reason is required, and it is
820
+ * printed on every dev build). Returns { expect } or { skip: reason }; anything else throws.
821
+ */
822
+ export function devSelfCheckSettings(value) {
823
+ if (value === undefined) return { expect: [QA_CONTROL_MARKER] };
824
+ if (value && typeof value === "object" && !Array.isArray(value)) {
825
+ if (typeof value.optOut === "string" && value.optOut.trim() && value.expectPresent === undefined) return { skip: value.optOut.trim() };
826
+ if (value.optOut === undefined && Array.isArray(value.expectPresent) && value.expectPresent.length > 0 && value.expectPresent.every((name) => typeof name === "string" && name)) return { expect: [...new Set([QA_CONTROL_MARKER, ...value.expectPresent])] };
827
+ }
828
+ throw new Error('releaseSwitches.devSelfCheck must be { "expectPresent": ["<string>", ...] } or { "optOut": "<why this dev build has no QA surface>" }');
829
+ }
830
+
526
831
  // ---------------------------------------------------------------------------------------------------------------------
527
832
  // Combined gate.
528
833
 
529
834
  // Every layer is optional input; a layer given no input is skipped, except that `requireBinary` fails a scan that
530
835
  // found no native binary. `bypass: ["feature-closure"]` exists only for the negative fixtures that prove the binary
531
836
  // layer independently; release.mjs never passes it.
532
- export function releaseSwitchFindings({ treeText, commands = [], sourceRoot, sourceRoots, skipRoots, inventoryText, binaryPaths = [], appForbid = [], requireBinary = true, bypass = [], remoteHost, remoteLoopback, devtools } = {}) {
837
+ export function releaseSwitchFindings({ treeText, commands = [], sourceRoot, sourceRoots, skipRoots, inventoryText, binaryPaths = [], appForbid = [], requireBinary = true, bypass = [], remoteHost, remoteLoopback, devtools, envHelpers, presenceAccepted = [] } = {}) {
533
838
  const findings = [];
534
839
  const bypassed = new Set(bypass);
840
+ // A name whose releasePresence claim is proven (owner in the tree or anchored scrub, every read cfg-gated) may stay in a release binary.
841
+ // `presenceAccepted` carries the result of an earlier full-source run (the pre-build gate) to a binary-only run.
842
+ const presence = sourceRoot && inventoryText != null ? releasePresenceFindings({ inventoryText, treeText, sourceRoot, sourceRoots, skipRoots, envHelpers }) : { accepted: new Set(), findings: [] };
843
+ const presentOk = new Set([...presenceAccepted, ...presence.accepted]);
844
+ findings.push(...presence.findings);
535
845
  const denyMap = denyNamesFor({ appForbid: [...appForbid, ...(inventoryText != null ? inventoryDenyNames(inventoryText) : [])] });
846
+ for (const name of presentOk) denyMap.delete(name);
536
847
  if (!bypassed.has("feature-closure")) {
537
848
  if (treeText != null) {
538
849
  findings.push(...featureClosureFindings(treeText, { allowDevtools: devtools?.mode === "content-only" }));
@@ -541,7 +852,7 @@ export function releaseSwitchFindings({ treeText, commands = [], sourceRoot, sou
541
852
  }
542
853
  for (const argv of commands) findings.push(...commandSwitchFindings(argv, { allowDevtools: devtools?.mode === "content-only" }));
543
854
  }
544
- if (sourceRoot && inventoryText != null) findings.push(...sourceSwitchFindings({ sourceRoot, sourceRoots, skipRoots, inventoryText, extraDeny: appForbid }));
855
+ if (sourceRoot && inventoryText != null) findings.push(...sourceSwitchFindings({ sourceRoot, sourceRoots, skipRoots, inventoryText, extraDeny: appForbid, envHelpers }));
545
856
  let receipt = { files: [], binaries: 0 };
546
857
  if (binaryPaths.length) {
547
858
  const scanned = scanSwitchPaths(binaryPaths, { denyMap });
@@ -575,16 +886,19 @@ export function localCrateDirsFromTree(treeText, root) {
575
886
  }
576
887
 
577
888
  const NON_SHIPPED_SKIP = new Set(["node_modules", "target", ".git"]);
578
- function hasPackageJson(dir, depth = 0) {
889
+ function hasMarkerFile(dir, marker, depth = 0) {
579
890
  if (depth > 6) return false;
580
891
  let entries;
581
892
  try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return false; }
582
893
  for (const entry of entries) {
583
- if (entry.isFile() && entry.name === "package.json") return true;
584
- if (entry.isDirectory() && !entry.isSymbolicLink() && !NON_SHIPPED_SKIP.has(entry.name) && hasPackageJson(path.join(dir, entry.name), depth + 1)) return true;
894
+ if (entry.isFile() && entry.name === marker) return true;
895
+ if (entry.isDirectory() && !entry.isSymbolicLink() && !NON_SHIPPED_SKIP.has(entry.name) && hasMarkerFile(path.join(dir, entry.name), marker, depth + 1)) return true;
585
896
  }
586
897
  return false;
587
898
  }
899
+ const hasPackageJson = (dir) => hasMarkerFile(dir, "package.json");
900
+ // A desktop Swift package (Package.swift) is compiled code, never tooling, whether or not a build script reaches it (#939).
901
+ const hasSwiftPackage = (dir) => hasMarkerFile(dir, "Package.swift");
588
902
  const within = (outer, inner) => inner === outer || inner.startsWith(outer + path.sep);
589
903
 
590
904
  const readJsonSafe = (file) => { try { return JSON.parse(readFileSync(file, "utf8")); } catch { return null; } };
@@ -621,9 +935,10 @@ function commandRefs(base, commands, scripts) {
621
935
  // and tsconfig.json name. Quoted strings in vite.config are read as paths when they exist under the root (root, publicDir, build input).
622
936
  function rootFrontendDirs(base) {
623
937
  const dirs = new Set();
624
- const add = (rel) => {
938
+ const typeChecked = new Set();
939
+ const add = (rel, into = dirs) => {
625
940
  const abs = path.resolve(base, rel);
626
- if (abs !== base && within(base, abs) && existsSync(abs)) dirs.add(abs);
941
+ if (abs !== base && within(base, abs) && existsSync(abs)) into.add(abs);
627
942
  };
628
943
  add("src"); add("public");
629
944
  for (const m of readTextSafe(path.join(base, "index.html")).matchAll(/\b(?:src|href)\s*=\s*["']([^"'#?]+)["']/g)) if (!/^[a-z][a-z0-9+.-]*:|^\/\//i.test(m[1])) add(m[1].replace(/^\//, ""));
@@ -633,9 +948,53 @@ function rootFrontendDirs(base) {
633
948
  }
634
949
  const ts = readTextSafe(path.join(base, "tsconfig.json"));
635
950
  for (const m of ts.matchAll(/"(?:include|files)"\s*:\s*\[([^\]]*)\]/g)) {
636
- for (const q of m[1].matchAll(/"([^"]+)"/g)) add(q[1].split(/[*?{[]/)[0].replace(/\/$/, "") || ".");
951
+ for (const q of m[1].matchAll(/"([^"]+)"/g)) add(q[1].split(/[*?{[]/)[0].replace(/\/$/, "") || ".", typeChecked);
637
952
  }
638
- return dirs;
953
+ // `tsconfig.json` `include`/`files` only say what `tsc` type-checks (MailRight's `scripts/`), not what a bundle contains (#1070): those
954
+ // directories are protected only when the frontend import graph reaches them (`frontendImportGraph`), never by being listed.
955
+ return { dirs, typeChecked };
956
+ }
957
+
958
+ // Source files the frontend build starts from: scripts named by the root `index.html`, `src/main.*` and `src/index.*`, and files named by quoted
959
+ // strings in `vite.config.*` (build input).
960
+ function frontendEntryFiles(base) {
961
+ const entries = new Set();
962
+ const addFile = (rel) => {
963
+ const abs = path.resolve(base, String(rel).replace(/^\//, ""));
964
+ if (within(base, abs) && JS_SOURCE.test(abs) && existsSync(abs)) entries.add(abs);
965
+ };
966
+ for (const m of readTextSafe(path.join(base, "index.html")).matchAll(/<script\b[^>]*\bsrc\s*=\s*["']([^"'#?]+)["']/gi)) if (!/^[a-z][a-z0-9+.-]*:|^\/\//i.test(m[1])) addFile(m[1]);
967
+ for (const stem of ["main", "index"]) for (const ext of ["ts", "tsx", "js", "jsx", "mjs"]) addFile(`src/${stem}.${ext}`);
968
+ for (const entry of readdirSafe(base)) {
969
+ if (!/^vite\.config\./.test(entry)) continue;
970
+ for (const m of readTextSafe(path.join(base, entry)).matchAll(/["'`]([^"'`\n]+)["'`]/g)) addFile(m[1]);
971
+ }
972
+ return entries;
973
+ }
974
+
975
+ const JS_SOURCE = /\.(?:[cm]?[jt]s|[jt]sx|vue|svelte)$/;
976
+ const IMPORT_SPEC = /(?:\bfrom\s*|\bimport\s*\(?\s*|\brequire\s*\(\s*|\bnew\s+URL\s*\(\s*)["']([^"']+)["']/g;
977
+ const RESOLVE_EXT = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".vue", ".svelte", ".json"];
978
+
979
+ // Every file the frontend build reaches through relative imports (`./x`, `../scripts/x.ts`, `import("./x")`, `new URL("./x", import.meta.url)`)
980
+ // from its entry files. Aliased and bare imports are not followed (the walk cannot resolve tsconfig `paths` or Vite `alias`).
981
+ function frontendImportGraph(base) {
982
+ const seen = new Set();
983
+ const queue = [...frontendEntryFiles(base)];
984
+ const exists = (file) => { try { return lstatSync(file).isFile(); } catch { return false; } };
985
+ while (queue.length && seen.size < 20000) {
986
+ const file = queue.pop();
987
+ if (seen.has(file)) continue;
988
+ seen.add(file);
989
+ for (const m of readTextSafe(file).matchAll(IMPORT_SPEC)) {
990
+ if (!m[1].startsWith(".")) continue;
991
+ const target = path.resolve(path.dirname(file), m[1].replace(/[?#].*$/, ""));
992
+ const stripped = target.replace(/\.(?:[cm]?js|jsx)$/, "");
993
+ const found = [target, ...RESOLVE_EXT.map((e) => target + e), ...RESOLVE_EXT.map((e) => stripped + e), ...RESOLVE_EXT.map((e) => path.join(target, `index${e}`))].find(exists);
994
+ if (found && within(base, found) && !seen.has(found)) queue.push(found);
995
+ }
996
+ }
997
+ return seen;
639
998
  }
640
999
  function readdirSafe(dir) { try { return readdirSync(dir); } catch { return []; } }
641
1000
 
@@ -644,8 +1003,8 @@ function readdirSafe(dir) { try { return readdirSync(dir); } catch { return [];
644
1003
  * An exclusion list: whatever is not declared is still scanned. Each entry is refused (`inventory-invalid`) when the dir is missing,
645
1004
  * absolute, escapes the root, is a symlink or the root itself, has an empty reason, contains or sits inside a local crate of the release
646
1005
  * cargo tree, contains or sits inside `src-tauri` or the Tauri `frontendDist` bundle, or contains or sits inside a package that has a
647
- * `package.json` (a frontend build input), overlaps the root frontend (`src/`, `public/`, directories named by `index.html`, `vite.config.*` or
648
- * `tsconfig.json`, when the root has a `package.json`), or contains a file named by a `src-tauri/tauri.conf.json` `before*Command` or a root
1006
+ * `package.json` (a frontend build input) or a `Package.swift`, contains or sits inside a path a Cargo build script compiles or watches (`buildScriptRefs`), overlaps the root frontend (`src/`, `public/`, directories named by `index.html` or
1007
+ * `vite.config.*`, when the root has a `package.json`; a directory only `tsconfig.json` names is refused when the frontend import graph reaches it), or contains a file named by a `src-tauri/tauri.conf.json` `before*Command` or a root
649
1008
  * `package.json` `build*` script or by the release recipe's own commands (`recipeCommands`; followed through `run <script>`), which run during the release build.
650
1009
  * Returns { findings, roots } where `roots` are the validated root-relative dirs, empty if any entry was refused.
651
1010
  */
@@ -664,7 +1023,11 @@ export function validateNonShipped({ root, treeText, nonShipped, recipeCommands
664
1023
  if (typeof dist === "string" && !/^[a-z][a-z0-9+.-]*:\/\//i.test(dist)) protectedDirs.push(path.resolve(base, "src-tauri", dist));
665
1024
  } catch { /* no readable tauri.conf.json: nothing extra to protect */ }
666
1025
  const pkg = readJsonSafe(path.join(base, "package.json"));
667
- const frontendDirs = pkg ? rootFrontendDirs(base) : new Set();
1026
+ const frontend = pkg ? rootFrontendDirs(base) : { dirs: new Set(), typeChecked: new Set() };
1027
+ const frontendDirs = frontend.dirs;
1028
+ let importGraph; // built once, only when a declared directory is one tsc type-checks
1029
+ const buildScriptDirs = [...new Set([base, path.join(base, "src-tauri"), ...localCrateDirsFromTree(treeText, base)])];
1030
+ const buildScripts = buildScriptRefs(buildScriptDirs);
668
1031
  const scripts = pkg?.scripts && typeof pkg.scripts === "object" ? pkg.scripts : {};
669
1032
  const hookObj = readJsonSafe(path.join(base, "src-tauri", "tauri.conf.json"))?.build ?? {};
670
1033
  const commands = [
@@ -691,11 +1054,23 @@ export function validateNonShipped({ root, treeText, nonShipped, recipeCommands
691
1054
  if (within(abs, guarded) || within(guarded, abs)) { bad(label, `dir \`${dir}\` overlaps shipped code (${path.relative(base, guarded) || "."}: a local crate of the release cargo tree, src-tauri or the frontend bundle); it cannot be declared non-shipped`); return; }
692
1055
  }
693
1056
  if (hasPackageJson(abs)) { bad(label, `dir \`${dir}\` contains a package.json (a possible frontend build input); it cannot be declared non-shipped`); return; }
1057
+ if (hasSwiftPackage(abs)) { bad(label, `dir \`${dir}\` contains a Package.swift (a desktop Swift package is compiled code); it cannot be declared non-shipped`); return; }
1058
+ for (let up = path.dirname(abs); within(base, up) && up !== base; up = path.dirname(up)) {
1059
+ if (existsSync(path.join(up, "Package.swift"))) { bad(label, `dir \`${dir}\` sits inside a Swift package (${path.relative(base, up)}/Package.swift); it cannot be declared non-shipped`); return; }
1060
+ }
1061
+ const scriptRef = [...buildScripts].find((r) => within(abs, r) || within(r, abs));
1062
+ if (scriptRef) { bad(label, `dir \`${dir}\` contains or sits inside a path a Cargo build script compiles or watches (${path.relative(base, scriptRef).split(path.sep).join("/")}: build.rs itself, include!/include_str!/include_bytes!, cc::Build file/include or cargo:rerun-if-changed); it cannot be declared non-shipped`); return; }
694
1063
  for (let up = path.dirname(abs); within(base, up) && up !== base; up = path.dirname(up)) {
695
1064
  if (existsSync(path.join(up, "package.json"))) { bad(label, `dir \`${dir}\` sits inside a package (${path.relative(base, up)}/package.json: a possible frontend build input); it cannot be declared non-shipped`); return; }
696
1065
  }
697
1066
  const guardedBy = [...frontendDirs].find((g) => within(abs, g) || within(g, abs));
698
1067
  if (guardedBy) { bad(label, `dir \`${dir}\` overlaps the app's root frontend (${path.relative(base, guardedBy)}: src/, public/ or a directory named by index.html, vite.config or tsconfig); it cannot be declared non-shipped`); return; }
1068
+ const typeChecked = [...frontend.typeChecked].find((g) => within(abs, g) || within(g, abs));
1069
+ if (typeChecked) {
1070
+ importGraph ??= frontendImportGraph(base);
1071
+ const reached = [...importGraph].find((file) => within(abs, file));
1072
+ if (reached) { bad(label, `dir \`${dir}\` is type-checked by tsconfig.json and the frontend import graph reaches ${path.relative(base, reached).split(path.sep).join("/")}, so a bundle contains it; it cannot be declared non-shipped`); return; }
1073
+ }
699
1074
  const buildRef = [...buildRefs].find((r) => within(abs, r) || within(r, abs));
700
1075
  if (buildRef) { bad(label, `dir \`${dir}\` contains or sits inside a build-time input (${path.relative(base, buildRef).split(path.sep).join("/")}: named by a tauri.conf.json before*Command or a package.json build script, which runs during the release build); it cannot be declared non-shipped`); return; }
701
1076
  if (typeof reason === "string" && reason.trim() !== "") roots.push(path.relative(base, abs));