@gadicc/loom 1.34.0 → 1.35.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.
Files changed (104) hide show
  1. package/README.md +108 -41
  2. package/esm/src/apiKeys/authorize.d.ts.map +1 -1
  3. package/esm/src/apiKeys/authorize.js +71 -0
  4. package/esm/src/apiKeys/betterAuth.d.ts +123 -0
  5. package/esm/src/apiKeys/betterAuth.d.ts.map +1 -0
  6. package/esm/src/apiKeys/betterAuth.js +164 -0
  7. package/esm/src/apiKeys/credentials.d.ts +37 -2
  8. package/esm/src/apiKeys/credentials.d.ts.map +1 -1
  9. package/esm/src/apiKeys/credentials.js +69 -8
  10. package/esm/src/apiKeys/lifecycle.d.ts +41 -0
  11. package/esm/src/apiKeys/lifecycle.d.ts.map +1 -0
  12. package/esm/src/apiKeys/lifecycle.js +6 -0
  13. package/esm/src/apiKeys/limits.d.ts +132 -0
  14. package/esm/src/apiKeys/limits.d.ts.map +1 -0
  15. package/esm/src/apiKeys/limits.js +246 -0
  16. package/esm/src/apiKeys/mod.d.ts +4 -0
  17. package/esm/src/apiKeys/mod.d.ts.map +1 -1
  18. package/esm/src/apiKeys/mod.js +4 -0
  19. package/esm/src/apiKeys/permissions.d.ts +56 -0
  20. package/esm/src/apiKeys/permissions.d.ts.map +1 -0
  21. package/esm/src/apiKeys/permissions.js +128 -0
  22. package/esm/src/apiKeys/policy.d.ts +3 -1
  23. package/esm/src/apiKeys/policy.d.ts.map +1 -1
  24. package/esm/src/apiKeys/policy.js +3 -1
  25. package/esm/src/apiKeys/types.d.ts +68 -1
  26. package/esm/src/apiKeys/types.d.ts.map +1 -1
  27. package/esm/src/cli/localDevLock.d.ts +97 -0
  28. package/esm/src/cli/localDevLock.d.ts.map +1 -0
  29. package/esm/src/cli/localDevLock.js +312 -0
  30. package/esm/src/cli/localDevPackage.d.ts +172 -0
  31. package/esm/src/cli/localDevPackage.d.ts.map +1 -0
  32. package/esm/src/cli/localDevPackage.js +617 -0
  33. package/esm/src/cli/migrationEnv.d.ts +19 -0
  34. package/esm/src/cli/migrationEnv.d.ts.map +1 -1
  35. package/esm/src/cli/migrationEnv.js +44 -1
  36. package/esm/src/cli/mod.d.ts +69 -4
  37. package/esm/src/cli/mod.d.ts.map +1 -1
  38. package/esm/src/cli/mod.js +2806 -437
  39. package/esm/src/cli/projectTooling.d.ts +19 -1
  40. package/esm/src/cli/projectTooling.d.ts.map +1 -1
  41. package/esm/src/cli/projectTooling.js +142 -12
  42. package/esm/src/mui/apiKeys.d.ts +123 -17
  43. package/esm/src/mui/apiKeys.d.ts.map +1 -1
  44. package/esm/src/mui/apiKeys.js +219 -78
  45. package/esm/src/mui/apiKeysView.d.ts +145 -0
  46. package/esm/src/mui/apiKeysView.d.ts.map +1 -1
  47. package/esm/src/mui/apiKeysView.js +278 -0
  48. package/esm/src/next/apiKeys/mod.d.ts +8 -1
  49. package/esm/src/next/apiKeys/mod.d.ts.map +1 -1
  50. package/esm/src/next/apiKeys/mod.js +5 -2
  51. package/package.json +2 -6
  52. package/script/src/apiKeys/authorize.d.ts.map +1 -1
  53. package/script/src/apiKeys/authorize.js +71 -0
  54. package/script/src/apiKeys/betterAuth.d.ts +123 -0
  55. package/script/src/apiKeys/betterAuth.d.ts.map +1 -0
  56. package/script/src/apiKeys/betterAuth.js +169 -0
  57. package/script/src/apiKeys/credentials.d.ts +37 -2
  58. package/script/src/apiKeys/credentials.d.ts.map +1 -1
  59. package/script/src/apiKeys/credentials.js +71 -8
  60. package/script/src/apiKeys/lifecycle.d.ts +41 -0
  61. package/script/src/apiKeys/lifecycle.d.ts.map +1 -0
  62. package/script/src/apiKeys/lifecycle.js +7 -0
  63. package/script/src/apiKeys/limits.d.ts +132 -0
  64. package/script/src/apiKeys/limits.d.ts.map +1 -0
  65. package/script/src/apiKeys/limits.js +254 -0
  66. package/script/src/apiKeys/mod.d.ts +4 -0
  67. package/script/src/apiKeys/mod.d.ts.map +1 -1
  68. package/script/src/apiKeys/mod.js +4 -0
  69. package/script/src/apiKeys/permissions.d.ts +56 -0
  70. package/script/src/apiKeys/permissions.d.ts.map +1 -0
  71. package/script/src/apiKeys/permissions.js +136 -0
  72. package/script/src/apiKeys/policy.d.ts +3 -1
  73. package/script/src/apiKeys/policy.d.ts.map +1 -1
  74. package/script/src/apiKeys/policy.js +3 -1
  75. package/script/src/apiKeys/types.d.ts +68 -1
  76. package/script/src/apiKeys/types.d.ts.map +1 -1
  77. package/script/src/cli/localDevLock.d.ts +97 -0
  78. package/script/src/cli/localDevLock.d.ts.map +1 -0
  79. package/script/src/cli/localDevLock.js +320 -0
  80. package/script/src/cli/localDevPackage.d.ts +172 -0
  81. package/script/src/cli/localDevPackage.d.ts.map +1 -0
  82. package/script/src/cli/localDevPackage.js +635 -0
  83. package/script/src/cli/migrationEnv.d.ts +19 -0
  84. package/script/src/cli/migrationEnv.d.ts.map +1 -1
  85. package/script/src/cli/migrationEnv.js +48 -1
  86. package/script/src/cli/mod.d.ts +69 -4
  87. package/script/src/cli/mod.d.ts.map +1 -1
  88. package/script/src/cli/mod.js +2807 -437
  89. package/script/src/cli/projectTooling.d.ts +19 -1
  90. package/script/src/cli/projectTooling.d.ts.map +1 -1
  91. package/script/src/cli/projectTooling.js +176 -12
  92. package/script/src/mui/apiKeys.d.ts +123 -17
  93. package/script/src/mui/apiKeys.d.ts.map +1 -1
  94. package/script/src/mui/apiKeys.js +220 -77
  95. package/script/src/mui/apiKeysView.d.ts +145 -0
  96. package/script/src/mui/apiKeysView.d.ts.map +1 -1
  97. package/script/src/mui/apiKeysView.js +291 -0
  98. package/script/src/next/apiKeys/mod.d.ts +8 -1
  99. package/script/src/next/apiKeys/mod.d.ts.map +1 -1
  100. package/script/src/next/apiKeys/mod.js +5 -2
  101. package/skills/loom/SKILL.md +111 -18
  102. package/skills/loom-api-keys/SKILL.md +101 -7
  103. package/skills/loom-auth/SKILL.md +9 -0
  104. package/skills/loom-db/SKILL.md +3 -1
@@ -1,7 +1,7 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { createHash, randomUUID } from "node:crypto";
3
3
  import { constants as fsConstants } from "node:fs";
4
- import { access, chmod, lstat, mkdir, mkdtemp, readdir, readFile, readlink, rm, stat, symlink, unlink, writeFile, } from "node:fs/promises";
4
+ import { access, chmod, lstat, mkdir, mkdtemp, readdir, readFile, readlink, realpath, rm, stat, symlink, unlink, writeFile, } from "node:fs/promises";
5
5
  import { createRequire } from "node:module";
6
6
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
7
7
  import process from "node:process";
@@ -13,12 +13,15 @@ import { resolveProductionBranch, } from "./releaseConfig.js";
13
13
  import { configureGithubVercelReleaseCredential, } from "./releaseCredentials.js";
14
14
  import { runGithubReleaseTrustCommand } from "./releaseTrustCommand.js";
15
15
  import { checkLocalDatabase, setupLocalDatabase } from "./localDb.js";
16
+ import { BETTER_AUTH_API_KEY_HTTP_PATHS } from "../apiKeys/betterAuth.js";
16
17
  import { DEFAULT_API_KEY_AUDIT_RETENTION } from "../apiKeys/retention.js";
17
18
  import { checkProjectSkills, getProjectSkillStatus, LOOM_EXTERNAL_SKILLS_GITIGNORE_LINE, removeLegacyNextSkillLink, setProjectSkillDisabled, syncExternalProjectSkills, syncInstalledPackageSkills, } from "./projectSkills.js";
18
19
  import { resolveMigrationEnvironment, resolveMigrationEnvironmentFromEnvFile, verifyMigrationConnection, verifyMigrationConnectionFromEnvFile, } from "./migrationEnv.js";
19
20
  import { prepareVercelBuildEnvironment, verifyVercelBuildArtifact, } from "./vercelBuildEnv.js";
20
21
  import { parseVercelReleaseTimeout, prepareVercelProjectRelease, promoteVercelProjectRelease, } from "./vercelProjectRelease.js";
21
- import { detectProjectTooling, ensureTask, ensureTaskFollowup, ensureTaskPrerequisite, findTaskConflicts, formatTaskInvocation, getTaskCommand, mutateDenoLinks, mutateProjectDependencies, readDenoLinks, readProjectPackageMetadata, readTaskStore, taskInvokes, taskRunsBeforeCommand, } from "./projectTooling.js";
22
+ import { detectProjectTooling, ensureTask, ensureTaskFollowup, ensureTaskPrerequisite, findTaskConflicts, formatTaskInvocation, getTaskCommand, mutateDenoLinks, mutatePackageJsonOverride, mutateProjectDependencies, parseJsonc, readDenoLinks, readProjectPackageMetadata, readTaskStore, taskInvokes, taskRunsBeforeCommand, } from "./projectTooling.js";
23
+ import { withLocalDevLock, } from "./localDevLock.js";
24
+ import { computeLoomSourceFingerprint, computePackageContentDigest, computePackageTreeSignature, findNewPeerVariantDuplicates, findPackageTreeDifference, formatLoomBuildStamp, getLockfileOverride, getLockfileRootImporterDependency, hasLoomBuildProvenance, LOOM_BUILD_STAMP_FILE, LOOM_PACKAGE_RELEVANT_PATHS, readLoomBuildStamp, } from "./localDevPackage.js";
22
25
  export const DEFAULT_LOOM_RANGE = "^1.0.0";
23
26
  export const LOOM_DEPENDENCY = "@gadicc/loom";
24
27
  export const LOOM_MANIFEST_SCHEMA = "https://loom.gadicc.local/project-manifest.schema.json";
@@ -30,24 +33,21 @@ export const LOOM_MANAGED_DEV_OVERRIDE_START = "# loom-managed:dev:start";
30
33
  export const LOOM_MANAGED_DEV_OVERRIDE_END = "# loom-managed:dev:end";
31
34
  export const LOOM_LOCAL_DEV_STATE_RELATIVE_PATH = ".loom/dev-state.json";
32
35
  export const LOOM_LOCAL_DEV_STATE_GITIGNORE_LINE = ".loom/dev-state.json";
36
+ /** Exclusive lock held while a local-dev sync checks, rebuilds, or installs. */
37
+ export const LOOM_LOCAL_DEV_LOCK_RELATIVE_PATH = ".loom/dev-sync.lock";
38
+ /** Ignores the sync lock and the short-lived lock that guards breaking it. */
39
+ export const LOOM_LOCAL_DEV_LOCK_GITIGNORE_LINE = ".loom/dev-sync.lock*";
40
+ /** Set for commands a sync runs, so nested Loom commands skip the sync. */
41
+ const LOOM_DEV_SYNC_ACTIVE_ENV = "LOOM_DEV_SYNC_ACTIVE";
33
42
  const DEFAULT_JOBS_MAX_DURATION_SECONDS = 1800;
34
43
  const LOOM_MANAGED_STATIC_JOB_ROUTE_MARKER = "// loom-managed:jobs-static-route";
35
44
  /** @deprecated Public npm installs no longer require project registry config. */
36
45
  export const LOOM_NPMRC_LINES = [];
37
- const LOOM_PACKAGE_RELEVANT_PATHS = [
38
- "LICENSE",
39
- "NOTICE",
40
- "README.md",
41
- "THIRD_PARTY_NOTICES.md",
42
- "bin",
43
- "deno.json",
44
- "deno.lock",
45
- "mod.ts",
46
- "runtime",
47
- "scripts/build_npm.ts",
48
- "skills",
49
- "src",
50
- ];
46
+ /**
47
+ * Exit status for a command that refreshed the linked local Loom package and
48
+ * stopped before running stale in-process Loom code (EX_TEMPFAIL: retry).
49
+ */
50
+ export const LOOM_LOCAL_DEV_RERUN_EXIT_CODE = 75;
51
51
  const PRODUCTION_GITHUB_ENVIRONMENT = "production";
52
52
  const REQUIRED_GITHUB_VERCEL_SECRET_NAMES = ["VERCEL_TOKEN"];
53
53
  const REQUIRED_GITHUB_VERCEL_ID_NAMES = [
@@ -319,14 +319,17 @@ async function writeTextIfChanged(path, text) {
319
319
  }
320
320
  export async function defaultCommandRunner(command, args, options) {
321
321
  return await new Promise((resolvePromise) => {
322
- const inherit = options.stdio === "inherit";
322
+ const inherit = options.stdio === "inherit" ||
323
+ options.stdio === "inherit-stderr";
323
324
  const pipeInput = !inherit && options.input !== undefined;
324
325
  const child = spawn(command, args, {
325
326
  cwd: options.cwd,
326
327
  env: options.env,
327
- stdio: inherit
328
- ? "inherit"
329
- : [pipeInput ? "pipe" : "ignore", "pipe", "pipe"],
328
+ stdio: options.stdio === "inherit-stderr"
329
+ ? ["inherit", 2, 2]
330
+ : inherit
331
+ ? "inherit"
332
+ : [pipeInput ? "pipe" : "ignore", "pipe", "pipe"],
330
333
  });
331
334
  const stdoutChunks = [];
332
335
  const stderrChunks = [];
@@ -612,6 +615,215 @@ function getPublishedLoomDependencySpec(packageJson) {
612
615
  }
613
616
  return dependency;
614
617
  }
618
+ function parseCatalogReference(spec) {
619
+ const match = spec?.match(/^catalog:(.*)$/);
620
+ return match ? match[1].trim() || "default" : null;
621
+ }
622
+ function parseYamlKeyLine(body) {
623
+ const match = body.match(/^(?:'([^']*)'|"([^"]*)"|([^\s#'"][^:]*?))\s*:(?:\s+(.*))?$/);
624
+ return match
625
+ ? { key: match[1] ?? match[2] ?? match[3], rest: match[4] ?? "" }
626
+ : null;
627
+ }
628
+ function isYamlBlockHeader(rest) {
629
+ return rest.trim() === "" || rest.trim().startsWith("#");
630
+ }
631
+ /**
632
+ * Returns the line indexes of the direct entries of the block map at `path`
633
+ * (for example `["catalogs", "loom"]`), or null when it is missing.
634
+ */
635
+ function findYamlBlockMapEntries(lines, path) {
636
+ let start = -1;
637
+ let end = lines.length;
638
+ for (const key of path) {
639
+ let childIndent = null;
640
+ let found = -1;
641
+ for (let index = start + 1; index < end; index += 1) {
642
+ const line = lines[index];
643
+ const trimmed = line.trim();
644
+ if (trimmed === "" || trimmed.startsWith("#"))
645
+ continue;
646
+ const indent = line.length - line.trimStart().length;
647
+ childIndent ??= indent;
648
+ if (indent !== childIndent)
649
+ continue;
650
+ const entry = parseYamlKeyLine(trimmed);
651
+ if (entry?.key === key && isYamlBlockHeader(entry.rest)) {
652
+ found = index;
653
+ break;
654
+ }
655
+ }
656
+ if (found === -1)
657
+ return null;
658
+ const headerIndent = lines[found].length - lines[found].trimStart().length;
659
+ start = found;
660
+ end = lines.length;
661
+ for (let index = found + 1; index < lines.length; index += 1) {
662
+ const line = lines[index];
663
+ const trimmed = line.trim();
664
+ if (trimmed === "" || trimmed.startsWith("#"))
665
+ continue;
666
+ if (line.length - line.trimStart().length <= headerIndent) {
667
+ end = index;
668
+ break;
669
+ }
670
+ }
671
+ }
672
+ const entries = [];
673
+ let childIndent = null;
674
+ for (let index = start + 1; index < end; index += 1) {
675
+ const line = lines[index];
676
+ const trimmed = line.trim();
677
+ if (trimmed === "" || trimmed.startsWith("#"))
678
+ continue;
679
+ const indent = line.length - line.trimStart().length;
680
+ childIndent ??= indent;
681
+ if (indent === childIndent)
682
+ entries.push(index);
683
+ }
684
+ return entries;
685
+ }
686
+ function splitYamlScalarComment(rest) {
687
+ const trimmed = rest.trim();
688
+ const quoted = trimmed.match(/^(['"])(.*?)\1(\s+#.*)?$/);
689
+ if (quoted) {
690
+ return { comment: quoted[3] ?? "", quote: quoted[1], value: quoted[2] };
691
+ }
692
+ const plain = trimmed.match(/^(.*?)(\s+#.*)?$/);
693
+ return { comment: plain[2] ?? "", quote: "", value: plain[1] };
694
+ }
695
+ function catalogPaths(catalog) {
696
+ // The default catalog may live under `catalog:` or `catalogs.default:`.
697
+ return catalog === "default"
698
+ ? [["catalog"], ["catalogs", "default"]]
699
+ : [["catalogs", catalog]];
700
+ }
701
+ /**
702
+ * Finds the line of the map at `path` when it is written as a flow map
703
+ * (`catalog: { ... }`), with its content when it fits on that line, or
704
+ * `unsupported` for flow maps Loom cannot read (multi-line or nested).
705
+ */
706
+ function findYamlFlowMapLine(lines, path) {
707
+ for (let depth = 0; depth < path.length; depth += 1) {
708
+ const parentEntries = findYamlBlockMapEntries(lines, path.slice(0, depth));
709
+ for (const line of parentEntries ?? []) {
710
+ const entry = parseYamlKeyLine(lines[line].trim());
711
+ if (entry?.key !== path[depth] || !entry.rest.trim().startsWith("{")) {
712
+ continue;
713
+ }
714
+ if (depth < path.length - 1)
715
+ return { line, unsupported: true };
716
+ const flow = entry.rest.trim().match(/^\{(.*)\}\s*(?:#.*)?$/);
717
+ return flow
718
+ ? { content: flow[1], line, unsupported: false }
719
+ : { line, unsupported: true };
720
+ }
721
+ }
722
+ return null;
723
+ }
724
+ function parseYamlFlowEntries(content) {
725
+ return content.split(",").flatMap((part) => {
726
+ const match = part.trim().match(/^(?:'([^']*)'|"([^"]*)"|([^:\s]+))\s*:\s*(.*?)\s*$/);
727
+ return match
728
+ ? [{
729
+ key: match[1] ?? match[2] ?? match[3],
730
+ value: splitYamlScalarComment(match[4]).value,
731
+ }]
732
+ : [];
733
+ });
734
+ }
735
+ /** Finds the Loom entry of a pnpm catalog in pnpm-workspace.yaml text. */
736
+ function findLoomCatalogEntry(workspaceText, catalog) {
737
+ if (!workspaceText)
738
+ return null;
739
+ const lines = normalizeText(workspaceText).split("\n");
740
+ for (const path of catalogPaths(catalog)) {
741
+ const label = `${path.join(".")}:`;
742
+ for (const line of findYamlBlockMapEntries(lines, path) ?? []) {
743
+ const entry = parseYamlKeyLine(lines[line].trim());
744
+ if (entry?.key !== LOOM_DEPENDENCY)
745
+ continue;
746
+ return {
747
+ catalog,
748
+ flow: false,
749
+ label,
750
+ line,
751
+ spec: splitYamlScalarComment(entry.rest).value,
752
+ };
753
+ }
754
+ const flow = findYamlFlowMapLine(lines, path);
755
+ if (flow && !flow.unsupported) {
756
+ const entry = parseYamlFlowEntries(flow.content).find((candidate) => candidate.key === LOOM_DEPENDENCY);
757
+ if (entry) {
758
+ return {
759
+ catalog,
760
+ flow: true,
761
+ label,
762
+ line: flow.line,
763
+ spec: entry.value,
764
+ };
765
+ }
766
+ }
767
+ }
768
+ return null;
769
+ }
770
+ /**
771
+ * Names a catalog that exists in a flow form Loom cannot read (multi-line
772
+ * or nested flow maps), so callers can say so instead of reporting a
773
+ * missing entry.
774
+ */
775
+ function findUnreadableLoomCatalog(workspaceText, catalog) {
776
+ if (!workspaceText)
777
+ return null;
778
+ const lines = normalizeText(workspaceText).split("\n");
779
+ for (const path of catalogPaths(catalog)) {
780
+ if (findYamlFlowMapLine(lines, path)?.unsupported) {
781
+ return `${path.join(".")}:`;
782
+ }
783
+ }
784
+ return null;
785
+ }
786
+ /** Rewrites a catalog entry's version, keeping its key, quotes, and comment. */
787
+ function setLoomCatalogEntryText(workspaceText, entry, spec) {
788
+ const lines = normalizeText(workspaceText).split("\n");
789
+ const line = lines[entry.line];
790
+ if (entry.flow) {
791
+ const pattern = /((['"]?)@gadicc\/loom\2\s*:\s*)(['"]?)([^,}'"]*?)\3(\s*[,}])/;
792
+ if (!pattern.test(line))
793
+ return null;
794
+ lines[entry.line] = line.replace(pattern, (_match, prefix, _key, quote, _value, after) => `${prefix}${quote}${spec}${quote}${after}`);
795
+ return lines.join("\n");
796
+ }
797
+ const colon = line.match(/^(\s*(?:'[^']*'|"[^"]*"|[^\s#'"][^:]*?)\s*:\s+)(.*)$/);
798
+ if (!colon)
799
+ return null;
800
+ const { comment, quote } = splitYamlScalarComment(colon[2]);
801
+ lines[entry.line] = `${colon[1]}${quote}${spec}${quote}${comment}`;
802
+ return lines.join("\n");
803
+ }
804
+ async function resolveLoomDependencySpec(cwd, packageJson, options = {}) {
805
+ const raw = packageJson.dependencies?.[LOOM_DEPENDENCY] ??
806
+ (options.includeDev
807
+ ? packageJson.devDependencies?.[LOOM_DEPENDENCY]
808
+ : undefined);
809
+ const catalogName = parseCatalogReference(raw);
810
+ if (!catalogName) {
811
+ return { catalogEntry: null, catalogName: null, effective: raw, raw };
812
+ }
813
+ const catalogEntry = findLoomCatalogEntry(await readTextIfExists(join(cwd, "pnpm-workspace.yaml")), catalogName);
814
+ return {
815
+ catalogEntry,
816
+ catalogName,
817
+ effective: catalogEntry?.spec,
818
+ raw,
819
+ };
820
+ }
821
+ /** Advice for moving a catalog-pinned Loom to `version`. */
822
+ function formatLoomCatalogPinAdvice(entry, catalogName, version) {
823
+ const map = entry?.label ??
824
+ (catalogName === "default" ? "catalog:" : `catalogs.${catalogName}:`);
825
+ return `Set ${LOOM_DEPENDENCY} to ${version} in the pnpm-workspace.yaml \`${map}\` map, then run \`pnpm install\` (\`pnpm add\` would replace the \`catalog:\` reference in package.json).`;
826
+ }
615
827
  function isLocalPackageSpec(spec) {
616
828
  return spec.startsWith("file:") || spec.startsWith("link:") ||
617
829
  spec.startsWith("workspace:");
@@ -823,19 +1035,20 @@ function ensureLinguiGitignoreText(existingText, generatedCatalogs) {
823
1035
  text: nextText,
824
1036
  };
825
1037
  }
826
- function loomDevStateGitignoreLineMatches(line) {
1038
+ function loomDevGitignoreLineMatches(line, path) {
827
1039
  const normalized = line.trim().replace(/^\/?/, "");
828
- return normalized === LOOM_LOCAL_DEV_STATE_GITIGNORE_LINE ||
829
- normalized === ".loom/" || normalized === ".loom";
1040
+ return normalized === path || normalized === ".loom/" ||
1041
+ normalized === ".loom";
830
1042
  }
831
1043
  function ensureLoomDevStateGitignoreText(existingText) {
832
1044
  const normalized = existingText ? normalizeText(existingText) : "";
833
1045
  const lines = normalized
834
1046
  .split("\n")
835
1047
  .filter((line, index, array) => index < array.length - 1 || line !== "");
836
- const missingLines = lines.some(loomDevStateGitignoreLineMatches)
837
- ? []
838
- : [LOOM_LOCAL_DEV_STATE_GITIGNORE_LINE];
1048
+ const missingLines = [
1049
+ LOOM_LOCAL_DEV_STATE_GITIGNORE_LINE,
1050
+ LOOM_LOCAL_DEV_LOCK_GITIGNORE_LINE,
1051
+ ].filter((path) => !lines.some((line) => loomDevGitignoreLineMatches(line, path)));
839
1052
  const nextText = missingLines.length
840
1053
  ? `${[...lines, ...missingLines].join("\n")}\n`
841
1054
  : normalized;
@@ -1184,18 +1397,34 @@ function dependencyExecutable(tooling, executable) {
1184
1397
  return `yarn ${executable}`;
1185
1398
  }
1186
1399
  }
1187
- function dependencyRefreshCommand(tooling, name, version) {
1400
+ /**
1401
+ * Command that moves one dependency to the given version without
1402
+ * re-resolving anything else. For pnpm, `pnpm add --save-exact` pins
1403
+ * package.json, replaces a local lockfile resolution left by an older
1404
+ * `pnpm update --no-save` link, and keeps every other locked version
1405
+ * (verified with pnpm 10.17); `pnpm update` would re-resolve the
1406
+ * dependency's subtree. Ranges get a plain install because `pnpm add`
1407
+ * rewrites a range's lower bound.
1408
+ */
1409
+ function dependencyRefreshCommand(tooling, name, version, options = {}) {
1188
1410
  switch (tooling.manager) {
1189
1411
  case "deno":
1190
1412
  return "deno install";
1191
1413
  case "npm":
1192
1414
  return `npm install --save-exact ${name}@${version}`;
1193
1415
  case "pnpm":
1194
- return `pnpm update --no-save ${name}@${version} && pnpm install`;
1416
+ return isExactSemverVersion(version)
1417
+ ? `pnpm add${options.pnpmWorkspaceRoot ? " -w" : ""} --save-exact ${name}@${version}`
1418
+ : "pnpm install";
1195
1419
  case "yarn":
1196
1420
  return `yarn add --exact ${name}@${version}`;
1197
1421
  }
1198
1422
  }
1423
+ /** Whether pnpm treats this project root as a workspace root with packages. */
1424
+ async function pnpmWorkspaceDeclaresPackages(cwd) {
1425
+ const text = await readTextIfExists(join(cwd, "pnpm-workspace.yaml"));
1426
+ return text !== null && /^packages:/m.test(normalizeText(text));
1427
+ }
1199
1428
  function getDbExpectedScripts(config, tooling) {
1200
1429
  const drizzleKit = dependencyExecutable(tooling.dependencies, "drizzle-kit");
1201
1430
  return {
@@ -1685,6 +1914,10 @@ function getApiKeysConfig(framework, dbConfig, packageJson, featureConfig) {
1685
1914
  ? "src/api-lib/apiKeys"
1686
1915
  : "api-lib/apiKeys";
1687
1916
  return {
1917
+ // Recorded by the app; Loom never infers or rewrites this choice.
1918
+ ...(featureConfig?.betterAuthHttpEndpoints !== undefined
1919
+ ? { betterAuthHttpEndpoints: featureConfig.betterAuthHttpEndpoints }
1920
+ : {}),
1688
1921
  entrypoints: {
1689
1922
  adminPage: featureConfig?.entrypoints?.adminPage ??
1690
1923
  `${appRoot}/admin/api-keys/page.tsx`,
@@ -1901,7 +2134,7 @@ export function ensureNextAgentsMdText(existingText) {
1901
2134
  : "\n\n"}${block}`;
1902
2135
  return { changed: text !== normalized, text };
1903
2136
  }
1904
- function getManagedDevOverrideBlock(overrideSpec, state) {
2137
+ function getManagedDevOverrideBlock(overrideSpec, state, layout = {}) {
1905
2138
  // This is a workaround for current pnpm behavior around local package
1906
2139
  // development. In testing with pnpm 10.x, direct `pnpm link` against Loom
1907
2140
  // mutated pnpm-workspace overrides anyway and broke peer resolution from
@@ -1920,13 +2153,32 @@ function getManagedDevOverrideBlock(overrideSpec, state) {
1920
2153
  : null,
1921
2154
  ].filter((line) => line !== null)
1922
2155
  : [];
2156
+ const pad = " ".repeat(layout.indent ?? 2);
1923
2157
  return [
1924
- ` ${LOOM_MANAGED_DEV_OVERRIDE_START}`,
1925
- ...stateLines.map((line) => ` ${line}`),
1926
- ` "${LOOM_DEPENDENCY}": ${JSON.stringify(overrideSpec)}`,
1927
- ` ${LOOM_MANAGED_DEV_OVERRIDE_END}`,
2158
+ `${pad}${LOOM_MANAGED_DEV_OVERRIDE_START}`,
2159
+ ...(layout.createdHeader === undefined ? [] : [
2160
+ `${pad}# overrides-header: ${layout.createdHeader ? "created" : "existing"}`,
2161
+ ]),
2162
+ ...(layout.replacedHeader
2163
+ ? [`${pad}# replaced-header: ${layout.replacedHeader}`]
2164
+ : []),
2165
+ ...stateLines.map((line) => `${pad}${line}`),
2166
+ `${pad}"${LOOM_DEPENDENCY}": ${JSON.stringify(overrideSpec)}`,
2167
+ `${pad}${LOOM_MANAGED_DEV_OVERRIDE_END}`,
1928
2168
  ].join("\n");
1929
2169
  }
2170
+ /** Reads the layout markers and indentation of an existing managed block. */
2171
+ function getManagedDevOverrideBlockLayout(blockText) {
2172
+ if (!blockText)
2173
+ return {};
2174
+ const header = getManagedDevStateValue(blockText, "overrides-header");
2175
+ return {
2176
+ // Blocks from before this marker always removed an empty bare header.
2177
+ createdHeader: header === undefined ? undefined : header === "created",
2178
+ indent: blockText.length - blockText.trimStart().length,
2179
+ replacedHeader: getManagedDevStateValue(blockText, "replaced-header"),
2180
+ };
2181
+ }
1930
2182
  function getManagedDevOverrideBlockRegex() {
1931
2183
  return new RegExp(`^[ \\t]*${escapeRegExp(LOOM_MANAGED_DEV_OVERRIDE_START)}\\n[\\s\\S]*?^[ \\t]*${escapeRegExp(LOOM_MANAGED_DEV_OVERRIDE_END)}\\n?`, "m");
1932
2184
  }
@@ -1936,24 +2188,149 @@ function formatYamlLines(lines) {
1936
2188
  }
1937
2189
  return lines.length ? `${lines.join("\n")}\n` : "";
1938
2190
  }
1939
- function findTopLevelSection(lines, sectionName) {
1940
- const header = `${sectionName}:`;
1941
- const start = lines.findIndex((line) => line === header);
1942
- if (start === -1) {
2191
+ const OVERRIDES_KEY_PATTERN = /^(?:overrides|"overrides"|'overrides'):(?:\s|$)/;
2192
+ /**
2193
+ * Locates the top-level `overrides:` key (plain or quoted) of
2194
+ * pnpm-workspace.yaml lines and how its value is written: a block map
2195
+ * (`overrides:`, optionally with a comment), an empty flow map
2196
+ * (`overrides: {}`), or another flow/scalar form Loom cannot add entries
2197
+ * to. `end` is the index of the next top-level key and `indent` the
2198
+ * indentation of the map's entries.
2199
+ */
2200
+ function findPnpmWorkspaceOverridesHeader(lines) {
2201
+ const index = lines.findIndex((line) => OVERRIDES_KEY_PATTERN.test(line));
2202
+ if (index === -1)
1943
2203
  return null;
1944
- }
2204
+ const value = lines[index].slice(lines[index].indexOf(":") + 1).trim();
2205
+ const style = value === "" || value.startsWith("#")
2206
+ ? "block"
2207
+ : /^\{\s*\}\s*(?:#.*)?$/.test(value)
2208
+ ? "empty-flow"
2209
+ : "other";
1945
2210
  let end = lines.length;
1946
- for (let index = start + 1; index < lines.length; index += 1) {
1947
- const line = lines[index];
1948
- if (line !== "" && !line.startsWith(" ") && !line.startsWith("\t")) {
1949
- end = index;
2211
+ let indent = null;
2212
+ for (let line = index + 1; line < lines.length; line += 1) {
2213
+ const trimmed = lines[line].trim();
2214
+ if (trimmed === "" || trimmed.startsWith("#"))
2215
+ continue;
2216
+ if (!/^\s/.test(lines[line])) {
2217
+ end = line;
2218
+ break;
2219
+ }
2220
+ indent ??= lines[line].length - lines[line].trimStart().length;
2221
+ }
2222
+ return { end, indent: indent ?? 2, index, style };
2223
+ }
2224
+ /**
2225
+ * Lists the keys of the top-level `overrides:` map in pnpm-workspace.yaml
2226
+ * text, in block or single-line flow style. Other maps that can mention
2227
+ * Loom, such as `catalog:` and `catalogs:`, are not overrides.
2228
+ */
2229
+ function getPnpmWorkspaceOverrideKeys(text) {
2230
+ const lines = normalizeText(text).split("\n");
2231
+ const start = findPnpmWorkspaceOverridesHeader(lines)?.index ?? -1;
2232
+ if (start === -1)
2233
+ return [];
2234
+ const flow = lines[start].slice(lines[start].indexOf(":") + 1).match(/^\s*\{(.*)\}\s*(?:#.*)?$/);
2235
+ if (flow) {
2236
+ return flow[1].split(",").flatMap((entry) => {
2237
+ const match = entry.trim().match(/^(?:'([^']*)'|"([^"]*)"|([^:]+?))\s*:/);
2238
+ return match ? [match[1] ?? match[2] ?? match[3]] : [];
2239
+ });
2240
+ }
2241
+ const keys = [];
2242
+ let indent = null;
2243
+ for (const line of lines.slice(start + 1)) {
2244
+ const trimmed = line.trim();
2245
+ if (trimmed === "" || trimmed.startsWith("#"))
2246
+ continue;
2247
+ // The next top-level key ends the map.
2248
+ if (!/^\s/.test(line))
1950
2249
  break;
2250
+ const lineIndent = line.length - line.trimStart().length;
2251
+ indent ??= lineIndent;
2252
+ if (lineIndent !== indent)
2253
+ continue;
2254
+ const match = trimmed.match(/^(?:'([^']+)'|"([^"]+)"|([^\s#'"][^:]*?))\s*:(?:\s|$)/);
2255
+ if (match)
2256
+ keys.push(match[1] ?? match[2] ?? match[3]);
2257
+ }
2258
+ return keys;
2259
+ }
2260
+ /** A YAML scalar without quotes or a trailing comment. */
2261
+ function plainYamlValue(value) {
2262
+ const trimmed = value.trim();
2263
+ if (/^["']/.test(trimmed)) {
2264
+ const quote = trimmed[0];
2265
+ const end = trimmed.indexOf(quote, 1);
2266
+ return end === -1 ? trimmed.slice(1) : trimmed.slice(1, end);
2267
+ }
2268
+ return trimmed.replace(/\s+#.*$/, "").trim();
2269
+ }
2270
+ /**
2271
+ * Local (`file:`/`link:`) Loom entries of the pnpm-workspace.yaml
2272
+ * `overrides:` map outside Loom's managed block, such as one written by
2273
+ * hand. `line` is the entry's line in `text` once the managed block is
2274
+ * removed, or null in flow style, which Loom does not edit.
2275
+ */
2276
+ function getUnmanagedPnpmWorkspaceLoomOverrides(text) {
2277
+ const entries = [];
2278
+ if (!text)
2279
+ return entries;
2280
+ const lines = normalizeText(text).replace(getManagedDevOverrideBlockRegex(), "").split("\n");
2281
+ const header = findPnpmWorkspaceOverridesHeader(lines);
2282
+ if (!header)
2283
+ return entries;
2284
+ const add = (key, value, line) => {
2285
+ const spec = plainYamlValue(value);
2286
+ if (overrideKeyTargetsLoom(key) && /^(?:file|link):/.test(spec)) {
2287
+ entries.push({ key, line, spec });
2288
+ }
2289
+ };
2290
+ const flow = lines[header.index].slice(lines[header.index].indexOf(":") + 1)
2291
+ .match(/^\s*\{(.*)\}\s*(?:#.*)?$/);
2292
+ if (flow) {
2293
+ for (const entry of flow[1].split(",")) {
2294
+ const match = entry.trim().match(/^(?:'([^']*)'|"([^"]*)"|([^:]+?))\s*:\s*(.*)$/);
2295
+ if (match)
2296
+ add(match[1] ?? match[2] ?? match[3], match[4], null);
1951
2297
  }
2298
+ return entries;
2299
+ }
2300
+ for (let index = header.index + 1; index < header.end; index += 1) {
2301
+ const line = lines[index];
2302
+ if (line.length - line.trimStart().length !== header.indent)
2303
+ continue;
2304
+ const match = line.trim().match(/^(?:'([^']+)'|"([^"]+)"|([^\s#'"][^:]*?))\s*:\s+(\S.*)$/);
2305
+ if (match)
2306
+ add(match[1] ?? match[2] ?? match[3], match[4], index);
2307
+ }
2308
+ return entries;
2309
+ }
2310
+ /**
2311
+ * Removes the block-style entries {@link getUnmanagedPnpmWorkspaceLoomOverrides}
2312
+ * finds, and a bare `overrides:` header left without entries. Expects text
2313
+ * without Loom's managed block. Flow-style entries stay and are returned.
2314
+ */
2315
+ function removeUnmanagedPnpmWorkspaceLoomOverrides(text) {
2316
+ const entries = getUnmanagedPnpmWorkspaceLoomOverrides(text);
2317
+ const lines = normalizeText(text).split("\n");
2318
+ const removable = new Set(entries.flatMap((entry) => entry.line === null ? [] : [entry.line]));
2319
+ const kept = lines.filter((_, index) => !removable.has(index));
2320
+ const header = findPnpmWorkspaceOverridesHeader(kept);
2321
+ if (removable.size && header?.style === "block" &&
2322
+ kept[header.index] === "overrides:" &&
2323
+ !hasYamlEntries(kept.slice(header.index + 1, header.end))) {
2324
+ kept.splice(header.index, 1);
1952
2325
  }
1953
- return { end, start };
2326
+ return {
2327
+ changed: removable.size > 0,
2328
+ kept: entries.filter((entry) => entry.line === null),
2329
+ text: formatYamlLines(kept).replace(/\n{3,}/g, "\n\n"),
2330
+ };
1954
2331
  }
1955
2332
  function hasUnmanagedLoomOverride(text) {
1956
- return /^[ \t]+["']?@gadicc\/loom["']?\s*:/m.test(text);
2333
+ return getPnpmWorkspaceOverrideKeys(text).some(overrideKeyTargetsLoom);
1957
2334
  }
1958
2335
  function getManagedDevOverrideSpec(text) {
1959
2336
  if (!text) {
@@ -2003,7 +2380,7 @@ function getManagedDevState(text) {
2003
2380
  }
2004
2381
  function setManagedDevStateText(existingText, overrideSpec, state) {
2005
2382
  const normalized = existingText ? normalizeText(existingText) : "";
2006
- const nextText = normalized.replace(getManagedDevOverrideBlockRegex(), `${getManagedDevOverrideBlock(overrideSpec, state)}\n`);
2383
+ const nextText = normalized.replace(getManagedDevOverrideBlockRegex(), `${getManagedDevOverrideBlock(overrideSpec, state, getManagedDevOverrideBlockLayout(getManagedDevOverrideBlockText(normalized)))}\n`);
2007
2384
  return {
2008
2385
  changed: nextText !== normalized,
2009
2386
  text: nextText,
@@ -2032,17 +2409,45 @@ export function ensurePnpmWorkspaceLocalDevText(existingText, overrideSpec) {
2032
2409
  text: normalized,
2033
2410
  };
2034
2411
  }
2035
- const blockLines = getManagedDevOverrideBlock(overrideSpec).split("\n");
2036
2412
  const lines = baseText === "" ? [] : baseText.replace(/\n$/, "").split("\n");
2037
- const overridesSection = findTopLevelSection(lines, "overrides");
2038
- if (overridesSection) {
2039
- lines.splice(overridesSection.start + 1, 0, ...blockLines);
2413
+ const header = findPnpmWorkspaceOverridesHeader(lines);
2414
+ // Relinking: put back the `overrides: {}` line an earlier link rewrote.
2415
+ const previous = getManagedDevOverrideBlockLayout(getManagedDevOverrideBlockText(normalized));
2416
+ if (header && previous.replacedHeader && lines[header.index] === "overrides:" &&
2417
+ !hasYamlEntries(lines.slice(header.index + 1, header.end))) {
2418
+ lines[header.index] = previous.replacedHeader;
2419
+ }
2420
+ const current = findPnpmWorkspaceOverridesHeader(lines);
2421
+ if (current?.style === "other") {
2422
+ return {
2423
+ changed: false,
2424
+ conflict: "pnpm-workspace.yaml writes `overrides` as a flow map or scalar. Rewrite it as a block map, one `name: version` entry per line under `overrides:`, so Loom can add its managed override.",
2425
+ text: normalized,
2426
+ };
2427
+ }
2428
+ if (current) {
2429
+ const replacedHeader = current.style === "empty-flow"
2430
+ ? lines[current.index]
2431
+ : undefined;
2432
+ if (replacedHeader)
2433
+ lines[current.index] = "overrides:";
2434
+ lines.splice(current.index + 1, 0, ...getManagedDevOverrideBlock(overrideSpec, undefined, {
2435
+ // A relink keeps what the first link recorded about the header,
2436
+ // including nothing at all for blocks written before the marker.
2437
+ createdHeader: previous.indent === undefined
2438
+ ? false
2439
+ : previous.createdHeader,
2440
+ indent: current.style === "block" ? current.indent : 2,
2441
+ replacedHeader,
2442
+ }).split("\n"));
2040
2443
  }
2041
2444
  else {
2042
2445
  if (lines.length && lines.at(-1) !== "") {
2043
2446
  lines.push("");
2044
2447
  }
2045
- lines.push("overrides:", ...blockLines);
2448
+ lines.push("overrides:", ...getManagedDevOverrideBlock(overrideSpec, undefined, {
2449
+ createdHeader: true,
2450
+ }).split("\n"));
2046
2451
  }
2047
2452
  const nextText = formatYamlLines(lines);
2048
2453
  return {
@@ -2059,19 +2464,21 @@ export function clearPnpmWorkspaceLocalDevText(existingText) {
2059
2464
  text: normalized,
2060
2465
  };
2061
2466
  }
2467
+ const { createdHeader, replacedHeader } = getManagedDevOverrideBlockLayout(getManagedDevOverrideBlockText(normalized));
2062
2468
  const withoutManaged = normalized.replace(getManagedDevOverrideBlockRegex(), "");
2063
2469
  const lines = withoutManaged === ""
2064
2470
  ? []
2065
2471
  : withoutManaged.replace(/\n$/, "").split("\n");
2066
- const overridesSection = findTopLevelSection(lines, "overrides");
2067
- if (overridesSection) {
2068
- const bodyLines = lines.slice(overridesSection.start + 1, overridesSection.end);
2069
- const hasEntries = bodyLines.some((line) => {
2070
- const trimmed = line.trim();
2071
- return trimmed !== "" && !trimmed.startsWith("#");
2072
- });
2073
- if (!hasEntries) {
2074
- lines.splice(overridesSection.start, overridesSection.end - overridesSection.start);
2472
+ const header = findPnpmWorkspaceOverridesHeader(lines);
2473
+ if (header?.style === "block" &&
2474
+ !hasYamlEntries(lines.slice(header.index + 1, header.end))) {
2475
+ if (replacedHeader) {
2476
+ lines[header.index] = replacedHeader;
2477
+ }
2478
+ else if (createdHeader ??
2479
+ // Older blocks did not record it; Loom only added bare headers.
2480
+ lines[header.index] === "overrides:") {
2481
+ lines.splice(header.index, header.end - header.index);
2075
2482
  }
2076
2483
  }
2077
2484
  const nextText = formatYamlLines(lines).replace(/\n{3,}/g, "\n\n");
@@ -2080,6 +2487,262 @@ export function clearPnpmWorkspaceLocalDevText(existingText) {
2080
2487
  text: nextText,
2081
2488
  };
2082
2489
  }
2490
+ const PACKAGE_JSON_OVERRIDE_LOCATIONS = [
2491
+ { field: "resolutions", location: "package.json#resolutions" },
2492
+ { field: "pnpm.overrides", location: "package.json#pnpm.overrides" },
2493
+ ];
2494
+ function formatPnpmOverrideLocation(location) {
2495
+ switch (location) {
2496
+ case "package.json#pnpm.overrides":
2497
+ return "package.json pnpm.overrides";
2498
+ case "package.json#resolutions":
2499
+ return "package.json resolutions";
2500
+ case "pnpm-workspace.yaml":
2501
+ return "pnpm-workspace.yaml";
2502
+ }
2503
+ }
2504
+ function getPackageJsonOverrideMap(packageJson, field) {
2505
+ const value = field === "resolutions"
2506
+ ? packageJson.resolutions
2507
+ : packageJson.pnpm?.overrides;
2508
+ return value && typeof value === "object" && !Array.isArray(value)
2509
+ ? value
2510
+ : {};
2511
+ }
2512
+ function isManagedPackageJsonLoomOverride(spec) {
2513
+ return typeof spec === "string" && spec.startsWith("file:");
2514
+ }
2515
+ /**
2516
+ * Lists local `file:` Loom overrides in package.json override maps. Loom only
2517
+ * writes `file:` specs there, and a local spec is never shippable, so these
2518
+ * entries are treated as the managed local-dev override.
2519
+ */
2520
+ function getPackageJsonLocalLoomOverrides(packageJson) {
2521
+ return PACKAGE_JSON_OVERRIDE_LOCATIONS.flatMap(({ field, location }) => {
2522
+ const spec = getPackageJsonOverrideMap(packageJson, field)[LOOM_DEPENDENCY];
2523
+ return isManagedPackageJsonLoomOverride(spec) ? [{ location, spec }] : [];
2524
+ });
2525
+ }
2526
+ /** Returns the managed local Loom override of a pnpm project, if active. */
2527
+ function getActivePnpmLocalDevOverride(workspaceText, packageJson) {
2528
+ const workspaceSpec = getManagedDevOverrideSpec(workspaceText);
2529
+ if (workspaceSpec) {
2530
+ return { location: "pnpm-workspace.yaml", spec: workspaceSpec };
2531
+ }
2532
+ return getPackageJsonLocalLoomOverrides(packageJson)[0] ?? null;
2533
+ }
2534
+ function getUnmanagedPnpmWorkspaceOverrideNames(text) {
2535
+ const normalized = text ? normalizeText(text) : "";
2536
+ return getPnpmWorkspaceOverrideKeys(normalized.replace(getManagedDevOverrideBlockRegex(), ""));
2537
+ }
2538
+ /** First pnpm release that reads `overrides` from pnpm-workspace.yaml. */
2539
+ const PNPM_WORKSPACE_OVERRIDES_SINCE = [10, 5, 1];
2540
+ function parsePnpmVersion(value) {
2541
+ const match = value?.match(/^(\d+)\.(\d+)\.(\d+)/);
2542
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
2543
+ }
2544
+ function pnpmVersionAtLeast(version, minimum) {
2545
+ for (let index = 0; index < 3; index += 1) {
2546
+ if (version[index] !== minimum[index]) {
2547
+ return version[index] > minimum[index];
2548
+ }
2549
+ }
2550
+ return true;
2551
+ }
2552
+ async function detectPnpmVersion(cwd, packageJson, commandRunner, env) {
2553
+ const declared = parsePnpmVersion(packageJson.packageManager?.match(/^pnpm@(.+)$/)?.[1]);
2554
+ if (declared)
2555
+ return declared;
2556
+ // Not npm_config_user_agent: it names the pnpm running the current
2557
+ // script, which can differ from the `pnpm` this process spawns (a pnpm
2558
+ // devDependency in node_modules/.bin, say).
2559
+ const cached = spawnedPnpmVersions.get(commandRunner)?.get(cwd);
2560
+ if (cached)
2561
+ return await cached;
2562
+ const pending = detectSpawnedPnpmVersion(cwd, commandRunner, env);
2563
+ const byCwd = spawnedPnpmVersions.get(commandRunner) ?? new Map();
2564
+ byCwd.set(cwd, pending);
2565
+ spawnedPnpmVersions.set(commandRunner, byCwd);
2566
+ return await pending;
2567
+ }
2568
+ /**
2569
+ * `pnpm --version` results for this process, per command runner and
2570
+ * project, so one command spawns pnpm at most once per project.
2571
+ */
2572
+ const spawnedPnpmVersions = new WeakMap();
2573
+ async function detectSpawnedPnpmVersion(cwd, commandRunner, env) {
2574
+ const result = await commandRunner("pnpm", ["--version"], { cwd, env })
2575
+ .catch(() => null);
2576
+ const running = result?.code === 0
2577
+ ? parsePnpmVersion(result.stdout.trim())
2578
+ : null;
2579
+ if (running)
2580
+ return running;
2581
+ // The pnpm that last installed node_modules, when pnpm itself cannot run.
2582
+ const modules = await readTextIfExists(join(cwd, "node_modules", ".modules.yaml"));
2583
+ return parsePnpmVersion(modules?.match(/^\s*"?packageManager"?\s*:\s*"?pnpm@([^"\s]+)/m)?.[1]);
2584
+ }
2585
+ /**
2586
+ * Chooses the override map pnpm will actually apply. Verified with real
2587
+ * pnpm 9.7.0 through 11.25.0 on a local directory override:
2588
+ * - before 10.5.1, pnpm reads overrides only from package.json `resolutions`
2589
+ * and `pnpm.overrides` (Loom creates `resolutions` when neither exists);
2590
+ * - from 10.5.1, pnpm also reads pnpm-workspace.yaml `overrides`, but only
2591
+ * while both package.json maps are empty, never merged with them;
2592
+ * - pnpm 11 reads only pnpm-workspace.yaml `overrides`.
2593
+ * Writing the override anywhere else leaves pnpm reporting an up-to-date
2594
+ * lockfile that still resolves the published package. An unknown version is
2595
+ * treated as pnpm 10.5.1 or newer.
2596
+ */
2597
+ async function resolvePnpmLocalDevOverrideLocation(cwd, packageJson, commandRunner, env) {
2598
+ const workspaceText = await readTextIfExists(join(cwd, "pnpm-workspace.yaml"));
2599
+ const workspaceBase = workspaceText
2600
+ ? normalizeText(workspaceText).replace(getManagedDevOverrideBlockRegex(), "")
2601
+ : "";
2602
+ const version = await detectPnpmVersion(cwd, packageJson, commandRunner, env);
2603
+ const pnpmVersion = version ? version.join(".") : null;
2604
+ const pnpmMajor = version ? version[0] : null;
2605
+ const pnpmLabel = pnpmVersion ? `pnpm ${pnpmVersion}` : "pnpm 10";
2606
+ const workspace = {
2607
+ conflict: hasUnmanagedLoomOverride(workspaceBase)
2608
+ ? `pnpm-workspace.yaml already defines an unmanaged override for ${LOOM_DEPENDENCY}. Move that override aside before enabling loom local-dev mode.`
2609
+ : null,
2610
+ location: "pnpm-workspace.yaml",
2611
+ notes: [],
2612
+ pnpmMajor,
2613
+ pnpmVersion,
2614
+ };
2615
+ const packageJsonEntries = PACKAGE_JSON_OVERRIDE_LOCATIONS.map(({ field, location }) => {
2616
+ const map = getPackageJsonOverrideMap(packageJson, field);
2617
+ return {
2618
+ loomSpec: map[LOOM_DEPENDENCY],
2619
+ location,
2620
+ names: Object.keys(map).filter((name) => !(name === LOOM_DEPENDENCY &&
2621
+ isManagedPackageJsonLoomOverride(map[name]))),
2622
+ };
2623
+ });
2624
+ const packageJsonHasOverrides = packageJsonEntries.some((entry) => entry.names.length > 0);
2625
+ if (pnpmMajor !== null && pnpmMajor >= 11) {
2626
+ return {
2627
+ ...workspace,
2628
+ notes: packageJsonHasOverrides
2629
+ ? [
2630
+ `pnpm ${pnpmVersion} ignores package.json resolutions and pnpm.overrides, so the Loom override stays in pnpm-workspace.yaml. Move any of those package.json entries the project still needs into pnpm-workspace.yaml overrides.`,
2631
+ ]
2632
+ : [],
2633
+ };
2634
+ }
2635
+ const readsWorkspaceOverrides = version === null ||
2636
+ pnpmVersionAtLeast(version, PNPM_WORKSPACE_OVERRIDES_SINCE);
2637
+ if (readsWorkspaceOverrides && !packageJsonHasOverrides)
2638
+ return workspace;
2639
+ const unmanagedLoom = packageJsonEntries.find((entry) => entry.loomSpec !== undefined &&
2640
+ !isManagedPackageJsonLoomOverride(entry.loomSpec));
2641
+ // pnpm 10 merges both package.json maps, so an override already in one of
2642
+ // them stays put rather than moving whenever the user edits the other.
2643
+ const location = packageJsonEntries.find((entry) => isManagedPackageJsonLoomOverride(entry.loomSpec))?.location ??
2644
+ packageJsonEntries.find((entry) => entry.names.length)?.location ??
2645
+ "package.json#resolutions";
2646
+ const label = formatPnpmOverrideLocation(location);
2647
+ const notes = [
2648
+ readsWorkspaceOverrides
2649
+ ? `${pnpmLabel} applies package.json resolutions/pnpm.overrides instead of pnpm-workspace.yaml overrides while either has entries, so the Loom override is kept in ${label}. Do not commit it; \`loom dev published\` removes it.`
2650
+ : `${pnpmLabel} reads overrides only from package.json (pnpm-workspace.yaml overrides need pnpm ${PNPM_WORKSPACE_OVERRIDES_SINCE.join(".")} or newer), so the Loom override is kept in ${label}. Do not commit it; \`loom dev published\` removes it.`,
2651
+ ];
2652
+ const ignoredWorkspaceNames = getUnmanagedPnpmWorkspaceOverrideNames(workspaceText);
2653
+ if (ignoredWorkspaceNames.length) {
2654
+ notes.push(`${pnpmLabel} also ignores these pnpm-workspace.yaml overrides: ${ignoredWorkspaceNames.join(", ")}. Keep all overrides in one place.`);
2655
+ }
2656
+ return {
2657
+ conflict: workspace.conflict ??
2658
+ (unmanagedLoom
2659
+ ? `${formatPnpmOverrideLocation(unmanagedLoom.location)} already defines an unmanaged override for ${LOOM_DEPENDENCY} (${String(unmanagedLoom.loomSpec)}). Move that override aside before enabling loom local-dev mode.`
2660
+ : null),
2661
+ location,
2662
+ notes,
2663
+ pnpmMajor,
2664
+ pnpmVersion,
2665
+ };
2666
+ }
2667
+ /**
2668
+ * Writes the managed override at one location, then removes managed
2669
+ * overrides from every other location, so pnpm sees exactly one Loom
2670
+ * override and an interrupted move never leaves none. An existing workspace
2671
+ * block for the same spec is kept with its sync state.
2672
+ */
2673
+ async function placePnpmLocalDevOverride(cwd, overrideSpec, location) {
2674
+ const changedFiles = new Set();
2675
+ const workspacePath = join(cwd, "pnpm-workspace.yaml");
2676
+ const setPackageJsonOverride = async (field, value) => {
2677
+ const update = await mutatePackageJsonOverride(cwd, field, LOOM_DEPENDENCY, value);
2678
+ if (update.changed)
2679
+ changedFiles.add("package.json");
2680
+ };
2681
+ const workspaceText = await readTextIfExists(workspacePath);
2682
+ if (location === "pnpm-workspace.yaml") {
2683
+ if (getManagedDevOverrideSpec(workspaceText) !== overrideSpec) {
2684
+ const update = ensurePnpmWorkspaceLocalDevText(workspaceText, overrideSpec);
2685
+ if (update.conflict)
2686
+ throw new Error(update.conflict);
2687
+ if (update.changed) {
2688
+ await writeTextOrDeleteIfEmpty(workspacePath, update.text);
2689
+ changedFiles.add("pnpm-workspace.yaml");
2690
+ }
2691
+ }
2692
+ }
2693
+ else {
2694
+ const target = PACKAGE_JSON_OVERRIDE_LOCATIONS.find((entry) => entry.location === location);
2695
+ const { packageJson } = await readProjectPackageJson(cwd);
2696
+ // Record, before writing, whether Loom is about to create the map (and
2697
+ // the `pnpm` object), so unlinking removes exactly what Loom added.
2698
+ const created = await readCreatedPackageJsonMaps(cwd);
2699
+ const pnpmField = target.field === "pnpm.overrides";
2700
+ if (getRawPackageJsonMap(packageJson, target.field) === undefined) {
2701
+ created[target.field] = true;
2702
+ if (pnpmField)
2703
+ created.pnpm = packageJson.pnpm === undefined;
2704
+ }
2705
+ else if (!isManagedPackageJsonLoomOverride(getPackageJsonOverrideMap(packageJson, target.field)[LOOM_DEPENDENCY])) {
2706
+ // A map without Loom's entry belongs to the project, even if an
2707
+ // earlier link created it: the user may have dropped Loom's entry by
2708
+ // hand and committed a map of their own since.
2709
+ created[target.field] = false;
2710
+ if (pnpmField)
2711
+ created.pnpm = false;
2712
+ }
2713
+ await setPackageJsonOverride(target.field, overrideSpec);
2714
+ await writeCreatedPackageJsonMaps(cwd, created, overrideSpec);
2715
+ }
2716
+ for (const { field, location: fieldLocation } of PACKAGE_JSON_OVERRIDE_LOCATIONS) {
2717
+ if (fieldLocation === location)
2718
+ continue;
2719
+ if (await removePackageJsonLoomOverride(cwd, field)) {
2720
+ changedFiles.add("package.json");
2721
+ }
2722
+ }
2723
+ if (location !== "pnpm-workspace.yaml") {
2724
+ const update = clearPnpmWorkspaceLocalDevText(await readTextIfExists(workspacePath));
2725
+ if (update.changed) {
2726
+ await writeTextOrDeleteIfEmpty(workspacePath, update.text);
2727
+ changedFiles.add("pnpm-workspace.yaml");
2728
+ }
2729
+ }
2730
+ return [...changedFiles];
2731
+ }
2732
+ /**
2733
+ * Proves that pnpm applied the managed override: pnpm records the override
2734
+ * map it actually used in the lockfile's top-level `overrides:` section.
2735
+ */
2736
+ function lockfileAppliesLocalDevOverride(lockfileText, overrideSpec) {
2737
+ return lockfileText !== null &&
2738
+ getLockfileOverride(lockfileText, LOOM_DEPENDENCY) === overrideSpec;
2739
+ }
2740
+ function hasYamlEntries(lines) {
2741
+ return lines.some((line) => {
2742
+ const trimmed = line.trim();
2743
+ return trimmed !== "" && !trimmed.startsWith("#");
2744
+ });
2745
+ }
2083
2746
  function pnpmWorkspaceExcludesMinimumReleaseAge(text, dependency) {
2084
2747
  if (!text)
2085
2748
  return false;
@@ -2144,6 +2807,13 @@ async function writeTextOrDeleteIfEmpty(path, text) {
2144
2807
  await mkdir(dirname(path), { recursive: true });
2145
2808
  await writeFile(path, text, "utf8");
2146
2809
  }
2810
+ async function isPnpmProject(cwd, packageJson) {
2811
+ if (packageJson.packageManager) {
2812
+ return packageJson.packageManager.startsWith("pnpm@");
2813
+ }
2814
+ return await exists(join(cwd, "pnpm-lock.yaml")) ||
2815
+ await exists(join(cwd, "pnpm-workspace.yaml"));
2816
+ }
2147
2817
  async function ensurePnpmProject(cwd, packageJson) {
2148
2818
  if (packageJson.packageManager?.startsWith("pnpm@") ||
2149
2819
  await exists(join(cwd, "pnpm-lock.yaml")) ||
@@ -2256,33 +2926,49 @@ async function isLocalLoomBuildStale(sourceRoot, localPackagePath) {
2256
2926
  if (!outputPackageStat) {
2257
2927
  return true;
2258
2928
  }
2929
+ // Builds record the content they started from. Compare content rather than
2930
+ // timestamps whenever that stamp exists; older builds lack it.
2931
+ const stamp = await readLoomBuildStamp(localPackagePath);
2932
+ if (stamp) {
2933
+ const fingerprint = await computeLoomSourceFingerprint(sourceRoot);
2934
+ if (!hasLoomBuildProvenance(stamp)) {
2935
+ // Rebuilt once per source fingerprint: a stamp without provenance or
2936
+ // digest is stale until a fresh build of this source shows that the
2937
+ // checkout's build script cannot write them (legacyBuildFingerprint).
2938
+ return stamp.legacyBuildFingerprint !== fingerprint;
2939
+ }
2940
+ // An output edited after the build no longer matches its digest.
2941
+ return stamp.sourceFingerprint !== fingerprint ||
2942
+ stamp.packageDigest !==
2943
+ await computePackageContentDigest(localPackagePath);
2944
+ }
2259
2945
  const sourceNewest = await getNewestMtimeMs(sourceRoot);
2260
2946
  const outputMtime = outputPackageStat.mtime?.getTime() ?? 0;
2261
2947
  return sourceNewest > outputMtime;
2262
2948
  }
2263
- async function filesHaveSameText(leftPath, rightPath) {
2264
- const [left, right] = await Promise.all([
2265
- readTextIfExists(leftPath),
2266
- readTextIfExists(rightPath),
2267
- ]);
2268
- return left !== null && right !== null && left === right;
2949
+ /**
2950
+ * After a build, notes in its stamp when the checkout's build script
2951
+ * predates build provenance (the fresh stamp has none), together with the
2952
+ * source fingerprint that build started from, so sync stops rebuilding that
2953
+ * source on every run. Builds that record provenance are left alone.
2954
+ */
2955
+ async function markLegacyLoomBuild(localPackagePath, fingerprintBeforeBuild) {
2956
+ const stamp = await readLoomBuildStamp(localPackagePath);
2957
+ if (!stamp || hasLoomBuildProvenance(stamp))
2958
+ return;
2959
+ const { version: _version, ...fields } = stamp;
2960
+ await writeFile(join(localPackagePath, LOOM_BUILD_STAMP_FILE), formatLoomBuildStamp({
2961
+ ...fields,
2962
+ legacyBuildFingerprint: fingerprintBeforeBuild,
2963
+ }), "utf8");
2269
2964
  }
2270
- async function isInstalledLocalLoomPackageStale(cwd, localPackagePath) {
2271
- const installedPath = join(cwd, "node_modules", LOOM_DEPENDENCY);
2272
- if (!await exists(join(installedPath, "package.json"))) {
2273
- return true;
2274
- }
2275
- const sentinelFiles = [
2276
- "package.json",
2277
- join("script", "bin", "loom.js"),
2278
- join("script", "src", "cli", "mod.js"),
2279
- ];
2280
- for (const relativePath of sentinelFiles) {
2281
- if (!await filesHaveSameText(join(localPackagePath, relativePath), join(installedPath, relativePath))) {
2282
- return true;
2283
- }
2284
- }
2285
- return false;
2965
+ /**
2966
+ * Describes how the consumer's installed Loom differs from the local build,
2967
+ * by file list and content, or returns null when they match. Version numbers
2968
+ * alone cannot tell rebuilds of the same version apart.
2969
+ */
2970
+ function findInstalledLocalLoomDifference(cwd, localPackagePath) {
2971
+ return findPackageTreeDifference(localPackagePath, join(cwd, "node_modules", LOOM_DEPENDENCY));
2286
2972
  }
2287
2973
  async function runCommandOrThrow(commandRunner, command, args, options) {
2288
2974
  const result = await commandRunner(command, args, options);
@@ -2351,6 +3037,10 @@ async function readLocalDevState(cwd) {
2351
3037
  if (state.version !== 1 || state.dependency !== LOOM_DEPENDENCY) {
2352
3038
  return null;
2353
3039
  }
3040
+ // Retired: whole-file package.json snapshots are never written back.
3041
+ const retired = state;
3042
+ delete retired.packageJsonBeforeOverride;
3043
+ delete retired.packageJsonWithOverride;
2354
3044
  return state;
2355
3045
  }
2356
3046
  catch {
@@ -2404,15 +3094,17 @@ function compareParsedVersions(left, right) {
2404
3094
  }
2405
3095
  return left.prerelease.localeCompare(right.prerelease);
2406
3096
  }
2407
- async function findPublishedLoomPublicationForCommit(sourceRoot, sourceCommit, commandRunner, env, preferredSpec) {
3097
+ async function findPublishedLoomPublicationForCommit(sourceRoot, sourceCommit, commandRunner, env, preferredSpec,
3098
+ /** Names the commit in refusals, such as "Loom commit abc, which built X,". */
3099
+ subject) {
2408
3100
  const publication = await resolveLoomCommitPublication(sourceRoot, sourceCommit, commandRunner, env, preferredSpec);
2409
3101
  switch (publication.status) {
2410
3102
  case "published":
2411
3103
  return publication;
2412
3104
  case "not-on-origin-main":
2413
- throw new Error(`Recorded Loom commit ${sourceCommit.slice(0, 12)} is not reachable from origin/main. Push or merge the Loom changes, fetch origin/main, publish Loom if needed, then rerun \`loom dev published\`.`);
3105
+ throw new Error(`${subject} is not reachable from origin/main. Push or merge the Loom changes, fetch origin/main, publish Loom if needed, then rerun \`loom dev published\`.`);
2414
3106
  case "no-release-tag":
2415
- throw new Error(`Recorded Loom commit ${sourceCommit.slice(0, 12)} is on origin/main, but no published Loom version contains that commit or matches its package-relevant files. Publish Loom first, fetch tags, then rerun \`loom dev published\`.`);
3107
+ throw new Error(`${subject} is on origin/main, but no published Loom version contains that commit or matches its package-relevant files. Publish Loom first, fetch tags, then rerun \`loom dev published\`.`);
2416
3108
  }
2417
3109
  }
2418
3110
  function parseSemverTags(tags) {
@@ -2482,127 +3174,310 @@ async function resolveLoomCommitPublication(sourceRoot, sourceCommit, commandRun
2482
3174
  }
2483
3175
  return { status: "no-release-tag" };
2484
3176
  }
2485
- export async function syncLocalDevPackage(cwd, options = {}) {
3177
+ async function readPackageJsonIfExists(cwd) {
3178
+ const text = await readTextIfExists(join(cwd, "package.json"));
3179
+ if (text === null)
3180
+ return null;
3181
+ try {
3182
+ return JSON.parse(text);
3183
+ }
3184
+ catch {
3185
+ return null;
3186
+ }
3187
+ }
3188
+ /** Marks a loaded-package signature that could not be taken. */
3189
+ export const UNKNOWN_PACKAGE_SIGNATURE = "unknown";
3190
+ /**
3191
+ * Signature of the installed Loom package when a command starts, taken when
3192
+ * the project is linked or a dev sync holds the lock (a `loom dev local`
3193
+ * running right now can replace the package). Unlinked projects with no
3194
+ * sync running skip the walk and yield {@link UNKNOWN_PACKAGE_SIGNATURE}, as
3195
+ * does a walk that fails: a project linked after this check is still
3196
+ * treated as refreshed when its sync had to wait for another one. Commands
3197
+ * a sync started return undefined, since they never sync themselves.
3198
+ */
3199
+ export async function captureLoadedLocalLoomSignature(cwd, env) {
3200
+ if (env[LOOM_DEV_SYNC_ACTIVE_ENV] === "1")
3201
+ return undefined;
3202
+ const linked = await detectLocalDevLink(cwd).then((link) => link.active, () => false);
3203
+ if (!linked && !await exists(join(cwd, LOOM_LOCAL_DEV_LOCK_RELATIVE_PATH))) {
3204
+ return UNKNOWN_PACKAGE_SIGNATURE;
3205
+ }
3206
+ return await computePackageTreeSignature(join(cwd, "node_modules", LOOM_DEPENDENCY)).catch(() => UNKNOWN_PACKAGE_SIGNATURE);
3207
+ }
3208
+ function formatPnpmOverrideNotAppliedMessage(override, pnpmVersion) {
3209
+ return `pnpm did not apply the Loom local-dev override in ${formatPnpmOverrideLocation(override.location)}: pnpm-lock.yaml does not record ${LOOM_DEPENDENCY}: ${override.spec} under overrides, so this app still resolves the published package. Loom placed it for ${pnpmVersion ? `pnpm ${pnpmVersion}` : "an unknown pnpm version"}: pnpm before 10.5.1 reads overrides only from package.json, pnpm 10.5.1 and later 10.x read pnpm-workspace.yaml overrides only while package.json has none, and pnpm 11 reads only pnpm-workspace.yaml. Make sure package.json packageManager names the pnpm version you run, then rerun \`loom dev sync\`.`;
3210
+ }
3211
+ /** The project's active local Loom link, read from its current files. */
3212
+ async function detectLocalDevLink(cwd) {
2486
3213
  const manifest = await readManifestIfExists(cwd);
2487
3214
  const tooling = await detectProjectTooling(cwd, manifest?.project?.tooling);
2488
3215
  const denoMode = usesDenoTooling(tooling);
2489
- const workspacePath = join(cwd, "pnpm-workspace.yaml");
2490
- const workspaceText = await readTextIfExists(workspacePath);
2491
- const overrideSpec = getManagedDevOverrideSpec(workspaceText);
3216
+ const activePnpmOverride = denoMode ? null : getActivePnpmLocalDevOverride(await readTextIfExists(join(cwd, "pnpm-workspace.yaml")), await readPackageJsonIfExists(cwd) ?? {});
2492
3217
  const denoConfig = denoMode
2493
3218
  ? await getDenoConfigForLinks(cwd, tooling)
2494
3219
  : null;
2495
3220
  const denoLink = denoConfig
2496
3221
  ? await findLocalLoomDenoLink(cwd, await readDenoLinks(cwd, denoConfig))
2497
3222
  : null;
2498
- if (!overrideSpec && !denoLink) {
2499
- if (options.requireActive) {
2500
- throw new Error("No managed Loom local-dev override is active. Run `loom dev local /path/to/loom` first.");
2501
- }
2502
- return {
2503
- buildRan: false,
2504
- changed: false,
2505
- notes: [],
2506
- packageRefreshRan: false,
2507
- ranCommands: [],
2508
- };
3223
+ return {
3224
+ active: activePnpmOverride !== null || denoLink !== null,
3225
+ activePnpmOverride,
3226
+ denoLink,
3227
+ denoMode,
3228
+ };
3229
+ }
3230
+ const NO_LOCAL_DEV_LINK_MESSAGE = "No managed Loom local-dev override is active. Run `loom dev local /path/to/loom` first.";
3231
+ export async function syncLocalDevPackage(cwd, options = {}) {
3232
+ const workspacePath = join(cwd, "pnpm-workspace.yaml");
3233
+ const inactive = (notes = []) => ({
3234
+ buildRan: false,
3235
+ changed: false,
3236
+ notes,
3237
+ packageRefreshRan: false,
3238
+ ranCommands: [],
3239
+ });
3240
+ if (!(await detectLocalDevLink(cwd)).active) {
3241
+ if (options.requireActive)
3242
+ throw new Error(NO_LOCAL_DEV_LINK_MESSAGE);
3243
+ return inactive();
2509
3244
  }
2510
- const { packageJson } = await readProjectPackageJson(cwd);
2511
- if (!denoMode)
2512
- await ensurePnpmProject(cwd, packageJson);
2513
- const commandRunner = options.commandRunner ?? defaultCommandRunner;
2514
3245
  const env = options.env ?? process.env;
2515
- const localPackagePath = denoLink?.path ??
2516
- fileSpecToPath(cwd, overrideSpec);
2517
- const sourceRoot = await resolveLocalLoomSourceRoot(localPackagePath);
2518
- const configuredSpec = packageJson.dependencies?.[LOOM_DEPENDENCY] ??
2519
- packageJson.devDependencies?.[LOOM_DEPENDENCY];
2520
- const desiredLocalVersion = await readPackageVersion(join(cwd, "node_modules", LOOM_DEPENDENCY)) ?? versionFromDependencySpec(configuredSpec) ??
2521
- await readPackageVersion(localPackagePath);
2522
- const currentLocalVersion = await readPackageVersion(localPackagePath);
2523
- const buildEnv = desiredLocalVersion && !env.NPM_PACKAGE_VERSION
2524
- ? { ...env, NPM_PACKAGE_VERSION: desiredLocalVersion }
2525
- : env;
2526
- const ranCommands = [];
2527
- let buildRan = false;
2528
- if (options.force || denoMode && currentLocalVersion !== desiredLocalVersion ||
2529
- await isLocalLoomBuildStale(sourceRoot, localPackagePath)) {
2530
- if (!sourceRoot) {
2531
- throw new Error(`Could not find the Loom source checkout for ${localPackagePath}; cannot rebuild the local package.`);
2532
- }
2533
- await runCommandOrThrow(commandRunner, "deno", ["task", "build"], {
2534
- cwd: sourceRoot,
2535
- env: buildEnv,
2536
- stdio: "inherit",
2537
- });
2538
- ranCommands.push("deno task build");
2539
- buildRan = true;
2540
- }
2541
- const packageRefreshNeeded = buildRan ||
2542
- await isInstalledLocalLoomPackageStale(cwd, localPackagePath);
2543
- let packageRefreshRan = false;
2544
- if (options.force || packageRefreshNeeded) {
2545
- if (denoMode) {
2546
- await runCommandOrThrow(commandRunner, "deno", ["install"], {
2547
- cwd,
2548
- env,
2549
- stdio: "inherit",
2550
- });
2551
- ranCommands.push("deno install");
3246
+ if (env[LOOM_DEV_SYNC_ACTIVE_ENV] === "1") {
3247
+ // A command started by a running sync (a package lifecycle script, say)
3248
+ // must not wait for the lock its own parent holds.
3249
+ return inactive([
3250
+ "Skipped the local Loom sync inside a running Loom dev sync.",
3251
+ ]);
3252
+ }
3253
+ return await withLocalDevLock(join(cwd, LOOM_LOCAL_DEV_LOCK_RELATIVE_PATH), async (lock) => {
3254
+ // Re-read under the lock: while this command waited, the user may have
3255
+ // switched back to the published package or linked another checkout.
3256
+ const { activePnpmOverride, denoLink, denoMode } = await detectLocalDevLink(cwd);
3257
+ if (!activePnpmOverride && !denoLink) {
3258
+ if (options.requireActive)
3259
+ throw new Error(NO_LOCAL_DEV_LINK_MESSAGE);
3260
+ return inactive([
3261
+ "The local Loom link was removed while this command waited.",
3262
+ ]);
2552
3263
  }
2553
- else {
2554
- const packageSpec = `${LOOM_DEPENDENCY}@file:${localPackagePath}`;
2555
- await runCommandOrThrow(commandRunner, "pnpm", ["update", "--no-save", packageSpec], { cwd, env, stdio: "inherit" });
2556
- ranCommands.push(`pnpm update --no-save ${packageSpec}`);
2557
- await runCommandOrThrow(commandRunner, "pnpm", ["install"], {
2558
- cwd,
2559
- env,
2560
- stdio: "inherit",
2561
- });
2562
- ranCommands.push("pnpm install");
3264
+ const { packageJson } = await readProjectPackageJson(cwd);
3265
+ if (!denoMode)
3266
+ await ensurePnpmProject(cwd, packageJson);
3267
+ const commandRunner = options.commandRunner ?? defaultCommandRunner;
3268
+ const childEnv = { ...env, [LOOM_DEV_SYNC_ACTIVE_ENV]: "1" };
3269
+ const childStdio = options.commandOutput === "stderr"
3270
+ ? "inherit-stderr"
3271
+ : "inherit";
3272
+ const notes = [];
3273
+ let pnpmVersion = null;
3274
+ // Whether this sync already changed the project, for lost-lock errors.
3275
+ let changesMade = false;
3276
+ let pnpmOverride = activePnpmOverride;
3277
+ if (pnpmOverride) {
3278
+ // Older Loom versions always wrote pnpm-workspace.yaml, which pnpm 10
3279
+ // ignores when package.json has overrides; move it where pnpm reads it.
3280
+ const placement = await resolvePnpmLocalDevOverrideLocation(cwd, packageJson, commandRunner, env);
3281
+ if (placement.conflict)
3282
+ throw new Error(placement.conflict);
3283
+ pnpmVersion = placement.pnpmVersion;
3284
+ await lock.assertHeld(false);
3285
+ const movedFiles = await placePnpmLocalDevOverride(cwd, pnpmOverride.spec, placement.location);
3286
+ if (movedFiles.length) {
3287
+ changesMade = true;
3288
+ notes.push(`Moved the Loom local-dev override to ${formatPnpmOverrideLocation(placement.location)} (updated ${movedFiles.join(", ")}).`, ...placement.notes);
3289
+ }
3290
+ pnpmOverride = {
3291
+ location: placement.location,
3292
+ spec: pnpmOverride.spec,
3293
+ };
2563
3294
  }
2564
- packageRefreshRan = true;
2565
- }
2566
- const currentWorkspaceText = await readTextIfExists(workspacePath);
2567
- const currentState = denoMode
2568
- ? await readLocalDevState(cwd)
2569
- : await getCurrentLocalDevState(cwd, currentWorkspaceText);
2570
- let state = null;
2571
- if (buildRan || packageRefreshRan || !currentState) {
2572
- state = await buildLocalDevState(localPackagePath, sourceRoot, commandRunner, env);
2573
- if (!denoMode) {
2574
- const stateUpdate = setManagedDevStateText(await readTextIfExists(workspacePath), overrideSpec, state);
2575
- if (stateUpdate.changed) {
2576
- await writeTextOrDeleteIfEmpty(workspacePath, stateUpdate.text);
3295
+ const localPackagePath = denoLink?.path ??
3296
+ fileSpecToPath(cwd, pnpmOverride.spec);
3297
+ const sourceRoot = await resolveLocalLoomSourceRoot(localPackagePath);
3298
+ const configuredSpec = (await resolveLoomDependencySpec(cwd, packageJson, { includeDev: true })).effective;
3299
+ const desiredLocalVersion = await readPackageVersion(join(cwd, "node_modules", LOOM_DEPENDENCY)) ?? versionFromDependencySpec(configuredSpec) ??
3300
+ await readPackageVersion(localPackagePath);
3301
+ const currentLocalVersion = await readPackageVersion(localPackagePath);
3302
+ const buildEnv = desiredLocalVersion && !env.NPM_PACKAGE_VERSION
3303
+ ? { ...childEnv, NPM_PACKAGE_VERSION: desiredLocalVersion }
3304
+ : childEnv;
3305
+ const ranCommands = [];
3306
+ let buildRan = false;
3307
+ if (options.force ||
3308
+ denoMode && currentLocalVersion !== desiredLocalVersion ||
3309
+ await isLocalLoomBuildStale(sourceRoot, localPackagePath)) {
3310
+ if (!sourceRoot) {
3311
+ throw new Error(`Could not find the Loom source checkout for ${localPackagePath}; cannot rebuild the local package.`);
3312
+ }
3313
+ // Run in the Loom checkout with its own deno.json (and so its own
3314
+ // deno.lock). Deno discovers config and lockfile from the working
3315
+ // directory, so a build resolved from the consumer would write a
3316
+ // deno.lock listing the consumer's package.json into its root.
3317
+ await lock.assertHeld(changesMade);
3318
+ const fingerprintBeforeBuild = await computeLoomSourceFingerprint(sourceRoot);
3319
+ await runCommandOrThrow(commandRunner, "deno", ["task", "--config", join(sourceRoot, "deno.json"), "build"], { cwd: sourceRoot, env: buildEnv, stdio: childStdio });
3320
+ ranCommands.push("deno task build");
3321
+ buildRan = true;
3322
+ changesMade = true;
3323
+ await markLegacyLoomBuild(localPackagePath, fingerprintBeforeBuild);
3324
+ }
3325
+ const lockfilePath = join(cwd, "pnpm-lock.yaml");
3326
+ const lockfileBefore = pnpmOverride
3327
+ ? await readTextIfExists(lockfilePath)
3328
+ : null;
3329
+ // A lockfile that does not record the override means pnpm has not linked
3330
+ // the local package yet (for example right after `loom dev local`).
3331
+ const overridePending = pnpmOverride !== null &&
3332
+ lockfileBefore !== null &&
3333
+ !lockfileAppliesLocalDevOverride(lockfileBefore, pnpmOverride.spec);
3334
+ const importerBefore = overridePending
3335
+ ? getLockfileRootImporterDependency(lockfileBefore, LOOM_DEPENDENCY)
3336
+ : null;
3337
+ if (importerBefore?.version && isLocalPackageSpec(importerBefore.version) &&
3338
+ !isLocalPackageSpec(importerBefore.specifier ?? "")) {
3339
+ // Earlier Loom versions linked with `pnpm update --no-save`, which also
3340
+ // re-resolved Loom's dependencies; this sync cannot tell which of those
3341
+ // lockfile changes were intended.
3342
+ notes.push("pnpm-lock.yaml was linked by an earlier Loom through `pnpm update --no-save`, which can also update Loom's own dependencies and add duplicate peer variants. If pnpm-lock.yaml has no other intended changes, restore it from git and rerun `loom dev sync`.");
3343
+ }
3344
+ const packageRefreshNeeded = buildRan || overridePending ||
3345
+ await findInstalledLocalLoomDifference(cwd, localPackagePath) !== null;
3346
+ let packageRefreshRan = false;
3347
+ const warnings = [];
3348
+ if (options.force || packageRefreshNeeded) {
3349
+ await lock.assertHeld(changesMade);
3350
+ if (denoMode) {
3351
+ await runCommandOrThrow(commandRunner, "deno", ["install"], {
3352
+ cwd,
3353
+ env: childEnv,
3354
+ stdio: childStdio,
3355
+ });
3356
+ ranCommands.push("deno install");
2577
3357
  }
2578
- }
2579
- }
2580
- if (state ?? currentState) {
2581
- await writeLocalDevStateIfChanged(cwd, state ?? currentState);
2582
- }
2583
- const notes = packageRefreshRan
2584
- ? [
2585
- `Local Loom package refreshed from ${localPackagePath}.`,
2586
- "If this command was using a stale installed Loom CLI, rerun it now.",
2587
- ]
2588
- : [`Local Loom package is already fresh: ${localPackagePath}`];
2589
- const recordedState = state ?? currentState;
2590
- if (recordedState?.sourceCommit) {
2591
- notes.push(`Recorded local Loom sync at commit ${recordedState.sourceCommit.slice(0, 12)}${recordedState.sourceDirty ? " with a dirty source tree" : ""}.`);
2592
- }
2593
- else if (sourceRoot) {
2594
- notes.push("Could not record a Loom git commit for this sync; `loom dev published` cannot prove whether unpublished Loom changes are required.");
2595
- }
3358
+ else {
3359
+ // A plain install applies the override and re-imports the local
3360
+ // directory package while reusing every other locked version.
3361
+ // `pnpm update` would re-resolve Loom's dependency subtree instead.
3362
+ await runCommandOrThrow(commandRunner, "pnpm", ["install", "--no-frozen-lockfile"], { cwd, env: childEnv, stdio: childStdio });
3363
+ ranCommands.push("pnpm install --no-frozen-lockfile");
3364
+ const lockfileAfter = await readTextIfExists(lockfilePath);
3365
+ if (lockfileAfter !== null &&
3366
+ !lockfileAppliesLocalDevOverride(lockfileAfter, pnpmOverride.spec)) {
3367
+ throw new Error(formatPnpmOverrideNotAppliedMessage(pnpmOverride, pnpmVersion));
3368
+ }
3369
+ if (lockfileBefore !== null && lockfileAfter !== null) {
3370
+ const duplicates = findNewPeerVariantDuplicates(lockfileBefore, lockfileAfter);
3371
+ if (duplicates.length) {
3372
+ warnings.push(`pnpm-lock.yaml gained duplicate peer variants: ${duplicates.map((duplicate) => `${duplicate.packageVersion} (${duplicate.before} -> ${duplicate.after})`).join(", ")}. Peer variants of one version load as separate module copies, which can break type checks and shared state; inspect them with \`pnpm why <package>\`.`);
3373
+ }
3374
+ }
3375
+ const remainingDifference = await findInstalledLocalLoomDifference(cwd, localPackagePath);
3376
+ if (remainingDifference) {
3377
+ warnings.push(`node_modules/${LOOM_DEPENDENCY} still differs from ${localPackagePath} after pnpm install (${remainingDifference}).`);
3378
+ }
3379
+ }
3380
+ packageRefreshRan = true;
3381
+ }
3382
+ await lock.assertHeld(changesMade || packageRefreshRan);
3383
+ const currentWorkspaceText = await readTextIfExists(workspacePath);
3384
+ const currentState = denoMode
3385
+ ? await readLocalDevState(cwd)
3386
+ : await getCurrentLocalDevState(cwd, currentWorkspaceText);
3387
+ let state = null;
3388
+ if (buildRan || packageRefreshRan || !currentState) {
3389
+ state = await buildLocalDevState(localPackagePath, sourceRoot, commandRunner, env);
3390
+ // Keep which package.json maps Loom created across syncs.
3391
+ const previous = await readLocalDevState(cwd);
3392
+ if (previous?.createdPackageJsonMaps !== undefined) {
3393
+ state.createdPackageJsonMaps = previous.createdPackageJsonMaps;
3394
+ }
3395
+ if (pnpmOverride?.location === "pnpm-workspace.yaml") {
3396
+ const stateUpdate = setManagedDevStateText(await readTextIfExists(workspacePath), pnpmOverride.spec, state);
3397
+ if (stateUpdate.changed) {
3398
+ await writeTextOrDeleteIfEmpty(workspacePath, stateUpdate.text);
3399
+ }
3400
+ }
3401
+ }
3402
+ if (state ?? currentState) {
3403
+ await writeLocalDevStateIfChanged(cwd, state ?? currentState);
3404
+ }
3405
+ // Another process may have replaced the package this process loaded,
3406
+ // while it waited for the lock or just before it took it; its
3407
+ // in-process Loom code is then stale.
3408
+ let refreshedElsewhere = false;
3409
+ if (!buildRan && !packageRefreshRan &&
3410
+ options.loadedPackageSignature !== undefined) {
3411
+ const current = options.loadedPackageSignature ===
3412
+ UNKNOWN_PACKAGE_SIGNATURE
3413
+ ? UNKNOWN_PACKAGE_SIGNATURE
3414
+ : await computePackageTreeSignature(join(cwd, "node_modules", LOOM_DEPENDENCY)).catch(() => UNKNOWN_PACKAGE_SIGNATURE);
3415
+ // Without both signatures, only a sync this one waited for is
3416
+ // evidence of a replacement; assume one then rather than run code
3417
+ // that may be stale.
3418
+ refreshedElsewhere = current === UNKNOWN_PACKAGE_SIGNATURE
3419
+ ? lock.waited
3420
+ : current !== options.loadedPackageSignature;
3421
+ }
3422
+ notes.push(packageRefreshRan
3423
+ ? `Local Loom package refreshed from ${localPackagePath}.`
3424
+ : refreshedElsewhere
3425
+ ? `Another Loom command refreshed the local Loom package from ${localPackagePath} after this one started.`
3426
+ : `Local Loom package is already fresh: ${localPackagePath}`, ...warnings.map((warning) => `Warning: ${warning}`));
3427
+ const recordedState = state ?? currentState;
3428
+ if (recordedState?.sourceCommit) {
3429
+ notes.push(`Recorded local Loom sync at commit ${recordedState.sourceCommit.slice(0, 12)}${recordedState.sourceDirty ? " with a dirty source tree" : ""}.`);
3430
+ }
3431
+ // What `loom dev published` will check is the build's own stamp.
3432
+ const stamp = sourceRoot
3433
+ ? await readLoomBuildStamp(localPackagePath)
3434
+ : null;
3435
+ if (stamp?.legacyBuildFingerprint && !hasLoomBuildProvenance(stamp)) {
3436
+ notes.push(`The local Loom build in ${localPackagePath} comes from a Loom checkout whose build script predates build provenance, so \`loom dev published\` will refuse it; relink to a newer Loom checkout before switching back.`);
3437
+ }
3438
+ else if (sourceRoot && (!stamp || !hasLoomBuildProvenance(stamp))) {
3439
+ notes.push(`The local Loom build in ${localPackagePath} does not record which commit it was built from, so \`loom dev published\` will refuse it; rebuild it with \`loom dev sync --force\`.`);
3440
+ }
3441
+ else if (stamp && !stamp.sourceCommit) {
3442
+ notes.push(`The local Loom build in ${localPackagePath} was made where git could not read the Loom commit, so \`loom dev published\` will refuse it; rebuild it from a git checkout of Loom with \`loom dev sync --force\`.`);
3443
+ }
3444
+ else if (stamp && stamp.sourceDirty !== false) {
3445
+ notes.push(`The local Loom build in ${localPackagePath} was made from uncommitted Loom changes, so \`loom dev published\` will refuse it until you commit them and rebuild with \`loom dev sync --force\`.`);
3446
+ }
3447
+ return {
3448
+ buildRan,
3449
+ changed: buildRan || packageRefreshRan || refreshedElsewhere,
3450
+ localPackagePath,
3451
+ notes,
3452
+ packageRefreshRan,
3453
+ ranCommands,
3454
+ };
3455
+ }, localDevLockOptions(options));
3456
+ }
3457
+ function localDevLockOptions(options) {
2596
3458
  return {
2597
- buildRan,
2598
- changed: buildRan || packageRefreshRan,
2599
- localPackagePath,
2600
- notes,
2601
- packageRefreshRan,
2602
- ranCommands,
3459
+ ...options.lock,
3460
+ onWait: (holder) => options.onLockWait?.(`Waiting for another Loom dev sync (${holder
3461
+ ? `process ${holder.pid} on ${holder.hostname}`
3462
+ : "unknown process"}) to finish.`),
2603
3463
  };
2604
3464
  }
2605
- export async function useLocalDevPackage(cwd, inputPath) {
3465
+ /**
3466
+ * Runs a local-dev config change under the project's sync lock, so it never
3467
+ * interleaves with a sync that reads and rewrites the same files. Commands a
3468
+ * sync started (LOOM_DEV_SYNC_ACTIVE) run without it to avoid waiting on
3469
+ * their own parent.
3470
+ */
3471
+ async function withProjectLocalDevLock(cwd, options, run) {
3472
+ const env = options.env ?? process.env;
3473
+ if (env[LOOM_DEV_SYNC_ACTIVE_ENV] === "1")
3474
+ return await run();
3475
+ return await withLocalDevLock(join(cwd, LOOM_LOCAL_DEV_LOCK_RELATIVE_PATH), run, localDevLockOptions(options));
3476
+ }
3477
+ export async function useLocalDevPackage(cwd, inputPath, options = {}) {
3478
+ return await withProjectLocalDevLock(cwd, options, () => useLocalDevPackageLocked(cwd, inputPath, options));
3479
+ }
3480
+ async function useLocalDevPackageLocked(cwd, inputPath, options) {
2606
3481
  const { packageJson } = await readProjectPackageJson(cwd);
2607
3482
  const manifest = await readManifestIfExists(cwd);
2608
3483
  const tooling = await detectProjectTooling(cwd, manifest?.project?.tooling);
@@ -2615,8 +3490,23 @@ export async function useLocalDevPackage(cwd, inputPath) {
2615
3490
  const denoConfig = await getDenoConfigForLinks(cwd, tooling);
2616
3491
  const relativeLocalPackagePath = relative(cwd, localPackagePath)
2617
3492
  .replaceAll("\\", "/");
3493
+ // A relink replaces the previous Loom link, found by its package name or,
3494
+ // when that package is gone, by the path dev state recorded for it.
3495
+ // Otherwise both stay linked and `loom dev published` removes only one.
3496
+ const recorded = await readLocalDevState(cwd);
3497
+ const previousLinks = [];
3498
+ for (const link of await readDenoLinks(cwd, denoConfig)) {
3499
+ if (link === relativeLocalPackagePath)
3500
+ continue;
3501
+ if (await findLocalLoomDenoLink(cwd, [link]) ||
3502
+ (recorded &&
3503
+ resolve(cwd, link) === resolve(cwd, recorded.localPackagePath))) {
3504
+ previousLinks.push(link);
3505
+ }
3506
+ }
2618
3507
  const update = await mutateDenoLinks(cwd, denoConfig, {
2619
3508
  add: relativeLocalPackagePath,
3509
+ remove: previousLinks,
2620
3510
  });
2621
3511
  const state = {
2622
3512
  dependency: LOOM_DEPENDENCY,
@@ -2640,26 +3530,218 @@ export async function useLocalDevPackage(cwd, inputPath) {
2640
3530
  }
2641
3531
  await ensurePnpmProject(cwd, packageJson);
2642
3532
  const overrideSpec = `file:${localPackagePath}`;
2643
- const workspacePath = join(cwd, "pnpm-workspace.yaml");
2644
- const update = ensurePnpmWorkspaceLocalDevText(await readTextIfExists(workspacePath), overrideSpec);
2645
- if (update.conflict) {
2646
- throw new Error(update.conflict);
2647
- }
2648
- const changedFiles = [];
2649
- if (update.changed) {
2650
- await writeTextOrDeleteIfEmpty(workspacePath, update.text);
2651
- changedFiles.push("pnpm-workspace.yaml");
2652
- }
3533
+ const loomDependency = await resolveLoomDependencySpec(cwd, packageJson);
3534
+ const restoreSpec = loomDependency.catalogName
3535
+ ? `${loomDependency.effective ?? publishedSpec} (from the pnpm-workspace.yaml catalog)`
3536
+ : publishedSpec;
3537
+ const placement = await resolvePnpmLocalDevOverrideLocation(cwd, packageJson, options.commandRunner ?? defaultCommandRunner, options.env ?? process.env);
3538
+ if (placement.conflict) {
3539
+ throw new Error(placement.conflict);
3540
+ }
3541
+ const changedFiles = await placePnpmLocalDevOverride(cwd, overrideSpec, placement.location);
2653
3542
  return {
2654
3543
  changedFiles,
2655
3544
  notes: [
2656
- `Local Loom dev override is active: ${overrideSpec}`,
3545
+ `Local Loom dev override is active in ${formatPnpmOverrideLocation(placement.location)}: ${overrideSpec}`,
3546
+ ...placement.notes,
2657
3547
  "Run `loom dev sync` to rebuild the local Loom package and refresh this project's pnpm install when needed.",
2658
- `Before committing or shipping a published build, run \`loom dev published\`, then \`pnpm update --no-save ${LOOM_DEPENDENCY}@${publishedSpec}\`, and then \`pnpm install\`.`,
3548
+ `Before committing or shipping a published build, run \`loom dev published\`, then \`pnpm install\` to restore ${LOOM_DEPENDENCY}@${restoreSpec}.`,
2659
3549
  ],
2660
3550
  };
2661
3551
  }
3552
+ /** Turns a `file:` or `link:` spec into the absolute directory it names. */
3553
+ function localSpecToPath(cwd, spec) {
3554
+ const value = spec.replace(/^(?:file|link):/, "");
3555
+ if (value.startsWith("//"))
3556
+ return new URL(`file:${value}`).pathname;
3557
+ return resolve(cwd, value);
3558
+ }
3559
+ /** The local spec pnpm-lock.yaml resolves Loom to, if it is local. */
3560
+ function getLockfileLocalLoomSpec(lockfileText) {
3561
+ if (!lockfileText)
3562
+ return null;
3563
+ const version = getLockfileRootImporterDependency(lockfileText, LOOM_DEPENDENCY)?.version?.replace(/\(.+$/, "");
3564
+ if (version !== undefined) {
3565
+ return isLocalPackageSpec(version) ? version : null;
3566
+ }
3567
+ return getLocalLoomLockfileResolution(lockfileText);
3568
+ }
3569
+ /**
3570
+ * The published Loom version pnpm has installed, when nothing local is
3571
+ * provably installed:
3572
+ * - pnpm-lock.yaml and pnpm's record of node_modules
3573
+ * (`node_modules/.pnpm/lock.yaml`) resolve Loom to the same registry
3574
+ * version, and the installed package has that version;
3575
+ * - `node_modules/@gadicc/loom` resolves into pnpm's virtual store entry for
3576
+ * that registry version, not a `file+`/`link+` entry. pnpm re-points it
3577
+ * before it writes either lockfile, so an interrupted install of a local
3578
+ * build (which carries the registry version) fails this check;
3579
+ * - when `localBuild` exists, the installed copy differs from it.
3580
+ * Null whenever any of that is uncertain, for example with
3581
+ * `node-linker=hoisted`, `enableGlobalVirtualStore` or a custom
3582
+ * `virtual-store-dir`, where no `node_modules/.pnpm` entry tells them apart.
3583
+ */
3584
+ async function findInstalledRegistryLoomVersion(cwd, lockfileText, localBuild) {
3585
+ const resolvedVersion = (text) => text
3586
+ ? getLockfileRootImporterDependency(text, LOOM_DEPENDENCY)?.version
3587
+ ?.replace(/\(.+$/, "") ?? null
3588
+ : null;
3589
+ const version = resolvedVersion(lockfileText);
3590
+ if (!version || isLocalPackageSpec(version))
3591
+ return null;
3592
+ const installedLockfile = await readTextIfExists(join(cwd, "node_modules", ".pnpm", "lock.yaml"));
3593
+ if (resolvedVersion(installedLockfile) !== version)
3594
+ return null;
3595
+ const installedPath = join(cwd, "node_modules", LOOM_DEPENDENCY);
3596
+ if (await readPackageVersion(installedPath) !== version)
3597
+ return null;
3598
+ const [store, installed] = await Promise.all([
3599
+ realpath(join(cwd, "node_modules", ".pnpm")).catch(() => null),
3600
+ realpath(installedPath).catch(() => null),
3601
+ ]);
3602
+ if (!store || !installed)
3603
+ return null;
3604
+ const entry = relative(store, installed).split(sep)[0];
3605
+ const registryEntry = `@gadicc+loom@${version}`;
3606
+ if (!(entry === registryEntry || entry.startsWith(`${registryEntry}_`) ||
3607
+ entry.startsWith(`${registryEntry}(`))) {
3608
+ return null;
3609
+ }
3610
+ if (await exists(join(localBuild, "package.json")) &&
3611
+ await findInstalledLocalLoomDifference(cwd, localBuild) === null) {
3612
+ return null;
3613
+ }
3614
+ return version;
3615
+ }
3616
+ /**
3617
+ * Lists every local Loom package the project points at, merging entries for
3618
+ * the same directory. For pnpm these are the managed overrides and the
3619
+ * lockfile's local resolution; for Deno, each link whose package is Loom,
3620
+ * or whose path dev state recorded for Loom when that package is gone.
3621
+ * Dev state only identifies such a link; it never proves anything.
3622
+ */
3623
+ async function collectLocalLoomTargets(cwd, project) {
3624
+ const targets = new Map();
3625
+ const add = async (path, source) => {
3626
+ const key = await realpath(path).catch(() => path);
3627
+ const target = targets.get(key) ?? { path: key, sources: [] };
3628
+ target.sources.push(source);
3629
+ targets.set(key, target);
3630
+ };
3631
+ const denoLinks = [];
3632
+ if (project.denoConfig) {
3633
+ const recorded = await readLocalDevState(cwd);
3634
+ const recordedPath = recorded?.localPackagePath
3635
+ ? resolve(cwd, recorded.localPackagePath)
3636
+ : null;
3637
+ for (const link of await readDenoLinks(cwd, project.denoConfig)) {
3638
+ const path = resolve(cwd, link);
3639
+ if (await findLocalLoomDenoLink(cwd, [link]) || path === recordedPath) {
3640
+ denoLinks.push(link);
3641
+ await add(path, `${project.denoConfig} links ${link}`);
3642
+ }
3643
+ }
3644
+ return { denoLinks, targets: [...targets.values()] };
3645
+ }
3646
+ const workspaceSpec = getManagedDevOverrideSpec(project.workspaceText);
3647
+ if (workspaceSpec && isManagedPackageJsonLoomOverride(workspaceSpec)) {
3648
+ await add(localSpecToPath(cwd, workspaceSpec), "the pnpm-workspace.yaml override");
3649
+ }
3650
+ for (const { key, spec } of getUnmanagedPnpmWorkspaceLoomOverrides(project.workspaceText)) {
3651
+ await add(localSpecToPath(cwd, spec), `the pnpm-workspace.yaml overrides entry for ${key}`);
3652
+ }
3653
+ for (const { location, spec } of getPackageJsonLocalLoomOverrides(project.packageJson)) {
3654
+ await add(localSpecToPath(cwd, spec), `the ${formatPnpmOverrideLocation(location)} override`);
3655
+ }
3656
+ const lockfileSpec = getLockfileLocalLoomSpec(project.lockfileText);
3657
+ if (lockfileSpec?.startsWith("workspace:")) {
3658
+ throw new Error(`pnpm-lock.yaml resolves ${LOOM_DEPENDENCY} to ${lockfileSpec}, a workspace package Loom cannot trace to a build, so it cannot prove that the installed Loom is published. Install a published ${LOOM_DEPENDENCY} instead.`);
3659
+ }
3660
+ if (lockfileSpec) {
3661
+ await add(localSpecToPath(cwd, lockfileSpec), "pnpm-lock.yaml");
3662
+ }
3663
+ return { denoLinks, targets: [...targets.values()] };
3664
+ }
3665
+ /**
3666
+ * Proves that the local Loom build this project has installed is published,
3667
+ * from that build's own stamp: the build must record a clean source commit,
3668
+ * the installed copy must match it (and, for pnpm, the lockfile must resolve
3669
+ * to it), and the commit must be covered by a release. Dev state and the
3670
+ * checkout's current git state are never consulted. Throws a refusal that
3671
+ * says what to do otherwise.
3672
+ */
3673
+ async function proveLocalLoomBuildPublished(cwd, target, options) {
3674
+ const { path } = target;
3675
+ const rerun = "then rerun `loom dev published`";
3676
+ if (!await exists(join(path, "package.json"))) {
3677
+ const lockfileOnly = target.sources.every((source) => source === "pnpm-lock.yaml");
3678
+ throw new Error(`${path}, which ${target.sources.join(" and ")} point${target.sources.length === 1 ? "s" : ""} at, holds no built Loom package. ${lockfileOnly
3679
+ ? "If the app does not need that build, restore pnpm-lock.yaml from git and run `pnpm install`; otherwise restore that Loom checkout, link it with `loom dev local` and run `loom dev sync`"
3680
+ : "Restore that Loom checkout and run `loom dev sync`, or link another with `loom dev local`"}, ${rerun}.`);
3681
+ }
3682
+ const stamp = await readLoomBuildStamp(path);
3683
+ if (stamp?.legacyBuildFingerprint && !hasLoomBuildProvenance(stamp)) {
3684
+ throw new Error(`The Loom build in ${path} comes from a Loom checkout whose build script predates build provenance, so \`loom dev published\` cannot prove that it is published. Relink to a newer Loom checkout with \`loom dev local\` and run \`loom dev sync\`, or confirm by other means that it is equivalent to a published Loom release and remove the override yourself.`);
3685
+ }
3686
+ if (!stamp || !hasLoomBuildProvenance(stamp)) {
3687
+ throw new Error(`The Loom build in ${path} does not record which commit it was built from (it has no build stamp, or one from before builds recorded it). Run \`loom dev sync\` to rebuild and install it, ${rerun}.`);
3688
+ }
3689
+ if (stamp.packageDigest !== await computePackageContentDigest(path)) {
3690
+ throw new Error(`${path} was modified after it was built. Run \`loom dev sync --force\`, ${rerun}.`);
3691
+ }
3692
+ if (!stamp.sourceCommit) {
3693
+ throw new Error(`The Loom build in ${path} was made where git could not read the Loom commit. Rebuild it from a git checkout of Loom with \`loom dev sync --force\`, ${rerun}.`);
3694
+ }
3695
+ const shortCommit = stamp.sourceCommit.slice(0, 12);
3696
+ if (stamp.sourceDirty !== false) {
3697
+ throw new Error(stamp.sourceDirty
3698
+ ? `The Loom build in ${path} was made from commit ${shortCommit} with uncommitted changes. Commit your Loom changes and rebuild with \`loom dev sync --force\`, publish Loom if needed, ${rerun}.`
3699
+ : `The Loom build in ${path} was made from commit ${shortCommit}, but git could not tell whether that checkout had uncommitted changes. Rebuild it with \`loom dev sync --force\`, ${rerun}.`);
3700
+ }
3701
+ // Deno loads a node_modules copy whenever its effective nodeModulesDir is
3702
+ // auto or manual, and manual is its default next to a package.json. So any
3703
+ // copy is compared unless the config says "none", where Deno loads the
3704
+ // linked directory itself.
3705
+ const nodeModulesDir = options.denoConfig
3706
+ ? parseJsonc(await readTextIfExists(join(cwd, options.denoConfig)) ?? "{}", options.denoConfig).nodeModulesDir
3707
+ : undefined;
3708
+ const installedCopy = !options.denoConfig ||
3709
+ (nodeModulesDir !== "none" &&
3710
+ await exists(join(cwd, "node_modules", LOOM_DEPENDENCY, "package.json")));
3711
+ const difference = installedCopy
3712
+ ? await findInstalledLocalLoomDifference(cwd, path)
3713
+ : null;
3714
+ if (difference) {
3715
+ throw new Error(`The installed Loom differs from ${path} (${difference}). Run \`loom dev sync\`, ${rerun}.`);
3716
+ }
3717
+ if (!options.denoConfig) {
3718
+ const lockfileSpec = getLockfileLocalLoomSpec(options.lockfileText);
3719
+ if (!lockfileSpec) {
3720
+ throw new Error(`pnpm-lock.yaml does not resolve ${LOOM_DEPENDENCY} to ${path}. Run \`loom dev sync\`, ${rerun}.`);
3721
+ }
3722
+ }
3723
+ const sourceRoot = await resolveLocalLoomSourceRoot(path);
3724
+ if (!sourceRoot) {
3725
+ throw new Error(`${path} is not inside a Loom source checkout, so Loom cannot check its build commit ${shortCommit} against Loom releases. Link the npm output of a Loom git checkout with \`loom dev local\` and run \`loom dev sync\`, ${rerun}.`);
3726
+ }
3727
+ const publication = await findPublishedLoomPublicationForCommit(sourceRoot, stamp.sourceCommit, options.commandRunner, options.env, options.preferredSpec, `Loom commit ${shortCommit}, which built ${path},`);
3728
+ return {
3729
+ note: publication.reason === "contains-commit"
3730
+ ? `The Loom build in ${path} comes from commit ${shortCommit}, which is included in published ${LOOM_DEPENDENCY}@${publication.version}.`
3731
+ : `The Loom build in ${path} comes from commit ${shortCommit}, which has no package-relevant changes after ${publication.tag}, so published ${LOOM_DEPENDENCY}@${publication.version} covers it.`,
3732
+ publication,
3733
+ };
3734
+ }
2662
3735
  export async function usePublishedDevPackage(cwd, options = {}) {
3736
+ // A project that was never linked has nothing a sync could be changing,
3737
+ // so it does not need the lock (or a new `.loom/` directory).
3738
+ if (!(await detectLocalDevLink(cwd)).active &&
3739
+ !await exists(join(cwd, ".loom"))) {
3740
+ return await usePublishedDevPackageLocked(cwd, options);
3741
+ }
3742
+ return await withProjectLocalDevLock(cwd, options, () => usePublishedDevPackageLocked(cwd, options));
3743
+ }
3744
+ async function usePublishedDevPackageLocked(cwd, options) {
2663
3745
  const { packageJson } = await readProjectPackageJson(cwd);
2664
3746
  const manifest = await readManifestIfExists(cwd);
2665
3747
  const tooling = await detectProjectTooling(cwd, manifest?.project?.tooling);
@@ -2673,75 +3755,227 @@ export async function usePublishedDevPackage(cwd, options = {}) {
2673
3755
  const denoConfig = denoMode
2674
3756
  ? await getDenoConfigForLinks(cwd, tooling)
2675
3757
  : null;
2676
- const denoLink = denoConfig
2677
- ? await findLocalLoomDenoLink(cwd, await readDenoLinks(cwd, denoConfig))
2678
- : null;
2679
- const activeOverrideSpec = denoLink?.link ??
2680
- getManagedDevOverrideSpec(workspaceText);
2681
- const localLockfileResolution = denoMode
3758
+ const lockfileText = denoMode
2682
3759
  ? null
2683
- : await getProjectLocalLoomLockfileResolution(cwd);
2684
- const state = denoMode
2685
- ? await readLocalDevState(cwd)
2686
- : await getCurrentLocalDevState(cwd, workspaceText);
3760
+ : await readTextIfExists(join(cwd, "pnpm-lock.yaml"));
3761
+ const localLockfileResolution = lockfileText
3762
+ ? getLocalLoomLockfileResolution(lockfileText)
3763
+ : null;
2687
3764
  const notes = [];
2688
- let publishedSpec = getPublishedLoomDependencySpec(packageJson);
2689
- const needsPublicationProof = Boolean(activeOverrideSpec || localLockfileResolution);
2690
- if (needsPublicationProof && state?.sourceCommit) {
2691
- if (state.sourceDirty) {
2692
- throw new Error(`Local Loom sync was recorded at commit ${state.sourceCommit.slice(0, 12)} with a dirty source tree. Commit or discard the Loom changes, run \`loom dev sync\`, publish Loom if needed, then rerun \`loom dev published\`.`);
2693
- }
2694
- if (!state.sourceRoot) {
2695
- throw new Error("Local Loom sync recorded a commit but not its source checkout. Run `loom dev sync` from a Loom source checkout before switching back to the published package.");
3765
+ const { denoLinks, targets } = await collectLocalLoomTargets(cwd, {
3766
+ denoConfig,
3767
+ lockfileText,
3768
+ packageJson,
3769
+ workspaceText,
3770
+ });
3771
+ if (targets.length > 1) {
3772
+ throw new Error(`This project points at more than one local Loom package:\n${targets.map((target) => `- ${target.path} (${target.sources.join(", ")})`).join("\n")}\nKeep one: link it with \`loom dev local <path>\` and run \`loom dev sync\`, then rerun \`loom dev published\`.`);
3773
+ }
3774
+ // A `catalog:` reference keeps its version in pnpm-workspace.yaml, which is
3775
+ // where the published version has to go too.
3776
+ const catalogDependency = denoMode
3777
+ ? null
3778
+ : await resolveLoomDependencySpec(cwd, packageJson);
3779
+ const catalog = catalogDependency?.catalogName ? catalogDependency : null;
3780
+ let publishedSpec = catalog
3781
+ ? catalog.effective && !isLocalPackageSpec(catalog.effective)
3782
+ ? catalog.effective
3783
+ : DEFAULT_LOOM_RANGE
3784
+ : getPublishedLoomDependencySpec(packageJson);
3785
+ // A pnpm link that was never installed left nothing local to prove: the
3786
+ // app still runs the published Loom it had. Deno reads a link directly or
3787
+ // copies it into node_modules on its next install or run, so Deno links
3788
+ // are always proved.
3789
+ const registryVersion = denoMode || targets.length !== 1
3790
+ ? null
3791
+ : await findInstalledRegistryLoomVersion(cwd, lockfileText, targets[0].path);
3792
+ if (registryVersion) {
3793
+ notes.push(`No local Loom build was installed (pnpm-lock.yaml and node_modules hold published ${LOOM_DEPENDENCY}@${registryVersion}), so the pin stays at ${publishedSpec}.`);
3794
+ }
3795
+ else if (targets.length === 1) {
3796
+ const proof = await proveLocalLoomBuildPublished(cwd, targets[0], {
3797
+ commandRunner,
3798
+ denoConfig,
3799
+ env,
3800
+ lockfileText,
3801
+ preferredSpec: publishedSpec,
3802
+ });
3803
+ publishedSpec = proof.publication.version;
3804
+ notes.push(proof.note);
3805
+ }
3806
+ const changedFiles = [];
3807
+ let catalogChanged = false;
3808
+ if (catalog) {
3809
+ const currentText = await readTextIfExists(workspacePath);
3810
+ const entry = findLoomCatalogEntry(currentText, catalog.catalogName);
3811
+ const unreadable = entry
3812
+ ? null
3813
+ : findUnreadableLoomCatalog(currentText, catalog.catalogName);
3814
+ if (unreadable) {
3815
+ notes.push(`pnpm-workspace.yaml writes the \`${unreadable}\` catalog as a multi-line or nested flow map, which Loom cannot edit; set ${LOOM_DEPENDENCY} to ${publishedSpec} there yourself.`);
2696
3816
  }
2697
- const publication = await findPublishedLoomPublicationForCommit(state.sourceRoot, state.sourceCommit, commandRunner, env, publishedSpec);
2698
- publishedSpec = publication.version;
2699
- if (publication.reason === "contains-commit") {
2700
- notes.push(`Local Loom commit ${state.sourceCommit.slice(0, 12)} is included in published ${LOOM_DEPENDENCY}@${publication.version}.`);
3817
+ else if (!entry) {
3818
+ notes.push(`package.json uses \`${catalog.raw}\`, but pnpm-workspace.yaml has no ${LOOM_DEPENDENCY} entry in that catalog; add \`${LOOM_DEPENDENCY}: ${publishedSpec}\` there.`);
2701
3819
  }
2702
- else {
2703
- notes.push(`Local Loom commit ${state.sourceCommit.slice(0, 12)} has no package-relevant changes after ${publication.tag}, so published ${LOOM_DEPENDENCY}@${publication.version} covers this sync.`);
3820
+ else if (entry.spec !== publishedSpec) {
3821
+ const updated = setLoomCatalogEntryText(currentText, entry, publishedSpec);
3822
+ if (updated !== null) {
3823
+ await writeFile(workspacePath, updated, "utf8");
3824
+ changedFiles.push("pnpm-workspace.yaml");
3825
+ catalogChanged = true;
3826
+ }
2704
3827
  }
2705
3828
  }
2706
- else if (needsPublicationProof) {
2707
- notes.push("No recorded Loom sync commit was found; switching back to the existing published dependency without proving whether local Loom changes were required.");
3829
+ else {
3830
+ const dependencyUpdate = await mutateProjectDependencies(cwd, tooling.dependencies, {
3831
+ dependencies: { [LOOM_DEPENDENCY]: publishedSpec },
3832
+ replace: true,
3833
+ });
3834
+ if (dependencyUpdate.changed) {
3835
+ changedFiles.push(dependencyUpdate.config);
3836
+ }
2708
3837
  }
2709
- const dependencyUpdate = await mutateProjectDependencies(cwd, tooling.dependencies, {
2710
- dependencies: { [LOOM_DEPENDENCY]: publishedSpec },
2711
- replace: true,
2712
- });
2713
- const denoUpdate = denoConfig && denoLink
2714
- ? await mutateDenoLinks(cwd, denoConfig, { remove: denoLink.link })
3838
+ const denoUpdate = denoConfig && denoLinks.length
3839
+ ? await mutateDenoLinks(cwd, denoConfig, { remove: denoLinks })
2715
3840
  : null;
2716
- const update = denoMode
2717
- ? { changed: denoUpdate?.changed ?? false, text: "" }
2718
- : clearPnpmWorkspaceLocalDevText(await readTextIfExists(workspacePath));
2719
- const changedFiles = [];
2720
- if (dependencyUpdate.changed) {
2721
- changedFiles.push(dependencyUpdate.config);
2722
- }
2723
- if (update.changed) {
2724
- if (denoMode) {
2725
- changedFiles.push(denoConfig);
3841
+ let overrideRemoved = false;
3842
+ if (denoMode) {
3843
+ if (denoUpdate?.changed) {
3844
+ // The dependency pin may have changed the same file already.
3845
+ if (!changedFiles.includes(denoConfig))
3846
+ changedFiles.push(denoConfig);
3847
+ overrideRemoved = true;
2726
3848
  }
2727
- else {
2728
- await writeTextOrDeleteIfEmpty(workspacePath, update.text);
2729
- changedFiles.push("pnpm-workspace.yaml");
3849
+ }
3850
+ else {
3851
+ for (const file of await clearPnpmLocalDevOverrides(cwd)) {
3852
+ if (!changedFiles.includes(file))
3853
+ changedFiles.push(file);
3854
+ overrideRemoved = true;
3855
+ }
3856
+ // Entries written by hand point pnpm at a local Loom just the same.
3857
+ const workspaceNow = await readTextIfExists(workspacePath);
3858
+ if (workspaceNow && !getManagedDevOverrideBlockText(workspaceNow)) {
3859
+ const update = removeUnmanagedPnpmWorkspaceLoomOverrides(workspaceNow);
3860
+ if (update.changed) {
3861
+ await writeTextOrDeleteIfEmpty(workspacePath, update.text);
3862
+ if (!changedFiles.includes("pnpm-workspace.yaml")) {
3863
+ changedFiles.push("pnpm-workspace.yaml");
3864
+ }
3865
+ overrideRemoved = true;
3866
+ }
3867
+ for (const { key, spec } of update.kept) {
3868
+ notes.push(`pnpm-workspace.yaml still overrides ${key} with ${spec} in a flow-style map, which Loom does not edit; remove that entry yourself before running \`pnpm install\`.`);
3869
+ }
2730
3870
  }
2731
3871
  }
2732
- if (update.changed || localLockfileResolution) {
2733
- notes.push(denoMode
2734
- ? `Run \`deno install\` in this project to return node_modules and deno.lock to published ${LOOM_DEPENDENCY}@${publishedSpec}.`
2735
- : `Run \`pnpm update --no-save ${LOOM_DEPENDENCY}@${publishedSpec}\` and then \`pnpm install\` in this project to return node_modules and the lockfile to the published ${LOOM_DEPENDENCY} dependency.`);
3872
+ if (denoMode) {
3873
+ if (overrideRemoved || localLockfileResolution) {
3874
+ notes.push(`Run \`deno install\` in this project to return node_modules and deno.lock to published ${LOOM_DEPENDENCY}@${publishedSpec}.`);
3875
+ }
2736
3876
  }
2737
- if (localLockfileResolution) {
2738
- notes.push(`pnpm-lock.yaml still resolves ${LOOM_DEPENDENCY} to ${localLockfileResolution} until that update is run.`);
3877
+ else if (overrideRemoved || localLockfileResolution) {
3878
+ const importer = lockfileText
3879
+ ? getLockfileRootImporterDependency(lockfileText, LOOM_DEPENDENCY)
3880
+ : null;
3881
+ // Earlier Loom versions linked through `pnpm update --no-save`, which
3882
+ // leaves the published specifier with a local version. While that
3883
+ // specifier still matches package.json, pnpm install treats the lockfile
3884
+ // as up to date and keeps the local resolution.
3885
+ const specifierUnchanged = catalog
3886
+ ? importer?.specifier === catalog.raw && !catalogChanged
3887
+ : importer?.specifier === publishedSpec;
3888
+ const legacyLocalResolution = importer?.version &&
3889
+ isLocalPackageSpec(importer.version) && specifierUnchanged
3890
+ ? localLockfileResolution ?? importer.version
3891
+ : null;
3892
+ if (legacyLocalResolution && catalog) {
3893
+ notes.push(`pnpm-lock.yaml still resolves ${LOOM_DEPENDENCY} to ${legacyLocalResolution} from an older \`pnpm update --no-save\` link, which a plain \`pnpm install\` keeps while the catalog version is unchanged. Restore pnpm-lock.yaml from git and run \`pnpm install\`.`);
3894
+ }
3895
+ else if (legacyLocalResolution) {
3896
+ const pinCommand = isExactSemverVersion(publishedSpec)
3897
+ ? `\`${dependencyRefreshCommand(tooling.dependencies, LOOM_DEPENDENCY, publishedSpec, { pnpmWorkspaceRoot: await pnpmWorkspaceDeclaresPackages(cwd) })}\``
3898
+ : `\`pnpm add --save-exact ${LOOM_DEPENDENCY}@<version>\` with the exact version to ship`;
3899
+ notes.push(`pnpm-lock.yaml still resolves ${LOOM_DEPENDENCY} to ${legacyLocalResolution} from an older \`pnpm update --no-save\` link, which a plain \`pnpm install\` keeps. If pnpm-lock.yaml has no other intended changes, restore it from git and run \`pnpm install\`, which also undoes dependency updates that link made; otherwise run ${pinCommand}, which replaces only the Loom resolution (\`pnpm add\` may re-sort package.json dependencies).`);
3900
+ }
3901
+ else {
3902
+ notes.push(`Run \`pnpm install\` in this project to return node_modules and pnpm-lock.yaml to published ${LOOM_DEPENDENCY}@${publishedSpec}; it keeps every other locked version.`);
3903
+ if (localLockfileResolution) {
3904
+ notes.push(`pnpm-lock.yaml still resolves ${LOOM_DEPENDENCY} to ${localLockfileResolution} until that install is run.`);
3905
+ }
3906
+ }
2739
3907
  }
2740
3908
  return {
2741
3909
  changedFiles,
2742
3910
  notes,
2743
3911
  };
2744
3912
  }
3913
+ /** Removes every managed local Loom override from a pnpm project. */
3914
+ async function clearPnpmLocalDevOverrides(cwd) {
3915
+ const changedFiles = [];
3916
+ const workspacePath = join(cwd, "pnpm-workspace.yaml");
3917
+ const workspaceUpdate = clearPnpmWorkspaceLocalDevText(await readTextIfExists(workspacePath));
3918
+ if (workspaceUpdate.changed) {
3919
+ await writeTextOrDeleteIfEmpty(workspacePath, workspaceUpdate.text);
3920
+ changedFiles.push("pnpm-workspace.yaml");
3921
+ }
3922
+ for (const { field } of PACKAGE_JSON_OVERRIDE_LOCATIONS) {
3923
+ if (await removePackageJsonLoomOverride(cwd, field) &&
3924
+ !changedFiles.includes("package.json")) {
3925
+ changedFiles.push("package.json");
3926
+ }
3927
+ }
3928
+ // Flags for maps whose Loom entry was already gone would otherwise
3929
+ // outlive the link and claim maps the project has since added.
3930
+ await writeCreatedPackageJsonMaps(cwd, {});
3931
+ return changedFiles;
3932
+ }
3933
+ function getRawPackageJsonMap(packageJson, field) {
3934
+ return field === "resolutions"
3935
+ ? packageJson.resolutions
3936
+ : packageJson.pnpm?.overrides;
3937
+ }
3938
+ async function readCreatedPackageJsonMaps(cwd) {
3939
+ return { ...(await readLocalDevState(cwd))?.createdPackageJsonMaps };
3940
+ }
3941
+ async function writeCreatedPackageJsonMaps(cwd, created, overrideSpec) {
3942
+ const state = await readLocalDevState(cwd);
3943
+ const { createdPackageJsonMaps: _previous, ...rest } = state ?? {
3944
+ dependency: LOOM_DEPENDENCY,
3945
+ localPackagePath: overrideSpec ? fileSpecToPath(cwd, overrideSpec) : "",
3946
+ syncedAt: new Date().toISOString(),
3947
+ version: 1,
3948
+ };
3949
+ if (!state && Object.keys(created).length === 0)
3950
+ return;
3951
+ await writeLocalDevStateIfChanged(cwd, Object.keys(created).length
3952
+ ? { ...rest, createdPackageJsonMaps: created }
3953
+ : rest);
3954
+ }
3955
+ /**
3956
+ * Removes Loom's managed (`file:`) override from one package.json map with
3957
+ * a minimal text edit. The map (and the `pnpm` object) is removed as well
3958
+ * only when it ends up empty and dev state records that Loom created it;
3959
+ * maps the project already had, or whose origin is unknown, always stay.
3960
+ * Never writes back a whole-file snapshot. Returns whether package.json
3961
+ * changed.
3962
+ */
3963
+ async function removePackageJsonLoomOverride(cwd, field) {
3964
+ const { packageJson } = await readProjectPackageJson(cwd);
3965
+ if (!isManagedPackageJsonLoomOverride(getPackageJsonOverrideMap(packageJson, field)[LOOM_DEPENDENCY])) {
3966
+ return false;
3967
+ }
3968
+ const created = await readCreatedPackageJsonMaps(cwd);
3969
+ const update = await mutatePackageJsonOverride(cwd, field, LOOM_DEPENDENCY, undefined, {
3970
+ removeEmptyMap: created[field] === true,
3971
+ removeEmptyPnpm: field === "pnpm.overrides" && created.pnpm === true,
3972
+ });
3973
+ delete created[field];
3974
+ if (field === "pnpm.overrides")
3975
+ delete created.pnpm;
3976
+ await writeCreatedPackageJsonMaps(cwd, created);
3977
+ return update.changed;
3978
+ }
2745
3979
  async function ensureManagedAgentsFile(cwd) {
2746
3980
  const relativePath = "AGENTS.md";
2747
3981
  const agentsPath = join(cwd, relativePath);
@@ -2956,7 +4190,15 @@ async function checkManagedAgentsFile(cwd) {
2956
4190
  warnings: [],
2957
4191
  };
2958
4192
  }
2959
- async function checkManagedLocalDevOverride(cwd, production = false) {
4193
+ /** Matches override keys that select Loom, including pnpm/yarn selectors. */
4194
+ function overrideKeyTargetsLoom(key) {
4195
+ const target = key.split(">").pop().trim();
4196
+ return target === LOOM_DEPENDENCY ||
4197
+ target.startsWith(`${LOOM_DEPENDENCY}@`) ||
4198
+ target.endsWith(`/${LOOM_DEPENDENCY}`) ||
4199
+ target.includes(`/${LOOM_DEPENDENCY}@`);
4200
+ }
4201
+ async function checkManagedLocalDevOverride(cwd, production, commandRunner, env) {
2960
4202
  const manifest = await readManifestIfExists(cwd);
2961
4203
  let denoLink = null;
2962
4204
  let denoConfig = null;
@@ -2971,8 +4213,17 @@ async function checkManagedLocalDevOverride(cwd, production = false) {
2971
4213
  // The main project tooling check reports invalid configuration separately.
2972
4214
  }
2973
4215
  const workspaceText = await readTextIfExists(join(cwd, "pnpm-workspace.yaml"));
2974
- const overrideSpec = getManagedDevOverrideSpec(workspaceText);
2975
- if (!overrideSpec && !denoLink) {
4216
+ const packageJson = denoLink ? null : await readPackageJsonIfExists(cwd);
4217
+ const workspaceSpec = getManagedDevOverrideSpec(workspaceText);
4218
+ // Any local spec for Loom in a package.json override map is a local-dev
4219
+ // link, whoever wrote it and whatever selector it uses, and must not ship.
4220
+ const packageJsonOverride = packageJson
4221
+ ? PACKAGE_JSON_OVERRIDE_LOCATIONS.flatMap(({ field, location }) => Object.entries(getPackageJsonOverrideMap(packageJson, field)).flatMap(([key, spec]) => overrideKeyTargetsLoom(key) && typeof spec === "string" &&
4222
+ isLocalPackageSpec(spec)
4223
+ ? [`${formatPnpmOverrideLocation(location)}: ${spec}`]
4224
+ : []))[0]
4225
+ : undefined;
4226
+ if (!workspaceSpec && !packageJsonOverride && !denoLink) {
2976
4227
  return {
2977
4228
  issues: [],
2978
4229
  suggestions: [],
@@ -2981,19 +4232,45 @@ async function checkManagedLocalDevOverride(cwd, production = false) {
2981
4232
  }
2982
4233
  const location = denoLink
2983
4234
  ? `${denoConfig} links: ${denoLink.link}`
2984
- : `pnpm-workspace.yaml: ${overrideSpec}`;
4235
+ : workspaceSpec
4236
+ ? `pnpm-workspace.yaml: ${workspaceSpec}`
4237
+ : packageJsonOverride;
2985
4238
  const restore = denoLink
2986
4239
  ? "Run `loom dev published`, then run `deno install` before committing or shipping a published build."
2987
- : `Run \`loom dev published\`, then follow its printed \`pnpm update --no-save ${LOOM_DEPENDENCY}@<version>\` command and run \`pnpm install\` before committing or shipping a published build.`;
4240
+ : "Run `loom dev published`, then run `pnpm install` (or the command it prints) before committing or shipping a published build.";
4241
+ const warnings = [];
4242
+ const suggestions = [restore];
4243
+ const activePnpmOverride = packageJson
4244
+ ? getActivePnpmLocalDevOverride(workspaceText, packageJson)
4245
+ : null;
4246
+ if (activePnpmOverride && packageJson) {
4247
+ // Use the same placement decision as `loom dev sync`, so the advice here
4248
+ // is exactly what the next sync does.
4249
+ const placement = await resolvePnpmLocalDevOverrideLocation(cwd, packageJson, commandRunner, env);
4250
+ const pnpmLabel = placement.pnpmVersion === null
4251
+ ? "pnpm (version unknown, assumed 10.5.1 or newer)"
4252
+ : `pnpm ${placement.pnpmVersion}`;
4253
+ if (placement.conflict) {
4254
+ warnings.push(placement.conflict);
4255
+ }
4256
+ else if (activePnpmOverride.location === "pnpm-workspace.yaml"
4257
+ ? placement.location !== "pnpm-workspace.yaml"
4258
+ : placement.location === "pnpm-workspace.yaml" &&
4259
+ placement.pnpmMajor !== null && placement.pnpmMajor >= 11) {
4260
+ warnings.push(`${pnpmLabel} does not apply the Loom override in ${formatPnpmOverrideLocation(activePnpmOverride.location)}, so this app may still use the published Loom package.`);
4261
+ suggestions.push(`Run \`loom dev sync\` to move the override to ${formatPnpmOverrideLocation(placement.location)}, where pnpm applies it.`);
4262
+ }
4263
+ }
2988
4264
  return {
2989
4265
  issues: production
2990
4266
  ? [
2991
4267
  `Local Loom dev override is active in ${location}`,
2992
4268
  ]
2993
4269
  : [],
2994
- suggestions: [restore],
2995
- warnings: production ? [] : [
4270
+ suggestions,
4271
+ warnings: production ? warnings : [
2996
4272
  `Local Loom dev override is active in ${location}`,
4273
+ ...warnings,
2997
4274
  ],
2998
4275
  };
2999
4276
  }
@@ -3032,7 +4309,6 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
3032
4309
  const issues = [];
3033
4310
  const suggestions = new Set();
3034
4311
  const warnings = [];
3035
- const dependency = packageJson.dependencies?.[LOOM_DEPENDENCY];
3036
4312
  const production = options.production;
3037
4313
  const projectMetadata = await readProjectPackageMetadata(cwd);
3038
4314
  let dependencyTooling = {
@@ -3046,8 +4322,38 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
3046
4322
  catch {
3047
4323
  // The main tooling check owns the validation error; release hints can fall back.
3048
4324
  }
4325
+ // A pnpm `catalog:` reference pins Loom in pnpm-workspace.yaml instead.
4326
+ // Other managers' catalogs (Yarn 4) are not read.
4327
+ const loomDependency = await resolveLoomDependencySpec(cwd, packageJson);
4328
+ const dependency = dependencyTooling.manager === "pnpm"
4329
+ ? loomDependency.effective
4330
+ : loomDependency.raw;
3049
4331
  const localLockfileResolution = await getProjectLocalLoomLockfileResolution(cwd);
3050
4332
  const devState = await readLocalDevState(cwd);
4333
+ const refreshOptions = {
4334
+ pnpmWorkspaceRoot: await pnpmWorkspaceDeclaresPackages(cwd),
4335
+ };
4336
+ const catalogName = dependencyTooling.manager === "pnpm"
4337
+ ? loomDependency.catalogName
4338
+ : null;
4339
+ const pinLocation = catalogName
4340
+ ? `the pnpm-workspace.yaml \`${loomDependency.catalogEntry?.label ?? "catalog:"}\` map`
4341
+ : dependencyTooling.config;
4342
+ // A pnpm pin change is a manual package.json edit plus `pnpm install`,
4343
+ // which gives the same lockfile as `pnpm add --save-exact` without
4344
+ // re-sorting package.json. Only a lockfile an older `pnpm update --no-save`
4345
+ // link left behind, under an unchanged pin, needs `pnpm add`.
4346
+ const pinSuggestion = (version) => catalogName
4347
+ ? formatLoomCatalogPinAdvice(loomDependency.catalogEntry, catalogName, version)
4348
+ : dependencyTooling.manager !== "pnpm"
4349
+ ? `Run ${dependencyRefreshCommand(dependencyTooling, LOOM_DEPENDENCY, version, refreshOptions)}.`
4350
+ : version === dependency
4351
+ ? `Restore pnpm-lock.yaml from git if it has no other intended changes and run \`pnpm install\`; otherwise run \`${dependencyRefreshCommand(dependencyTooling, LOOM_DEPENDENCY, version, refreshOptions)}\` (\`pnpm add\` may re-sort package.json dependencies).`
4352
+ : `Set ${LOOM_DEPENDENCY} to ${version} in package.json, then run \`pnpm install\`.`;
4353
+ // While the override is active it forces the local package whatever the
4354
+ // pin says, so it has to be removed before any refresh can help.
4355
+ const pnpmOverrideActive = dependencyTooling.manager === "pnpm" &&
4356
+ getActivePnpmLocalDevOverride(await readTextIfExists(join(cwd, "pnpm-workspace.yaml")), packageJson) !== null;
3051
4357
  if (localLockfileResolution) {
3052
4358
  addReleaseCheckMessage(issues, warnings, production, `pnpm-lock.yaml resolves @gadicc/loom to a local package: ${localLockfileResolution}`);
3053
4359
  suggestions.add("Run `loom dev published`, then refresh the lockfile with the published @gadicc/loom version before production build.");
@@ -3079,8 +4385,10 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
3079
4385
  "package-equivalent"
3080
4386
  ? `package-relevant files match ${LOOM_DEPENDENCY}@${publication.version}`
3081
4387
  : `it is published as ${LOOM_DEPENDENCY}@${publication.version}`;
3082
- addReleaseCheckMessage(issues, warnings, production, `This app was last synced against Loom commit ${shortCommit}; ${publicationDescription}, but ${dependencyTooling.config} is pinned to ${dependency}.`);
3083
- suggestions.add(`Run ${dependencyRefreshCommand(dependencyTooling, LOOM_DEPENDENCY, publication.version)}.`);
4388
+ addReleaseCheckMessage(issues, warnings, production, `This app was last synced against Loom commit ${shortCommit}; ${publicationDescription}, but ${pinLocation} is pinned to ${dependency}.`);
4389
+ suggestions.add(pnpmOverrideActive
4390
+ ? "Run `loom dev published`, which pins the covering version, then run `pnpm install`."
4391
+ : pinSuggestion(publication.version));
3084
4392
  }
3085
4393
  else if (localLockfileResolution) {
3086
4394
  const publicationDescription = publication.reason ===
@@ -3088,7 +4396,13 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
3088
4396
  ? `has no package-relevant changes after ${publication.tag}, so ${LOOM_DEPENDENCY}@${publication.version} covers it`
3089
4397
  : `is published as ${LOOM_DEPENDENCY}@${publication.version}`;
3090
4398
  warnings.push(`The synced Loom commit ${shortCommit} ${publicationDescription}; refresh the lockfile away from ${localLockfileResolution}.`);
3091
- suggestions.add(`Run ${dependencyRefreshCommand(dependencyTooling, LOOM_DEPENDENCY, publication.version)}.`);
4399
+ suggestions.add(pnpmOverrideActive
4400
+ ? "Run `loom dev published`, which pins the covering version, then run `pnpm install`."
4401
+ : catalogName && dependency === publication.version
4402
+ // pnpm keeps a local resolution while the catalog version
4403
+ // it was linked under is unchanged.
4404
+ ? "Restore pnpm-lock.yaml from git and run `pnpm install`."
4405
+ : pinSuggestion(publication.version));
3092
4406
  }
3093
4407
  break;
3094
4408
  }
@@ -3113,8 +4427,12 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
3113
4427
  else {
3114
4428
  const installedPackage = parseJson(installedPackageText, join("node_modules", LOOM_DEPENDENCY, "package.json"));
3115
4429
  if (installedPackage.version !== dependency) {
3116
- issues.push(`Installed ${LOOM_DEPENDENCY} version ${installedPackage.version} does not match ${dependencyTooling.config} ${dependency}.`);
3117
- suggestions.add(`Run ${dependencyRefreshCommand(dependencyTooling, LOOM_DEPENDENCY, dependency)}.`);
4430
+ issues.push(`Installed ${LOOM_DEPENDENCY} version ${installedPackage.version} does not match ${pinLocation} ${dependency}.`);
4431
+ suggestions.add(pnpmOverrideActive
4432
+ ? "Run `loom dev published`, then run `pnpm install`."
4433
+ : dependencyTooling.manager === "pnpm"
4434
+ ? "Run `pnpm install`."
4435
+ : pinSuggestion(dependency));
3118
4436
  }
3119
4437
  }
3120
4438
  }
@@ -4692,6 +6010,18 @@ import { apiKeyPolicy } from "${toAliasImportPath(config.modules.policyModule)}"
4692
6010
  import { apiKeyAuditRepository } from "${toAliasImportPath(config.modules.repositoryModule)}";
4693
6011
 
4694
6012
  // Generated verifier stub: adapt Better Auth verifyApiKey() exactly once here.
6013
+ // Replace it with Loom's shared verifier, which checks the requested
6014
+ // permission itself so a scope miss is denied as insufficient_permission:
6015
+ //
6016
+ // import { createBetterAuthApiKeyVerifier } from "@gadicc/loom/apiKeys";
6017
+ // import { auth } from "<the app's Better Auth module>";
6018
+ // import { apiKeyScopes } from "<the app's defineApiKeyScopes registry>";
6019
+ //
6020
+ // export const apiKeyVerifier = createBetterAuthApiKeyVerifier({
6021
+ // auth,
6022
+ // configId: "default", // the api-key plugin configId these keys use
6023
+ // scopes: apiKeyScopes,
6024
+ // });
4695
6025
  export const apiKeyVerifier: ApiKeyVerifier = {
4696
6026
  verify() {
4697
6027
  return Promise.resolve({ ok: false, code: "invalid_credential" });
@@ -8513,7 +9843,7 @@ async function applyApiKeysFeature(cwd, framework, manifest, activate) {
8513
9843
  changedFiles.push(...materialized.changedFiles);
8514
9844
  notes.push(...materialized.notes);
8515
9845
  config.schema = materialized.schema;
8516
- notes.push("No migration was generated. Review the audit schema diff, reconcile the Better Auth API-key table, then generate the app-local migration deliberately.", "Install compatible matching `better-auth` and `@better-auth/api-key` versions, configure user-owned keys, keep API-key sessions disabled, and disable the plugin's built-in per-key rate limit for this release.");
9846
+ notes.push("No migration was generated. Review the audit schema diff, reconcile the Better Auth API-key table, then generate the app-local migration deliberately.", "Install compatible matching `better-auth` and `@better-auth/api-key` versions, configure user-owned keys, keep API-key sessions disabled, and disable the plugin's built-in per-key rate limit for this release.", "Disable the api-key plugin's HTTP endpoints in the app-owned Better Auth options with `disabledPaths: withBetterAuthApiKeyHttpPathsDisabled()` from `@gadicc/loom/apiKeys`. Otherwise any signed-in user can call them to re-enable revoked keys, remove expiry, or hard-delete keys; server actions calling `auth.api.*` keep working.");
8517
9847
  }
8518
9848
  const scaffolds = [
8519
9849
  [config.modules.policyModule, apiKeysPolicyTemplate(), "policy"],
@@ -9526,184 +10856,1124 @@ async function checkFilesFeature(cwd, framework, manifest, options) {
9526
10856
  for (const suggestion of local.suggestions)
9527
10857
  suggestions.add(suggestion);
9528
10858
  }
9529
- const routeText = await readTextIfExists(join(cwd, config.entrypoints.routeHandler));
9530
- if (!routeText) {
9531
- issues.push(`Files route handler is missing: ${config.entrypoints.routeHandler}`);
9532
- suggestions.add("Run `loom add files` to scaffold the files route handler.");
10859
+ const routeText = await readTextIfExists(join(cwd, config.entrypoints.routeHandler));
10860
+ if (!routeText) {
10861
+ issues.push(`Files route handler is missing: ${config.entrypoints.routeHandler}`);
10862
+ suggestions.add("Run `loom add files` to scaffold the files route handler.");
10863
+ }
10864
+ else {
10865
+ if (!matchesImportSource(routeText, ["@gadicc/loom/next/files"])) {
10866
+ issues.push(`Files route handler is not wired to @gadicc/loom/next/files: ${config.entrypoints.routeHandler}`);
10867
+ }
10868
+ if (!routeText.includes("createFilesRouteHandlers")) {
10869
+ issues.push(`Files route handler does not call createFilesRouteHandlers: ${config.entrypoints.routeHandler}`);
10870
+ }
10871
+ const routeImportChecks = [
10872
+ [config.modules.accessModule, "access policy"],
10873
+ [config.modules.repositoryModule, "repository"],
10874
+ [config.modules.storageModule, "storage adapter"],
10875
+ ];
10876
+ for (const [modulePath, label] of routeImportChecks) {
10877
+ if (!matchesImportSource(routeText, getImportSpecifierCandidates(config.entrypoints.routeHandler, modulePath))) {
10878
+ issues.push(`Files route handler does not import the configured ${label}: ${config.entrypoints.routeHandler}`);
10879
+ suggestions.add(`Import the files ${label} from ${modulePath} in the route handler.`);
10880
+ }
10881
+ }
10882
+ }
10883
+ return {
10884
+ issues,
10885
+ suggestions: [...suggestions],
10886
+ warnings,
10887
+ };
10888
+ }
10889
+ async function checkMailFeature(cwd, framework, manifest, options) {
10890
+ const issues = [];
10891
+ const suggestions = new Set();
10892
+ const warnings = [];
10893
+ const feature = manifest.features.mail;
10894
+ if (!feature || feature.status !== "active") {
10895
+ return { issues, suggestions: [], warnings };
10896
+ }
10897
+ for (const dependency of ["auth", "db"]) {
10898
+ if (manifest.features[dependency]?.status !== "active") {
10899
+ issues.push(`Mail feature requires the active ${dependency} feature.`);
10900
+ suggestions.add(`Run \`loom add ${dependency}\` before using mail.`);
10901
+ }
10902
+ }
10903
+ if (issues.length)
10904
+ return { issues, suggestions: [...suggestions], warnings };
10905
+ const { packageJson } = await readProjectPackageJson(cwd);
10906
+ const dbConfig = mergeDbConfig(framework, manifest.features.db.config);
10907
+ const config = getMailConfig(framework, dbConfig, packageJson, feature.config, manifest.features.jobs?.status === "active");
10908
+ const schema = config.schema;
10909
+ const latestSchema = getLatestManagedSchemaConfig(schema);
10910
+ if (schema.mode !== "managed-local" || schema.blueprint !== "mail") {
10911
+ issues.push("Mail must use the managed-local mail schema blueprint.");
10912
+ suggestions.add("Run `loom add mail` to restore the mail schema config.");
10913
+ }
10914
+ if (schema.exports.length !== 3) {
10915
+ issues.push("Mail schema must configure message, delivery, and event exports.");
10916
+ }
10917
+ if (schema.version > MAIL_SCHEMA_BLUEPRINT_VERSION) {
10918
+ issues.push(`Mail schema blueprint version ${schema.version} is newer than this Loom package supports.`);
10919
+ }
10920
+ else if (schema.version < MAIL_SCHEMA_BLUEPRINT_VERSION) {
10921
+ warnings.push(`Mail schema blueprint is stale: ${schema.version} < ${MAIL_SCHEMA_BLUEPRINT_VERSION}.`);
10922
+ suggestions.add("Run `loom db schemas sync`, then review and migrate the diff.");
10923
+ }
10924
+ const schemaText = await readTextIfExists(join(cwd, schema.module));
10925
+ if (!schemaText) {
10926
+ issues.push(`Mail schema file is missing: ${schema.module}`);
10927
+ suggestions.add("Run `loom db schemas sync`.");
10928
+ }
10929
+ else {
10930
+ const currentHash = hashManagedSchemaText(schemaText);
10931
+ if (currentHash !== schema.hash) {
10932
+ if (currentHash === latestSchema.hash) {
10933
+ warnings.push(`Mail schema manifest hash is stale for ${schema.module}.`);
10934
+ suggestions.add("Run `loom db schemas sync` to refresh loom.json.");
10935
+ }
10936
+ else {
10937
+ issues.push(`Mail schema file has local edits outside the managed hash: ${schema.module}`);
10938
+ suggestions.add("Move app-specific mail schema additions to a separate file, then run `loom db schemas sync`.");
10939
+ }
10940
+ }
10941
+ const barrelText = await readTextIfExists(join(cwd, dbConfig.dirs.schemaDir, "index.ts"));
10942
+ if (!barrelText || !schemaBarrelExportsModule(barrelText, schema, dbConfig)) {
10943
+ issues.push(`DB schema barrel does not export the managed mail schema: ${dbConfig.dirs.schemaDir}/index.ts`);
10944
+ suggestions.add("Run `loom db schemas sync`.");
10945
+ }
10946
+ }
10947
+ const requiredFiles = [
10948
+ config.modules.accessModule,
10949
+ config.modules.actionsModule,
10950
+ config.modules.repositoryModule,
10951
+ config.modules.serviceModule,
10952
+ config.modules.transportModule,
10953
+ config.entrypoints.adminPage,
10954
+ config.entrypoints.webhookRoute,
10955
+ ...(config.jobs.enabled ? [config.modules.jobModule] : []),
10956
+ ];
10957
+ for (const relativePath of requiredFiles) {
10958
+ if (!await exists(join(cwd, relativePath))) {
10959
+ issues.push(`Mail scaffold file is missing: ${relativePath}`);
10960
+ suggestions.add("Run `loom add mail` to restore missing scaffolds.");
10961
+ }
10962
+ }
10963
+ const accessText = await readTextIfExists(join(cwd, config.modules.accessModule));
10964
+ if (accessText && !accessText.includes("authorizeMailAdmin")) {
10965
+ issues.push(`Mail access module does not export authorizeMailAdmin: ${config.modules.accessModule}`);
10966
+ }
10967
+ const generatedDenyAll = accessText?.includes("Mail admin access policy is not configured.") ?? false;
10968
+ if (generatedDenyAll) {
10969
+ const message = `Mail admin access still uses the generated deny-all stub: ${config.modules.accessModule}`;
10970
+ if (options.production)
10971
+ issues.push(message);
10972
+ else
10973
+ warnings.push(message);
10974
+ suggestions.add("Connect authorizeMailAdmin() to the app's fresh session/admin-role check.");
10975
+ }
10976
+ const contentChecks = [
10977
+ [
10978
+ config.modules.repositoryModule,
10979
+ "@gadicc/loom/mail",
10980
+ "Mail repository is not typed against the shared mail contract",
10981
+ ],
10982
+ [
10983
+ config.modules.serviceModule,
10984
+ "createLoomMailService",
10985
+ "Mail service is not wired to the shared durable service",
10986
+ ],
10987
+ [
10988
+ config.modules.transportModule,
10989
+ "createPostalMailTransport",
10990
+ "Mail transport is not wired to the Postal adapter",
10991
+ ],
10992
+ [
10993
+ config.modules.transportModule,
10994
+ "POSTAL_WEBHOOK_PUBLIC_KEYS",
10995
+ "Mail transport does not configure Postal webhook public keys",
10996
+ ],
10997
+ [
10998
+ config.entrypoints.webhookRoute,
10999
+ "createPostalWebhookRouteHandler",
11000
+ "Mail webhook route does not use the signed shared route handler",
11001
+ ],
11002
+ [
11003
+ config.modules.actionsModule,
11004
+ "authorizeMailAdmin",
11005
+ "Mail admin actions do not enforce the app-owned admin boundary",
11006
+ ],
11007
+ [
11008
+ config.entrypoints.adminPage,
11009
+ "authorizeMailAdmin",
11010
+ "Mail admin page does not enforce the app-owned admin boundary",
11011
+ ],
11012
+ ];
11013
+ for (const [relativePath, snippet, label] of contentChecks) {
11014
+ const text = await readTextIfExists(join(cwd, relativePath));
11015
+ if (text && !text.includes(snippet)) {
11016
+ issues.push(`${label}: ${relativePath}`);
11017
+ suggestions.add("Run `loom add mail` or update loom.json for intentional paths.");
11018
+ }
11019
+ }
11020
+ if (config.ui.adapter === "mui" &&
11021
+ !hasPackageDependency(packageJson, "@mui/material")) {
11022
+ issues.push("Mail's MUI adapter is active but @mui/material is not installed.");
11023
+ }
11024
+ if (config.jobs.enabled && manifest.features.jobs?.status !== "active") {
11025
+ warnings.push("Mail drain job is enabled while the Loom jobs feature is inactive.");
11026
+ suggestions.add("Run `loom add jobs` or disable features.mail.config.jobs.enabled.");
11027
+ }
11028
+ return { issues, suggestions: [...suggestions], warnings };
11029
+ }
11030
+ function packageDependencySpec(packageJson, dependencyName) {
11031
+ return packageJson.dependencies?.[dependencyName] ??
11032
+ packageJson.devDependencies?.[dependencyName];
11033
+ }
11034
+ function dependencyMajorMinor(spec) {
11035
+ const match = spec?.match(/(\d+)\.(\d+)/);
11036
+ return match ? `${match[1]}.${match[2]}` : undefined;
11037
+ }
11038
+ /**
11039
+ * Blanks JavaScript/TypeScript comments while keeping string and template
11040
+ * literals, so advisory text checks ignore commented-out code. Newlines are
11041
+ * kept. Regular-expression literals are not recognised; one containing a
11042
+ * quote or comment opener can confuse it, which only affects these checks.
11043
+ */
11044
+ function stripJsComments(text) {
11045
+ let output = "";
11046
+ let index = 0;
11047
+ while (index < text.length) {
11048
+ const char = text[index];
11049
+ const next = text[index + 1];
11050
+ if (char === "/" && next === "/") {
11051
+ const end = text.indexOf("\n", index);
11052
+ output += " ";
11053
+ if (end === -1)
11054
+ break;
11055
+ index = end;
11056
+ continue;
11057
+ }
11058
+ if (char === "/" && next === "*") {
11059
+ const end = text.indexOf("*/", index + 2);
11060
+ const comment = end === -1
11061
+ ? text.slice(index)
11062
+ : text.slice(index, end + 2);
11063
+ output += comment.replace(/[^\n]/g, " ");
11064
+ index += comment.length;
11065
+ continue;
11066
+ }
11067
+ if (char === '"' || char === "'" || char === "`") {
11068
+ const end = skipJsStringLiteral(text, index);
11069
+ output += text.slice(index, end);
11070
+ index = end;
11071
+ continue;
11072
+ }
11073
+ output += char;
11074
+ index += 1;
11075
+ }
11076
+ return output;
11077
+ }
11078
+ /** Returns the index just past the string literal that starts at `start`. */
11079
+ function skipJsStringLiteral(text, start) {
11080
+ const quote = text[start];
11081
+ let index = start + 1;
11082
+ while (index < text.length) {
11083
+ const char = text[index];
11084
+ if (char === "\\") {
11085
+ index += 2;
11086
+ continue;
11087
+ }
11088
+ index += 1;
11089
+ if (char === quote)
11090
+ break;
11091
+ if (quote !== "`" && char === "\n")
11092
+ break;
11093
+ }
11094
+ return Math.min(index, text.length);
11095
+ }
11096
+ /**
11097
+ * Replaces the contents of string and template literals with spaces, keeping
11098
+ * quotes, newlines, and offsets, so searches only see code.
11099
+ */
11100
+ function blankJsStrings(text) {
11101
+ let output = "";
11102
+ let index = 0;
11103
+ while (index < text.length) {
11104
+ const char = text[index];
11105
+ if (char === '"' || char === "'" || char === "`") {
11106
+ const end = skipJsStringLiteral(text, index);
11107
+ output += char + text.slice(index + 1, end).replace(/[^\n]/g, " ");
11108
+ if (end - index >= 2 && text[end - 1] === char) {
11109
+ output = output.slice(0, -1) + char;
11110
+ }
11111
+ index = end;
11112
+ continue;
11113
+ }
11114
+ output += char;
11115
+ index += 1;
11116
+ }
11117
+ return output;
11118
+ }
11119
+ /** Comment-free text plus a same-length copy whose string contents are blank. */
11120
+ function prepareJsText(text) {
11121
+ const code = stripJsComments(text);
11122
+ return { blanked: blankJsStrings(code), code };
11123
+ }
11124
+ /**
11125
+ * Reads one expression starting at `start` until a top-level `,`, `;`, or
11126
+ * closing bracket, skipping string literals. A top-level line break ends it
11127
+ * unless the neighbouring lines continue it (an operator or `.` on either
11128
+ * side), so a chained `.filter()` stays part of the expression. Expects
11129
+ * comment-free text.
11130
+ */
11131
+ function readJsExpression(text, start) {
11132
+ const blanked = blankJsStrings(text);
11133
+ let index = start;
11134
+ while (index < blanked.length && /\s/.test(blanked[index]))
11135
+ index += 1;
11136
+ const begin = index;
11137
+ let depth = 0;
11138
+ while (index < blanked.length) {
11139
+ const char = blanked[index];
11140
+ if (char === "(" || char === "[" || char === "{")
11141
+ depth += 1;
11142
+ else if (char === ")" || char === "]" || char === "}") {
11143
+ if (depth === 0)
11144
+ break;
11145
+ depth -= 1;
11146
+ }
11147
+ else if (depth === 0 && (char === "," || char === ";")) {
11148
+ break;
11149
+ }
11150
+ else if (depth === 0 && char === "\n") {
11151
+ const before = blanked.slice(begin, index).trimEnd();
11152
+ const after = blanked.slice(index).trimStart();
11153
+ const continued = /[=([{,?:+\-*/%&|^!<>~.]$/.test(before) ||
11154
+ /^(?:[.?:+\-*/%&|^<>=([]|as\s|satisfies\s)/.test(after);
11155
+ if (!continued)
11156
+ break;
11157
+ }
11158
+ index += 1;
11159
+ }
11160
+ return text.slice(begin, index).trim();
11161
+ }
11162
+ /** Index of the bracket closing the one at `open` in blanked text, or -1. */
11163
+ function findJsClosingBracket(blanked, open) {
11164
+ let depth = 0;
11165
+ for (let index = open; index < blanked.length; index += 1) {
11166
+ const char = blanked[index];
11167
+ if (char === "(" || char === "[" || char === "{")
11168
+ depth += 1;
11169
+ else if (char === ")" || char === "]" || char === "}") {
11170
+ depth -= 1;
11171
+ if (depth === 0)
11172
+ return index;
11173
+ }
11174
+ }
11175
+ return -1;
11176
+ }
11177
+ /** Splits list or object-literal contents on top-level commas. */
11178
+ function splitJsTopLevel(text) {
11179
+ const blanked = blankJsStrings(text);
11180
+ const parts = [];
11181
+ let depth = 0;
11182
+ let start = 0;
11183
+ for (let index = 0; index < blanked.length; index += 1) {
11184
+ const char = blanked[index];
11185
+ if (char === "(" || char === "[" || char === "{")
11186
+ depth += 1;
11187
+ else if (char === ")" || char === "]" || char === "}")
11188
+ depth -= 1;
11189
+ else if (char === "," && depth === 0) {
11190
+ parts.push(text.slice(start, index).trim());
11191
+ start = index + 1;
11192
+ }
11193
+ }
11194
+ parts.push(text.slice(start).trim());
11195
+ return parts.filter(Boolean);
11196
+ }
11197
+ /** Drops wrapping parentheses and a top-level `as T`/`satisfies T` suffix. */
11198
+ function unwrapJsExpression(expression) {
11199
+ let current = expression.trim();
11200
+ for (let attempt = 0; attempt < 8; attempt += 1) {
11201
+ const blanked = blankJsStrings(current);
11202
+ let depth = 0;
11203
+ let cut = -1;
11204
+ for (let index = 0; index < blanked.length; index += 1) {
11205
+ const char = blanked[index];
11206
+ if (char === "(" || char === "[" || char === "{")
11207
+ depth += 1;
11208
+ else if (char === ")" || char === "]" || char === "}")
11209
+ depth -= 1;
11210
+ else if (depth === 0 && /\s/.test(char) &&
11211
+ /^\s+(?:as|satisfies)\s/.test(blanked.slice(index))) {
11212
+ cut = index;
11213
+ break;
11214
+ }
11215
+ }
11216
+ if (cut !== -1) {
11217
+ current = current.slice(0, cut).trim();
11218
+ continue;
11219
+ }
11220
+ if (current.startsWith("(") &&
11221
+ findJsClosingBracket(blanked, 0) === current.length - 1) {
11222
+ current = current.slice(1, -1).trim();
11223
+ continue;
11224
+ }
11225
+ break;
11226
+ }
11227
+ return current;
11228
+ }
11229
+ /** `{ callee, args }` when the whole expression is one call, else null. */
11230
+ function parseWholeJsCall(expression) {
11231
+ const match = expression.match(/^([A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*)\s*\(/);
11232
+ if (!match)
11233
+ return null;
11234
+ const open = match[0].length - 1;
11235
+ if (findJsClosingBracket(blankJsStrings(expression), open) !==
11236
+ expression.length - 1) {
11237
+ return null;
11238
+ }
11239
+ return {
11240
+ args: expression.slice(open + 1, -1),
11241
+ callee: match[1].replace(/\s+/g, ""),
11242
+ };
11243
+ }
11244
+ /** The contents of a whole `[...]` or `{...}` literal, else null. */
11245
+ function wholeJsBracketContents(expression, open) {
11246
+ if (!expression.startsWith(open) ||
11247
+ findJsClosingBracket(blankJsStrings(expression), 0) !==
11248
+ expression.length - 1) {
11249
+ return null;
11250
+ }
11251
+ return expression.slice(1, -1);
11252
+ }
11253
+ /** The value of a plain string literal (no template substitutions). */
11254
+ function jsStringLiteralValue(expression) {
11255
+ const quote = expression[0];
11256
+ if (quote !== '"' && quote !== "'" && quote !== "`")
11257
+ return null;
11258
+ if (skipJsStringLiteral(expression, 0) !== expression.length)
11259
+ return null;
11260
+ const value = expression.slice(1, -1);
11261
+ return value.includes("\\") || (quote === "`" && value.includes("${"))
11262
+ ? null
11263
+ : value;
11264
+ }
11265
+ const JS_IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
11266
+ const JS_IDENTIFIER_SOURCE = String.raw `[A-Za-z_$][\w$]*`;
11267
+ const LOOM_API_KEYS_IMPORT_SOURCES = new Set([
11268
+ "@gadicc/loom",
11269
+ "@gadicc/loom/api-keys",
11270
+ "@gadicc/loom/apiKeys",
11271
+ ]);
11272
+ const NO_JS_ENV = new Map();
11273
+ async function loadJsSourceModule(context, relativePath) {
11274
+ if (!context.modules.has(relativePath)) {
11275
+ const text = await readTextIfExists(join(context.cwd, relativePath));
11276
+ context.modules.set(relativePath, text === null
11277
+ ? null
11278
+ : { path: relativePath, prepared: prepareJsText(text) });
11279
+ }
11280
+ return context.modules.get(relativePath) ?? null;
11281
+ }
11282
+ /**
11283
+ * Value imports of a module: `imported` is `"*"` for a namespace import and
11284
+ * `"default"` for a default import.
11285
+ */
11286
+ function parseJsValueImports(module) {
11287
+ const { blanked, code } = module.prepared;
11288
+ const imports = [];
11289
+ const pattern = /(?<![\w$.])import\s+(type\s+)?([^;]*?)\s*from\s*(["'])([^"']+)\3/g;
11290
+ for (const match of code.matchAll(pattern)) {
11291
+ if (match[1] || !blanked.startsWith("import", match.index ?? 0))
11292
+ continue;
11293
+ const clause = match[2].trim();
11294
+ const source = match[4];
11295
+ const defaultImport = clause.match(/^([A-Za-z_$][\w$]*)\s*(?:,|$)/);
11296
+ if (defaultImport) {
11297
+ imports.push({ imported: "default", local: defaultImport[1], source });
11298
+ }
11299
+ const namespace = clause.match(/\*\s*as\s+([A-Za-z_$][\w$]*)/);
11300
+ if (namespace) {
11301
+ imports.push({ imported: "*", local: namespace[1], source });
11302
+ }
11303
+ const named = clause.match(/\{([^}]*)\}/);
11304
+ for (const specifier of named ? named[1].split(",") : []) {
11305
+ const trimmed = specifier.trim();
11306
+ if (!trimmed || /^type\s/.test(trimmed))
11307
+ continue;
11308
+ const [imported, local = imported] = trimmed.split(/\s+as\s+/);
11309
+ if (JS_IDENTIFIER.test(imported) && JS_IDENTIFIER.test(local)) {
11310
+ imports.push({ imported, local, source });
11311
+ }
11312
+ }
11313
+ }
11314
+ return imports;
11315
+ }
11316
+ /** Bracket depth before each offset of blanked text. */
11317
+ function jsBracketDepths(blanked) {
11318
+ const depths = new Int32Array(blanked.length + 1);
11319
+ let depth = 0;
11320
+ for (let index = 0; index < blanked.length; index += 1) {
11321
+ depths[index] = depth;
11322
+ const char = blanked[index];
11323
+ if (char === "(" || char === "[" || char === "{")
11324
+ depth += 1;
11325
+ else if (char === ")" || char === "]" || char === "}") {
11326
+ depth = Math.max(0, depth - 1);
11327
+ }
11328
+ }
11329
+ depths[blanked.length] = depth;
11330
+ return depths;
11331
+ }
11332
+ function addJsIdentifiers(names, text) {
11333
+ for (const match of text.matchAll(/[A-Za-z_$][\w$]*/g))
11334
+ names.add(match[0]);
11335
+ }
11336
+ /**
11337
+ * Offset of a function body: after a parameter list's closing parenthesis,
11338
+ * an optional return type, then `{` or `=>`. Returns -1 otherwise.
11339
+ */
11340
+ function jsFunctionBodyStart(blanked, close) {
11341
+ const after = blanked.slice(close + 1).match(/^\s*(?::[^{};=]*?)?\s*(=>|\{)/);
11342
+ if (!after)
11343
+ return -1;
11344
+ return close + 1 + after[0].length - after[1].length;
11345
+ }
11346
+ /** Start and end offsets of a function body that begins at `start`. */
11347
+ function jsFunctionBodyRange(module, start) {
11348
+ const { blanked, code } = module.prepared;
11349
+ let index = start;
11350
+ if (blanked.startsWith("=>", index)) {
11351
+ index += 2;
11352
+ while (index < blanked.length && /\s/.test(blanked[index]))
11353
+ index += 1;
11354
+ if (blanked[index] !== "{") {
11355
+ const expression = readJsExpression(code, index);
11356
+ return { end: index + expression.length, start: index };
11357
+ }
11358
+ }
11359
+ const end = findJsClosingBracket(blanked, index);
11360
+ return end === -1 ? null : { end, start: index };
11361
+ }
11362
+ /** The first parameter's name when it is a plain identifier. */
11363
+ function firstJsParameterName(parameters) {
11364
+ const [first] = splitJsTopLevel(parameters);
11365
+ const name = first?.replace(/\s*=[\s\S]*$/, "").replace(/\s*:[\s\S]*$/, "")
11366
+ .replace(/\?$/, "").trim();
11367
+ return name && JS_IDENTIFIER.test(name) ? name : undefined;
11368
+ }
11369
+ /** Computes, once per module, the facts used for identifier resolution. */
11370
+ function analyzeJsModule(module) {
11371
+ if (module.scope)
11372
+ return module.scope;
11373
+ const { blanked, code } = module.prepared;
11374
+ const depths = jsBracketDepths(blanked);
11375
+ const nestedNames = new Set();
11376
+ const topLevel = new Map();
11377
+ const functions = [];
11378
+ const addTopLevel = (name, binding) => {
11379
+ topLevel.set(name, [...(topLevel.get(name) ?? []), binding]);
11380
+ };
11381
+ for (const match of blanked.matchAll(/(?<![\w$.])(const|let|var)\s+([A-Za-z_$][\w$]*|[{[])/g)) {
11382
+ const index = match.index ?? 0;
11383
+ const target = match[2];
11384
+ const nested = depths[index] > 0;
11385
+ if (target === "{" || target === "[") {
11386
+ // Destructuring: every identifier in the pattern may be bound.
11387
+ const open = index + match[0].length - 1;
11388
+ const close = findJsClosingBracket(blanked, open);
11389
+ const names = new Set();
11390
+ addJsIdentifiers(names, blanked.slice(open, close + 1));
11391
+ for (const name of names) {
11392
+ if (nested)
11393
+ nestedNames.add(name);
11394
+ else
11395
+ addTopLevel(name, { kind: "other" });
11396
+ }
11397
+ continue;
11398
+ }
11399
+ if (nested) {
11400
+ nestedNames.add(target);
11401
+ continue;
11402
+ }
11403
+ const initializer = new RegExp(String.raw `^\s*(?::[^=;]*)?=(?![=>])`).exec(blanked.slice(index + match[0].length));
11404
+ addTopLevel(target, match[1] === "const" && initializer
11405
+ ? {
11406
+ initializer: index + match[0].length + initializer[0].length,
11407
+ kind: "const",
11408
+ }
11409
+ : { kind: "other" });
11410
+ }
11411
+ for (const match of blanked.matchAll(/(?<![\w$.])(?:function\s*\*?|class)\s+([A-Za-z_$][\w$]*)/g)) {
11412
+ if (depths[match.index ?? 0] > 0)
11413
+ nestedNames.add(match[1]);
11414
+ else
11415
+ addTopLevel(match[1], { kind: "other" });
11416
+ }
11417
+ for (const entry of parseJsValueImports(module)) {
11418
+ addTopLevel(entry.local, entry.imported === "*" || entry.imported === "default"
11419
+ ? { kind: "other" }
11420
+ : { imported: entry.imported, kind: "import", source: entry.source });
11421
+ }
11422
+ // Parameter-like lists (functions, arrows, methods, catch clauses, and
11423
+ // control-flow headers) all count as nested bindings.
11424
+ for (let index = 0; index < blanked.length; index += 1) {
11425
+ if (blanked[index] !== "(")
11426
+ continue;
11427
+ const close = findJsClosingBracket(blanked, index);
11428
+ if (close === -1 || jsFunctionBodyStart(blanked, close) === -1)
11429
+ continue;
11430
+ addJsIdentifiers(nestedNames, blanked.slice(index + 1, close));
11431
+ }
11432
+ for (const match of blanked.matchAll(/([A-Za-z_$][\w$]*)\s*=>/g)) {
11433
+ nestedNames.add(match[1]);
11434
+ }
11435
+ // Top-level functions, for factories that forward their first parameter.
11436
+ const definitions = [
11437
+ /(?<![\w$.])(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)\s*\(/g,
11438
+ /(?<![\w$.])const\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]*)?=\s*(?:async\s+)?(?:function\s*\*?\s*[\w$]*\s*)?\(/g,
11439
+ ];
11440
+ for (const pattern of definitions) {
11441
+ for (const match of blanked.matchAll(pattern)) {
11442
+ const index = match.index ?? 0;
11443
+ if (depths[index] > 0)
11444
+ continue;
11445
+ const open = index + match[0].length - 1;
11446
+ const close = findJsClosingBracket(blanked, open);
11447
+ const bodyStart = close === -1 ? -1 : jsFunctionBodyStart(blanked, close);
11448
+ const body = bodyStart === -1
11449
+ ? null
11450
+ : jsFunctionBodyRange(module, bodyStart);
11451
+ if (!body)
11452
+ continue;
11453
+ functions.push({
11454
+ bodyEnd: body.end,
11455
+ bodyStart: body.start,
11456
+ name: match[1],
11457
+ parameter: firstJsParameterName(code.slice(open + 1, close)),
11458
+ });
11459
+ }
11460
+ }
11461
+ for (const match of blanked.matchAll(/(?<![\w$.])const\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]*)?=\s*(?:async\s+)?([A-Za-z_$][\w$]*)\s*=>/g)) {
11462
+ const index = match.index ?? 0;
11463
+ if (depths[index] > 0)
11464
+ continue;
11465
+ const body = jsFunctionBodyRange(module, index + match[0].length - 2);
11466
+ if (body) {
11467
+ functions.push({
11468
+ bodyEnd: body.end,
11469
+ bodyStart: body.start,
11470
+ name: match[1],
11471
+ parameter: match[2],
11472
+ });
11473
+ }
11474
+ }
11475
+ module.scope = { functions, nestedNames, topLevel };
11476
+ return module.scope;
11477
+ }
11478
+ /**
11479
+ * Whether a module mutates `name` after binding it: member assignment
11480
+ * (`name.disabledPaths = …`, `name.length = 0`), a removing array method,
11481
+ * `delete`, `Object.assign` and similar, or reassignment.
11482
+ */
11483
+ function isJsBindingMutated(module, name) {
11484
+ const { blanked } = module.prepared;
11485
+ const id = escapeRegExp(name);
11486
+ const member = String
11487
+ .raw `(?:\s*\??\.\s*${JS_IDENTIFIER_SOURCE}|\s*\[[^\]]*\])`;
11488
+ const assignment = String
11489
+ .raw `\s*(?:[-+*/%&|^]|\*\*|<<|>>>?|\?\?|&&|\|\|)?=(?![=>])`;
11490
+ return [
11491
+ new RegExp(String.raw `(?<![\w$.])${id}${member}+${assignment}`),
11492
+ new RegExp(String
11493
+ .raw `(?<![\w$.])${id}${member}*\s*\??\.\s*(?:splice|pop|shift|fill|copyWithin)\s*\(`),
11494
+ new RegExp(String.raw `\bdelete\s+${id}\b`),
11495
+ new RegExp(String
11496
+ .raw `\bObject\s*\.\s*(?:assign|defineProperty|defineProperties|setPrototypeOf)\s*\(\s*${id}\b`),
11497
+ new RegExp(String.raw `(?<![\w$.]|(?:const|let|var)\s+)${id}${assignment}`),
11498
+ ].some((pattern) => pattern.test(blanked));
11499
+ }
11500
+ /**
11501
+ * Local names under which a module imported a Loom API-key export, including
11502
+ * aliases and `namespace.name` for namespace imports. A name that is also
11503
+ * bound elsewhere in the module is left out.
11504
+ */
11505
+ function loomApiKeyExportNames(module, exportName) {
11506
+ const scope = analyzeJsModule(module);
11507
+ const names = new Set();
11508
+ for (const entry of parseJsValueImports(module)) {
11509
+ if (!LOOM_API_KEYS_IMPORT_SOURCES.has(entry.source))
11510
+ continue;
11511
+ if (scope.nestedNames.has(entry.local) ||
11512
+ (scope.topLevel.get(entry.local)?.length ?? 0) !== 1) {
11513
+ continue;
11514
+ }
11515
+ if (entry.imported === exportName)
11516
+ names.add(entry.local);
11517
+ if (entry.imported === "*")
11518
+ names.add(`${entry.local}.${exportName}`);
11519
+ }
11520
+ return names;
11521
+ }
11522
+ /**
11523
+ * Resolves an identifier, proven or not at all: an enclosing factory
11524
+ * parameter, or the single top-level `const` (or one relative/`@/` import of
11525
+ * one while hops remain) that nothing nested shadows and nothing mutates.
11526
+ */
11527
+ async function resolveJsName(context, binding, name) {
11528
+ if (binding.env.has(name)) {
11529
+ const parameter = binding.env.get(name) ?? null;
11530
+ return parameter && !isJsBindingMutated(binding.module, name)
11531
+ ? parameter
11532
+ : null;
11533
+ }
11534
+ const module = binding.module;
11535
+ const scope = analyzeJsModule(module);
11536
+ const sites = scope.topLevel.get(name) ?? [];
11537
+ if (scope.nestedNames.has(name) || sites.length !== 1)
11538
+ return null;
11539
+ if (isJsBindingMutated(module, name))
11540
+ return null;
11541
+ const [site] = sites;
11542
+ if (site.kind === "const") {
11543
+ return {
11544
+ env: NO_JS_ENV,
11545
+ expression: readJsExpression(module.prepared.code, site.initializer),
11546
+ importHops: binding.importHops,
11547
+ module,
11548
+ };
11549
+ }
11550
+ if (site.kind !== "import" || binding.importHops <= 0)
11551
+ return null;
11552
+ const resolved = await resolveLocalSourceImport(context.cwd, context.framework, resolve(context.cwd, module.path), site.source);
11553
+ if (!resolved)
11554
+ return null;
11555
+ const target = await loadJsSourceModule(context, relative(context.cwd, resolved).replaceAll("\\", "/"));
11556
+ return target
11557
+ ? await resolveJsName(context, {
11558
+ env: NO_JS_ENV,
11559
+ expression: site.imported,
11560
+ importHops: binding.importHops - 1,
11561
+ module: target,
11562
+ }, site.imported)
11563
+ : null;
11564
+ }
11565
+ /**
11566
+ * Whether a `disabledPaths` value provably contains every api-key plugin path:
11567
+ * the whole value is Loom's helper call (any arguments) or constant, an array
11568
+ * literal that spreads either, an array literal listing every path, or
11569
+ * `<options>.disabledPaths` of options that prove it. Anything else, such as
11570
+ * a conditional or a filtered list, is unproven.
11571
+ */
11572
+ async function jsValueDisablesApiKeyPaths(context, binding, depth = 0) {
11573
+ if (depth > 12)
11574
+ return false;
11575
+ const expression = unwrapJsExpression(binding.expression);
11576
+ const compact = expression.replace(/\s+/g, "");
11577
+ const shadowed = (name) => binding.env.has(name.split(".")[0]);
11578
+ const constants = loomApiKeyExportNames(binding.module, "BETTER_AUTH_API_KEY_HTTP_PATHS");
11579
+ if (constants.has(compact) && !shadowed(compact))
11580
+ return true;
11581
+ if (JS_IDENTIFIER.test(expression)) {
11582
+ const resolved = await resolveJsName(context, binding, expression);
11583
+ return resolved
11584
+ ? await jsValueDisablesApiKeyPaths(context, resolved, depth + 1)
11585
+ : false;
11586
+ }
11587
+ const member = compact.match(/^([A-Za-z_$][\w$]*)\??\.disabledPaths$/);
11588
+ if (member) {
11589
+ return await jsOptionsDisableApiKeyPaths(context, { ...binding, expression: member[1] }, depth + 1) === true;
11590
+ }
11591
+ const call = parseWholeJsCall(expression);
11592
+ if (call) {
11593
+ return loomApiKeyExportNames(binding.module, "withBetterAuthApiKeyHttpPathsDisabled").has(call.callee) && !shadowed(call.callee);
11594
+ }
11595
+ const list = wholeJsBracketContents(expression, "[");
11596
+ if (list === null)
11597
+ return false;
11598
+ const literals = new Set();
11599
+ for (const element of splitJsTopLevel(list)) {
11600
+ if (element.startsWith("...")) {
11601
+ if (await jsValueDisablesApiKeyPaths(context, { ...binding, expression: element.slice(3) }, depth + 1)) {
11602
+ return true;
11603
+ }
11604
+ continue;
11605
+ }
11606
+ const literal = jsStringLiteralValue(element);
11607
+ if (literal !== null)
11608
+ literals.add(literal);
11609
+ }
11610
+ return BETTER_AUTH_API_KEY_HTTP_PATHS.every((path) => literals.has(path));
11611
+ }
11612
+ /**
11613
+ * Evaluates Better Auth options for `disabledPaths`: `true` when proven,
11614
+ * `false` when set to something unproven, `undefined` when not set. Entries
11615
+ * apply in order, so a later key or spread overrides an earlier one. Options
11616
+ * or spreads that do not resolve to an object literal, computed keys, and
11617
+ * accessors are unproven.
11618
+ */
11619
+ async function jsOptionsDisableApiKeyPaths(context, binding, depth = 0) {
11620
+ if (depth > 12)
11621
+ return false;
11622
+ const expression = unwrapJsExpression(binding.expression);
11623
+ if (JS_IDENTIFIER.test(expression)) {
11624
+ const resolved = await resolveJsName(context, binding, expression);
11625
+ return resolved
11626
+ ? await jsOptionsDisableApiKeyPaths(context, resolved, depth + 1)
11627
+ : false;
11628
+ }
11629
+ const contents = wholeJsBracketContents(expression, "{");
11630
+ if (contents === null)
11631
+ return false;
11632
+ let result;
11633
+ for (const entry of splitJsTopLevel(contents)) {
11634
+ if (entry.startsWith("...")) {
11635
+ const spread = await jsOptionsDisableApiKeyPaths(context, { ...binding, expression: entry.slice(3) }, depth + 1);
11636
+ if (spread !== undefined)
11637
+ result = spread;
11638
+ continue;
11639
+ }
11640
+ if (entry.startsWith("[")) {
11641
+ // A computed key may evaluate to "disabledPaths".
11642
+ result = false;
11643
+ continue;
11644
+ }
11645
+ if (entry === "disabledPaths") {
11646
+ result = await jsValueDisablesApiKeyPaths(context, { ...binding, expression: entry }, depth + 1);
11647
+ continue;
11648
+ }
11649
+ const property = entry.match(/^(["']?)([A-Za-z_$][\w$]*)\1\s*:/);
11650
+ if (property?.[2] === "disabledPaths") {
11651
+ result = await jsValueDisablesApiKeyPaths(context, {
11652
+ ...binding,
11653
+ expression: entry.slice(property[0].length),
11654
+ }, depth + 1);
11655
+ }
11656
+ else if (!property &&
11657
+ /^(?:async\s+|get\s+|set\s+)?["']?disabledPaths\b/.test(entry)) {
11658
+ // A getter or method cannot be checked statically.
11659
+ result = false;
11660
+ }
11661
+ }
11662
+ return result;
11663
+ }
11664
+ /**
11665
+ * Every `callee(` call outside strings and comments. Member calls such as
11666
+ * `x.callee(` count only when `allowMember` is set; a function declaration
11667
+ * `function callee(` never counts.
11668
+ */
11669
+ function findJsCalls(module, callee, options = {}) {
11670
+ const { blanked, code } = module.prepared;
11671
+ const calls = [];
11672
+ const pattern = new RegExp(`${options.allowMember ? "\\b" : "(?<![\\w$.])"}${escapeRegExp(callee)}\\s*\\(`, "g");
11673
+ for (const match of blanked.matchAll(pattern)) {
11674
+ const index = match.index ?? 0;
11675
+ if (/\bfunction\s*\*?\s*$/.test(blanked.slice(0, index)))
11676
+ continue;
11677
+ const open = index + match[0].length - 1;
11678
+ const close = findJsClosingBracket(blanked, open);
11679
+ if (close === -1)
11680
+ continue;
11681
+ calls.push({
11682
+ firstArgument: splitJsTopLevel(code.slice(open + 1, close))[0],
11683
+ open,
11684
+ });
9533
11685
  }
9534
- else {
9535
- if (!matchesImportSource(routeText, ["@gadicc/loom/next/files"])) {
9536
- issues.push(`Files route handler is not wired to @gadicc/loom/next/files: ${config.entrypoints.routeHandler}`);
11686
+ return calls;
11687
+ }
11688
+ /**
11689
+ * Reads the app's Better Auth configuration and decides whether it provably
11690
+ * disables every api-key plugin HTTP endpoint.
11691
+ *
11692
+ * Every `betterAuth(` call in the auth module and, when it imports the auth
11693
+ * module, the auth runtime module must be proven; there must be at least one.
11694
+ * A call inside a top-level factory is evaluated once per call of that factory
11695
+ * in those modules, with the factory's first parameter bound to the call's
11696
+ * argument, so options the factory ignores are not credited. Identifiers
11697
+ * resolve only to unshadowed, unmutated top-level `const` initializers,
11698
+ * following one relative or `@/` import. `modules` lists every file read.
11699
+ */
11700
+ async function inspectBetterAuthApiKeyHttpPaths(cwd, framework, manifest) {
11701
+ const authConfig = await mergeAuthConfig(cwd, framework, manifest.features.auth?.config);
11702
+ const authModulePath = authConfig.modules.authModule;
11703
+ const context = { cwd, framework, modules: new Map() };
11704
+ const authModule = await loadJsSourceModule(context, authModulePath);
11705
+ const scanned = authModule ? [authModule] : [];
11706
+ let runtimeModule = null;
11707
+ /** Local names of auth-module exports imported by the runtime module. */
11708
+ const runtimeAliases = new Map();
11709
+ const runtimePath = authConfig.modules.authRuntimeModule;
11710
+ const runtimeText = runtimePath
11711
+ ? await readTextIfExists(join(cwd, runtimePath))
11712
+ : null;
11713
+ if (authModule && runtimePath && runtimeText &&
11714
+ matchesImportSource(runtimeText, getImportSpecifierCandidates(runtimePath, authModulePath))) {
11715
+ runtimeModule = await loadJsSourceModule(context, runtimePath);
11716
+ if (runtimeModule) {
11717
+ scanned.push(runtimeModule);
11718
+ const authModuleAbsolute = resolve(cwd, authModulePath);
11719
+ for (const entry of parseJsValueImports(runtimeModule)) {
11720
+ if (entry.imported === "*" || entry.imported === "default")
11721
+ continue;
11722
+ const resolved = await resolveLocalSourceImport(cwd, framework, resolve(cwd, runtimePath), entry.source);
11723
+ if (resolved === authModuleAbsolute) {
11724
+ runtimeAliases.set(entry.imported, entry.local);
11725
+ }
11726
+ }
9537
11727
  }
9538
- if (!routeText.includes("createFilesRouteHandlers")) {
9539
- issues.push(`Files route handler does not call createFilesRouteHandlers: ${config.entrypoints.routeHandler}`);
11728
+ }
11729
+ const factoryCalls = (module, factory) => {
11730
+ const calls = findJsCalls(module, factory).map((call) => ({
11731
+ call,
11732
+ module,
11733
+ }));
11734
+ const alias = runtimeAliases.get(factory);
11735
+ const runtime = runtimeModule;
11736
+ if (module === authModule && alias && runtime) {
11737
+ calls.push(...findJsCalls(runtime, alias).map((call) => ({
11738
+ call,
11739
+ module: runtime,
11740
+ })));
9540
11741
  }
9541
- const routeImportChecks = [
9542
- [config.modules.accessModule, "access policy"],
9543
- [config.modules.repositoryModule, "repository"],
9544
- [config.modules.storageModule, "storage adapter"],
9545
- ];
9546
- for (const [modulePath, label] of routeImportChecks) {
9547
- if (!matchesImportSource(routeText, getImportSpecifierCandidates(config.entrypoints.routeHandler, modulePath))) {
9548
- issues.push(`Files route handler does not import the configured ${label}: ${config.entrypoints.routeHandler}`);
9549
- suggestions.add(`Import the files ${label} from ${modulePath} in the route handler.`);
11742
+ return calls;
11743
+ };
11744
+ let calls = 0;
11745
+ let disabled = true;
11746
+ for (const module of scanned) {
11747
+ const functions = analyzeJsModule(module).functions;
11748
+ for (const call of findJsCalls(module, "betterAuth")) {
11749
+ calls += 1;
11750
+ const options = (env) => call.firstArgument === undefined
11751
+ ? Promise.resolve(false)
11752
+ : jsOptionsDisableApiKeyPaths(context, {
11753
+ env,
11754
+ expression: call.firstArgument,
11755
+ importHops: 1,
11756
+ module,
11757
+ }).then((result) => result === true);
11758
+ const factory = functions.find((item) => call.open >= item.bodyStart && call.open < item.bodyEnd);
11759
+ const uses = factory ? factoryCalls(module, factory.name) : [];
11760
+ let proven;
11761
+ if (factory && uses.length) {
11762
+ proven = true;
11763
+ for (const use of uses) {
11764
+ const argument = use.call.firstArgument;
11765
+ const env = new Map(factory.parameter
11766
+ ? [[
11767
+ factory.parameter,
11768
+ argument === undefined ? null : {
11769
+ env: NO_JS_ENV,
11770
+ expression: argument,
11771
+ importHops: 1,
11772
+ module: use.module,
11773
+ },
11774
+ ]]
11775
+ : []);
11776
+ if (!await options(env)) {
11777
+ proven = false;
11778
+ break;
11779
+ }
11780
+ }
11781
+ }
11782
+ else {
11783
+ proven = await options(NO_JS_ENV);
9550
11784
  }
11785
+ if (!proven)
11786
+ disabled = false;
9551
11787
  }
9552
11788
  }
11789
+ const loaded = [...context.modules.values()].filter((module) => module !== null);
9553
11790
  return {
9554
- issues,
9555
- suggestions: [...suggestions],
9556
- warnings,
11791
+ authModuleRead: authModule !== null,
11792
+ authModulePath,
11793
+ disabled: calls > 0 && disabled,
11794
+ modules: loaded,
9557
11795
  };
9558
11796
  }
9559
- async function checkMailFeature(cwd, framework, manifest, options) {
9560
- const issues = [];
9561
- const suggestions = new Set();
9562
- const warnings = [];
9563
- const feature = manifest.features.mail;
9564
- if (!feature || feature.status !== "active") {
9565
- return { issues, suggestions: [], warnings };
9566
- }
9567
- for (const dependency of ["auth", "db"]) {
9568
- if (manifest.features[dependency]?.status !== "active") {
9569
- issues.push(`Mail feature requires the active ${dependency} feature.`);
9570
- suggestions.add(`Run \`loom add ${dependency}\` before using mail.`);
9571
- }
9572
- }
9573
- if (issues.length)
9574
- return { issues, suggestions: [...suggestions], warnings };
9575
- const { packageJson } = await readProjectPackageJson(cwd);
9576
- const dbConfig = mergeDbConfig(framework, manifest.features.db.config);
9577
- const config = getMailConfig(framework, dbConfig, packageJson, feature.config, manifest.features.jobs?.status === "active");
9578
- const schema = config.schema;
9579
- const latestSchema = getLatestManagedSchemaConfig(schema);
9580
- if (schema.mode !== "managed-local" || schema.blueprint !== "mail") {
9581
- issues.push("Mail must use the managed-local mail schema blueprint.");
9582
- suggestions.add("Run `loom add mail` to restore the mail schema config.");
9583
- }
9584
- if (schema.exports.length !== 3) {
9585
- issues.push("Mail schema must configure message, delivery, and event exports.");
9586
- }
9587
- if (schema.version > MAIL_SCHEMA_BLUEPRINT_VERSION) {
9588
- issues.push(`Mail schema blueprint version ${schema.version} is newer than this Loom package supports.`);
9589
- }
9590
- else if (schema.version < MAIL_SCHEMA_BLUEPRINT_VERSION) {
9591
- warnings.push(`Mail schema blueprint is stale: ${schema.version} < ${MAIL_SCHEMA_BLUEPRINT_VERSION}.`);
9592
- suggestions.add("Run `loom db schemas sync`, then review and migrate the diff.");
9593
- }
9594
- const schemaText = await readTextIfExists(join(cwd, schema.module));
9595
- if (!schemaText) {
9596
- issues.push(`Mail schema file is missing: ${schema.module}`);
9597
- suggestions.add("Run `loom db schemas sync`.");
11797
+ /**
11798
+ * Advisory, single-module object reading for the authorizer warnings: an
11799
+ * identifier resolves to its initializer only when the module declares that
11800
+ * name exactly once (`const`, at any depth) and nowhere else.
11801
+ */
11802
+ function readJsObjectShape(module, expression, depth = 0) {
11803
+ if (depth > 8)
11804
+ return null;
11805
+ const unwrapped = unwrapJsExpression(expression);
11806
+ if (JS_IDENTIFIER.test(unwrapped)) {
11807
+ const { blanked, code } = module.prepared;
11808
+ const id = escapeRegExp(unwrapped);
11809
+ const declarations = [
11810
+ ...blanked.matchAll(new RegExp(String
11811
+ .raw `(?<![\w$.])(?:const|let|var|function|class)\s+${id}\b|\bimport\b[^;]*\b${id}\b[^;]*\bfrom\b`, "g")),
11812
+ ];
11813
+ if (declarations.length !== 1)
11814
+ return null;
11815
+ const declaration = new RegExp(String.raw `(?<![\w$.])const\s+${id}\s*(?::[^=;]*)?=(?![=>])`).exec(blanked);
11816
+ return declaration
11817
+ ? readJsObjectShape(module, readJsExpression(code, declaration.index + declaration[0].length), depth + 1)
11818
+ : null;
9598
11819
  }
9599
- else {
9600
- const currentHash = hashManagedSchemaText(schemaText);
9601
- if (currentHash !== schema.hash) {
9602
- if (currentHash === latestSchema.hash) {
9603
- warnings.push(`Mail schema manifest hash is stale for ${schema.module}.`);
9604
- suggestions.add("Run `loom db schemas sync` to refresh loom.json.");
9605
- }
11820
+ const contents = wholeJsBracketContents(unwrapped, "{");
11821
+ if (contents === null)
11822
+ return null;
11823
+ const shape = { complete: true, entries: [] };
11824
+ for (const entry of splitJsTopLevel(contents)) {
11825
+ if (entry.startsWith("...")) {
11826
+ const spread = readJsObjectShape(module, entry.slice(3), depth + 1);
11827
+ if (!spread)
11828
+ shape.complete = false;
9606
11829
  else {
9607
- issues.push(`Mail schema file has local edits outside the managed hash: ${schema.module}`);
9608
- suggestions.add("Move app-specific mail schema additions to a separate file, then run `loom db schemas sync`.");
11830
+ shape.entries.push(...spread.entries);
11831
+ shape.complete &&= spread.complete;
9609
11832
  }
11833
+ continue;
9610
11834
  }
9611
- const barrelText = await readTextIfExists(join(cwd, dbConfig.dirs.schemaDir, "index.ts"));
9612
- if (!barrelText || !schemaBarrelExportsModule(barrelText, schema, dbConfig)) {
9613
- issues.push(`DB schema barrel does not export the managed mail schema: ${dbConfig.dirs.schemaDir}/index.ts`);
9614
- suggestions.add("Run `loom db schemas sync`.");
11835
+ const property = entry.match(/^(["']?)([A-Za-z_$][\w$]*)\1\s*(:)?/);
11836
+ if (!property) {
11837
+ shape.complete = false;
11838
+ continue;
9615
11839
  }
11840
+ shape.entries.push({
11841
+ key: property[2],
11842
+ value: property[3] ? entry.slice(property[0].length) : property[2],
11843
+ });
9616
11844
  }
9617
- const requiredFiles = [
9618
- config.modules.accessModule,
9619
- config.modules.actionsModule,
9620
- config.modules.repositoryModule,
9621
- config.modules.serviceModule,
9622
- config.modules.transportModule,
9623
- config.entrypoints.adminPage,
9624
- config.entrypoints.webhookRoute,
9625
- ...(config.jobs.enabled ? [config.modules.jobModule] : []),
9626
- ];
9627
- for (const relativePath of requiredFiles) {
9628
- if (!await exists(join(cwd, relativePath))) {
9629
- issues.push(`Mail scaffold file is missing: ${relativePath}`);
9630
- suggestions.add("Run `loom add mail` to restore missing scaffolds.");
11845
+ return shape;
11846
+ }
11847
+ const PERMISSION_CODE_LITERAL = String
11848
+ .raw `(["'\x60])[A-Z0-9_]*PERMISSION[A-Z0-9_]*\1`;
11849
+ const JS_EQUALITY = String.raw `(?:===|!==|==|!=)`;
11850
+ /**
11851
+ * Comparisons of an error `code` with a PERMISSION code, and a PERMISSION
11852
+ * code list checked with `.includes(…code)`. `token` is checked against
11853
+ * string-blanked text so matches inside strings do not count.
11854
+ */
11855
+ const PERMISSION_CODE_MAPPINGS = [
11856
+ {
11857
+ pattern: new RegExp(String
11858
+ .raw `\bcode\s*${JS_EQUALITY}\s*(?:${PERMISSION_CODE_LITERAL}|[\w$.?]*\b[A-Z0-9_]*PERMISSION[A-Z0-9_]*\b)`, "g"),
11859
+ token: "code",
11860
+ },
11861
+ {
11862
+ pattern: new RegExp(String
11863
+ .raw `${PERMISSION_CODE_LITERAL}\s*${JS_EQUALITY}\s*[\w$.?]*\bcode\b`, "g"),
11864
+ token: "code",
11865
+ },
11866
+ {
11867
+ pattern: new RegExp(String
11868
+ .raw `\[[^\]]*PERMISSION[^\]]*\]\s*\.\s*includes\s*\(\s*[\w$.?]*\bcode\s*\)`, "g"),
11869
+ token: "includes",
11870
+ },
11871
+ ];
11872
+ /** Whether a `switch` on an error `code` has a PERMISSION `case` label. */
11873
+ function hasPermissionCodeCase(prepared) {
11874
+ const { blanked, code } = prepared;
11875
+ for (const match of blanked.matchAll(/\bswitch\s*\(/g)) {
11876
+ const open = (match.index ?? 0) + match[0].length - 1;
11877
+ const close = findJsClosingBracket(blanked, open);
11878
+ if (close === -1 || !/\bcode\s*$/.test(blanked.slice(open + 1, close))) {
11879
+ continue;
9631
11880
  }
9632
- }
9633
- const accessText = await readTextIfExists(join(cwd, config.modules.accessModule));
9634
- if (accessText && !accessText.includes("authorizeMailAdmin")) {
9635
- issues.push(`Mail access module does not export authorizeMailAdmin: ${config.modules.accessModule}`);
9636
- }
9637
- const generatedDenyAll = accessText?.includes("Mail admin access policy is not configured.") ?? false;
9638
- if (generatedDenyAll) {
9639
- const message = `Mail admin access still uses the generated deny-all stub: ${config.modules.accessModule}`;
9640
- if (options.production)
9641
- issues.push(message);
9642
- else
9643
- warnings.push(message);
9644
- suggestions.add("Connect authorizeMailAdmin() to the app's fresh session/admin-role check.");
9645
- }
9646
- const contentChecks = [
9647
- [
9648
- config.modules.repositoryModule,
9649
- "@gadicc/loom/mail",
9650
- "Mail repository is not typed against the shared mail contract",
9651
- ],
9652
- [
9653
- config.modules.serviceModule,
9654
- "createLoomMailService",
9655
- "Mail service is not wired to the shared durable service",
9656
- ],
9657
- [
9658
- config.modules.transportModule,
9659
- "createPostalMailTransport",
9660
- "Mail transport is not wired to the Postal adapter",
9661
- ],
9662
- [
9663
- config.modules.transportModule,
9664
- "POSTAL_WEBHOOK_PUBLIC_KEYS",
9665
- "Mail transport does not configure Postal webhook public keys",
9666
- ],
9667
- [
9668
- config.entrypoints.webhookRoute,
9669
- "createPostalWebhookRouteHandler",
9670
- "Mail webhook route does not use the signed shared route handler",
9671
- ],
9672
- [
9673
- config.modules.actionsModule,
9674
- "authorizeMailAdmin",
9675
- "Mail admin actions do not enforce the app-owned admin boundary",
9676
- ],
9677
- [
9678
- config.entrypoints.adminPage,
9679
- "authorizeMailAdmin",
9680
- "Mail admin page does not enforce the app-owned admin boundary",
9681
- ],
9682
- ];
9683
- for (const [relativePath, snippet, label] of contentChecks) {
9684
- const text = await readTextIfExists(join(cwd, relativePath));
9685
- if (text && !text.includes(snippet)) {
9686
- issues.push(`${label}: ${relativePath}`);
9687
- suggestions.add("Run `loom add mail` or update loom.json for intentional paths.");
11881
+ const bodyOpen = blanked.indexOf("{", close);
11882
+ const bodyClose = bodyOpen === -1
11883
+ ? -1
11884
+ : findJsClosingBracket(blanked, bodyOpen);
11885
+ if (bodyClose === -1 || blanked.slice(close + 1, bodyOpen).trim())
11886
+ continue;
11887
+ const pattern = new RegExp(String.raw `\bcase\s+${PERMISSION_CODE_LITERAL}\s*:`, "g");
11888
+ for (const label of code.slice(bodyOpen, bodyClose).matchAll(pattern)) {
11889
+ if (blanked.startsWith("case", bodyOpen + (label.index ?? 0))) {
11890
+ return true;
11891
+ }
9688
11892
  }
9689
11893
  }
9690
- if (config.ui.adapter === "mui" &&
9691
- !hasPackageDependency(packageJson, "@mui/material")) {
9692
- issues.push("Mail's MUI adapter is active but @mui/material is not installed.");
11894
+ return false;
11895
+ }
11896
+ /** Advisory findings for an app-owned Better Auth api-key verifier. */
11897
+ function checkApiKeysAuthorizerText(modulePath, text) {
11898
+ const warnings = [];
11899
+ const module = {
11900
+ path: modulePath,
11901
+ prepared: prepareJsText(text),
11902
+ };
11903
+ for (const call of findJsCalls(module, "verifyApiKey", { allowMember: true })) {
11904
+ const outer = call.firstArgument === undefined
11905
+ ? null
11906
+ : readJsObjectShape(module, call.firstArgument);
11907
+ let bodyValue;
11908
+ for (const entry of outer?.entries ?? []) {
11909
+ if (entry.key === "body")
11910
+ bodyValue = entry.value;
11911
+ }
11912
+ // Skip both warnings when the body cannot be read, rather than guess.
11913
+ const body = bodyValue === undefined
11914
+ ? null
11915
+ : readJsObjectShape(module, bodyValue);
11916
+ if (!body)
11917
+ continue;
11918
+ if (body.entries.some((entry) => entry.key === "permissions")) {
11919
+ warnings.push(`API-key authorizer passes permissions to verifyApiKey(); Better Auth then reports a valid key that lacks the permission as KEY_NOT_FOUND, so a scope miss is audited as invalid_credential instead of insufficient_permission: ${modulePath}`);
11920
+ }
11921
+ if (body.complete && !body.entries.some((entry) => entry.key === "configId")) {
11922
+ warnings.push(`API-key authorizer calls verifyApiKey() without configId, so keys from any api-key plugin configuration verify: ${modulePath}`);
11923
+ }
9693
11924
  }
9694
- if (config.jobs.enabled && manifest.features.jobs?.status !== "active") {
9695
- warnings.push("Mail drain job is enabled while the Loom jobs feature is inactive.");
9696
- suggestions.add("Run `loom add jobs` or disable features.mail.config.jobs.enabled.");
11925
+ const { blanked, code } = module.prepared;
11926
+ const mapsPermissionCode = hasPermissionCodeCase(module.prepared) ||
11927
+ PERMISSION_CODE_MAPPINGS.some(({ pattern, token }) => [...code.matchAll(pattern)].some((match) => {
11928
+ const tokenIndex = (match.index ?? 0) +
11929
+ match[0].search(new RegExp(`\\b${token}\\b`));
11930
+ return blanked.startsWith(token, tokenIndex);
11931
+ }));
11932
+ if (mapsPermissionCode) {
11933
+ warnings.push(`API-key authorizer maps a Better Auth PERMISSION error code that verifyApiKey() never returns; a missing permission arrives as KEY_NOT_FOUND: ${modulePath}`);
9697
11934
  }
9698
- return { issues, suggestions: [...suggestions], warnings };
9699
- }
9700
- function packageDependencySpec(packageJson, dependencyName) {
9701
- return packageJson.dependencies?.[dependencyName] ??
9702
- packageJson.devDependencies?.[dependencyName];
11935
+ return [...new Set(warnings)];
9703
11936
  }
9704
- function dependencyMajorMinor(spec) {
9705
- const match = spec?.match(/(\d+)\.(\d+)/);
9706
- return match ? `${match[1]}.${match[2]}` : undefined;
11937
+ /**
11938
+ * The props an identifier belongs to in blanked text: the enclosing JSX
11939
+ * opening tag (`<Name ... >`) or, outside JSX, the innermost enclosing
11940
+ * `{...}` or `(...)`. Returns null for JSX children text.
11941
+ */
11942
+ function jsEnclosingPropsRegion(blanked, index) {
11943
+ let depth = 0;
11944
+ for (let cursor = index - 1; cursor >= 0; cursor -= 1) {
11945
+ const char = blanked[cursor];
11946
+ if (char === ")" || char === "]" || char === "}")
11947
+ depth += 1;
11948
+ else if (char === "(" || char === "[" || char === "{") {
11949
+ if (depth === 0) {
11950
+ if (char === "[")
11951
+ continue;
11952
+ const close = findJsClosingBracket(blanked, cursor);
11953
+ return blanked.slice(cursor, close === -1 ? undefined : close + 1);
11954
+ }
11955
+ depth -= 1;
11956
+ }
11957
+ else if (depth === 0 && char === ">" && blanked[cursor - 1] !== "=") {
11958
+ // The identifier follows a closed tag: it is JSX text, not a prop.
11959
+ return null;
11960
+ }
11961
+ else if (depth === 0 && char === "<" && /[A-Za-z]/.test(blanked[cursor + 1] ?? "")) {
11962
+ let end = index;
11963
+ let inner = 0;
11964
+ for (; end < blanked.length; end += 1) {
11965
+ const next = blanked[end];
11966
+ if (next === "(" || next === "[" || next === "{")
11967
+ inner += 1;
11968
+ else if (next === ")" || next === "]" || next === "}")
11969
+ inner -= 1;
11970
+ else if (inner === 0 && next === ">" && blanked[end - 1] !== "=")
11971
+ break;
11972
+ }
11973
+ return blanked.slice(cursor, end + 1);
11974
+ }
11975
+ }
11976
+ return blanked;
9707
11977
  }
9708
11978
  async function checkApiKeysFeature(cwd, framework, manifest, options) {
9709
11979
  const issues = [];
@@ -9849,6 +12119,57 @@ async function checkApiKeysFeature(cwd, framework, manifest, options) {
9849
12119
  if (issues.length || warnings.length) {
9850
12120
  suggestions.add("Run `loom add api-keys` to restore missing foundation files without overwriting custom modules.");
9851
12121
  }
12122
+ // Development hint only: the deprecated flag cannot describe Bearer or
12123
+ // header transports, so its copy can contradict the authorizer.
12124
+ if (!options.production) {
12125
+ for (const pagePath of [
12126
+ config.entrypoints.userPage,
12127
+ config.entrypoints.adminPage,
12128
+ ]) {
12129
+ const text = await readTextIfExists(join(cwd, pagePath));
12130
+ const blanked = text ? prepareJsText(text).blanked : "";
12131
+ const uncovered = [
12132
+ ...blanked.matchAll(/\bqueryCredentialsEnabled\b/g),
12133
+ ].some((match) => {
12134
+ const region = jsEnclosingPropsRegion(blanked, match.index ?? 0);
12135
+ return region !== null && !/\bcredentialOptions\b/.test(region);
12136
+ });
12137
+ if (uncovered) {
12138
+ warnings.push(`API-key page passes the deprecated queryCredentialsEnabled without credentialOptions, so its transport guidance can contradict the authorizer: ${pagePath}`);
12139
+ suggestions.add("Pass the authorizer's credentialOptions to ApiKeysManager (and ApiKeyTransportGuidance), keeping that object in a small import-free module both import.");
12140
+ }
12141
+ }
12142
+ }
12143
+ const authorizerText = await readTextIfExists(join(cwd, config.modules.authorizerModule));
12144
+ if (authorizerText) {
12145
+ const authorizerWarnings = checkApiKeysAuthorizerText(config.modules.authorizerModule, authorizerText);
12146
+ if (authorizerWarnings.length) {
12147
+ warnings.push(...authorizerWarnings);
12148
+ suggestions.add("Use `createBetterAuthApiKeyVerifier` from `@gadicc/loom/apiKeys`: it verifies with a configId and without permissions, then checks the permission itself.");
12149
+ }
12150
+ }
12151
+ const httpEndpoints = config.betterAuthHttpEndpoints;
12152
+ if (httpEndpoints !== undefined && httpEndpoints !== "disabled" &&
12153
+ httpEndpoints !== "app-owned") {
12154
+ issues.push(`Unknown api-keys betterAuthHttpEndpoints value in loom.json: ${JSON.stringify(httpEndpoints)}. Use "disabled" or "app-owned".`);
12155
+ }
12156
+ const authConfig = await inspectBetterAuthApiKeyHttpPaths(cwd, framework, manifest);
12157
+ if (httpEndpoints !== "app-owned" && !authConfig.disabled) {
12158
+ const location = authConfig.authModuleRead
12159
+ ? `no disabledPaths covering ${BETTER_AUTH_API_KEY_HTTP_PATHS.join(", ")} was proven in the Better Auth options read from: ${authConfig.modules.map((module) => module.path).join(", ")}`
12160
+ : `the auth module could not be read: ${authConfig.authModulePath}`;
12161
+ const message = `Better Auth api-key HTTP endpoints are reachable by any signed-in user (re-enable revoked keys, remove expiry, hard-delete); ${location}`;
12162
+ if (options.production)
12163
+ issues.push(message);
12164
+ else
12165
+ warnings.push(message);
12166
+ suggestions.add('Pass `disabledPaths: withBetterAuthApiKeyHttpPathsDisabled()` (imported from `@gadicc/loom/apiKeys`) after any spreads in every betterAuth() call, or in a top-level const options object in the auth module or one module it imports; a factory must forward its options parameter. Record `betterAuthHttpEndpoints: "app-owned"` under the api-keys config in loom.json only when the app deliberately serves and guards those endpoints itself.');
12167
+ }
12168
+ for (const module of authConfig.modules) {
12169
+ if (/\benableSessionForAPIKeys\s*:\s*true\b/.test(module.prepared.blanked)) {
12170
+ warnings.push(`Better Auth api-key sessions are enabled (enableSessionForAPIKeys: true), so an API key acts as a full user session outside Loom's scope checks and audit: ${module.path}`);
12171
+ }
12172
+ }
9852
12173
  return { issues, suggestions: [...suggestions], warnings };
9853
12174
  }
9854
12175
  async function checkAuthFeature(cwd, framework, manifest) {
@@ -10639,6 +12960,22 @@ export async function checkProject(cwd, env = process.env, options = {}) {
10639
12960
  else if (isLocalPackageSpec(dependency)) {
10640
12961
  issues.push(`${LOOM_DEPENDENCY} is set to ${dependency}. Keep the committed dependency on a published version and use \`loom dev local <path>\` for local development instead.`);
10641
12962
  }
12963
+ else if (parseCatalogReference(dependency) && await isPnpmProject(cwd, packageJson)) {
12964
+ // Only pnpm catalogs live in pnpm-workspace.yaml (Yarn 4 has its own).
12965
+ const catalogDependency = await resolveLoomDependencySpec(cwd, packageJson);
12966
+ const unreadable = catalogDependency.catalogEntry
12967
+ ? null
12968
+ : findUnreadableLoomCatalog(await readTextIfExists(join(cwd, "pnpm-workspace.yaml")), catalogDependency.catalogName);
12969
+ if (unreadable) {
12970
+ issues.push(`pnpm-workspace.yaml writes the \`${unreadable}\` catalog as a multi-line or nested flow map, which Loom cannot read. Write it as a block map or a single-line flow map.`);
12971
+ }
12972
+ else if (!catalogDependency.catalogEntry) {
12973
+ issues.push(`${LOOM_DEPENDENCY} uses \`${dependency}\`, but pnpm-workspace.yaml has no ${LOOM_DEPENDENCY} entry in that catalog.`);
12974
+ }
12975
+ else if (isLocalPackageSpec(catalogDependency.catalogEntry.spec)) {
12976
+ issues.push(`The pnpm-workspace.yaml \`${catalogDependency.catalogEntry.label}\` map sets ${LOOM_DEPENDENCY} to ${catalogDependency.catalogEntry.spec}. Keep the committed catalog on a published version and use \`loom dev local <path>\` for local development instead.`);
12977
+ }
12978
+ }
10642
12979
  const manifestPath = join(cwd, "loom.json");
10643
12980
  const manifestText = await readTextIfExists(manifestPath);
10644
12981
  let manifest = null;
@@ -10722,7 +13059,7 @@ export async function checkProject(cwd, env = process.env, options = {}) {
10722
13059
  for (const suggestion of nextGuidanceCheck.suggestions) {
10723
13060
  suggestions.add(suggestion);
10724
13061
  }
10725
- const localDevCheck = await checkManagedLocalDevOverride(cwd, options.production ?? false);
13062
+ const localDevCheck = await checkManagedLocalDevOverride(cwd, options.production ?? false, options.commandRunner ?? defaultCommandRunner, env);
10726
13063
  warnings.push(...localDevCheck.warnings);
10727
13064
  issues.push(...localDevCheck.issues);
10728
13065
  for (const suggestion of localDevCheck.suggestions) {
@@ -11129,7 +13466,7 @@ async function runStatus(cwd, io) {
11129
13466
  ? parseJson(installedPackageText, join("node_modules", LOOM_DEPENDENCY, "package.json"))
11130
13467
  : null;
11131
13468
  const workspaceText = await readTextIfExists(join(cwd, "pnpm-workspace.yaml"));
11132
- const overrideSpec = getManagedDevOverrideSpec(workspaceText);
13469
+ const pnpmOverride = getActivePnpmLocalDevOverride(workspaceText, packageJson);
11133
13470
  let denoOverride = null;
11134
13471
  try {
11135
13472
  const tooling = await detectProjectTooling(cwd, manifest?.project?.tooling);
@@ -11151,13 +13488,22 @@ async function runStatus(cwd, io) {
11151
13488
  io.out(`Loom status for ${projectName}`);
11152
13489
  io.out("");
11153
13490
  io.out("Package:");
11154
- io.out(` ${projectMetadata.config}: ${dependencySpec ? `${LOOM_DEPENDENCY} ${dependencySpec}` : "not declared"}`);
13491
+ const catalogEntry = parseCatalogReference(dependencySpec)
13492
+ ? findLoomCatalogEntry(workspaceText, parseCatalogReference(dependencySpec))
13493
+ : null;
13494
+ io.out(` ${projectMetadata.config}: ${dependencySpec
13495
+ ? `${LOOM_DEPENDENCY} ${dependencySpec}${catalogEntry
13496
+ ? ` (${catalogEntry.spec} from pnpm-workspace.yaml ${catalogEntry.label})`
13497
+ : ""}`
13498
+ : "not declared"}`);
11155
13499
  io.out(` installed: ${installedPackage?.version ?? "not installed"}`);
11156
13500
  io.out(` local dev override: ${denoOverride
11157
13501
  ? `active (${denoOverride.config} links ${denoOverride.link})`
11158
- : overrideSpec
11159
- ? `active (${overrideSpec})`
11160
- : "none"}`);
13502
+ : pnpmOverride?.location === "pnpm-workspace.yaml"
13503
+ ? `active (${pnpmOverride.spec})`
13504
+ : pnpmOverride
13505
+ ? `active (${formatPnpmOverrideLocation(pnpmOverride.location)}: ${pnpmOverride.spec})`
13506
+ : "none"}`);
11161
13507
  io.out(` lockfile local resolution: ${localLockfileResolution ?? "none"}`);
11162
13508
  io.out("");
11163
13509
  io.out("Project:");
@@ -11297,8 +13643,9 @@ function printHelp({ out }) {
11297
13643
  out(" --local-db-host <host> Local PostgreSQL host (default: db.localtest.me).");
11298
13644
  out(" --local-db-port <port> Local PostgreSQL port (default: 5432).");
11299
13645
  out(" --replace-local-target Replace an existing development URL during local DB setup.");
13646
+ out(" --cwd <dir> Run in <dir>, resolved from the current directory.");
11300
13647
  out(" --no-color Disable colored CLI output.");
11301
- out(" --no-sync Skip automatic local-dev package sync.");
13648
+ out(" --no-sync Skip automatic local-dev package sync. After a sync that refreshes the package, `loom env` still runs its command; other commands exit 75 and ask for a rerun.");
11302
13649
  out(" --force Force `loom dev sync` to rebuild and reinstall.");
11303
13650
  out(" --name <name> Override the resource name for `loom db neon setup`.");
11304
13651
  out(" --plan <plan> Pass a Vercel Marketplace plan id to Neon setup.");
@@ -12114,7 +14461,9 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
12114
14461
  io.err("Missing local package path. Example: `loom dev local /path/to/loom`.");
12115
14462
  return 1;
12116
14463
  }
12117
- const result = await useLocalDevPackage(cwd, pathInput);
14464
+ const result = await useLocalDevPackage(cwd, pathInput, {
14465
+ onLockWait: io.err,
14466
+ });
12118
14467
  if (result.changedFiles.length) {
12119
14468
  io.out(`Updated ${result.changedFiles.join(", ")}.`);
12120
14469
  }
@@ -12126,6 +14475,7 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
12126
14475
  }
12127
14476
  if (!options.noSync) {
12128
14477
  const syncResult = await syncLocalDevPackage(cwd, {
14478
+ onLockWait: io.err,
12129
14479
  requireActive: true,
12130
14480
  });
12131
14481
  for (const note of syncResult.notes) {
@@ -12137,6 +14487,7 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
12137
14487
  case "sync": {
12138
14488
  const result = await syncLocalDevPackage(cwd, {
12139
14489
  force: options.force,
14490
+ onLockWait: io.err,
12140
14491
  requireActive: true,
12141
14492
  });
12142
14493
  if (result.changed) {
@@ -12151,7 +14502,9 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
12151
14502
  return 0;
12152
14503
  }
12153
14504
  case "published": {
12154
- const result = await usePublishedDevPackage(cwd);
14505
+ const result = await usePublishedDevPackage(cwd, {
14506
+ onLockWait: io.err,
14507
+ });
12155
14508
  if (result.changedFiles.length) {
12156
14509
  io.out(`Updated ${result.changedFiles.join(", ")}.`);
12157
14510
  }
@@ -12229,7 +14582,7 @@ async function runCheck(cwd, strictSkills, production, network, noProgress, noCo
12229
14582
  export async function runCli(args = process.argv.slice(2), io = {
12230
14583
  err: (line) => console.error(line),
12231
14584
  out: (line) => console.log(line),
12232
- }) {
14585
+ }, options = {}) {
12233
14586
  const parsed = parseArgs({
12234
14587
  allowPositionals: true,
12235
14588
  args,
@@ -12299,13 +14652,29 @@ export async function runCli(args = process.argv.slice(2), io = {
12299
14652
  !addListOnly &&
12300
14653
  !productionCheck &&
12301
14654
  !parsed.values["no-sync"]) {
12302
- const syncResult = await syncLocalDevPackage(cwd);
14655
+ // Taken before waiting on another sync, so a refresh by that sync shows
14656
+ // up as a change and this process does not run the code it replaced.
14657
+ const loadedPackageSignature = await captureLoadedLocalLoomSignature(cwd, process.env);
14658
+ const syncResult = await syncLocalDevPackage(cwd, {
14659
+ commandOutput: command === "env" ? "stderr" : "stdout",
14660
+ commandRunner: options.commandRunner,
14661
+ loadedPackageSignature,
14662
+ onLockWait: io.err,
14663
+ });
12303
14664
  if (syncResult.changed) {
14665
+ // `loom env` only loads env files before spawning the wrapped command,
14666
+ // a new process that loads the refreshed package, so it continues.
14667
+ // Every other command would run this process's stale Loom code, so it
14668
+ // stops with a retry status instead of reporting success.
14669
+ const report = command === "env" ? io.err : io.out;
12304
14670
  for (const note of syncResult.notes) {
12305
- io.out(`Note: ${note}`);
14671
+ report(`Note: ${note}`);
12306
14672
  }
12307
- io.out("Re-run the original command to use the refreshed Loom package.");
12308
- return 0;
14673
+ if (command !== "env") {
14674
+ io.err(`The linked local Loom package was refreshed, so \`loom ${[command, arg1].filter(Boolean).join(" ")}\` did not run. Re-run it to use the refreshed package (exit status ${LOOM_LOCAL_DEV_RERUN_EXIT_CODE}).`);
14675
+ return LOOM_LOCAL_DEV_RERUN_EXIT_CODE;
14676
+ }
14677
+ io.err("Running the wrapped command with the refreshed Loom package.");
12309
14678
  }
12310
14679
  }
12311
14680
  switch (command) {
@@ -12350,7 +14719,7 @@ export async function runCli(args = process.argv.slice(2), io = {
12350
14719
  acceptUnknownLicense: parsed.values["accept-unknown-license"],
12351
14720
  });
12352
14721
  case "env":
12353
- return await runEnvCommand(cwd, arg1, [arg2, ...rest].filter((arg) => arg !== undefined), io);
14722
+ return await runEnvCommand(cwd, arg1, [arg2, ...rest].filter((arg) => arg !== undefined), io, { commandRunner: options.commandRunner });
12354
14723
  case "db":
12355
14724
  return await runDb(cwd, arg1, [arg2, ...rest].filter(Boolean), io, {
12356
14725
  connect: parsed.values.connect,