@gadicc/loom 1.33.1 → 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 (110) 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/localDb.d.ts +28 -0
  28. package/esm/src/cli/localDb.d.ts.map +1 -0
  29. package/esm/src/cli/localDb.js +366 -0
  30. package/esm/src/cli/localDevLock.d.ts +97 -0
  31. package/esm/src/cli/localDevLock.d.ts.map +1 -0
  32. package/esm/src/cli/localDevLock.js +312 -0
  33. package/esm/src/cli/localDevPackage.d.ts +172 -0
  34. package/esm/src/cli/localDevPackage.d.ts.map +1 -0
  35. package/esm/src/cli/localDevPackage.js +617 -0
  36. package/esm/src/cli/migrationEnv.d.ts +19 -0
  37. package/esm/src/cli/migrationEnv.d.ts.map +1 -1
  38. package/esm/src/cli/migrationEnv.js +44 -1
  39. package/esm/src/cli/mod.d.ts +69 -4
  40. package/esm/src/cli/mod.d.ts.map +1 -1
  41. package/esm/src/cli/mod.js +2822 -419
  42. package/esm/src/cli/projectTooling.d.ts +19 -1
  43. package/esm/src/cli/projectTooling.d.ts.map +1 -1
  44. package/esm/src/cli/projectTooling.js +142 -12
  45. package/esm/src/mui/apiKeys.d.ts +123 -17
  46. package/esm/src/mui/apiKeys.d.ts.map +1 -1
  47. package/esm/src/mui/apiKeys.js +219 -78
  48. package/esm/src/mui/apiKeysView.d.ts +145 -0
  49. package/esm/src/mui/apiKeysView.d.ts.map +1 -1
  50. package/esm/src/mui/apiKeysView.js +278 -0
  51. package/esm/src/next/apiKeys/mod.d.ts +8 -1
  52. package/esm/src/next/apiKeys/mod.d.ts.map +1 -1
  53. package/esm/src/next/apiKeys/mod.js +5 -2
  54. package/package.json +2 -6
  55. package/script/src/apiKeys/authorize.d.ts.map +1 -1
  56. package/script/src/apiKeys/authorize.js +71 -0
  57. package/script/src/apiKeys/betterAuth.d.ts +123 -0
  58. package/script/src/apiKeys/betterAuth.d.ts.map +1 -0
  59. package/script/src/apiKeys/betterAuth.js +169 -0
  60. package/script/src/apiKeys/credentials.d.ts +37 -2
  61. package/script/src/apiKeys/credentials.d.ts.map +1 -1
  62. package/script/src/apiKeys/credentials.js +71 -8
  63. package/script/src/apiKeys/lifecycle.d.ts +41 -0
  64. package/script/src/apiKeys/lifecycle.d.ts.map +1 -0
  65. package/script/src/apiKeys/lifecycle.js +7 -0
  66. package/script/src/apiKeys/limits.d.ts +132 -0
  67. package/script/src/apiKeys/limits.d.ts.map +1 -0
  68. package/script/src/apiKeys/limits.js +254 -0
  69. package/script/src/apiKeys/mod.d.ts +4 -0
  70. package/script/src/apiKeys/mod.d.ts.map +1 -1
  71. package/script/src/apiKeys/mod.js +4 -0
  72. package/script/src/apiKeys/permissions.d.ts +56 -0
  73. package/script/src/apiKeys/permissions.d.ts.map +1 -0
  74. package/script/src/apiKeys/permissions.js +136 -0
  75. package/script/src/apiKeys/policy.d.ts +3 -1
  76. package/script/src/apiKeys/policy.d.ts.map +1 -1
  77. package/script/src/apiKeys/policy.js +3 -1
  78. package/script/src/apiKeys/types.d.ts +68 -1
  79. package/script/src/apiKeys/types.d.ts.map +1 -1
  80. package/script/src/cli/localDb.d.ts +28 -0
  81. package/script/src/cli/localDb.d.ts.map +1 -0
  82. package/script/src/cli/localDb.js +370 -0
  83. package/script/src/cli/localDevLock.d.ts +97 -0
  84. package/script/src/cli/localDevLock.d.ts.map +1 -0
  85. package/script/src/cli/localDevLock.js +320 -0
  86. package/script/src/cli/localDevPackage.d.ts +172 -0
  87. package/script/src/cli/localDevPackage.d.ts.map +1 -0
  88. package/script/src/cli/localDevPackage.js +635 -0
  89. package/script/src/cli/migrationEnv.d.ts +19 -0
  90. package/script/src/cli/migrationEnv.d.ts.map +1 -1
  91. package/script/src/cli/migrationEnv.js +48 -1
  92. package/script/src/cli/mod.d.ts +69 -4
  93. package/script/src/cli/mod.d.ts.map +1 -1
  94. package/script/src/cli/mod.js +2823 -419
  95. package/script/src/cli/projectTooling.d.ts +19 -1
  96. package/script/src/cli/projectTooling.d.ts.map +1 -1
  97. package/script/src/cli/projectTooling.js +176 -12
  98. package/script/src/mui/apiKeys.d.ts +123 -17
  99. package/script/src/mui/apiKeys.d.ts.map +1 -1
  100. package/script/src/mui/apiKeys.js +220 -77
  101. package/script/src/mui/apiKeysView.d.ts +145 -0
  102. package/script/src/mui/apiKeysView.d.ts.map +1 -1
  103. package/script/src/mui/apiKeysView.js +291 -0
  104. package/script/src/next/apiKeys/mod.d.ts +8 -1
  105. package/script/src/next/apiKeys/mod.d.ts.map +1 -1
  106. package/script/src/next/apiKeys/mod.js +5 -2
  107. package/skills/loom/SKILL.md +116 -18
  108. package/skills/loom-api-keys/SKILL.md +101 -7
  109. package/skills/loom-auth/SKILL.md +9 -0
  110. package/skills/loom-db/SKILL.md +33 -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;
@@ -84,12 +85,16 @@ const filesR2Policy_js_1 = require("./filesR2Policy.js");
84
85
  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");
88
+ const localDb_js_1 = require("./localDb.js");
89
+ const betterAuth_js_1 = require("../apiKeys/betterAuth.js");
87
90
  const retention_js_1 = require("../apiKeys/retention.js");
88
91
  const projectSkills_js_1 = require("./projectSkills.js");
89
92
  const migrationEnv_js_1 = require("./migrationEnv.js");
90
93
  const vercelBuildEnv_js_1 = require("./vercelBuildEnv.js");
91
94
  const vercelProjectRelease_js_1 = require("./vercelProjectRelease.js");
92
95
  const projectTooling_js_1 = require("./projectTooling.js");
96
+ const localDevLock_js_1 = require("./localDevLock.js");
97
+ const localDevPackage_js_1 = require("./localDevPackage.js");
93
98
  exports.DEFAULT_LOOM_RANGE = "^1.0.0";
94
99
  exports.LOOM_DEPENDENCY = "@gadicc/loom";
95
100
  exports.LOOM_MANIFEST_SCHEMA = "https://loom.gadicc.local/project-manifest.schema.json";
@@ -101,24 +106,21 @@ exports.LOOM_MANAGED_DEV_OVERRIDE_START = "# loom-managed:dev:start";
101
106
  exports.LOOM_MANAGED_DEV_OVERRIDE_END = "# loom-managed:dev:end";
102
107
  exports.LOOM_LOCAL_DEV_STATE_RELATIVE_PATH = ".loom/dev-state.json";
103
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";
104
115
  const DEFAULT_JOBS_MAX_DURATION_SECONDS = 1800;
105
116
  const LOOM_MANAGED_STATIC_JOB_ROUTE_MARKER = "// loom-managed:jobs-static-route";
106
117
  /** @deprecated Public npm installs no longer require project registry config. */
107
118
  exports.LOOM_NPMRC_LINES = [];
108
- const LOOM_PACKAGE_RELEVANT_PATHS = [
109
- "LICENSE",
110
- "NOTICE",
111
- "README.md",
112
- "THIRD_PARTY_NOTICES.md",
113
- "bin",
114
- "deno.json",
115
- "deno.lock",
116
- "mod.ts",
117
- "runtime",
118
- "scripts/build_npm.ts",
119
- "skills",
120
- "src",
121
- ];
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;
122
124
  const PRODUCTION_GITHUB_ENVIRONMENT = "production";
123
125
  const REQUIRED_GITHUB_VERCEL_SECRET_NAMES = ["VERCEL_TOKEN"];
124
126
  const REQUIRED_GITHUB_VERCEL_ID_NAMES = [
@@ -390,14 +392,17 @@ async function writeTextIfChanged(path, text) {
390
392
  }
391
393
  async function defaultCommandRunner(command, args, options) {
392
394
  return await new Promise((resolvePromise) => {
393
- const inherit = options.stdio === "inherit";
395
+ const inherit = options.stdio === "inherit" ||
396
+ options.stdio === "inherit-stderr";
394
397
  const pipeInput = !inherit && options.input !== undefined;
395
398
  const child = (0, node_child_process_1.spawn)(command, args, {
396
399
  cwd: options.cwd,
397
400
  env: options.env,
398
- stdio: inherit
399
- ? "inherit"
400
- : [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"],
401
406
  });
402
407
  const stdoutChunks = [];
403
408
  const stderrChunks = [];
@@ -683,6 +688,215 @@ function getPublishedLoomDependencySpec(packageJson) {
683
688
  }
684
689
  return dependency;
685
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
+ }
686
900
  function isLocalPackageSpec(spec) {
687
901
  return spec.startsWith("file:") || spec.startsWith("link:") ||
688
902
  spec.startsWith("workspace:");
@@ -894,19 +1108,20 @@ function ensureLinguiGitignoreText(existingText, generatedCatalogs) {
894
1108
  text: nextText,
895
1109
  };
896
1110
  }
897
- function loomDevStateGitignoreLineMatches(line) {
1111
+ function loomDevGitignoreLineMatches(line, path) {
898
1112
  const normalized = line.trim().replace(/^\/?/, "");
899
- return normalized === exports.LOOM_LOCAL_DEV_STATE_GITIGNORE_LINE ||
900
- normalized === ".loom/" || normalized === ".loom";
1113
+ return normalized === path || normalized === ".loom/" ||
1114
+ normalized === ".loom";
901
1115
  }
902
1116
  function ensureLoomDevStateGitignoreText(existingText) {
903
1117
  const normalized = existingText ? normalizeText(existingText) : "";
904
1118
  const lines = normalized
905
1119
  .split("\n")
906
1120
  .filter((line, index, array) => index < array.length - 1 || line !== "");
907
- const missingLines = lines.some(loomDevStateGitignoreLineMatches)
908
- ? []
909
- : [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)));
910
1125
  const nextText = missingLines.length
911
1126
  ? `${[...lines, ...missingLines].join("\n")}\n`
912
1127
  : normalized;
@@ -1255,18 +1470,34 @@ function dependencyExecutable(tooling, executable) {
1255
1470
  return `yarn ${executable}`;
1256
1471
  }
1257
1472
  }
1258
- 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 = {}) {
1259
1483
  switch (tooling.manager) {
1260
1484
  case "deno":
1261
1485
  return "deno install";
1262
1486
  case "npm":
1263
1487
  return `npm install --save-exact ${name}@${version}`;
1264
1488
  case "pnpm":
1265
- 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";
1266
1492
  case "yarn":
1267
1493
  return `yarn add --exact ${name}@${version}`;
1268
1494
  }
1269
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
+ }
1270
1501
  function getDbExpectedScripts(config, tooling) {
1271
1502
  const drizzleKit = dependencyExecutable(tooling.dependencies, "drizzle-kit");
1272
1503
  return {
@@ -1756,6 +1987,10 @@ function getApiKeysConfig(framework, dbConfig, packageJson, featureConfig) {
1756
1987
  ? "src/api-lib/apiKeys"
1757
1988
  : "api-lib/apiKeys";
1758
1989
  return {
1990
+ // Recorded by the app; Loom never infers or rewrites this choice.
1991
+ ...(featureConfig?.betterAuthHttpEndpoints !== undefined
1992
+ ? { betterAuthHttpEndpoints: featureConfig.betterAuthHttpEndpoints }
1993
+ : {}),
1759
1994
  entrypoints: {
1760
1995
  adminPage: featureConfig?.entrypoints?.adminPage ??
1761
1996
  `${appRoot}/admin/api-keys/page.tsx`,
@@ -1972,7 +2207,7 @@ function ensureNextAgentsMdText(existingText) {
1972
2207
  : "\n\n"}${block}`;
1973
2208
  return { changed: text !== normalized, text };
1974
2209
  }
1975
- function getManagedDevOverrideBlock(overrideSpec, state) {
2210
+ function getManagedDevOverrideBlock(overrideSpec, state, layout = {}) {
1976
2211
  // This is a workaround for current pnpm behavior around local package
1977
2212
  // development. In testing with pnpm 10.x, direct `pnpm link` against Loom
1978
2213
  // mutated pnpm-workspace overrides anyway and broke peer resolution from
@@ -1991,13 +2226,32 @@ function getManagedDevOverrideBlock(overrideSpec, state) {
1991
2226
  : null,
1992
2227
  ].filter((line) => line !== null)
1993
2228
  : [];
2229
+ const pad = " ".repeat(layout.indent ?? 2);
1994
2230
  return [
1995
- ` ${exports.LOOM_MANAGED_DEV_OVERRIDE_START}`,
1996
- ...stateLines.map((line) => ` ${line}`),
1997
- ` "${exports.LOOM_DEPENDENCY}": ${JSON.stringify(overrideSpec)}`,
1998
- ` ${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}`,
1999
2241
  ].join("\n");
2000
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
+ }
2001
2255
  function getManagedDevOverrideBlockRegex() {
2002
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");
2003
2257
  }
@@ -2007,24 +2261,149 @@ function formatYamlLines(lines) {
2007
2261
  }
2008
2262
  return lines.length ? `${lines.join("\n")}\n` : "";
2009
2263
  }
2010
- function findTopLevelSection(lines, sectionName) {
2011
- const header = `${sectionName}:`;
2012
- const start = lines.findIndex((line) => line === header);
2013
- 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)
2014
2276
  return null;
2015
- }
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";
2016
2283
  let end = lines.length;
2017
- for (let index = start + 1; index < lines.length; index += 1) {
2018
- const line = lines[index];
2019
- if (line !== "" && !line.startsWith(" ") && !line.startsWith("\t")) {
2020
- 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))
2021
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);
2022
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);
2023
2398
  }
2024
- 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
+ };
2025
2404
  }
2026
2405
  function hasUnmanagedLoomOverride(text) {
2027
- return /^[ \t]+["']?@gadicc\/loom["']?\s*:/m.test(text);
2406
+ return getPnpmWorkspaceOverrideKeys(text).some(overrideKeyTargetsLoom);
2028
2407
  }
2029
2408
  function getManagedDevOverrideSpec(text) {
2030
2409
  if (!text) {
@@ -2074,7 +2453,7 @@ function getManagedDevState(text) {
2074
2453
  }
2075
2454
  function setManagedDevStateText(existingText, overrideSpec, state) {
2076
2455
  const normalized = existingText ? normalizeText(existingText) : "";
2077
- const nextText = normalized.replace(getManagedDevOverrideBlockRegex(), `${getManagedDevOverrideBlock(overrideSpec, state)}\n`);
2456
+ const nextText = normalized.replace(getManagedDevOverrideBlockRegex(), `${getManagedDevOverrideBlock(overrideSpec, state, getManagedDevOverrideBlockLayout(getManagedDevOverrideBlockText(normalized)))}\n`);
2078
2457
  return {
2079
2458
  changed: nextText !== normalized,
2080
2459
  text: nextText,
@@ -2103,17 +2482,45 @@ function ensurePnpmWorkspaceLocalDevText(existingText, overrideSpec) {
2103
2482
  text: normalized,
2104
2483
  };
2105
2484
  }
2106
- const blockLines = getManagedDevOverrideBlock(overrideSpec).split("\n");
2107
2485
  const lines = baseText === "" ? [] : baseText.replace(/\n$/, "").split("\n");
2108
- const overridesSection = findTopLevelSection(lines, "overrides");
2109
- if (overridesSection) {
2110
- 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"));
2111
2516
  }
2112
2517
  else {
2113
2518
  if (lines.length && lines.at(-1) !== "") {
2114
2519
  lines.push("");
2115
2520
  }
2116
- lines.push("overrides:", ...blockLines);
2521
+ lines.push("overrides:", ...getManagedDevOverrideBlock(overrideSpec, undefined, {
2522
+ createdHeader: true,
2523
+ }).split("\n"));
2117
2524
  }
2118
2525
  const nextText = formatYamlLines(lines);
2119
2526
  return {
@@ -2130,19 +2537,21 @@ function clearPnpmWorkspaceLocalDevText(existingText) {
2130
2537
  text: normalized,
2131
2538
  };
2132
2539
  }
2540
+ const { createdHeader, replacedHeader } = getManagedDevOverrideBlockLayout(getManagedDevOverrideBlockText(normalized));
2133
2541
  const withoutManaged = normalized.replace(getManagedDevOverrideBlockRegex(), "");
2134
2542
  const lines = withoutManaged === ""
2135
2543
  ? []
2136
2544
  : withoutManaged.replace(/\n$/, "").split("\n");
2137
- const overridesSection = findTopLevelSection(lines, "overrides");
2138
- if (overridesSection) {
2139
- const bodyLines = lines.slice(overridesSection.start + 1, overridesSection.end);
2140
- const hasEntries = bodyLines.some((line) => {
2141
- const trimmed = line.trim();
2142
- return trimmed !== "" && !trimmed.startsWith("#");
2143
- });
2144
- if (!hasEntries) {
2145
- 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);
2146
2555
  }
2147
2556
  }
2148
2557
  const nextText = formatYamlLines(lines).replace(/\n{3,}/g, "\n\n");
@@ -2151,6 +2560,262 @@ function clearPnpmWorkspaceLocalDevText(existingText) {
2151
2560
  text: nextText,
2152
2561
  };
2153
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
+ }
2154
2819
  function pnpmWorkspaceExcludesMinimumReleaseAge(text, dependency) {
2155
2820
  if (!text)
2156
2821
  return false;
@@ -2215,6 +2880,13 @@ async function writeTextOrDeleteIfEmpty(path, text) {
2215
2880
  await (0, promises_1.mkdir)((0, node_path_1.dirname)(path), { recursive: true });
2216
2881
  await (0, promises_1.writeFile)(path, text, "utf8");
2217
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
+ }
2218
2890
  async function ensurePnpmProject(cwd, packageJson) {
2219
2891
  if (packageJson.packageManager?.startsWith("pnpm@") ||
2220
2892
  await exists((0, node_path_1.join)(cwd, "pnpm-lock.yaml")) ||
@@ -2327,33 +2999,49 @@ async function isLocalLoomBuildStale(sourceRoot, localPackagePath) {
2327
2999
  if (!outputPackageStat) {
2328
3000
  return true;
2329
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
+ }
2330
3018
  const sourceNewest = await getNewestMtimeMs(sourceRoot);
2331
3019
  const outputMtime = outputPackageStat.mtime?.getTime() ?? 0;
2332
3020
  return sourceNewest > outputMtime;
2333
3021
  }
2334
- async function filesHaveSameText(leftPath, rightPath) {
2335
- const [left, right] = await Promise.all([
2336
- readTextIfExists(leftPath),
2337
- readTextIfExists(rightPath),
2338
- ]);
2339
- 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");
2340
3037
  }
2341
- async function isInstalledLocalLoomPackageStale(cwd, localPackagePath) {
2342
- const installedPath = (0, node_path_1.join)(cwd, "node_modules", exports.LOOM_DEPENDENCY);
2343
- if (!await exists((0, node_path_1.join)(installedPath, "package.json"))) {
2344
- return true;
2345
- }
2346
- const sentinelFiles = [
2347
- "package.json",
2348
- (0, node_path_1.join)("script", "bin", "loom.js"),
2349
- (0, node_path_1.join)("script", "src", "cli", "mod.js"),
2350
- ];
2351
- for (const relativePath of sentinelFiles) {
2352
- if (!await filesHaveSameText((0, node_path_1.join)(localPackagePath, relativePath), (0, node_path_1.join)(installedPath, relativePath))) {
2353
- return true;
2354
- }
2355
- }
2356
- 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));
2357
3045
  }
2358
3046
  async function runCommandOrThrow(commandRunner, command, args, options) {
2359
3047
  const result = await commandRunner(command, args, options);
@@ -2422,6 +3110,10 @@ async function readLocalDevState(cwd) {
2422
3110
  if (state.version !== 1 || state.dependency !== exports.LOOM_DEPENDENCY) {
2423
3111
  return null;
2424
3112
  }
3113
+ // Retired: whole-file package.json snapshots are never written back.
3114
+ const retired = state;
3115
+ delete retired.packageJsonBeforeOverride;
3116
+ delete retired.packageJsonWithOverride;
2425
3117
  return state;
2426
3118
  }
2427
3119
  catch {
@@ -2475,15 +3167,17 @@ function compareParsedVersions(left, right) {
2475
3167
  }
2476
3168
  return left.prerelease.localeCompare(right.prerelease);
2477
3169
  }
2478
- 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) {
2479
3173
  const publication = await resolveLoomCommitPublication(sourceRoot, sourceCommit, commandRunner, env, preferredSpec);
2480
3174
  switch (publication.status) {
2481
3175
  case "published":
2482
3176
  return publication;
2483
3177
  case "not-on-origin-main":
2484
- 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\`.`);
2485
3179
  case "no-release-tag":
2486
- 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\`.`);
2487
3181
  }
2488
3182
  }
2489
3183
  function parseSemverTags(tags) {
@@ -2502,7 +3196,7 @@ async function getPackageRelevantChangedPaths(sourceRoot, fromRef, toRef, comman
2502
3196
  "--name-only",
2503
3197
  `${fromRef}..${toRef}`,
2504
3198
  "--",
2505
- ...LOOM_PACKAGE_RELEVANT_PATHS,
3199
+ ...localDevPackage_js_1.LOOM_PACKAGE_RELEVANT_PATHS,
2506
3200
  ], env);
2507
3201
  return changedPaths
2508
3202
  ?.split("\n")
@@ -2553,127 +3247,310 @@ async function resolveLoomCommitPublication(sourceRoot, sourceCommit, commandRun
2553
3247
  }
2554
3248
  return { status: "no-release-tag" };
2555
3249
  }
2556
- 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) {
2557
3286
  const manifest = await readManifestIfExists(cwd);
2558
3287
  const tooling = await (0, projectTooling_js_1.detectProjectTooling)(cwd, manifest?.project?.tooling);
2559
3288
  const denoMode = usesDenoTooling(tooling);
2560
- const workspacePath = (0, node_path_1.join)(cwd, "pnpm-workspace.yaml");
2561
- const workspaceText = await readTextIfExists(workspacePath);
2562
- const overrideSpec = getManagedDevOverrideSpec(workspaceText);
3289
+ const activePnpmOverride = denoMode ? null : getActivePnpmLocalDevOverride(await readTextIfExists((0, node_path_1.join)(cwd, "pnpm-workspace.yaml")), await readPackageJsonIfExists(cwd) ?? {});
2563
3290
  const denoConfig = denoMode
2564
3291
  ? await getDenoConfigForLinks(cwd, tooling)
2565
3292
  : null;
2566
3293
  const denoLink = denoConfig
2567
3294
  ? await findLocalLoomDenoLink(cwd, await (0, projectTooling_js_1.readDenoLinks)(cwd, denoConfig))
2568
3295
  : null;
2569
- if (!overrideSpec && !denoLink) {
2570
- if (options.requireActive) {
2571
- throw new Error("No managed Loom local-dev override is active. Run `loom dev local /path/to/loom` first.");
2572
- }
2573
- return {
2574
- buildRan: false,
2575
- changed: false,
2576
- notes: [],
2577
- packageRefreshRan: false,
2578
- ranCommands: [],
2579
- };
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();
2580
3317
  }
2581
- const { packageJson } = await readProjectPackageJson(cwd);
2582
- if (!denoMode)
2583
- await ensurePnpmProject(cwd, packageJson);
2584
- const commandRunner = options.commandRunner ?? defaultCommandRunner;
2585
3318
  const env = options.env ?? node_process_1.default.env;
2586
- const localPackagePath = denoLink?.path ??
2587
- fileSpecToPath(cwd, overrideSpec);
2588
- const sourceRoot = await resolveLocalLoomSourceRoot(localPackagePath);
2589
- const configuredSpec = packageJson.dependencies?.[exports.LOOM_DEPENDENCY] ??
2590
- packageJson.devDependencies?.[exports.LOOM_DEPENDENCY];
2591
- const desiredLocalVersion = await readPackageVersion((0, node_path_1.join)(cwd, "node_modules", exports.LOOM_DEPENDENCY)) ?? versionFromDependencySpec(configuredSpec) ??
2592
- await readPackageVersion(localPackagePath);
2593
- const currentLocalVersion = await readPackageVersion(localPackagePath);
2594
- const buildEnv = desiredLocalVersion && !env.NPM_PACKAGE_VERSION
2595
- ? { ...env, NPM_PACKAGE_VERSION: desiredLocalVersion }
2596
- : env;
2597
- const ranCommands = [];
2598
- let buildRan = false;
2599
- if (options.force || denoMode && currentLocalVersion !== desiredLocalVersion ||
2600
- await isLocalLoomBuildStale(sourceRoot, localPackagePath)) {
2601
- if (!sourceRoot) {
2602
- throw new Error(`Could not find the Loom source checkout for ${localPackagePath}; cannot rebuild the local package.`);
2603
- }
2604
- await runCommandOrThrow(commandRunner, "deno", ["task", "build"], {
2605
- cwd: sourceRoot,
2606
- env: buildEnv,
2607
- stdio: "inherit",
2608
- });
2609
- ranCommands.push("deno task build");
2610
- buildRan = true;
2611
- }
2612
- const packageRefreshNeeded = buildRan ||
2613
- await isInstalledLocalLoomPackageStale(cwd, localPackagePath);
2614
- let packageRefreshRan = false;
2615
- if (options.force || packageRefreshNeeded) {
2616
- if (denoMode) {
2617
- await runCommandOrThrow(commandRunner, "deno", ["install"], {
2618
- cwd,
2619
- env,
2620
- stdio: "inherit",
2621
- });
2622
- 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
+ ]);
2623
3336
  }
2624
- else {
2625
- const packageSpec = `${exports.LOOM_DEPENDENCY}@file:${localPackagePath}`;
2626
- await runCommandOrThrow(commandRunner, "pnpm", ["update", "--no-save", packageSpec], { cwd, env, stdio: "inherit" });
2627
- ranCommands.push(`pnpm update --no-save ${packageSpec}`);
2628
- await runCommandOrThrow(commandRunner, "pnpm", ["install"], {
2629
- cwd,
2630
- env,
2631
- stdio: "inherit",
2632
- });
2633
- 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
+ };
2634
3367
  }
2635
- packageRefreshRan = true;
2636
- }
2637
- const currentWorkspaceText = await readTextIfExists(workspacePath);
2638
- const currentState = denoMode
2639
- ? await readLocalDevState(cwd)
2640
- : await getCurrentLocalDevState(cwd, currentWorkspaceText);
2641
- let state = null;
2642
- if (buildRan || packageRefreshRan || !currentState) {
2643
- state = await buildLocalDevState(localPackagePath, sourceRoot, commandRunner, env);
2644
- if (!denoMode) {
2645
- const stateUpdate = setManagedDevStateText(await readTextIfExists(workspacePath), overrideSpec, state);
2646
- if (stateUpdate.changed) {
2647
- 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");
2648
3430
  }
2649
- }
2650
- }
2651
- if (state ?? currentState) {
2652
- await writeLocalDevStateIfChanged(cwd, state ?? currentState);
2653
- }
2654
- const notes = packageRefreshRan
2655
- ? [
2656
- `Local Loom package refreshed from ${localPackagePath}.`,
2657
- "If this command was using a stale installed Loom CLI, rerun it now.",
2658
- ]
2659
- : [`Local Loom package is already fresh: ${localPackagePath}`];
2660
- const recordedState = state ?? currentState;
2661
- if (recordedState?.sourceCommit) {
2662
- notes.push(`Recorded local Loom sync at commit ${recordedState.sourceCommit.slice(0, 12)}${recordedState.sourceDirty ? " with a dirty source tree" : ""}.`);
2663
- }
2664
- else if (sourceRoot) {
2665
- notes.push("Could not record a Loom git commit for this sync; `loom dev published` cannot prove whether unpublished Loom changes are required.");
2666
- }
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) {
2667
3531
  return {
2668
- buildRan,
2669
- changed: buildRan || packageRefreshRan,
2670
- localPackagePath,
2671
- notes,
2672
- packageRefreshRan,
2673
- 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.`),
2674
3536
  };
2675
3537
  }
2676
- 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) {
2677
3554
  const { packageJson } = await readProjectPackageJson(cwd);
2678
3555
  const manifest = await readManifestIfExists(cwd);
2679
3556
  const tooling = await (0, projectTooling_js_1.detectProjectTooling)(cwd, manifest?.project?.tooling);
@@ -2686,8 +3563,23 @@ async function useLocalDevPackage(cwd, inputPath) {
2686
3563
  const denoConfig = await getDenoConfigForLinks(cwd, tooling);
2687
3564
  const relativeLocalPackagePath = (0, node_path_1.relative)(cwd, localPackagePath)
2688
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
+ }
2689
3580
  const update = await (0, projectTooling_js_1.mutateDenoLinks)(cwd, denoConfig, {
2690
3581
  add: relativeLocalPackagePath,
3582
+ remove: previousLinks,
2691
3583
  });
2692
3584
  const state = {
2693
3585
  dependency: exports.LOOM_DEPENDENCY,
@@ -2711,26 +3603,218 @@ async function useLocalDevPackage(cwd, inputPath) {
2711
3603
  }
2712
3604
  await ensurePnpmProject(cwd, packageJson);
2713
3605
  const overrideSpec = `file:${localPackagePath}`;
2714
- const workspacePath = (0, node_path_1.join)(cwd, "pnpm-workspace.yaml");
2715
- const update = ensurePnpmWorkspaceLocalDevText(await readTextIfExists(workspacePath), overrideSpec);
2716
- if (update.conflict) {
2717
- throw new Error(update.conflict);
2718
- }
2719
- const changedFiles = [];
2720
- if (update.changed) {
2721
- await writeTextOrDeleteIfEmpty(workspacePath, update.text);
2722
- changedFiles.push("pnpm-workspace.yaml");
2723
- }
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);
2724
3615
  return {
2725
3616
  changedFiles,
2726
3617
  notes: [
2727
- `Local Loom dev override is active: ${overrideSpec}`,
3618
+ `Local Loom dev override is active in ${formatPnpmOverrideLocation(placement.location)}: ${overrideSpec}`,
3619
+ ...placement.notes,
2728
3620
  "Run `loom dev sync` to rebuild the local Loom package and refresh this project's pnpm install when needed.",
2729
- `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}.`,
2730
3622
  ],
2731
3623
  };
2732
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
+ }
2733
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) {
2734
3818
  const { packageJson } = await readProjectPackageJson(cwd);
2735
3819
  const manifest = await readManifestIfExists(cwd);
2736
3820
  const tooling = await (0, projectTooling_js_1.detectProjectTooling)(cwd, manifest?.project?.tooling);
@@ -2744,75 +3828,227 @@ async function usePublishedDevPackage(cwd, options = {}) {
2744
3828
  const denoConfig = denoMode
2745
3829
  ? await getDenoConfigForLinks(cwd, tooling)
2746
3830
  : null;
2747
- const denoLink = denoConfig
2748
- ? await findLocalLoomDenoLink(cwd, await (0, projectTooling_js_1.readDenoLinks)(cwd, denoConfig))
2749
- : null;
2750
- const activeOverrideSpec = denoLink?.link ??
2751
- getManagedDevOverrideSpec(workspaceText);
2752
- const localLockfileResolution = denoMode
3831
+ const lockfileText = denoMode
2753
3832
  ? null
2754
- : await getProjectLocalLoomLockfileResolution(cwd);
2755
- const state = denoMode
2756
- ? await readLocalDevState(cwd)
2757
- : 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;
2758
3837
  const notes = [];
2759
- let publishedSpec = getPublishedLoomDependencySpec(packageJson);
2760
- const needsPublicationProof = Boolean(activeOverrideSpec || localLockfileResolution);
2761
- if (needsPublicationProof && state?.sourceCommit) {
2762
- if (state.sourceDirty) {
2763
- 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\`.`);
2764
- }
2765
- if (!state.sourceRoot) {
2766
- 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.`);
2767
3889
  }
2768
- const publication = await findPublishedLoomPublicationForCommit(state.sourceRoot, state.sourceCommit, commandRunner, env, publishedSpec);
2769
- publishedSpec = publication.version;
2770
- if (publication.reason === "contains-commit") {
2771
- 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.`);
2772
3892
  }
2773
- else {
2774
- 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
+ }
2775
3900
  }
2776
3901
  }
2777
- else if (needsPublicationProof) {
2778
- 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
+ }
2779
3910
  }
2780
- const dependencyUpdate = await (0, projectTooling_js_1.mutateProjectDependencies)(cwd, tooling.dependencies, {
2781
- dependencies: { [exports.LOOM_DEPENDENCY]: publishedSpec },
2782
- replace: true,
2783
- });
2784
- const denoUpdate = denoConfig && denoLink
2785
- ? 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 })
2786
3913
  : null;
2787
- const update = denoMode
2788
- ? { changed: denoUpdate?.changed ?? false, text: "" }
2789
- : clearPnpmWorkspaceLocalDevText(await readTextIfExists(workspacePath));
2790
- const changedFiles = [];
2791
- if (dependencyUpdate.changed) {
2792
- changedFiles.push(dependencyUpdate.config);
2793
- }
2794
- if (update.changed) {
2795
- if (denoMode) {
2796
- 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;
2797
3921
  }
2798
- else {
2799
- await writeTextOrDeleteIfEmpty(workspacePath, update.text);
2800
- 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
+ }
2801
3943
  }
2802
3944
  }
2803
- if (update.changed || localLockfileResolution) {
2804
- notes.push(denoMode
2805
- ? `Run \`deno install\` in this project to return node_modules and deno.lock to published ${exports.LOOM_DEPENDENCY}@${publishedSpec}.`
2806
- : `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
+ }
2807
3949
  }
2808
- if (localLockfileResolution) {
2809
- 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
+ }
2810
3980
  }
2811
3981
  return {
2812
3982
  changedFiles,
2813
3983
  notes,
2814
3984
  };
2815
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
+ }
2816
4052
  async function ensureManagedAgentsFile(cwd) {
2817
4053
  const relativePath = "AGENTS.md";
2818
4054
  const agentsPath = (0, node_path_1.join)(cwd, relativePath);
@@ -3027,7 +4263,15 @@ async function checkManagedAgentsFile(cwd) {
3027
4263
  warnings: [],
3028
4264
  };
3029
4265
  }
3030
- 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) {
3031
4275
  const manifest = await readManifestIfExists(cwd);
3032
4276
  let denoLink = null;
3033
4277
  let denoConfig = null;
@@ -3042,8 +4286,17 @@ async function checkManagedLocalDevOverride(cwd, production = false) {
3042
4286
  // The main project tooling check reports invalid configuration separately.
3043
4287
  }
3044
4288
  const workspaceText = await readTextIfExists((0, node_path_1.join)(cwd, "pnpm-workspace.yaml"));
3045
- const overrideSpec = getManagedDevOverrideSpec(workspaceText);
3046
- 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) {
3047
4300
  return {
3048
4301
  issues: [],
3049
4302
  suggestions: [],
@@ -3052,19 +4305,45 @@ async function checkManagedLocalDevOverride(cwd, production = false) {
3052
4305
  }
3053
4306
  const location = denoLink
3054
4307
  ? `${denoConfig} links: ${denoLink.link}`
3055
- : `pnpm-workspace.yaml: ${overrideSpec}`;
4308
+ : workspaceSpec
4309
+ ? `pnpm-workspace.yaml: ${workspaceSpec}`
4310
+ : packageJsonOverride;
3056
4311
  const restore = denoLink
3057
4312
  ? "Run `loom dev published`, then run `deno install` before committing or shipping a published build."
3058
- : `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
+ }
3059
4337
  return {
3060
4338
  issues: production
3061
4339
  ? [
3062
4340
  `Local Loom dev override is active in ${location}`,
3063
4341
  ]
3064
4342
  : [],
3065
- suggestions: [restore],
3066
- warnings: production ? [] : [
4343
+ suggestions,
4344
+ warnings: production ? warnings : [
3067
4345
  `Local Loom dev override is active in ${location}`,
4346
+ ...warnings,
3068
4347
  ],
3069
4348
  };
3070
4349
  }
@@ -3103,7 +4382,6 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
3103
4382
  const issues = [];
3104
4383
  const suggestions = new Set();
3105
4384
  const warnings = [];
3106
- const dependency = packageJson.dependencies?.[exports.LOOM_DEPENDENCY];
3107
4385
  const production = options.production;
3108
4386
  const projectMetadata = await (0, projectTooling_js_1.readProjectPackageMetadata)(cwd);
3109
4387
  let dependencyTooling = {
@@ -3117,8 +4395,38 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
3117
4395
  catch {
3118
4396
  // The main tooling check owns the validation error; release hints can fall back.
3119
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;
3120
4404
  const localLockfileResolution = await getProjectLocalLoomLockfileResolution(cwd);
3121
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;
3122
4430
  if (localLockfileResolution) {
3123
4431
  addReleaseCheckMessage(issues, warnings, production, `pnpm-lock.yaml resolves @gadicc/loom to a local package: ${localLockfileResolution}`);
3124
4432
  suggestions.add("Run `loom dev published`, then refresh the lockfile with the published @gadicc/loom version before production build.");
@@ -3150,8 +4458,10 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
3150
4458
  "package-equivalent"
3151
4459
  ? `package-relevant files match ${exports.LOOM_DEPENDENCY}@${publication.version}`
3152
4460
  : `it is published as ${exports.LOOM_DEPENDENCY}@${publication.version}`;
3153
- addReleaseCheckMessage(issues, warnings, production, `This app was last synced against Loom commit ${shortCommit}; ${publicationDescription}, but ${dependencyTooling.config} is pinned to ${dependency}.`);
3154
- 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));
3155
4465
  }
3156
4466
  else if (localLockfileResolution) {
3157
4467
  const publicationDescription = publication.reason ===
@@ -3159,7 +4469,13 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
3159
4469
  ? `has no package-relevant changes after ${publication.tag}, so ${exports.LOOM_DEPENDENCY}@${publication.version} covers it`
3160
4470
  : `is published as ${exports.LOOM_DEPENDENCY}@${publication.version}`;
3161
4471
  warnings.push(`The synced Loom commit ${shortCommit} ${publicationDescription}; refresh the lockfile away from ${localLockfileResolution}.`);
3162
- 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));
3163
4479
  }
3164
4480
  break;
3165
4481
  }
@@ -3184,8 +4500,12 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
3184
4500
  else {
3185
4501
  const installedPackage = parseJson(installedPackageText, (0, node_path_1.join)("node_modules", exports.LOOM_DEPENDENCY, "package.json"));
3186
4502
  if (installedPackage.version !== dependency) {
3187
- issues.push(`Installed ${exports.LOOM_DEPENDENCY} version ${installedPackage.version} does not match ${dependencyTooling.config} ${dependency}.`);
3188
- 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));
3189
4509
  }
3190
4510
  }
3191
4511
  }
@@ -4763,6 +6083,18 @@ import { apiKeyPolicy } from "${toAliasImportPath(config.modules.policyModule)}"
4763
6083
  import { apiKeyAuditRepository } from "${toAliasImportPath(config.modules.repositoryModule)}";
4764
6084
 
4765
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
+ // });
4766
6098
  export const apiKeyVerifier: ApiKeyVerifier = {
4767
6099
  verify() {
4768
6100
  return Promise.resolve({ ok: false, code: "invalid_credential" });
@@ -6166,9 +7498,11 @@ async function ensureMinioBucket(cwd, commandRunner, env, endpoint, bucket, acce
6166
7498
  ok: false,
6167
7499
  };
6168
7500
  }
6169
- async function promptForLocalFilesValue(question, secret = false) {
7501
+ async function promptForLocalFilesValue(question, secret = false, context = "MinIO") {
6170
7502
  if (!node_process_1.default.stdin.isTTY) {
6171
- throw new Error("MinIO admin credentials are required. Run interactively or set MINIO_ROOT_USER and MINIO_ROOT_PASSWORD in the command environment.");
7503
+ throw new Error(context === "MinIO"
7504
+ ? "MinIO admin credentials are required. Run interactively or set MINIO_ROOT_USER and MINIO_ROOT_PASSWORD in the command environment."
7505
+ : "PostgreSQL admin credentials are required. Run interactively or set LOOM_DB_LOCAL_ADMIN_PASSWORD in the command environment.");
6172
7506
  }
6173
7507
  if (!secret) {
6174
7508
  const input = (0, promises_2.createInterface)({
@@ -6200,7 +7534,7 @@ async function promptForLocalFilesValue(question, secret = false) {
6200
7534
  }
6201
7535
  if (character === "\u0003") {
6202
7536
  stdin.off("data", onData);
6203
- rejectPromise(new Error("MinIO setup was cancelled."));
7537
+ rejectPromise(new Error(`${context} setup was cancelled.`));
6204
7538
  return;
6205
7539
  }
6206
7540
  if (character === "\u007f" || character === "\b") {
@@ -8582,7 +9916,7 @@ async function applyApiKeysFeature(cwd, framework, manifest, activate) {
8582
9916
  changedFiles.push(...materialized.changedFiles);
8583
9917
  notes.push(...materialized.notes);
8584
9918
  config.schema = materialized.schema;
8585
- 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.");
8586
9920
  }
8587
9921
  const scaffolds = [
8588
9922
  [config.modules.policyModule, apiKeysPolicyTemplate(), "policy"],
@@ -9619,160 +10953,1100 @@ async function checkFilesFeature(cwd, framework, manifest, options) {
9619
10953
  }
9620
10954
  }
9621
10955
  }
9622
- return {
9623
- issues,
9624
- suggestions: [...suggestions],
9625
- warnings,
9626
- };
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));
9627
11684
  }
9628
- async function checkMailFeature(cwd, framework, manifest, options) {
9629
- const issues = [];
9630
- const suggestions = new Set();
9631
- const warnings = [];
9632
- const feature = manifest.features.mail;
9633
- if (!feature || feature.status !== "active") {
9634
- return { issues, suggestions: [], warnings };
9635
- }
9636
- for (const dependency of ["auth", "db"]) {
9637
- if (manifest.features[dependency]?.status !== "active") {
9638
- issues.push(`Mail feature requires the active ${dependency} feature.`);
9639
- suggestions.add(`Run \`loom add ${dependency}\` before using mail.`);
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;
9640
11733
  }
9641
11734
  }
9642
- if (issues.length)
9643
- return { issues, suggestions: [...suggestions], warnings };
9644
- const { packageJson } = await readProjectPackageJson(cwd);
9645
- const dbConfig = mergeDbConfig(framework, manifest.features.db.config);
9646
- const config = getMailConfig(framework, dbConfig, packageJson, feature.config, manifest.features.jobs?.status === "active");
9647
- const schema = config.schema;
9648
- const latestSchema = getLatestManagedSchemaConfig(schema);
9649
- if (schema.mode !== "managed-local" || schema.blueprint !== "mail") {
9650
- issues.push("Mail must use the managed-local mail schema blueprint.");
9651
- suggestions.add("Run `loom add mail` to restore the mail schema config.");
9652
- }
9653
- if (schema.exports.length !== 3) {
9654
- issues.push("Mail schema must configure message, delivery, and event exports.");
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
+ });
9655
11758
  }
9656
- if (schema.version > MAIL_SCHEMA_BLUEPRINT_VERSION) {
9657
- issues.push(`Mail schema blueprint version ${schema.version} is newer than this Loom package supports.`);
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
+ }
11800
+ }
9658
11801
  }
9659
- else if (schema.version < MAIL_SCHEMA_BLUEPRINT_VERSION) {
9660
- warnings.push(`Mail schema blueprint is stale: ${schema.version} < ${MAIL_SCHEMA_BLUEPRINT_VERSION}.`);
9661
- suggestions.add("Run `loom db schemas sync`, then review and migrate the diff.");
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
+ })));
11814
+ }
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);
11857
+ }
11858
+ if (!proven)
11859
+ disabled = false;
11860
+ }
9662
11861
  }
9663
- const schemaText = await readTextIfExists((0, node_path_1.join)(cwd, schema.module));
9664
- if (!schemaText) {
9665
- issues.push(`Mail schema file is missing: ${schema.module}`);
9666
- suggestions.add("Run `loom db schemas sync`.");
11862
+ const loaded = [...context.modules.values()].filter((module) => module !== null);
11863
+ return {
11864
+ authModuleRead: authModule !== null,
11865
+ authModulePath,
11866
+ disabled: calls > 0 && disabled,
11867
+ modules: loaded,
11868
+ };
11869
+ }
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;
9667
11892
  }
9668
- else {
9669
- const currentHash = hashManagedSchemaText(schemaText);
9670
- if (currentHash !== schema.hash) {
9671
- if (currentHash === latestSchema.hash) {
9672
- warnings.push(`Mail schema manifest hash is stale for ${schema.module}.`);
9673
- suggestions.add("Run `loom db schemas sync` to refresh loom.json.");
9674
- }
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;
9675
11902
  else {
9676
- issues.push(`Mail schema file has local edits outside the managed hash: ${schema.module}`);
9677
- 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;
9678
11905
  }
11906
+ continue;
9679
11907
  }
9680
- const barrelText = await readTextIfExists((0, node_path_1.join)(cwd, dbConfig.dirs.schemaDir, "index.ts"));
9681
- if (!barrelText || !schemaBarrelExportsModule(barrelText, schema, dbConfig)) {
9682
- issues.push(`DB schema barrel does not export the managed mail schema: ${dbConfig.dirs.schemaDir}/index.ts`);
9683
- 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;
9684
11912
  }
11913
+ shape.entries.push({
11914
+ key: property[2],
11915
+ value: property[3] ? entry.slice(property[0].length) : property[2],
11916
+ });
9685
11917
  }
9686
- const requiredFiles = [
9687
- config.modules.accessModule,
9688
- config.modules.actionsModule,
9689
- config.modules.repositoryModule,
9690
- config.modules.serviceModule,
9691
- config.modules.transportModule,
9692
- config.entrypoints.adminPage,
9693
- config.entrypoints.webhookRoute,
9694
- ...(config.jobs.enabled ? [config.modules.jobModule] : []),
9695
- ];
9696
- for (const relativePath of requiredFiles) {
9697
- if (!await exists((0, node_path_1.join)(cwd, relativePath))) {
9698
- issues.push(`Mail scaffold file is missing: ${relativePath}`);
9699
- 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;
9700
11953
  }
9701
- }
9702
- const accessText = await readTextIfExists((0, node_path_1.join)(cwd, config.modules.accessModule));
9703
- if (accessText && !accessText.includes("authorizeMailAdmin")) {
9704
- issues.push(`Mail access module does not export authorizeMailAdmin: ${config.modules.accessModule}`);
9705
- }
9706
- const generatedDenyAll = accessText?.includes("Mail admin access policy is not configured.") ?? false;
9707
- if (generatedDenyAll) {
9708
- const message = `Mail admin access still uses the generated deny-all stub: ${config.modules.accessModule}`;
9709
- if (options.production)
9710
- issues.push(message);
9711
- else
9712
- warnings.push(message);
9713
- suggestions.add("Connect authorizeMailAdmin() to the app's fresh session/admin-role check.");
9714
- }
9715
- const contentChecks = [
9716
- [
9717
- config.modules.repositoryModule,
9718
- "@gadicc/loom/mail",
9719
- "Mail repository is not typed against the shared mail contract",
9720
- ],
9721
- [
9722
- config.modules.serviceModule,
9723
- "createLoomMailService",
9724
- "Mail service is not wired to the shared durable service",
9725
- ],
9726
- [
9727
- config.modules.transportModule,
9728
- "createPostalMailTransport",
9729
- "Mail transport is not wired to the Postal adapter",
9730
- ],
9731
- [
9732
- config.modules.transportModule,
9733
- "POSTAL_WEBHOOK_PUBLIC_KEYS",
9734
- "Mail transport does not configure Postal webhook public keys",
9735
- ],
9736
- [
9737
- config.entrypoints.webhookRoute,
9738
- "createPostalWebhookRouteHandler",
9739
- "Mail webhook route does not use the signed shared route handler",
9740
- ],
9741
- [
9742
- config.modules.actionsModule,
9743
- "authorizeMailAdmin",
9744
- "Mail admin actions do not enforce the app-owned admin boundary",
9745
- ],
9746
- [
9747
- config.entrypoints.adminPage,
9748
- "authorizeMailAdmin",
9749
- "Mail admin page does not enforce the app-owned admin boundary",
9750
- ],
9751
- ];
9752
- for (const [relativePath, snippet, label] of contentChecks) {
9753
- const text = await readTextIfExists((0, node_path_1.join)(cwd, relativePath));
9754
- if (text && !text.includes(snippet)) {
9755
- issues.push(`${label}: ${relativePath}`);
9756
- 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
+ }
9757
11965
  }
9758
11966
  }
9759
- if (config.ui.adapter === "mui" &&
9760
- !hasPackageDependency(packageJson, "@mui/material")) {
9761
- 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
+ }
9762
11997
  }
9763
- if (config.jobs.enabled && manifest.features.jobs?.status !== "active") {
9764
- warnings.push("Mail drain job is enabled while the Loom jobs feature is inactive.");
9765
- 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}`);
9766
12007
  }
9767
- return { issues, suggestions: [...suggestions], warnings };
9768
- }
9769
- function packageDependencySpec(packageJson, dependencyName) {
9770
- return packageJson.dependencies?.[dependencyName] ??
9771
- packageJson.devDependencies?.[dependencyName];
12008
+ return [...new Set(warnings)];
9772
12009
  }
9773
- function dependencyMajorMinor(spec) {
9774
- const match = spec?.match(/(\d+)\.(\d+)/);
9775
- 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;
9776
12050
  }
9777
12051
  async function checkApiKeysFeature(cwd, framework, manifest, options) {
9778
12052
  const issues = [];
@@ -9918,6 +12192,57 @@ async function checkApiKeysFeature(cwd, framework, manifest, options) {
9918
12192
  if (issues.length || warnings.length) {
9919
12193
  suggestions.add("Run `loom add api-keys` to restore missing foundation files without overwriting custom modules.");
9920
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
+ }
9921
12246
  return { issues, suggestions: [...suggestions], warnings };
9922
12247
  }
9923
12248
  async function checkAuthFeature(cwd, framework, manifest) {
@@ -10708,6 +13033,22 @@ async function checkProject(cwd, env = node_process_1.default.env, options = {})
10708
13033
  else if (isLocalPackageSpec(dependency)) {
10709
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.`);
10710
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
+ }
10711
13052
  const manifestPath = (0, node_path_1.join)(cwd, "loom.json");
10712
13053
  const manifestText = await readTextIfExists(manifestPath);
10713
13054
  let manifest = null;
@@ -10791,7 +13132,7 @@ async function checkProject(cwd, env = node_process_1.default.env, options = {})
10791
13132
  for (const suggestion of nextGuidanceCheck.suggestions) {
10792
13133
  suggestions.add(suggestion);
10793
13134
  }
10794
- const localDevCheck = await checkManagedLocalDevOverride(cwd, options.production ?? false);
13135
+ const localDevCheck = await checkManagedLocalDevOverride(cwd, options.production ?? false, options.commandRunner ?? defaultCommandRunner, env);
10795
13136
  warnings.push(...localDevCheck.warnings);
10796
13137
  issues.push(...localDevCheck.issues);
10797
13138
  for (const suggestion of localDevCheck.suggestions) {
@@ -11198,7 +13539,7 @@ async function runStatus(cwd, io) {
11198
13539
  ? parseJson(installedPackageText, (0, node_path_1.join)("node_modules", exports.LOOM_DEPENDENCY, "package.json"))
11199
13540
  : null;
11200
13541
  const workspaceText = await readTextIfExists((0, node_path_1.join)(cwd, "pnpm-workspace.yaml"));
11201
- const overrideSpec = getManagedDevOverrideSpec(workspaceText);
13542
+ const pnpmOverride = getActivePnpmLocalDevOverride(workspaceText, packageJson);
11202
13543
  let denoOverride = null;
11203
13544
  try {
11204
13545
  const tooling = await (0, projectTooling_js_1.detectProjectTooling)(cwd, manifest?.project?.tooling);
@@ -11220,13 +13561,22 @@ async function runStatus(cwd, io) {
11220
13561
  io.out(`Loom status for ${projectName}`);
11221
13562
  io.out("");
11222
13563
  io.out("Package:");
11223
- 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"}`);
11224
13572
  io.out(` installed: ${installedPackage?.version ?? "not installed"}`);
11225
13573
  io.out(` local dev override: ${denoOverride
11226
13574
  ? `active (${denoOverride.config} links ${denoOverride.link})`
11227
- : overrideSpec
11228
- ? `active (${overrideSpec})`
11229
- : "none"}`);
13575
+ : pnpmOverride?.location === "pnpm-workspace.yaml"
13576
+ ? `active (${pnpmOverride.spec})`
13577
+ : pnpmOverride
13578
+ ? `active (${formatPnpmOverrideLocation(pnpmOverride.location)}: ${pnpmOverride.spec})`
13579
+ : "none"}`);
11230
13580
  io.out(` lockfile local resolution: ${localLockfileResolution ?? "none"}`);
11231
13581
  io.out("");
11232
13582
  io.out("Project:");
@@ -11340,6 +13690,7 @@ function printHelp({ out }) {
11340
13690
  out(" db fixtures Run the Loom-managed DB fixture dump script for the active DB feature.");
11341
13691
  out(" db schema-gen Run the Loom-managed Valibot generator workflow for the active DB feature. Pass extra generator args after `--`.");
11342
13692
  out(" db schemas sync Materialize active Loom-managed DB schema blueprints into app-local schema files.");
13693
+ out(" db local setup|check Provision or verify a restricted project database on existing local PostgreSQL.");
11343
13694
  out(" db neon setup Provision and connect a Vercel-managed Neon database for Production and Preview.");
11344
13695
  out(" db neon check Run the DB/Neon network checks registered for the active DB feature.");
11345
13696
  out(" db migrations verify-env Validate migration URL precedence and role metadata without printing credentials. Add --connect for a live access preflight.");
@@ -11362,8 +13713,12 @@ function printHelp({ out }) {
11362
13713
  out(" --network Run registered network checks after the local project checks.");
11363
13714
  out(" --production Treat local Loom dev overrides and local lockfile resolutions as release-blocking check failures.");
11364
13715
  out(" --no-progress Disable the interactive network progress renderer.");
13716
+ out(" --local-db-host <host> Local PostgreSQL host (default: db.localtest.me).");
13717
+ out(" --local-db-port <port> Local PostgreSQL port (default: 5432).");
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.");
11365
13720
  out(" --no-color Disable colored CLI output.");
11366
- 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.");
11367
13722
  out(" --force Force `loom dev sync` to rebuild and reinstall.");
11368
13723
  out(" --name <name> Override the resource name for `loom db neon setup`.");
11369
13724
  out(" --plan <plan> Pass a Vercel Marketplace plan id to Neon setup.");
@@ -12129,6 +14484,27 @@ async function runDb(cwd, command, args, io, options = {}) {
12129
14484
  return 1;
12130
14485
  }
12131
14486
  switch (command) {
14487
+ case "local": {
14488
+ const localOptions = {
14489
+ commandRunner: defaultCommandRunner,
14490
+ host: options.localDbHost,
14491
+ port: options.localDbPort,
14492
+ replaceLocalTarget: options.replaceLocalTarget,
14493
+ promptSecret: async (question) => await promptForLocalFilesValue(question, true, "PostgreSQL"),
14494
+ };
14495
+ if (args[0] === "setup") {
14496
+ const result = await (0, localDb_js_1.setupLocalDatabase)(cwd, localOptions);
14497
+ io.out(`Local PostgreSQL is ready: ${result.database} at ${result.host}:${result.port}.`);
14498
+ return 0;
14499
+ }
14500
+ if (args[0] === "check") {
14501
+ const result = await (0, localDb_js_1.checkLocalDatabase)(cwd, localOptions);
14502
+ io.out(`Local PostgreSQL check passed: ${result.database} as ${result.role}.`);
14503
+ return 0;
14504
+ }
14505
+ io.err("Usage: loom db local setup|check");
14506
+ return 1;
14507
+ }
12132
14508
  case "fixtures":
12133
14509
  return await runDbFixtures(cwd, args);
12134
14510
  case "schema-gen":
@@ -12158,7 +14534,9 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
12158
14534
  io.err("Missing local package path. Example: `loom dev local /path/to/loom`.");
12159
14535
  return 1;
12160
14536
  }
12161
- const result = await useLocalDevPackage(cwd, pathInput);
14537
+ const result = await useLocalDevPackage(cwd, pathInput, {
14538
+ onLockWait: io.err,
14539
+ });
12162
14540
  if (result.changedFiles.length) {
12163
14541
  io.out(`Updated ${result.changedFiles.join(", ")}.`);
12164
14542
  }
@@ -12170,6 +14548,7 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
12170
14548
  }
12171
14549
  if (!options.noSync) {
12172
14550
  const syncResult = await syncLocalDevPackage(cwd, {
14551
+ onLockWait: io.err,
12173
14552
  requireActive: true,
12174
14553
  });
12175
14554
  for (const note of syncResult.notes) {
@@ -12181,6 +14560,7 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
12181
14560
  case "sync": {
12182
14561
  const result = await syncLocalDevPackage(cwd, {
12183
14562
  force: options.force,
14563
+ onLockWait: io.err,
12184
14564
  requireActive: true,
12185
14565
  });
12186
14566
  if (result.changed) {
@@ -12195,7 +14575,9 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
12195
14575
  return 0;
12196
14576
  }
12197
14577
  case "published": {
12198
- const result = await usePublishedDevPackage(cwd);
14578
+ const result = await usePublishedDevPackage(cwd, {
14579
+ onLockWait: io.err,
14580
+ });
12199
14581
  if (result.changedFiles.length) {
12200
14582
  io.out(`Updated ${result.changedFiles.join(", ")}.`);
12201
14583
  }
@@ -12273,7 +14655,7 @@ async function runCheck(cwd, strictSkills, production, network, noProgress, noCo
12273
14655
  async function runCli(args = node_process_1.default.argv.slice(2), io = {
12274
14656
  err: (line) => console.error(line),
12275
14657
  out: (line) => console.log(line),
12276
- }) {
14658
+ }, options = {}) {
12277
14659
  const parsed = (0, node_util_1.parseArgs)({
12278
14660
  allowPositionals: true,
12279
14661
  args,
@@ -12293,6 +14675,8 @@ async function runCli(args = node_process_1.default.argv.slice(2), io = {
12293
14675
  help: { short: "h", type: "boolean" },
12294
14676
  jurisdiction: { type: "string" },
12295
14677
  "local-bucket": { type: "string" },
14678
+ "local-db-host": { type: "string" },
14679
+ "local-db-port": { type: "string" },
12296
14680
  "local-endpoint": { type: "string" },
12297
14681
  "local-provider": { type: "string" },
12298
14682
  "location-hint": { type: "string" },
@@ -12309,6 +14693,7 @@ async function runCli(args = node_process_1.default.argv.slice(2), io = {
12309
14693
  "production-bucket": { type: "string" },
12310
14694
  "preview-bucket": { type: "string" },
12311
14695
  repair: { type: "boolean" },
14696
+ "replace-local-target": { type: "boolean" },
12312
14697
  region: { type: "string" },
12313
14698
  resource: { type: "string" },
12314
14699
  "strict-skills": { type: "boolean" },
@@ -12340,13 +14725,29 @@ async function runCli(args = node_process_1.default.argv.slice(2), io = {
12340
14725
  !addListOnly &&
12341
14726
  !productionCheck &&
12342
14727
  !parsed.values["no-sync"]) {
12343
- 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
+ });
12344
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;
12345
14743
  for (const note of syncResult.notes) {
12346
- io.out(`Note: ${note}`);
14744
+ report(`Note: ${note}`);
12347
14745
  }
12348
- io.out("Re-run the original command to use the refreshed Loom package.");
12349
- 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.");
12350
14751
  }
12351
14752
  }
12352
14753
  switch (command) {
@@ -12391,10 +14792,13 @@ async function runCli(args = node_process_1.default.argv.slice(2), io = {
12391
14792
  acceptUnknownLicense: parsed.values["accept-unknown-license"],
12392
14793
  });
12393
14794
  case "env":
12394
- 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 });
12395
14796
  case "db":
12396
14797
  return await runDb(cwd, arg1, [arg2, ...rest].filter(Boolean), io, {
12397
14798
  connect: parsed.values.connect,
14799
+ localDbHost: parsed.values["local-db-host"],
14800
+ localDbPort: parsed.values["local-db-port"],
14801
+ replaceLocalTarget: parsed.values["replace-local-target"],
12398
14802
  name: parsed.values.name,
12399
14803
  environment: parsed.values.environment,
12400
14804
  envFile: parsed.values["env-file"],