@gadicc/loom 1.34.0 → 1.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +108 -41
  2. package/esm/src/apiKeys/authorize.d.ts.map +1 -1
  3. package/esm/src/apiKeys/authorize.js +71 -0
  4. package/esm/src/apiKeys/betterAuth.d.ts +123 -0
  5. package/esm/src/apiKeys/betterAuth.d.ts.map +1 -0
  6. package/esm/src/apiKeys/betterAuth.js +164 -0
  7. package/esm/src/apiKeys/credentials.d.ts +37 -2
  8. package/esm/src/apiKeys/credentials.d.ts.map +1 -1
  9. package/esm/src/apiKeys/credentials.js +69 -8
  10. package/esm/src/apiKeys/lifecycle.d.ts +41 -0
  11. package/esm/src/apiKeys/lifecycle.d.ts.map +1 -0
  12. package/esm/src/apiKeys/lifecycle.js +6 -0
  13. package/esm/src/apiKeys/limits.d.ts +132 -0
  14. package/esm/src/apiKeys/limits.d.ts.map +1 -0
  15. package/esm/src/apiKeys/limits.js +246 -0
  16. package/esm/src/apiKeys/mod.d.ts +4 -0
  17. package/esm/src/apiKeys/mod.d.ts.map +1 -1
  18. package/esm/src/apiKeys/mod.js +4 -0
  19. package/esm/src/apiKeys/permissions.d.ts +56 -0
  20. package/esm/src/apiKeys/permissions.d.ts.map +1 -0
  21. package/esm/src/apiKeys/permissions.js +128 -0
  22. package/esm/src/apiKeys/policy.d.ts +3 -1
  23. package/esm/src/apiKeys/policy.d.ts.map +1 -1
  24. package/esm/src/apiKeys/policy.js +3 -1
  25. package/esm/src/apiKeys/types.d.ts +68 -1
  26. package/esm/src/apiKeys/types.d.ts.map +1 -1
  27. package/esm/src/cli/localDevLock.d.ts +97 -0
  28. package/esm/src/cli/localDevLock.d.ts.map +1 -0
  29. package/esm/src/cli/localDevLock.js +312 -0
  30. package/esm/src/cli/localDevPackage.d.ts +172 -0
  31. package/esm/src/cli/localDevPackage.d.ts.map +1 -0
  32. package/esm/src/cli/localDevPackage.js +617 -0
  33. package/esm/src/cli/migrationEnv.d.ts +19 -0
  34. package/esm/src/cli/migrationEnv.d.ts.map +1 -1
  35. package/esm/src/cli/migrationEnv.js +44 -1
  36. package/esm/src/cli/mod.d.ts +69 -4
  37. package/esm/src/cli/mod.d.ts.map +1 -1
  38. package/esm/src/cli/mod.js +2806 -437
  39. package/esm/src/cli/projectTooling.d.ts +19 -1
  40. package/esm/src/cli/projectTooling.d.ts.map +1 -1
  41. package/esm/src/cli/projectTooling.js +142 -12
  42. package/esm/src/mui/apiKeys.d.ts +123 -17
  43. package/esm/src/mui/apiKeys.d.ts.map +1 -1
  44. package/esm/src/mui/apiKeys.js +219 -78
  45. package/esm/src/mui/apiKeysView.d.ts +145 -0
  46. package/esm/src/mui/apiKeysView.d.ts.map +1 -1
  47. package/esm/src/mui/apiKeysView.js +278 -0
  48. package/esm/src/next/apiKeys/mod.d.ts +8 -1
  49. package/esm/src/next/apiKeys/mod.d.ts.map +1 -1
  50. package/esm/src/next/apiKeys/mod.js +5 -2
  51. package/package.json +2 -6
  52. package/script/src/apiKeys/authorize.d.ts.map +1 -1
  53. package/script/src/apiKeys/authorize.js +71 -0
  54. package/script/src/apiKeys/betterAuth.d.ts +123 -0
  55. package/script/src/apiKeys/betterAuth.d.ts.map +1 -0
  56. package/script/src/apiKeys/betterAuth.js +169 -0
  57. package/script/src/apiKeys/credentials.d.ts +37 -2
  58. package/script/src/apiKeys/credentials.d.ts.map +1 -1
  59. package/script/src/apiKeys/credentials.js +71 -8
  60. package/script/src/apiKeys/lifecycle.d.ts +41 -0
  61. package/script/src/apiKeys/lifecycle.d.ts.map +1 -0
  62. package/script/src/apiKeys/lifecycle.js +7 -0
  63. package/script/src/apiKeys/limits.d.ts +132 -0
  64. package/script/src/apiKeys/limits.d.ts.map +1 -0
  65. package/script/src/apiKeys/limits.js +254 -0
  66. package/script/src/apiKeys/mod.d.ts +4 -0
  67. package/script/src/apiKeys/mod.d.ts.map +1 -1
  68. package/script/src/apiKeys/mod.js +4 -0
  69. package/script/src/apiKeys/permissions.d.ts +56 -0
  70. package/script/src/apiKeys/permissions.d.ts.map +1 -0
  71. package/script/src/apiKeys/permissions.js +136 -0
  72. package/script/src/apiKeys/policy.d.ts +3 -1
  73. package/script/src/apiKeys/policy.d.ts.map +1 -1
  74. package/script/src/apiKeys/policy.js +3 -1
  75. package/script/src/apiKeys/types.d.ts +68 -1
  76. package/script/src/apiKeys/types.d.ts.map +1 -1
  77. package/script/src/cli/localDevLock.d.ts +97 -0
  78. package/script/src/cli/localDevLock.d.ts.map +1 -0
  79. package/script/src/cli/localDevLock.js +320 -0
  80. package/script/src/cli/localDevPackage.d.ts +172 -0
  81. package/script/src/cli/localDevPackage.d.ts.map +1 -0
  82. package/script/src/cli/localDevPackage.js +635 -0
  83. package/script/src/cli/migrationEnv.d.ts +19 -0
  84. package/script/src/cli/migrationEnv.d.ts.map +1 -1
  85. package/script/src/cli/migrationEnv.js +48 -1
  86. package/script/src/cli/mod.d.ts +69 -4
  87. package/script/src/cli/mod.d.ts.map +1 -1
  88. package/script/src/cli/mod.js +2807 -437
  89. package/script/src/cli/projectTooling.d.ts +19 -1
  90. package/script/src/cli/projectTooling.d.ts.map +1 -1
  91. package/script/src/cli/projectTooling.js +176 -12
  92. package/script/src/mui/apiKeys.d.ts +123 -17
  93. package/script/src/mui/apiKeys.d.ts.map +1 -1
  94. package/script/src/mui/apiKeys.js +220 -77
  95. package/script/src/mui/apiKeysView.d.ts +145 -0
  96. package/script/src/mui/apiKeysView.d.ts.map +1 -1
  97. package/script/src/mui/apiKeysView.js +291 -0
  98. package/script/src/next/apiKeys/mod.d.ts +8 -1
  99. package/script/src/next/apiKeys/mod.d.ts.map +1 -1
  100. package/script/src/next/apiKeys/mod.js +5 -2
  101. package/skills/loom/SKILL.md +111 -18
  102. package/skills/loom-api-keys/SKILL.md +101 -7
  103. package/skills/loom-auth/SKILL.md +9 -0
  104. package/skills/loom-db/SKILL.md +3 -1
@@ -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:`) 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) && /^(?:file|link):/.test(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,310 @@ async function resolveLoomCommitPublication(sourceRoot, sourceCommit, commandRun
2554
3247
  }
2555
3248
  return { status: "no-release-tag" };
2556
3249
  }
2557
- async function syncLocalDevPackage(cwd, options = {}) {
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);
3256
+ }
3257
+ catch {
3258
+ return null;
3259
+ }
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;
3278
+ }
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
+ /** The project's active local Loom link, read from its current files. */
3285
+ async function detectLocalDevLink(cwd) {
2558
3286
  const manifest = await readManifestIfExists(cwd);
2559
3287
  const tooling = await (0, projectTooling_js_1.detectProjectTooling)(cwd, manifest?.project?.tooling);
2560
3288
  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);
3289
+ const activePnpmOverride = denoMode ? null : getActivePnpmLocalDevOverride(await readTextIfExists((0, node_path_1.join)(cwd, "pnpm-workspace.yaml")), await readPackageJsonIfExists(cwd) ?? {});
2564
3290
  const denoConfig = denoMode
2565
3291
  ? await getDenoConfigForLinks(cwd, tooling)
2566
3292
  : null;
2567
3293
  const denoLink = denoConfig
2568
3294
  ? await findLocalLoomDenoLink(cwd, await (0, projectTooling_js_1.readDenoLinks)(cwd, denoConfig))
2569
3295
  : 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
- };
3296
+ return {
3297
+ active: activePnpmOverride !== null || denoLink !== null,
3298
+ activePnpmOverride,
3299
+ denoLink,
3300
+ denoMode,
3301
+ };
3302
+ }
3303
+ const NO_LOCAL_DEV_LINK_MESSAGE = "No managed Loom local-dev override is active. Run `loom dev local /path/to/loom` first.";
3304
+ async function syncLocalDevPackage(cwd, options = {}) {
3305
+ const workspacePath = (0, node_path_1.join)(cwd, "pnpm-workspace.yaml");
3306
+ const inactive = (notes = []) => ({
3307
+ buildRan: false,
3308
+ changed: false,
3309
+ notes,
3310
+ packageRefreshRan: false,
3311
+ ranCommands: [],
3312
+ });
3313
+ if (!(await detectLocalDevLink(cwd)).active) {
3314
+ if (options.requireActive)
3315
+ throw new Error(NO_LOCAL_DEV_LINK_MESSAGE);
3316
+ return inactive();
2581
3317
  }
2582
- const { packageJson } = await readProjectPackageJson(cwd);
2583
- if (!denoMode)
2584
- await ensurePnpmProject(cwd, packageJson);
2585
- const commandRunner = options.commandRunner ?? defaultCommandRunner;
2586
3318
  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");
3319
+ if (env[LOOM_DEV_SYNC_ACTIVE_ENV] === "1") {
3320
+ // A command started by a running sync (a package lifecycle script, say)
3321
+ // must not wait for the lock its own parent holds.
3322
+ return inactive([
3323
+ "Skipped the local Loom sync inside a running Loom dev sync.",
3324
+ ]);
3325
+ }
3326
+ return await (0, localDevLock_js_1.withLocalDevLock)((0, node_path_1.join)(cwd, exports.LOOM_LOCAL_DEV_LOCK_RELATIVE_PATH), async (lock) => {
3327
+ // Re-read under the lock: while this command waited, the user may have
3328
+ // switched back to the published package or linked another checkout.
3329
+ const { activePnpmOverride, denoLink, denoMode } = await detectLocalDevLink(cwd);
3330
+ if (!activePnpmOverride && !denoLink) {
3331
+ if (options.requireActive)
3332
+ throw new Error(NO_LOCAL_DEV_LINK_MESSAGE);
3333
+ return inactive([
3334
+ "The local Loom link was removed while this command waited.",
3335
+ ]);
2624
3336
  }
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");
3337
+ const { packageJson } = await readProjectPackageJson(cwd);
3338
+ if (!denoMode)
3339
+ await ensurePnpmProject(cwd, packageJson);
3340
+ const commandRunner = options.commandRunner ?? defaultCommandRunner;
3341
+ const childEnv = { ...env, [LOOM_DEV_SYNC_ACTIVE_ENV]: "1" };
3342
+ const childStdio = options.commandOutput === "stderr"
3343
+ ? "inherit-stderr"
3344
+ : "inherit";
3345
+ const notes = [];
3346
+ let pnpmVersion = null;
3347
+ // Whether this sync already changed the project, for lost-lock errors.
3348
+ let changesMade = false;
3349
+ let pnpmOverride = activePnpmOverride;
3350
+ if (pnpmOverride) {
3351
+ // Older Loom versions always wrote pnpm-workspace.yaml, which pnpm 10
3352
+ // ignores when package.json has overrides; move it where pnpm reads it.
3353
+ const placement = await resolvePnpmLocalDevOverrideLocation(cwd, packageJson, commandRunner, env);
3354
+ if (placement.conflict)
3355
+ throw new Error(placement.conflict);
3356
+ pnpmVersion = placement.pnpmVersion;
3357
+ await lock.assertHeld(false);
3358
+ const movedFiles = await placePnpmLocalDevOverride(cwd, pnpmOverride.spec, placement.location);
3359
+ if (movedFiles.length) {
3360
+ changesMade = true;
3361
+ notes.push(`Moved the Loom local-dev override to ${formatPnpmOverrideLocation(placement.location)} (updated ${movedFiles.join(", ")}).`, ...placement.notes);
3362
+ }
3363
+ pnpmOverride = {
3364
+ location: placement.location,
3365
+ spec: pnpmOverride.spec,
3366
+ };
2635
3367
  }
2636
- packageRefreshRan = true;
2637
- }
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);
3368
+ const localPackagePath = denoLink?.path ??
3369
+ fileSpecToPath(cwd, pnpmOverride.spec);
3370
+ const sourceRoot = await resolveLocalLoomSourceRoot(localPackagePath);
3371
+ const configuredSpec = (await resolveLoomDependencySpec(cwd, packageJson, { includeDev: true })).effective;
3372
+ const desiredLocalVersion = await readPackageVersion((0, node_path_1.join)(cwd, "node_modules", exports.LOOM_DEPENDENCY)) ?? versionFromDependencySpec(configuredSpec) ??
3373
+ await readPackageVersion(localPackagePath);
3374
+ const currentLocalVersion = await readPackageVersion(localPackagePath);
3375
+ const buildEnv = desiredLocalVersion && !env.NPM_PACKAGE_VERSION
3376
+ ? { ...childEnv, NPM_PACKAGE_VERSION: desiredLocalVersion }
3377
+ : childEnv;
3378
+ const ranCommands = [];
3379
+ let buildRan = false;
3380
+ if (options.force ||
3381
+ denoMode && currentLocalVersion !== desiredLocalVersion ||
3382
+ await isLocalLoomBuildStale(sourceRoot, localPackagePath)) {
3383
+ if (!sourceRoot) {
3384
+ throw new Error(`Could not find the Loom source checkout for ${localPackagePath}; cannot rebuild the local package.`);
3385
+ }
3386
+ // Run in the Loom checkout with its own deno.json (and so its own
3387
+ // deno.lock). Deno discovers config and lockfile from the working
3388
+ // directory, so a build resolved from the consumer would write a
3389
+ // deno.lock listing the consumer's package.json into its root.
3390
+ await lock.assertHeld(changesMade);
3391
+ const fingerprintBeforeBuild = await (0, localDevPackage_js_1.computeLoomSourceFingerprint)(sourceRoot);
3392
+ await runCommandOrThrow(commandRunner, "deno", ["task", "--config", (0, node_path_1.join)(sourceRoot, "deno.json"), "build"], { cwd: sourceRoot, env: buildEnv, stdio: childStdio });
3393
+ ranCommands.push("deno task build");
3394
+ buildRan = true;
3395
+ changesMade = true;
3396
+ await markLegacyLoomBuild(localPackagePath, fingerprintBeforeBuild);
3397
+ }
3398
+ const lockfilePath = (0, node_path_1.join)(cwd, "pnpm-lock.yaml");
3399
+ const lockfileBefore = pnpmOverride
3400
+ ? await readTextIfExists(lockfilePath)
3401
+ : null;
3402
+ // A lockfile that does not record the override means pnpm has not linked
3403
+ // the local package yet (for example right after `loom dev local`).
3404
+ const overridePending = pnpmOverride !== null &&
3405
+ lockfileBefore !== null &&
3406
+ !lockfileAppliesLocalDevOverride(lockfileBefore, pnpmOverride.spec);
3407
+ const importerBefore = overridePending
3408
+ ? (0, localDevPackage_js_1.getLockfileRootImporterDependency)(lockfileBefore, exports.LOOM_DEPENDENCY)
3409
+ : null;
3410
+ if (importerBefore?.version && isLocalPackageSpec(importerBefore.version) &&
3411
+ !isLocalPackageSpec(importerBefore.specifier ?? "")) {
3412
+ // Earlier Loom versions linked with `pnpm update --no-save`, which also
3413
+ // re-resolved Loom's dependencies; this sync cannot tell which of those
3414
+ // lockfile changes were intended.
3415
+ 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`.");
3416
+ }
3417
+ const packageRefreshNeeded = buildRan || overridePending ||
3418
+ await findInstalledLocalLoomDifference(cwd, localPackagePath) !== null;
3419
+ let packageRefreshRan = false;
3420
+ const warnings = [];
3421
+ if (options.force || packageRefreshNeeded) {
3422
+ await lock.assertHeld(changesMade);
3423
+ if (denoMode) {
3424
+ await runCommandOrThrow(commandRunner, "deno", ["install"], {
3425
+ cwd,
3426
+ env: childEnv,
3427
+ stdio: childStdio,
3428
+ });
3429
+ ranCommands.push("deno install");
2649
3430
  }
2650
- }
2651
- }
2652
- if (state ?? currentState) {
2653
- await writeLocalDevStateIfChanged(cwd, state ?? currentState);
2654
- }
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" : ""}.`);
2664
- }
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.");
2667
- }
3431
+ else {
3432
+ // A plain install applies the override and re-imports the local
3433
+ // directory package while reusing every other locked version.
3434
+ // `pnpm update` would re-resolve Loom's dependency subtree instead.
3435
+ await runCommandOrThrow(commandRunner, "pnpm", ["install", "--no-frozen-lockfile"], { cwd, env: childEnv, stdio: childStdio });
3436
+ ranCommands.push("pnpm install --no-frozen-lockfile");
3437
+ const lockfileAfter = await readTextIfExists(lockfilePath);
3438
+ if (lockfileAfter !== null &&
3439
+ !lockfileAppliesLocalDevOverride(lockfileAfter, pnpmOverride.spec)) {
3440
+ throw new Error(formatPnpmOverrideNotAppliedMessage(pnpmOverride, pnpmVersion));
3441
+ }
3442
+ if (lockfileBefore !== null && lockfileAfter !== null) {
3443
+ const duplicates = (0, localDevPackage_js_1.findNewPeerVariantDuplicates)(lockfileBefore, lockfileAfter);
3444
+ if (duplicates.length) {
3445
+ 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>\`.`);
3446
+ }
3447
+ }
3448
+ const remainingDifference = await findInstalledLocalLoomDifference(cwd, localPackagePath);
3449
+ if (remainingDifference) {
3450
+ warnings.push(`node_modules/${exports.LOOM_DEPENDENCY} still differs from ${localPackagePath} after pnpm install (${remainingDifference}).`);
3451
+ }
3452
+ }
3453
+ packageRefreshRan = true;
3454
+ }
3455
+ await lock.assertHeld(changesMade || packageRefreshRan);
3456
+ const currentWorkspaceText = await readTextIfExists(workspacePath);
3457
+ const currentState = denoMode
3458
+ ? await readLocalDevState(cwd)
3459
+ : await getCurrentLocalDevState(cwd, currentWorkspaceText);
3460
+ let state = null;
3461
+ if (buildRan || packageRefreshRan || !currentState) {
3462
+ state = await buildLocalDevState(localPackagePath, sourceRoot, commandRunner, env);
3463
+ // Keep which package.json maps Loom created across syncs.
3464
+ const previous = await readLocalDevState(cwd);
3465
+ if (previous?.createdPackageJsonMaps !== undefined) {
3466
+ state.createdPackageJsonMaps = previous.createdPackageJsonMaps;
3467
+ }
3468
+ if (pnpmOverride?.location === "pnpm-workspace.yaml") {
3469
+ const stateUpdate = setManagedDevStateText(await readTextIfExists(workspacePath), pnpmOverride.spec, state);
3470
+ if (stateUpdate.changed) {
3471
+ await writeTextOrDeleteIfEmpty(workspacePath, stateUpdate.text);
3472
+ }
3473
+ }
3474
+ }
3475
+ if (state ?? currentState) {
3476
+ await writeLocalDevStateIfChanged(cwd, state ?? currentState);
3477
+ }
3478
+ // Another process may have replaced the package this process loaded,
3479
+ // while it waited for the lock or just before it took it; its
3480
+ // in-process Loom code is then stale.
3481
+ let refreshedElsewhere = false;
3482
+ if (!buildRan && !packageRefreshRan &&
3483
+ options.loadedPackageSignature !== undefined) {
3484
+ const current = options.loadedPackageSignature ===
3485
+ exports.UNKNOWN_PACKAGE_SIGNATURE
3486
+ ? exports.UNKNOWN_PACKAGE_SIGNATURE
3487
+ : await (0, localDevPackage_js_1.computePackageTreeSignature)((0, node_path_1.join)(cwd, "node_modules", exports.LOOM_DEPENDENCY)).catch(() => exports.UNKNOWN_PACKAGE_SIGNATURE);
3488
+ // Without both signatures, only a sync this one waited for is
3489
+ // evidence of a replacement; assume one then rather than run code
3490
+ // that may be stale.
3491
+ refreshedElsewhere = current === exports.UNKNOWN_PACKAGE_SIGNATURE
3492
+ ? lock.waited
3493
+ : current !== options.loadedPackageSignature;
3494
+ }
3495
+ notes.push(packageRefreshRan
3496
+ ? `Local Loom package refreshed from ${localPackagePath}.`
3497
+ : refreshedElsewhere
3498
+ ? `Another Loom command refreshed the local Loom package from ${localPackagePath} after this one started.`
3499
+ : `Local Loom package is already fresh: ${localPackagePath}`, ...warnings.map((warning) => `Warning: ${warning}`));
3500
+ const recordedState = state ?? currentState;
3501
+ if (recordedState?.sourceCommit) {
3502
+ notes.push(`Recorded local Loom sync at commit ${recordedState.sourceCommit.slice(0, 12)}${recordedState.sourceDirty ? " with a dirty source tree" : ""}.`);
3503
+ }
3504
+ // What `loom dev published` will check is the build's own stamp.
3505
+ const stamp = sourceRoot
3506
+ ? await (0, localDevPackage_js_1.readLoomBuildStamp)(localPackagePath)
3507
+ : null;
3508
+ if (stamp?.legacyBuildFingerprint && !(0, localDevPackage_js_1.hasLoomBuildProvenance)(stamp)) {
3509
+ 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.`);
3510
+ }
3511
+ else if (sourceRoot && (!stamp || !(0, localDevPackage_js_1.hasLoomBuildProvenance)(stamp))) {
3512
+ 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\`.`);
3513
+ }
3514
+ else if (stamp && !stamp.sourceCommit) {
3515
+ 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\`.`);
3516
+ }
3517
+ else if (stamp && stamp.sourceDirty !== false) {
3518
+ 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\`.`);
3519
+ }
3520
+ return {
3521
+ buildRan,
3522
+ changed: buildRan || packageRefreshRan || refreshedElsewhere,
3523
+ localPackagePath,
3524
+ notes,
3525
+ packageRefreshRan,
3526
+ ranCommands,
3527
+ };
3528
+ }, localDevLockOptions(options));
3529
+ }
3530
+ function localDevLockOptions(options) {
2668
3531
  return {
2669
- buildRan,
2670
- changed: buildRan || packageRefreshRan,
2671
- localPackagePath,
2672
- notes,
2673
- packageRefreshRan,
2674
- ranCommands,
3532
+ ...options.lock,
3533
+ onWait: (holder) => options.onLockWait?.(`Waiting for another Loom dev sync (${holder
3534
+ ? `process ${holder.pid} on ${holder.hostname}`
3535
+ : "unknown process"}) to finish.`),
2675
3536
  };
2676
3537
  }
2677
- async function useLocalDevPackage(cwd, inputPath) {
3538
+ /**
3539
+ * Runs a local-dev config change under the project's sync lock, so it never
3540
+ * interleaves with a sync that reads and rewrites the same files. Commands a
3541
+ * sync started (LOOM_DEV_SYNC_ACTIVE) run without it to avoid waiting on
3542
+ * their own parent.
3543
+ */
3544
+ async function withProjectLocalDevLock(cwd, options, run) {
3545
+ const env = options.env ?? node_process_1.default.env;
3546
+ if (env[LOOM_DEV_SYNC_ACTIVE_ENV] === "1")
3547
+ return await run();
3548
+ return await (0, localDevLock_js_1.withLocalDevLock)((0, node_path_1.join)(cwd, exports.LOOM_LOCAL_DEV_LOCK_RELATIVE_PATH), run, localDevLockOptions(options));
3549
+ }
3550
+ async function useLocalDevPackage(cwd, inputPath, options = {}) {
3551
+ return await withProjectLocalDevLock(cwd, options, () => useLocalDevPackageLocked(cwd, inputPath, options));
3552
+ }
3553
+ async function useLocalDevPackageLocked(cwd, inputPath, options) {
2678
3554
  const { packageJson } = await readProjectPackageJson(cwd);
2679
3555
  const manifest = await readManifestIfExists(cwd);
2680
3556
  const tooling = await (0, projectTooling_js_1.detectProjectTooling)(cwd, manifest?.project?.tooling);
@@ -2687,8 +3563,23 @@ async function useLocalDevPackage(cwd, inputPath) {
2687
3563
  const denoConfig = await getDenoConfigForLinks(cwd, tooling);
2688
3564
  const relativeLocalPackagePath = (0, node_path_1.relative)(cwd, localPackagePath)
2689
3565
  .replaceAll("\\", "/");
3566
+ // A relink replaces the previous Loom link, found by its package name or,
3567
+ // when that package is gone, by the path dev state recorded for it.
3568
+ // Otherwise both stay linked and `loom dev published` removes only one.
3569
+ const recorded = await readLocalDevState(cwd);
3570
+ const previousLinks = [];
3571
+ for (const link of await (0, projectTooling_js_1.readDenoLinks)(cwd, denoConfig)) {
3572
+ if (link === relativeLocalPackagePath)
3573
+ continue;
3574
+ if (await findLocalLoomDenoLink(cwd, [link]) ||
3575
+ (recorded &&
3576
+ (0, node_path_1.resolve)(cwd, link) === (0, node_path_1.resolve)(cwd, recorded.localPackagePath))) {
3577
+ previousLinks.push(link);
3578
+ }
3579
+ }
2690
3580
  const update = await (0, projectTooling_js_1.mutateDenoLinks)(cwd, denoConfig, {
2691
3581
  add: relativeLocalPackagePath,
3582
+ remove: previousLinks,
2692
3583
  });
2693
3584
  const state = {
2694
3585
  dependency: exports.LOOM_DEPENDENCY,
@@ -2712,26 +3603,218 @@ async function useLocalDevPackage(cwd, inputPath) {
2712
3603
  }
2713
3604
  await ensurePnpmProject(cwd, packageJson);
2714
3605
  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
- }
3606
+ const loomDependency = await resolveLoomDependencySpec(cwd, packageJson);
3607
+ const restoreSpec = loomDependency.catalogName
3608
+ ? `${loomDependency.effective ?? publishedSpec} (from the pnpm-workspace.yaml catalog)`
3609
+ : publishedSpec;
3610
+ const placement = await resolvePnpmLocalDevOverrideLocation(cwd, packageJson, options.commandRunner ?? defaultCommandRunner, options.env ?? node_process_1.default.env);
3611
+ if (placement.conflict) {
3612
+ throw new Error(placement.conflict);
3613
+ }
3614
+ const changedFiles = await placePnpmLocalDevOverride(cwd, overrideSpec, placement.location);
2725
3615
  return {
2726
3616
  changedFiles,
2727
3617
  notes: [
2728
- `Local Loom dev override is active: ${overrideSpec}`,
3618
+ `Local Loom dev override is active in ${formatPnpmOverrideLocation(placement.location)}: ${overrideSpec}`,
3619
+ ...placement.notes,
2729
3620
  "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\`.`,
3621
+ `Before committing or shipping a published build, run \`loom dev published\`, then \`pnpm install\` to restore ${exports.LOOM_DEPENDENCY}@${restoreSpec}.`,
2731
3622
  ],
2732
3623
  };
2733
3624
  }
3625
+ /** Turns a `file:` or `link:` spec into the absolute directory it names. */
3626
+ function localSpecToPath(cwd, spec) {
3627
+ const value = spec.replace(/^(?:file|link):/, "");
3628
+ if (value.startsWith("//"))
3629
+ return new URL(`file:${value}`).pathname;
3630
+ return (0, node_path_1.resolve)(cwd, value);
3631
+ }
3632
+ /** The local spec pnpm-lock.yaml resolves Loom to, if it is local. */
3633
+ function getLockfileLocalLoomSpec(lockfileText) {
3634
+ if (!lockfileText)
3635
+ return null;
3636
+ const version = (0, localDevPackage_js_1.getLockfileRootImporterDependency)(lockfileText, exports.LOOM_DEPENDENCY)?.version?.replace(/\(.+$/, "");
3637
+ if (version !== undefined) {
3638
+ return isLocalPackageSpec(version) ? version : null;
3639
+ }
3640
+ return getLocalLoomLockfileResolution(lockfileText);
3641
+ }
3642
+ /**
3643
+ * The published Loom version pnpm has installed, when nothing local is
3644
+ * provably installed:
3645
+ * - pnpm-lock.yaml and pnpm's record of node_modules
3646
+ * (`node_modules/.pnpm/lock.yaml`) resolve Loom to the same registry
3647
+ * version, and the installed package has that version;
3648
+ * - `node_modules/@gadicc/loom` resolves into pnpm's virtual store entry for
3649
+ * that registry version, not a `file+`/`link+` entry. pnpm re-points it
3650
+ * before it writes either lockfile, so an interrupted install of a local
3651
+ * build (which carries the registry version) fails this check;
3652
+ * - when `localBuild` exists, the installed copy differs from it.
3653
+ * Null whenever any of that is uncertain, for example with
3654
+ * `node-linker=hoisted`, `enableGlobalVirtualStore` or a custom
3655
+ * `virtual-store-dir`, where no `node_modules/.pnpm` entry tells them apart.
3656
+ */
3657
+ async function findInstalledRegistryLoomVersion(cwd, lockfileText, localBuild) {
3658
+ const resolvedVersion = (text) => text
3659
+ ? (0, localDevPackage_js_1.getLockfileRootImporterDependency)(text, exports.LOOM_DEPENDENCY)?.version
3660
+ ?.replace(/\(.+$/, "") ?? null
3661
+ : null;
3662
+ const version = resolvedVersion(lockfileText);
3663
+ if (!version || isLocalPackageSpec(version))
3664
+ return null;
3665
+ const installedLockfile = await readTextIfExists((0, node_path_1.join)(cwd, "node_modules", ".pnpm", "lock.yaml"));
3666
+ if (resolvedVersion(installedLockfile) !== version)
3667
+ return null;
3668
+ const installedPath = (0, node_path_1.join)(cwd, "node_modules", exports.LOOM_DEPENDENCY);
3669
+ if (await readPackageVersion(installedPath) !== version)
3670
+ return null;
3671
+ const [store, installed] = await Promise.all([
3672
+ (0, promises_1.realpath)((0, node_path_1.join)(cwd, "node_modules", ".pnpm")).catch(() => null),
3673
+ (0, promises_1.realpath)(installedPath).catch(() => null),
3674
+ ]);
3675
+ if (!store || !installed)
3676
+ return null;
3677
+ const entry = (0, node_path_1.relative)(store, installed).split(node_path_1.sep)[0];
3678
+ const registryEntry = `@gadicc+loom@${version}`;
3679
+ if (!(entry === registryEntry || entry.startsWith(`${registryEntry}_`) ||
3680
+ entry.startsWith(`${registryEntry}(`))) {
3681
+ return null;
3682
+ }
3683
+ if (await exists((0, node_path_1.join)(localBuild, "package.json")) &&
3684
+ await findInstalledLocalLoomDifference(cwd, localBuild) === null) {
3685
+ return null;
3686
+ }
3687
+ return version;
3688
+ }
3689
+ /**
3690
+ * Lists every local Loom package the project points at, merging entries for
3691
+ * the same directory. For pnpm these are the managed overrides and the
3692
+ * lockfile's local resolution; for Deno, each link whose package is Loom,
3693
+ * or whose path dev state recorded for Loom when that package is gone.
3694
+ * Dev state only identifies such a link; it never proves anything.
3695
+ */
3696
+ async function collectLocalLoomTargets(cwd, project) {
3697
+ const targets = new Map();
3698
+ const add = async (path, source) => {
3699
+ const key = await (0, promises_1.realpath)(path).catch(() => path);
3700
+ const target = targets.get(key) ?? { path: key, sources: [] };
3701
+ target.sources.push(source);
3702
+ targets.set(key, target);
3703
+ };
3704
+ const denoLinks = [];
3705
+ if (project.denoConfig) {
3706
+ const recorded = await readLocalDevState(cwd);
3707
+ const recordedPath = recorded?.localPackagePath
3708
+ ? (0, node_path_1.resolve)(cwd, recorded.localPackagePath)
3709
+ : null;
3710
+ for (const link of await (0, projectTooling_js_1.readDenoLinks)(cwd, project.denoConfig)) {
3711
+ const path = (0, node_path_1.resolve)(cwd, link);
3712
+ if (await findLocalLoomDenoLink(cwd, [link]) || path === recordedPath) {
3713
+ denoLinks.push(link);
3714
+ await add(path, `${project.denoConfig} links ${link}`);
3715
+ }
3716
+ }
3717
+ return { denoLinks, targets: [...targets.values()] };
3718
+ }
3719
+ const workspaceSpec = getManagedDevOverrideSpec(project.workspaceText);
3720
+ if (workspaceSpec && isManagedPackageJsonLoomOverride(workspaceSpec)) {
3721
+ await add(localSpecToPath(cwd, workspaceSpec), "the pnpm-workspace.yaml override");
3722
+ }
3723
+ for (const { key, spec } of getUnmanagedPnpmWorkspaceLoomOverrides(project.workspaceText)) {
3724
+ await add(localSpecToPath(cwd, spec), `the pnpm-workspace.yaml overrides entry for ${key}`);
3725
+ }
3726
+ for (const { location, spec } of getPackageJsonLocalLoomOverrides(project.packageJson)) {
3727
+ await add(localSpecToPath(cwd, spec), `the ${formatPnpmOverrideLocation(location)} override`);
3728
+ }
3729
+ const lockfileSpec = getLockfileLocalLoomSpec(project.lockfileText);
3730
+ if (lockfileSpec?.startsWith("workspace:")) {
3731
+ 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.`);
3732
+ }
3733
+ if (lockfileSpec) {
3734
+ await add(localSpecToPath(cwd, lockfileSpec), "pnpm-lock.yaml");
3735
+ }
3736
+ return { denoLinks, targets: [...targets.values()] };
3737
+ }
3738
+ /**
3739
+ * Proves that the local Loom build this project has installed is published,
3740
+ * from that build's own stamp: the build must record a clean source commit,
3741
+ * the installed copy must match it (and, for pnpm, the lockfile must resolve
3742
+ * to it), and the commit must be covered by a release. Dev state and the
3743
+ * checkout's current git state are never consulted. Throws a refusal that
3744
+ * says what to do otherwise.
3745
+ */
3746
+ async function proveLocalLoomBuildPublished(cwd, target, options) {
3747
+ const { path } = target;
3748
+ const rerun = "then rerun `loom dev published`";
3749
+ if (!await exists((0, node_path_1.join)(path, "package.json"))) {
3750
+ const lockfileOnly = target.sources.every((source) => source === "pnpm-lock.yaml");
3751
+ throw new Error(`${path}, which ${target.sources.join(" and ")} point${target.sources.length === 1 ? "s" : ""} at, holds no built Loom package. ${lockfileOnly
3752
+ ? "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`"
3753
+ : "Restore that Loom checkout and run `loom dev sync`, or link another with `loom dev local`"}, ${rerun}.`);
3754
+ }
3755
+ const stamp = await (0, localDevPackage_js_1.readLoomBuildStamp)(path);
3756
+ if (stamp?.legacyBuildFingerprint && !(0, localDevPackage_js_1.hasLoomBuildProvenance)(stamp)) {
3757
+ 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.`);
3758
+ }
3759
+ if (!stamp || !(0, localDevPackage_js_1.hasLoomBuildProvenance)(stamp)) {
3760
+ 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}.`);
3761
+ }
3762
+ if (stamp.packageDigest !== await (0, localDevPackage_js_1.computePackageContentDigest)(path)) {
3763
+ throw new Error(`${path} was modified after it was built. Run \`loom dev sync --force\`, ${rerun}.`);
3764
+ }
3765
+ if (!stamp.sourceCommit) {
3766
+ 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}.`);
3767
+ }
3768
+ const shortCommit = stamp.sourceCommit.slice(0, 12);
3769
+ if (stamp.sourceDirty !== false) {
3770
+ throw new Error(stamp.sourceDirty
3771
+ ? `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}.`
3772
+ : `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}.`);
3773
+ }
3774
+ // Deno loads a node_modules copy whenever its effective nodeModulesDir is
3775
+ // auto or manual, and manual is its default next to a package.json. So any
3776
+ // copy is compared unless the config says "none", where Deno loads the
3777
+ // linked directory itself.
3778
+ const nodeModulesDir = options.denoConfig
3779
+ ? (0, projectTooling_js_1.parseJsonc)(await readTextIfExists((0, node_path_1.join)(cwd, options.denoConfig)) ?? "{}", options.denoConfig).nodeModulesDir
3780
+ : undefined;
3781
+ const installedCopy = !options.denoConfig ||
3782
+ (nodeModulesDir !== "none" &&
3783
+ await exists((0, node_path_1.join)(cwd, "node_modules", exports.LOOM_DEPENDENCY, "package.json")));
3784
+ const difference = installedCopy
3785
+ ? await findInstalledLocalLoomDifference(cwd, path)
3786
+ : null;
3787
+ if (difference) {
3788
+ throw new Error(`The installed Loom differs from ${path} (${difference}). Run \`loom dev sync\`, ${rerun}.`);
3789
+ }
3790
+ if (!options.denoConfig) {
3791
+ const lockfileSpec = getLockfileLocalLoomSpec(options.lockfileText);
3792
+ if (!lockfileSpec) {
3793
+ throw new Error(`pnpm-lock.yaml does not resolve ${exports.LOOM_DEPENDENCY} to ${path}. Run \`loom dev sync\`, ${rerun}.`);
3794
+ }
3795
+ }
3796
+ const sourceRoot = await resolveLocalLoomSourceRoot(path);
3797
+ if (!sourceRoot) {
3798
+ 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}.`);
3799
+ }
3800
+ const publication = await findPublishedLoomPublicationForCommit(sourceRoot, stamp.sourceCommit, options.commandRunner, options.env, options.preferredSpec, `Loom commit ${shortCommit}, which built ${path},`);
3801
+ return {
3802
+ note: publication.reason === "contains-commit"
3803
+ ? `The Loom build in ${path} comes from commit ${shortCommit}, which is included in published ${exports.LOOM_DEPENDENCY}@${publication.version}.`
3804
+ : `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.`,
3805
+ publication,
3806
+ };
3807
+ }
2734
3808
  async function usePublishedDevPackage(cwd, options = {}) {
3809
+ // A project that was never linked has nothing a sync could be changing,
3810
+ // so it does not need the lock (or a new `.loom/` directory).
3811
+ if (!(await detectLocalDevLink(cwd)).active &&
3812
+ !await exists((0, node_path_1.join)(cwd, ".loom"))) {
3813
+ return await usePublishedDevPackageLocked(cwd, options);
3814
+ }
3815
+ return await withProjectLocalDevLock(cwd, options, () => usePublishedDevPackageLocked(cwd, options));
3816
+ }
3817
+ async function usePublishedDevPackageLocked(cwd, options) {
2735
3818
  const { packageJson } = await readProjectPackageJson(cwd);
2736
3819
  const manifest = await readManifestIfExists(cwd);
2737
3820
  const tooling = await (0, projectTooling_js_1.detectProjectTooling)(cwd, manifest?.project?.tooling);
@@ -2745,75 +3828,227 @@ async function usePublishedDevPackage(cwd, options = {}) {
2745
3828
  const denoConfig = denoMode
2746
3829
  ? await getDenoConfigForLinks(cwd, tooling)
2747
3830
  : 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
3831
+ const lockfileText = denoMode
2754
3832
  ? null
2755
- : await getProjectLocalLoomLockfileResolution(cwd);
2756
- const state = denoMode
2757
- ? await readLocalDevState(cwd)
2758
- : await getCurrentLocalDevState(cwd, workspaceText);
3833
+ : await readTextIfExists((0, node_path_1.join)(cwd, "pnpm-lock.yaml"));
3834
+ const localLockfileResolution = lockfileText
3835
+ ? getLocalLoomLockfileResolution(lockfileText)
3836
+ : null;
2759
3837
  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.");
3838
+ const { denoLinks, targets } = await collectLocalLoomTargets(cwd, {
3839
+ denoConfig,
3840
+ lockfileText,
3841
+ packageJson,
3842
+ workspaceText,
3843
+ });
3844
+ if (targets.length > 1) {
3845
+ 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\`.`);
3846
+ }
3847
+ // A `catalog:` reference keeps its version in pnpm-workspace.yaml, which is
3848
+ // where the published version has to go too.
3849
+ const catalogDependency = denoMode
3850
+ ? null
3851
+ : await resolveLoomDependencySpec(cwd, packageJson);
3852
+ const catalog = catalogDependency?.catalogName ? catalogDependency : null;
3853
+ let publishedSpec = catalog
3854
+ ? catalog.effective && !isLocalPackageSpec(catalog.effective)
3855
+ ? catalog.effective
3856
+ : exports.DEFAULT_LOOM_RANGE
3857
+ : getPublishedLoomDependencySpec(packageJson);
3858
+ // A pnpm link that was never installed left nothing local to prove: the
3859
+ // app still runs the published Loom it had. Deno reads a link directly or
3860
+ // copies it into node_modules on its next install or run, so Deno links
3861
+ // are always proved.
3862
+ const registryVersion = denoMode || targets.length !== 1
3863
+ ? null
3864
+ : await findInstalledRegistryLoomVersion(cwd, lockfileText, targets[0].path);
3865
+ if (registryVersion) {
3866
+ 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}.`);
3867
+ }
3868
+ else if (targets.length === 1) {
3869
+ const proof = await proveLocalLoomBuildPublished(cwd, targets[0], {
3870
+ commandRunner,
3871
+ denoConfig,
3872
+ env,
3873
+ lockfileText,
3874
+ preferredSpec: publishedSpec,
3875
+ });
3876
+ publishedSpec = proof.publication.version;
3877
+ notes.push(proof.note);
3878
+ }
3879
+ const changedFiles = [];
3880
+ let catalogChanged = false;
3881
+ if (catalog) {
3882
+ const currentText = await readTextIfExists(workspacePath);
3883
+ const entry = findLoomCatalogEntry(currentText, catalog.catalogName);
3884
+ const unreadable = entry
3885
+ ? null
3886
+ : findUnreadableLoomCatalog(currentText, catalog.catalogName);
3887
+ if (unreadable) {
3888
+ 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
3889
  }
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}.`);
3890
+ else if (!entry) {
3891
+ 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
3892
  }
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.`);
3893
+ else if (entry.spec !== publishedSpec) {
3894
+ const updated = setLoomCatalogEntryText(currentText, entry, publishedSpec);
3895
+ if (updated !== null) {
3896
+ await (0, promises_1.writeFile)(workspacePath, updated, "utf8");
3897
+ changedFiles.push("pnpm-workspace.yaml");
3898
+ catalogChanged = true;
3899
+ }
2776
3900
  }
2777
3901
  }
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.");
3902
+ else {
3903
+ const dependencyUpdate = await (0, projectTooling_js_1.mutateProjectDependencies)(cwd, tooling.dependencies, {
3904
+ dependencies: { [exports.LOOM_DEPENDENCY]: publishedSpec },
3905
+ replace: true,
3906
+ });
3907
+ if (dependencyUpdate.changed) {
3908
+ changedFiles.push(dependencyUpdate.config);
3909
+ }
2780
3910
  }
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 })
3911
+ const denoUpdate = denoConfig && denoLinks.length
3912
+ ? await (0, projectTooling_js_1.mutateDenoLinks)(cwd, denoConfig, { remove: denoLinks })
2787
3913
  : 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);
2794
- }
2795
- if (update.changed) {
2796
- if (denoMode) {
2797
- changedFiles.push(denoConfig);
3914
+ let overrideRemoved = false;
3915
+ if (denoMode) {
3916
+ if (denoUpdate?.changed) {
3917
+ // The dependency pin may have changed the same file already.
3918
+ if (!changedFiles.includes(denoConfig))
3919
+ changedFiles.push(denoConfig);
3920
+ overrideRemoved = true;
2798
3921
  }
2799
- else {
2800
- await writeTextOrDeleteIfEmpty(workspacePath, update.text);
2801
- changedFiles.push("pnpm-workspace.yaml");
3922
+ }
3923
+ else {
3924
+ for (const file of await clearPnpmLocalDevOverrides(cwd)) {
3925
+ if (!changedFiles.includes(file))
3926
+ changedFiles.push(file);
3927
+ overrideRemoved = true;
3928
+ }
3929
+ // Entries written by hand point pnpm at a local Loom just the same.
3930
+ const workspaceNow = await readTextIfExists(workspacePath);
3931
+ if (workspaceNow && !getManagedDevOverrideBlockText(workspaceNow)) {
3932
+ const update = removeUnmanagedPnpmWorkspaceLoomOverrides(workspaceNow);
3933
+ if (update.changed) {
3934
+ await writeTextOrDeleteIfEmpty(workspacePath, update.text);
3935
+ if (!changedFiles.includes("pnpm-workspace.yaml")) {
3936
+ changedFiles.push("pnpm-workspace.yaml");
3937
+ }
3938
+ overrideRemoved = true;
3939
+ }
3940
+ for (const { key, spec } of update.kept) {
3941
+ 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\`.`);
3942
+ }
2802
3943
  }
2803
3944
  }
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.`);
3945
+ if (denoMode) {
3946
+ if (overrideRemoved || localLockfileResolution) {
3947
+ notes.push(`Run \`deno install\` in this project to return node_modules and deno.lock to published ${exports.LOOM_DEPENDENCY}@${publishedSpec}.`);
3948
+ }
2808
3949
  }
2809
- if (localLockfileResolution) {
2810
- notes.push(`pnpm-lock.yaml still resolves ${exports.LOOM_DEPENDENCY} to ${localLockfileResolution} until that update is run.`);
3950
+ else if (overrideRemoved || localLockfileResolution) {
3951
+ const importer = lockfileText
3952
+ ? (0, localDevPackage_js_1.getLockfileRootImporterDependency)(lockfileText, exports.LOOM_DEPENDENCY)
3953
+ : null;
3954
+ // Earlier Loom versions linked through `pnpm update --no-save`, which
3955
+ // leaves the published specifier with a local version. While that
3956
+ // specifier still matches package.json, pnpm install treats the lockfile
3957
+ // as up to date and keeps the local resolution.
3958
+ const specifierUnchanged = catalog
3959
+ ? importer?.specifier === catalog.raw && !catalogChanged
3960
+ : importer?.specifier === publishedSpec;
3961
+ const legacyLocalResolution = importer?.version &&
3962
+ isLocalPackageSpec(importer.version) && specifierUnchanged
3963
+ ? localLockfileResolution ?? importer.version
3964
+ : null;
3965
+ if (legacyLocalResolution && catalog) {
3966
+ 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\`.`);
3967
+ }
3968
+ else if (legacyLocalResolution) {
3969
+ const pinCommand = isExactSemverVersion(publishedSpec)
3970
+ ? `\`${dependencyRefreshCommand(tooling.dependencies, exports.LOOM_DEPENDENCY, publishedSpec, { pnpmWorkspaceRoot: await pnpmWorkspaceDeclaresPackages(cwd) })}\``
3971
+ : `\`pnpm add --save-exact ${exports.LOOM_DEPENDENCY}@<version>\` with the exact version to ship`;
3972
+ 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).`);
3973
+ }
3974
+ else {
3975
+ 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.`);
3976
+ if (localLockfileResolution) {
3977
+ notes.push(`pnpm-lock.yaml still resolves ${exports.LOOM_DEPENDENCY} to ${localLockfileResolution} until that install is run.`);
3978
+ }
3979
+ }
2811
3980
  }
2812
3981
  return {
2813
3982
  changedFiles,
2814
3983
  notes,
2815
3984
  };
2816
3985
  }
3986
+ /** Removes every managed local Loom override from a pnpm project. */
3987
+ async function clearPnpmLocalDevOverrides(cwd) {
3988
+ const changedFiles = [];
3989
+ const workspacePath = (0, node_path_1.join)(cwd, "pnpm-workspace.yaml");
3990
+ const workspaceUpdate = clearPnpmWorkspaceLocalDevText(await readTextIfExists(workspacePath));
3991
+ if (workspaceUpdate.changed) {
3992
+ await writeTextOrDeleteIfEmpty(workspacePath, workspaceUpdate.text);
3993
+ changedFiles.push("pnpm-workspace.yaml");
3994
+ }
3995
+ for (const { field } of PACKAGE_JSON_OVERRIDE_LOCATIONS) {
3996
+ if (await removePackageJsonLoomOverride(cwd, field) &&
3997
+ !changedFiles.includes("package.json")) {
3998
+ changedFiles.push("package.json");
3999
+ }
4000
+ }
4001
+ // Flags for maps whose Loom entry was already gone would otherwise
4002
+ // outlive the link and claim maps the project has since added.
4003
+ await writeCreatedPackageJsonMaps(cwd, {});
4004
+ return changedFiles;
4005
+ }
4006
+ function getRawPackageJsonMap(packageJson, field) {
4007
+ return field === "resolutions"
4008
+ ? packageJson.resolutions
4009
+ : packageJson.pnpm?.overrides;
4010
+ }
4011
+ async function readCreatedPackageJsonMaps(cwd) {
4012
+ return { ...(await readLocalDevState(cwd))?.createdPackageJsonMaps };
4013
+ }
4014
+ async function writeCreatedPackageJsonMaps(cwd, created, overrideSpec) {
4015
+ const state = await readLocalDevState(cwd);
4016
+ const { createdPackageJsonMaps: _previous, ...rest } = state ?? {
4017
+ dependency: exports.LOOM_DEPENDENCY,
4018
+ localPackagePath: overrideSpec ? fileSpecToPath(cwd, overrideSpec) : "",
4019
+ syncedAt: new Date().toISOString(),
4020
+ version: 1,
4021
+ };
4022
+ if (!state && Object.keys(created).length === 0)
4023
+ return;
4024
+ await writeLocalDevStateIfChanged(cwd, Object.keys(created).length
4025
+ ? { ...rest, createdPackageJsonMaps: created }
4026
+ : rest);
4027
+ }
4028
+ /**
4029
+ * Removes Loom's managed (`file:`) override from one package.json map with
4030
+ * a minimal text edit. The map (and the `pnpm` object) is removed as well
4031
+ * only when it ends up empty and dev state records that Loom created it;
4032
+ * maps the project already had, or whose origin is unknown, always stay.
4033
+ * Never writes back a whole-file snapshot. Returns whether package.json
4034
+ * changed.
4035
+ */
4036
+ async function removePackageJsonLoomOverride(cwd, field) {
4037
+ const { packageJson } = await readProjectPackageJson(cwd);
4038
+ if (!isManagedPackageJsonLoomOverride(getPackageJsonOverrideMap(packageJson, field)[exports.LOOM_DEPENDENCY])) {
4039
+ return false;
4040
+ }
4041
+ const created = await readCreatedPackageJsonMaps(cwd);
4042
+ const update = await (0, projectTooling_js_1.mutatePackageJsonOverride)(cwd, field, exports.LOOM_DEPENDENCY, undefined, {
4043
+ removeEmptyMap: created[field] === true,
4044
+ removeEmptyPnpm: field === "pnpm.overrides" && created.pnpm === true,
4045
+ });
4046
+ delete created[field];
4047
+ if (field === "pnpm.overrides")
4048
+ delete created.pnpm;
4049
+ await writeCreatedPackageJsonMaps(cwd, created);
4050
+ return update.changed;
4051
+ }
2817
4052
  async function ensureManagedAgentsFile(cwd) {
2818
4053
  const relativePath = "AGENTS.md";
2819
4054
  const agentsPath = (0, node_path_1.join)(cwd, relativePath);
@@ -3028,7 +4263,15 @@ async function checkManagedAgentsFile(cwd) {
3028
4263
  warnings: [],
3029
4264
  };
3030
4265
  }
3031
- async function checkManagedLocalDevOverride(cwd, production = false) {
4266
+ /** Matches override keys that select Loom, including pnpm/yarn selectors. */
4267
+ function overrideKeyTargetsLoom(key) {
4268
+ const target = key.split(">").pop().trim();
4269
+ return target === exports.LOOM_DEPENDENCY ||
4270
+ target.startsWith(`${exports.LOOM_DEPENDENCY}@`) ||
4271
+ target.endsWith(`/${exports.LOOM_DEPENDENCY}`) ||
4272
+ target.includes(`/${exports.LOOM_DEPENDENCY}@`);
4273
+ }
4274
+ async function checkManagedLocalDevOverride(cwd, production, commandRunner, env) {
3032
4275
  const manifest = await readManifestIfExists(cwd);
3033
4276
  let denoLink = null;
3034
4277
  let denoConfig = null;
@@ -3043,8 +4286,17 @@ async function checkManagedLocalDevOverride(cwd, production = false) {
3043
4286
  // The main project tooling check reports invalid configuration separately.
3044
4287
  }
3045
4288
  const workspaceText = await readTextIfExists((0, node_path_1.join)(cwd, "pnpm-workspace.yaml"));
3046
- const overrideSpec = getManagedDevOverrideSpec(workspaceText);
3047
- if (!overrideSpec && !denoLink) {
4289
+ const packageJson = denoLink ? null : await readPackageJsonIfExists(cwd);
4290
+ const workspaceSpec = getManagedDevOverrideSpec(workspaceText);
4291
+ // Any local spec for Loom in a package.json override map is a local-dev
4292
+ // link, whoever wrote it and whatever selector it uses, and must not ship.
4293
+ const packageJsonOverride = packageJson
4294
+ ? PACKAGE_JSON_OVERRIDE_LOCATIONS.flatMap(({ field, location }) => Object.entries(getPackageJsonOverrideMap(packageJson, field)).flatMap(([key, spec]) => overrideKeyTargetsLoom(key) && typeof spec === "string" &&
4295
+ isLocalPackageSpec(spec)
4296
+ ? [`${formatPnpmOverrideLocation(location)}: ${spec}`]
4297
+ : []))[0]
4298
+ : undefined;
4299
+ if (!workspaceSpec && !packageJsonOverride && !denoLink) {
3048
4300
  return {
3049
4301
  issues: [],
3050
4302
  suggestions: [],
@@ -3053,19 +4305,45 @@ async function checkManagedLocalDevOverride(cwd, production = false) {
3053
4305
  }
3054
4306
  const location = denoLink
3055
4307
  ? `${denoConfig} links: ${denoLink.link}`
3056
- : `pnpm-workspace.yaml: ${overrideSpec}`;
4308
+ : workspaceSpec
4309
+ ? `pnpm-workspace.yaml: ${workspaceSpec}`
4310
+ : packageJsonOverride;
3057
4311
  const restore = denoLink
3058
4312
  ? "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.`;
4313
+ : "Run `loom dev published`, then run `pnpm install` (or the command it prints) before committing or shipping a published build.";
4314
+ const warnings = [];
4315
+ const suggestions = [restore];
4316
+ const activePnpmOverride = packageJson
4317
+ ? getActivePnpmLocalDevOverride(workspaceText, packageJson)
4318
+ : null;
4319
+ if (activePnpmOverride && packageJson) {
4320
+ // Use the same placement decision as `loom dev sync`, so the advice here
4321
+ // is exactly what the next sync does.
4322
+ const placement = await resolvePnpmLocalDevOverrideLocation(cwd, packageJson, commandRunner, env);
4323
+ const pnpmLabel = placement.pnpmVersion === null
4324
+ ? "pnpm (version unknown, assumed 10.5.1 or newer)"
4325
+ : `pnpm ${placement.pnpmVersion}`;
4326
+ if (placement.conflict) {
4327
+ warnings.push(placement.conflict);
4328
+ }
4329
+ else if (activePnpmOverride.location === "pnpm-workspace.yaml"
4330
+ ? placement.location !== "pnpm-workspace.yaml"
4331
+ : placement.location === "pnpm-workspace.yaml" &&
4332
+ placement.pnpmMajor !== null && placement.pnpmMajor >= 11) {
4333
+ warnings.push(`${pnpmLabel} does not apply the Loom override in ${formatPnpmOverrideLocation(activePnpmOverride.location)}, so this app may still use the published Loom package.`);
4334
+ suggestions.push(`Run \`loom dev sync\` to move the override to ${formatPnpmOverrideLocation(placement.location)}, where pnpm applies it.`);
4335
+ }
4336
+ }
3060
4337
  return {
3061
4338
  issues: production
3062
4339
  ? [
3063
4340
  `Local Loom dev override is active in ${location}`,
3064
4341
  ]
3065
4342
  : [],
3066
- suggestions: [restore],
3067
- warnings: production ? [] : [
4343
+ suggestions,
4344
+ warnings: production ? warnings : [
3068
4345
  `Local Loom dev override is active in ${location}`,
4346
+ ...warnings,
3069
4347
  ],
3070
4348
  };
3071
4349
  }
@@ -3104,7 +4382,6 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
3104
4382
  const issues = [];
3105
4383
  const suggestions = new Set();
3106
4384
  const warnings = [];
3107
- const dependency = packageJson.dependencies?.[exports.LOOM_DEPENDENCY];
3108
4385
  const production = options.production;
3109
4386
  const projectMetadata = await (0, projectTooling_js_1.readProjectPackageMetadata)(cwd);
3110
4387
  let dependencyTooling = {
@@ -3118,8 +4395,38 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
3118
4395
  catch {
3119
4396
  // The main tooling check owns the validation error; release hints can fall back.
3120
4397
  }
4398
+ // A pnpm `catalog:` reference pins Loom in pnpm-workspace.yaml instead.
4399
+ // Other managers' catalogs (Yarn 4) are not read.
4400
+ const loomDependency = await resolveLoomDependencySpec(cwd, packageJson);
4401
+ const dependency = dependencyTooling.manager === "pnpm"
4402
+ ? loomDependency.effective
4403
+ : loomDependency.raw;
3121
4404
  const localLockfileResolution = await getProjectLocalLoomLockfileResolution(cwd);
3122
4405
  const devState = await readLocalDevState(cwd);
4406
+ const refreshOptions = {
4407
+ pnpmWorkspaceRoot: await pnpmWorkspaceDeclaresPackages(cwd),
4408
+ };
4409
+ const catalogName = dependencyTooling.manager === "pnpm"
4410
+ ? loomDependency.catalogName
4411
+ : null;
4412
+ const pinLocation = catalogName
4413
+ ? `the pnpm-workspace.yaml \`${loomDependency.catalogEntry?.label ?? "catalog:"}\` map`
4414
+ : dependencyTooling.config;
4415
+ // A pnpm pin change is a manual package.json edit plus `pnpm install`,
4416
+ // which gives the same lockfile as `pnpm add --save-exact` without
4417
+ // re-sorting package.json. Only a lockfile an older `pnpm update --no-save`
4418
+ // link left behind, under an unchanged pin, needs `pnpm add`.
4419
+ const pinSuggestion = (version) => catalogName
4420
+ ? formatLoomCatalogPinAdvice(loomDependency.catalogEntry, catalogName, version)
4421
+ : dependencyTooling.manager !== "pnpm"
4422
+ ? `Run ${dependencyRefreshCommand(dependencyTooling, exports.LOOM_DEPENDENCY, version, refreshOptions)}.`
4423
+ : version === dependency
4424
+ ? `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).`
4425
+ : `Set ${exports.LOOM_DEPENDENCY} to ${version} in package.json, then run \`pnpm install\`.`;
4426
+ // While the override is active it forces the local package whatever the
4427
+ // pin says, so it has to be removed before any refresh can help.
4428
+ const pnpmOverrideActive = dependencyTooling.manager === "pnpm" &&
4429
+ getActivePnpmLocalDevOverride(await readTextIfExists((0, node_path_1.join)(cwd, "pnpm-workspace.yaml")), packageJson) !== null;
3123
4430
  if (localLockfileResolution) {
3124
4431
  addReleaseCheckMessage(issues, warnings, production, `pnpm-lock.yaml resolves @gadicc/loom to a local package: ${localLockfileResolution}`);
3125
4432
  suggestions.add("Run `loom dev published`, then refresh the lockfile with the published @gadicc/loom version before production build.");
@@ -3151,8 +4458,10 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
3151
4458
  "package-equivalent"
3152
4459
  ? `package-relevant files match ${exports.LOOM_DEPENDENCY}@${publication.version}`
3153
4460
  : `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)}.`);
4461
+ addReleaseCheckMessage(issues, warnings, production, `This app was last synced against Loom commit ${shortCommit}; ${publicationDescription}, but ${pinLocation} is pinned to ${dependency}.`);
4462
+ suggestions.add(pnpmOverrideActive
4463
+ ? "Run `loom dev published`, which pins the covering version, then run `pnpm install`."
4464
+ : pinSuggestion(publication.version));
3156
4465
  }
3157
4466
  else if (localLockfileResolution) {
3158
4467
  const publicationDescription = publication.reason ===
@@ -3160,7 +4469,13 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
3160
4469
  ? `has no package-relevant changes after ${publication.tag}, so ${exports.LOOM_DEPENDENCY}@${publication.version} covers it`
3161
4470
  : `is published as ${exports.LOOM_DEPENDENCY}@${publication.version}`;
3162
4471
  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)}.`);
4472
+ suggestions.add(pnpmOverrideActive
4473
+ ? "Run `loom dev published`, which pins the covering version, then run `pnpm install`."
4474
+ : catalogName && dependency === publication.version
4475
+ // pnpm keeps a local resolution while the catalog version
4476
+ // it was linked under is unchanged.
4477
+ ? "Restore pnpm-lock.yaml from git and run `pnpm install`."
4478
+ : pinSuggestion(publication.version));
3164
4479
  }
3165
4480
  break;
3166
4481
  }
@@ -3185,8 +4500,12 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
3185
4500
  else {
3186
4501
  const installedPackage = parseJson(installedPackageText, (0, node_path_1.join)("node_modules", exports.LOOM_DEPENDENCY, "package.json"));
3187
4502
  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)}.`);
4503
+ issues.push(`Installed ${exports.LOOM_DEPENDENCY} version ${installedPackage.version} does not match ${pinLocation} ${dependency}.`);
4504
+ suggestions.add(pnpmOverrideActive
4505
+ ? "Run `loom dev published`, then run `pnpm install`."
4506
+ : dependencyTooling.manager === "pnpm"
4507
+ ? "Run `pnpm install`."
4508
+ : pinSuggestion(dependency));
3190
4509
  }
3191
4510
  }
3192
4511
  }
@@ -4764,6 +6083,18 @@ import { apiKeyPolicy } from "${toAliasImportPath(config.modules.policyModule)}"
4764
6083
  import { apiKeyAuditRepository } from "${toAliasImportPath(config.modules.repositoryModule)}";
4765
6084
 
4766
6085
  // Generated verifier stub: adapt Better Auth verifyApiKey() exactly once here.
6086
+ // Replace it with Loom's shared verifier, which checks the requested
6087
+ // permission itself so a scope miss is denied as insufficient_permission:
6088
+ //
6089
+ // import { createBetterAuthApiKeyVerifier } from "@gadicc/loom/apiKeys";
6090
+ // import { auth } from "<the app's Better Auth module>";
6091
+ // import { apiKeyScopes } from "<the app's defineApiKeyScopes registry>";
6092
+ //
6093
+ // export const apiKeyVerifier = createBetterAuthApiKeyVerifier({
6094
+ // auth,
6095
+ // configId: "default", // the api-key plugin configId these keys use
6096
+ // scopes: apiKeyScopes,
6097
+ // });
4767
6098
  export const apiKeyVerifier: ApiKeyVerifier = {
4768
6099
  verify() {
4769
6100
  return Promise.resolve({ ok: false, code: "invalid_credential" });
@@ -8585,7 +9916,7 @@ async function applyApiKeysFeature(cwd, framework, manifest, activate) {
8585
9916
  changedFiles.push(...materialized.changedFiles);
8586
9917
  notes.push(...materialized.notes);
8587
9918
  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.");
9919
+ 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
9920
  }
8590
9921
  const scaffolds = [
8591
9922
  [config.modules.policyModule, apiKeysPolicyTemplate(), "policy"],
@@ -9598,184 +10929,1124 @@ async function checkFilesFeature(cwd, framework, manifest, options) {
9598
10929
  for (const suggestion of local.suggestions)
9599
10930
  suggestions.add(suggestion);
9600
10931
  }
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.");
10932
+ const routeText = await readTextIfExists((0, node_path_1.join)(cwd, config.entrypoints.routeHandler));
10933
+ if (!routeText) {
10934
+ issues.push(`Files route handler is missing: ${config.entrypoints.routeHandler}`);
10935
+ suggestions.add("Run `loom add files` to scaffold the files route handler.");
10936
+ }
10937
+ else {
10938
+ if (!matchesImportSource(routeText, ["@gadicc/loom/next/files"])) {
10939
+ issues.push(`Files route handler is not wired to @gadicc/loom/next/files: ${config.entrypoints.routeHandler}`);
10940
+ }
10941
+ if (!routeText.includes("createFilesRouteHandlers")) {
10942
+ issues.push(`Files route handler does not call createFilesRouteHandlers: ${config.entrypoints.routeHandler}`);
10943
+ }
10944
+ const routeImportChecks = [
10945
+ [config.modules.accessModule, "access policy"],
10946
+ [config.modules.repositoryModule, "repository"],
10947
+ [config.modules.storageModule, "storage adapter"],
10948
+ ];
10949
+ for (const [modulePath, label] of routeImportChecks) {
10950
+ if (!matchesImportSource(routeText, getImportSpecifierCandidates(config.entrypoints.routeHandler, modulePath))) {
10951
+ issues.push(`Files route handler does not import the configured ${label}: ${config.entrypoints.routeHandler}`);
10952
+ suggestions.add(`Import the files ${label} from ${modulePath} in the route handler.`);
10953
+ }
10954
+ }
10955
+ }
10956
+ return {
10957
+ issues,
10958
+ suggestions: [...suggestions],
10959
+ warnings,
10960
+ };
10961
+ }
10962
+ async function checkMailFeature(cwd, framework, manifest, options) {
10963
+ const issues = [];
10964
+ const suggestions = new Set();
10965
+ const warnings = [];
10966
+ const feature = manifest.features.mail;
10967
+ if (!feature || feature.status !== "active") {
10968
+ return { issues, suggestions: [], warnings };
10969
+ }
10970
+ for (const dependency of ["auth", "db"]) {
10971
+ if (manifest.features[dependency]?.status !== "active") {
10972
+ issues.push(`Mail feature requires the active ${dependency} feature.`);
10973
+ suggestions.add(`Run \`loom add ${dependency}\` before using mail.`);
10974
+ }
10975
+ }
10976
+ if (issues.length)
10977
+ return { issues, suggestions: [...suggestions], warnings };
10978
+ const { packageJson } = await readProjectPackageJson(cwd);
10979
+ const dbConfig = mergeDbConfig(framework, manifest.features.db.config);
10980
+ const config = getMailConfig(framework, dbConfig, packageJson, feature.config, manifest.features.jobs?.status === "active");
10981
+ const schema = config.schema;
10982
+ const latestSchema = getLatestManagedSchemaConfig(schema);
10983
+ if (schema.mode !== "managed-local" || schema.blueprint !== "mail") {
10984
+ issues.push("Mail must use the managed-local mail schema blueprint.");
10985
+ suggestions.add("Run `loom add mail` to restore the mail schema config.");
10986
+ }
10987
+ if (schema.exports.length !== 3) {
10988
+ issues.push("Mail schema must configure message, delivery, and event exports.");
10989
+ }
10990
+ if (schema.version > MAIL_SCHEMA_BLUEPRINT_VERSION) {
10991
+ issues.push(`Mail schema blueprint version ${schema.version} is newer than this Loom package supports.`);
10992
+ }
10993
+ else if (schema.version < MAIL_SCHEMA_BLUEPRINT_VERSION) {
10994
+ warnings.push(`Mail schema blueprint is stale: ${schema.version} < ${MAIL_SCHEMA_BLUEPRINT_VERSION}.`);
10995
+ suggestions.add("Run `loom db schemas sync`, then review and migrate the diff.");
10996
+ }
10997
+ const schemaText = await readTextIfExists((0, node_path_1.join)(cwd, schema.module));
10998
+ if (!schemaText) {
10999
+ issues.push(`Mail schema file is missing: ${schema.module}`);
11000
+ suggestions.add("Run `loom db schemas sync`.");
11001
+ }
11002
+ else {
11003
+ const currentHash = hashManagedSchemaText(schemaText);
11004
+ if (currentHash !== schema.hash) {
11005
+ if (currentHash === latestSchema.hash) {
11006
+ warnings.push(`Mail schema manifest hash is stale for ${schema.module}.`);
11007
+ suggestions.add("Run `loom db schemas sync` to refresh loom.json.");
11008
+ }
11009
+ else {
11010
+ issues.push(`Mail schema file has local edits outside the managed hash: ${schema.module}`);
11011
+ suggestions.add("Move app-specific mail schema additions to a separate file, then run `loom db schemas sync`.");
11012
+ }
11013
+ }
11014
+ const barrelText = await readTextIfExists((0, node_path_1.join)(cwd, dbConfig.dirs.schemaDir, "index.ts"));
11015
+ if (!barrelText || !schemaBarrelExportsModule(barrelText, schema, dbConfig)) {
11016
+ issues.push(`DB schema barrel does not export the managed mail schema: ${dbConfig.dirs.schemaDir}/index.ts`);
11017
+ suggestions.add("Run `loom db schemas sync`.");
11018
+ }
11019
+ }
11020
+ const requiredFiles = [
11021
+ config.modules.accessModule,
11022
+ config.modules.actionsModule,
11023
+ config.modules.repositoryModule,
11024
+ config.modules.serviceModule,
11025
+ config.modules.transportModule,
11026
+ config.entrypoints.adminPage,
11027
+ config.entrypoints.webhookRoute,
11028
+ ...(config.jobs.enabled ? [config.modules.jobModule] : []),
11029
+ ];
11030
+ for (const relativePath of requiredFiles) {
11031
+ if (!await exists((0, node_path_1.join)(cwd, relativePath))) {
11032
+ issues.push(`Mail scaffold file is missing: ${relativePath}`);
11033
+ suggestions.add("Run `loom add mail` to restore missing scaffolds.");
11034
+ }
11035
+ }
11036
+ const accessText = await readTextIfExists((0, node_path_1.join)(cwd, config.modules.accessModule));
11037
+ if (accessText && !accessText.includes("authorizeMailAdmin")) {
11038
+ issues.push(`Mail access module does not export authorizeMailAdmin: ${config.modules.accessModule}`);
11039
+ }
11040
+ const generatedDenyAll = accessText?.includes("Mail admin access policy is not configured.") ?? false;
11041
+ if (generatedDenyAll) {
11042
+ const message = `Mail admin access still uses the generated deny-all stub: ${config.modules.accessModule}`;
11043
+ if (options.production)
11044
+ issues.push(message);
11045
+ else
11046
+ warnings.push(message);
11047
+ suggestions.add("Connect authorizeMailAdmin() to the app's fresh session/admin-role check.");
11048
+ }
11049
+ const contentChecks = [
11050
+ [
11051
+ config.modules.repositoryModule,
11052
+ "@gadicc/loom/mail",
11053
+ "Mail repository is not typed against the shared mail contract",
11054
+ ],
11055
+ [
11056
+ config.modules.serviceModule,
11057
+ "createLoomMailService",
11058
+ "Mail service is not wired to the shared durable service",
11059
+ ],
11060
+ [
11061
+ config.modules.transportModule,
11062
+ "createPostalMailTransport",
11063
+ "Mail transport is not wired to the Postal adapter",
11064
+ ],
11065
+ [
11066
+ config.modules.transportModule,
11067
+ "POSTAL_WEBHOOK_PUBLIC_KEYS",
11068
+ "Mail transport does not configure Postal webhook public keys",
11069
+ ],
11070
+ [
11071
+ config.entrypoints.webhookRoute,
11072
+ "createPostalWebhookRouteHandler",
11073
+ "Mail webhook route does not use the signed shared route handler",
11074
+ ],
11075
+ [
11076
+ config.modules.actionsModule,
11077
+ "authorizeMailAdmin",
11078
+ "Mail admin actions do not enforce the app-owned admin boundary",
11079
+ ],
11080
+ [
11081
+ config.entrypoints.adminPage,
11082
+ "authorizeMailAdmin",
11083
+ "Mail admin page does not enforce the app-owned admin boundary",
11084
+ ],
11085
+ ];
11086
+ for (const [relativePath, snippet, label] of contentChecks) {
11087
+ const text = await readTextIfExists((0, node_path_1.join)(cwd, relativePath));
11088
+ if (text && !text.includes(snippet)) {
11089
+ issues.push(`${label}: ${relativePath}`);
11090
+ suggestions.add("Run `loom add mail` or update loom.json for intentional paths.");
11091
+ }
11092
+ }
11093
+ if (config.ui.adapter === "mui" &&
11094
+ !hasPackageDependency(packageJson, "@mui/material")) {
11095
+ issues.push("Mail's MUI adapter is active but @mui/material is not installed.");
11096
+ }
11097
+ if (config.jobs.enabled && manifest.features.jobs?.status !== "active") {
11098
+ warnings.push("Mail drain job is enabled while the Loom jobs feature is inactive.");
11099
+ suggestions.add("Run `loom add jobs` or disable features.mail.config.jobs.enabled.");
11100
+ }
11101
+ return { issues, suggestions: [...suggestions], warnings };
11102
+ }
11103
+ function packageDependencySpec(packageJson, dependencyName) {
11104
+ return packageJson.dependencies?.[dependencyName] ??
11105
+ packageJson.devDependencies?.[dependencyName];
11106
+ }
11107
+ function dependencyMajorMinor(spec) {
11108
+ const match = spec?.match(/(\d+)\.(\d+)/);
11109
+ return match ? `${match[1]}.${match[2]}` : undefined;
11110
+ }
11111
+ /**
11112
+ * Blanks JavaScript/TypeScript comments while keeping string and template
11113
+ * literals, so advisory text checks ignore commented-out code. Newlines are
11114
+ * kept. Regular-expression literals are not recognised; one containing a
11115
+ * quote or comment opener can confuse it, which only affects these checks.
11116
+ */
11117
+ function stripJsComments(text) {
11118
+ let output = "";
11119
+ let index = 0;
11120
+ while (index < text.length) {
11121
+ const char = text[index];
11122
+ const next = text[index + 1];
11123
+ if (char === "/" && next === "/") {
11124
+ const end = text.indexOf("\n", index);
11125
+ output += " ";
11126
+ if (end === -1)
11127
+ break;
11128
+ index = end;
11129
+ continue;
11130
+ }
11131
+ if (char === "/" && next === "*") {
11132
+ const end = text.indexOf("*/", index + 2);
11133
+ const comment = end === -1
11134
+ ? text.slice(index)
11135
+ : text.slice(index, end + 2);
11136
+ output += comment.replace(/[^\n]/g, " ");
11137
+ index += comment.length;
11138
+ continue;
11139
+ }
11140
+ if (char === '"' || char === "'" || char === "`") {
11141
+ const end = skipJsStringLiteral(text, index);
11142
+ output += text.slice(index, end);
11143
+ index = end;
11144
+ continue;
11145
+ }
11146
+ output += char;
11147
+ index += 1;
11148
+ }
11149
+ return output;
11150
+ }
11151
+ /** Returns the index just past the string literal that starts at `start`. */
11152
+ function skipJsStringLiteral(text, start) {
11153
+ const quote = text[start];
11154
+ let index = start + 1;
11155
+ while (index < text.length) {
11156
+ const char = text[index];
11157
+ if (char === "\\") {
11158
+ index += 2;
11159
+ continue;
11160
+ }
11161
+ index += 1;
11162
+ if (char === quote)
11163
+ break;
11164
+ if (quote !== "`" && char === "\n")
11165
+ break;
11166
+ }
11167
+ return Math.min(index, text.length);
11168
+ }
11169
+ /**
11170
+ * Replaces the contents of string and template literals with spaces, keeping
11171
+ * quotes, newlines, and offsets, so searches only see code.
11172
+ */
11173
+ function blankJsStrings(text) {
11174
+ let output = "";
11175
+ let index = 0;
11176
+ while (index < text.length) {
11177
+ const char = text[index];
11178
+ if (char === '"' || char === "'" || char === "`") {
11179
+ const end = skipJsStringLiteral(text, index);
11180
+ output += char + text.slice(index + 1, end).replace(/[^\n]/g, " ");
11181
+ if (end - index >= 2 && text[end - 1] === char) {
11182
+ output = output.slice(0, -1) + char;
11183
+ }
11184
+ index = end;
11185
+ continue;
11186
+ }
11187
+ output += char;
11188
+ index += 1;
11189
+ }
11190
+ return output;
11191
+ }
11192
+ /** Comment-free text plus a same-length copy whose string contents are blank. */
11193
+ function prepareJsText(text) {
11194
+ const code = stripJsComments(text);
11195
+ return { blanked: blankJsStrings(code), code };
11196
+ }
11197
+ /**
11198
+ * Reads one expression starting at `start` until a top-level `,`, `;`, or
11199
+ * closing bracket, skipping string literals. A top-level line break ends it
11200
+ * unless the neighbouring lines continue it (an operator or `.` on either
11201
+ * side), so a chained `.filter()` stays part of the expression. Expects
11202
+ * comment-free text.
11203
+ */
11204
+ function readJsExpression(text, start) {
11205
+ const blanked = blankJsStrings(text);
11206
+ let index = start;
11207
+ while (index < blanked.length && /\s/.test(blanked[index]))
11208
+ index += 1;
11209
+ const begin = index;
11210
+ let depth = 0;
11211
+ while (index < blanked.length) {
11212
+ const char = blanked[index];
11213
+ if (char === "(" || char === "[" || char === "{")
11214
+ depth += 1;
11215
+ else if (char === ")" || char === "]" || char === "}") {
11216
+ if (depth === 0)
11217
+ break;
11218
+ depth -= 1;
11219
+ }
11220
+ else if (depth === 0 && (char === "," || char === ";")) {
11221
+ break;
11222
+ }
11223
+ else if (depth === 0 && char === "\n") {
11224
+ const before = blanked.slice(begin, index).trimEnd();
11225
+ const after = blanked.slice(index).trimStart();
11226
+ const continued = /[=([{,?:+\-*/%&|^!<>~.]$/.test(before) ||
11227
+ /^(?:[.?:+\-*/%&|^<>=([]|as\s|satisfies\s)/.test(after);
11228
+ if (!continued)
11229
+ break;
11230
+ }
11231
+ index += 1;
11232
+ }
11233
+ return text.slice(begin, index).trim();
11234
+ }
11235
+ /** Index of the bracket closing the one at `open` in blanked text, or -1. */
11236
+ function findJsClosingBracket(blanked, open) {
11237
+ let depth = 0;
11238
+ for (let index = open; index < blanked.length; index += 1) {
11239
+ const char = blanked[index];
11240
+ if (char === "(" || char === "[" || char === "{")
11241
+ depth += 1;
11242
+ else if (char === ")" || char === "]" || char === "}") {
11243
+ depth -= 1;
11244
+ if (depth === 0)
11245
+ return index;
11246
+ }
11247
+ }
11248
+ return -1;
11249
+ }
11250
+ /** Splits list or object-literal contents on top-level commas. */
11251
+ function splitJsTopLevel(text) {
11252
+ const blanked = blankJsStrings(text);
11253
+ const parts = [];
11254
+ let depth = 0;
11255
+ let start = 0;
11256
+ for (let index = 0; index < blanked.length; index += 1) {
11257
+ const char = blanked[index];
11258
+ if (char === "(" || char === "[" || char === "{")
11259
+ depth += 1;
11260
+ else if (char === ")" || char === "]" || char === "}")
11261
+ depth -= 1;
11262
+ else if (char === "," && depth === 0) {
11263
+ parts.push(text.slice(start, index).trim());
11264
+ start = index + 1;
11265
+ }
11266
+ }
11267
+ parts.push(text.slice(start).trim());
11268
+ return parts.filter(Boolean);
11269
+ }
11270
+ /** Drops wrapping parentheses and a top-level `as T`/`satisfies T` suffix. */
11271
+ function unwrapJsExpression(expression) {
11272
+ let current = expression.trim();
11273
+ for (let attempt = 0; attempt < 8; attempt += 1) {
11274
+ const blanked = blankJsStrings(current);
11275
+ let depth = 0;
11276
+ let cut = -1;
11277
+ for (let index = 0; index < blanked.length; index += 1) {
11278
+ const char = blanked[index];
11279
+ if (char === "(" || char === "[" || char === "{")
11280
+ depth += 1;
11281
+ else if (char === ")" || char === "]" || char === "}")
11282
+ depth -= 1;
11283
+ else if (depth === 0 && /\s/.test(char) &&
11284
+ /^\s+(?:as|satisfies)\s/.test(blanked.slice(index))) {
11285
+ cut = index;
11286
+ break;
11287
+ }
11288
+ }
11289
+ if (cut !== -1) {
11290
+ current = current.slice(0, cut).trim();
11291
+ continue;
11292
+ }
11293
+ if (current.startsWith("(") &&
11294
+ findJsClosingBracket(blanked, 0) === current.length - 1) {
11295
+ current = current.slice(1, -1).trim();
11296
+ continue;
11297
+ }
11298
+ break;
11299
+ }
11300
+ return current;
11301
+ }
11302
+ /** `{ callee, args }` when the whole expression is one call, else null. */
11303
+ function parseWholeJsCall(expression) {
11304
+ const match = expression.match(/^([A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*)\s*\(/);
11305
+ if (!match)
11306
+ return null;
11307
+ const open = match[0].length - 1;
11308
+ if (findJsClosingBracket(blankJsStrings(expression), open) !==
11309
+ expression.length - 1) {
11310
+ return null;
11311
+ }
11312
+ return {
11313
+ args: expression.slice(open + 1, -1),
11314
+ callee: match[1].replace(/\s+/g, ""),
11315
+ };
11316
+ }
11317
+ /** The contents of a whole `[...]` or `{...}` literal, else null. */
11318
+ function wholeJsBracketContents(expression, open) {
11319
+ if (!expression.startsWith(open) ||
11320
+ findJsClosingBracket(blankJsStrings(expression), 0) !==
11321
+ expression.length - 1) {
11322
+ return null;
11323
+ }
11324
+ return expression.slice(1, -1);
11325
+ }
11326
+ /** The value of a plain string literal (no template substitutions). */
11327
+ function jsStringLiteralValue(expression) {
11328
+ const quote = expression[0];
11329
+ if (quote !== '"' && quote !== "'" && quote !== "`")
11330
+ return null;
11331
+ if (skipJsStringLiteral(expression, 0) !== expression.length)
11332
+ return null;
11333
+ const value = expression.slice(1, -1);
11334
+ return value.includes("\\") || (quote === "`" && value.includes("${"))
11335
+ ? null
11336
+ : value;
11337
+ }
11338
+ const JS_IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
11339
+ const JS_IDENTIFIER_SOURCE = String.raw `[A-Za-z_$][\w$]*`;
11340
+ const LOOM_API_KEYS_IMPORT_SOURCES = new Set([
11341
+ "@gadicc/loom",
11342
+ "@gadicc/loom/api-keys",
11343
+ "@gadicc/loom/apiKeys",
11344
+ ]);
11345
+ const NO_JS_ENV = new Map();
11346
+ async function loadJsSourceModule(context, relativePath) {
11347
+ if (!context.modules.has(relativePath)) {
11348
+ const text = await readTextIfExists((0, node_path_1.join)(context.cwd, relativePath));
11349
+ context.modules.set(relativePath, text === null
11350
+ ? null
11351
+ : { path: relativePath, prepared: prepareJsText(text) });
11352
+ }
11353
+ return context.modules.get(relativePath) ?? null;
11354
+ }
11355
+ /**
11356
+ * Value imports of a module: `imported` is `"*"` for a namespace import and
11357
+ * `"default"` for a default import.
11358
+ */
11359
+ function parseJsValueImports(module) {
11360
+ const { blanked, code } = module.prepared;
11361
+ const imports = [];
11362
+ const pattern = /(?<![\w$.])import\s+(type\s+)?([^;]*?)\s*from\s*(["'])([^"']+)\3/g;
11363
+ for (const match of code.matchAll(pattern)) {
11364
+ if (match[1] || !blanked.startsWith("import", match.index ?? 0))
11365
+ continue;
11366
+ const clause = match[2].trim();
11367
+ const source = match[4];
11368
+ const defaultImport = clause.match(/^([A-Za-z_$][\w$]*)\s*(?:,|$)/);
11369
+ if (defaultImport) {
11370
+ imports.push({ imported: "default", local: defaultImport[1], source });
11371
+ }
11372
+ const namespace = clause.match(/\*\s*as\s+([A-Za-z_$][\w$]*)/);
11373
+ if (namespace) {
11374
+ imports.push({ imported: "*", local: namespace[1], source });
11375
+ }
11376
+ const named = clause.match(/\{([^}]*)\}/);
11377
+ for (const specifier of named ? named[1].split(",") : []) {
11378
+ const trimmed = specifier.trim();
11379
+ if (!trimmed || /^type\s/.test(trimmed))
11380
+ continue;
11381
+ const [imported, local = imported] = trimmed.split(/\s+as\s+/);
11382
+ if (JS_IDENTIFIER.test(imported) && JS_IDENTIFIER.test(local)) {
11383
+ imports.push({ imported, local, source });
11384
+ }
11385
+ }
11386
+ }
11387
+ return imports;
11388
+ }
11389
+ /** Bracket depth before each offset of blanked text. */
11390
+ function jsBracketDepths(blanked) {
11391
+ const depths = new Int32Array(blanked.length + 1);
11392
+ let depth = 0;
11393
+ for (let index = 0; index < blanked.length; index += 1) {
11394
+ depths[index] = depth;
11395
+ const char = blanked[index];
11396
+ if (char === "(" || char === "[" || char === "{")
11397
+ depth += 1;
11398
+ else if (char === ")" || char === "]" || char === "}") {
11399
+ depth = Math.max(0, depth - 1);
11400
+ }
11401
+ }
11402
+ depths[blanked.length] = depth;
11403
+ return depths;
11404
+ }
11405
+ function addJsIdentifiers(names, text) {
11406
+ for (const match of text.matchAll(/[A-Za-z_$][\w$]*/g))
11407
+ names.add(match[0]);
11408
+ }
11409
+ /**
11410
+ * Offset of a function body: after a parameter list's closing parenthesis,
11411
+ * an optional return type, then `{` or `=>`. Returns -1 otherwise.
11412
+ */
11413
+ function jsFunctionBodyStart(blanked, close) {
11414
+ const after = blanked.slice(close + 1).match(/^\s*(?::[^{};=]*?)?\s*(=>|\{)/);
11415
+ if (!after)
11416
+ return -1;
11417
+ return close + 1 + after[0].length - after[1].length;
11418
+ }
11419
+ /** Start and end offsets of a function body that begins at `start`. */
11420
+ function jsFunctionBodyRange(module, start) {
11421
+ const { blanked, code } = module.prepared;
11422
+ let index = start;
11423
+ if (blanked.startsWith("=>", index)) {
11424
+ index += 2;
11425
+ while (index < blanked.length && /\s/.test(blanked[index]))
11426
+ index += 1;
11427
+ if (blanked[index] !== "{") {
11428
+ const expression = readJsExpression(code, index);
11429
+ return { end: index + expression.length, start: index };
11430
+ }
11431
+ }
11432
+ const end = findJsClosingBracket(blanked, index);
11433
+ return end === -1 ? null : { end, start: index };
11434
+ }
11435
+ /** The first parameter's name when it is a plain identifier. */
11436
+ function firstJsParameterName(parameters) {
11437
+ const [first] = splitJsTopLevel(parameters);
11438
+ const name = first?.replace(/\s*=[\s\S]*$/, "").replace(/\s*:[\s\S]*$/, "")
11439
+ .replace(/\?$/, "").trim();
11440
+ return name && JS_IDENTIFIER.test(name) ? name : undefined;
11441
+ }
11442
+ /** Computes, once per module, the facts used for identifier resolution. */
11443
+ function analyzeJsModule(module) {
11444
+ if (module.scope)
11445
+ return module.scope;
11446
+ const { blanked, code } = module.prepared;
11447
+ const depths = jsBracketDepths(blanked);
11448
+ const nestedNames = new Set();
11449
+ const topLevel = new Map();
11450
+ const functions = [];
11451
+ const addTopLevel = (name, binding) => {
11452
+ topLevel.set(name, [...(topLevel.get(name) ?? []), binding]);
11453
+ };
11454
+ for (const match of blanked.matchAll(/(?<![\w$.])(const|let|var)\s+([A-Za-z_$][\w$]*|[{[])/g)) {
11455
+ const index = match.index ?? 0;
11456
+ const target = match[2];
11457
+ const nested = depths[index] > 0;
11458
+ if (target === "{" || target === "[") {
11459
+ // Destructuring: every identifier in the pattern may be bound.
11460
+ const open = index + match[0].length - 1;
11461
+ const close = findJsClosingBracket(blanked, open);
11462
+ const names = new Set();
11463
+ addJsIdentifiers(names, blanked.slice(open, close + 1));
11464
+ for (const name of names) {
11465
+ if (nested)
11466
+ nestedNames.add(name);
11467
+ else
11468
+ addTopLevel(name, { kind: "other" });
11469
+ }
11470
+ continue;
11471
+ }
11472
+ if (nested) {
11473
+ nestedNames.add(target);
11474
+ continue;
11475
+ }
11476
+ const initializer = new RegExp(String.raw `^\s*(?::[^=;]*)?=(?![=>])`).exec(blanked.slice(index + match[0].length));
11477
+ addTopLevel(target, match[1] === "const" && initializer
11478
+ ? {
11479
+ initializer: index + match[0].length + initializer[0].length,
11480
+ kind: "const",
11481
+ }
11482
+ : { kind: "other" });
11483
+ }
11484
+ for (const match of blanked.matchAll(/(?<![\w$.])(?:function\s*\*?|class)\s+([A-Za-z_$][\w$]*)/g)) {
11485
+ if (depths[match.index ?? 0] > 0)
11486
+ nestedNames.add(match[1]);
11487
+ else
11488
+ addTopLevel(match[1], { kind: "other" });
11489
+ }
11490
+ for (const entry of parseJsValueImports(module)) {
11491
+ addTopLevel(entry.local, entry.imported === "*" || entry.imported === "default"
11492
+ ? { kind: "other" }
11493
+ : { imported: entry.imported, kind: "import", source: entry.source });
11494
+ }
11495
+ // Parameter-like lists (functions, arrows, methods, catch clauses, and
11496
+ // control-flow headers) all count as nested bindings.
11497
+ for (let index = 0; index < blanked.length; index += 1) {
11498
+ if (blanked[index] !== "(")
11499
+ continue;
11500
+ const close = findJsClosingBracket(blanked, index);
11501
+ if (close === -1 || jsFunctionBodyStart(blanked, close) === -1)
11502
+ continue;
11503
+ addJsIdentifiers(nestedNames, blanked.slice(index + 1, close));
11504
+ }
11505
+ for (const match of blanked.matchAll(/([A-Za-z_$][\w$]*)\s*=>/g)) {
11506
+ nestedNames.add(match[1]);
11507
+ }
11508
+ // Top-level functions, for factories that forward their first parameter.
11509
+ const definitions = [
11510
+ /(?<![\w$.])(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)\s*\(/g,
11511
+ /(?<![\w$.])const\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]*)?=\s*(?:async\s+)?(?:function\s*\*?\s*[\w$]*\s*)?\(/g,
11512
+ ];
11513
+ for (const pattern of definitions) {
11514
+ for (const match of blanked.matchAll(pattern)) {
11515
+ const index = match.index ?? 0;
11516
+ if (depths[index] > 0)
11517
+ continue;
11518
+ const open = index + match[0].length - 1;
11519
+ const close = findJsClosingBracket(blanked, open);
11520
+ const bodyStart = close === -1 ? -1 : jsFunctionBodyStart(blanked, close);
11521
+ const body = bodyStart === -1
11522
+ ? null
11523
+ : jsFunctionBodyRange(module, bodyStart);
11524
+ if (!body)
11525
+ continue;
11526
+ functions.push({
11527
+ bodyEnd: body.end,
11528
+ bodyStart: body.start,
11529
+ name: match[1],
11530
+ parameter: firstJsParameterName(code.slice(open + 1, close)),
11531
+ });
11532
+ }
11533
+ }
11534
+ for (const match of blanked.matchAll(/(?<![\w$.])const\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]*)?=\s*(?:async\s+)?([A-Za-z_$][\w$]*)\s*=>/g)) {
11535
+ const index = match.index ?? 0;
11536
+ if (depths[index] > 0)
11537
+ continue;
11538
+ const body = jsFunctionBodyRange(module, index + match[0].length - 2);
11539
+ if (body) {
11540
+ functions.push({
11541
+ bodyEnd: body.end,
11542
+ bodyStart: body.start,
11543
+ name: match[1],
11544
+ parameter: match[2],
11545
+ });
11546
+ }
11547
+ }
11548
+ module.scope = { functions, nestedNames, topLevel };
11549
+ return module.scope;
11550
+ }
11551
+ /**
11552
+ * Whether a module mutates `name` after binding it: member assignment
11553
+ * (`name.disabledPaths = …`, `name.length = 0`), a removing array method,
11554
+ * `delete`, `Object.assign` and similar, or reassignment.
11555
+ */
11556
+ function isJsBindingMutated(module, name) {
11557
+ const { blanked } = module.prepared;
11558
+ const id = escapeRegExp(name);
11559
+ const member = String
11560
+ .raw `(?:\s*\??\.\s*${JS_IDENTIFIER_SOURCE}|\s*\[[^\]]*\])`;
11561
+ const assignment = String
11562
+ .raw `\s*(?:[-+*/%&|^]|\*\*|<<|>>>?|\?\?|&&|\|\|)?=(?![=>])`;
11563
+ return [
11564
+ new RegExp(String.raw `(?<![\w$.])${id}${member}+${assignment}`),
11565
+ new RegExp(String
11566
+ .raw `(?<![\w$.])${id}${member}*\s*\??\.\s*(?:splice|pop|shift|fill|copyWithin)\s*\(`),
11567
+ new RegExp(String.raw `\bdelete\s+${id}\b`),
11568
+ new RegExp(String
11569
+ .raw `\bObject\s*\.\s*(?:assign|defineProperty|defineProperties|setPrototypeOf)\s*\(\s*${id}\b`),
11570
+ new RegExp(String.raw `(?<![\w$.]|(?:const|let|var)\s+)${id}${assignment}`),
11571
+ ].some((pattern) => pattern.test(blanked));
11572
+ }
11573
+ /**
11574
+ * Local names under which a module imported a Loom API-key export, including
11575
+ * aliases and `namespace.name` for namespace imports. A name that is also
11576
+ * bound elsewhere in the module is left out.
11577
+ */
11578
+ function loomApiKeyExportNames(module, exportName) {
11579
+ const scope = analyzeJsModule(module);
11580
+ const names = new Set();
11581
+ for (const entry of parseJsValueImports(module)) {
11582
+ if (!LOOM_API_KEYS_IMPORT_SOURCES.has(entry.source))
11583
+ continue;
11584
+ if (scope.nestedNames.has(entry.local) ||
11585
+ (scope.topLevel.get(entry.local)?.length ?? 0) !== 1) {
11586
+ continue;
11587
+ }
11588
+ if (entry.imported === exportName)
11589
+ names.add(entry.local);
11590
+ if (entry.imported === "*")
11591
+ names.add(`${entry.local}.${exportName}`);
11592
+ }
11593
+ return names;
11594
+ }
11595
+ /**
11596
+ * Resolves an identifier, proven or not at all: an enclosing factory
11597
+ * parameter, or the single top-level `const` (or one relative/`@/` import of
11598
+ * one while hops remain) that nothing nested shadows and nothing mutates.
11599
+ */
11600
+ async function resolveJsName(context, binding, name) {
11601
+ if (binding.env.has(name)) {
11602
+ const parameter = binding.env.get(name) ?? null;
11603
+ return parameter && !isJsBindingMutated(binding.module, name)
11604
+ ? parameter
11605
+ : null;
11606
+ }
11607
+ const module = binding.module;
11608
+ const scope = analyzeJsModule(module);
11609
+ const sites = scope.topLevel.get(name) ?? [];
11610
+ if (scope.nestedNames.has(name) || sites.length !== 1)
11611
+ return null;
11612
+ if (isJsBindingMutated(module, name))
11613
+ return null;
11614
+ const [site] = sites;
11615
+ if (site.kind === "const") {
11616
+ return {
11617
+ env: NO_JS_ENV,
11618
+ expression: readJsExpression(module.prepared.code, site.initializer),
11619
+ importHops: binding.importHops,
11620
+ module,
11621
+ };
11622
+ }
11623
+ if (site.kind !== "import" || binding.importHops <= 0)
11624
+ return null;
11625
+ const resolved = await resolveLocalSourceImport(context.cwd, context.framework, (0, node_path_1.resolve)(context.cwd, module.path), site.source);
11626
+ if (!resolved)
11627
+ return null;
11628
+ const target = await loadJsSourceModule(context, (0, node_path_1.relative)(context.cwd, resolved).replaceAll("\\", "/"));
11629
+ return target
11630
+ ? await resolveJsName(context, {
11631
+ env: NO_JS_ENV,
11632
+ expression: site.imported,
11633
+ importHops: binding.importHops - 1,
11634
+ module: target,
11635
+ }, site.imported)
11636
+ : null;
11637
+ }
11638
+ /**
11639
+ * Whether a `disabledPaths` value provably contains every api-key plugin path:
11640
+ * the whole value is Loom's helper call (any arguments) or constant, an array
11641
+ * literal that spreads either, an array literal listing every path, or
11642
+ * `<options>.disabledPaths` of options that prove it. Anything else, such as
11643
+ * a conditional or a filtered list, is unproven.
11644
+ */
11645
+ async function jsValueDisablesApiKeyPaths(context, binding, depth = 0) {
11646
+ if (depth > 12)
11647
+ return false;
11648
+ const expression = unwrapJsExpression(binding.expression);
11649
+ const compact = expression.replace(/\s+/g, "");
11650
+ const shadowed = (name) => binding.env.has(name.split(".")[0]);
11651
+ const constants = loomApiKeyExportNames(binding.module, "BETTER_AUTH_API_KEY_HTTP_PATHS");
11652
+ if (constants.has(compact) && !shadowed(compact))
11653
+ return true;
11654
+ if (JS_IDENTIFIER.test(expression)) {
11655
+ const resolved = await resolveJsName(context, binding, expression);
11656
+ return resolved
11657
+ ? await jsValueDisablesApiKeyPaths(context, resolved, depth + 1)
11658
+ : false;
11659
+ }
11660
+ const member = compact.match(/^([A-Za-z_$][\w$]*)\??\.disabledPaths$/);
11661
+ if (member) {
11662
+ return await jsOptionsDisableApiKeyPaths(context, { ...binding, expression: member[1] }, depth + 1) === true;
11663
+ }
11664
+ const call = parseWholeJsCall(expression);
11665
+ if (call) {
11666
+ return loomApiKeyExportNames(binding.module, "withBetterAuthApiKeyHttpPathsDisabled").has(call.callee) && !shadowed(call.callee);
11667
+ }
11668
+ const list = wholeJsBracketContents(expression, "[");
11669
+ if (list === null)
11670
+ return false;
11671
+ const literals = new Set();
11672
+ for (const element of splitJsTopLevel(list)) {
11673
+ if (element.startsWith("...")) {
11674
+ if (await jsValueDisablesApiKeyPaths(context, { ...binding, expression: element.slice(3) }, depth + 1)) {
11675
+ return true;
11676
+ }
11677
+ continue;
11678
+ }
11679
+ const literal = jsStringLiteralValue(element);
11680
+ if (literal !== null)
11681
+ literals.add(literal);
11682
+ }
11683
+ return betterAuth_js_1.BETTER_AUTH_API_KEY_HTTP_PATHS.every((path) => literals.has(path));
11684
+ }
11685
+ /**
11686
+ * Evaluates Better Auth options for `disabledPaths`: `true` when proven,
11687
+ * `false` when set to something unproven, `undefined` when not set. Entries
11688
+ * apply in order, so a later key or spread overrides an earlier one. Options
11689
+ * or spreads that do not resolve to an object literal, computed keys, and
11690
+ * accessors are unproven.
11691
+ */
11692
+ async function jsOptionsDisableApiKeyPaths(context, binding, depth = 0) {
11693
+ if (depth > 12)
11694
+ return false;
11695
+ const expression = unwrapJsExpression(binding.expression);
11696
+ if (JS_IDENTIFIER.test(expression)) {
11697
+ const resolved = await resolveJsName(context, binding, expression);
11698
+ return resolved
11699
+ ? await jsOptionsDisableApiKeyPaths(context, resolved, depth + 1)
11700
+ : false;
11701
+ }
11702
+ const contents = wholeJsBracketContents(expression, "{");
11703
+ if (contents === null)
11704
+ return false;
11705
+ let result;
11706
+ for (const entry of splitJsTopLevel(contents)) {
11707
+ if (entry.startsWith("...")) {
11708
+ const spread = await jsOptionsDisableApiKeyPaths(context, { ...binding, expression: entry.slice(3) }, depth + 1);
11709
+ if (spread !== undefined)
11710
+ result = spread;
11711
+ continue;
11712
+ }
11713
+ if (entry.startsWith("[")) {
11714
+ // A computed key may evaluate to "disabledPaths".
11715
+ result = false;
11716
+ continue;
11717
+ }
11718
+ if (entry === "disabledPaths") {
11719
+ result = await jsValueDisablesApiKeyPaths(context, { ...binding, expression: entry }, depth + 1);
11720
+ continue;
11721
+ }
11722
+ const property = entry.match(/^(["']?)([A-Za-z_$][\w$]*)\1\s*:/);
11723
+ if (property?.[2] === "disabledPaths") {
11724
+ result = await jsValueDisablesApiKeyPaths(context, {
11725
+ ...binding,
11726
+ expression: entry.slice(property[0].length),
11727
+ }, depth + 1);
11728
+ }
11729
+ else if (!property &&
11730
+ /^(?:async\s+|get\s+|set\s+)?["']?disabledPaths\b/.test(entry)) {
11731
+ // A getter or method cannot be checked statically.
11732
+ result = false;
11733
+ }
11734
+ }
11735
+ return result;
11736
+ }
11737
+ /**
11738
+ * Every `callee(` call outside strings and comments. Member calls such as
11739
+ * `x.callee(` count only when `allowMember` is set; a function declaration
11740
+ * `function callee(` never counts.
11741
+ */
11742
+ function findJsCalls(module, callee, options = {}) {
11743
+ const { blanked, code } = module.prepared;
11744
+ const calls = [];
11745
+ const pattern = new RegExp(`${options.allowMember ? "\\b" : "(?<![\\w$.])"}${escapeRegExp(callee)}\\s*\\(`, "g");
11746
+ for (const match of blanked.matchAll(pattern)) {
11747
+ const index = match.index ?? 0;
11748
+ if (/\bfunction\s*\*?\s*$/.test(blanked.slice(0, index)))
11749
+ continue;
11750
+ const open = index + match[0].length - 1;
11751
+ const close = findJsClosingBracket(blanked, open);
11752
+ if (close === -1)
11753
+ continue;
11754
+ calls.push({
11755
+ firstArgument: splitJsTopLevel(code.slice(open + 1, close))[0],
11756
+ open,
11757
+ });
9605
11758
  }
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}`);
11759
+ return calls;
11760
+ }
11761
+ /**
11762
+ * Reads the app's Better Auth configuration and decides whether it provably
11763
+ * disables every api-key plugin HTTP endpoint.
11764
+ *
11765
+ * Every `betterAuth(` call in the auth module and, when it imports the auth
11766
+ * module, the auth runtime module must be proven; there must be at least one.
11767
+ * A call inside a top-level factory is evaluated once per call of that factory
11768
+ * in those modules, with the factory's first parameter bound to the call's
11769
+ * argument, so options the factory ignores are not credited. Identifiers
11770
+ * resolve only to unshadowed, unmutated top-level `const` initializers,
11771
+ * following one relative or `@/` import. `modules` lists every file read.
11772
+ */
11773
+ async function inspectBetterAuthApiKeyHttpPaths(cwd, framework, manifest) {
11774
+ const authConfig = await mergeAuthConfig(cwd, framework, manifest.features.auth?.config);
11775
+ const authModulePath = authConfig.modules.authModule;
11776
+ const context = { cwd, framework, modules: new Map() };
11777
+ const authModule = await loadJsSourceModule(context, authModulePath);
11778
+ const scanned = authModule ? [authModule] : [];
11779
+ let runtimeModule = null;
11780
+ /** Local names of auth-module exports imported by the runtime module. */
11781
+ const runtimeAliases = new Map();
11782
+ const runtimePath = authConfig.modules.authRuntimeModule;
11783
+ const runtimeText = runtimePath
11784
+ ? await readTextIfExists((0, node_path_1.join)(cwd, runtimePath))
11785
+ : null;
11786
+ if (authModule && runtimePath && runtimeText &&
11787
+ matchesImportSource(runtimeText, getImportSpecifierCandidates(runtimePath, authModulePath))) {
11788
+ runtimeModule = await loadJsSourceModule(context, runtimePath);
11789
+ if (runtimeModule) {
11790
+ scanned.push(runtimeModule);
11791
+ const authModuleAbsolute = (0, node_path_1.resolve)(cwd, authModulePath);
11792
+ for (const entry of parseJsValueImports(runtimeModule)) {
11793
+ if (entry.imported === "*" || entry.imported === "default")
11794
+ continue;
11795
+ const resolved = await resolveLocalSourceImport(cwd, framework, (0, node_path_1.resolve)(cwd, runtimePath), entry.source);
11796
+ if (resolved === authModuleAbsolute) {
11797
+ runtimeAliases.set(entry.imported, entry.local);
11798
+ }
11799
+ }
9609
11800
  }
9610
- if (!routeText.includes("createFilesRouteHandlers")) {
9611
- issues.push(`Files route handler does not call createFilesRouteHandlers: ${config.entrypoints.routeHandler}`);
11801
+ }
11802
+ const factoryCalls = (module, factory) => {
11803
+ const calls = findJsCalls(module, factory).map((call) => ({
11804
+ call,
11805
+ module,
11806
+ }));
11807
+ const alias = runtimeAliases.get(factory);
11808
+ const runtime = runtimeModule;
11809
+ if (module === authModule && alias && runtime) {
11810
+ calls.push(...findJsCalls(runtime, alias).map((call) => ({
11811
+ call,
11812
+ module: runtime,
11813
+ })));
9612
11814
  }
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.`);
11815
+ return calls;
11816
+ };
11817
+ let calls = 0;
11818
+ let disabled = true;
11819
+ for (const module of scanned) {
11820
+ const functions = analyzeJsModule(module).functions;
11821
+ for (const call of findJsCalls(module, "betterAuth")) {
11822
+ calls += 1;
11823
+ const options = (env) => call.firstArgument === undefined
11824
+ ? Promise.resolve(false)
11825
+ : jsOptionsDisableApiKeyPaths(context, {
11826
+ env,
11827
+ expression: call.firstArgument,
11828
+ importHops: 1,
11829
+ module,
11830
+ }).then((result) => result === true);
11831
+ const factory = functions.find((item) => call.open >= item.bodyStart && call.open < item.bodyEnd);
11832
+ const uses = factory ? factoryCalls(module, factory.name) : [];
11833
+ let proven;
11834
+ if (factory && uses.length) {
11835
+ proven = true;
11836
+ for (const use of uses) {
11837
+ const argument = use.call.firstArgument;
11838
+ const env = new Map(factory.parameter
11839
+ ? [[
11840
+ factory.parameter,
11841
+ argument === undefined ? null : {
11842
+ env: NO_JS_ENV,
11843
+ expression: argument,
11844
+ importHops: 1,
11845
+ module: use.module,
11846
+ },
11847
+ ]]
11848
+ : []);
11849
+ if (!await options(env)) {
11850
+ proven = false;
11851
+ break;
11852
+ }
11853
+ }
11854
+ }
11855
+ else {
11856
+ proven = await options(NO_JS_ENV);
9622
11857
  }
11858
+ if (!proven)
11859
+ disabled = false;
9623
11860
  }
9624
11861
  }
11862
+ const loaded = [...context.modules.values()].filter((module) => module !== null);
9625
11863
  return {
9626
- issues,
9627
- suggestions: [...suggestions],
9628
- warnings,
11864
+ authModuleRead: authModule !== null,
11865
+ authModulePath,
11866
+ disabled: calls > 0 && disabled,
11867
+ modules: loaded,
9629
11868
  };
9630
11869
  }
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`.");
11870
+ /**
11871
+ * Advisory, single-module object reading for the authorizer warnings: an
11872
+ * identifier resolves to its initializer only when the module declares that
11873
+ * name exactly once (`const`, at any depth) and nowhere else.
11874
+ */
11875
+ function readJsObjectShape(module, expression, depth = 0) {
11876
+ if (depth > 8)
11877
+ return null;
11878
+ const unwrapped = unwrapJsExpression(expression);
11879
+ if (JS_IDENTIFIER.test(unwrapped)) {
11880
+ const { blanked, code } = module.prepared;
11881
+ const id = escapeRegExp(unwrapped);
11882
+ const declarations = [
11883
+ ...blanked.matchAll(new RegExp(String
11884
+ .raw `(?<![\w$.])(?:const|let|var|function|class)\s+${id}\b|\bimport\b[^;]*\b${id}\b[^;]*\bfrom\b`, "g")),
11885
+ ];
11886
+ if (declarations.length !== 1)
11887
+ return null;
11888
+ const declaration = new RegExp(String.raw `(?<![\w$.])const\s+${id}\s*(?::[^=;]*)?=(?![=>])`).exec(blanked);
11889
+ return declaration
11890
+ ? readJsObjectShape(module, readJsExpression(code, declaration.index + declaration[0].length), depth + 1)
11891
+ : null;
9670
11892
  }
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
- }
11893
+ const contents = wholeJsBracketContents(unwrapped, "{");
11894
+ if (contents === null)
11895
+ return null;
11896
+ const shape = { complete: true, entries: [] };
11897
+ for (const entry of splitJsTopLevel(contents)) {
11898
+ if (entry.startsWith("...")) {
11899
+ const spread = readJsObjectShape(module, entry.slice(3), depth + 1);
11900
+ if (!spread)
11901
+ shape.complete = false;
9678
11902
  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`.");
11903
+ shape.entries.push(...spread.entries);
11904
+ shape.complete &&= spread.complete;
9681
11905
  }
11906
+ continue;
9682
11907
  }
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`.");
11908
+ const property = entry.match(/^(["']?)([A-Za-z_$][\w$]*)\1\s*(:)?/);
11909
+ if (!property) {
11910
+ shape.complete = false;
11911
+ continue;
9687
11912
  }
11913
+ shape.entries.push({
11914
+ key: property[2],
11915
+ value: property[3] ? entry.slice(property[0].length) : property[2],
11916
+ });
9688
11917
  }
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.");
11918
+ return shape;
11919
+ }
11920
+ const PERMISSION_CODE_LITERAL = String
11921
+ .raw `(["'\x60])[A-Z0-9_]*PERMISSION[A-Z0-9_]*\1`;
11922
+ const JS_EQUALITY = String.raw `(?:===|!==|==|!=)`;
11923
+ /**
11924
+ * Comparisons of an error `code` with a PERMISSION code, and a PERMISSION
11925
+ * code list checked with `.includes(…code)`. `token` is checked against
11926
+ * string-blanked text so matches inside strings do not count.
11927
+ */
11928
+ const PERMISSION_CODE_MAPPINGS = [
11929
+ {
11930
+ pattern: new RegExp(String
11931
+ .raw `\bcode\s*${JS_EQUALITY}\s*(?:${PERMISSION_CODE_LITERAL}|[\w$.?]*\b[A-Z0-9_]*PERMISSION[A-Z0-9_]*\b)`, "g"),
11932
+ token: "code",
11933
+ },
11934
+ {
11935
+ pattern: new RegExp(String
11936
+ .raw `${PERMISSION_CODE_LITERAL}\s*${JS_EQUALITY}\s*[\w$.?]*\bcode\b`, "g"),
11937
+ token: "code",
11938
+ },
11939
+ {
11940
+ pattern: new RegExp(String
11941
+ .raw `\[[^\]]*PERMISSION[^\]]*\]\s*\.\s*includes\s*\(\s*[\w$.?]*\bcode\s*\)`, "g"),
11942
+ token: "includes",
11943
+ },
11944
+ ];
11945
+ /** Whether a `switch` on an error `code` has a PERMISSION `case` label. */
11946
+ function hasPermissionCodeCase(prepared) {
11947
+ const { blanked, code } = prepared;
11948
+ for (const match of blanked.matchAll(/\bswitch\s*\(/g)) {
11949
+ const open = (match.index ?? 0) + match[0].length - 1;
11950
+ const close = findJsClosingBracket(blanked, open);
11951
+ if (close === -1 || !/\bcode\s*$/.test(blanked.slice(open + 1, close))) {
11952
+ continue;
9703
11953
  }
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.");
11954
+ const bodyOpen = blanked.indexOf("{", close);
11955
+ const bodyClose = bodyOpen === -1
11956
+ ? -1
11957
+ : findJsClosingBracket(blanked, bodyOpen);
11958
+ if (bodyClose === -1 || blanked.slice(close + 1, bodyOpen).trim())
11959
+ continue;
11960
+ const pattern = new RegExp(String.raw `\bcase\s+${PERMISSION_CODE_LITERAL}\s*:`, "g");
11961
+ for (const label of code.slice(bodyOpen, bodyClose).matchAll(pattern)) {
11962
+ if (blanked.startsWith("case", bodyOpen + (label.index ?? 0))) {
11963
+ return true;
11964
+ }
9760
11965
  }
9761
11966
  }
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.");
11967
+ return false;
11968
+ }
11969
+ /** Advisory findings for an app-owned Better Auth api-key verifier. */
11970
+ function checkApiKeysAuthorizerText(modulePath, text) {
11971
+ const warnings = [];
11972
+ const module = {
11973
+ path: modulePath,
11974
+ prepared: prepareJsText(text),
11975
+ };
11976
+ for (const call of findJsCalls(module, "verifyApiKey", { allowMember: true })) {
11977
+ const outer = call.firstArgument === undefined
11978
+ ? null
11979
+ : readJsObjectShape(module, call.firstArgument);
11980
+ let bodyValue;
11981
+ for (const entry of outer?.entries ?? []) {
11982
+ if (entry.key === "body")
11983
+ bodyValue = entry.value;
11984
+ }
11985
+ // Skip both warnings when the body cannot be read, rather than guess.
11986
+ const body = bodyValue === undefined
11987
+ ? null
11988
+ : readJsObjectShape(module, bodyValue);
11989
+ if (!body)
11990
+ continue;
11991
+ if (body.entries.some((entry) => entry.key === "permissions")) {
11992
+ 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}`);
11993
+ }
11994
+ if (body.complete && !body.entries.some((entry) => entry.key === "configId")) {
11995
+ warnings.push(`API-key authorizer calls verifyApiKey() without configId, so keys from any api-key plugin configuration verify: ${modulePath}`);
11996
+ }
9765
11997
  }
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.");
11998
+ const { blanked, code } = module.prepared;
11999
+ const mapsPermissionCode = hasPermissionCodeCase(module.prepared) ||
12000
+ PERMISSION_CODE_MAPPINGS.some(({ pattern, token }) => [...code.matchAll(pattern)].some((match) => {
12001
+ const tokenIndex = (match.index ?? 0) +
12002
+ match[0].search(new RegExp(`\\b${token}\\b`));
12003
+ return blanked.startsWith(token, tokenIndex);
12004
+ }));
12005
+ if (mapsPermissionCode) {
12006
+ 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
12007
  }
9770
- return { issues, suggestions: [...suggestions], warnings };
9771
- }
9772
- function packageDependencySpec(packageJson, dependencyName) {
9773
- return packageJson.dependencies?.[dependencyName] ??
9774
- packageJson.devDependencies?.[dependencyName];
12008
+ return [...new Set(warnings)];
9775
12009
  }
9776
- function dependencyMajorMinor(spec) {
9777
- const match = spec?.match(/(\d+)\.(\d+)/);
9778
- return match ? `${match[1]}.${match[2]}` : undefined;
12010
+ /**
12011
+ * The props an identifier belongs to in blanked text: the enclosing JSX
12012
+ * opening tag (`<Name ... >`) or, outside JSX, the innermost enclosing
12013
+ * `{...}` or `(...)`. Returns null for JSX children text.
12014
+ */
12015
+ function jsEnclosingPropsRegion(blanked, index) {
12016
+ let depth = 0;
12017
+ for (let cursor = index - 1; cursor >= 0; cursor -= 1) {
12018
+ const char = blanked[cursor];
12019
+ if (char === ")" || char === "]" || char === "}")
12020
+ depth += 1;
12021
+ else if (char === "(" || char === "[" || char === "{") {
12022
+ if (depth === 0) {
12023
+ if (char === "[")
12024
+ continue;
12025
+ const close = findJsClosingBracket(blanked, cursor);
12026
+ return blanked.slice(cursor, close === -1 ? undefined : close + 1);
12027
+ }
12028
+ depth -= 1;
12029
+ }
12030
+ else if (depth === 0 && char === ">" && blanked[cursor - 1] !== "=") {
12031
+ // The identifier follows a closed tag: it is JSX text, not a prop.
12032
+ return null;
12033
+ }
12034
+ else if (depth === 0 && char === "<" && /[A-Za-z]/.test(blanked[cursor + 1] ?? "")) {
12035
+ let end = index;
12036
+ let inner = 0;
12037
+ for (; end < blanked.length; end += 1) {
12038
+ const next = blanked[end];
12039
+ if (next === "(" || next === "[" || next === "{")
12040
+ inner += 1;
12041
+ else if (next === ")" || next === "]" || next === "}")
12042
+ inner -= 1;
12043
+ else if (inner === 0 && next === ">" && blanked[end - 1] !== "=")
12044
+ break;
12045
+ }
12046
+ return blanked.slice(cursor, end + 1);
12047
+ }
12048
+ }
12049
+ return blanked;
9779
12050
  }
9780
12051
  async function checkApiKeysFeature(cwd, framework, manifest, options) {
9781
12052
  const issues = [];
@@ -9921,6 +12192,57 @@ async function checkApiKeysFeature(cwd, framework, manifest, options) {
9921
12192
  if (issues.length || warnings.length) {
9922
12193
  suggestions.add("Run `loom add api-keys` to restore missing foundation files without overwriting custom modules.");
9923
12194
  }
12195
+ // Development hint only: the deprecated flag cannot describe Bearer or
12196
+ // header transports, so its copy can contradict the authorizer.
12197
+ if (!options.production) {
12198
+ for (const pagePath of [
12199
+ config.entrypoints.userPage,
12200
+ config.entrypoints.adminPage,
12201
+ ]) {
12202
+ const text = await readTextIfExists((0, node_path_1.join)(cwd, pagePath));
12203
+ const blanked = text ? prepareJsText(text).blanked : "";
12204
+ const uncovered = [
12205
+ ...blanked.matchAll(/\bqueryCredentialsEnabled\b/g),
12206
+ ].some((match) => {
12207
+ const region = jsEnclosingPropsRegion(blanked, match.index ?? 0);
12208
+ return region !== null && !/\bcredentialOptions\b/.test(region);
12209
+ });
12210
+ if (uncovered) {
12211
+ warnings.push(`API-key page passes the deprecated queryCredentialsEnabled without credentialOptions, so its transport guidance can contradict the authorizer: ${pagePath}`);
12212
+ suggestions.add("Pass the authorizer's credentialOptions to ApiKeysManager (and ApiKeyTransportGuidance), keeping that object in a small import-free module both import.");
12213
+ }
12214
+ }
12215
+ }
12216
+ const authorizerText = await readTextIfExists((0, node_path_1.join)(cwd, config.modules.authorizerModule));
12217
+ if (authorizerText) {
12218
+ const authorizerWarnings = checkApiKeysAuthorizerText(config.modules.authorizerModule, authorizerText);
12219
+ if (authorizerWarnings.length) {
12220
+ warnings.push(...authorizerWarnings);
12221
+ suggestions.add("Use `createBetterAuthApiKeyVerifier` from `@gadicc/loom/apiKeys`: it verifies with a configId and without permissions, then checks the permission itself.");
12222
+ }
12223
+ }
12224
+ const httpEndpoints = config.betterAuthHttpEndpoints;
12225
+ if (httpEndpoints !== undefined && httpEndpoints !== "disabled" &&
12226
+ httpEndpoints !== "app-owned") {
12227
+ issues.push(`Unknown api-keys betterAuthHttpEndpoints value in loom.json: ${JSON.stringify(httpEndpoints)}. Use "disabled" or "app-owned".`);
12228
+ }
12229
+ const authConfig = await inspectBetterAuthApiKeyHttpPaths(cwd, framework, manifest);
12230
+ if (httpEndpoints !== "app-owned" && !authConfig.disabled) {
12231
+ const location = authConfig.authModuleRead
12232
+ ? `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(", ")}`
12233
+ : `the auth module could not be read: ${authConfig.authModulePath}`;
12234
+ const message = `Better Auth api-key HTTP endpoints are reachable by any signed-in user (re-enable revoked keys, remove expiry, hard-delete); ${location}`;
12235
+ if (options.production)
12236
+ issues.push(message);
12237
+ else
12238
+ warnings.push(message);
12239
+ 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.');
12240
+ }
12241
+ for (const module of authConfig.modules) {
12242
+ if (/\benableSessionForAPIKeys\s*:\s*true\b/.test(module.prepared.blanked)) {
12243
+ 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}`);
12244
+ }
12245
+ }
9924
12246
  return { issues, suggestions: [...suggestions], warnings };
9925
12247
  }
9926
12248
  async function checkAuthFeature(cwd, framework, manifest) {
@@ -10711,6 +13033,22 @@ async function checkProject(cwd, env = node_process_1.default.env, options = {})
10711
13033
  else if (isLocalPackageSpec(dependency)) {
10712
13034
  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
13035
  }
13036
+ else if (parseCatalogReference(dependency) && await isPnpmProject(cwd, packageJson)) {
13037
+ // Only pnpm catalogs live in pnpm-workspace.yaml (Yarn 4 has its own).
13038
+ const catalogDependency = await resolveLoomDependencySpec(cwd, packageJson);
13039
+ const unreadable = catalogDependency.catalogEntry
13040
+ ? null
13041
+ : findUnreadableLoomCatalog(await readTextIfExists((0, node_path_1.join)(cwd, "pnpm-workspace.yaml")), catalogDependency.catalogName);
13042
+ if (unreadable) {
13043
+ 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.`);
13044
+ }
13045
+ else if (!catalogDependency.catalogEntry) {
13046
+ issues.push(`${exports.LOOM_DEPENDENCY} uses \`${dependency}\`, but pnpm-workspace.yaml has no ${exports.LOOM_DEPENDENCY} entry in that catalog.`);
13047
+ }
13048
+ else if (isLocalPackageSpec(catalogDependency.catalogEntry.spec)) {
13049
+ 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.`);
13050
+ }
13051
+ }
10714
13052
  const manifestPath = (0, node_path_1.join)(cwd, "loom.json");
10715
13053
  const manifestText = await readTextIfExists(manifestPath);
10716
13054
  let manifest = null;
@@ -10794,7 +13132,7 @@ async function checkProject(cwd, env = node_process_1.default.env, options = {})
10794
13132
  for (const suggestion of nextGuidanceCheck.suggestions) {
10795
13133
  suggestions.add(suggestion);
10796
13134
  }
10797
- const localDevCheck = await checkManagedLocalDevOverride(cwd, options.production ?? false);
13135
+ const localDevCheck = await checkManagedLocalDevOverride(cwd, options.production ?? false, options.commandRunner ?? defaultCommandRunner, env);
10798
13136
  warnings.push(...localDevCheck.warnings);
10799
13137
  issues.push(...localDevCheck.issues);
10800
13138
  for (const suggestion of localDevCheck.suggestions) {
@@ -11201,7 +13539,7 @@ async function runStatus(cwd, io) {
11201
13539
  ? parseJson(installedPackageText, (0, node_path_1.join)("node_modules", exports.LOOM_DEPENDENCY, "package.json"))
11202
13540
  : null;
11203
13541
  const workspaceText = await readTextIfExists((0, node_path_1.join)(cwd, "pnpm-workspace.yaml"));
11204
- const overrideSpec = getManagedDevOverrideSpec(workspaceText);
13542
+ const pnpmOverride = getActivePnpmLocalDevOverride(workspaceText, packageJson);
11205
13543
  let denoOverride = null;
11206
13544
  try {
11207
13545
  const tooling = await (0, projectTooling_js_1.detectProjectTooling)(cwd, manifest?.project?.tooling);
@@ -11223,13 +13561,22 @@ async function runStatus(cwd, io) {
11223
13561
  io.out(`Loom status for ${projectName}`);
11224
13562
  io.out("");
11225
13563
  io.out("Package:");
11226
- io.out(` ${projectMetadata.config}: ${dependencySpec ? `${exports.LOOM_DEPENDENCY} ${dependencySpec}` : "not declared"}`);
13564
+ const catalogEntry = parseCatalogReference(dependencySpec)
13565
+ ? findLoomCatalogEntry(workspaceText, parseCatalogReference(dependencySpec))
13566
+ : null;
13567
+ io.out(` ${projectMetadata.config}: ${dependencySpec
13568
+ ? `${exports.LOOM_DEPENDENCY} ${dependencySpec}${catalogEntry
13569
+ ? ` (${catalogEntry.spec} from pnpm-workspace.yaml ${catalogEntry.label})`
13570
+ : ""}`
13571
+ : "not declared"}`);
11227
13572
  io.out(` installed: ${installedPackage?.version ?? "not installed"}`);
11228
13573
  io.out(` local dev override: ${denoOverride
11229
13574
  ? `active (${denoOverride.config} links ${denoOverride.link})`
11230
- : overrideSpec
11231
- ? `active (${overrideSpec})`
11232
- : "none"}`);
13575
+ : pnpmOverride?.location === "pnpm-workspace.yaml"
13576
+ ? `active (${pnpmOverride.spec})`
13577
+ : pnpmOverride
13578
+ ? `active (${formatPnpmOverrideLocation(pnpmOverride.location)}: ${pnpmOverride.spec})`
13579
+ : "none"}`);
11233
13580
  io.out(` lockfile local resolution: ${localLockfileResolution ?? "none"}`);
11234
13581
  io.out("");
11235
13582
  io.out("Project:");
@@ -11369,8 +13716,9 @@ function printHelp({ out }) {
11369
13716
  out(" --local-db-host <host> Local PostgreSQL host (default: db.localtest.me).");
11370
13717
  out(" --local-db-port <port> Local PostgreSQL port (default: 5432).");
11371
13718
  out(" --replace-local-target Replace an existing development URL during local DB setup.");
13719
+ out(" --cwd <dir> Run in <dir>, resolved from the current directory.");
11372
13720
  out(" --no-color Disable colored CLI output.");
11373
- out(" --no-sync Skip automatic local-dev package sync.");
13721
+ 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
13722
  out(" --force Force `loom dev sync` to rebuild and reinstall.");
11375
13723
  out(" --name <name> Override the resource name for `loom db neon setup`.");
11376
13724
  out(" --plan <plan> Pass a Vercel Marketplace plan id to Neon setup.");
@@ -12186,7 +14534,9 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
12186
14534
  io.err("Missing local package path. Example: `loom dev local /path/to/loom`.");
12187
14535
  return 1;
12188
14536
  }
12189
- const result = await useLocalDevPackage(cwd, pathInput);
14537
+ const result = await useLocalDevPackage(cwd, pathInput, {
14538
+ onLockWait: io.err,
14539
+ });
12190
14540
  if (result.changedFiles.length) {
12191
14541
  io.out(`Updated ${result.changedFiles.join(", ")}.`);
12192
14542
  }
@@ -12198,6 +14548,7 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
12198
14548
  }
12199
14549
  if (!options.noSync) {
12200
14550
  const syncResult = await syncLocalDevPackage(cwd, {
14551
+ onLockWait: io.err,
12201
14552
  requireActive: true,
12202
14553
  });
12203
14554
  for (const note of syncResult.notes) {
@@ -12209,6 +14560,7 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
12209
14560
  case "sync": {
12210
14561
  const result = await syncLocalDevPackage(cwd, {
12211
14562
  force: options.force,
14563
+ onLockWait: io.err,
12212
14564
  requireActive: true,
12213
14565
  });
12214
14566
  if (result.changed) {
@@ -12223,7 +14575,9 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
12223
14575
  return 0;
12224
14576
  }
12225
14577
  case "published": {
12226
- const result = await usePublishedDevPackage(cwd);
14578
+ const result = await usePublishedDevPackage(cwd, {
14579
+ onLockWait: io.err,
14580
+ });
12227
14581
  if (result.changedFiles.length) {
12228
14582
  io.out(`Updated ${result.changedFiles.join(", ")}.`);
12229
14583
  }
@@ -12301,7 +14655,7 @@ async function runCheck(cwd, strictSkills, production, network, noProgress, noCo
12301
14655
  async function runCli(args = node_process_1.default.argv.slice(2), io = {
12302
14656
  err: (line) => console.error(line),
12303
14657
  out: (line) => console.log(line),
12304
- }) {
14658
+ }, options = {}) {
12305
14659
  const parsed = (0, node_util_1.parseArgs)({
12306
14660
  allowPositionals: true,
12307
14661
  args,
@@ -12371,13 +14725,29 @@ async function runCli(args = node_process_1.default.argv.slice(2), io = {
12371
14725
  !addListOnly &&
12372
14726
  !productionCheck &&
12373
14727
  !parsed.values["no-sync"]) {
12374
- const syncResult = await syncLocalDevPackage(cwd);
14728
+ // Taken before waiting on another sync, so a refresh by that sync shows
14729
+ // up as a change and this process does not run the code it replaced.
14730
+ const loadedPackageSignature = await captureLoadedLocalLoomSignature(cwd, node_process_1.default.env);
14731
+ const syncResult = await syncLocalDevPackage(cwd, {
14732
+ commandOutput: command === "env" ? "stderr" : "stdout",
14733
+ commandRunner: options.commandRunner,
14734
+ loadedPackageSignature,
14735
+ onLockWait: io.err,
14736
+ });
12375
14737
  if (syncResult.changed) {
14738
+ // `loom env` only loads env files before spawning the wrapped command,
14739
+ // a new process that loads the refreshed package, so it continues.
14740
+ // Every other command would run this process's stale Loom code, so it
14741
+ // stops with a retry status instead of reporting success.
14742
+ const report = command === "env" ? io.err : io.out;
12376
14743
  for (const note of syncResult.notes) {
12377
- io.out(`Note: ${note}`);
14744
+ report(`Note: ${note}`);
12378
14745
  }
12379
- io.out("Re-run the original command to use the refreshed Loom package.");
12380
- return 0;
14746
+ if (command !== "env") {
14747
+ 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}).`);
14748
+ return exports.LOOM_LOCAL_DEV_RERUN_EXIT_CODE;
14749
+ }
14750
+ io.err("Running the wrapped command with the refreshed Loom package.");
12381
14751
  }
12382
14752
  }
12383
14753
  switch (command) {
@@ -12422,7 +14792,7 @@ async function runCli(args = node_process_1.default.argv.slice(2), io = {
12422
14792
  acceptUnknownLicense: parsed.values["accept-unknown-license"],
12423
14793
  });
12424
14794
  case "env":
12425
- return await runEnvCommand(cwd, arg1, [arg2, ...rest].filter((arg) => arg !== undefined), io);
14795
+ return await runEnvCommand(cwd, arg1, [arg2, ...rest].filter((arg) => arg !== undefined), io, { commandRunner: options.commandRunner });
12426
14796
  case "db":
12427
14797
  return await runDb(cwd, arg1, [arg2, ...rest].filter(Boolean), io, {
12428
14798
  connect: parsed.values.connect,