@gadicc/loom 1.34.0 → 1.35.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +126 -49
  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 +3060 -451
  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 +3061 -451
  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 +125 -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
@@ -36,7 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.LOOM_NPMRC_LINES = exports.LOOM_LOCAL_DEV_STATE_GITIGNORE_LINE = exports.LOOM_LOCAL_DEV_STATE_RELATIVE_PATH = exports.LOOM_MANAGED_DEV_OVERRIDE_END = exports.LOOM_MANAGED_DEV_OVERRIDE_START = exports.LOOM_MANAGED_NEXT_AGENTS_END = exports.LOOM_MANAGED_NEXT_AGENTS_START = exports.LOOM_MANAGED_AGENTS_END = exports.LOOM_MANAGED_AGENTS_START = exports.LOOM_MANIFEST_SCHEMA = exports.LOOM_DEPENDENCY = exports.DEFAULT_LOOM_RANGE = void 0;
39
+ exports.UNKNOWN_PACKAGE_SIGNATURE = exports.LOOM_LOCAL_DEV_RERUN_EXIT_CODE = exports.LOOM_NPMRC_LINES = exports.LOOM_LOCAL_DEV_LOCK_GITIGNORE_LINE = exports.LOOM_LOCAL_DEV_LOCK_RELATIVE_PATH = exports.LOOM_LOCAL_DEV_STATE_GITIGNORE_LINE = exports.LOOM_LOCAL_DEV_STATE_RELATIVE_PATH = exports.LOOM_MANAGED_DEV_OVERRIDE_END = exports.LOOM_MANAGED_DEV_OVERRIDE_START = exports.LOOM_MANAGED_NEXT_AGENTS_END = exports.LOOM_MANAGED_NEXT_AGENTS_START = exports.LOOM_MANAGED_AGENTS_END = exports.LOOM_MANAGED_AGENTS_START = exports.LOOM_MANIFEST_SCHEMA = exports.LOOM_DEPENDENCY = exports.DEFAULT_LOOM_RANGE = void 0;
40
40
  exports.defaultCommandRunner = defaultCommandRunner;
41
41
  exports.shouldUseInteractiveNetworkProgress = shouldUseInteractiveNetworkProgress;
42
42
  exports.ensureNpmrcText = ensureNpmrcText;
@@ -48,6 +48,7 @@ exports.ensureNextAgentsMdText = ensureNextAgentsMdText;
48
48
  exports.ensurePnpmWorkspaceLocalDevText = ensurePnpmWorkspaceLocalDevText;
49
49
  exports.clearPnpmWorkspaceLocalDevText = clearPnpmWorkspaceLocalDevText;
50
50
  exports.ensurePnpmWorkspaceLoomReleaseAgeExcludeText = ensurePnpmWorkspaceLoomReleaseAgeExcludeText;
51
+ exports.captureLoadedLocalLoomSignature = captureLoadedLocalLoomSignature;
51
52
  exports.syncLocalDevPackage = syncLocalDevPackage;
52
53
  exports.useLocalDevPackage = useLocalDevPackage;
53
54
  exports.usePublishedDevPackage = usePublishedDevPackage;
@@ -85,12 +86,15 @@ const releaseConfig_js_1 = require("./releaseConfig.js");
85
86
  const releaseCredentials_js_1 = require("./releaseCredentials.js");
86
87
  const releaseTrustCommand_js_1 = require("./releaseTrustCommand.js");
87
88
  const localDb_js_1 = require("./localDb.js");
89
+ const betterAuth_js_1 = require("../apiKeys/betterAuth.js");
88
90
  const retention_js_1 = require("../apiKeys/retention.js");
89
91
  const projectSkills_js_1 = require("./projectSkills.js");
90
92
  const migrationEnv_js_1 = require("./migrationEnv.js");
91
93
  const vercelBuildEnv_js_1 = require("./vercelBuildEnv.js");
92
94
  const vercelProjectRelease_js_1 = require("./vercelProjectRelease.js");
93
95
  const projectTooling_js_1 = require("./projectTooling.js");
96
+ const localDevLock_js_1 = require("./localDevLock.js");
97
+ const localDevPackage_js_1 = require("./localDevPackage.js");
94
98
  exports.DEFAULT_LOOM_RANGE = "^1.0.0";
95
99
  exports.LOOM_DEPENDENCY = "@gadicc/loom";
96
100
  exports.LOOM_MANIFEST_SCHEMA = "https://loom.gadicc.local/project-manifest.schema.json";
@@ -102,24 +106,21 @@ exports.LOOM_MANAGED_DEV_OVERRIDE_START = "# loom-managed:dev:start";
102
106
  exports.LOOM_MANAGED_DEV_OVERRIDE_END = "# loom-managed:dev:end";
103
107
  exports.LOOM_LOCAL_DEV_STATE_RELATIVE_PATH = ".loom/dev-state.json";
104
108
  exports.LOOM_LOCAL_DEV_STATE_GITIGNORE_LINE = ".loom/dev-state.json";
109
+ /** Exclusive lock held while a local-dev sync checks, rebuilds, or installs. */
110
+ exports.LOOM_LOCAL_DEV_LOCK_RELATIVE_PATH = ".loom/dev-sync.lock";
111
+ /** Ignores the sync lock and the short-lived lock that guards breaking it. */
112
+ exports.LOOM_LOCAL_DEV_LOCK_GITIGNORE_LINE = ".loom/dev-sync.lock*";
113
+ /** Set for commands a sync runs, so nested Loom commands skip the sync. */
114
+ const LOOM_DEV_SYNC_ACTIVE_ENV = "LOOM_DEV_SYNC_ACTIVE";
105
115
  const DEFAULT_JOBS_MAX_DURATION_SECONDS = 1800;
106
116
  const LOOM_MANAGED_STATIC_JOB_ROUTE_MARKER = "// loom-managed:jobs-static-route";
107
117
  /** @deprecated Public npm installs no longer require project registry config. */
108
118
  exports.LOOM_NPMRC_LINES = [];
109
- const LOOM_PACKAGE_RELEVANT_PATHS = [
110
- "LICENSE",
111
- "NOTICE",
112
- "README.md",
113
- "THIRD_PARTY_NOTICES.md",
114
- "bin",
115
- "deno.json",
116
- "deno.lock",
117
- "mod.ts",
118
- "runtime",
119
- "scripts/build_npm.ts",
120
- "skills",
121
- "src",
122
- ];
119
+ /**
120
+ * Exit status for a command that refreshed the linked local Loom package and
121
+ * stopped before running stale in-process Loom code (EX_TEMPFAIL: retry).
122
+ */
123
+ exports.LOOM_LOCAL_DEV_RERUN_EXIT_CODE = 75;
123
124
  const PRODUCTION_GITHUB_ENVIRONMENT = "production";
124
125
  const REQUIRED_GITHUB_VERCEL_SECRET_NAMES = ["VERCEL_TOKEN"];
125
126
  const REQUIRED_GITHUB_VERCEL_ID_NAMES = [
@@ -391,14 +392,17 @@ async function writeTextIfChanged(path, text) {
391
392
  }
392
393
  async function defaultCommandRunner(command, args, options) {
393
394
  return await new Promise((resolvePromise) => {
394
- const inherit = options.stdio === "inherit";
395
+ const inherit = options.stdio === "inherit" ||
396
+ options.stdio === "inherit-stderr";
395
397
  const pipeInput = !inherit && options.input !== undefined;
396
398
  const child = (0, node_child_process_1.spawn)(command, args, {
397
399
  cwd: options.cwd,
398
400
  env: options.env,
399
- stdio: inherit
400
- ? "inherit"
401
- : [pipeInput ? "pipe" : "ignore", "pipe", "pipe"],
401
+ stdio: options.stdio === "inherit-stderr"
402
+ ? ["inherit", 2, 2]
403
+ : inherit
404
+ ? "inherit"
405
+ : [pipeInput ? "pipe" : "ignore", "pipe", "pipe"],
402
406
  });
403
407
  const stdoutChunks = [];
404
408
  const stderrChunks = [];
@@ -684,6 +688,215 @@ function getPublishedLoomDependencySpec(packageJson) {
684
688
  }
685
689
  return dependency;
686
690
  }
691
+ function parseCatalogReference(spec) {
692
+ const match = spec?.match(/^catalog:(.*)$/);
693
+ return match ? match[1].trim() || "default" : null;
694
+ }
695
+ function parseYamlKeyLine(body) {
696
+ const match = body.match(/^(?:'([^']*)'|"([^"]*)"|([^\s#'"][^:]*?))\s*:(?:\s+(.*))?$/);
697
+ return match
698
+ ? { key: match[1] ?? match[2] ?? match[3], rest: match[4] ?? "" }
699
+ : null;
700
+ }
701
+ function isYamlBlockHeader(rest) {
702
+ return rest.trim() === "" || rest.trim().startsWith("#");
703
+ }
704
+ /**
705
+ * Returns the line indexes of the direct entries of the block map at `path`
706
+ * (for example `["catalogs", "loom"]`), or null when it is missing.
707
+ */
708
+ function findYamlBlockMapEntries(lines, path) {
709
+ let start = -1;
710
+ let end = lines.length;
711
+ for (const key of path) {
712
+ let childIndent = null;
713
+ let found = -1;
714
+ for (let index = start + 1; index < end; index += 1) {
715
+ const line = lines[index];
716
+ const trimmed = line.trim();
717
+ if (trimmed === "" || trimmed.startsWith("#"))
718
+ continue;
719
+ const indent = line.length - line.trimStart().length;
720
+ childIndent ??= indent;
721
+ if (indent !== childIndent)
722
+ continue;
723
+ const entry = parseYamlKeyLine(trimmed);
724
+ if (entry?.key === key && isYamlBlockHeader(entry.rest)) {
725
+ found = index;
726
+ break;
727
+ }
728
+ }
729
+ if (found === -1)
730
+ return null;
731
+ const headerIndent = lines[found].length - lines[found].trimStart().length;
732
+ start = found;
733
+ end = lines.length;
734
+ for (let index = found + 1; index < lines.length; index += 1) {
735
+ const line = lines[index];
736
+ const trimmed = line.trim();
737
+ if (trimmed === "" || trimmed.startsWith("#"))
738
+ continue;
739
+ if (line.length - line.trimStart().length <= headerIndent) {
740
+ end = index;
741
+ break;
742
+ }
743
+ }
744
+ }
745
+ const entries = [];
746
+ let childIndent = null;
747
+ for (let index = start + 1; index < end; index += 1) {
748
+ const line = lines[index];
749
+ const trimmed = line.trim();
750
+ if (trimmed === "" || trimmed.startsWith("#"))
751
+ continue;
752
+ const indent = line.length - line.trimStart().length;
753
+ childIndent ??= indent;
754
+ if (indent === childIndent)
755
+ entries.push(index);
756
+ }
757
+ return entries;
758
+ }
759
+ function splitYamlScalarComment(rest) {
760
+ const trimmed = rest.trim();
761
+ const quoted = trimmed.match(/^(['"])(.*?)\1(\s+#.*)?$/);
762
+ if (quoted) {
763
+ return { comment: quoted[3] ?? "", quote: quoted[1], value: quoted[2] };
764
+ }
765
+ const plain = trimmed.match(/^(.*?)(\s+#.*)?$/);
766
+ return { comment: plain[2] ?? "", quote: "", value: plain[1] };
767
+ }
768
+ function catalogPaths(catalog) {
769
+ // The default catalog may live under `catalog:` or `catalogs.default:`.
770
+ return catalog === "default"
771
+ ? [["catalog"], ["catalogs", "default"]]
772
+ : [["catalogs", catalog]];
773
+ }
774
+ /**
775
+ * Finds the line of the map at `path` when it is written as a flow map
776
+ * (`catalog: { ... }`), with its content when it fits on that line, or
777
+ * `unsupported` for flow maps Loom cannot read (multi-line or nested).
778
+ */
779
+ function findYamlFlowMapLine(lines, path) {
780
+ for (let depth = 0; depth < path.length; depth += 1) {
781
+ const parentEntries = findYamlBlockMapEntries(lines, path.slice(0, depth));
782
+ for (const line of parentEntries ?? []) {
783
+ const entry = parseYamlKeyLine(lines[line].trim());
784
+ if (entry?.key !== path[depth] || !entry.rest.trim().startsWith("{")) {
785
+ continue;
786
+ }
787
+ if (depth < path.length - 1)
788
+ return { line, unsupported: true };
789
+ const flow = entry.rest.trim().match(/^\{(.*)\}\s*(?:#.*)?$/);
790
+ return flow
791
+ ? { content: flow[1], line, unsupported: false }
792
+ : { line, unsupported: true };
793
+ }
794
+ }
795
+ return null;
796
+ }
797
+ function parseYamlFlowEntries(content) {
798
+ return content.split(",").flatMap((part) => {
799
+ const match = part.trim().match(/^(?:'([^']*)'|"([^"]*)"|([^:\s]+))\s*:\s*(.*?)\s*$/);
800
+ return match
801
+ ? [{
802
+ key: match[1] ?? match[2] ?? match[3],
803
+ value: splitYamlScalarComment(match[4]).value,
804
+ }]
805
+ : [];
806
+ });
807
+ }
808
+ /** Finds the Loom entry of a pnpm catalog in pnpm-workspace.yaml text. */
809
+ function findLoomCatalogEntry(workspaceText, catalog) {
810
+ if (!workspaceText)
811
+ return null;
812
+ const lines = normalizeText(workspaceText).split("\n");
813
+ for (const path of catalogPaths(catalog)) {
814
+ const label = `${path.join(".")}:`;
815
+ for (const line of findYamlBlockMapEntries(lines, path) ?? []) {
816
+ const entry = parseYamlKeyLine(lines[line].trim());
817
+ if (entry?.key !== exports.LOOM_DEPENDENCY)
818
+ continue;
819
+ return {
820
+ catalog,
821
+ flow: false,
822
+ label,
823
+ line,
824
+ spec: splitYamlScalarComment(entry.rest).value,
825
+ };
826
+ }
827
+ const flow = findYamlFlowMapLine(lines, path);
828
+ if (flow && !flow.unsupported) {
829
+ const entry = parseYamlFlowEntries(flow.content).find((candidate) => candidate.key === exports.LOOM_DEPENDENCY);
830
+ if (entry) {
831
+ return {
832
+ catalog,
833
+ flow: true,
834
+ label,
835
+ line: flow.line,
836
+ spec: entry.value,
837
+ };
838
+ }
839
+ }
840
+ }
841
+ return null;
842
+ }
843
+ /**
844
+ * Names a catalog that exists in a flow form Loom cannot read (multi-line
845
+ * or nested flow maps), so callers can say so instead of reporting a
846
+ * missing entry.
847
+ */
848
+ function findUnreadableLoomCatalog(workspaceText, catalog) {
849
+ if (!workspaceText)
850
+ return null;
851
+ const lines = normalizeText(workspaceText).split("\n");
852
+ for (const path of catalogPaths(catalog)) {
853
+ if (findYamlFlowMapLine(lines, path)?.unsupported) {
854
+ return `${path.join(".")}:`;
855
+ }
856
+ }
857
+ return null;
858
+ }
859
+ /** Rewrites a catalog entry's version, keeping its key, quotes, and comment. */
860
+ function setLoomCatalogEntryText(workspaceText, entry, spec) {
861
+ const lines = normalizeText(workspaceText).split("\n");
862
+ const line = lines[entry.line];
863
+ if (entry.flow) {
864
+ const pattern = /((['"]?)@gadicc\/loom\2\s*:\s*)(['"]?)([^,}'"]*?)\3(\s*[,}])/;
865
+ if (!pattern.test(line))
866
+ return null;
867
+ lines[entry.line] = line.replace(pattern, (_match, prefix, _key, quote, _value, after) => `${prefix}${quote}${spec}${quote}${after}`);
868
+ return lines.join("\n");
869
+ }
870
+ const colon = line.match(/^(\s*(?:'[^']*'|"[^"]*"|[^\s#'"][^:]*?)\s*:\s+)(.*)$/);
871
+ if (!colon)
872
+ return null;
873
+ const { comment, quote } = splitYamlScalarComment(colon[2]);
874
+ lines[entry.line] = `${colon[1]}${quote}${spec}${quote}${comment}`;
875
+ return lines.join("\n");
876
+ }
877
+ async function resolveLoomDependencySpec(cwd, packageJson, options = {}) {
878
+ const raw = packageJson.dependencies?.[exports.LOOM_DEPENDENCY] ??
879
+ (options.includeDev
880
+ ? packageJson.devDependencies?.[exports.LOOM_DEPENDENCY]
881
+ : undefined);
882
+ const catalogName = parseCatalogReference(raw);
883
+ if (!catalogName) {
884
+ return { catalogEntry: null, catalogName: null, effective: raw, raw };
885
+ }
886
+ const catalogEntry = findLoomCatalogEntry(await readTextIfExists((0, node_path_1.join)(cwd, "pnpm-workspace.yaml")), catalogName);
887
+ return {
888
+ catalogEntry,
889
+ catalogName,
890
+ effective: catalogEntry?.spec,
891
+ raw,
892
+ };
893
+ }
894
+ /** Advice for moving a catalog-pinned Loom to `version`. */
895
+ function formatLoomCatalogPinAdvice(entry, catalogName, version) {
896
+ const map = entry?.label ??
897
+ (catalogName === "default" ? "catalog:" : `catalogs.${catalogName}:`);
898
+ return `Set ${exports.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).`;
899
+ }
687
900
  function isLocalPackageSpec(spec) {
688
901
  return spec.startsWith("file:") || spec.startsWith("link:") ||
689
902
  spec.startsWith("workspace:");
@@ -895,19 +1108,20 @@ function ensureLinguiGitignoreText(existingText, generatedCatalogs) {
895
1108
  text: nextText,
896
1109
  };
897
1110
  }
898
- function loomDevStateGitignoreLineMatches(line) {
1111
+ function loomDevGitignoreLineMatches(line, path) {
899
1112
  const normalized = line.trim().replace(/^\/?/, "");
900
- return normalized === exports.LOOM_LOCAL_DEV_STATE_GITIGNORE_LINE ||
901
- normalized === ".loom/" || normalized === ".loom";
1113
+ return normalized === path || normalized === ".loom/" ||
1114
+ normalized === ".loom";
902
1115
  }
903
1116
  function ensureLoomDevStateGitignoreText(existingText) {
904
1117
  const normalized = existingText ? normalizeText(existingText) : "";
905
1118
  const lines = normalized
906
1119
  .split("\n")
907
1120
  .filter((line, index, array) => index < array.length - 1 || line !== "");
908
- const missingLines = lines.some(loomDevStateGitignoreLineMatches)
909
- ? []
910
- : [exports.LOOM_LOCAL_DEV_STATE_GITIGNORE_LINE];
1121
+ const missingLines = [
1122
+ exports.LOOM_LOCAL_DEV_STATE_GITIGNORE_LINE,
1123
+ exports.LOOM_LOCAL_DEV_LOCK_GITIGNORE_LINE,
1124
+ ].filter((path) => !lines.some((line) => loomDevGitignoreLineMatches(line, path)));
911
1125
  const nextText = missingLines.length
912
1126
  ? `${[...lines, ...missingLines].join("\n")}\n`
913
1127
  : normalized;
@@ -1256,18 +1470,34 @@ function dependencyExecutable(tooling, executable) {
1256
1470
  return `yarn ${executable}`;
1257
1471
  }
1258
1472
  }
1259
- function dependencyRefreshCommand(tooling, name, version) {
1473
+ /**
1474
+ * Command that moves one dependency to the given version without
1475
+ * re-resolving anything else. For pnpm, `pnpm add --save-exact` pins
1476
+ * package.json, replaces a local lockfile resolution left by an older
1477
+ * `pnpm update --no-save` link, and keeps every other locked version
1478
+ * (verified with pnpm 10.17); `pnpm update` would re-resolve the
1479
+ * dependency's subtree. Ranges get a plain install because `pnpm add`
1480
+ * rewrites a range's lower bound.
1481
+ */
1482
+ function dependencyRefreshCommand(tooling, name, version, options = {}) {
1260
1483
  switch (tooling.manager) {
1261
1484
  case "deno":
1262
1485
  return "deno install";
1263
1486
  case "npm":
1264
1487
  return `npm install --save-exact ${name}@${version}`;
1265
1488
  case "pnpm":
1266
- return `pnpm update --no-save ${name}@${version} && pnpm install`;
1489
+ return isExactSemverVersion(version)
1490
+ ? `pnpm add${options.pnpmWorkspaceRoot ? " -w" : ""} --save-exact ${name}@${version}`
1491
+ : "pnpm install";
1267
1492
  case "yarn":
1268
1493
  return `yarn add --exact ${name}@${version}`;
1269
1494
  }
1270
1495
  }
1496
+ /** Whether pnpm treats this project root as a workspace root with packages. */
1497
+ async function pnpmWorkspaceDeclaresPackages(cwd) {
1498
+ const text = await readTextIfExists((0, node_path_1.join)(cwd, "pnpm-workspace.yaml"));
1499
+ return text !== null && /^packages:/m.test(normalizeText(text));
1500
+ }
1271
1501
  function getDbExpectedScripts(config, tooling) {
1272
1502
  const drizzleKit = dependencyExecutable(tooling.dependencies, "drizzle-kit");
1273
1503
  return {
@@ -1757,6 +1987,10 @@ function getApiKeysConfig(framework, dbConfig, packageJson, featureConfig) {
1757
1987
  ? "src/api-lib/apiKeys"
1758
1988
  : "api-lib/apiKeys";
1759
1989
  return {
1990
+ // Recorded by the app; Loom never infers or rewrites this choice.
1991
+ ...(featureConfig?.betterAuthHttpEndpoints !== undefined
1992
+ ? { betterAuthHttpEndpoints: featureConfig.betterAuthHttpEndpoints }
1993
+ : {}),
1760
1994
  entrypoints: {
1761
1995
  adminPage: featureConfig?.entrypoints?.adminPage ??
1762
1996
  `${appRoot}/admin/api-keys/page.tsx`,
@@ -1973,7 +2207,7 @@ function ensureNextAgentsMdText(existingText) {
1973
2207
  : "\n\n"}${block}`;
1974
2208
  return { changed: text !== normalized, text };
1975
2209
  }
1976
- function getManagedDevOverrideBlock(overrideSpec, state) {
2210
+ function getManagedDevOverrideBlock(overrideSpec, state, layout = {}) {
1977
2211
  // This is a workaround for current pnpm behavior around local package
1978
2212
  // development. In testing with pnpm 10.x, direct `pnpm link` against Loom
1979
2213
  // mutated pnpm-workspace overrides anyway and broke peer resolution from
@@ -1992,13 +2226,32 @@ function getManagedDevOverrideBlock(overrideSpec, state) {
1992
2226
  : null,
1993
2227
  ].filter((line) => line !== null)
1994
2228
  : [];
2229
+ const pad = " ".repeat(layout.indent ?? 2);
1995
2230
  return [
1996
- ` ${exports.LOOM_MANAGED_DEV_OVERRIDE_START}`,
1997
- ...stateLines.map((line) => ` ${line}`),
1998
- ` "${exports.LOOM_DEPENDENCY}": ${JSON.stringify(overrideSpec)}`,
1999
- ` ${exports.LOOM_MANAGED_DEV_OVERRIDE_END}`,
2231
+ `${pad}${exports.LOOM_MANAGED_DEV_OVERRIDE_START}`,
2232
+ ...(layout.createdHeader === undefined ? [] : [
2233
+ `${pad}# overrides-header: ${layout.createdHeader ? "created" : "existing"}`,
2234
+ ]),
2235
+ ...(layout.replacedHeader
2236
+ ? [`${pad}# replaced-header: ${layout.replacedHeader}`]
2237
+ : []),
2238
+ ...stateLines.map((line) => `${pad}${line}`),
2239
+ `${pad}"${exports.LOOM_DEPENDENCY}": ${JSON.stringify(overrideSpec)}`,
2240
+ `${pad}${exports.LOOM_MANAGED_DEV_OVERRIDE_END}`,
2000
2241
  ].join("\n");
2001
2242
  }
2243
+ /** Reads the layout markers and indentation of an existing managed block. */
2244
+ function getManagedDevOverrideBlockLayout(blockText) {
2245
+ if (!blockText)
2246
+ return {};
2247
+ const header = getManagedDevStateValue(blockText, "overrides-header");
2248
+ return {
2249
+ // Blocks from before this marker always removed an empty bare header.
2250
+ createdHeader: header === undefined ? undefined : header === "created",
2251
+ indent: blockText.length - blockText.trimStart().length,
2252
+ replacedHeader: getManagedDevStateValue(blockText, "replaced-header"),
2253
+ };
2254
+ }
2002
2255
  function getManagedDevOverrideBlockRegex() {
2003
2256
  return new RegExp(`^[ \\t]*${escapeRegExp(exports.LOOM_MANAGED_DEV_OVERRIDE_START)}\\n[\\s\\S]*?^[ \\t]*${escapeRegExp(exports.LOOM_MANAGED_DEV_OVERRIDE_END)}\\n?`, "m");
2004
2257
  }
@@ -2008,24 +2261,149 @@ function formatYamlLines(lines) {
2008
2261
  }
2009
2262
  return lines.length ? `${lines.join("\n")}\n` : "";
2010
2263
  }
2011
- function findTopLevelSection(lines, sectionName) {
2012
- const header = `${sectionName}:`;
2013
- const start = lines.findIndex((line) => line === header);
2014
- if (start === -1) {
2264
+ const OVERRIDES_KEY_PATTERN = /^(?:overrides|"overrides"|'overrides'):(?:\s|$)/;
2265
+ /**
2266
+ * Locates the top-level `overrides:` key (plain or quoted) of
2267
+ * pnpm-workspace.yaml lines and how its value is written: a block map
2268
+ * (`overrides:`, optionally with a comment), an empty flow map
2269
+ * (`overrides: {}`), or another flow/scalar form Loom cannot add entries
2270
+ * to. `end` is the index of the next top-level key and `indent` the
2271
+ * indentation of the map's entries.
2272
+ */
2273
+ function findPnpmWorkspaceOverridesHeader(lines) {
2274
+ const index = lines.findIndex((line) => OVERRIDES_KEY_PATTERN.test(line));
2275
+ if (index === -1)
2015
2276
  return null;
2016
- }
2277
+ const value = lines[index].slice(lines[index].indexOf(":") + 1).trim();
2278
+ const style = value === "" || value.startsWith("#")
2279
+ ? "block"
2280
+ : /^\{\s*\}\s*(?:#.*)?$/.test(value)
2281
+ ? "empty-flow"
2282
+ : "other";
2017
2283
  let end = lines.length;
2018
- for (let index = start + 1; index < lines.length; index += 1) {
2019
- const line = lines[index];
2020
- if (line !== "" && !line.startsWith(" ") && !line.startsWith("\t")) {
2021
- end = index;
2284
+ let indent = null;
2285
+ for (let line = index + 1; line < lines.length; line += 1) {
2286
+ const trimmed = lines[line].trim();
2287
+ if (trimmed === "" || trimmed.startsWith("#"))
2288
+ continue;
2289
+ if (!/^\s/.test(lines[line])) {
2290
+ end = line;
2291
+ break;
2292
+ }
2293
+ indent ??= lines[line].length - lines[line].trimStart().length;
2294
+ }
2295
+ return { end, indent: indent ?? 2, index, style };
2296
+ }
2297
+ /**
2298
+ * Lists the keys of the top-level `overrides:` map in pnpm-workspace.yaml
2299
+ * text, in block or single-line flow style. Other maps that can mention
2300
+ * Loom, such as `catalog:` and `catalogs:`, are not overrides.
2301
+ */
2302
+ function getPnpmWorkspaceOverrideKeys(text) {
2303
+ const lines = normalizeText(text).split("\n");
2304
+ const start = findPnpmWorkspaceOverridesHeader(lines)?.index ?? -1;
2305
+ if (start === -1)
2306
+ return [];
2307
+ const flow = lines[start].slice(lines[start].indexOf(":") + 1).match(/^\s*\{(.*)\}\s*(?:#.*)?$/);
2308
+ if (flow) {
2309
+ return flow[1].split(",").flatMap((entry) => {
2310
+ const match = entry.trim().match(/^(?:'([^']*)'|"([^"]*)"|([^:]+?))\s*:/);
2311
+ return match ? [match[1] ?? match[2] ?? match[3]] : [];
2312
+ });
2313
+ }
2314
+ const keys = [];
2315
+ let indent = null;
2316
+ for (const line of lines.slice(start + 1)) {
2317
+ const trimmed = line.trim();
2318
+ if (trimmed === "" || trimmed.startsWith("#"))
2319
+ continue;
2320
+ // The next top-level key ends the map.
2321
+ if (!/^\s/.test(line))
2022
2322
  break;
2323
+ const lineIndent = line.length - line.trimStart().length;
2324
+ indent ??= lineIndent;
2325
+ if (lineIndent !== indent)
2326
+ continue;
2327
+ const match = trimmed.match(/^(?:'([^']+)'|"([^"]+)"|([^\s#'"][^:]*?))\s*:(?:\s|$)/);
2328
+ if (match)
2329
+ keys.push(match[1] ?? match[2] ?? match[3]);
2330
+ }
2331
+ return keys;
2332
+ }
2333
+ /** A YAML scalar without quotes or a trailing comment. */
2334
+ function plainYamlValue(value) {
2335
+ const trimmed = value.trim();
2336
+ if (/^["']/.test(trimmed)) {
2337
+ const quote = trimmed[0];
2338
+ const end = trimmed.indexOf(quote, 1);
2339
+ return end === -1 ? trimmed.slice(1) : trimmed.slice(1, end);
2340
+ }
2341
+ return trimmed.replace(/\s+#.*$/, "").trim();
2342
+ }
2343
+ /**
2344
+ * Local (`file:`/`link:`/`workspace:`) Loom entries of the pnpm-workspace.yaml
2345
+ * `overrides:` map outside Loom's managed block, such as one written by
2346
+ * hand. `line` is the entry's line in `text` once the managed block is
2347
+ * removed, or null in flow style, which Loom does not edit.
2348
+ */
2349
+ function getUnmanagedPnpmWorkspaceLoomOverrides(text) {
2350
+ const entries = [];
2351
+ if (!text)
2352
+ return entries;
2353
+ const lines = normalizeText(text).replace(getManagedDevOverrideBlockRegex(), "").split("\n");
2354
+ const header = findPnpmWorkspaceOverridesHeader(lines);
2355
+ if (!header)
2356
+ return entries;
2357
+ const add = (key, value, line) => {
2358
+ const spec = plainYamlValue(value);
2359
+ if (overrideKeyTargetsLoom(key) && isLocalPackageSpec(spec)) {
2360
+ entries.push({ key, line, spec });
2361
+ }
2362
+ };
2363
+ const flow = lines[header.index].slice(lines[header.index].indexOf(":") + 1)
2364
+ .match(/^\s*\{(.*)\}\s*(?:#.*)?$/);
2365
+ if (flow) {
2366
+ for (const entry of flow[1].split(",")) {
2367
+ const match = entry.trim().match(/^(?:'([^']*)'|"([^"]*)"|([^:]+?))\s*:\s*(.*)$/);
2368
+ if (match)
2369
+ add(match[1] ?? match[2] ?? match[3], match[4], null);
2023
2370
  }
2371
+ return entries;
2372
+ }
2373
+ for (let index = header.index + 1; index < header.end; index += 1) {
2374
+ const line = lines[index];
2375
+ if (line.length - line.trimStart().length !== header.indent)
2376
+ continue;
2377
+ const match = line.trim().match(/^(?:'([^']+)'|"([^"]+)"|([^\s#'"][^:]*?))\s*:\s+(\S.*)$/);
2378
+ if (match)
2379
+ add(match[1] ?? match[2] ?? match[3], match[4], index);
2380
+ }
2381
+ return entries;
2382
+ }
2383
+ /**
2384
+ * Removes the block-style entries {@link getUnmanagedPnpmWorkspaceLoomOverrides}
2385
+ * finds, and a bare `overrides:` header left without entries. Expects text
2386
+ * without Loom's managed block. Flow-style entries stay and are returned.
2387
+ */
2388
+ function removeUnmanagedPnpmWorkspaceLoomOverrides(text) {
2389
+ const entries = getUnmanagedPnpmWorkspaceLoomOverrides(text);
2390
+ const lines = normalizeText(text).split("\n");
2391
+ const removable = new Set(entries.flatMap((entry) => entry.line === null ? [] : [entry.line]));
2392
+ const kept = lines.filter((_, index) => !removable.has(index));
2393
+ const header = findPnpmWorkspaceOverridesHeader(kept);
2394
+ if (removable.size && header?.style === "block" &&
2395
+ kept[header.index] === "overrides:" &&
2396
+ !hasYamlEntries(kept.slice(header.index + 1, header.end))) {
2397
+ kept.splice(header.index, 1);
2024
2398
  }
2025
- return { end, start };
2399
+ return {
2400
+ changed: removable.size > 0,
2401
+ kept: entries.filter((entry) => entry.line === null),
2402
+ text: formatYamlLines(kept).replace(/\n{3,}/g, "\n\n"),
2403
+ };
2026
2404
  }
2027
2405
  function hasUnmanagedLoomOverride(text) {
2028
- return /^[ \t]+["']?@gadicc\/loom["']?\s*:/m.test(text);
2406
+ return getPnpmWorkspaceOverrideKeys(text).some(overrideKeyTargetsLoom);
2029
2407
  }
2030
2408
  function getManagedDevOverrideSpec(text) {
2031
2409
  if (!text) {
@@ -2075,7 +2453,7 @@ function getManagedDevState(text) {
2075
2453
  }
2076
2454
  function setManagedDevStateText(existingText, overrideSpec, state) {
2077
2455
  const normalized = existingText ? normalizeText(existingText) : "";
2078
- const nextText = normalized.replace(getManagedDevOverrideBlockRegex(), `${getManagedDevOverrideBlock(overrideSpec, state)}\n`);
2456
+ const nextText = normalized.replace(getManagedDevOverrideBlockRegex(), `${getManagedDevOverrideBlock(overrideSpec, state, getManagedDevOverrideBlockLayout(getManagedDevOverrideBlockText(normalized)))}\n`);
2079
2457
  return {
2080
2458
  changed: nextText !== normalized,
2081
2459
  text: nextText,
@@ -2104,17 +2482,45 @@ function ensurePnpmWorkspaceLocalDevText(existingText, overrideSpec) {
2104
2482
  text: normalized,
2105
2483
  };
2106
2484
  }
2107
- const blockLines = getManagedDevOverrideBlock(overrideSpec).split("\n");
2108
2485
  const lines = baseText === "" ? [] : baseText.replace(/\n$/, "").split("\n");
2109
- const overridesSection = findTopLevelSection(lines, "overrides");
2110
- if (overridesSection) {
2111
- lines.splice(overridesSection.start + 1, 0, ...blockLines);
2486
+ const header = findPnpmWorkspaceOverridesHeader(lines);
2487
+ // Relinking: put back the `overrides: {}` line an earlier link rewrote.
2488
+ const previous = getManagedDevOverrideBlockLayout(getManagedDevOverrideBlockText(normalized));
2489
+ if (header && previous.replacedHeader && lines[header.index] === "overrides:" &&
2490
+ !hasYamlEntries(lines.slice(header.index + 1, header.end))) {
2491
+ lines[header.index] = previous.replacedHeader;
2492
+ }
2493
+ const current = findPnpmWorkspaceOverridesHeader(lines);
2494
+ if (current?.style === "other") {
2495
+ return {
2496
+ changed: false,
2497
+ 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.",
2498
+ text: normalized,
2499
+ };
2500
+ }
2501
+ if (current) {
2502
+ const replacedHeader = current.style === "empty-flow"
2503
+ ? lines[current.index]
2504
+ : undefined;
2505
+ if (replacedHeader)
2506
+ lines[current.index] = "overrides:";
2507
+ lines.splice(current.index + 1, 0, ...getManagedDevOverrideBlock(overrideSpec, undefined, {
2508
+ // A relink keeps what the first link recorded about the header,
2509
+ // including nothing at all for blocks written before the marker.
2510
+ createdHeader: previous.indent === undefined
2511
+ ? false
2512
+ : previous.createdHeader,
2513
+ indent: current.style === "block" ? current.indent : 2,
2514
+ replacedHeader,
2515
+ }).split("\n"));
2112
2516
  }
2113
2517
  else {
2114
2518
  if (lines.length && lines.at(-1) !== "") {
2115
2519
  lines.push("");
2116
2520
  }
2117
- lines.push("overrides:", ...blockLines);
2521
+ lines.push("overrides:", ...getManagedDevOverrideBlock(overrideSpec, undefined, {
2522
+ createdHeader: true,
2523
+ }).split("\n"));
2118
2524
  }
2119
2525
  const nextText = formatYamlLines(lines);
2120
2526
  return {
@@ -2131,19 +2537,21 @@ function clearPnpmWorkspaceLocalDevText(existingText) {
2131
2537
  text: normalized,
2132
2538
  };
2133
2539
  }
2540
+ const { createdHeader, replacedHeader } = getManagedDevOverrideBlockLayout(getManagedDevOverrideBlockText(normalized));
2134
2541
  const withoutManaged = normalized.replace(getManagedDevOverrideBlockRegex(), "");
2135
2542
  const lines = withoutManaged === ""
2136
2543
  ? []
2137
2544
  : withoutManaged.replace(/\n$/, "").split("\n");
2138
- const overridesSection = findTopLevelSection(lines, "overrides");
2139
- if (overridesSection) {
2140
- const bodyLines = lines.slice(overridesSection.start + 1, overridesSection.end);
2141
- const hasEntries = bodyLines.some((line) => {
2142
- const trimmed = line.trim();
2143
- return trimmed !== "" && !trimmed.startsWith("#");
2144
- });
2145
- if (!hasEntries) {
2146
- lines.splice(overridesSection.start, overridesSection.end - overridesSection.start);
2545
+ const header = findPnpmWorkspaceOverridesHeader(lines);
2546
+ if (header?.style === "block" &&
2547
+ !hasYamlEntries(lines.slice(header.index + 1, header.end))) {
2548
+ if (replacedHeader) {
2549
+ lines[header.index] = replacedHeader;
2550
+ }
2551
+ else if (createdHeader ??
2552
+ // Older blocks did not record it; Loom only added bare headers.
2553
+ lines[header.index] === "overrides:") {
2554
+ lines.splice(header.index, header.end - header.index);
2147
2555
  }
2148
2556
  }
2149
2557
  const nextText = formatYamlLines(lines).replace(/\n{3,}/g, "\n\n");
@@ -2152,6 +2560,262 @@ function clearPnpmWorkspaceLocalDevText(existingText) {
2152
2560
  text: nextText,
2153
2561
  };
2154
2562
  }
2563
+ const PACKAGE_JSON_OVERRIDE_LOCATIONS = [
2564
+ { field: "resolutions", location: "package.json#resolutions" },
2565
+ { field: "pnpm.overrides", location: "package.json#pnpm.overrides" },
2566
+ ];
2567
+ function formatPnpmOverrideLocation(location) {
2568
+ switch (location) {
2569
+ case "package.json#pnpm.overrides":
2570
+ return "package.json pnpm.overrides";
2571
+ case "package.json#resolutions":
2572
+ return "package.json resolutions";
2573
+ case "pnpm-workspace.yaml":
2574
+ return "pnpm-workspace.yaml";
2575
+ }
2576
+ }
2577
+ function getPackageJsonOverrideMap(packageJson, field) {
2578
+ const value = field === "resolutions"
2579
+ ? packageJson.resolutions
2580
+ : packageJson.pnpm?.overrides;
2581
+ return value && typeof value === "object" && !Array.isArray(value)
2582
+ ? value
2583
+ : {};
2584
+ }
2585
+ function isManagedPackageJsonLoomOverride(spec) {
2586
+ return typeof spec === "string" && spec.startsWith("file:");
2587
+ }
2588
+ /**
2589
+ * Lists local `file:` Loom overrides in package.json override maps. Loom only
2590
+ * writes `file:` specs there, and a local spec is never shippable, so these
2591
+ * entries are treated as the managed local-dev override.
2592
+ */
2593
+ function getPackageJsonLocalLoomOverrides(packageJson) {
2594
+ return PACKAGE_JSON_OVERRIDE_LOCATIONS.flatMap(({ field, location }) => {
2595
+ const spec = getPackageJsonOverrideMap(packageJson, field)[exports.LOOM_DEPENDENCY];
2596
+ return isManagedPackageJsonLoomOverride(spec) ? [{ location, spec }] : [];
2597
+ });
2598
+ }
2599
+ /** Returns the managed local Loom override of a pnpm project, if active. */
2600
+ function getActivePnpmLocalDevOverride(workspaceText, packageJson) {
2601
+ const workspaceSpec = getManagedDevOverrideSpec(workspaceText);
2602
+ if (workspaceSpec) {
2603
+ return { location: "pnpm-workspace.yaml", spec: workspaceSpec };
2604
+ }
2605
+ return getPackageJsonLocalLoomOverrides(packageJson)[0] ?? null;
2606
+ }
2607
+ function getUnmanagedPnpmWorkspaceOverrideNames(text) {
2608
+ const normalized = text ? normalizeText(text) : "";
2609
+ return getPnpmWorkspaceOverrideKeys(normalized.replace(getManagedDevOverrideBlockRegex(), ""));
2610
+ }
2611
+ /** First pnpm release that reads `overrides` from pnpm-workspace.yaml. */
2612
+ const PNPM_WORKSPACE_OVERRIDES_SINCE = [10, 5, 1];
2613
+ function parsePnpmVersion(value) {
2614
+ const match = value?.match(/^(\d+)\.(\d+)\.(\d+)/);
2615
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
2616
+ }
2617
+ function pnpmVersionAtLeast(version, minimum) {
2618
+ for (let index = 0; index < 3; index += 1) {
2619
+ if (version[index] !== minimum[index]) {
2620
+ return version[index] > minimum[index];
2621
+ }
2622
+ }
2623
+ return true;
2624
+ }
2625
+ async function detectPnpmVersion(cwd, packageJson, commandRunner, env) {
2626
+ const declared = parsePnpmVersion(packageJson.packageManager?.match(/^pnpm@(.+)$/)?.[1]);
2627
+ if (declared)
2628
+ return declared;
2629
+ // Not npm_config_user_agent: it names the pnpm running the current
2630
+ // script, which can differ from the `pnpm` this process spawns (a pnpm
2631
+ // devDependency in node_modules/.bin, say).
2632
+ const cached = spawnedPnpmVersions.get(commandRunner)?.get(cwd);
2633
+ if (cached)
2634
+ return await cached;
2635
+ const pending = detectSpawnedPnpmVersion(cwd, commandRunner, env);
2636
+ const byCwd = spawnedPnpmVersions.get(commandRunner) ?? new Map();
2637
+ byCwd.set(cwd, pending);
2638
+ spawnedPnpmVersions.set(commandRunner, byCwd);
2639
+ return await pending;
2640
+ }
2641
+ /**
2642
+ * `pnpm --version` results for this process, per command runner and
2643
+ * project, so one command spawns pnpm at most once per project.
2644
+ */
2645
+ const spawnedPnpmVersions = new WeakMap();
2646
+ async function detectSpawnedPnpmVersion(cwd, commandRunner, env) {
2647
+ const result = await commandRunner("pnpm", ["--version"], { cwd, env })
2648
+ .catch(() => null);
2649
+ const running = result?.code === 0
2650
+ ? parsePnpmVersion(result.stdout.trim())
2651
+ : null;
2652
+ if (running)
2653
+ return running;
2654
+ // The pnpm that last installed node_modules, when pnpm itself cannot run.
2655
+ const modules = await readTextIfExists((0, node_path_1.join)(cwd, "node_modules", ".modules.yaml"));
2656
+ return parsePnpmVersion(modules?.match(/^\s*"?packageManager"?\s*:\s*"?pnpm@([^"\s]+)/m)?.[1]);
2657
+ }
2658
+ /**
2659
+ * Chooses the override map pnpm will actually apply. Verified with real
2660
+ * pnpm 9.7.0 through 11.25.0 on a local directory override:
2661
+ * - before 10.5.1, pnpm reads overrides only from package.json `resolutions`
2662
+ * and `pnpm.overrides` (Loom creates `resolutions` when neither exists);
2663
+ * - from 10.5.1, pnpm also reads pnpm-workspace.yaml `overrides`, but only
2664
+ * while both package.json maps are empty, never merged with them;
2665
+ * - pnpm 11 reads only pnpm-workspace.yaml `overrides`.
2666
+ * Writing the override anywhere else leaves pnpm reporting an up-to-date
2667
+ * lockfile that still resolves the published package. An unknown version is
2668
+ * treated as pnpm 10.5.1 or newer.
2669
+ */
2670
+ async function resolvePnpmLocalDevOverrideLocation(cwd, packageJson, commandRunner, env) {
2671
+ const workspaceText = await readTextIfExists((0, node_path_1.join)(cwd, "pnpm-workspace.yaml"));
2672
+ const workspaceBase = workspaceText
2673
+ ? normalizeText(workspaceText).replace(getManagedDevOverrideBlockRegex(), "")
2674
+ : "";
2675
+ const version = await detectPnpmVersion(cwd, packageJson, commandRunner, env);
2676
+ const pnpmVersion = version ? version.join(".") : null;
2677
+ const pnpmMajor = version ? version[0] : null;
2678
+ const pnpmLabel = pnpmVersion ? `pnpm ${pnpmVersion}` : "pnpm 10";
2679
+ const workspace = {
2680
+ conflict: hasUnmanagedLoomOverride(workspaceBase)
2681
+ ? `pnpm-workspace.yaml already defines an unmanaged override for ${exports.LOOM_DEPENDENCY}. Move that override aside before enabling loom local-dev mode.`
2682
+ : null,
2683
+ location: "pnpm-workspace.yaml",
2684
+ notes: [],
2685
+ pnpmMajor,
2686
+ pnpmVersion,
2687
+ };
2688
+ const packageJsonEntries = PACKAGE_JSON_OVERRIDE_LOCATIONS.map(({ field, location }) => {
2689
+ const map = getPackageJsonOverrideMap(packageJson, field);
2690
+ return {
2691
+ loomSpec: map[exports.LOOM_DEPENDENCY],
2692
+ location,
2693
+ names: Object.keys(map).filter((name) => !(name === exports.LOOM_DEPENDENCY &&
2694
+ isManagedPackageJsonLoomOverride(map[name]))),
2695
+ };
2696
+ });
2697
+ const packageJsonHasOverrides = packageJsonEntries.some((entry) => entry.names.length > 0);
2698
+ if (pnpmMajor !== null && pnpmMajor >= 11) {
2699
+ return {
2700
+ ...workspace,
2701
+ notes: packageJsonHasOverrides
2702
+ ? [
2703
+ `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.`,
2704
+ ]
2705
+ : [],
2706
+ };
2707
+ }
2708
+ const readsWorkspaceOverrides = version === null ||
2709
+ pnpmVersionAtLeast(version, PNPM_WORKSPACE_OVERRIDES_SINCE);
2710
+ if (readsWorkspaceOverrides && !packageJsonHasOverrides)
2711
+ return workspace;
2712
+ const unmanagedLoom = packageJsonEntries.find((entry) => entry.loomSpec !== undefined &&
2713
+ !isManagedPackageJsonLoomOverride(entry.loomSpec));
2714
+ // pnpm 10 merges both package.json maps, so an override already in one of
2715
+ // them stays put rather than moving whenever the user edits the other.
2716
+ const location = packageJsonEntries.find((entry) => isManagedPackageJsonLoomOverride(entry.loomSpec))?.location ??
2717
+ packageJsonEntries.find((entry) => entry.names.length)?.location ??
2718
+ "package.json#resolutions";
2719
+ const label = formatPnpmOverrideLocation(location);
2720
+ const notes = [
2721
+ readsWorkspaceOverrides
2722
+ ? `${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.`
2723
+ : `${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.`,
2724
+ ];
2725
+ const ignoredWorkspaceNames = getUnmanagedPnpmWorkspaceOverrideNames(workspaceText);
2726
+ if (ignoredWorkspaceNames.length) {
2727
+ notes.push(`${pnpmLabel} also ignores these pnpm-workspace.yaml overrides: ${ignoredWorkspaceNames.join(", ")}. Keep all overrides in one place.`);
2728
+ }
2729
+ return {
2730
+ conflict: workspace.conflict ??
2731
+ (unmanagedLoom
2732
+ ? `${formatPnpmOverrideLocation(unmanagedLoom.location)} already defines an unmanaged override for ${exports.LOOM_DEPENDENCY} (${String(unmanagedLoom.loomSpec)}). Move that override aside before enabling loom local-dev mode.`
2733
+ : null),
2734
+ location,
2735
+ notes,
2736
+ pnpmMajor,
2737
+ pnpmVersion,
2738
+ };
2739
+ }
2740
+ /**
2741
+ * Writes the managed override at one location, then removes managed
2742
+ * overrides from every other location, so pnpm sees exactly one Loom
2743
+ * override and an interrupted move never leaves none. An existing workspace
2744
+ * block for the same spec is kept with its sync state.
2745
+ */
2746
+ async function placePnpmLocalDevOverride(cwd, overrideSpec, location) {
2747
+ const changedFiles = new Set();
2748
+ const workspacePath = (0, node_path_1.join)(cwd, "pnpm-workspace.yaml");
2749
+ const setPackageJsonOverride = async (field, value) => {
2750
+ const update = await (0, projectTooling_js_1.mutatePackageJsonOverride)(cwd, field, exports.LOOM_DEPENDENCY, value);
2751
+ if (update.changed)
2752
+ changedFiles.add("package.json");
2753
+ };
2754
+ const workspaceText = await readTextIfExists(workspacePath);
2755
+ if (location === "pnpm-workspace.yaml") {
2756
+ if (getManagedDevOverrideSpec(workspaceText) !== overrideSpec) {
2757
+ const update = ensurePnpmWorkspaceLocalDevText(workspaceText, overrideSpec);
2758
+ if (update.conflict)
2759
+ throw new Error(update.conflict);
2760
+ if (update.changed) {
2761
+ await writeTextOrDeleteIfEmpty(workspacePath, update.text);
2762
+ changedFiles.add("pnpm-workspace.yaml");
2763
+ }
2764
+ }
2765
+ }
2766
+ else {
2767
+ const target = PACKAGE_JSON_OVERRIDE_LOCATIONS.find((entry) => entry.location === location);
2768
+ const { packageJson } = await readProjectPackageJson(cwd);
2769
+ // Record, before writing, whether Loom is about to create the map (and
2770
+ // the `pnpm` object), so unlinking removes exactly what Loom added.
2771
+ const created = await readCreatedPackageJsonMaps(cwd);
2772
+ const pnpmField = target.field === "pnpm.overrides";
2773
+ if (getRawPackageJsonMap(packageJson, target.field) === undefined) {
2774
+ created[target.field] = true;
2775
+ if (pnpmField)
2776
+ created.pnpm = packageJson.pnpm === undefined;
2777
+ }
2778
+ else if (!isManagedPackageJsonLoomOverride(getPackageJsonOverrideMap(packageJson, target.field)[exports.LOOM_DEPENDENCY])) {
2779
+ // A map without Loom's entry belongs to the project, even if an
2780
+ // earlier link created it: the user may have dropped Loom's entry by
2781
+ // hand and committed a map of their own since.
2782
+ created[target.field] = false;
2783
+ if (pnpmField)
2784
+ created.pnpm = false;
2785
+ }
2786
+ await setPackageJsonOverride(target.field, overrideSpec);
2787
+ await writeCreatedPackageJsonMaps(cwd, created, overrideSpec);
2788
+ }
2789
+ for (const { field, location: fieldLocation } of PACKAGE_JSON_OVERRIDE_LOCATIONS) {
2790
+ if (fieldLocation === location)
2791
+ continue;
2792
+ if (await removePackageJsonLoomOverride(cwd, field)) {
2793
+ changedFiles.add("package.json");
2794
+ }
2795
+ }
2796
+ if (location !== "pnpm-workspace.yaml") {
2797
+ const update = clearPnpmWorkspaceLocalDevText(await readTextIfExists(workspacePath));
2798
+ if (update.changed) {
2799
+ await writeTextOrDeleteIfEmpty(workspacePath, update.text);
2800
+ changedFiles.add("pnpm-workspace.yaml");
2801
+ }
2802
+ }
2803
+ return [...changedFiles];
2804
+ }
2805
+ /**
2806
+ * Proves that pnpm applied the managed override: pnpm records the override
2807
+ * map it actually used in the lockfile's top-level `overrides:` section.
2808
+ */
2809
+ function lockfileAppliesLocalDevOverride(lockfileText, overrideSpec) {
2810
+ return lockfileText !== null &&
2811
+ (0, localDevPackage_js_1.getLockfileOverride)(lockfileText, exports.LOOM_DEPENDENCY) === overrideSpec;
2812
+ }
2813
+ function hasYamlEntries(lines) {
2814
+ return lines.some((line) => {
2815
+ const trimmed = line.trim();
2816
+ return trimmed !== "" && !trimmed.startsWith("#");
2817
+ });
2818
+ }
2155
2819
  function pnpmWorkspaceExcludesMinimumReleaseAge(text, dependency) {
2156
2820
  if (!text)
2157
2821
  return false;
@@ -2216,6 +2880,13 @@ async function writeTextOrDeleteIfEmpty(path, text) {
2216
2880
  await (0, promises_1.mkdir)((0, node_path_1.dirname)(path), { recursive: true });
2217
2881
  await (0, promises_1.writeFile)(path, text, "utf8");
2218
2882
  }
2883
+ async function isPnpmProject(cwd, packageJson) {
2884
+ if (packageJson.packageManager) {
2885
+ return packageJson.packageManager.startsWith("pnpm@");
2886
+ }
2887
+ return await exists((0, node_path_1.join)(cwd, "pnpm-lock.yaml")) ||
2888
+ await exists((0, node_path_1.join)(cwd, "pnpm-workspace.yaml"));
2889
+ }
2219
2890
  async function ensurePnpmProject(cwd, packageJson) {
2220
2891
  if (packageJson.packageManager?.startsWith("pnpm@") ||
2221
2892
  await exists((0, node_path_1.join)(cwd, "pnpm-lock.yaml")) ||
@@ -2328,33 +2999,49 @@ async function isLocalLoomBuildStale(sourceRoot, localPackagePath) {
2328
2999
  if (!outputPackageStat) {
2329
3000
  return true;
2330
3001
  }
3002
+ // Builds record the content they started from. Compare content rather than
3003
+ // timestamps whenever that stamp exists; older builds lack it.
3004
+ const stamp = await (0, localDevPackage_js_1.readLoomBuildStamp)(localPackagePath);
3005
+ if (stamp) {
3006
+ const fingerprint = await (0, localDevPackage_js_1.computeLoomSourceFingerprint)(sourceRoot);
3007
+ if (!(0, localDevPackage_js_1.hasLoomBuildProvenance)(stamp)) {
3008
+ // Rebuilt once per source fingerprint: a stamp without provenance or
3009
+ // digest is stale until a fresh build of this source shows that the
3010
+ // checkout's build script cannot write them (legacyBuildFingerprint).
3011
+ return stamp.legacyBuildFingerprint !== fingerprint;
3012
+ }
3013
+ // An output edited after the build no longer matches its digest.
3014
+ return stamp.sourceFingerprint !== fingerprint ||
3015
+ stamp.packageDigest !==
3016
+ await (0, localDevPackage_js_1.computePackageContentDigest)(localPackagePath);
3017
+ }
2331
3018
  const sourceNewest = await getNewestMtimeMs(sourceRoot);
2332
3019
  const outputMtime = outputPackageStat.mtime?.getTime() ?? 0;
2333
3020
  return sourceNewest > outputMtime;
2334
3021
  }
2335
- async function filesHaveSameText(leftPath, rightPath) {
2336
- const [left, right] = await Promise.all([
2337
- readTextIfExists(leftPath),
2338
- readTextIfExists(rightPath),
2339
- ]);
2340
- return left !== null && right !== null && left === right;
3022
+ /**
3023
+ * After a build, notes in its stamp when the checkout's build script
3024
+ * predates build provenance (the fresh stamp has none), together with the
3025
+ * source fingerprint that build started from, so sync stops rebuilding that
3026
+ * source on every run. Builds that record provenance are left alone.
3027
+ */
3028
+ async function markLegacyLoomBuild(localPackagePath, fingerprintBeforeBuild) {
3029
+ const stamp = await (0, localDevPackage_js_1.readLoomBuildStamp)(localPackagePath);
3030
+ if (!stamp || (0, localDevPackage_js_1.hasLoomBuildProvenance)(stamp))
3031
+ return;
3032
+ const { version: _version, ...fields } = stamp;
3033
+ await (0, promises_1.writeFile)((0, node_path_1.join)(localPackagePath, localDevPackage_js_1.LOOM_BUILD_STAMP_FILE), (0, localDevPackage_js_1.formatLoomBuildStamp)({
3034
+ ...fields,
3035
+ legacyBuildFingerprint: fingerprintBeforeBuild,
3036
+ }), "utf8");
2341
3037
  }
2342
- async function isInstalledLocalLoomPackageStale(cwd, localPackagePath) {
2343
- const installedPath = (0, node_path_1.join)(cwd, "node_modules", exports.LOOM_DEPENDENCY);
2344
- if (!await exists((0, node_path_1.join)(installedPath, "package.json"))) {
2345
- return true;
2346
- }
2347
- const sentinelFiles = [
2348
- "package.json",
2349
- (0, node_path_1.join)("script", "bin", "loom.js"),
2350
- (0, node_path_1.join)("script", "src", "cli", "mod.js"),
2351
- ];
2352
- for (const relativePath of sentinelFiles) {
2353
- if (!await filesHaveSameText((0, node_path_1.join)(localPackagePath, relativePath), (0, node_path_1.join)(installedPath, relativePath))) {
2354
- return true;
2355
- }
2356
- }
2357
- return false;
3038
+ /**
3039
+ * Describes how the consumer's installed Loom differs from the local build,
3040
+ * by file list and content, or returns null when they match. Version numbers
3041
+ * alone cannot tell rebuilds of the same version apart.
3042
+ */
3043
+ function findInstalledLocalLoomDifference(cwd, localPackagePath) {
3044
+ return (0, localDevPackage_js_1.findPackageTreeDifference)(localPackagePath, (0, node_path_1.join)(cwd, "node_modules", exports.LOOM_DEPENDENCY));
2358
3045
  }
2359
3046
  async function runCommandOrThrow(commandRunner, command, args, options) {
2360
3047
  const result = await commandRunner(command, args, options);
@@ -2423,6 +3110,10 @@ async function readLocalDevState(cwd) {
2423
3110
  if (state.version !== 1 || state.dependency !== exports.LOOM_DEPENDENCY) {
2424
3111
  return null;
2425
3112
  }
3113
+ // Retired: whole-file package.json snapshots are never written back.
3114
+ const retired = state;
3115
+ delete retired.packageJsonBeforeOverride;
3116
+ delete retired.packageJsonWithOverride;
2426
3117
  return state;
2427
3118
  }
2428
3119
  catch {
@@ -2476,15 +3167,17 @@ function compareParsedVersions(left, right) {
2476
3167
  }
2477
3168
  return left.prerelease.localeCompare(right.prerelease);
2478
3169
  }
2479
- async function findPublishedLoomPublicationForCommit(sourceRoot, sourceCommit, commandRunner, env, preferredSpec) {
3170
+ async function findPublishedLoomPublicationForCommit(sourceRoot, sourceCommit, commandRunner, env, preferredSpec,
3171
+ /** Names the commit in refusals, such as "Loom commit abc, which built X,". */
3172
+ subject) {
2480
3173
  const publication = await resolveLoomCommitPublication(sourceRoot, sourceCommit, commandRunner, env, preferredSpec);
2481
3174
  switch (publication.status) {
2482
3175
  case "published":
2483
3176
  return publication;
2484
3177
  case "not-on-origin-main":
2485
- 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\`.`);
3178
+ 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\`.`);
2486
3179
  case "no-release-tag":
2487
- 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\`.`);
3180
+ 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\`.`);
2488
3181
  }
2489
3182
  }
2490
3183
  function parseSemverTags(tags) {
@@ -2503,7 +3196,7 @@ async function getPackageRelevantChangedPaths(sourceRoot, fromRef, toRef, comman
2503
3196
  "--name-only",
2504
3197
  `${fromRef}..${toRef}`,
2505
3198
  "--",
2506
- ...LOOM_PACKAGE_RELEVANT_PATHS,
3199
+ ...localDevPackage_js_1.LOOM_PACKAGE_RELEVANT_PATHS,
2507
3200
  ], env);
2508
3201
  return changedPaths
2509
3202
  ?.split("\n")
@@ -2554,127 +3247,512 @@ async function resolveLoomCommitPublication(sourceRoot, sourceCommit, commandRun
2554
3247
  }
2555
3248
  return { status: "no-release-tag" };
2556
3249
  }
2557
- async function syncLocalDevPackage(cwd, options = {}) {
2558
- const manifest = await readManifestIfExists(cwd);
2559
- const tooling = await (0, projectTooling_js_1.detectProjectTooling)(cwd, manifest?.project?.tooling);
2560
- const denoMode = usesDenoTooling(tooling);
2561
- const workspacePath = (0, node_path_1.join)(cwd, "pnpm-workspace.yaml");
2562
- const workspaceText = await readTextIfExists(workspacePath);
2563
- const overrideSpec = getManagedDevOverrideSpec(workspaceText);
2564
- const denoConfig = denoMode
2565
- ? await getDenoConfigForLinks(cwd, tooling)
2566
- : null;
2567
- const denoLink = denoConfig
2568
- ? await findLocalLoomDenoLink(cwd, await (0, projectTooling_js_1.readDenoLinks)(cwd, denoConfig))
2569
- : null;
2570
- if (!overrideSpec && !denoLink) {
2571
- if (options.requireActive) {
2572
- throw new Error("No managed Loom local-dev override is active. Run `loom dev local /path/to/loom` first.");
2573
- }
2574
- return {
2575
- buildRan: false,
2576
- changed: false,
2577
- notes: [],
2578
- packageRefreshRan: false,
2579
- ranCommands: [],
2580
- };
2581
- }
2582
- const { packageJson } = await readProjectPackageJson(cwd);
2583
- if (!denoMode)
2584
- await ensurePnpmProject(cwd, packageJson);
2585
- const commandRunner = options.commandRunner ?? defaultCommandRunner;
2586
- const env = options.env ?? node_process_1.default.env;
2587
- const localPackagePath = denoLink?.path ??
2588
- fileSpecToPath(cwd, overrideSpec);
2589
- const sourceRoot = await resolveLocalLoomSourceRoot(localPackagePath);
2590
- const configuredSpec = packageJson.dependencies?.[exports.LOOM_DEPENDENCY] ??
2591
- packageJson.devDependencies?.[exports.LOOM_DEPENDENCY];
2592
- const desiredLocalVersion = await readPackageVersion((0, node_path_1.join)(cwd, "node_modules", exports.LOOM_DEPENDENCY)) ?? versionFromDependencySpec(configuredSpec) ??
2593
- await readPackageVersion(localPackagePath);
2594
- const currentLocalVersion = await readPackageVersion(localPackagePath);
2595
- const buildEnv = desiredLocalVersion && !env.NPM_PACKAGE_VERSION
2596
- ? { ...env, NPM_PACKAGE_VERSION: desiredLocalVersion }
2597
- : env;
2598
- const ranCommands = [];
2599
- let buildRan = false;
2600
- if (options.force || denoMode && currentLocalVersion !== desiredLocalVersion ||
2601
- await isLocalLoomBuildStale(sourceRoot, localPackagePath)) {
2602
- if (!sourceRoot) {
2603
- throw new Error(`Could not find the Loom source checkout for ${localPackagePath}; cannot rebuild the local package.`);
2604
- }
2605
- await runCommandOrThrow(commandRunner, "deno", ["task", "build"], {
2606
- cwd: sourceRoot,
2607
- env: buildEnv,
2608
- stdio: "inherit",
2609
- });
2610
- ranCommands.push("deno task build");
2611
- buildRan = true;
2612
- }
2613
- const packageRefreshNeeded = buildRan ||
2614
- await isInstalledLocalLoomPackageStale(cwd, localPackagePath);
2615
- let packageRefreshRan = false;
2616
- if (options.force || packageRefreshNeeded) {
2617
- if (denoMode) {
2618
- await runCommandOrThrow(commandRunner, "deno", ["install"], {
2619
- cwd,
2620
- env,
2621
- stdio: "inherit",
2622
- });
2623
- ranCommands.push("deno install");
2624
- }
2625
- else {
2626
- const packageSpec = `${exports.LOOM_DEPENDENCY}@file:${localPackagePath}`;
2627
- await runCommandOrThrow(commandRunner, "pnpm", ["update", "--no-save", packageSpec], { cwd, env, stdio: "inherit" });
2628
- ranCommands.push(`pnpm update --no-save ${packageSpec}`);
2629
- await runCommandOrThrow(commandRunner, "pnpm", ["install"], {
2630
- cwd,
2631
- env,
2632
- stdio: "inherit",
2633
- });
2634
- ranCommands.push("pnpm install");
2635
- }
2636
- packageRefreshRan = true;
3250
+ async function readPackageJsonIfExists(cwd) {
3251
+ const text = await readTextIfExists((0, node_path_1.join)(cwd, "package.json"));
3252
+ if (text === null)
3253
+ return null;
3254
+ try {
3255
+ return JSON.parse(text);
2637
3256
  }
2638
- const currentWorkspaceText = await readTextIfExists(workspacePath);
2639
- const currentState = denoMode
2640
- ? await readLocalDevState(cwd)
2641
- : await getCurrentLocalDevState(cwd, currentWorkspaceText);
2642
- let state = null;
2643
- if (buildRan || packageRefreshRan || !currentState) {
2644
- state = await buildLocalDevState(localPackagePath, sourceRoot, commandRunner, env);
2645
- if (!denoMode) {
2646
- const stateUpdate = setManagedDevStateText(await readTextIfExists(workspacePath), overrideSpec, state);
2647
- if (stateUpdate.changed) {
2648
- await writeTextOrDeleteIfEmpty(workspacePath, stateUpdate.text);
2649
- }
2650
- }
3257
+ catch {
3258
+ return null;
2651
3259
  }
2652
- if (state ?? currentState) {
2653
- await writeLocalDevStateIfChanged(cwd, state ?? currentState);
3260
+ }
3261
+ /** Marks a loaded-package signature that could not be taken. */
3262
+ exports.UNKNOWN_PACKAGE_SIGNATURE = "unknown";
3263
+ /**
3264
+ * Signature of the installed Loom package when a command starts, taken when
3265
+ * the project is linked or a dev sync holds the lock (a `loom dev local`
3266
+ * running right now can replace the package). Unlinked projects with no
3267
+ * sync running skip the walk and yield {@link UNKNOWN_PACKAGE_SIGNATURE}, as
3268
+ * does a walk that fails: a project linked after this check is still
3269
+ * treated as refreshed when its sync had to wait for another one. Commands
3270
+ * a sync started return undefined, since they never sync themselves.
3271
+ */
3272
+ async function captureLoadedLocalLoomSignature(cwd, env) {
3273
+ if (env[LOOM_DEV_SYNC_ACTIVE_ENV] === "1")
3274
+ return undefined;
3275
+ const linked = await detectLocalDevLink(cwd).then((link) => link.active, () => false);
3276
+ if (!linked && !await exists((0, node_path_1.join)(cwd, exports.LOOM_LOCAL_DEV_LOCK_RELATIVE_PATH))) {
3277
+ return exports.UNKNOWN_PACKAGE_SIGNATURE;
2654
3278
  }
2655
- const notes = packageRefreshRan
2656
- ? [
2657
- `Local Loom package refreshed from ${localPackagePath}.`,
2658
- "If this command was using a stale installed Loom CLI, rerun it now.",
2659
- ]
2660
- : [`Local Loom package is already fresh: ${localPackagePath}`];
2661
- const recordedState = state ?? currentState;
2662
- if (recordedState?.sourceCommit) {
2663
- notes.push(`Recorded local Loom sync at commit ${recordedState.sourceCommit.slice(0, 12)}${recordedState.sourceDirty ? " with a dirty source tree" : ""}.`);
3279
+ return await (0, localDevPackage_js_1.computePackageTreeSignature)((0, node_path_1.join)(cwd, "node_modules", exports.LOOM_DEPENDENCY)).catch(() => exports.UNKNOWN_PACKAGE_SIGNATURE);
3280
+ }
3281
+ function formatPnpmOverrideNotAppliedMessage(override, pnpmVersion) {
3282
+ return `pnpm did not apply the Loom local-dev override in ${formatPnpmOverrideLocation(override.location)}: pnpm-lock.yaml does not record ${exports.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\`.`;
3283
+ }
3284
+ /** Whether deno.lock records a `links` entry for Loom. */
3285
+ async function denoLockLinksLoom(cwd) {
3286
+ const text = await readTextIfExists((0, node_path_1.join)(cwd, "deno.lock"));
3287
+ if (!text)
3288
+ return false;
3289
+ let lock;
3290
+ try {
3291
+ lock = JSON.parse(text);
2664
3292
  }
2665
- else if (sourceRoot) {
2666
- notes.push("Could not record a Loom git commit for this sync; `loom dev published` cannot prove whether unpublished Loom changes are required.");
3293
+ catch {
3294
+ // Unreadable: assume it may record one.
3295
+ return true;
2667
3296
  }
2668
- return {
2669
- buildRan,
2670
- changed: buildRan || packageRefreshRan,
2671
- localPackagePath,
2672
- notes,
2673
- packageRefreshRan,
2674
- ranCommands,
3297
+ const linkKeys = (scope) => scope && typeof scope === "object" &&
3298
+ scope.links &&
3299
+ typeof scope.links === "object"
3300
+ ? Object.keys(scope.links)
3301
+ : [];
3302
+ const members = lock.workspace?.members &&
3303
+ typeof lock.workspace.members === "object"
3304
+ ? Object.values(lock.workspace.members)
3305
+ : [];
3306
+ return [lock.workspace, ...members].flatMap(linkKeys).some((key) => key === exports.LOOM_DEPENDENCY || key.startsWith(`npm:${exports.LOOM_DEPENDENCY}@`) ||
3307
+ key.startsWith(`${exports.LOOM_DEPENDENCY}@`));
3308
+ }
3309
+ /**
3310
+ * Every Deno `links` entry that is, or may be, Loom's: its package is named
3311
+ * Loom, or its package is gone. A dangling entry may be Loom's whatever
3312
+ * identifies it (the path dev state recorded, a Loom link in deno.lock, or
3313
+ * nothing at all): node_modules can still hold what Deno copied from it,
3314
+ * and a broken link cannot ship anyway.
3315
+ */
3316
+ async function findLoomDenoLinks(cwd, denoConfig) {
3317
+ const links = [];
3318
+ for (const link of await (0, projectTooling_js_1.readDenoLinks)(cwd, denoConfig)) {
3319
+ const path = (0, node_path_1.resolve)(cwd, link);
3320
+ const dangling = !await exists((0, node_path_1.join)(path, "package.json"));
3321
+ if (dangling || await findLocalLoomDenoLink(cwd, [link])) {
3322
+ links.push({ dangling, link, path });
3323
+ }
3324
+ }
3325
+ return links;
3326
+ }
3327
+ /**
3328
+ * Local Loom overrides and links in the project's config: Loom overrides
3329
+ * with a local (`file:`/`link:`/`workspace:`) spec under any selector, in
3330
+ * package.json maps or pnpm-workspace.yaml (managed or hand-written), a local
3331
+ * Loom catalog entry, and Deno links to Loom, dangling ones included. Each
3332
+ * is described for messages.
3333
+ */
3334
+ async function findLocalLoomLinks(cwd) {
3335
+ const manifest = await readManifestIfExists(cwd);
3336
+ const tooling = await (0, projectTooling_js_1.detectProjectTooling)(cwd, manifest?.project?.tooling);
3337
+ const packageJson = await readPackageJsonIfExists(cwd) ?? {};
3338
+ const workspaceText = await readTextIfExists((0, node_path_1.join)(cwd, "pnpm-workspace.yaml"));
3339
+ const links = [];
3340
+ // Reported by the catalog check itself; still local Loom in use.
3341
+ const catalogLinks = [];
3342
+ for (const { field, location } of PACKAGE_JSON_OVERRIDE_LOCATIONS) {
3343
+ for (const [key, spec] of Object.entries(getPackageJsonOverrideMap(packageJson, field))) {
3344
+ if (overrideKeyTargetsLoom(key) && typeof spec === "string" &&
3345
+ isLocalPackageSpec(spec)) {
3346
+ links.push(`${formatPnpmOverrideLocation(location)}: ${spec}`);
3347
+ }
3348
+ }
3349
+ }
3350
+ const managedSpec = getManagedDevOverrideSpec(workspaceText);
3351
+ if (managedSpec)
3352
+ links.push(`pnpm-workspace.yaml: ${managedSpec}`);
3353
+ for (const { key, spec } of getUnmanagedPnpmWorkspaceLoomOverrides(workspaceText)) {
3354
+ links.push(`pnpm-workspace.yaml overrides ${key}: ${spec}`);
3355
+ }
3356
+ const dependency = await resolveLoomDependencySpec(cwd, packageJson);
3357
+ if (dependency.catalogName && dependency.effective &&
3358
+ isLocalPackageSpec(dependency.effective)) {
3359
+ catalogLinks.push(`pnpm-workspace.yaml catalog ${dependency.catalogName}: ${dependency.effective}`);
3360
+ }
3361
+ if (usesDenoTooling(tooling)) {
3362
+ const denoConfig = await getDenoConfigForLinks(cwd, tooling);
3363
+ for (const { dangling, link } of await findLoomDenoLinks(cwd, denoConfig)) {
3364
+ links.push(`${denoConfig} links: ${link}${dangling ? " (its package is gone; it may be Loom's)" : ""}`);
3365
+ }
3366
+ }
3367
+ return {
3368
+ catalogLinks,
3369
+ denoMode: usesDenoTooling(tooling),
3370
+ links,
3371
+ packageJson,
3372
+ };
3373
+ }
3374
+ /**
3375
+ * The published Loom version a Deno project's node_modules copy came from,
3376
+ * when deno.lock proves it: the lock records no Loom link, resolves the
3377
+ * project's `npm:@gadicc/loom@<pin>` specifier to a version installed from
3378
+ * the registry (its npm entry carries an integrity hash, which a linked
3379
+ * package's entry lacks), and node_modules holds that version. Null
3380
+ * otherwise, including without a deno.lock.
3381
+ */
3382
+ async function findInstalledDenoRegistryLoomVersion(cwd, packageJson) {
3383
+ const text = await readTextIfExists((0, node_path_1.join)(cwd, "deno.lock"));
3384
+ if (!text || await denoLockLinksLoom(cwd))
3385
+ return null;
3386
+ let lock;
3387
+ try {
3388
+ lock = JSON.parse(text);
3389
+ }
3390
+ catch {
3391
+ return null;
3392
+ }
3393
+ const manifest = await readManifestIfExists(cwd);
3394
+ const tooling = await (0, projectTooling_js_1.detectProjectTooling)(cwd, manifest?.project?.tooling);
3395
+ const denoConfig = await getDenoConfigForLinks(cwd, tooling);
3396
+ const imports = (0, projectTooling_js_1.parseJsonc)(await readTextIfExists((0, node_path_1.join)(cwd, denoConfig)) ?? "{}", denoConfig).imports ?? {};
3397
+ const pinned = [
3398
+ imports[exports.LOOM_DEPENDENCY],
3399
+ packageJson.dependencies?.[exports.LOOM_DEPENDENCY] &&
3400
+ `npm:${exports.LOOM_DEPENDENCY}@${packageJson.dependencies[exports.LOOM_DEPENDENCY]}`,
3401
+ ].find((spec) => typeof spec === "string" && spec.startsWith(`npm:${exports.LOOM_DEPENDENCY}@`) &&
3402
+ lock.specifiers?.[spec] !== undefined);
3403
+ const resolved = pinned ? lock.specifiers[pinned] : undefined;
3404
+ if (!resolved)
3405
+ return null;
3406
+ const entry = lock.npm?.[`${exports.LOOM_DEPENDENCY}@${resolved}`];
3407
+ if (typeof entry?.integrity !== "string")
3408
+ return null;
3409
+ const version = resolved.replace(/_.*$/, "");
3410
+ return await readPackageVersion((0, node_path_1.join)(cwd, "node_modules", exports.LOOM_DEPENDENCY)) ===
3411
+ version
3412
+ ? version
3413
+ : null;
3414
+ }
3415
+ /**
3416
+ * Why this project may still run local Loom code; empty only when it
3417
+ * provably does not. One predicate decides this for `loom dev published`
3418
+ * (whether to drop the sync record) and `loom check` (whether that record
3419
+ * is stale):
3420
+ * - any local Loom override, catalog entry or Deno link
3421
+ * ({@link findLocalLoomLinks});
3422
+ * - pnpm-lock.yaml resolving Loom locally, or deno.lock recording a Loom link;
3423
+ * - an installed node_modules/@gadicc/loom that is not provably the
3424
+ * published package: for pnpm, unless it is pnpm's registry store entry
3425
+ * ({@link findInstalledRegistryLoomVersion}); for Deno, any copy, since a
3426
+ * copied link looks like a registry install. A missing one is not
3427
+ * installed.
3428
+ * Errors while finding out count as in use. Loom reads overrides,
3429
+ * lockfiles and node_modules from this directory only, so a member of an
3430
+ * enclosing pnpm workspace, whose root holds them, always counts as in use.
3431
+ */
3432
+ async function findLocalLoomUse(cwd) {
3433
+ try {
3434
+ const { catalogLinks, denoMode, links, packageJson } = await findLocalLoomLinks(cwd);
3435
+ const uses = [...links, ...catalogLinks].map((reason) => ({
3436
+ kind: "link",
3437
+ reason,
3438
+ }));
3439
+ if (!denoMode && !await exists((0, node_path_1.join)(cwd, "pnpm-workspace.yaml"))) {
3440
+ for (let parent = (0, node_path_1.dirname)((0, node_path_1.resolve)(cwd)); parent !== (0, node_path_1.dirname)(parent); parent = (0, node_path_1.dirname)(parent)) {
3441
+ if (await exists((0, node_path_1.join)(parent, "pnpm-workspace.yaml"))) {
3442
+ uses.push({
3443
+ kind: "workspace",
3444
+ reason: `this project is in the pnpm workspace at ${parent}, whose overrides and lockfile Loom does not read`,
3445
+ });
3446
+ break;
3447
+ }
3448
+ }
3449
+ }
3450
+ const lockfileText = await readTextIfExists((0, node_path_1.join)(cwd, "pnpm-lock.yaml"));
3451
+ const lockfileResolution = lockfileText
3452
+ ? getLocalLoomLockfileResolution(lockfileText)
3453
+ : null;
3454
+ if (lockfileResolution) {
3455
+ uses.push({
3456
+ kind: "lockfile",
3457
+ reason: `pnpm-lock.yaml resolves Loom to ${lockfileResolution}`,
3458
+ });
3459
+ }
3460
+ if (await denoLockLinksLoom(cwd)) {
3461
+ uses.push({
3462
+ kind: "lockfile",
3463
+ reason: "deno.lock records a link for Loom",
3464
+ });
3465
+ }
3466
+ if (await exists((0, node_path_1.join)(cwd, "node_modules", exports.LOOM_DEPENDENCY, "package.json"))) {
3467
+ const proven = denoMode
3468
+ ? await findInstalledDenoRegistryLoomVersion(cwd, packageJson)
3469
+ : await findInstalledRegistryLoomVersion(cwd, lockfileText, (await readLocalDevState(cwd))?.localPackagePath);
3470
+ if (!proven) {
3471
+ uses.push({
3472
+ kind: "installed",
3473
+ reason: "node_modules/@gadicc/loom is not provably the published package",
3474
+ });
3475
+ }
3476
+ }
3477
+ return uses;
3478
+ }
3479
+ catch (error) {
3480
+ return [{
3481
+ kind: "error",
3482
+ reason: `Loom could not tell whether local Loom is in use: ${error.message}`,
3483
+ }];
3484
+ }
3485
+ }
3486
+ /** The project's active local Loom link, read from its current files. */
3487
+ async function detectLocalDevLink(cwd) {
3488
+ const manifest = await readManifestIfExists(cwd);
3489
+ const tooling = await (0, projectTooling_js_1.detectProjectTooling)(cwd, manifest?.project?.tooling);
3490
+ const denoMode = usesDenoTooling(tooling);
3491
+ const activePnpmOverride = denoMode ? null : getActivePnpmLocalDevOverride(await readTextIfExists((0, node_path_1.join)(cwd, "pnpm-workspace.yaml")), await readPackageJsonIfExists(cwd) ?? {});
3492
+ const denoConfig = denoMode
3493
+ ? await getDenoConfigForLinks(cwd, tooling)
3494
+ : null;
3495
+ const denoLink = denoConfig
3496
+ ? await findLocalLoomDenoLink(cwd, await (0, projectTooling_js_1.readDenoLinks)(cwd, denoConfig))
3497
+ : null;
3498
+ return {
3499
+ active: activePnpmOverride !== null || denoLink !== null,
3500
+ activePnpmOverride,
3501
+ denoLink,
3502
+ denoMode,
3503
+ };
3504
+ }
3505
+ const NO_LOCAL_DEV_LINK_MESSAGE = "No managed Loom local-dev override is active. Run `loom dev local /path/to/loom` first.";
3506
+ async function syncLocalDevPackage(cwd, options = {}) {
3507
+ const workspacePath = (0, node_path_1.join)(cwd, "pnpm-workspace.yaml");
3508
+ const inactive = (notes = []) => ({
3509
+ buildRan: false,
3510
+ changed: false,
3511
+ notes,
3512
+ packageRefreshRan: false,
3513
+ ranCommands: [],
3514
+ });
3515
+ if (!(await detectLocalDevLink(cwd)).active) {
3516
+ if (options.requireActive)
3517
+ throw new Error(NO_LOCAL_DEV_LINK_MESSAGE);
3518
+ return inactive();
3519
+ }
3520
+ const env = options.env ?? node_process_1.default.env;
3521
+ if (env[LOOM_DEV_SYNC_ACTIVE_ENV] === "1") {
3522
+ // A command started by a running sync (a package lifecycle script, say)
3523
+ // must not wait for the lock its own parent holds.
3524
+ return inactive([
3525
+ "Skipped the local Loom sync inside a running Loom dev sync.",
3526
+ ]);
3527
+ }
3528
+ return await (0, localDevLock_js_1.withLocalDevLock)((0, node_path_1.join)(cwd, exports.LOOM_LOCAL_DEV_LOCK_RELATIVE_PATH), async (lock) => {
3529
+ // Re-read under the lock: while this command waited, the user may have
3530
+ // switched back to the published package or linked another checkout.
3531
+ const { activePnpmOverride, denoLink, denoMode } = await detectLocalDevLink(cwd);
3532
+ if (!activePnpmOverride && !denoLink) {
3533
+ if (options.requireActive)
3534
+ throw new Error(NO_LOCAL_DEV_LINK_MESSAGE);
3535
+ return inactive([
3536
+ "The local Loom link was removed while this command waited.",
3537
+ ]);
3538
+ }
3539
+ const { packageJson } = await readProjectPackageJson(cwd);
3540
+ if (!denoMode)
3541
+ await ensurePnpmProject(cwd, packageJson);
3542
+ const commandRunner = options.commandRunner ?? defaultCommandRunner;
3543
+ const childEnv = { ...env, [LOOM_DEV_SYNC_ACTIVE_ENV]: "1" };
3544
+ const childStdio = options.commandOutput === "stderr"
3545
+ ? "inherit-stderr"
3546
+ : "inherit";
3547
+ const notes = [];
3548
+ let pnpmVersion = null;
3549
+ // Whether this sync already changed the project, for lost-lock errors.
3550
+ let changesMade = false;
3551
+ let pnpmOverride = activePnpmOverride;
3552
+ if (pnpmOverride) {
3553
+ // Older Loom versions always wrote pnpm-workspace.yaml, which pnpm 10
3554
+ // ignores when package.json has overrides; move it where pnpm reads it.
3555
+ const placement = await resolvePnpmLocalDevOverrideLocation(cwd, packageJson, commandRunner, env);
3556
+ if (placement.conflict)
3557
+ throw new Error(placement.conflict);
3558
+ pnpmVersion = placement.pnpmVersion;
3559
+ await lock.assertHeld(false);
3560
+ const movedFiles = await placePnpmLocalDevOverride(cwd, pnpmOverride.spec, placement.location);
3561
+ if (movedFiles.length) {
3562
+ changesMade = true;
3563
+ notes.push(`Moved the Loom local-dev override to ${formatPnpmOverrideLocation(placement.location)} (updated ${movedFiles.join(", ")}).`, ...placement.notes);
3564
+ }
3565
+ pnpmOverride = {
3566
+ location: placement.location,
3567
+ spec: pnpmOverride.spec,
3568
+ };
3569
+ }
3570
+ const localPackagePath = denoLink?.path ??
3571
+ fileSpecToPath(cwd, pnpmOverride.spec);
3572
+ const sourceRoot = await resolveLocalLoomSourceRoot(localPackagePath);
3573
+ const configuredSpec = (await resolveLoomDependencySpec(cwd, packageJson, { includeDev: true })).effective;
3574
+ const desiredLocalVersion = await readPackageVersion((0, node_path_1.join)(cwd, "node_modules", exports.LOOM_DEPENDENCY)) ?? versionFromDependencySpec(configuredSpec) ??
3575
+ await readPackageVersion(localPackagePath);
3576
+ const currentLocalVersion = await readPackageVersion(localPackagePath);
3577
+ const buildEnv = desiredLocalVersion && !env.NPM_PACKAGE_VERSION
3578
+ ? { ...childEnv, NPM_PACKAGE_VERSION: desiredLocalVersion }
3579
+ : childEnv;
3580
+ const ranCommands = [];
3581
+ let buildRan = false;
3582
+ if (options.force ||
3583
+ denoMode && currentLocalVersion !== desiredLocalVersion ||
3584
+ await isLocalLoomBuildStale(sourceRoot, localPackagePath)) {
3585
+ if (!sourceRoot) {
3586
+ throw new Error(`Could not find the Loom source checkout for ${localPackagePath}; cannot rebuild the local package.`);
3587
+ }
3588
+ // Run in the Loom checkout with its own deno.json (and so its own
3589
+ // deno.lock). Deno discovers config and lockfile from the working
3590
+ // directory, so a build resolved from the consumer would write a
3591
+ // deno.lock listing the consumer's package.json into its root.
3592
+ await lock.assertHeld(changesMade);
3593
+ const fingerprintBeforeBuild = await (0, localDevPackage_js_1.computeLoomSourceFingerprint)(sourceRoot);
3594
+ await runCommandOrThrow(commandRunner, "deno", ["task", "--config", (0, node_path_1.join)(sourceRoot, "deno.json"), "build"], { cwd: sourceRoot, env: buildEnv, stdio: childStdio });
3595
+ ranCommands.push("deno task build");
3596
+ buildRan = true;
3597
+ changesMade = true;
3598
+ await markLegacyLoomBuild(localPackagePath, fingerprintBeforeBuild);
3599
+ }
3600
+ const lockfilePath = (0, node_path_1.join)(cwd, "pnpm-lock.yaml");
3601
+ const lockfileBefore = pnpmOverride
3602
+ ? await readTextIfExists(lockfilePath)
3603
+ : null;
3604
+ // A lockfile that does not record the override means pnpm has not linked
3605
+ // the local package yet (for example right after `loom dev local`).
3606
+ const overridePending = pnpmOverride !== null &&
3607
+ lockfileBefore !== null &&
3608
+ !lockfileAppliesLocalDevOverride(lockfileBefore, pnpmOverride.spec);
3609
+ const importerBefore = overridePending
3610
+ ? (0, localDevPackage_js_1.getLockfileRootImporterDependency)(lockfileBefore, exports.LOOM_DEPENDENCY)
3611
+ : null;
3612
+ if (importerBefore?.version && isLocalPackageSpec(importerBefore.version) &&
3613
+ !isLocalPackageSpec(importerBefore.specifier ?? "")) {
3614
+ // Earlier Loom versions linked with `pnpm update --no-save`, which also
3615
+ // re-resolved Loom's dependencies; this sync cannot tell which of those
3616
+ // lockfile changes were intended.
3617
+ 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`.");
3618
+ }
3619
+ const packageRefreshNeeded = buildRan || overridePending ||
3620
+ await findInstalledLocalLoomDifference(cwd, localPackagePath) !== null;
3621
+ let packageRefreshRan = false;
3622
+ const warnings = [];
3623
+ if (options.force || packageRefreshNeeded) {
3624
+ await lock.assertHeld(changesMade);
3625
+ if (denoMode) {
3626
+ await runCommandOrThrow(commandRunner, "deno", ["install"], {
3627
+ cwd,
3628
+ env: childEnv,
3629
+ stdio: childStdio,
3630
+ });
3631
+ ranCommands.push("deno install");
3632
+ }
3633
+ else {
3634
+ // A plain install applies the override and re-imports the local
3635
+ // directory package while reusing every other locked version.
3636
+ // `pnpm update` would re-resolve Loom's dependency subtree instead.
3637
+ await runCommandOrThrow(commandRunner, "pnpm", ["install", "--no-frozen-lockfile"], { cwd, env: childEnv, stdio: childStdio });
3638
+ ranCommands.push("pnpm install --no-frozen-lockfile");
3639
+ const lockfileAfter = await readTextIfExists(lockfilePath);
3640
+ if (lockfileAfter !== null &&
3641
+ !lockfileAppliesLocalDevOverride(lockfileAfter, pnpmOverride.spec)) {
3642
+ throw new Error(formatPnpmOverrideNotAppliedMessage(pnpmOverride, pnpmVersion));
3643
+ }
3644
+ if (lockfileBefore !== null && lockfileAfter !== null) {
3645
+ const duplicates = (0, localDevPackage_js_1.findNewPeerVariantDuplicates)(lockfileBefore, lockfileAfter);
3646
+ if (duplicates.length) {
3647
+ 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>\`.`);
3648
+ }
3649
+ }
3650
+ const remainingDifference = await findInstalledLocalLoomDifference(cwd, localPackagePath);
3651
+ if (remainingDifference) {
3652
+ warnings.push(`node_modules/${exports.LOOM_DEPENDENCY} still differs from ${localPackagePath} after pnpm install (${remainingDifference}).`);
3653
+ }
3654
+ }
3655
+ packageRefreshRan = true;
3656
+ }
3657
+ await lock.assertHeld(changesMade || packageRefreshRan);
3658
+ const currentWorkspaceText = await readTextIfExists(workspacePath);
3659
+ const currentState = denoMode
3660
+ ? await readLocalDevState(cwd)
3661
+ : await getCurrentLocalDevState(cwd, currentWorkspaceText);
3662
+ let state = null;
3663
+ if (buildRan || packageRefreshRan || !currentState) {
3664
+ state = await buildLocalDevState(localPackagePath, sourceRoot, commandRunner, env);
3665
+ // Keep which package.json maps Loom created across syncs.
3666
+ const previous = await readLocalDevState(cwd);
3667
+ if (previous?.createdPackageJsonMaps !== undefined) {
3668
+ state.createdPackageJsonMaps = previous.createdPackageJsonMaps;
3669
+ }
3670
+ if (pnpmOverride?.location === "pnpm-workspace.yaml") {
3671
+ const stateUpdate = setManagedDevStateText(await readTextIfExists(workspacePath), pnpmOverride.spec, state);
3672
+ if (stateUpdate.changed) {
3673
+ await writeTextOrDeleteIfEmpty(workspacePath, stateUpdate.text);
3674
+ }
3675
+ }
3676
+ }
3677
+ if (state ?? currentState) {
3678
+ await writeLocalDevStateIfChanged(cwd, state ?? currentState);
3679
+ }
3680
+ // Another process may have replaced the package this process loaded,
3681
+ // while it waited for the lock or just before it took it; its
3682
+ // in-process Loom code is then stale.
3683
+ let refreshedElsewhere = false;
3684
+ if (!buildRan && !packageRefreshRan &&
3685
+ options.loadedPackageSignature !== undefined) {
3686
+ const current = options.loadedPackageSignature ===
3687
+ exports.UNKNOWN_PACKAGE_SIGNATURE
3688
+ ? exports.UNKNOWN_PACKAGE_SIGNATURE
3689
+ : await (0, localDevPackage_js_1.computePackageTreeSignature)((0, node_path_1.join)(cwd, "node_modules", exports.LOOM_DEPENDENCY)).catch(() => exports.UNKNOWN_PACKAGE_SIGNATURE);
3690
+ // Without both signatures, only a sync this one waited for is
3691
+ // evidence of a replacement; assume one then rather than run code
3692
+ // that may be stale.
3693
+ refreshedElsewhere = current === exports.UNKNOWN_PACKAGE_SIGNATURE
3694
+ ? lock.waited
3695
+ : current !== options.loadedPackageSignature;
3696
+ }
3697
+ notes.push(packageRefreshRan
3698
+ ? `Local Loom package refreshed from ${localPackagePath}.`
3699
+ : refreshedElsewhere
3700
+ ? `Another Loom command refreshed the local Loom package from ${localPackagePath} after this one started.`
3701
+ : `Local Loom package is already fresh: ${localPackagePath}`, ...warnings.map((warning) => `Warning: ${warning}`));
3702
+ const recordedState = state ?? currentState;
3703
+ if (recordedState?.sourceCommit) {
3704
+ notes.push(`Recorded local Loom sync at commit ${recordedState.sourceCommit.slice(0, 12)}${recordedState.sourceDirty ? " with a dirty source tree" : ""}.`);
3705
+ }
3706
+ // What `loom dev published` will check is the build's own stamp.
3707
+ const stamp = sourceRoot
3708
+ ? await (0, localDevPackage_js_1.readLoomBuildStamp)(localPackagePath)
3709
+ : null;
3710
+ if (stamp?.legacyBuildFingerprint && !(0, localDevPackage_js_1.hasLoomBuildProvenance)(stamp)) {
3711
+ 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.`);
3712
+ }
3713
+ else if (sourceRoot && (!stamp || !(0, localDevPackage_js_1.hasLoomBuildProvenance)(stamp))) {
3714
+ 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\`.`);
3715
+ }
3716
+ else if (stamp && !stamp.sourceCommit) {
3717
+ 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\`.`);
3718
+ }
3719
+ else if (stamp && stamp.sourceDirty !== false) {
3720
+ 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\`.`);
3721
+ }
3722
+ return {
3723
+ buildRan,
3724
+ changed: buildRan || packageRefreshRan || refreshedElsewhere,
3725
+ localPackagePath,
3726
+ notes,
3727
+ packageRefreshRan,
3728
+ ranCommands,
3729
+ };
3730
+ }, localDevLockOptions(options));
3731
+ }
3732
+ function localDevLockOptions(options) {
3733
+ return {
3734
+ ...options.lock,
3735
+ onWait: (holder) => options.onLockWait?.(`Waiting for another Loom dev sync (${holder
3736
+ ? `process ${holder.pid} on ${holder.hostname}`
3737
+ : "unknown process"}) to finish.`),
2675
3738
  };
2676
3739
  }
2677
- async function useLocalDevPackage(cwd, inputPath) {
3740
+ /**
3741
+ * Runs a local-dev config change under the project's sync lock, so it never
3742
+ * interleaves with a sync that reads and rewrites the same files. Commands a
3743
+ * sync started (LOOM_DEV_SYNC_ACTIVE) run without it to avoid waiting on
3744
+ * their own parent.
3745
+ */
3746
+ async function withProjectLocalDevLock(cwd, options, run) {
3747
+ const env = options.env ?? node_process_1.default.env;
3748
+ if (env[LOOM_DEV_SYNC_ACTIVE_ENV] === "1")
3749
+ return await run();
3750
+ return await (0, localDevLock_js_1.withLocalDevLock)((0, node_path_1.join)(cwd, exports.LOOM_LOCAL_DEV_LOCK_RELATIVE_PATH), run, localDevLockOptions(options));
3751
+ }
3752
+ async function useLocalDevPackage(cwd, inputPath, options = {}) {
3753
+ return await withProjectLocalDevLock(cwd, options, () => useLocalDevPackageLocked(cwd, inputPath, options));
3754
+ }
3755
+ async function useLocalDevPackageLocked(cwd, inputPath, options) {
2678
3756
  const { packageJson } = await readProjectPackageJson(cwd);
2679
3757
  const manifest = await readManifestIfExists(cwd);
2680
3758
  const tooling = await (0, projectTooling_js_1.detectProjectTooling)(cwd, manifest?.project?.tooling);
@@ -2687,8 +3765,23 @@ async function useLocalDevPackage(cwd, inputPath) {
2687
3765
  const denoConfig = await getDenoConfigForLinks(cwd, tooling);
2688
3766
  const relativeLocalPackagePath = (0, node_path_1.relative)(cwd, localPackagePath)
2689
3767
  .replaceAll("\\", "/");
3768
+ // A relink replaces the previous Loom link, found by its package name or,
3769
+ // when that package is gone, by the path dev state recorded for it.
3770
+ // Otherwise both stay linked and `loom dev published` removes only one.
3771
+ const recorded = await readLocalDevState(cwd);
3772
+ const previousLinks = [];
3773
+ for (const link of await (0, projectTooling_js_1.readDenoLinks)(cwd, denoConfig)) {
3774
+ if (link === relativeLocalPackagePath)
3775
+ continue;
3776
+ if (await findLocalLoomDenoLink(cwd, [link]) ||
3777
+ (recorded &&
3778
+ (0, node_path_1.resolve)(cwd, link) === (0, node_path_1.resolve)(cwd, recorded.localPackagePath))) {
3779
+ previousLinks.push(link);
3780
+ }
3781
+ }
2690
3782
  const update = await (0, projectTooling_js_1.mutateDenoLinks)(cwd, denoConfig, {
2691
3783
  add: relativeLocalPackagePath,
3784
+ remove: previousLinks,
2692
3785
  });
2693
3786
  const state = {
2694
3787
  dependency: exports.LOOM_DEPENDENCY,
@@ -2712,26 +3805,216 @@ async function useLocalDevPackage(cwd, inputPath) {
2712
3805
  }
2713
3806
  await ensurePnpmProject(cwd, packageJson);
2714
3807
  const overrideSpec = `file:${localPackagePath}`;
2715
- const workspacePath = (0, node_path_1.join)(cwd, "pnpm-workspace.yaml");
2716
- const update = ensurePnpmWorkspaceLocalDevText(await readTextIfExists(workspacePath), overrideSpec);
2717
- if (update.conflict) {
2718
- throw new Error(update.conflict);
2719
- }
2720
- const changedFiles = [];
2721
- if (update.changed) {
2722
- await writeTextOrDeleteIfEmpty(workspacePath, update.text);
2723
- changedFiles.push("pnpm-workspace.yaml");
2724
- }
3808
+ const loomDependency = await resolveLoomDependencySpec(cwd, packageJson);
3809
+ const restoreSpec = loomDependency.catalogName
3810
+ ? `${loomDependency.effective ?? publishedSpec} (from the pnpm-workspace.yaml catalog)`
3811
+ : publishedSpec;
3812
+ const placement = await resolvePnpmLocalDevOverrideLocation(cwd, packageJson, options.commandRunner ?? defaultCommandRunner, options.env ?? node_process_1.default.env);
3813
+ if (placement.conflict) {
3814
+ throw new Error(placement.conflict);
3815
+ }
3816
+ const changedFiles = await placePnpmLocalDevOverride(cwd, overrideSpec, placement.location);
2725
3817
  return {
2726
3818
  changedFiles,
2727
3819
  notes: [
2728
- `Local Loom dev override is active: ${overrideSpec}`,
3820
+ `Local Loom dev override is active in ${formatPnpmOverrideLocation(placement.location)}: ${overrideSpec}`,
3821
+ ...placement.notes,
2729
3822
  "Run `loom dev sync` to rebuild the local Loom package and refresh this project's pnpm install when needed.",
2730
- `Before committing or shipping a published build, run \`loom dev published\`, then \`pnpm update --no-save ${exports.LOOM_DEPENDENCY}@${publishedSpec}\`, and then \`pnpm install\`.`,
3823
+ `Before committing or shipping a published build, run \`loom dev published\`, then \`pnpm install\` to restore ${exports.LOOM_DEPENDENCY}@${restoreSpec}.`,
2731
3824
  ],
2732
3825
  };
2733
3826
  }
3827
+ /** Turns a `file:` or `link:` spec into the absolute directory it names. */
3828
+ function localSpecToPath(cwd, spec) {
3829
+ const value = spec.replace(/^(?:file|link):/, "");
3830
+ if (value.startsWith("//"))
3831
+ return new URL(`file:${value}`).pathname;
3832
+ return (0, node_path_1.resolve)(cwd, value);
3833
+ }
3834
+ /** The local spec pnpm-lock.yaml resolves Loom to, if it is local. */
3835
+ function getLockfileLocalLoomSpec(lockfileText) {
3836
+ if (!lockfileText)
3837
+ return null;
3838
+ const version = (0, localDevPackage_js_1.getLockfileRootImporterDependency)(lockfileText, exports.LOOM_DEPENDENCY)?.version?.replace(/\(.+$/, "");
3839
+ if (version !== undefined) {
3840
+ return isLocalPackageSpec(version) ? version : null;
3841
+ }
3842
+ return getLocalLoomLockfileResolution(lockfileText);
3843
+ }
3844
+ /**
3845
+ * The published Loom version pnpm has installed, when nothing local is
3846
+ * provably installed:
3847
+ * - pnpm-lock.yaml and pnpm's record of node_modules
3848
+ * (`node_modules/.pnpm/lock.yaml`) resolve Loom to the same registry
3849
+ * version, and the installed package has that version;
3850
+ * - `node_modules/@gadicc/loom` resolves into pnpm's virtual store entry for
3851
+ * that registry version, not a `file+`/`link+` entry. pnpm re-points it
3852
+ * before it writes either lockfile, so an interrupted install of a local
3853
+ * build (which carries the registry version) fails this check;
3854
+ * - when `localBuild` exists, the installed copy differs from it.
3855
+ * Null whenever any of that is uncertain, for example with
3856
+ * `node-linker=hoisted`, `enableGlobalVirtualStore` or a custom
3857
+ * `virtual-store-dir`, where no `node_modules/.pnpm` entry tells them apart.
3858
+ */
3859
+ async function findInstalledRegistryLoomVersion(cwd, lockfileText, localBuild) {
3860
+ const resolvedVersion = (text) => text
3861
+ ? (0, localDevPackage_js_1.getLockfileRootImporterDependency)(text, exports.LOOM_DEPENDENCY)?.version
3862
+ ?.replace(/\(.+$/, "") ?? null
3863
+ : null;
3864
+ const version = resolvedVersion(lockfileText);
3865
+ if (!version || isLocalPackageSpec(version))
3866
+ return null;
3867
+ const installedLockfile = await readTextIfExists((0, node_path_1.join)(cwd, "node_modules", ".pnpm", "lock.yaml"));
3868
+ if (resolvedVersion(installedLockfile) !== version)
3869
+ return null;
3870
+ const installedPath = (0, node_path_1.join)(cwd, "node_modules", exports.LOOM_DEPENDENCY);
3871
+ if (await readPackageVersion(installedPath) !== version)
3872
+ return null;
3873
+ const [store, installed] = await Promise.all([
3874
+ (0, promises_1.realpath)((0, node_path_1.join)(cwd, "node_modules", ".pnpm")).catch(() => null),
3875
+ (0, promises_1.realpath)(installedPath).catch(() => null),
3876
+ ]);
3877
+ if (!store || !installed)
3878
+ return null;
3879
+ const entry = (0, node_path_1.relative)(store, installed).split(node_path_1.sep)[0];
3880
+ const registryEntry = `@gadicc+loom@${version}`;
3881
+ if (!(entry === registryEntry || entry.startsWith(`${registryEntry}_`) ||
3882
+ entry.startsWith(`${registryEntry}(`))) {
3883
+ return null;
3884
+ }
3885
+ if (localBuild && await exists((0, node_path_1.join)(localBuild, "package.json")) &&
3886
+ await findInstalledLocalLoomDifference(cwd, localBuild) === null) {
3887
+ return null;
3888
+ }
3889
+ return version;
3890
+ }
3891
+ /**
3892
+ * Lists every local Loom package the project points at, merging entries for
3893
+ * the same directory. For pnpm these are the managed overrides and the
3894
+ * lockfile's local resolution; for Deno, each link whose package is Loom,
3895
+ * or whose path dev state recorded for Loom when that package is gone.
3896
+ * Dev state only identifies such a link; it never proves anything.
3897
+ */
3898
+ async function collectLocalLoomTargets(cwd, project) {
3899
+ const targets = new Map();
3900
+ const add = async (path, source) => {
3901
+ const key = await (0, promises_1.realpath)(path).catch(() => path);
3902
+ const target = targets.get(key) ?? { path: key, sources: [] };
3903
+ target.sources.push(source);
3904
+ targets.set(key, target);
3905
+ };
3906
+ const denoLinks = [];
3907
+ if (project.denoConfig) {
3908
+ for (const { link, path } of await findLoomDenoLinks(cwd, project.denoConfig)) {
3909
+ denoLinks.push(link);
3910
+ await add(path, `${project.denoConfig} links ${link}`);
3911
+ }
3912
+ return { denoLinks, targets: [...targets.values()] };
3913
+ }
3914
+ const workspaceSpec = getManagedDevOverrideSpec(project.workspaceText);
3915
+ if (workspaceSpec && isManagedPackageJsonLoomOverride(workspaceSpec)) {
3916
+ await add(localSpecToPath(cwd, workspaceSpec), "the pnpm-workspace.yaml override");
3917
+ }
3918
+ for (const { key, spec } of getUnmanagedPnpmWorkspaceLoomOverrides(project.workspaceText)) {
3919
+ if (spec.startsWith("workspace:")) {
3920
+ throw new Error(`pnpm-workspace.yaml overrides ${key} with ${spec}, a workspace package Loom cannot trace to a build, so it cannot prove that the installed Loom is published. Remove that override and install a published ${exports.LOOM_DEPENDENCY} instead.`);
3921
+ }
3922
+ await add(localSpecToPath(cwd, spec), `the pnpm-workspace.yaml overrides entry for ${key}`);
3923
+ }
3924
+ for (const { location, spec } of getPackageJsonLocalLoomOverrides(project.packageJson)) {
3925
+ await add(localSpecToPath(cwd, spec), `the ${formatPnpmOverrideLocation(location)} override`);
3926
+ }
3927
+ const lockfileSpec = getLockfileLocalLoomSpec(project.lockfileText);
3928
+ if (lockfileSpec?.startsWith("workspace:")) {
3929
+ throw new Error(`pnpm-lock.yaml resolves ${exports.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 ${exports.LOOM_DEPENDENCY} instead.`);
3930
+ }
3931
+ if (lockfileSpec) {
3932
+ await add(localSpecToPath(cwd, lockfileSpec), "pnpm-lock.yaml");
3933
+ }
3934
+ return { denoLinks, targets: [...targets.values()] };
3935
+ }
3936
+ /**
3937
+ * Proves that the local Loom build this project has installed is published,
3938
+ * from that build's own stamp: the build must record a clean source commit,
3939
+ * the installed copy must match it (and, for pnpm, the lockfile must resolve
3940
+ * to it), and the commit must be covered by a release. Dev state and the
3941
+ * checkout's current git state are never consulted. Throws a refusal that
3942
+ * says what to do otherwise.
3943
+ */
3944
+ async function proveLocalLoomBuildPublished(cwd, target, options) {
3945
+ const { path } = target;
3946
+ const rerun = "then rerun `loom dev published`";
3947
+ if (!await exists((0, node_path_1.join)(path, "package.json"))) {
3948
+ const lockfileOnly = target.sources.every((source) => source === "pnpm-lock.yaml");
3949
+ throw new Error(`${path}, which ${target.sources.join(" and ")} point${target.sources.length === 1 ? "s" : ""} at, holds no built Loom package. ${lockfileOnly
3950
+ ? "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`"
3951
+ : options.denoConfig
3952
+ ? `Restore that Loom checkout and run \`loom dev sync\`, or link another with \`loom dev local\`; if the app does not need that build, remove the link from ${options.denoConfig} yourself and run \`deno install\``
3953
+ : "Restore that Loom checkout and run `loom dev sync`, or link another with `loom dev local`"}, ${rerun}.`);
3954
+ }
3955
+ const stamp = await (0, localDevPackage_js_1.readLoomBuildStamp)(path);
3956
+ if (stamp?.legacyBuildFingerprint && !(0, localDevPackage_js_1.hasLoomBuildProvenance)(stamp)) {
3957
+ 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.`);
3958
+ }
3959
+ if (!stamp || !(0, localDevPackage_js_1.hasLoomBuildProvenance)(stamp)) {
3960
+ 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}.`);
3961
+ }
3962
+ if (stamp.packageDigest !== await (0, localDevPackage_js_1.computePackageContentDigest)(path)) {
3963
+ throw new Error(`${path} was modified after it was built. Run \`loom dev sync --force\`, ${rerun}.`);
3964
+ }
3965
+ if (!stamp.sourceCommit) {
3966
+ 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}.`);
3967
+ }
3968
+ const shortCommit = stamp.sourceCommit.slice(0, 12);
3969
+ if (stamp.sourceDirty !== false) {
3970
+ throw new Error(stamp.sourceDirty
3971
+ ? `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}.`
3972
+ : `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}.`);
3973
+ }
3974
+ // Deno loads a node_modules copy whenever its effective nodeModulesDir is
3975
+ // auto or manual, and manual is its default next to a package.json. So any
3976
+ // copy is compared unless the config says "none", where Deno loads the
3977
+ // linked directory itself.
3978
+ const nodeModulesDir = options.denoConfig
3979
+ ? (0, projectTooling_js_1.parseJsonc)(await readTextIfExists((0, node_path_1.join)(cwd, options.denoConfig)) ?? "{}", options.denoConfig).nodeModulesDir
3980
+ : undefined;
3981
+ const installedCopy = !options.denoConfig ||
3982
+ (nodeModulesDir !== "none" &&
3983
+ await exists((0, node_path_1.join)(cwd, "node_modules", exports.LOOM_DEPENDENCY, "package.json")));
3984
+ const difference = installedCopy
3985
+ ? await findInstalledLocalLoomDifference(cwd, path)
3986
+ : null;
3987
+ if (difference) {
3988
+ throw new Error(`The installed Loom differs from ${path} (${difference}). Run \`loom dev sync\`, ${rerun}.`);
3989
+ }
3990
+ if (!options.denoConfig) {
3991
+ const lockfileSpec = getLockfileLocalLoomSpec(options.lockfileText);
3992
+ if (!lockfileSpec) {
3993
+ throw new Error(`pnpm-lock.yaml does not resolve ${exports.LOOM_DEPENDENCY} to ${path}. Run \`loom dev sync\`, ${rerun}.`);
3994
+ }
3995
+ }
3996
+ const sourceRoot = await resolveLocalLoomSourceRoot(path);
3997
+ if (!sourceRoot) {
3998
+ 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}.`);
3999
+ }
4000
+ const publication = await findPublishedLoomPublicationForCommit(sourceRoot, stamp.sourceCommit, options.commandRunner, options.env, options.preferredSpec, `Loom commit ${shortCommit}, which built ${path},`);
4001
+ return {
4002
+ note: publication.reason === "contains-commit"
4003
+ ? `The Loom build in ${path} comes from commit ${shortCommit}, which is included in published ${exports.LOOM_DEPENDENCY}@${publication.version}.`
4004
+ : `The Loom build in ${path} comes from commit ${shortCommit}, which has no package-relevant changes after ${publication.tag}, so published ${exports.LOOM_DEPENDENCY}@${publication.version} covers it.`,
4005
+ publication,
4006
+ };
4007
+ }
2734
4008
  async function usePublishedDevPackage(cwd, options = {}) {
4009
+ // A project that was never linked has nothing a sync could be changing,
4010
+ // so it does not need the lock (or a new `.loom/` directory).
4011
+ if (!(await detectLocalDevLink(cwd)).active &&
4012
+ !await exists((0, node_path_1.join)(cwd, ".loom"))) {
4013
+ return await usePublishedDevPackageLocked(cwd, options);
4014
+ }
4015
+ return await withProjectLocalDevLock(cwd, options, () => usePublishedDevPackageLocked(cwd, options));
4016
+ }
4017
+ async function usePublishedDevPackageLocked(cwd, options) {
2735
4018
  const { packageJson } = await readProjectPackageJson(cwd);
2736
4019
  const manifest = await readManifestIfExists(cwd);
2737
4020
  const tooling = await (0, projectTooling_js_1.detectProjectTooling)(cwd, manifest?.project?.tooling);
@@ -2745,75 +4028,235 @@ async function usePublishedDevPackage(cwd, options = {}) {
2745
4028
  const denoConfig = denoMode
2746
4029
  ? await getDenoConfigForLinks(cwd, tooling)
2747
4030
  : null;
2748
- const denoLink = denoConfig
2749
- ? await findLocalLoomDenoLink(cwd, await (0, projectTooling_js_1.readDenoLinks)(cwd, denoConfig))
2750
- : null;
2751
- const activeOverrideSpec = denoLink?.link ??
2752
- getManagedDevOverrideSpec(workspaceText);
2753
- const localLockfileResolution = denoMode
4031
+ const lockfileText = denoMode
2754
4032
  ? null
2755
- : await getProjectLocalLoomLockfileResolution(cwd);
2756
- const state = denoMode
2757
- ? await readLocalDevState(cwd)
2758
- : await getCurrentLocalDevState(cwd, workspaceText);
4033
+ : await readTextIfExists((0, node_path_1.join)(cwd, "pnpm-lock.yaml"));
4034
+ const localLockfileResolution = lockfileText
4035
+ ? getLocalLoomLockfileResolution(lockfileText)
4036
+ : null;
2759
4037
  const notes = [];
2760
- let publishedSpec = getPublishedLoomDependencySpec(packageJson);
2761
- const needsPublicationProof = Boolean(activeOverrideSpec || localLockfileResolution);
2762
- if (needsPublicationProof && state?.sourceCommit) {
2763
- if (state.sourceDirty) {
2764
- 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\`.`);
2765
- }
2766
- if (!state.sourceRoot) {
2767
- 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.");
4038
+ const { denoLinks, targets } = await collectLocalLoomTargets(cwd, {
4039
+ denoConfig,
4040
+ lockfileText,
4041
+ packageJson,
4042
+ workspaceText,
4043
+ });
4044
+ if (targets.length > 1) {
4045
+ 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\`.`);
4046
+ }
4047
+ // A `catalog:` reference keeps its version in pnpm-workspace.yaml, which is
4048
+ // where the published version has to go too.
4049
+ const catalogDependency = denoMode
4050
+ ? null
4051
+ : await resolveLoomDependencySpec(cwd, packageJson);
4052
+ const catalog = catalogDependency?.catalogName ? catalogDependency : null;
4053
+ let publishedSpec = catalog
4054
+ ? catalog.effective && !isLocalPackageSpec(catalog.effective)
4055
+ ? catalog.effective
4056
+ : exports.DEFAULT_LOOM_RANGE
4057
+ : getPublishedLoomDependencySpec(packageJson);
4058
+ // A pnpm link that was never installed left nothing local to prove: the
4059
+ // app still runs the published Loom it had. Deno reads a link directly or
4060
+ // copies it into node_modules on its next install or run, so Deno links
4061
+ // are always proved.
4062
+ const registryVersion = denoMode || targets.length !== 1
4063
+ ? null
4064
+ : await findInstalledRegistryLoomVersion(cwd, lockfileText, targets[0].path);
4065
+ if (registryVersion) {
4066
+ notes.push(`No local Loom build was installed (pnpm-lock.yaml and node_modules hold published ${exports.LOOM_DEPENDENCY}@${registryVersion}), so the pin stays at ${publishedSpec}.`);
4067
+ }
4068
+ else if (targets.length === 1) {
4069
+ const proof = await proveLocalLoomBuildPublished(cwd, targets[0], {
4070
+ commandRunner,
4071
+ denoConfig,
4072
+ env,
4073
+ lockfileText,
4074
+ preferredSpec: publishedSpec,
4075
+ });
4076
+ publishedSpec = proof.publication.version;
4077
+ notes.push(proof.note);
4078
+ }
4079
+ const changedFiles = [];
4080
+ let catalogChanged = false;
4081
+ if (catalog) {
4082
+ const currentText = await readTextIfExists(workspacePath);
4083
+ const entry = findLoomCatalogEntry(currentText, catalog.catalogName);
4084
+ const unreadable = entry
4085
+ ? null
4086
+ : findUnreadableLoomCatalog(currentText, catalog.catalogName);
4087
+ if (unreadable) {
4088
+ notes.push(`pnpm-workspace.yaml writes the \`${unreadable}\` catalog as a multi-line or nested flow map, which Loom cannot edit; set ${exports.LOOM_DEPENDENCY} to ${publishedSpec} there yourself.`);
2768
4089
  }
2769
- const publication = await findPublishedLoomPublicationForCommit(state.sourceRoot, state.sourceCommit, commandRunner, env, publishedSpec);
2770
- publishedSpec = publication.version;
2771
- if (publication.reason === "contains-commit") {
2772
- notes.push(`Local Loom commit ${state.sourceCommit.slice(0, 12)} is included in published ${exports.LOOM_DEPENDENCY}@${publication.version}.`);
4090
+ else if (!entry) {
4091
+ notes.push(`package.json uses \`${catalog.raw}\`, but pnpm-workspace.yaml has no ${exports.LOOM_DEPENDENCY} entry in that catalog; add \`${exports.LOOM_DEPENDENCY}: ${publishedSpec}\` there.`);
2773
4092
  }
2774
- else {
2775
- notes.push(`Local Loom commit ${state.sourceCommit.slice(0, 12)} has no package-relevant changes after ${publication.tag}, so published ${exports.LOOM_DEPENDENCY}@${publication.version} covers this sync.`);
4093
+ else if (entry.spec !== publishedSpec) {
4094
+ const updated = setLoomCatalogEntryText(currentText, entry, publishedSpec);
4095
+ if (updated !== null) {
4096
+ await (0, promises_1.writeFile)(workspacePath, updated, "utf8");
4097
+ changedFiles.push("pnpm-workspace.yaml");
4098
+ catalogChanged = true;
4099
+ }
2776
4100
  }
2777
4101
  }
2778
- else if (needsPublicationProof) {
2779
- notes.push("No recorded Loom sync commit was found; switching back to the existing published dependency without proving whether local Loom changes were required.");
4102
+ else {
4103
+ const dependencyUpdate = await (0, projectTooling_js_1.mutateProjectDependencies)(cwd, tooling.dependencies, {
4104
+ dependencies: { [exports.LOOM_DEPENDENCY]: publishedSpec },
4105
+ replace: true,
4106
+ });
4107
+ if (dependencyUpdate.changed) {
4108
+ changedFiles.push(dependencyUpdate.config);
4109
+ }
2780
4110
  }
2781
- const dependencyUpdate = await (0, projectTooling_js_1.mutateProjectDependencies)(cwd, tooling.dependencies, {
2782
- dependencies: { [exports.LOOM_DEPENDENCY]: publishedSpec },
2783
- replace: true,
2784
- });
2785
- const denoUpdate = denoConfig && denoLink
2786
- ? await (0, projectTooling_js_1.mutateDenoLinks)(cwd, denoConfig, { remove: denoLink.link })
4111
+ const denoUpdate = denoConfig && denoLinks.length
4112
+ ? await (0, projectTooling_js_1.mutateDenoLinks)(cwd, denoConfig, { remove: denoLinks })
2787
4113
  : null;
2788
- const update = denoMode
2789
- ? { changed: denoUpdate?.changed ?? false, text: "" }
2790
- : clearPnpmWorkspaceLocalDevText(await readTextIfExists(workspacePath));
2791
- const changedFiles = [];
2792
- if (dependencyUpdate.changed) {
2793
- changedFiles.push(dependencyUpdate.config);
4114
+ let overrideRemoved = false;
4115
+ if (denoMode) {
4116
+ if (denoUpdate?.changed) {
4117
+ // The dependency pin may have changed the same file already.
4118
+ if (!changedFiles.includes(denoConfig))
4119
+ changedFiles.push(denoConfig);
4120
+ overrideRemoved = true;
4121
+ }
2794
4122
  }
2795
- if (update.changed) {
2796
- if (denoMode) {
2797
- changedFiles.push(denoConfig);
4123
+ else {
4124
+ for (const file of await clearPnpmLocalDevOverrides(cwd)) {
4125
+ if (!changedFiles.includes(file))
4126
+ changedFiles.push(file);
4127
+ overrideRemoved = true;
4128
+ }
4129
+ // Entries written by hand point pnpm at a local Loom just the same.
4130
+ const workspaceNow = await readTextIfExists(workspacePath);
4131
+ if (workspaceNow && !getManagedDevOverrideBlockText(workspaceNow)) {
4132
+ const update = removeUnmanagedPnpmWorkspaceLoomOverrides(workspaceNow);
4133
+ if (update.changed) {
4134
+ await writeTextOrDeleteIfEmpty(workspacePath, update.text);
4135
+ if (!changedFiles.includes("pnpm-workspace.yaml")) {
4136
+ changedFiles.push("pnpm-workspace.yaml");
4137
+ }
4138
+ overrideRemoved = true;
4139
+ }
4140
+ for (const { key, spec } of update.kept) {
4141
+ 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\`.`);
4142
+ }
2798
4143
  }
2799
- else {
2800
- await writeTextOrDeleteIfEmpty(workspacePath, update.text);
2801
- changedFiles.push("pnpm-workspace.yaml");
4144
+ }
4145
+ if (denoMode) {
4146
+ if (overrideRemoved || localLockfileResolution) {
4147
+ notes.push(`Run \`deno install\` in this project to return node_modules and deno.lock to published ${exports.LOOM_DEPENDENCY}@${publishedSpec}.`);
2802
4148
  }
2803
4149
  }
2804
- if (update.changed || localLockfileResolution) {
2805
- notes.push(denoMode
2806
- ? `Run \`deno install\` in this project to return node_modules and deno.lock to published ${exports.LOOM_DEPENDENCY}@${publishedSpec}.`
2807
- : `Run \`pnpm update --no-save ${exports.LOOM_DEPENDENCY}@${publishedSpec}\` and then \`pnpm install\` in this project to return node_modules and the lockfile to the published ${exports.LOOM_DEPENDENCY} dependency.`);
4150
+ else if (overrideRemoved || localLockfileResolution) {
4151
+ const importer = lockfileText
4152
+ ? (0, localDevPackage_js_1.getLockfileRootImporterDependency)(lockfileText, exports.LOOM_DEPENDENCY)
4153
+ : null;
4154
+ // Earlier Loom versions linked through `pnpm update --no-save`, which
4155
+ // leaves the published specifier with a local version. While that
4156
+ // specifier still matches package.json, pnpm install treats the lockfile
4157
+ // as up to date and keeps the local resolution.
4158
+ const specifierUnchanged = catalog
4159
+ ? importer?.specifier === catalog.raw && !catalogChanged
4160
+ : importer?.specifier === publishedSpec;
4161
+ const legacyLocalResolution = importer?.version &&
4162
+ isLocalPackageSpec(importer.version) && specifierUnchanged
4163
+ ? localLockfileResolution ?? importer.version
4164
+ : null;
4165
+ if (legacyLocalResolution && catalog) {
4166
+ notes.push(`pnpm-lock.yaml still resolves ${exports.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\`.`);
4167
+ }
4168
+ else if (legacyLocalResolution) {
4169
+ const pinCommand = isExactSemverVersion(publishedSpec)
4170
+ ? `\`${dependencyRefreshCommand(tooling.dependencies, exports.LOOM_DEPENDENCY, publishedSpec, { pnpmWorkspaceRoot: await pnpmWorkspaceDeclaresPackages(cwd) })}\``
4171
+ : `\`pnpm add --save-exact ${exports.LOOM_DEPENDENCY}@<version>\` with the exact version to ship`;
4172
+ notes.push(`pnpm-lock.yaml still resolves ${exports.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).`);
4173
+ }
4174
+ else {
4175
+ notes.push(`Run \`pnpm install\` in this project to return node_modules and pnpm-lock.yaml to published ${exports.LOOM_DEPENDENCY}@${publishedSpec}; it keeps every other locked version.`);
4176
+ if (localLockfileResolution) {
4177
+ notes.push(`pnpm-lock.yaml still resolves ${exports.LOOM_DEPENDENCY} to ${localLockfileResolution} until that install is run.`);
4178
+ }
4179
+ }
2808
4180
  }
2809
- if (localLockfileResolution) {
2810
- notes.push(`pnpm-lock.yaml still resolves ${exports.LOOM_DEPENDENCY} to ${localLockfileResolution} until that update is run.`);
4181
+ // Once nothing local can be in use, the sync record describes code the app
4182
+ // no longer runs; kept, `loom check` would go on checking a commit in a
4183
+ // checkout that may since be gone. Until then (typically until the
4184
+ // `pnpm install` this command asks for), it stays. Created-map flags were
4185
+ // cleared above.
4186
+ if ((await findLocalLoomUse(cwd)).length === 0) {
4187
+ await (0, promises_1.rm)((0, node_path_1.join)(cwd, exports.LOOM_LOCAL_DEV_STATE_RELATIVE_PATH), { force: true });
2811
4188
  }
2812
4189
  return {
2813
4190
  changedFiles,
2814
4191
  notes,
2815
4192
  };
2816
4193
  }
4194
+ /** Removes every managed local Loom override from a pnpm project. */
4195
+ async function clearPnpmLocalDevOverrides(cwd) {
4196
+ const changedFiles = [];
4197
+ const workspacePath = (0, node_path_1.join)(cwd, "pnpm-workspace.yaml");
4198
+ const workspaceUpdate = clearPnpmWorkspaceLocalDevText(await readTextIfExists(workspacePath));
4199
+ if (workspaceUpdate.changed) {
4200
+ await writeTextOrDeleteIfEmpty(workspacePath, workspaceUpdate.text);
4201
+ changedFiles.push("pnpm-workspace.yaml");
4202
+ }
4203
+ for (const { field } of PACKAGE_JSON_OVERRIDE_LOCATIONS) {
4204
+ if (await removePackageJsonLoomOverride(cwd, field) &&
4205
+ !changedFiles.includes("package.json")) {
4206
+ changedFiles.push("package.json");
4207
+ }
4208
+ }
4209
+ // Flags for maps whose Loom entry was already gone would otherwise
4210
+ // outlive the link and claim maps the project has since added.
4211
+ await writeCreatedPackageJsonMaps(cwd, {});
4212
+ return changedFiles;
4213
+ }
4214
+ function getRawPackageJsonMap(packageJson, field) {
4215
+ return field === "resolutions"
4216
+ ? packageJson.resolutions
4217
+ : packageJson.pnpm?.overrides;
4218
+ }
4219
+ async function readCreatedPackageJsonMaps(cwd) {
4220
+ return { ...(await readLocalDevState(cwd))?.createdPackageJsonMaps };
4221
+ }
4222
+ async function writeCreatedPackageJsonMaps(cwd, created, overrideSpec) {
4223
+ const state = await readLocalDevState(cwd);
4224
+ const { createdPackageJsonMaps: _previous, ...rest } = state ?? {
4225
+ dependency: exports.LOOM_DEPENDENCY,
4226
+ localPackagePath: overrideSpec ? fileSpecToPath(cwd, overrideSpec) : "",
4227
+ syncedAt: new Date().toISOString(),
4228
+ version: 1,
4229
+ };
4230
+ if (!state && Object.keys(created).length === 0)
4231
+ return;
4232
+ await writeLocalDevStateIfChanged(cwd, Object.keys(created).length
4233
+ ? { ...rest, createdPackageJsonMaps: created }
4234
+ : rest);
4235
+ }
4236
+ /**
4237
+ * Removes Loom's managed (`file:`) override from one package.json map with
4238
+ * a minimal text edit. The map (and the `pnpm` object) is removed as well
4239
+ * only when it ends up empty and dev state records that Loom created it;
4240
+ * maps the project already had, or whose origin is unknown, always stay.
4241
+ * Never writes back a whole-file snapshot. Returns whether package.json
4242
+ * changed.
4243
+ */
4244
+ async function removePackageJsonLoomOverride(cwd, field) {
4245
+ const { packageJson } = await readProjectPackageJson(cwd);
4246
+ if (!isManagedPackageJsonLoomOverride(getPackageJsonOverrideMap(packageJson, field)[exports.LOOM_DEPENDENCY])) {
4247
+ return false;
4248
+ }
4249
+ const created = await readCreatedPackageJsonMaps(cwd);
4250
+ const update = await (0, projectTooling_js_1.mutatePackageJsonOverride)(cwd, field, exports.LOOM_DEPENDENCY, undefined, {
4251
+ removeEmptyMap: created[field] === true,
4252
+ removeEmptyPnpm: field === "pnpm.overrides" && created.pnpm === true,
4253
+ });
4254
+ delete created[field];
4255
+ if (field === "pnpm.overrides")
4256
+ delete created.pnpm;
4257
+ await writeCreatedPackageJsonMaps(cwd, created);
4258
+ return update.changed;
4259
+ }
2817
4260
  async function ensureManagedAgentsFile(cwd) {
2818
4261
  const relativePath = "AGENTS.md";
2819
4262
  const agentsPath = (0, node_path_1.join)(cwd, relativePath);
@@ -3028,7 +4471,15 @@ async function checkManagedAgentsFile(cwd) {
3028
4471
  warnings: [],
3029
4472
  };
3030
4473
  }
3031
- async function checkManagedLocalDevOverride(cwd, production = false) {
4474
+ /** Matches override keys that select Loom, including pnpm/yarn selectors. */
4475
+ function overrideKeyTargetsLoom(key) {
4476
+ const target = key.split(">").pop().trim();
4477
+ return target === exports.LOOM_DEPENDENCY ||
4478
+ target.startsWith(`${exports.LOOM_DEPENDENCY}@`) ||
4479
+ target.endsWith(`/${exports.LOOM_DEPENDENCY}`) ||
4480
+ target.includes(`/${exports.LOOM_DEPENDENCY}@`);
4481
+ }
4482
+ async function checkManagedLocalDevOverride(cwd, production, commandRunner, env) {
3032
4483
  const manifest = await readManifestIfExists(cwd);
3033
4484
  let denoLink = null;
3034
4485
  let denoConfig = null;
@@ -3043,8 +4494,15 @@ async function checkManagedLocalDevOverride(cwd, production = false) {
3043
4494
  // The main project tooling check reports invalid configuration separately.
3044
4495
  }
3045
4496
  const workspaceText = await readTextIfExists((0, node_path_1.join)(cwd, "pnpm-workspace.yaml"));
3046
- const overrideSpec = getManagedDevOverrideSpec(workspaceText);
3047
- if (!overrideSpec && !denoLink) {
4497
+ const denoMode = denoConfig !== null;
4498
+ const packageJson = denoMode ? null : await readPackageJsonIfExists(cwd);
4499
+ // Any local spec for Loom in an override map, whoever wrote it and
4500
+ // whatever selector it uses, is a local-dev link and must not ship; so is
4501
+ // a Deno link to Loom, even one whose package is gone. The same finder
4502
+ // decides whether a sync record is stale. A local catalog entry has its
4503
+ // own, clearer issue.
4504
+ const links = await findLocalLoomLinks(cwd).then((found) => found.links, () => []);
4505
+ if (!links.length && !denoLink) {
3048
4506
  return {
3049
4507
  issues: [],
3050
4508
  suggestions: [],
@@ -3053,19 +4511,43 @@ async function checkManagedLocalDevOverride(cwd, production = false) {
3053
4511
  }
3054
4512
  const location = denoLink
3055
4513
  ? `${denoConfig} links: ${denoLink.link}`
3056
- : `pnpm-workspace.yaml: ${overrideSpec}`;
3057
- const restore = denoLink
4514
+ : links[0];
4515
+ const restore = denoMode
3058
4516
  ? "Run `loom dev published`, then run `deno install` before committing or shipping a published build."
3059
- : `Run \`loom dev published\`, then follow its printed \`pnpm update --no-save ${exports.LOOM_DEPENDENCY}@<version>\` command and run \`pnpm install\` before committing or shipping a published build.`;
4517
+ : "Run `loom dev published`, then run `pnpm install` (or the command it prints) before committing or shipping a published build.";
4518
+ const warnings = [];
4519
+ const suggestions = [restore];
4520
+ const activePnpmOverride = packageJson
4521
+ ? getActivePnpmLocalDevOverride(workspaceText, packageJson)
4522
+ : null;
4523
+ if (activePnpmOverride && packageJson) {
4524
+ // Use the same placement decision as `loom dev sync`, so the advice here
4525
+ // is exactly what the next sync does.
4526
+ const placement = await resolvePnpmLocalDevOverrideLocation(cwd, packageJson, commandRunner, env);
4527
+ const pnpmLabel = placement.pnpmVersion === null
4528
+ ? "pnpm (version unknown, assumed 10.5.1 or newer)"
4529
+ : `pnpm ${placement.pnpmVersion}`;
4530
+ if (placement.conflict) {
4531
+ warnings.push(placement.conflict);
4532
+ }
4533
+ else if (activePnpmOverride.location === "pnpm-workspace.yaml"
4534
+ ? placement.location !== "pnpm-workspace.yaml"
4535
+ : placement.location === "pnpm-workspace.yaml" &&
4536
+ placement.pnpmMajor !== null && placement.pnpmMajor >= 11) {
4537
+ warnings.push(`${pnpmLabel} does not apply the Loom override in ${formatPnpmOverrideLocation(activePnpmOverride.location)}, so this app may still use the published Loom package.`);
4538
+ suggestions.push(`Run \`loom dev sync\` to move the override to ${formatPnpmOverrideLocation(placement.location)}, where pnpm applies it.`);
4539
+ }
4540
+ }
3060
4541
  return {
3061
4542
  issues: production
3062
4543
  ? [
3063
4544
  `Local Loom dev override is active in ${location}`,
3064
4545
  ]
3065
4546
  : [],
3066
- suggestions: [restore],
3067
- warnings: production ? [] : [
4547
+ suggestions,
4548
+ warnings: production ? warnings : [
3068
4549
  `Local Loom dev override is active in ${location}`,
4550
+ ...warnings,
3069
4551
  ],
3070
4552
  };
3071
4553
  }
@@ -3104,7 +4586,6 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
3104
4586
  const issues = [];
3105
4587
  const suggestions = new Set();
3106
4588
  const warnings = [];
3107
- const dependency = packageJson.dependencies?.[exports.LOOM_DEPENDENCY];
3108
4589
  const production = options.production;
3109
4590
  const projectMetadata = await (0, projectTooling_js_1.readProjectPackageMetadata)(cwd);
3110
4591
  let dependencyTooling = {
@@ -3118,16 +4599,82 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
3118
4599
  catch {
3119
4600
  // The main tooling check owns the validation error; release hints can fall back.
3120
4601
  }
4602
+ // A pnpm `catalog:` reference pins Loom in pnpm-workspace.yaml instead.
4603
+ // Other managers' catalogs (Yarn 4) are not read.
4604
+ const loomDependency = await resolveLoomDependencySpec(cwd, packageJson);
4605
+ const dependency = dependencyTooling.manager === "pnpm"
4606
+ ? loomDependency.effective
4607
+ : loomDependency.raw;
3121
4608
  const localLockfileResolution = await getProjectLocalLoomLockfileResolution(cwd);
3122
4609
  const devState = await readLocalDevState(cwd);
4610
+ const refreshOptions = {
4611
+ pnpmWorkspaceRoot: await pnpmWorkspaceDeclaresPackages(cwd),
4612
+ };
4613
+ const catalogName = dependencyTooling.manager === "pnpm"
4614
+ ? loomDependency.catalogName
4615
+ : null;
4616
+ const pinLocation = catalogName
4617
+ ? `the pnpm-workspace.yaml \`${loomDependency.catalogEntry?.label ?? "catalog:"}\` map`
4618
+ : dependencyTooling.config;
4619
+ // A pnpm pin change is a manual package.json edit plus `pnpm install`,
4620
+ // which gives the same lockfile as `pnpm add --save-exact` without
4621
+ // re-sorting package.json. Only a lockfile an older `pnpm update --no-save`
4622
+ // link left behind, under an unchanged pin, needs `pnpm add`.
4623
+ const pinSuggestion = (version) => catalogName
4624
+ ? formatLoomCatalogPinAdvice(loomDependency.catalogEntry, catalogName, version)
4625
+ : dependencyTooling.manager !== "pnpm"
4626
+ ? `Run ${dependencyRefreshCommand(dependencyTooling, exports.LOOM_DEPENDENCY, version, refreshOptions)}.`
4627
+ : version === dependency
4628
+ ? `Restore pnpm-lock.yaml from git if it has no other intended changes and run \`pnpm install\`; otherwise run \`${dependencyRefreshCommand(dependencyTooling, exports.LOOM_DEPENDENCY, version, refreshOptions)}\` (\`pnpm add\` may re-sort package.json dependencies).`
4629
+ : `Set ${exports.LOOM_DEPENDENCY} to ${version} in package.json, then run \`pnpm install\`.`;
4630
+ // While the override is active it forces the local package whatever the
4631
+ // pin says, so it has to be removed before any refresh can help.
4632
+ const pnpmOverrideActive = dependencyTooling.manager === "pnpm" &&
4633
+ getActivePnpmLocalDevOverride(await readTextIfExists((0, node_path_1.join)(cwd, "pnpm-workspace.yaml")), packageJson) !== null;
3123
4634
  if (localLockfileResolution) {
3124
4635
  addReleaseCheckMessage(issues, warnings, production, `pnpm-lock.yaml resolves @gadicc/loom to a local package: ${localLockfileResolution}`);
3125
4636
  suggestions.add("Run `loom dev published`, then refresh the lockfile with the published @gadicc/loom version before production build.");
3126
4637
  }
3127
- if (devState?.sourceCommit) {
4638
+ // The sync record only matters while the app can still run local Loom
4639
+ // code. Without a link, an override or a local lockfile resolution, the
4640
+ // app runs a published Loom, and the record (perhaps naming a checkout
4641
+ // that is gone) is stale.
4642
+ const localLoomUses = await findLocalLoomUse(cwd);
4643
+ const localLoomInUse = localLoomUses.length > 0;
4644
+ // Only an installed copy Loom cannot prove published, with no link or
4645
+ // lockfile pointing at local Loom, is too weak to fail a release by
4646
+ // itself: the record's findings stay warnings then.
4647
+ const recordGatesRelease = production &&
4648
+ localLoomUses.some((use) => use.kind !== "installed");
4649
+ if (devState?.sourceCommit && !localLoomInUse) {
4650
+ const shortCommit = devState.sourceCommit.slice(0, 12);
4651
+ warnings.push(`${exports.LOOM_LOCAL_DEV_STATE_RELATIVE_PATH} still records a local Loom sync at commit ${shortCommit}, but no local Loom is linked, locked or installed any more, so it is stale and can be deleted.`);
4652
+ // The app may still rely on what that sync contained: advise, never
4653
+ // fail, when a newer release covers it than the app pins. A checkout
4654
+ // that is gone is not looked up at all.
4655
+ if (devState.sourceRoot && !devState.sourceDirty &&
4656
+ dependency && isExactSemverVersion(dependency) &&
4657
+ await exists(devState.sourceRoot)) {
4658
+ const publication = await resolveLoomCommitPublication(devState.sourceRoot, devState.sourceCommit, options.commandRunner, options.env, dependency);
4659
+ if (publication.status === "published" &&
4660
+ publication.version !== dependency) {
4661
+ warnings.push(`This app was last synced against Loom commit ${shortCommit}; ${publication.reason === "package-equivalent"
4662
+ ? `package-relevant files match ${exports.LOOM_DEPENDENCY}@${publication.version}`
4663
+ : `it is published as ${exports.LOOM_DEPENDENCY}@${publication.version}`}, but ${pinLocation} is pinned to ${dependency}.`);
4664
+ suggestions.add(pinSuggestion(publication.version));
4665
+ }
4666
+ }
4667
+ }
4668
+ else if (devState?.sourceCommit && devState.sourceRoot &&
4669
+ !devState.sourceDirty && !await exists(devState.sourceRoot)) {
4670
+ // A deleted checkout is not evidence of unpublished code; the active
4671
+ // link or lockfile already fails the release check on its own.
4672
+ warnings.push(`This app was last synced against Loom commit ${devState.sourceCommit.slice(0, 12)} in ${devState.sourceRoot}, which no longer exists, so Loom cannot check that commit.`);
4673
+ }
4674
+ else if (devState?.sourceCommit) {
3128
4675
  const shortCommit = devState.sourceCommit.slice(0, 12);
3129
4676
  if (devState.sourceDirty) {
3130
- addReleaseCheckMessage(issues, warnings, production, `This app was last synced against Loom commit ${shortCommit} with a dirty source tree.`);
4677
+ addReleaseCheckMessage(issues, warnings, recordGatesRelease, `This app was last synced against Loom commit ${shortCommit} with a dirty source tree.`);
3131
4678
  suggestions.add("Commit or discard the Loom changes, rerun `loom dev sync`, and publish Loom if the app depends on those changes.");
3132
4679
  }
3133
4680
  else if (!devState.sourceRoot) {
@@ -3137,11 +4684,11 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
3137
4684
  const publication = await resolveLoomCommitPublication(devState.sourceRoot, devState.sourceCommit, options.commandRunner, options.env, isExactSemverVersion(dependency ?? "") ? dependency : undefined);
3138
4685
  switch (publication.status) {
3139
4686
  case "not-on-origin-main":
3140
- addReleaseCheckMessage(issues, warnings, production, `This app was last synced against Loom commit ${shortCommit}, which is not reachable from origin/main.`);
4687
+ addReleaseCheckMessage(issues, warnings, recordGatesRelease, `This app was last synced against Loom commit ${shortCommit}, which is not reachable from origin/main.`);
3141
4688
  suggestions.add("Push or merge the Loom changes, fetch origin/main, publish Loom if needed, then rerun `loom dev published`.");
3142
4689
  break;
3143
4690
  case "no-release-tag":
3144
- addReleaseCheckMessage(issues, warnings, production, `This app was last synced against Loom commit ${shortCommit}, but no published Loom version contains that commit or matches its package-relevant files.`);
4691
+ addReleaseCheckMessage(issues, warnings, recordGatesRelease, `This app was last synced against Loom commit ${shortCommit}, but no published Loom version contains that commit or matches its package-relevant files.`);
3145
4692
  suggestions.add("Publish Loom first, fetch tags, then rerun `loom dev published`.");
3146
4693
  break;
3147
4694
  case "published":
@@ -3151,8 +4698,10 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
3151
4698
  "package-equivalent"
3152
4699
  ? `package-relevant files match ${exports.LOOM_DEPENDENCY}@${publication.version}`
3153
4700
  : `it is published as ${exports.LOOM_DEPENDENCY}@${publication.version}`;
3154
- addReleaseCheckMessage(issues, warnings, production, `This app was last synced against Loom commit ${shortCommit}; ${publicationDescription}, but ${dependencyTooling.config} is pinned to ${dependency}.`);
3155
- suggestions.add(`Run ${dependencyRefreshCommand(dependencyTooling, exports.LOOM_DEPENDENCY, publication.version)}.`);
4701
+ addReleaseCheckMessage(issues, warnings, recordGatesRelease, `This app was last synced against Loom commit ${shortCommit}; ${publicationDescription}, but ${pinLocation} is pinned to ${dependency}.`);
4702
+ suggestions.add(pnpmOverrideActive
4703
+ ? "Run `loom dev published`, which pins the covering version, then run `pnpm install`."
4704
+ : pinSuggestion(publication.version));
3156
4705
  }
3157
4706
  else if (localLockfileResolution) {
3158
4707
  const publicationDescription = publication.reason ===
@@ -3160,7 +4709,13 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
3160
4709
  ? `has no package-relevant changes after ${publication.tag}, so ${exports.LOOM_DEPENDENCY}@${publication.version} covers it`
3161
4710
  : `is published as ${exports.LOOM_DEPENDENCY}@${publication.version}`;
3162
4711
  warnings.push(`The synced Loom commit ${shortCommit} ${publicationDescription}; refresh the lockfile away from ${localLockfileResolution}.`);
3163
- suggestions.add(`Run ${dependencyRefreshCommand(dependencyTooling, exports.LOOM_DEPENDENCY, publication.version)}.`);
4712
+ suggestions.add(pnpmOverrideActive
4713
+ ? "Run `loom dev published`, which pins the covering version, then run `pnpm install`."
4714
+ : catalogName && dependency === publication.version
4715
+ // pnpm keeps a local resolution while the catalog version
4716
+ // it was linked under is unchanged.
4717
+ ? "Restore pnpm-lock.yaml from git and run `pnpm install`."
4718
+ : pinSuggestion(publication.version));
3164
4719
  }
3165
4720
  break;
3166
4721
  }
@@ -3185,8 +4740,12 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
3185
4740
  else {
3186
4741
  const installedPackage = parseJson(installedPackageText, (0, node_path_1.join)("node_modules", exports.LOOM_DEPENDENCY, "package.json"));
3187
4742
  if (installedPackage.version !== dependency) {
3188
- issues.push(`Installed ${exports.LOOM_DEPENDENCY} version ${installedPackage.version} does not match ${dependencyTooling.config} ${dependency}.`);
3189
- suggestions.add(`Run ${dependencyRefreshCommand(dependencyTooling, exports.LOOM_DEPENDENCY, dependency)}.`);
4743
+ issues.push(`Installed ${exports.LOOM_DEPENDENCY} version ${installedPackage.version} does not match ${pinLocation} ${dependency}.`);
4744
+ suggestions.add(pnpmOverrideActive
4745
+ ? "Run `loom dev published`, then run `pnpm install`."
4746
+ : dependencyTooling.manager === "pnpm"
4747
+ ? "Run `pnpm install`."
4748
+ : pinSuggestion(dependency));
3190
4749
  }
3191
4750
  }
3192
4751
  }
@@ -4764,6 +6323,18 @@ import { apiKeyPolicy } from "${toAliasImportPath(config.modules.policyModule)}"
4764
6323
  import { apiKeyAuditRepository } from "${toAliasImportPath(config.modules.repositoryModule)}";
4765
6324
 
4766
6325
  // Generated verifier stub: adapt Better Auth verifyApiKey() exactly once here.
6326
+ // Replace it with Loom's shared verifier, which checks the requested
6327
+ // permission itself so a scope miss is denied as insufficient_permission:
6328
+ //
6329
+ // import { createBetterAuthApiKeyVerifier } from "@gadicc/loom/apiKeys";
6330
+ // import { auth } from "<the app's Better Auth module>";
6331
+ // import { apiKeyScopes } from "<the app's defineApiKeyScopes registry>";
6332
+ //
6333
+ // export const apiKeyVerifier = createBetterAuthApiKeyVerifier({
6334
+ // auth,
6335
+ // configId: "default", // the api-key plugin configId these keys use
6336
+ // scopes: apiKeyScopes,
6337
+ // });
4767
6338
  export const apiKeyVerifier: ApiKeyVerifier = {
4768
6339
  verify() {
4769
6340
  return Promise.resolve({ ok: false, code: "invalid_credential" });
@@ -8585,7 +10156,7 @@ async function applyApiKeysFeature(cwd, framework, manifest, activate) {
8585
10156
  changedFiles.push(...materialized.changedFiles);
8586
10157
  notes.push(...materialized.notes);
8587
10158
  config.schema = materialized.schema;
8588
- 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.");
10159
+ 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.");
8589
10160
  }
8590
10161
  const scaffolds = [
8591
10162
  [config.modules.policyModule, apiKeysPolicyTemplate(), "policy"],
@@ -9598,184 +11169,1124 @@ async function checkFilesFeature(cwd, framework, manifest, options) {
9598
11169
  for (const suggestion of local.suggestions)
9599
11170
  suggestions.add(suggestion);
9600
11171
  }
9601
- const routeText = await readTextIfExists((0, node_path_1.join)(cwd, config.entrypoints.routeHandler));
9602
- if (!routeText) {
9603
- issues.push(`Files route handler is missing: ${config.entrypoints.routeHandler}`);
9604
- suggestions.add("Run `loom add files` to scaffold the files route handler.");
11172
+ const routeText = await readTextIfExists((0, node_path_1.join)(cwd, config.entrypoints.routeHandler));
11173
+ if (!routeText) {
11174
+ issues.push(`Files route handler is missing: ${config.entrypoints.routeHandler}`);
11175
+ suggestions.add("Run `loom add files` to scaffold the files route handler.");
11176
+ }
11177
+ else {
11178
+ if (!matchesImportSource(routeText, ["@gadicc/loom/next/files"])) {
11179
+ issues.push(`Files route handler is not wired to @gadicc/loom/next/files: ${config.entrypoints.routeHandler}`);
11180
+ }
11181
+ if (!routeText.includes("createFilesRouteHandlers")) {
11182
+ issues.push(`Files route handler does not call createFilesRouteHandlers: ${config.entrypoints.routeHandler}`);
11183
+ }
11184
+ const routeImportChecks = [
11185
+ [config.modules.accessModule, "access policy"],
11186
+ [config.modules.repositoryModule, "repository"],
11187
+ [config.modules.storageModule, "storage adapter"],
11188
+ ];
11189
+ for (const [modulePath, label] of routeImportChecks) {
11190
+ if (!matchesImportSource(routeText, getImportSpecifierCandidates(config.entrypoints.routeHandler, modulePath))) {
11191
+ issues.push(`Files route handler does not import the configured ${label}: ${config.entrypoints.routeHandler}`);
11192
+ suggestions.add(`Import the files ${label} from ${modulePath} in the route handler.`);
11193
+ }
11194
+ }
11195
+ }
11196
+ return {
11197
+ issues,
11198
+ suggestions: [...suggestions],
11199
+ warnings,
11200
+ };
11201
+ }
11202
+ async function checkMailFeature(cwd, framework, manifest, options) {
11203
+ const issues = [];
11204
+ const suggestions = new Set();
11205
+ const warnings = [];
11206
+ const feature = manifest.features.mail;
11207
+ if (!feature || feature.status !== "active") {
11208
+ return { issues, suggestions: [], warnings };
11209
+ }
11210
+ for (const dependency of ["auth", "db"]) {
11211
+ if (manifest.features[dependency]?.status !== "active") {
11212
+ issues.push(`Mail feature requires the active ${dependency} feature.`);
11213
+ suggestions.add(`Run \`loom add ${dependency}\` before using mail.`);
11214
+ }
11215
+ }
11216
+ if (issues.length)
11217
+ return { issues, suggestions: [...suggestions], warnings };
11218
+ const { packageJson } = await readProjectPackageJson(cwd);
11219
+ const dbConfig = mergeDbConfig(framework, manifest.features.db.config);
11220
+ const config = getMailConfig(framework, dbConfig, packageJson, feature.config, manifest.features.jobs?.status === "active");
11221
+ const schema = config.schema;
11222
+ const latestSchema = getLatestManagedSchemaConfig(schema);
11223
+ if (schema.mode !== "managed-local" || schema.blueprint !== "mail") {
11224
+ issues.push("Mail must use the managed-local mail schema blueprint.");
11225
+ suggestions.add("Run `loom add mail` to restore the mail schema config.");
11226
+ }
11227
+ if (schema.exports.length !== 3) {
11228
+ issues.push("Mail schema must configure message, delivery, and event exports.");
11229
+ }
11230
+ if (schema.version > MAIL_SCHEMA_BLUEPRINT_VERSION) {
11231
+ issues.push(`Mail schema blueprint version ${schema.version} is newer than this Loom package supports.`);
11232
+ }
11233
+ else if (schema.version < MAIL_SCHEMA_BLUEPRINT_VERSION) {
11234
+ warnings.push(`Mail schema blueprint is stale: ${schema.version} < ${MAIL_SCHEMA_BLUEPRINT_VERSION}.`);
11235
+ suggestions.add("Run `loom db schemas sync`, then review and migrate the diff.");
11236
+ }
11237
+ const schemaText = await readTextIfExists((0, node_path_1.join)(cwd, schema.module));
11238
+ if (!schemaText) {
11239
+ issues.push(`Mail schema file is missing: ${schema.module}`);
11240
+ suggestions.add("Run `loom db schemas sync`.");
11241
+ }
11242
+ else {
11243
+ const currentHash = hashManagedSchemaText(schemaText);
11244
+ if (currentHash !== schema.hash) {
11245
+ if (currentHash === latestSchema.hash) {
11246
+ warnings.push(`Mail schema manifest hash is stale for ${schema.module}.`);
11247
+ suggestions.add("Run `loom db schemas sync` to refresh loom.json.");
11248
+ }
11249
+ else {
11250
+ issues.push(`Mail schema file has local edits outside the managed hash: ${schema.module}`);
11251
+ suggestions.add("Move app-specific mail schema additions to a separate file, then run `loom db schemas sync`.");
11252
+ }
11253
+ }
11254
+ const barrelText = await readTextIfExists((0, node_path_1.join)(cwd, dbConfig.dirs.schemaDir, "index.ts"));
11255
+ if (!barrelText || !schemaBarrelExportsModule(barrelText, schema, dbConfig)) {
11256
+ issues.push(`DB schema barrel does not export the managed mail schema: ${dbConfig.dirs.schemaDir}/index.ts`);
11257
+ suggestions.add("Run `loom db schemas sync`.");
11258
+ }
11259
+ }
11260
+ const requiredFiles = [
11261
+ config.modules.accessModule,
11262
+ config.modules.actionsModule,
11263
+ config.modules.repositoryModule,
11264
+ config.modules.serviceModule,
11265
+ config.modules.transportModule,
11266
+ config.entrypoints.adminPage,
11267
+ config.entrypoints.webhookRoute,
11268
+ ...(config.jobs.enabled ? [config.modules.jobModule] : []),
11269
+ ];
11270
+ for (const relativePath of requiredFiles) {
11271
+ if (!await exists((0, node_path_1.join)(cwd, relativePath))) {
11272
+ issues.push(`Mail scaffold file is missing: ${relativePath}`);
11273
+ suggestions.add("Run `loom add mail` to restore missing scaffolds.");
11274
+ }
11275
+ }
11276
+ const accessText = await readTextIfExists((0, node_path_1.join)(cwd, config.modules.accessModule));
11277
+ if (accessText && !accessText.includes("authorizeMailAdmin")) {
11278
+ issues.push(`Mail access module does not export authorizeMailAdmin: ${config.modules.accessModule}`);
11279
+ }
11280
+ const generatedDenyAll = accessText?.includes("Mail admin access policy is not configured.") ?? false;
11281
+ if (generatedDenyAll) {
11282
+ const message = `Mail admin access still uses the generated deny-all stub: ${config.modules.accessModule}`;
11283
+ if (options.production)
11284
+ issues.push(message);
11285
+ else
11286
+ warnings.push(message);
11287
+ suggestions.add("Connect authorizeMailAdmin() to the app's fresh session/admin-role check.");
11288
+ }
11289
+ const contentChecks = [
11290
+ [
11291
+ config.modules.repositoryModule,
11292
+ "@gadicc/loom/mail",
11293
+ "Mail repository is not typed against the shared mail contract",
11294
+ ],
11295
+ [
11296
+ config.modules.serviceModule,
11297
+ "createLoomMailService",
11298
+ "Mail service is not wired to the shared durable service",
11299
+ ],
11300
+ [
11301
+ config.modules.transportModule,
11302
+ "createPostalMailTransport",
11303
+ "Mail transport is not wired to the Postal adapter",
11304
+ ],
11305
+ [
11306
+ config.modules.transportModule,
11307
+ "POSTAL_WEBHOOK_PUBLIC_KEYS",
11308
+ "Mail transport does not configure Postal webhook public keys",
11309
+ ],
11310
+ [
11311
+ config.entrypoints.webhookRoute,
11312
+ "createPostalWebhookRouteHandler",
11313
+ "Mail webhook route does not use the signed shared route handler",
11314
+ ],
11315
+ [
11316
+ config.modules.actionsModule,
11317
+ "authorizeMailAdmin",
11318
+ "Mail admin actions do not enforce the app-owned admin boundary",
11319
+ ],
11320
+ [
11321
+ config.entrypoints.adminPage,
11322
+ "authorizeMailAdmin",
11323
+ "Mail admin page does not enforce the app-owned admin boundary",
11324
+ ],
11325
+ ];
11326
+ for (const [relativePath, snippet, label] of contentChecks) {
11327
+ const text = await readTextIfExists((0, node_path_1.join)(cwd, relativePath));
11328
+ if (text && !text.includes(snippet)) {
11329
+ issues.push(`${label}: ${relativePath}`);
11330
+ suggestions.add("Run `loom add mail` or update loom.json for intentional paths.");
11331
+ }
11332
+ }
11333
+ if (config.ui.adapter === "mui" &&
11334
+ !hasPackageDependency(packageJson, "@mui/material")) {
11335
+ issues.push("Mail's MUI adapter is active but @mui/material is not installed.");
11336
+ }
11337
+ if (config.jobs.enabled && manifest.features.jobs?.status !== "active") {
11338
+ warnings.push("Mail drain job is enabled while the Loom jobs feature is inactive.");
11339
+ suggestions.add("Run `loom add jobs` or disable features.mail.config.jobs.enabled.");
11340
+ }
11341
+ return { issues, suggestions: [...suggestions], warnings };
11342
+ }
11343
+ function packageDependencySpec(packageJson, dependencyName) {
11344
+ return packageJson.dependencies?.[dependencyName] ??
11345
+ packageJson.devDependencies?.[dependencyName];
11346
+ }
11347
+ function dependencyMajorMinor(spec) {
11348
+ const match = spec?.match(/(\d+)\.(\d+)/);
11349
+ return match ? `${match[1]}.${match[2]}` : undefined;
11350
+ }
11351
+ /**
11352
+ * Blanks JavaScript/TypeScript comments while keeping string and template
11353
+ * literals, so advisory text checks ignore commented-out code. Newlines are
11354
+ * kept. Regular-expression literals are not recognised; one containing a
11355
+ * quote or comment opener can confuse it, which only affects these checks.
11356
+ */
11357
+ function stripJsComments(text) {
11358
+ let output = "";
11359
+ let index = 0;
11360
+ while (index < text.length) {
11361
+ const char = text[index];
11362
+ const next = text[index + 1];
11363
+ if (char === "/" && next === "/") {
11364
+ const end = text.indexOf("\n", index);
11365
+ output += " ";
11366
+ if (end === -1)
11367
+ break;
11368
+ index = end;
11369
+ continue;
11370
+ }
11371
+ if (char === "/" && next === "*") {
11372
+ const end = text.indexOf("*/", index + 2);
11373
+ const comment = end === -1
11374
+ ? text.slice(index)
11375
+ : text.slice(index, end + 2);
11376
+ output += comment.replace(/[^\n]/g, " ");
11377
+ index += comment.length;
11378
+ continue;
11379
+ }
11380
+ if (char === '"' || char === "'" || char === "`") {
11381
+ const end = skipJsStringLiteral(text, index);
11382
+ output += text.slice(index, end);
11383
+ index = end;
11384
+ continue;
11385
+ }
11386
+ output += char;
11387
+ index += 1;
11388
+ }
11389
+ return output;
11390
+ }
11391
+ /** Returns the index just past the string literal that starts at `start`. */
11392
+ function skipJsStringLiteral(text, start) {
11393
+ const quote = text[start];
11394
+ let index = start + 1;
11395
+ while (index < text.length) {
11396
+ const char = text[index];
11397
+ if (char === "\\") {
11398
+ index += 2;
11399
+ continue;
11400
+ }
11401
+ index += 1;
11402
+ if (char === quote)
11403
+ break;
11404
+ if (quote !== "`" && char === "\n")
11405
+ break;
11406
+ }
11407
+ return Math.min(index, text.length);
11408
+ }
11409
+ /**
11410
+ * Replaces the contents of string and template literals with spaces, keeping
11411
+ * quotes, newlines, and offsets, so searches only see code.
11412
+ */
11413
+ function blankJsStrings(text) {
11414
+ let output = "";
11415
+ let index = 0;
11416
+ while (index < text.length) {
11417
+ const char = text[index];
11418
+ if (char === '"' || char === "'" || char === "`") {
11419
+ const end = skipJsStringLiteral(text, index);
11420
+ output += char + text.slice(index + 1, end).replace(/[^\n]/g, " ");
11421
+ if (end - index >= 2 && text[end - 1] === char) {
11422
+ output = output.slice(0, -1) + char;
11423
+ }
11424
+ index = end;
11425
+ continue;
11426
+ }
11427
+ output += char;
11428
+ index += 1;
11429
+ }
11430
+ return output;
11431
+ }
11432
+ /** Comment-free text plus a same-length copy whose string contents are blank. */
11433
+ function prepareJsText(text) {
11434
+ const code = stripJsComments(text);
11435
+ return { blanked: blankJsStrings(code), code };
11436
+ }
11437
+ /**
11438
+ * Reads one expression starting at `start` until a top-level `,`, `;`, or
11439
+ * closing bracket, skipping string literals. A top-level line break ends it
11440
+ * unless the neighbouring lines continue it (an operator or `.` on either
11441
+ * side), so a chained `.filter()` stays part of the expression. Expects
11442
+ * comment-free text.
11443
+ */
11444
+ function readJsExpression(text, start) {
11445
+ const blanked = blankJsStrings(text);
11446
+ let index = start;
11447
+ while (index < blanked.length && /\s/.test(blanked[index]))
11448
+ index += 1;
11449
+ const begin = index;
11450
+ let depth = 0;
11451
+ while (index < blanked.length) {
11452
+ const char = blanked[index];
11453
+ if (char === "(" || char === "[" || char === "{")
11454
+ depth += 1;
11455
+ else if (char === ")" || char === "]" || char === "}") {
11456
+ if (depth === 0)
11457
+ break;
11458
+ depth -= 1;
11459
+ }
11460
+ else if (depth === 0 && (char === "," || char === ";")) {
11461
+ break;
11462
+ }
11463
+ else if (depth === 0 && char === "\n") {
11464
+ const before = blanked.slice(begin, index).trimEnd();
11465
+ const after = blanked.slice(index).trimStart();
11466
+ const continued = /[=([{,?:+\-*/%&|^!<>~.]$/.test(before) ||
11467
+ /^(?:[.?:+\-*/%&|^<>=([]|as\s|satisfies\s)/.test(after);
11468
+ if (!continued)
11469
+ break;
11470
+ }
11471
+ index += 1;
11472
+ }
11473
+ return text.slice(begin, index).trim();
11474
+ }
11475
+ /** Index of the bracket closing the one at `open` in blanked text, or -1. */
11476
+ function findJsClosingBracket(blanked, open) {
11477
+ let depth = 0;
11478
+ for (let index = open; index < blanked.length; index += 1) {
11479
+ const char = blanked[index];
11480
+ if (char === "(" || char === "[" || char === "{")
11481
+ depth += 1;
11482
+ else if (char === ")" || char === "]" || char === "}") {
11483
+ depth -= 1;
11484
+ if (depth === 0)
11485
+ return index;
11486
+ }
11487
+ }
11488
+ return -1;
11489
+ }
11490
+ /** Splits list or object-literal contents on top-level commas. */
11491
+ function splitJsTopLevel(text) {
11492
+ const blanked = blankJsStrings(text);
11493
+ const parts = [];
11494
+ let depth = 0;
11495
+ let start = 0;
11496
+ for (let index = 0; index < blanked.length; index += 1) {
11497
+ const char = blanked[index];
11498
+ if (char === "(" || char === "[" || char === "{")
11499
+ depth += 1;
11500
+ else if (char === ")" || char === "]" || char === "}")
11501
+ depth -= 1;
11502
+ else if (char === "," && depth === 0) {
11503
+ parts.push(text.slice(start, index).trim());
11504
+ start = index + 1;
11505
+ }
11506
+ }
11507
+ parts.push(text.slice(start).trim());
11508
+ return parts.filter(Boolean);
11509
+ }
11510
+ /** Drops wrapping parentheses and a top-level `as T`/`satisfies T` suffix. */
11511
+ function unwrapJsExpression(expression) {
11512
+ let current = expression.trim();
11513
+ for (let attempt = 0; attempt < 8; attempt += 1) {
11514
+ const blanked = blankJsStrings(current);
11515
+ let depth = 0;
11516
+ let cut = -1;
11517
+ for (let index = 0; index < blanked.length; index += 1) {
11518
+ const char = blanked[index];
11519
+ if (char === "(" || char === "[" || char === "{")
11520
+ depth += 1;
11521
+ else if (char === ")" || char === "]" || char === "}")
11522
+ depth -= 1;
11523
+ else if (depth === 0 && /\s/.test(char) &&
11524
+ /^\s+(?:as|satisfies)\s/.test(blanked.slice(index))) {
11525
+ cut = index;
11526
+ break;
11527
+ }
11528
+ }
11529
+ if (cut !== -1) {
11530
+ current = current.slice(0, cut).trim();
11531
+ continue;
11532
+ }
11533
+ if (current.startsWith("(") &&
11534
+ findJsClosingBracket(blanked, 0) === current.length - 1) {
11535
+ current = current.slice(1, -1).trim();
11536
+ continue;
11537
+ }
11538
+ break;
11539
+ }
11540
+ return current;
11541
+ }
11542
+ /** `{ callee, args }` when the whole expression is one call, else null. */
11543
+ function parseWholeJsCall(expression) {
11544
+ const match = expression.match(/^([A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*)\s*\(/);
11545
+ if (!match)
11546
+ return null;
11547
+ const open = match[0].length - 1;
11548
+ if (findJsClosingBracket(blankJsStrings(expression), open) !==
11549
+ expression.length - 1) {
11550
+ return null;
11551
+ }
11552
+ return {
11553
+ args: expression.slice(open + 1, -1),
11554
+ callee: match[1].replace(/\s+/g, ""),
11555
+ };
11556
+ }
11557
+ /** The contents of a whole `[...]` or `{...}` literal, else null. */
11558
+ function wholeJsBracketContents(expression, open) {
11559
+ if (!expression.startsWith(open) ||
11560
+ findJsClosingBracket(blankJsStrings(expression), 0) !==
11561
+ expression.length - 1) {
11562
+ return null;
11563
+ }
11564
+ return expression.slice(1, -1);
11565
+ }
11566
+ /** The value of a plain string literal (no template substitutions). */
11567
+ function jsStringLiteralValue(expression) {
11568
+ const quote = expression[0];
11569
+ if (quote !== '"' && quote !== "'" && quote !== "`")
11570
+ return null;
11571
+ if (skipJsStringLiteral(expression, 0) !== expression.length)
11572
+ return null;
11573
+ const value = expression.slice(1, -1);
11574
+ return value.includes("\\") || (quote === "`" && value.includes("${"))
11575
+ ? null
11576
+ : value;
11577
+ }
11578
+ const JS_IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
11579
+ const JS_IDENTIFIER_SOURCE = String.raw `[A-Za-z_$][\w$]*`;
11580
+ const LOOM_API_KEYS_IMPORT_SOURCES = new Set([
11581
+ "@gadicc/loom",
11582
+ "@gadicc/loom/api-keys",
11583
+ "@gadicc/loom/apiKeys",
11584
+ ]);
11585
+ const NO_JS_ENV = new Map();
11586
+ async function loadJsSourceModule(context, relativePath) {
11587
+ if (!context.modules.has(relativePath)) {
11588
+ const text = await readTextIfExists((0, node_path_1.join)(context.cwd, relativePath));
11589
+ context.modules.set(relativePath, text === null
11590
+ ? null
11591
+ : { path: relativePath, prepared: prepareJsText(text) });
11592
+ }
11593
+ return context.modules.get(relativePath) ?? null;
11594
+ }
11595
+ /**
11596
+ * Value imports of a module: `imported` is `"*"` for a namespace import and
11597
+ * `"default"` for a default import.
11598
+ */
11599
+ function parseJsValueImports(module) {
11600
+ const { blanked, code } = module.prepared;
11601
+ const imports = [];
11602
+ const pattern = /(?<![\w$.])import\s+(type\s+)?([^;]*?)\s*from\s*(["'])([^"']+)\3/g;
11603
+ for (const match of code.matchAll(pattern)) {
11604
+ if (match[1] || !blanked.startsWith("import", match.index ?? 0))
11605
+ continue;
11606
+ const clause = match[2].trim();
11607
+ const source = match[4];
11608
+ const defaultImport = clause.match(/^([A-Za-z_$][\w$]*)\s*(?:,|$)/);
11609
+ if (defaultImport) {
11610
+ imports.push({ imported: "default", local: defaultImport[1], source });
11611
+ }
11612
+ const namespace = clause.match(/\*\s*as\s+([A-Za-z_$][\w$]*)/);
11613
+ if (namespace) {
11614
+ imports.push({ imported: "*", local: namespace[1], source });
11615
+ }
11616
+ const named = clause.match(/\{([^}]*)\}/);
11617
+ for (const specifier of named ? named[1].split(",") : []) {
11618
+ const trimmed = specifier.trim();
11619
+ if (!trimmed || /^type\s/.test(trimmed))
11620
+ continue;
11621
+ const [imported, local = imported] = trimmed.split(/\s+as\s+/);
11622
+ if (JS_IDENTIFIER.test(imported) && JS_IDENTIFIER.test(local)) {
11623
+ imports.push({ imported, local, source });
11624
+ }
11625
+ }
11626
+ }
11627
+ return imports;
11628
+ }
11629
+ /** Bracket depth before each offset of blanked text. */
11630
+ function jsBracketDepths(blanked) {
11631
+ const depths = new Int32Array(blanked.length + 1);
11632
+ let depth = 0;
11633
+ for (let index = 0; index < blanked.length; index += 1) {
11634
+ depths[index] = depth;
11635
+ const char = blanked[index];
11636
+ if (char === "(" || char === "[" || char === "{")
11637
+ depth += 1;
11638
+ else if (char === ")" || char === "]" || char === "}") {
11639
+ depth = Math.max(0, depth - 1);
11640
+ }
11641
+ }
11642
+ depths[blanked.length] = depth;
11643
+ return depths;
11644
+ }
11645
+ function addJsIdentifiers(names, text) {
11646
+ for (const match of text.matchAll(/[A-Za-z_$][\w$]*/g))
11647
+ names.add(match[0]);
11648
+ }
11649
+ /**
11650
+ * Offset of a function body: after a parameter list's closing parenthesis,
11651
+ * an optional return type, then `{` or `=>`. Returns -1 otherwise.
11652
+ */
11653
+ function jsFunctionBodyStart(blanked, close) {
11654
+ const after = blanked.slice(close + 1).match(/^\s*(?::[^{};=]*?)?\s*(=>|\{)/);
11655
+ if (!after)
11656
+ return -1;
11657
+ return close + 1 + after[0].length - after[1].length;
11658
+ }
11659
+ /** Start and end offsets of a function body that begins at `start`. */
11660
+ function jsFunctionBodyRange(module, start) {
11661
+ const { blanked, code } = module.prepared;
11662
+ let index = start;
11663
+ if (blanked.startsWith("=>", index)) {
11664
+ index += 2;
11665
+ while (index < blanked.length && /\s/.test(blanked[index]))
11666
+ index += 1;
11667
+ if (blanked[index] !== "{") {
11668
+ const expression = readJsExpression(code, index);
11669
+ return { end: index + expression.length, start: index };
11670
+ }
11671
+ }
11672
+ const end = findJsClosingBracket(blanked, index);
11673
+ return end === -1 ? null : { end, start: index };
11674
+ }
11675
+ /** The first parameter's name when it is a plain identifier. */
11676
+ function firstJsParameterName(parameters) {
11677
+ const [first] = splitJsTopLevel(parameters);
11678
+ const name = first?.replace(/\s*=[\s\S]*$/, "").replace(/\s*:[\s\S]*$/, "")
11679
+ .replace(/\?$/, "").trim();
11680
+ return name && JS_IDENTIFIER.test(name) ? name : undefined;
11681
+ }
11682
+ /** Computes, once per module, the facts used for identifier resolution. */
11683
+ function analyzeJsModule(module) {
11684
+ if (module.scope)
11685
+ return module.scope;
11686
+ const { blanked, code } = module.prepared;
11687
+ const depths = jsBracketDepths(blanked);
11688
+ const nestedNames = new Set();
11689
+ const topLevel = new Map();
11690
+ const functions = [];
11691
+ const addTopLevel = (name, binding) => {
11692
+ topLevel.set(name, [...(topLevel.get(name) ?? []), binding]);
11693
+ };
11694
+ for (const match of blanked.matchAll(/(?<![\w$.])(const|let|var)\s+([A-Za-z_$][\w$]*|[{[])/g)) {
11695
+ const index = match.index ?? 0;
11696
+ const target = match[2];
11697
+ const nested = depths[index] > 0;
11698
+ if (target === "{" || target === "[") {
11699
+ // Destructuring: every identifier in the pattern may be bound.
11700
+ const open = index + match[0].length - 1;
11701
+ const close = findJsClosingBracket(blanked, open);
11702
+ const names = new Set();
11703
+ addJsIdentifiers(names, blanked.slice(open, close + 1));
11704
+ for (const name of names) {
11705
+ if (nested)
11706
+ nestedNames.add(name);
11707
+ else
11708
+ addTopLevel(name, { kind: "other" });
11709
+ }
11710
+ continue;
11711
+ }
11712
+ if (nested) {
11713
+ nestedNames.add(target);
11714
+ continue;
11715
+ }
11716
+ const initializer = new RegExp(String.raw `^\s*(?::[^=;]*)?=(?![=>])`).exec(blanked.slice(index + match[0].length));
11717
+ addTopLevel(target, match[1] === "const" && initializer
11718
+ ? {
11719
+ initializer: index + match[0].length + initializer[0].length,
11720
+ kind: "const",
11721
+ }
11722
+ : { kind: "other" });
11723
+ }
11724
+ for (const match of blanked.matchAll(/(?<![\w$.])(?:function\s*\*?|class)\s+([A-Za-z_$][\w$]*)/g)) {
11725
+ if (depths[match.index ?? 0] > 0)
11726
+ nestedNames.add(match[1]);
11727
+ else
11728
+ addTopLevel(match[1], { kind: "other" });
11729
+ }
11730
+ for (const entry of parseJsValueImports(module)) {
11731
+ addTopLevel(entry.local, entry.imported === "*" || entry.imported === "default"
11732
+ ? { kind: "other" }
11733
+ : { imported: entry.imported, kind: "import", source: entry.source });
11734
+ }
11735
+ // Parameter-like lists (functions, arrows, methods, catch clauses, and
11736
+ // control-flow headers) all count as nested bindings.
11737
+ for (let index = 0; index < blanked.length; index += 1) {
11738
+ if (blanked[index] !== "(")
11739
+ continue;
11740
+ const close = findJsClosingBracket(blanked, index);
11741
+ if (close === -1 || jsFunctionBodyStart(blanked, close) === -1)
11742
+ continue;
11743
+ addJsIdentifiers(nestedNames, blanked.slice(index + 1, close));
11744
+ }
11745
+ for (const match of blanked.matchAll(/([A-Za-z_$][\w$]*)\s*=>/g)) {
11746
+ nestedNames.add(match[1]);
11747
+ }
11748
+ // Top-level functions, for factories that forward their first parameter.
11749
+ const definitions = [
11750
+ /(?<![\w$.])(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)\s*\(/g,
11751
+ /(?<![\w$.])const\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]*)?=\s*(?:async\s+)?(?:function\s*\*?\s*[\w$]*\s*)?\(/g,
11752
+ ];
11753
+ for (const pattern of definitions) {
11754
+ for (const match of blanked.matchAll(pattern)) {
11755
+ const index = match.index ?? 0;
11756
+ if (depths[index] > 0)
11757
+ continue;
11758
+ const open = index + match[0].length - 1;
11759
+ const close = findJsClosingBracket(blanked, open);
11760
+ const bodyStart = close === -1 ? -1 : jsFunctionBodyStart(blanked, close);
11761
+ const body = bodyStart === -1
11762
+ ? null
11763
+ : jsFunctionBodyRange(module, bodyStart);
11764
+ if (!body)
11765
+ continue;
11766
+ functions.push({
11767
+ bodyEnd: body.end,
11768
+ bodyStart: body.start,
11769
+ name: match[1],
11770
+ parameter: firstJsParameterName(code.slice(open + 1, close)),
11771
+ });
11772
+ }
11773
+ }
11774
+ for (const match of blanked.matchAll(/(?<![\w$.])const\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]*)?=\s*(?:async\s+)?([A-Za-z_$][\w$]*)\s*=>/g)) {
11775
+ const index = match.index ?? 0;
11776
+ if (depths[index] > 0)
11777
+ continue;
11778
+ const body = jsFunctionBodyRange(module, index + match[0].length - 2);
11779
+ if (body) {
11780
+ functions.push({
11781
+ bodyEnd: body.end,
11782
+ bodyStart: body.start,
11783
+ name: match[1],
11784
+ parameter: match[2],
11785
+ });
11786
+ }
11787
+ }
11788
+ module.scope = { functions, nestedNames, topLevel };
11789
+ return module.scope;
11790
+ }
11791
+ /**
11792
+ * Whether a module mutates `name` after binding it: member assignment
11793
+ * (`name.disabledPaths = …`, `name.length = 0`), a removing array method,
11794
+ * `delete`, `Object.assign` and similar, or reassignment.
11795
+ */
11796
+ function isJsBindingMutated(module, name) {
11797
+ const { blanked } = module.prepared;
11798
+ const id = escapeRegExp(name);
11799
+ const member = String
11800
+ .raw `(?:\s*\??\.\s*${JS_IDENTIFIER_SOURCE}|\s*\[[^\]]*\])`;
11801
+ const assignment = String
11802
+ .raw `\s*(?:[-+*/%&|^]|\*\*|<<|>>>?|\?\?|&&|\|\|)?=(?![=>])`;
11803
+ return [
11804
+ new RegExp(String.raw `(?<![\w$.])${id}${member}+${assignment}`),
11805
+ new RegExp(String
11806
+ .raw `(?<![\w$.])${id}${member}*\s*\??\.\s*(?:splice|pop|shift|fill|copyWithin)\s*\(`),
11807
+ new RegExp(String.raw `\bdelete\s+${id}\b`),
11808
+ new RegExp(String
11809
+ .raw `\bObject\s*\.\s*(?:assign|defineProperty|defineProperties|setPrototypeOf)\s*\(\s*${id}\b`),
11810
+ new RegExp(String.raw `(?<![\w$.]|(?:const|let|var)\s+)${id}${assignment}`),
11811
+ ].some((pattern) => pattern.test(blanked));
11812
+ }
11813
+ /**
11814
+ * Local names under which a module imported a Loom API-key export, including
11815
+ * aliases and `namespace.name` for namespace imports. A name that is also
11816
+ * bound elsewhere in the module is left out.
11817
+ */
11818
+ function loomApiKeyExportNames(module, exportName) {
11819
+ const scope = analyzeJsModule(module);
11820
+ const names = new Set();
11821
+ for (const entry of parseJsValueImports(module)) {
11822
+ if (!LOOM_API_KEYS_IMPORT_SOURCES.has(entry.source))
11823
+ continue;
11824
+ if (scope.nestedNames.has(entry.local) ||
11825
+ (scope.topLevel.get(entry.local)?.length ?? 0) !== 1) {
11826
+ continue;
11827
+ }
11828
+ if (entry.imported === exportName)
11829
+ names.add(entry.local);
11830
+ if (entry.imported === "*")
11831
+ names.add(`${entry.local}.${exportName}`);
11832
+ }
11833
+ return names;
11834
+ }
11835
+ /**
11836
+ * Resolves an identifier, proven or not at all: an enclosing factory
11837
+ * parameter, or the single top-level `const` (or one relative/`@/` import of
11838
+ * one while hops remain) that nothing nested shadows and nothing mutates.
11839
+ */
11840
+ async function resolveJsName(context, binding, name) {
11841
+ if (binding.env.has(name)) {
11842
+ const parameter = binding.env.get(name) ?? null;
11843
+ return parameter && !isJsBindingMutated(binding.module, name)
11844
+ ? parameter
11845
+ : null;
11846
+ }
11847
+ const module = binding.module;
11848
+ const scope = analyzeJsModule(module);
11849
+ const sites = scope.topLevel.get(name) ?? [];
11850
+ if (scope.nestedNames.has(name) || sites.length !== 1)
11851
+ return null;
11852
+ if (isJsBindingMutated(module, name))
11853
+ return null;
11854
+ const [site] = sites;
11855
+ if (site.kind === "const") {
11856
+ return {
11857
+ env: NO_JS_ENV,
11858
+ expression: readJsExpression(module.prepared.code, site.initializer),
11859
+ importHops: binding.importHops,
11860
+ module,
11861
+ };
11862
+ }
11863
+ if (site.kind !== "import" || binding.importHops <= 0)
11864
+ return null;
11865
+ const resolved = await resolveLocalSourceImport(context.cwd, context.framework, (0, node_path_1.resolve)(context.cwd, module.path), site.source);
11866
+ if (!resolved)
11867
+ return null;
11868
+ const target = await loadJsSourceModule(context, (0, node_path_1.relative)(context.cwd, resolved).replaceAll("\\", "/"));
11869
+ return target
11870
+ ? await resolveJsName(context, {
11871
+ env: NO_JS_ENV,
11872
+ expression: site.imported,
11873
+ importHops: binding.importHops - 1,
11874
+ module: target,
11875
+ }, site.imported)
11876
+ : null;
11877
+ }
11878
+ /**
11879
+ * Whether a `disabledPaths` value provably contains every api-key plugin path:
11880
+ * the whole value is Loom's helper call (any arguments) or constant, an array
11881
+ * literal that spreads either, an array literal listing every path, or
11882
+ * `<options>.disabledPaths` of options that prove it. Anything else, such as
11883
+ * a conditional or a filtered list, is unproven.
11884
+ */
11885
+ async function jsValueDisablesApiKeyPaths(context, binding, depth = 0) {
11886
+ if (depth > 12)
11887
+ return false;
11888
+ const expression = unwrapJsExpression(binding.expression);
11889
+ const compact = expression.replace(/\s+/g, "");
11890
+ const shadowed = (name) => binding.env.has(name.split(".")[0]);
11891
+ const constants = loomApiKeyExportNames(binding.module, "BETTER_AUTH_API_KEY_HTTP_PATHS");
11892
+ if (constants.has(compact) && !shadowed(compact))
11893
+ return true;
11894
+ if (JS_IDENTIFIER.test(expression)) {
11895
+ const resolved = await resolveJsName(context, binding, expression);
11896
+ return resolved
11897
+ ? await jsValueDisablesApiKeyPaths(context, resolved, depth + 1)
11898
+ : false;
11899
+ }
11900
+ const member = compact.match(/^([A-Za-z_$][\w$]*)\??\.disabledPaths$/);
11901
+ if (member) {
11902
+ return await jsOptionsDisableApiKeyPaths(context, { ...binding, expression: member[1] }, depth + 1) === true;
11903
+ }
11904
+ const call = parseWholeJsCall(expression);
11905
+ if (call) {
11906
+ return loomApiKeyExportNames(binding.module, "withBetterAuthApiKeyHttpPathsDisabled").has(call.callee) && !shadowed(call.callee);
11907
+ }
11908
+ const list = wholeJsBracketContents(expression, "[");
11909
+ if (list === null)
11910
+ return false;
11911
+ const literals = new Set();
11912
+ for (const element of splitJsTopLevel(list)) {
11913
+ if (element.startsWith("...")) {
11914
+ if (await jsValueDisablesApiKeyPaths(context, { ...binding, expression: element.slice(3) }, depth + 1)) {
11915
+ return true;
11916
+ }
11917
+ continue;
11918
+ }
11919
+ const literal = jsStringLiteralValue(element);
11920
+ if (literal !== null)
11921
+ literals.add(literal);
11922
+ }
11923
+ return betterAuth_js_1.BETTER_AUTH_API_KEY_HTTP_PATHS.every((path) => literals.has(path));
11924
+ }
11925
+ /**
11926
+ * Evaluates Better Auth options for `disabledPaths`: `true` when proven,
11927
+ * `false` when set to something unproven, `undefined` when not set. Entries
11928
+ * apply in order, so a later key or spread overrides an earlier one. Options
11929
+ * or spreads that do not resolve to an object literal, computed keys, and
11930
+ * accessors are unproven.
11931
+ */
11932
+ async function jsOptionsDisableApiKeyPaths(context, binding, depth = 0) {
11933
+ if (depth > 12)
11934
+ return false;
11935
+ const expression = unwrapJsExpression(binding.expression);
11936
+ if (JS_IDENTIFIER.test(expression)) {
11937
+ const resolved = await resolveJsName(context, binding, expression);
11938
+ return resolved
11939
+ ? await jsOptionsDisableApiKeyPaths(context, resolved, depth + 1)
11940
+ : false;
11941
+ }
11942
+ const contents = wholeJsBracketContents(expression, "{");
11943
+ if (contents === null)
11944
+ return false;
11945
+ let result;
11946
+ for (const entry of splitJsTopLevel(contents)) {
11947
+ if (entry.startsWith("...")) {
11948
+ const spread = await jsOptionsDisableApiKeyPaths(context, { ...binding, expression: entry.slice(3) }, depth + 1);
11949
+ if (spread !== undefined)
11950
+ result = spread;
11951
+ continue;
11952
+ }
11953
+ if (entry.startsWith("[")) {
11954
+ // A computed key may evaluate to "disabledPaths".
11955
+ result = false;
11956
+ continue;
11957
+ }
11958
+ if (entry === "disabledPaths") {
11959
+ result = await jsValueDisablesApiKeyPaths(context, { ...binding, expression: entry }, depth + 1);
11960
+ continue;
11961
+ }
11962
+ const property = entry.match(/^(["']?)([A-Za-z_$][\w$]*)\1\s*:/);
11963
+ if (property?.[2] === "disabledPaths") {
11964
+ result = await jsValueDisablesApiKeyPaths(context, {
11965
+ ...binding,
11966
+ expression: entry.slice(property[0].length),
11967
+ }, depth + 1);
11968
+ }
11969
+ else if (!property &&
11970
+ /^(?:async\s+|get\s+|set\s+)?["']?disabledPaths\b/.test(entry)) {
11971
+ // A getter or method cannot be checked statically.
11972
+ result = false;
11973
+ }
11974
+ }
11975
+ return result;
11976
+ }
11977
+ /**
11978
+ * Every `callee(` call outside strings and comments. Member calls such as
11979
+ * `x.callee(` count only when `allowMember` is set; a function declaration
11980
+ * `function callee(` never counts.
11981
+ */
11982
+ function findJsCalls(module, callee, options = {}) {
11983
+ const { blanked, code } = module.prepared;
11984
+ const calls = [];
11985
+ const pattern = new RegExp(`${options.allowMember ? "\\b" : "(?<![\\w$.])"}${escapeRegExp(callee)}\\s*\\(`, "g");
11986
+ for (const match of blanked.matchAll(pattern)) {
11987
+ const index = match.index ?? 0;
11988
+ if (/\bfunction\s*\*?\s*$/.test(blanked.slice(0, index)))
11989
+ continue;
11990
+ const open = index + match[0].length - 1;
11991
+ const close = findJsClosingBracket(blanked, open);
11992
+ if (close === -1)
11993
+ continue;
11994
+ calls.push({
11995
+ firstArgument: splitJsTopLevel(code.slice(open + 1, close))[0],
11996
+ open,
11997
+ });
9605
11998
  }
9606
- else {
9607
- if (!matchesImportSource(routeText, ["@gadicc/loom/next/files"])) {
9608
- issues.push(`Files route handler is not wired to @gadicc/loom/next/files: ${config.entrypoints.routeHandler}`);
11999
+ return calls;
12000
+ }
12001
+ /**
12002
+ * Reads the app's Better Auth configuration and decides whether it provably
12003
+ * disables every api-key plugin HTTP endpoint.
12004
+ *
12005
+ * Every `betterAuth(` call in the auth module and, when it imports the auth
12006
+ * module, the auth runtime module must be proven; there must be at least one.
12007
+ * A call inside a top-level factory is evaluated once per call of that factory
12008
+ * in those modules, with the factory's first parameter bound to the call's
12009
+ * argument, so options the factory ignores are not credited. Identifiers
12010
+ * resolve only to unshadowed, unmutated top-level `const` initializers,
12011
+ * following one relative or `@/` import. `modules` lists every file read.
12012
+ */
12013
+ async function inspectBetterAuthApiKeyHttpPaths(cwd, framework, manifest) {
12014
+ const authConfig = await mergeAuthConfig(cwd, framework, manifest.features.auth?.config);
12015
+ const authModulePath = authConfig.modules.authModule;
12016
+ const context = { cwd, framework, modules: new Map() };
12017
+ const authModule = await loadJsSourceModule(context, authModulePath);
12018
+ const scanned = authModule ? [authModule] : [];
12019
+ let runtimeModule = null;
12020
+ /** Local names of auth-module exports imported by the runtime module. */
12021
+ const runtimeAliases = new Map();
12022
+ const runtimePath = authConfig.modules.authRuntimeModule;
12023
+ const runtimeText = runtimePath
12024
+ ? await readTextIfExists((0, node_path_1.join)(cwd, runtimePath))
12025
+ : null;
12026
+ if (authModule && runtimePath && runtimeText &&
12027
+ matchesImportSource(runtimeText, getImportSpecifierCandidates(runtimePath, authModulePath))) {
12028
+ runtimeModule = await loadJsSourceModule(context, runtimePath);
12029
+ if (runtimeModule) {
12030
+ scanned.push(runtimeModule);
12031
+ const authModuleAbsolute = (0, node_path_1.resolve)(cwd, authModulePath);
12032
+ for (const entry of parseJsValueImports(runtimeModule)) {
12033
+ if (entry.imported === "*" || entry.imported === "default")
12034
+ continue;
12035
+ const resolved = await resolveLocalSourceImport(cwd, framework, (0, node_path_1.resolve)(cwd, runtimePath), entry.source);
12036
+ if (resolved === authModuleAbsolute) {
12037
+ runtimeAliases.set(entry.imported, entry.local);
12038
+ }
12039
+ }
9609
12040
  }
9610
- if (!routeText.includes("createFilesRouteHandlers")) {
9611
- issues.push(`Files route handler does not call createFilesRouteHandlers: ${config.entrypoints.routeHandler}`);
12041
+ }
12042
+ const factoryCalls = (module, factory) => {
12043
+ const calls = findJsCalls(module, factory).map((call) => ({
12044
+ call,
12045
+ module,
12046
+ }));
12047
+ const alias = runtimeAliases.get(factory);
12048
+ const runtime = runtimeModule;
12049
+ if (module === authModule && alias && runtime) {
12050
+ calls.push(...findJsCalls(runtime, alias).map((call) => ({
12051
+ call,
12052
+ module: runtime,
12053
+ })));
9612
12054
  }
9613
- const routeImportChecks = [
9614
- [config.modules.accessModule, "access policy"],
9615
- [config.modules.repositoryModule, "repository"],
9616
- [config.modules.storageModule, "storage adapter"],
9617
- ];
9618
- for (const [modulePath, label] of routeImportChecks) {
9619
- if (!matchesImportSource(routeText, getImportSpecifierCandidates(config.entrypoints.routeHandler, modulePath))) {
9620
- issues.push(`Files route handler does not import the configured ${label}: ${config.entrypoints.routeHandler}`);
9621
- suggestions.add(`Import the files ${label} from ${modulePath} in the route handler.`);
12055
+ return calls;
12056
+ };
12057
+ let calls = 0;
12058
+ let disabled = true;
12059
+ for (const module of scanned) {
12060
+ const functions = analyzeJsModule(module).functions;
12061
+ for (const call of findJsCalls(module, "betterAuth")) {
12062
+ calls += 1;
12063
+ const options = (env) => call.firstArgument === undefined
12064
+ ? Promise.resolve(false)
12065
+ : jsOptionsDisableApiKeyPaths(context, {
12066
+ env,
12067
+ expression: call.firstArgument,
12068
+ importHops: 1,
12069
+ module,
12070
+ }).then((result) => result === true);
12071
+ const factory = functions.find((item) => call.open >= item.bodyStart && call.open < item.bodyEnd);
12072
+ const uses = factory ? factoryCalls(module, factory.name) : [];
12073
+ let proven;
12074
+ if (factory && uses.length) {
12075
+ proven = true;
12076
+ for (const use of uses) {
12077
+ const argument = use.call.firstArgument;
12078
+ const env = new Map(factory.parameter
12079
+ ? [[
12080
+ factory.parameter,
12081
+ argument === undefined ? null : {
12082
+ env: NO_JS_ENV,
12083
+ expression: argument,
12084
+ importHops: 1,
12085
+ module: use.module,
12086
+ },
12087
+ ]]
12088
+ : []);
12089
+ if (!await options(env)) {
12090
+ proven = false;
12091
+ break;
12092
+ }
12093
+ }
12094
+ }
12095
+ else {
12096
+ proven = await options(NO_JS_ENV);
9622
12097
  }
12098
+ if (!proven)
12099
+ disabled = false;
9623
12100
  }
9624
12101
  }
12102
+ const loaded = [...context.modules.values()].filter((module) => module !== null);
9625
12103
  return {
9626
- issues,
9627
- suggestions: [...suggestions],
9628
- warnings,
12104
+ authModuleRead: authModule !== null,
12105
+ authModulePath,
12106
+ disabled: calls > 0 && disabled,
12107
+ modules: loaded,
9629
12108
  };
9630
12109
  }
9631
- async function checkMailFeature(cwd, framework, manifest, options) {
9632
- const issues = [];
9633
- const suggestions = new Set();
9634
- const warnings = [];
9635
- const feature = manifest.features.mail;
9636
- if (!feature || feature.status !== "active") {
9637
- return { issues, suggestions: [], warnings };
9638
- }
9639
- for (const dependency of ["auth", "db"]) {
9640
- if (manifest.features[dependency]?.status !== "active") {
9641
- issues.push(`Mail feature requires the active ${dependency} feature.`);
9642
- suggestions.add(`Run \`loom add ${dependency}\` before using mail.`);
9643
- }
9644
- }
9645
- if (issues.length)
9646
- return { issues, suggestions: [...suggestions], warnings };
9647
- const { packageJson } = await readProjectPackageJson(cwd);
9648
- const dbConfig = mergeDbConfig(framework, manifest.features.db.config);
9649
- const config = getMailConfig(framework, dbConfig, packageJson, feature.config, manifest.features.jobs?.status === "active");
9650
- const schema = config.schema;
9651
- const latestSchema = getLatestManagedSchemaConfig(schema);
9652
- if (schema.mode !== "managed-local" || schema.blueprint !== "mail") {
9653
- issues.push("Mail must use the managed-local mail schema blueprint.");
9654
- suggestions.add("Run `loom add mail` to restore the mail schema config.");
9655
- }
9656
- if (schema.exports.length !== 3) {
9657
- issues.push("Mail schema must configure message, delivery, and event exports.");
9658
- }
9659
- if (schema.version > MAIL_SCHEMA_BLUEPRINT_VERSION) {
9660
- issues.push(`Mail schema blueprint version ${schema.version} is newer than this Loom package supports.`);
9661
- }
9662
- else if (schema.version < MAIL_SCHEMA_BLUEPRINT_VERSION) {
9663
- warnings.push(`Mail schema blueprint is stale: ${schema.version} < ${MAIL_SCHEMA_BLUEPRINT_VERSION}.`);
9664
- suggestions.add("Run `loom db schemas sync`, then review and migrate the diff.");
9665
- }
9666
- const schemaText = await readTextIfExists((0, node_path_1.join)(cwd, schema.module));
9667
- if (!schemaText) {
9668
- issues.push(`Mail schema file is missing: ${schema.module}`);
9669
- suggestions.add("Run `loom db schemas sync`.");
12110
+ /**
12111
+ * Advisory, single-module object reading for the authorizer warnings: an
12112
+ * identifier resolves to its initializer only when the module declares that
12113
+ * name exactly once (`const`, at any depth) and nowhere else.
12114
+ */
12115
+ function readJsObjectShape(module, expression, depth = 0) {
12116
+ if (depth > 8)
12117
+ return null;
12118
+ const unwrapped = unwrapJsExpression(expression);
12119
+ if (JS_IDENTIFIER.test(unwrapped)) {
12120
+ const { blanked, code } = module.prepared;
12121
+ const id = escapeRegExp(unwrapped);
12122
+ const declarations = [
12123
+ ...blanked.matchAll(new RegExp(String
12124
+ .raw `(?<![\w$.])(?:const|let|var|function|class)\s+${id}\b|\bimport\b[^;]*\b${id}\b[^;]*\bfrom\b`, "g")),
12125
+ ];
12126
+ if (declarations.length !== 1)
12127
+ return null;
12128
+ const declaration = new RegExp(String.raw `(?<![\w$.])const\s+${id}\s*(?::[^=;]*)?=(?![=>])`).exec(blanked);
12129
+ return declaration
12130
+ ? readJsObjectShape(module, readJsExpression(code, declaration.index + declaration[0].length), depth + 1)
12131
+ : null;
9670
12132
  }
9671
- else {
9672
- const currentHash = hashManagedSchemaText(schemaText);
9673
- if (currentHash !== schema.hash) {
9674
- if (currentHash === latestSchema.hash) {
9675
- warnings.push(`Mail schema manifest hash is stale for ${schema.module}.`);
9676
- suggestions.add("Run `loom db schemas sync` to refresh loom.json.");
9677
- }
12133
+ const contents = wholeJsBracketContents(unwrapped, "{");
12134
+ if (contents === null)
12135
+ return null;
12136
+ const shape = { complete: true, entries: [] };
12137
+ for (const entry of splitJsTopLevel(contents)) {
12138
+ if (entry.startsWith("...")) {
12139
+ const spread = readJsObjectShape(module, entry.slice(3), depth + 1);
12140
+ if (!spread)
12141
+ shape.complete = false;
9678
12142
  else {
9679
- issues.push(`Mail schema file has local edits outside the managed hash: ${schema.module}`);
9680
- suggestions.add("Move app-specific mail schema additions to a separate file, then run `loom db schemas sync`.");
12143
+ shape.entries.push(...spread.entries);
12144
+ shape.complete &&= spread.complete;
9681
12145
  }
12146
+ continue;
9682
12147
  }
9683
- const barrelText = await readTextIfExists((0, node_path_1.join)(cwd, dbConfig.dirs.schemaDir, "index.ts"));
9684
- if (!barrelText || !schemaBarrelExportsModule(barrelText, schema, dbConfig)) {
9685
- issues.push(`DB schema barrel does not export the managed mail schema: ${dbConfig.dirs.schemaDir}/index.ts`);
9686
- suggestions.add("Run `loom db schemas sync`.");
12148
+ const property = entry.match(/^(["']?)([A-Za-z_$][\w$]*)\1\s*(:)?/);
12149
+ if (!property) {
12150
+ shape.complete = false;
12151
+ continue;
9687
12152
  }
12153
+ shape.entries.push({
12154
+ key: property[2],
12155
+ value: property[3] ? entry.slice(property[0].length) : property[2],
12156
+ });
9688
12157
  }
9689
- const requiredFiles = [
9690
- config.modules.accessModule,
9691
- config.modules.actionsModule,
9692
- config.modules.repositoryModule,
9693
- config.modules.serviceModule,
9694
- config.modules.transportModule,
9695
- config.entrypoints.adminPage,
9696
- config.entrypoints.webhookRoute,
9697
- ...(config.jobs.enabled ? [config.modules.jobModule] : []),
9698
- ];
9699
- for (const relativePath of requiredFiles) {
9700
- if (!await exists((0, node_path_1.join)(cwd, relativePath))) {
9701
- issues.push(`Mail scaffold file is missing: ${relativePath}`);
9702
- suggestions.add("Run `loom add mail` to restore missing scaffolds.");
12158
+ return shape;
12159
+ }
12160
+ const PERMISSION_CODE_LITERAL = String
12161
+ .raw `(["'\x60])[A-Z0-9_]*PERMISSION[A-Z0-9_]*\1`;
12162
+ const JS_EQUALITY = String.raw `(?:===|!==|==|!=)`;
12163
+ /**
12164
+ * Comparisons of an error `code` with a PERMISSION code, and a PERMISSION
12165
+ * code list checked with `.includes(…code)`. `token` is checked against
12166
+ * string-blanked text so matches inside strings do not count.
12167
+ */
12168
+ const PERMISSION_CODE_MAPPINGS = [
12169
+ {
12170
+ pattern: new RegExp(String
12171
+ .raw `\bcode\s*${JS_EQUALITY}\s*(?:${PERMISSION_CODE_LITERAL}|[\w$.?]*\b[A-Z0-9_]*PERMISSION[A-Z0-9_]*\b)`, "g"),
12172
+ token: "code",
12173
+ },
12174
+ {
12175
+ pattern: new RegExp(String
12176
+ .raw `${PERMISSION_CODE_LITERAL}\s*${JS_EQUALITY}\s*[\w$.?]*\bcode\b`, "g"),
12177
+ token: "code",
12178
+ },
12179
+ {
12180
+ pattern: new RegExp(String
12181
+ .raw `\[[^\]]*PERMISSION[^\]]*\]\s*\.\s*includes\s*\(\s*[\w$.?]*\bcode\s*\)`, "g"),
12182
+ token: "includes",
12183
+ },
12184
+ ];
12185
+ /** Whether a `switch` on an error `code` has a PERMISSION `case` label. */
12186
+ function hasPermissionCodeCase(prepared) {
12187
+ const { blanked, code } = prepared;
12188
+ for (const match of blanked.matchAll(/\bswitch\s*\(/g)) {
12189
+ const open = (match.index ?? 0) + match[0].length - 1;
12190
+ const close = findJsClosingBracket(blanked, open);
12191
+ if (close === -1 || !/\bcode\s*$/.test(blanked.slice(open + 1, close))) {
12192
+ continue;
9703
12193
  }
9704
- }
9705
- const accessText = await readTextIfExists((0, node_path_1.join)(cwd, config.modules.accessModule));
9706
- if (accessText && !accessText.includes("authorizeMailAdmin")) {
9707
- issues.push(`Mail access module does not export authorizeMailAdmin: ${config.modules.accessModule}`);
9708
- }
9709
- const generatedDenyAll = accessText?.includes("Mail admin access policy is not configured.") ?? false;
9710
- if (generatedDenyAll) {
9711
- const message = `Mail admin access still uses the generated deny-all stub: ${config.modules.accessModule}`;
9712
- if (options.production)
9713
- issues.push(message);
9714
- else
9715
- warnings.push(message);
9716
- suggestions.add("Connect authorizeMailAdmin() to the app's fresh session/admin-role check.");
9717
- }
9718
- const contentChecks = [
9719
- [
9720
- config.modules.repositoryModule,
9721
- "@gadicc/loom/mail",
9722
- "Mail repository is not typed against the shared mail contract",
9723
- ],
9724
- [
9725
- config.modules.serviceModule,
9726
- "createLoomMailService",
9727
- "Mail service is not wired to the shared durable service",
9728
- ],
9729
- [
9730
- config.modules.transportModule,
9731
- "createPostalMailTransport",
9732
- "Mail transport is not wired to the Postal adapter",
9733
- ],
9734
- [
9735
- config.modules.transportModule,
9736
- "POSTAL_WEBHOOK_PUBLIC_KEYS",
9737
- "Mail transport does not configure Postal webhook public keys",
9738
- ],
9739
- [
9740
- config.entrypoints.webhookRoute,
9741
- "createPostalWebhookRouteHandler",
9742
- "Mail webhook route does not use the signed shared route handler",
9743
- ],
9744
- [
9745
- config.modules.actionsModule,
9746
- "authorizeMailAdmin",
9747
- "Mail admin actions do not enforce the app-owned admin boundary",
9748
- ],
9749
- [
9750
- config.entrypoints.adminPage,
9751
- "authorizeMailAdmin",
9752
- "Mail admin page does not enforce the app-owned admin boundary",
9753
- ],
9754
- ];
9755
- for (const [relativePath, snippet, label] of contentChecks) {
9756
- const text = await readTextIfExists((0, node_path_1.join)(cwd, relativePath));
9757
- if (text && !text.includes(snippet)) {
9758
- issues.push(`${label}: ${relativePath}`);
9759
- suggestions.add("Run `loom add mail` or update loom.json for intentional paths.");
12194
+ const bodyOpen = blanked.indexOf("{", close);
12195
+ const bodyClose = bodyOpen === -1
12196
+ ? -1
12197
+ : findJsClosingBracket(blanked, bodyOpen);
12198
+ if (bodyClose === -1 || blanked.slice(close + 1, bodyOpen).trim())
12199
+ continue;
12200
+ const pattern = new RegExp(String.raw `\bcase\s+${PERMISSION_CODE_LITERAL}\s*:`, "g");
12201
+ for (const label of code.slice(bodyOpen, bodyClose).matchAll(pattern)) {
12202
+ if (blanked.startsWith("case", bodyOpen + (label.index ?? 0))) {
12203
+ return true;
12204
+ }
9760
12205
  }
9761
12206
  }
9762
- if (config.ui.adapter === "mui" &&
9763
- !hasPackageDependency(packageJson, "@mui/material")) {
9764
- issues.push("Mail's MUI adapter is active but @mui/material is not installed.");
12207
+ return false;
12208
+ }
12209
+ /** Advisory findings for an app-owned Better Auth api-key verifier. */
12210
+ function checkApiKeysAuthorizerText(modulePath, text) {
12211
+ const warnings = [];
12212
+ const module = {
12213
+ path: modulePath,
12214
+ prepared: prepareJsText(text),
12215
+ };
12216
+ for (const call of findJsCalls(module, "verifyApiKey", { allowMember: true })) {
12217
+ const outer = call.firstArgument === undefined
12218
+ ? null
12219
+ : readJsObjectShape(module, call.firstArgument);
12220
+ let bodyValue;
12221
+ for (const entry of outer?.entries ?? []) {
12222
+ if (entry.key === "body")
12223
+ bodyValue = entry.value;
12224
+ }
12225
+ // Skip both warnings when the body cannot be read, rather than guess.
12226
+ const body = bodyValue === undefined
12227
+ ? null
12228
+ : readJsObjectShape(module, bodyValue);
12229
+ if (!body)
12230
+ continue;
12231
+ if (body.entries.some((entry) => entry.key === "permissions")) {
12232
+ 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}`);
12233
+ }
12234
+ if (body.complete && !body.entries.some((entry) => entry.key === "configId")) {
12235
+ warnings.push(`API-key authorizer calls verifyApiKey() without configId, so keys from any api-key plugin configuration verify: ${modulePath}`);
12236
+ }
9765
12237
  }
9766
- if (config.jobs.enabled && manifest.features.jobs?.status !== "active") {
9767
- warnings.push("Mail drain job is enabled while the Loom jobs feature is inactive.");
9768
- suggestions.add("Run `loom add jobs` or disable features.mail.config.jobs.enabled.");
12238
+ const { blanked, code } = module.prepared;
12239
+ const mapsPermissionCode = hasPermissionCodeCase(module.prepared) ||
12240
+ PERMISSION_CODE_MAPPINGS.some(({ pattern, token }) => [...code.matchAll(pattern)].some((match) => {
12241
+ const tokenIndex = (match.index ?? 0) +
12242
+ match[0].search(new RegExp(`\\b${token}\\b`));
12243
+ return blanked.startsWith(token, tokenIndex);
12244
+ }));
12245
+ if (mapsPermissionCode) {
12246
+ 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}`);
9769
12247
  }
9770
- return { issues, suggestions: [...suggestions], warnings };
9771
- }
9772
- function packageDependencySpec(packageJson, dependencyName) {
9773
- return packageJson.dependencies?.[dependencyName] ??
9774
- packageJson.devDependencies?.[dependencyName];
12248
+ return [...new Set(warnings)];
9775
12249
  }
9776
- function dependencyMajorMinor(spec) {
9777
- const match = spec?.match(/(\d+)\.(\d+)/);
9778
- return match ? `${match[1]}.${match[2]}` : undefined;
12250
+ /**
12251
+ * The props an identifier belongs to in blanked text: the enclosing JSX
12252
+ * opening tag (`<Name ... >`) or, outside JSX, the innermost enclosing
12253
+ * `{...}` or `(...)`. Returns null for JSX children text.
12254
+ */
12255
+ function jsEnclosingPropsRegion(blanked, index) {
12256
+ let depth = 0;
12257
+ for (let cursor = index - 1; cursor >= 0; cursor -= 1) {
12258
+ const char = blanked[cursor];
12259
+ if (char === ")" || char === "]" || char === "}")
12260
+ depth += 1;
12261
+ else if (char === "(" || char === "[" || char === "{") {
12262
+ if (depth === 0) {
12263
+ if (char === "[")
12264
+ continue;
12265
+ const close = findJsClosingBracket(blanked, cursor);
12266
+ return blanked.slice(cursor, close === -1 ? undefined : close + 1);
12267
+ }
12268
+ depth -= 1;
12269
+ }
12270
+ else if (depth === 0 && char === ">" && blanked[cursor - 1] !== "=") {
12271
+ // The identifier follows a closed tag: it is JSX text, not a prop.
12272
+ return null;
12273
+ }
12274
+ else if (depth === 0 && char === "<" && /[A-Za-z]/.test(blanked[cursor + 1] ?? "")) {
12275
+ let end = index;
12276
+ let inner = 0;
12277
+ for (; end < blanked.length; end += 1) {
12278
+ const next = blanked[end];
12279
+ if (next === "(" || next === "[" || next === "{")
12280
+ inner += 1;
12281
+ else if (next === ")" || next === "]" || next === "}")
12282
+ inner -= 1;
12283
+ else if (inner === 0 && next === ">" && blanked[end - 1] !== "=")
12284
+ break;
12285
+ }
12286
+ return blanked.slice(cursor, end + 1);
12287
+ }
12288
+ }
12289
+ return blanked;
9779
12290
  }
9780
12291
  async function checkApiKeysFeature(cwd, framework, manifest, options) {
9781
12292
  const issues = [];
@@ -9921,6 +12432,57 @@ async function checkApiKeysFeature(cwd, framework, manifest, options) {
9921
12432
  if (issues.length || warnings.length) {
9922
12433
  suggestions.add("Run `loom add api-keys` to restore missing foundation files without overwriting custom modules.");
9923
12434
  }
12435
+ // Development hint only: the deprecated flag cannot describe Bearer or
12436
+ // header transports, so its copy can contradict the authorizer.
12437
+ if (!options.production) {
12438
+ for (const pagePath of [
12439
+ config.entrypoints.userPage,
12440
+ config.entrypoints.adminPage,
12441
+ ]) {
12442
+ const text = await readTextIfExists((0, node_path_1.join)(cwd, pagePath));
12443
+ const blanked = text ? prepareJsText(text).blanked : "";
12444
+ const uncovered = [
12445
+ ...blanked.matchAll(/\bqueryCredentialsEnabled\b/g),
12446
+ ].some((match) => {
12447
+ const region = jsEnclosingPropsRegion(blanked, match.index ?? 0);
12448
+ return region !== null && !/\bcredentialOptions\b/.test(region);
12449
+ });
12450
+ if (uncovered) {
12451
+ warnings.push(`API-key page passes the deprecated queryCredentialsEnabled without credentialOptions, so its transport guidance can contradict the authorizer: ${pagePath}`);
12452
+ suggestions.add("Pass the authorizer's credentialOptions to ApiKeysManager (and ApiKeyTransportGuidance), keeping that object in a small import-free module both import.");
12453
+ }
12454
+ }
12455
+ }
12456
+ const authorizerText = await readTextIfExists((0, node_path_1.join)(cwd, config.modules.authorizerModule));
12457
+ if (authorizerText) {
12458
+ const authorizerWarnings = checkApiKeysAuthorizerText(config.modules.authorizerModule, authorizerText);
12459
+ if (authorizerWarnings.length) {
12460
+ warnings.push(...authorizerWarnings);
12461
+ suggestions.add("Use `createBetterAuthApiKeyVerifier` from `@gadicc/loom/apiKeys`: it verifies with a configId and without permissions, then checks the permission itself.");
12462
+ }
12463
+ }
12464
+ const httpEndpoints = config.betterAuthHttpEndpoints;
12465
+ if (httpEndpoints !== undefined && httpEndpoints !== "disabled" &&
12466
+ httpEndpoints !== "app-owned") {
12467
+ issues.push(`Unknown api-keys betterAuthHttpEndpoints value in loom.json: ${JSON.stringify(httpEndpoints)}. Use "disabled" or "app-owned".`);
12468
+ }
12469
+ const authConfig = await inspectBetterAuthApiKeyHttpPaths(cwd, framework, manifest);
12470
+ if (httpEndpoints !== "app-owned" && !authConfig.disabled) {
12471
+ const location = authConfig.authModuleRead
12472
+ ? `no disabledPaths covering ${betterAuth_js_1.BETTER_AUTH_API_KEY_HTTP_PATHS.join(", ")} was proven in the Better Auth options read from: ${authConfig.modules.map((module) => module.path).join(", ")}`
12473
+ : `the auth module could not be read: ${authConfig.authModulePath}`;
12474
+ const message = `Better Auth api-key HTTP endpoints are reachable by any signed-in user (re-enable revoked keys, remove expiry, hard-delete); ${location}`;
12475
+ if (options.production)
12476
+ issues.push(message);
12477
+ else
12478
+ warnings.push(message);
12479
+ 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.');
12480
+ }
12481
+ for (const module of authConfig.modules) {
12482
+ if (/\benableSessionForAPIKeys\s*:\s*true\b/.test(module.prepared.blanked)) {
12483
+ 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}`);
12484
+ }
12485
+ }
9924
12486
  return { issues, suggestions: [...suggestions], warnings };
9925
12487
  }
9926
12488
  async function checkAuthFeature(cwd, framework, manifest) {
@@ -10711,6 +13273,22 @@ async function checkProject(cwd, env = node_process_1.default.env, options = {})
10711
13273
  else if (isLocalPackageSpec(dependency)) {
10712
13274
  issues.push(`${exports.LOOM_DEPENDENCY} is set to ${dependency}. Keep the committed dependency on a published version and use \`loom dev local <path>\` for local development instead.`);
10713
13275
  }
13276
+ else if (parseCatalogReference(dependency) && await isPnpmProject(cwd, packageJson)) {
13277
+ // Only pnpm catalogs live in pnpm-workspace.yaml (Yarn 4 has its own).
13278
+ const catalogDependency = await resolveLoomDependencySpec(cwd, packageJson);
13279
+ const unreadable = catalogDependency.catalogEntry
13280
+ ? null
13281
+ : findUnreadableLoomCatalog(await readTextIfExists((0, node_path_1.join)(cwd, "pnpm-workspace.yaml")), catalogDependency.catalogName);
13282
+ if (unreadable) {
13283
+ 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.`);
13284
+ }
13285
+ else if (!catalogDependency.catalogEntry) {
13286
+ issues.push(`${exports.LOOM_DEPENDENCY} uses \`${dependency}\`, but pnpm-workspace.yaml has no ${exports.LOOM_DEPENDENCY} entry in that catalog.`);
13287
+ }
13288
+ else if (isLocalPackageSpec(catalogDependency.catalogEntry.spec)) {
13289
+ issues.push(`The pnpm-workspace.yaml \`${catalogDependency.catalogEntry.label}\` map sets ${exports.LOOM_DEPENDENCY} to ${catalogDependency.catalogEntry.spec}. Keep the committed catalog on a published version and use \`loom dev local <path>\` for local development instead.`);
13290
+ }
13291
+ }
10714
13292
  const manifestPath = (0, node_path_1.join)(cwd, "loom.json");
10715
13293
  const manifestText = await readTextIfExists(manifestPath);
10716
13294
  let manifest = null;
@@ -10794,7 +13372,7 @@ async function checkProject(cwd, env = node_process_1.default.env, options = {})
10794
13372
  for (const suggestion of nextGuidanceCheck.suggestions) {
10795
13373
  suggestions.add(suggestion);
10796
13374
  }
10797
- const localDevCheck = await checkManagedLocalDevOverride(cwd, options.production ?? false);
13375
+ const localDevCheck = await checkManagedLocalDevOverride(cwd, options.production ?? false, options.commandRunner ?? defaultCommandRunner, env);
10798
13376
  warnings.push(...localDevCheck.warnings);
10799
13377
  issues.push(...localDevCheck.issues);
10800
13378
  for (const suggestion of localDevCheck.suggestions) {
@@ -11201,7 +13779,7 @@ async function runStatus(cwd, io) {
11201
13779
  ? parseJson(installedPackageText, (0, node_path_1.join)("node_modules", exports.LOOM_DEPENDENCY, "package.json"))
11202
13780
  : null;
11203
13781
  const workspaceText = await readTextIfExists((0, node_path_1.join)(cwd, "pnpm-workspace.yaml"));
11204
- const overrideSpec = getManagedDevOverrideSpec(workspaceText);
13782
+ const pnpmOverride = getActivePnpmLocalDevOverride(workspaceText, packageJson);
11205
13783
  let denoOverride = null;
11206
13784
  try {
11207
13785
  const tooling = await (0, projectTooling_js_1.detectProjectTooling)(cwd, manifest?.project?.tooling);
@@ -11223,13 +13801,22 @@ async function runStatus(cwd, io) {
11223
13801
  io.out(`Loom status for ${projectName}`);
11224
13802
  io.out("");
11225
13803
  io.out("Package:");
11226
- io.out(` ${projectMetadata.config}: ${dependencySpec ? `${exports.LOOM_DEPENDENCY} ${dependencySpec}` : "not declared"}`);
13804
+ const catalogEntry = parseCatalogReference(dependencySpec)
13805
+ ? findLoomCatalogEntry(workspaceText, parseCatalogReference(dependencySpec))
13806
+ : null;
13807
+ io.out(` ${projectMetadata.config}: ${dependencySpec
13808
+ ? `${exports.LOOM_DEPENDENCY} ${dependencySpec}${catalogEntry
13809
+ ? ` (${catalogEntry.spec} from pnpm-workspace.yaml ${catalogEntry.label})`
13810
+ : ""}`
13811
+ : "not declared"}`);
11227
13812
  io.out(` installed: ${installedPackage?.version ?? "not installed"}`);
11228
13813
  io.out(` local dev override: ${denoOverride
11229
13814
  ? `active (${denoOverride.config} links ${denoOverride.link})`
11230
- : overrideSpec
11231
- ? `active (${overrideSpec})`
11232
- : "none"}`);
13815
+ : pnpmOverride?.location === "pnpm-workspace.yaml"
13816
+ ? `active (${pnpmOverride.spec})`
13817
+ : pnpmOverride
13818
+ ? `active (${formatPnpmOverrideLocation(pnpmOverride.location)}: ${pnpmOverride.spec})`
13819
+ : "none"}`);
11233
13820
  io.out(` lockfile local resolution: ${localLockfileResolution ?? "none"}`);
11234
13821
  io.out("");
11235
13822
  io.out("Project:");
@@ -11369,8 +13956,9 @@ function printHelp({ out }) {
11369
13956
  out(" --local-db-host <host> Local PostgreSQL host (default: db.localtest.me).");
11370
13957
  out(" --local-db-port <port> Local PostgreSQL port (default: 5432).");
11371
13958
  out(" --replace-local-target Replace an existing development URL during local DB setup.");
13959
+ out(" --cwd <dir> Run in <dir>, resolved from the current directory.");
11372
13960
  out(" --no-color Disable colored CLI output.");
11373
- out(" --no-sync Skip automatic local-dev package sync.");
13961
+ 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.");
11374
13962
  out(" --force Force `loom dev sync` to rebuild and reinstall.");
11375
13963
  out(" --name <name> Override the resource name for `loom db neon setup`.");
11376
13964
  out(" --plan <plan> Pass a Vercel Marketplace plan id to Neon setup.");
@@ -12186,7 +14774,9 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
12186
14774
  io.err("Missing local package path. Example: `loom dev local /path/to/loom`.");
12187
14775
  return 1;
12188
14776
  }
12189
- const result = await useLocalDevPackage(cwd, pathInput);
14777
+ const result = await useLocalDevPackage(cwd, pathInput, {
14778
+ onLockWait: io.err,
14779
+ });
12190
14780
  if (result.changedFiles.length) {
12191
14781
  io.out(`Updated ${result.changedFiles.join(", ")}.`);
12192
14782
  }
@@ -12198,6 +14788,7 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
12198
14788
  }
12199
14789
  if (!options.noSync) {
12200
14790
  const syncResult = await syncLocalDevPackage(cwd, {
14791
+ onLockWait: io.err,
12201
14792
  requireActive: true,
12202
14793
  });
12203
14794
  for (const note of syncResult.notes) {
@@ -12209,6 +14800,7 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
12209
14800
  case "sync": {
12210
14801
  const result = await syncLocalDevPackage(cwd, {
12211
14802
  force: options.force,
14803
+ onLockWait: io.err,
12212
14804
  requireActive: true,
12213
14805
  });
12214
14806
  if (result.changed) {
@@ -12223,7 +14815,9 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
12223
14815
  return 0;
12224
14816
  }
12225
14817
  case "published": {
12226
- const result = await usePublishedDevPackage(cwd);
14818
+ const result = await usePublishedDevPackage(cwd, {
14819
+ onLockWait: io.err,
14820
+ });
12227
14821
  if (result.changedFiles.length) {
12228
14822
  io.out(`Updated ${result.changedFiles.join(", ")}.`);
12229
14823
  }
@@ -12301,7 +14895,7 @@ async function runCheck(cwd, strictSkills, production, network, noProgress, noCo
12301
14895
  async function runCli(args = node_process_1.default.argv.slice(2), io = {
12302
14896
  err: (line) => console.error(line),
12303
14897
  out: (line) => console.log(line),
12304
- }) {
14898
+ }, options = {}) {
12305
14899
  const parsed = (0, node_util_1.parseArgs)({
12306
14900
  allowPositionals: true,
12307
14901
  args,
@@ -12371,13 +14965,29 @@ async function runCli(args = node_process_1.default.argv.slice(2), io = {
12371
14965
  !addListOnly &&
12372
14966
  !productionCheck &&
12373
14967
  !parsed.values["no-sync"]) {
12374
- const syncResult = await syncLocalDevPackage(cwd);
14968
+ // Taken before waiting on another sync, so a refresh by that sync shows
14969
+ // up as a change and this process does not run the code it replaced.
14970
+ const loadedPackageSignature = await captureLoadedLocalLoomSignature(cwd, node_process_1.default.env);
14971
+ const syncResult = await syncLocalDevPackage(cwd, {
14972
+ commandOutput: command === "env" ? "stderr" : "stdout",
14973
+ commandRunner: options.commandRunner,
14974
+ loadedPackageSignature,
14975
+ onLockWait: io.err,
14976
+ });
12375
14977
  if (syncResult.changed) {
14978
+ // `loom env` only loads env files before spawning the wrapped command,
14979
+ // a new process that loads the refreshed package, so it continues.
14980
+ // Every other command would run this process's stale Loom code, so it
14981
+ // stops with a retry status instead of reporting success.
14982
+ const report = command === "env" ? io.err : io.out;
12376
14983
  for (const note of syncResult.notes) {
12377
- io.out(`Note: ${note}`);
14984
+ report(`Note: ${note}`);
12378
14985
  }
12379
- io.out("Re-run the original command to use the refreshed Loom package.");
12380
- return 0;
14986
+ if (command !== "env") {
14987
+ 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 ${exports.LOOM_LOCAL_DEV_RERUN_EXIT_CODE}).`);
14988
+ return exports.LOOM_LOCAL_DEV_RERUN_EXIT_CODE;
14989
+ }
14990
+ io.err("Running the wrapped command with the refreshed Loom package.");
12381
14991
  }
12382
14992
  }
12383
14993
  switch (command) {
@@ -12422,7 +15032,7 @@ async function runCli(args = node_process_1.default.argv.slice(2), io = {
12422
15032
  acceptUnknownLicense: parsed.values["accept-unknown-license"],
12423
15033
  });
12424
15034
  case "env":
12425
- return await runEnvCommand(cwd, arg1, [arg2, ...rest].filter((arg) => arg !== undefined), io);
15035
+ return await runEnvCommand(cwd, arg1, [arg2, ...rest].filter((arg) => arg !== undefined), io, { commandRunner: options.commandRunner });
12426
15036
  case "db":
12427
15037
  return await runDb(cwd, arg1, [arg2, ...rest].filter(Boolean), io, {
12428
15038
  connect: parsed.values.connect,