@gadicc/loom 1.34.0 → 1.35.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +126 -49
  2. package/esm/src/apiKeys/authorize.d.ts.map +1 -1
  3. package/esm/src/apiKeys/authorize.js +71 -0
  4. package/esm/src/apiKeys/betterAuth.d.ts +123 -0
  5. package/esm/src/apiKeys/betterAuth.d.ts.map +1 -0
  6. package/esm/src/apiKeys/betterAuth.js +164 -0
  7. package/esm/src/apiKeys/credentials.d.ts +37 -2
  8. package/esm/src/apiKeys/credentials.d.ts.map +1 -1
  9. package/esm/src/apiKeys/credentials.js +69 -8
  10. package/esm/src/apiKeys/lifecycle.d.ts +41 -0
  11. package/esm/src/apiKeys/lifecycle.d.ts.map +1 -0
  12. package/esm/src/apiKeys/lifecycle.js +6 -0
  13. package/esm/src/apiKeys/limits.d.ts +132 -0
  14. package/esm/src/apiKeys/limits.d.ts.map +1 -0
  15. package/esm/src/apiKeys/limits.js +246 -0
  16. package/esm/src/apiKeys/mod.d.ts +4 -0
  17. package/esm/src/apiKeys/mod.d.ts.map +1 -1
  18. package/esm/src/apiKeys/mod.js +4 -0
  19. package/esm/src/apiKeys/permissions.d.ts +56 -0
  20. package/esm/src/apiKeys/permissions.d.ts.map +1 -0
  21. package/esm/src/apiKeys/permissions.js +128 -0
  22. package/esm/src/apiKeys/policy.d.ts +3 -1
  23. package/esm/src/apiKeys/policy.d.ts.map +1 -1
  24. package/esm/src/apiKeys/policy.js +3 -1
  25. package/esm/src/apiKeys/types.d.ts +68 -1
  26. package/esm/src/apiKeys/types.d.ts.map +1 -1
  27. package/esm/src/cli/localDevLock.d.ts +97 -0
  28. package/esm/src/cli/localDevLock.d.ts.map +1 -0
  29. package/esm/src/cli/localDevLock.js +312 -0
  30. package/esm/src/cli/localDevPackage.d.ts +172 -0
  31. package/esm/src/cli/localDevPackage.d.ts.map +1 -0
  32. package/esm/src/cli/localDevPackage.js +617 -0
  33. package/esm/src/cli/migrationEnv.d.ts +19 -0
  34. package/esm/src/cli/migrationEnv.d.ts.map +1 -1
  35. package/esm/src/cli/migrationEnv.js +44 -1
  36. package/esm/src/cli/mod.d.ts +69 -4
  37. package/esm/src/cli/mod.d.ts.map +1 -1
  38. package/esm/src/cli/mod.js +3060 -451
  39. package/esm/src/cli/projectTooling.d.ts +19 -1
  40. package/esm/src/cli/projectTooling.d.ts.map +1 -1
  41. package/esm/src/cli/projectTooling.js +142 -12
  42. package/esm/src/mui/apiKeys.d.ts +123 -17
  43. package/esm/src/mui/apiKeys.d.ts.map +1 -1
  44. package/esm/src/mui/apiKeys.js +219 -78
  45. package/esm/src/mui/apiKeysView.d.ts +145 -0
  46. package/esm/src/mui/apiKeysView.d.ts.map +1 -1
  47. package/esm/src/mui/apiKeysView.js +278 -0
  48. package/esm/src/next/apiKeys/mod.d.ts +8 -1
  49. package/esm/src/next/apiKeys/mod.d.ts.map +1 -1
  50. package/esm/src/next/apiKeys/mod.js +5 -2
  51. package/package.json +2 -6
  52. package/script/src/apiKeys/authorize.d.ts.map +1 -1
  53. package/script/src/apiKeys/authorize.js +71 -0
  54. package/script/src/apiKeys/betterAuth.d.ts +123 -0
  55. package/script/src/apiKeys/betterAuth.d.ts.map +1 -0
  56. package/script/src/apiKeys/betterAuth.js +169 -0
  57. package/script/src/apiKeys/credentials.d.ts +37 -2
  58. package/script/src/apiKeys/credentials.d.ts.map +1 -1
  59. package/script/src/apiKeys/credentials.js +71 -8
  60. package/script/src/apiKeys/lifecycle.d.ts +41 -0
  61. package/script/src/apiKeys/lifecycle.d.ts.map +1 -0
  62. package/script/src/apiKeys/lifecycle.js +7 -0
  63. package/script/src/apiKeys/limits.d.ts +132 -0
  64. package/script/src/apiKeys/limits.d.ts.map +1 -0
  65. package/script/src/apiKeys/limits.js +254 -0
  66. package/script/src/apiKeys/mod.d.ts +4 -0
  67. package/script/src/apiKeys/mod.d.ts.map +1 -1
  68. package/script/src/apiKeys/mod.js +4 -0
  69. package/script/src/apiKeys/permissions.d.ts +56 -0
  70. package/script/src/apiKeys/permissions.d.ts.map +1 -0
  71. package/script/src/apiKeys/permissions.js +136 -0
  72. package/script/src/apiKeys/policy.d.ts +3 -1
  73. package/script/src/apiKeys/policy.d.ts.map +1 -1
  74. package/script/src/apiKeys/policy.js +3 -1
  75. package/script/src/apiKeys/types.d.ts +68 -1
  76. package/script/src/apiKeys/types.d.ts.map +1 -1
  77. package/script/src/cli/localDevLock.d.ts +97 -0
  78. package/script/src/cli/localDevLock.d.ts.map +1 -0
  79. package/script/src/cli/localDevLock.js +320 -0
  80. package/script/src/cli/localDevPackage.d.ts +172 -0
  81. package/script/src/cli/localDevPackage.d.ts.map +1 -0
  82. package/script/src/cli/localDevPackage.js +635 -0
  83. package/script/src/cli/migrationEnv.d.ts +19 -0
  84. package/script/src/cli/migrationEnv.d.ts.map +1 -1
  85. package/script/src/cli/migrationEnv.js +48 -1
  86. package/script/src/cli/mod.d.ts +69 -4
  87. package/script/src/cli/mod.d.ts.map +1 -1
  88. package/script/src/cli/mod.js +3061 -451
  89. package/script/src/cli/projectTooling.d.ts +19 -1
  90. package/script/src/cli/projectTooling.d.ts.map +1 -1
  91. package/script/src/cli/projectTooling.js +176 -12
  92. package/script/src/mui/apiKeys.d.ts +123 -17
  93. package/script/src/mui/apiKeys.d.ts.map +1 -1
  94. package/script/src/mui/apiKeys.js +220 -77
  95. package/script/src/mui/apiKeysView.d.ts +145 -0
  96. package/script/src/mui/apiKeysView.d.ts.map +1 -1
  97. package/script/src/mui/apiKeysView.js +291 -0
  98. package/script/src/next/apiKeys/mod.d.ts +8 -1
  99. package/script/src/next/apiKeys/mod.d.ts.map +1 -1
  100. package/script/src/next/apiKeys/mod.js +5 -2
  101. package/skills/loom/SKILL.md +125 -18
  102. package/skills/loom-api-keys/SKILL.md +101 -7
  103. package/skills/loom-auth/SKILL.md +9 -0
  104. package/skills/loom-db/SKILL.md +3 -1
@@ -0,0 +1,635 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LOOM_BUILD_STAMP_FILE = exports.LOOM_PACKAGE_RELEVANT_PATHS = void 0;
4
+ exports.readLoomSourceProvenance = readLoomSourceProvenance;
5
+ exports.settleLoomBuildProvenance = settleLoomBuildProvenance;
6
+ exports.hasLoomBuildProvenance = hasLoomBuildProvenance;
7
+ exports.computeLoomSourceFingerprint = computeLoomSourceFingerprint;
8
+ exports.snapshotLoomSources = snapshotLoomSources;
9
+ exports.loomSourcesWrittenDuringBuild = loomSourcesWrittenDuringBuild;
10
+ exports.formatLoomBuildStamp = formatLoomBuildStamp;
11
+ exports.readLoomBuildStamp = readLoomBuildStamp;
12
+ exports.computePackageContentDigest = computePackageContentDigest;
13
+ exports.findPackageTreeDifference = findPackageTreeDifference;
14
+ exports.computePackageTreeSignature = computePackageTreeSignature;
15
+ exports.getLockfileOverride = getLockfileOverride;
16
+ exports.getLockfileRootImporterDependency = getLockfileRootImporterDependency;
17
+ exports.getLockfileSnapshotVariants = getLockfileSnapshotVariants;
18
+ exports.findNewPeerVariantDuplicates = findNewPeerVariantDuplicates;
19
+ const node_crypto_1 = require("node:crypto");
20
+ const promises_1 = require("node:fs/promises");
21
+ const node_path_1 = require("node:path");
22
+ /**
23
+ * Loom repository paths whose content can change the generated npm package.
24
+ * Release equivalence (`git diff`) and local build fingerprints share this list.
25
+ * It includes every script `scripts/build_npm.ts` imports.
26
+ */
27
+ exports.LOOM_PACKAGE_RELEVANT_PATHS = [
28
+ "LICENSE",
29
+ "NOTICE",
30
+ "README.md",
31
+ "THIRD_PARTY_NOTICES.md",
32
+ "bin",
33
+ "deno.json",
34
+ "deno.lock",
35
+ "mod.ts",
36
+ "runtime",
37
+ "scripts/browser_entrypoints.ts",
38
+ "scripts/build_npm.ts",
39
+ "scripts/git_visible_copy.ts",
40
+ "scripts/node_check_dependencies.ts",
41
+ "scripts/npm_package.ts",
42
+ "skills",
43
+ "src",
44
+ ];
45
+ /**
46
+ * Build stamp written into Loom's `npm/` output by `scripts/build_npm.ts`.
47
+ * The build excludes it from the packed package, so it never reaches npm or a
48
+ * consumer's `node_modules`.
49
+ */
50
+ exports.LOOM_BUILD_STAMP_FILE = ".loom-build.json";
51
+ /**
52
+ * Asks git for a checkout's HEAD commit and whether its working tree differs
53
+ * from it: tracked changes, untracked files that are not ignored (listed
54
+ * individually, whatever `status.showUntrackedFiles` says), or files marked
55
+ * skip-worktree or assume-unchanged, whose changes `git status` hides.
56
+ * `git` runs one git command in the checkout and returns its stdout, or null
57
+ * when it failed (git missing, not a repository). Whatever git cannot answer
58
+ * is null.
59
+ */
60
+ function readLoomSourceProvenance(git) {
61
+ const head = git(["rev-parse", "HEAD"])?.trim() ?? "";
62
+ if (!/^[0-9a-f]{40,64}$/.test(head)) {
63
+ return { sourceCommit: null, sourceDirty: null };
64
+ }
65
+ const status = git(["status", "--porcelain", "--untracked-files=all"]);
66
+ // `ls-files -v` tags skip-worktree files S and assume-unchanged files with
67
+ // a lowercase letter.
68
+ const tags = status === null ? null : git(["ls-files", "-v"]);
69
+ return {
70
+ sourceCommit: head,
71
+ sourceDirty: status === null || tags === null
72
+ ? null
73
+ : status.trim() !== "" ||
74
+ tags.split("\n").some((line) => /^(?:S|[a-z]) /.test(line)),
75
+ };
76
+ }
77
+ /**
78
+ * Settles a build's provenance from what git reported when the build started
79
+ * and when it finished. Any change in between (a commit, a checkout, an
80
+ * edit, which `sourcesChanged` reports from the source fingerprints, or git
81
+ * becoming unable to tell) means the output may mix two states, so the build
82
+ * is stamped dirty, which `loom dev published` refuses; the starting commit
83
+ * is kept. A start git could not read stays unknown.
84
+ */
85
+ function settleLoomBuildProvenance(start, end, sourcesChanged) {
86
+ const changedDuringBuild = sourcesChanged ||
87
+ end.sourceCommit !== start.sourceCommit ||
88
+ end.sourceDirty !== start.sourceDirty;
89
+ const provenance = changedDuringBuild && start.sourceCommit !== null
90
+ ? { sourceCommit: start.sourceCommit, sourceDirty: true }
91
+ : start;
92
+ return { changedDuringBuild, provenance };
93
+ }
94
+ /**
95
+ * Whether a stamp records the build's provenance and output digest. Stamps
96
+ * from older build scripts lack them.
97
+ */
98
+ function hasLoomBuildProvenance(stamp) {
99
+ return stamp.sourceCommit !== undefined && stamp.sourceDirty !== undefined &&
100
+ typeof stamp.packageDigest === "string";
101
+ }
102
+ const SOURCE_FINGERPRINT_SKIPPED_DIRS = new Set([
103
+ ".git",
104
+ "coverage",
105
+ "node_modules",
106
+ "npm",
107
+ ]);
108
+ // dnt builds with `test: false`, so test-only edits cannot change the output.
109
+ const SOURCE_FINGERPRINT_SKIPPED_FILE = /\.test\.[cm]?[jt]sx?$/;
110
+ function compareNames(left, right) {
111
+ return left < right ? -1 : left > right ? 1 : 0;
112
+ }
113
+ function isMissingPathError(error) {
114
+ const code = error?.code;
115
+ return code === "ENOENT" || code === "ENOTDIR";
116
+ }
117
+ async function statIfExists(path) {
118
+ try {
119
+ return await (0, promises_1.stat)(path);
120
+ }
121
+ catch (error) {
122
+ if (isMissingPathError(error))
123
+ return null;
124
+ throw error;
125
+ }
126
+ }
127
+ /**
128
+ * Lists the package-relevant source files of a Loom checkout in fingerprint
129
+ * order, with their stats. Test files and build outputs are skipped.
130
+ */
131
+ async function listLoomSourceFiles(sourceRoot) {
132
+ const files = [];
133
+ const visit = async (relativePath) => {
134
+ const pathStat = await statIfExists((0, node_path_1.join)(sourceRoot, relativePath));
135
+ if (!pathStat)
136
+ return;
137
+ if (pathStat.isDirectory()) {
138
+ const entries = (await (0, promises_1.readdir)((0, node_path_1.join)(sourceRoot, relativePath)))
139
+ .sort(compareNames);
140
+ for (const name of entries) {
141
+ if (SOURCE_FINGERPRINT_SKIPPED_DIRS.has(name))
142
+ continue;
143
+ await visit(`${relativePath}/${name}`);
144
+ }
145
+ return;
146
+ }
147
+ if (pathStat.isFile() && !SOURCE_FINGERPRINT_SKIPPED_FILE.test(relativePath)) {
148
+ files.push({ path: relativePath, stat: pathStat });
149
+ }
150
+ };
151
+ for (const path of [...exports.LOOM_PACKAGE_RELEVANT_PATHS].sort(compareNames)) {
152
+ await visit(path);
153
+ }
154
+ return files;
155
+ }
156
+ /**
157
+ * Hashes the content of every package-relevant file in a Loom checkout.
158
+ * Unlike modification times, the result changes exactly when a rebuild could
159
+ * produce a different package, including after checkouts that restore older
160
+ * timestamps and edits made while a build is running.
161
+ */
162
+ async function computeLoomSourceFingerprint(sourceRoot) {
163
+ const hash = (0, node_crypto_1.createHash)("sha256");
164
+ hash.update("loom-source-fingerprint:1\n");
165
+ for (const { path } of await listLoomSourceFiles(sourceRoot)) {
166
+ const content = await (0, promises_1.readFile)((0, node_path_1.join)(sourceRoot, path));
167
+ hash.update(`${path}\0${content.length}\0`);
168
+ hash.update(content);
169
+ hash.update("\0");
170
+ }
171
+ return `sha256:${hash.digest("hex")}`;
172
+ }
173
+ /** Records {@link LoomSourceSnapshot} for a Loom checkout. */
174
+ async function snapshotLoomSources(sourceRoot) {
175
+ return new Map((await listLoomSourceFiles(sourceRoot)).map(({ path, stat }) => [
176
+ path,
177
+ { mtimeMs: stat.mtimeMs, size: stat.size },
178
+ ]));
179
+ }
180
+ /**
181
+ * How far before a build's start a whole-second modification time still
182
+ * counts as possibly written during it: FAT stores even seconds, and
183
+ * timestamps are rounded down to the filesystem's granularity.
184
+ */
185
+ const COARSE_MTIME_MARGIN_MS = 2_500;
186
+ /**
187
+ * Whether any package-relevant source file was written while a build ran,
188
+ * from snapshots taken when it started (at `startedAtMs`) and when it
189
+ * finished. Content alone misses an edit that was reverted before the build
190
+ * finished, but the revert rewrites the file:
191
+ * - a file added, removed, resized or with a new modification time counts;
192
+ * - so does one modified at or after the start;
193
+ * - on filesystems with coarse timestamps (a whole-second modification time)
194
+ * an edit can keep the old value, so a file modified shortly before the
195
+ * start counts as well.
196
+ */
197
+ function loomSourcesWrittenDuringBuild(start, end, startedAtMs) {
198
+ if (start.size !== end.size)
199
+ return true;
200
+ for (const [path, after] of end) {
201
+ const before = start.get(path);
202
+ if (!before || before.size !== after.size ||
203
+ before.mtimeMs !== after.mtimeMs || after.mtimeMs >= startedAtMs) {
204
+ return true;
205
+ }
206
+ if (after.mtimeMs % 1000 === 0 &&
207
+ after.mtimeMs >= startedAtMs - COARSE_MTIME_MARGIN_MS) {
208
+ return true;
209
+ }
210
+ }
211
+ return false;
212
+ }
213
+ /** Serializes the build stamp that `scripts/build_npm.ts` writes. */
214
+ function formatLoomBuildStamp(stamp) {
215
+ const value = { version: 1, ...stamp };
216
+ return `${JSON.stringify(value, null, 2)}\n`;
217
+ }
218
+ /** Reads a build stamp, returning null when it is absent or unrecognized. */
219
+ async function readLoomBuildStamp(packagePath) {
220
+ let text;
221
+ try {
222
+ text = await (0, promises_1.readFile)((0, node_path_1.join)(packagePath, exports.LOOM_BUILD_STAMP_FILE), "utf8");
223
+ }
224
+ catch (error) {
225
+ if (isMissingPathError(error))
226
+ return null;
227
+ throw error;
228
+ }
229
+ try {
230
+ const stamp = JSON.parse(text);
231
+ const commitOk = stamp.sourceCommit === undefined ||
232
+ stamp.sourceCommit === null || typeof stamp.sourceCommit === "string";
233
+ const dirtyOk = stamp.sourceDirty === undefined ||
234
+ stamp.sourceDirty === null || typeof stamp.sourceDirty === "boolean";
235
+ const digestOk = stamp.packageDigest === undefined ||
236
+ typeof stamp.packageDigest === "string";
237
+ const legacyOk = stamp.legacyBuildFingerprint === undefined ||
238
+ typeof stamp.legacyBuildFingerprint === "string";
239
+ return stamp.version === 1 &&
240
+ typeof stamp.sourceFingerprint === "string" && commitOk && dirtyOk &&
241
+ digestOk && legacyOk
242
+ ? stamp
243
+ : null;
244
+ }
245
+ catch {
246
+ return null;
247
+ }
248
+ }
249
+ /** Names npm packing, and so pnpm's directory import, always leaves out. */
250
+ const ALWAYS_UNPACKED_NAMES = new Set([
251
+ "CVS",
252
+ "config.gypi",
253
+ "node_modules",
254
+ "npm-debug.log",
255
+ "package-lock.json",
256
+ ]);
257
+ async function readTextOrNull(path) {
258
+ try {
259
+ return await (0, promises_1.readFile)(path, "utf8");
260
+ }
261
+ catch (error) {
262
+ if (isMissingPathError(error))
263
+ return null;
264
+ throw error;
265
+ }
266
+ }
267
+ /**
268
+ * Reads the root ignore rules npm packing applies to a package directory
269
+ * (`.npmignore`, else `.gitignore`). Only literal names are understood, which
270
+ * covers the `.npmignore` dnt writes; globs, nested paths, negations, and a
271
+ * `files` allowlist return null so callers fall back to a weaker comparison.
272
+ */
273
+ async function readPackExclusions(root) {
274
+ try {
275
+ const packageJson = JSON.parse(await readTextOrNull((0, node_path_1.join)(root, "package.json")) ?? "{}");
276
+ if (packageJson.files !== undefined)
277
+ return null;
278
+ }
279
+ catch {
280
+ return null;
281
+ }
282
+ const ignoreText = await readTextOrNull((0, node_path_1.join)(root, ".npmignore")) ??
283
+ await readTextOrNull((0, node_path_1.join)(root, ".gitignore")) ?? "";
284
+ const exclusions = {
285
+ anyDepth: new Set(),
286
+ topLevel: new Set(),
287
+ };
288
+ for (const rawLine of ignoreText.split(/\r?\n/)) {
289
+ const line = rawLine.trim();
290
+ if (line === "" || line.startsWith("#"))
291
+ continue;
292
+ if (line.startsWith("!"))
293
+ return null;
294
+ const anchored = line.startsWith("/");
295
+ const name = line.replace(/^\/+/, "").replace(/\/+$/, "");
296
+ if (name === "")
297
+ continue;
298
+ if (/[*?[\]\\/]/.test(name))
299
+ return null;
300
+ (anchored ? exclusions.topLevel : exclusions.anyDepth).add(name);
301
+ }
302
+ return exclusions;
303
+ }
304
+ function isPackedEntry(name, anyDepthExclusions) {
305
+ // Dot entries cover npm's other always-ignored names (.git, .npmrc, ...)
306
+ // and the ignore files themselves.
307
+ return !name.startsWith(".") && !ALWAYS_UNPACKED_NAMES.has(name) &&
308
+ !name.endsWith(".orig") && !anyDepthExclusions.has(name);
309
+ }
310
+ async function collectPackageFiles(root, includeTopLevel, anyDepthExclusions) {
311
+ const files = new Map();
312
+ let nestedIgnoreFile = false;
313
+ const visit = async (relativePath) => {
314
+ const directory = relativePath ? (0, node_path_1.join)(root, relativePath) : root;
315
+ const entries = (await (0, promises_1.readdir)(directory, { withFileTypes: true }))
316
+ .sort((left, right) => compareNames(left.name, right.name));
317
+ for (const entry of entries) {
318
+ if (relativePath &&
319
+ (entry.name === ".npmignore" || entry.name === ".gitignore")) {
320
+ nestedIgnoreFile = true;
321
+ }
322
+ if (!isPackedEntry(entry.name, anyDepthExclusions))
323
+ continue;
324
+ if (!relativePath && !includeTopLevel(entry.name))
325
+ continue;
326
+ const childPath = relativePath
327
+ ? `${relativePath}/${entry.name}`
328
+ : entry.name;
329
+ let isDirectory = entry.isDirectory();
330
+ let isFile = entry.isFile();
331
+ let fileStat = { ino: 0, mtimeMs: 0, size: 0 };
332
+ if (entry.isSymbolicLink() || isFile) {
333
+ const childStat = await statIfExists((0, node_path_1.join)(root, childPath));
334
+ if (!childStat)
335
+ continue;
336
+ isDirectory = childStat.isDirectory();
337
+ isFile = childStat.isFile();
338
+ fileStat = {
339
+ ino: childStat.ino,
340
+ mtimeMs: childStat.mtimeMs,
341
+ size: childStat.size,
342
+ };
343
+ }
344
+ if (isDirectory) {
345
+ await visit(childPath);
346
+ }
347
+ else if (isFile) {
348
+ files.set(childPath, fileStat);
349
+ }
350
+ }
351
+ };
352
+ await visit("");
353
+ return { files, nestedIgnoreFile };
354
+ }
355
+ /**
356
+ * Digest of a built package's files by path and content, filtered as
357
+ * {@link findPackageTreeDifference} filters them: its root ignore rules,
358
+ * npm's always-ignored names, and every dot entry, which Loom's packing
359
+ * approximation treats as unpacked although npm would pack some. The build
360
+ * stamp records it, so any later edit to those files shows.
361
+ */
362
+ async function computePackageContentDigest(root) {
363
+ let exclusions = await readPackExclusions(root);
364
+ const collect = () => collectPackageFiles(root, (name) => !exclusions?.topLevel.has(name), exclusions?.anyDepth ?? new Set());
365
+ let collected = await collect();
366
+ if (exclusions && collected.nestedIgnoreFile) {
367
+ // As in findPackageTreeDifference: nested rules are not applied.
368
+ exclusions = null;
369
+ collected = await collect();
370
+ }
371
+ const hash = (0, node_crypto_1.createHash)("sha256");
372
+ hash.update("loom-package-digest:1\n");
373
+ for (const path of [...collected.files.keys()].sort(compareNames)) {
374
+ const content = await (0, promises_1.readFile)((0, node_path_1.join)(root, path));
375
+ hash.update(`${path}\0${content.length}\0`);
376
+ hash.update(content);
377
+ hash.update("\0");
378
+ }
379
+ return `sha256:${hash.digest("hex")}`;
380
+ }
381
+ /**
382
+ * Compares a built package directory with the copy a package manager
383
+ * installed from it, by file list and byte content. Returns a short
384
+ * description of the first difference, or null when the installed copy
385
+ * matches.
386
+ *
387
+ * Both trees are filtered by the build's packing rules (its root
388
+ * `.npmignore` plus npm's always-ignored names), so a build that only adds a
389
+ * new top-level entry is still detected. When those rules cannot be read
390
+ * literally, top-level build entries absent from the installed copy are
391
+ * skipped instead.
392
+ */
393
+ async function findPackageTreeDifference(builtRoot, installedRoot) {
394
+ const installedTopLevel = await (0, promises_1.readdir)(installedRoot).catch((error) => {
395
+ if (isMissingPathError(error))
396
+ return null;
397
+ throw error;
398
+ });
399
+ if (!installedTopLevel?.includes("package.json")) {
400
+ return "the package is not installed";
401
+ }
402
+ const installedNames = new Set(installedTopLevel);
403
+ const collect = (exclusions) => {
404
+ const includeTopLevel = exclusions
405
+ ? (name) => !exclusions.topLevel.has(name)
406
+ : (name) => installedNames.has(name);
407
+ const anyDepth = exclusions?.anyDepth ?? new Set();
408
+ return Promise.all([
409
+ collectPackageFiles(builtRoot, includeTopLevel, anyDepth),
410
+ collectPackageFiles(installedRoot, includeTopLevel, anyDepth),
411
+ ]);
412
+ };
413
+ let exclusions = await readPackExclusions(builtRoot);
414
+ let [built, installed] = await collect(exclusions);
415
+ if (exclusions && built.nestedIgnoreFile) {
416
+ // Nested ignore files add rules this reader does not apply.
417
+ exclusions = null;
418
+ [built, installed] = await collect(exclusions);
419
+ }
420
+ const builtFiles = built.files;
421
+ const installedFiles = installed.files;
422
+ for (const path of builtFiles.keys()) {
423
+ if (!installedFiles.has(path))
424
+ return `${path} is not installed`;
425
+ }
426
+ for (const path of installedFiles.keys()) {
427
+ if (!builtFiles.has(path))
428
+ return `${path} is no longer built`;
429
+ }
430
+ for (const [path, { size }] of builtFiles) {
431
+ if (installedFiles.get(path)?.size !== size)
432
+ return `${path} differs`;
433
+ }
434
+ for (const path of builtFiles.keys()) {
435
+ const [builtContent, installedContent] = await Promise.all([
436
+ (0, promises_1.readFile)((0, node_path_1.join)(builtRoot, path)),
437
+ (0, promises_1.readFile)((0, node_path_1.join)(installedRoot, path)),
438
+ ]);
439
+ if (!builtContent.equals(installedContent))
440
+ return `${path} differs`;
441
+ }
442
+ return null;
443
+ }
444
+ /**
445
+ * Cheap signature of an installed package tree: its real path plus each
446
+ * file's path, size, inode, and modification time (no file contents), or
447
+ * null when it is not installed. pnpm links unchanged files from its
448
+ * content-addressed store, so the signature changes when the package is
449
+ * replaced with different content. Lets a process tell whether the package
450
+ * it loaded was replaced later.
451
+ */
452
+ async function computePackageTreeSignature(root) {
453
+ const topLevel = await (0, promises_1.readdir)(root).catch((error) => {
454
+ if (isMissingPathError(error))
455
+ return null;
456
+ throw error;
457
+ });
458
+ if (!topLevel?.includes("package.json"))
459
+ return null;
460
+ const { files } = await collectPackageFiles(root, () => true, new Set());
461
+ const hash = (0, node_crypto_1.createHash)("sha256");
462
+ hash.update(`${await (0, promises_1.realpath)(root)}\n`);
463
+ for (const [path, { ino, mtimeMs, size }] of files) {
464
+ hash.update(`${path}\0${size}\0${ino}\0${mtimeMs}\n`);
465
+ }
466
+ return `stat:${hash.digest("hex")}`;
467
+ }
468
+ function unquoteYamlScalar(value) {
469
+ const trimmed = value.trim();
470
+ if (trimmed.startsWith("'") && trimmed.endsWith("'") && trimmed.length > 1) {
471
+ return trimmed.slice(1, -1).replaceAll("''", "'");
472
+ }
473
+ if (trimmed.startsWith('"') && trimmed.endsWith('"') && trimmed.length > 1) {
474
+ try {
475
+ return JSON.parse(trimmed);
476
+ }
477
+ catch {
478
+ return trimmed.slice(1, -1);
479
+ }
480
+ }
481
+ return trimmed;
482
+ }
483
+ /** Splits `key: value` YAML mapping lines at the given indentation. */
484
+ function parseYamlMappingLine(line, indent) {
485
+ const prefix = " ".repeat(indent);
486
+ if (!line.startsWith(prefix) || line[indent] === " ")
487
+ return null;
488
+ const body = line.slice(indent);
489
+ if (body.startsWith("#"))
490
+ return null;
491
+ const match = body.match(/^(?:'((?:[^']|'')*)'|"((?:[^"\\]|\\.)*)"|([^\s'"#][^\s]*?)):(?:\s+(.*))?$/);
492
+ if (!match)
493
+ return null;
494
+ const key = match[1] !== undefined
495
+ ? match[1].replaceAll("''", "'")
496
+ : match[2] !== undefined
497
+ ? unquoteYamlScalar(`"${match[2]}"`)
498
+ : match[3];
499
+ return { key, value: match[4] === undefined ? "" : match[4] };
500
+ }
501
+ /**
502
+ * Returns the project document of a lockfile. With `configDependencies`,
503
+ * pnpm 11 writes a multi-document lockfile whose first document locks the
504
+ * config-dependency environment and has its own importers and snapshots;
505
+ * the project document, which carries `settings:`, comes last.
506
+ */
507
+ function getMainLockfileDocument(lockfileText) {
508
+ const documents = lockfileText.replace(/\r\n/g, "\n")
509
+ .split(/^---[ \t]*$/m)
510
+ .filter((document) => document.trim() !== "");
511
+ if (documents.length <= 1)
512
+ return documents[0] ?? "";
513
+ for (let index = documents.length - 1; index >= 0; index -= 1) {
514
+ if (/^settings:/m.test(documents[index]))
515
+ return documents[index];
516
+ }
517
+ return documents[documents.length - 1];
518
+ }
519
+ /** Returns the lines of a top-level section of a pnpm lockfile. */
520
+ function getLockfileSection(lockfileText, section) {
521
+ const lines = getMainLockfileDocument(lockfileText).split("\n");
522
+ const start = lines.indexOf(`${section}:`);
523
+ if (start === -1)
524
+ return [];
525
+ const body = [];
526
+ for (const line of lines.slice(start + 1)) {
527
+ if (line !== "" && !line.startsWith(" ") && !line.startsWith("#"))
528
+ break;
529
+ body.push(line);
530
+ }
531
+ return body;
532
+ }
533
+ /**
534
+ * Reads the override pnpm recorded for a package in the lockfile's top-level
535
+ * `overrides:` map. pnpm records the override map it actually applied, so
536
+ * this proves whether an override took effect.
537
+ */
538
+ function getLockfileOverride(lockfileText, name) {
539
+ for (const line of getLockfileSection(lockfileText, "overrides")) {
540
+ const entry = parseYamlMappingLine(line, 2);
541
+ if (entry?.key === name)
542
+ return unquoteYamlScalar(entry.value);
543
+ }
544
+ return null;
545
+ }
546
+ /** Reads a direct dependency of the root importer (`.`) from a lockfile. */
547
+ function getLockfileRootImporterDependency(lockfileText, name) {
548
+ let inRootImporter = false;
549
+ let inDependency = false;
550
+ const result = {};
551
+ for (const line of getLockfileSection(lockfileText, "importers")) {
552
+ const importer = parseYamlMappingLine(line, 2);
553
+ if (importer) {
554
+ if (inDependency)
555
+ break;
556
+ inRootImporter = importer.key === ".";
557
+ continue;
558
+ }
559
+ if (!inRootImporter)
560
+ continue;
561
+ if (parseYamlMappingLine(line, 4)) {
562
+ if (inDependency)
563
+ break;
564
+ continue;
565
+ }
566
+ const dependency = parseYamlMappingLine(line, 6);
567
+ if (dependency) {
568
+ if (inDependency)
569
+ break;
570
+ inDependency = dependency.key === name;
571
+ continue;
572
+ }
573
+ const field = inDependency ? parseYamlMappingLine(line, 8) : null;
574
+ if (field?.key === "specifier") {
575
+ result.specifier = unquoteYamlScalar(field.value);
576
+ }
577
+ else if (field?.key === "version") {
578
+ result.version = unquoteYamlScalar(field.value);
579
+ }
580
+ }
581
+ return result.specifier !== undefined || result.version !== undefined
582
+ ? result
583
+ : null;
584
+ }
585
+ /**
586
+ * Groups lockfile snapshot keys by `name@version`, collecting the peer (and
587
+ * patch) suffix of each variant, for example `(react@19.2.0)`.
588
+ */
589
+ function getLockfileSnapshotVariants(lockfileText) {
590
+ const variants = new Map();
591
+ const section = getLockfileSection(lockfileText, "snapshots");
592
+ // Lockfile v6 and older kept peer variants in `packages:` with a `/` prefix.
593
+ const lines = section.length
594
+ ? section
595
+ : getLockfileSection(lockfileText, "packages");
596
+ for (const line of lines) {
597
+ const entry = parseYamlMappingLine(line, 2);
598
+ if (!entry)
599
+ continue;
600
+ const key = entry.key.replace(/^\//, "");
601
+ const versionSeparator = key.indexOf("@", key.startsWith("@") ? 1 : 0);
602
+ if (versionSeparator <= 0)
603
+ continue;
604
+ const suffixStart = key.indexOf("(", versionSeparator);
605
+ const base = suffixStart === -1 ? key : key.slice(0, suffixStart);
606
+ const suffix = suffixStart === -1 ? "" : key.slice(suffixStart);
607
+ const set = variants.get(base) ?? new Set();
608
+ set.add(suffix);
609
+ variants.set(base, set);
610
+ }
611
+ return variants;
612
+ }
613
+ /**
614
+ * Lists `name@version` entries that have more than one peer variant after a
615
+ * lockfile change and more variants than before it. Pre-existing duplicates
616
+ * are ignored so warnings point only at what the change introduced.
617
+ */
618
+ function findNewPeerVariantDuplicates(beforeLockfileText, afterLockfileText) {
619
+ const before = beforeLockfileText
620
+ ? getLockfileSnapshotVariants(beforeLockfileText)
621
+ : new Map();
622
+ const after = getLockfileSnapshotVariants(afterLockfileText);
623
+ const duplicates = [];
624
+ for (const [packageVersion, variants] of after) {
625
+ const beforeCount = before.get(packageVersion)?.size ?? 0;
626
+ if (variants.size > 1 && variants.size > beforeCount) {
627
+ duplicates.push({
628
+ after: variants.size,
629
+ before: beforeCount,
630
+ packageVersion,
631
+ });
632
+ }
633
+ }
634
+ return duplicates.sort((left, right) => compareNames(left.packageVersion, right.packageVersion));
635
+ }
@@ -29,6 +29,25 @@ export declare function resolveMigrationEnvironment(env: Record<string, string |
29
29
  * process values, including a dedicated migration secret, to take precedence.
30
30
  */
31
31
  export declare function resolveMigrationEnvironmentFromEnvFile(envFile: string, env: Record<string, string | undefined>): MigrationEnvironmentResolution;
32
+ /**
33
+ * Thrown when the app does not have the optional `postgres` peer installed,
34
+ * so the connection preflight cannot run at all.
35
+ */
36
+ export declare class MigrationDriverMissingError extends Error {
37
+ constructor();
38
+ }
39
+ /**
40
+ * Whether `error` reports that `packageName` itself could not be resolved, as
41
+ * thrown by Node's ESM loader (`ERR_MODULE_NOT_FOUND`), Node's CommonJS
42
+ * `require` used by the npm CLI build (`MODULE_NOT_FOUND`), Deno
43
+ * (`Import "x" not a dependency`), or Yarn Plug'n'Play when the app does not
44
+ * provide the peer (`MISSING_PEER_DEPENDENCY`). A missing file inside an
45
+ * installed package, which Node reports by its path, does not count.
46
+ */
47
+ export declare function isPackageNotFoundError(error: unknown, packageName: string): boolean;
48
+ declare const importPostgres: () => Promise<any>;
49
+ /** Loads the app's `postgres` driver, which is an optional Loom peer. */
50
+ export declare function loadPostgresDriver(importModule?: typeof importPostgres): Promise<any>;
32
51
  /**
33
52
  * Authenticates with the selected migration URL and verifies that the
34
53
  * connection reaches the declared role/database with usable schema access.
@@ -1 +1 @@
1
- {"version":3,"file":"migrationEnv.d.ts","sourceRoot":"","sources":["../../../src/src/cli/migrationEnv.ts"],"names":[],"mappings":"AAGA,QAAA,MAAM,wCAAwC,iHAKpC,CAAC;AAEX,MAAM,MAAM,2BAA2B,GACrC,OAAO,wCAAwC,CAAC,MAAM,CAAC,CAAC;AAE1D,MAAM,MAAM,8BAA8B,GAAG;IAC3C,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,OAAO,CAAC;IAChB,OAAO,EAAE,2BAA2B,CAAC;IACrC,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,6EAA6E;AAC7E,MAAM,MAAM,+BAA+B,GACvC,8BAA8B,GAC9B;IACA,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAEJ,KAAK,4BAA4B,GAAG;IAClC,iBAAiB,EAAE,OAAO,CAAC;IAC3B,YAAY,EAAE,OAAO,CAAC;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;CACvB,CAAC;AAEF,KAAK,sBAAsB,GAAG,CAC5B,WAAW,EAAE,MAAM,KAChB,OAAO,CAAC,4BAA4B,CAAC,CAAC;AAO3C;;;GAGG;AACH,wBAAgB,2B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