@moldea.ai/cli 13.0.4 → 14.0.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.
@@ -0,0 +1,3529 @@
1
+ import { c as validateByteLimit, d as ERRORS, f as Exception, l as isIntegerValid, m as hasErrorCode, n as CoreOperationException, t as CoreConfigurationException, u as isObjectValid } from "./chunk-728df961.mjs";
2
+ import { A as formatMoldeaCliJsonScopeResult, B as ERRORS$2, C as formatMoldeaCliHumanInspectResult, D as formatMoldeaCliJsonContentResult, E as formatMoldeaCliJsonCompositionResult, F as isRepositoryDirectoryInputValid, H as MOLDEA_CLI_COMMANDS, I as createMoldeaCliOutputPage, L as calculateMoldeaCliJsonDigest, M as createMoldeaCliOwnedError, N as MOLDEA_CLI_GIT_WORKING_TREE_SOURCE, O as formatMoldeaCliJsonError, P as parseMoldeaCliArguments, R as decodeMoldeaCliCursor, S as formatMoldeaCliHumanError, T as formatMoldeaCliHumanValidateResult, U as ERRORS$1, V as MoldeaCliOutputPageException, _ as createMoldeaCliInspectProjection, a as require_semver, b as formatMoldeaCliHumanCompositionResult, c as checkGitResult, d as listUntrackedFiles, f as readConfigBoolean, g as createMoldeaCliDiagnosticRecord, h as runGit, j as formatMoldeaCliJsonValidateResult, k as formatMoldeaCliJsonInspectResult, l as createGitFailure, m as readTopLevel, o as MoldeaCliCompositionException, p as readIndexEntries, s as createGitVersionPreflight, u as readGit, v as createMoldeaCliValidateProjection, w as formatMoldeaCliHumanScopeResult, x as formatMoldeaCliHumanContentResult, y as formatMoldeaCliHelp, z as encodeMoldeaCliCursor } from "./chunk-d5af3eda.mjs";
3
+ import { g as countUtf8Bytes } from "./chunk-a5514957.mjs";
4
+ import { n as createCore } from "./chunk-459da9cf.mjs";
5
+ import { a as compareRepositoryPaths$1, c as isRepositoryPath, i as RepositorySourceException, l as parseRepositoryPath, n as REPOSITORY_ROOT, o as createRepositoryComparison, r as RepositoryPathException } from "./chunk-8d6114d2.mjs";
6
+ import path from "node:path";
7
+ import process$1 from "node:process";
8
+ import { fileURLToPath } from "node:url";
9
+ import { constants } from "node:fs";
10
+ import { constants as constants$1 } from "node:os";
11
+ import { TextDecoder as TextDecoder$1 } from "node:util";
12
+ import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
13
+ import { lstat, open, opendir, readdir, readlink, realpath, stat } from "node:fs/promises";
14
+ import { Buffer as Buffer$1 } from "node:buffer";
15
+ //#region ../../node_modules/.pnpm/jg-utilities@1.7.2/node_modules/jg-utilities/dist/utils/byte-cache.js
16
+ var cloneBytes = (bytes) => new Uint8Array(bytes);
17
+ var createByteCache = ({ maxBytes, maxEntries }) => {
18
+ validateByteLimit(maxBytes);
19
+ if (maxEntries !== void 0 && (!Number.isSafeInteger(maxEntries) || maxEntries < 1)) throw new Exception("The entry limit must be a positive safe integer.", {
20
+ code: ERRORS.INVALID_BYTE_LIMIT,
21
+ data: { maxEntries: String(maxEntries) }
22
+ });
23
+ const entryLimit = maxEntries ?? Number.POSITIVE_INFINITY;
24
+ const entries = new Map();
25
+ let byteLength = 0;
26
+ let retainedBytes = 0;
27
+ let retainedEntries = 0;
28
+ const evict = (key, entry) => {
29
+ entries.delete(key);
30
+ byteLength -= entry.bytes.byteLength;
31
+ };
32
+ return {
33
+ get: (key) => {
34
+ const entry = entries.get(key);
35
+ if (entry === void 0) return;
36
+ entries.delete(key);
37
+ entries.set(key, entry);
38
+ return cloneBytes(entry.bytes);
39
+ },
40
+ set: (key, bytes) => {
41
+ const existing = entries.get(key);
42
+ if (existing !== void 0 && existing.retentions > 0) return false;
43
+ if (retainedBytes + bytes.byteLength > maxBytes || retainedEntries + 1 > entryLimit) return false;
44
+ if (existing !== void 0) evict(key, existing);
45
+ for (const [oldestKey, oldest] of entries) {
46
+ if (byteLength + bytes.byteLength <= maxBytes && entries.size < entryLimit) break;
47
+ if (oldest.retentions === 0) evict(oldestKey, oldest);
48
+ }
49
+ entries.set(key, {
50
+ bytes: cloneBytes(bytes),
51
+ retentions: 0
52
+ });
53
+ byteLength += bytes.byteLength;
54
+ return true;
55
+ },
56
+ retain: (key) => {
57
+ let entry = entries.get(key);
58
+ if (entry === void 0) return;
59
+ if (entry.retentions === 0) {
60
+ retainedBytes += entry.bytes.byteLength;
61
+ retainedEntries += 1;
62
+ }
63
+ entry.retentions += 1;
64
+ return {
65
+ copyBytes: () => entry === void 0 ? void 0 : cloneBytes(entry.bytes),
66
+ release: () => {
67
+ if (entry === void 0) return;
68
+ entry.retentions -= 1;
69
+ if (entry.retentions === 0) {
70
+ retainedBytes -= entry.bytes.byteLength;
71
+ retainedEntries -= 1;
72
+ }
73
+ entry = void 0;
74
+ }
75
+ };
76
+ },
77
+ get byteLength() {
78
+ return byteLength;
79
+ }
80
+ };
81
+ };
82
+ //#endregion
83
+ //#region ../../node_modules/.pnpm/jg-utilities@1.7.2/node_modules/jg-utilities/dist/utils/constants.js
84
+ var MAX_TIMEOUT_MS = 2147483647;
85
+ //#endregion
86
+ //#region ../../node_modules/.pnpm/jg-utilities@1.7.2/node_modules/jg-utilities/dist/utils/request-coordinator.js
87
+ var assertQueueLimit = (limit, name) => {
88
+ if (!isIntegerValid(limit, 0)) throw new Exception("The queue limit must be an integer of at least 0.", {
89
+ code: ERRORS.INVALID_QUEUE_LIMIT,
90
+ data: { [name]: String(limit) }
91
+ });
92
+ };
93
+ var toDeadlineMs = (deadline) => {
94
+ const deadlineMs = deadline instanceof Date ? deadline.getTime() : deadline;
95
+ if (typeof deadlineMs !== "number" || Number.isNaN(new Date(deadlineMs).getTime())) throw new Exception("The deadline must be a valid Date or epoch milliseconds a Date accepts.", {
96
+ code: ERRORS.INVALID_DATE,
97
+ data: { deadline: String(deadline) }
98
+ });
99
+ return deadlineMs;
100
+ };
101
+ var createRequestCoordinator = ({ maxConcurrent, maxQueued }) => {
102
+ if (!isIntegerValid(maxConcurrent, 1)) throw new Exception("The concurrency limit must be an integer of at least 1.", {
103
+ code: ERRORS.INVALID_CONCURRENCY_LIMIT,
104
+ data: { maxConcurrent: String(maxConcurrent) }
105
+ });
106
+ assertQueueLimit(maxQueued, "maxQueued");
107
+ let activeCount = 0;
108
+ let cooldownUntil = 0;
109
+ let timer;
110
+ let isClosed = false;
111
+ const waiters = [];
112
+ const createCooldownError = () => new Exception("Requests are paused until the cooldown ends.", {
113
+ code: ERRORS.REQUEST_COOLDOWN_ACTIVE,
114
+ data: { retryAt: new Date(cooldownUntil).toISOString() }
115
+ });
116
+ const createClosedError = () => new Exception("The request coordinator is closed.", { code: ERRORS.REQUEST_COORDINATOR_CLOSED });
117
+ const clearTimer = () => {
118
+ if (timer !== void 0) {
119
+ clearTimeout(timer);
120
+ timer = void 0;
121
+ }
122
+ };
123
+ const schedule = () => {
124
+ clearTimer();
125
+ if (waiters.length === 0) return;
126
+ const remainingMs = cooldownUntil - Date.now();
127
+ if (remainingMs > 0) {
128
+ for (let index = waiters.length - 1; index >= 0; index -= 1) {
129
+ const waiter = waiters[index];
130
+ if (waiter?.rejectDuringCooldown === true) {
131
+ waiters.splice(index, 1);
132
+ waiter.detach();
133
+ waiter.reject(createCooldownError());
134
+ }
135
+ }
136
+ if (waiters.length > 0) timer = setTimeout(schedule, Math.min(remainingMs, MAX_TIMEOUT_MS));
137
+ return;
138
+ }
139
+ while (activeCount < maxConcurrent) {
140
+ const waiter = waiters.shift();
141
+ if (waiter === void 0) return;
142
+ waiter.detach();
143
+ if (waiter.signal?.aborted === true) waiter.reject(waiter.signal.reason);
144
+ else {
145
+ activeCount += 1;
146
+ waiter.resolve();
147
+ }
148
+ }
149
+ };
150
+ const acquire = ({ signal, caller, maxQueuedForCaller, rejectDuringCooldown = false }) => {
151
+ if (isClosed) return Promise.reject(createClosedError());
152
+ if (signal?.aborted === true) return Promise.reject(signal.reason);
153
+ if (maxQueuedForCaller !== void 0) assertQueueLimit(maxQueuedForCaller, "maxQueuedForCaller");
154
+ const isCoolingDown = cooldownUntil > Date.now();
155
+ if (isCoolingDown && rejectDuringCooldown) return Promise.reject(createCooldownError());
156
+ if (!isCoolingDown && activeCount < maxConcurrent && waiters.length === 0) {
157
+ activeCount += 1;
158
+ return Promise.resolve();
159
+ }
160
+ if (maxQueuedForCaller !== void 0) {
161
+ const callerQueued = waiters.filter((waiter) => waiter.caller === caller).length;
162
+ if (callerQueued >= maxQueuedForCaller) return Promise.reject(new Exception("The request queue is full.", {
163
+ code: ERRORS.REQUEST_QUEUE_FULL,
164
+ data: {
165
+ scope: "caller",
166
+ queued: callerQueued,
167
+ limit: maxQueuedForCaller
168
+ }
169
+ }));
170
+ }
171
+ if (waiters.length >= maxQueued) return Promise.reject(new Exception("The request queue is full.", {
172
+ code: ERRORS.REQUEST_QUEUE_FULL,
173
+ data: {
174
+ scope: "global",
175
+ queued: waiters.length,
176
+ limit: maxQueued
177
+ }
178
+ }));
179
+ return new Promise((resolve, reject) => {
180
+ const onAbort = () => {
181
+ waiters.splice(waiters.indexOf(waiter), 1);
182
+ waiter.detach();
183
+ schedule();
184
+ reject(signal?.reason);
185
+ };
186
+ const waiter = {
187
+ caller,
188
+ signal,
189
+ rejectDuringCooldown,
190
+ resolve,
191
+ reject,
192
+ detach: () => signal?.removeEventListener("abort", onAbort)
193
+ };
194
+ waiters.push(waiter);
195
+ signal?.addEventListener("abort", onAbort, { once: true });
196
+ schedule();
197
+ });
198
+ };
199
+ return {
200
+ run: async (task, options = {}) => {
201
+ await acquire(options);
202
+ try {
203
+ return await task();
204
+ } finally {
205
+ activeCount -= 1;
206
+ schedule();
207
+ }
208
+ },
209
+ deferUntil: (deadline) => {
210
+ cooldownUntil = Math.max(cooldownUntil, toDeadlineMs(deadline));
211
+ schedule();
212
+ },
213
+ isIdle: () => activeCount === 0 && waiters.length === 0 && cooldownUntil <= Date.now(),
214
+ close: () => {
215
+ isClosed = true;
216
+ clearTimer();
217
+ for (const waiter of waiters.splice(0)) {
218
+ waiter.detach();
219
+ waiter.reject(createClosedError());
220
+ }
221
+ }
222
+ };
223
+ };
224
+ //#endregion
225
+ //#region ../../node_modules/.pnpm/jg-process@1.6.2/node_modules/jg-process/dist/shutdown-signal/constants.js
226
+ var DEFAULT_SHUTDOWN_SIGNALS = ["SIGINT", "SIGTERM"];
227
+ var UNHANDLEABLE_SIGNALS = new Set(["SIGKILL", "SIGSTOP"]);
228
+ //#endregion
229
+ //#region ../../node_modules/.pnpm/jg-process@1.6.2/node_modules/jg-process/dist/shutdown-signal/shutdown-signal.js
230
+ var createInvalidSignalError = () => new Exception("The shutdown needs a non-empty list of signals Node.js can listen for, such as SIGINT, other than SIGKILL and SIGSTOP, and an onSignal that's a function when it's given.", { code: ERRORS$1.INVALID_SIGNAL });
231
+ var readSignals = (signals) => {
232
+ const unique = Array.isArray(signals) ? [...new Set(signals)] : [];
233
+ if (!(unique.length > 0 && unique.every((signal) => typeof signal === "string" && Object.hasOwn(constants$1.signals, signal) && !UNHANDLEABLE_SIGNALS.has(signal)))) throw createInvalidSignalError();
234
+ return unique;
235
+ };
236
+ var createShutdownSignal = ({ signals = DEFAULT_SHUTDOWN_SIGNALS, onSignal, setExitCode = true, forceOnRepeat = false, disconnect = false } = {}) => {
237
+ if (onSignal !== void 0 && typeof onSignal !== "function") throw createInvalidSignalError();
238
+ const listenedSignals = readSignals(signals);
239
+ const controller = new AbortController();
240
+ let received = null;
241
+ let isDisposed = false;
242
+ const toExitCode = (signal) => 128 + constants$1.signals[signal];
243
+ const onDisconnect = () => {
244
+ onProcessSignal("SIGTERM");
245
+ };
246
+ const onProcessSignal = (signal) => {
247
+ if (received !== null) return;
248
+ received = signal;
249
+ const exitCode = toExitCode(signal);
250
+ if (setExitCode) process.exitCode = exitCode;
251
+ if (forceOnRepeat) dispose();
252
+ controller.abort(new Exception(`The process was interrupted by ${signal}.`, {
253
+ code: ERRORS$1.PROCESS_INTERRUPTED,
254
+ data: {
255
+ signal,
256
+ exitCode
257
+ }
258
+ }));
259
+ try {
260
+ Promise.resolve(onSignal?.(signal)).catch(() => void 0);
261
+ } catch {}
262
+ };
263
+ const dispose = () => {
264
+ if (isDisposed) return;
265
+ isDisposed = true;
266
+ for (const signal of listenedSignals) process.off(signal, onProcessSignal);
267
+ process.off("disconnect", onDisconnect);
268
+ };
269
+ for (const signal of listenedSignals) process.on(signal, onProcessSignal);
270
+ if (disconnect && process.send !== void 0) {
271
+ if (process.connected) process.on("disconnect", onDisconnect);
272
+ else onDisconnect();
273
+ }
274
+ return {
275
+ signal: controller.signal,
276
+ receivedSignal: () => received,
277
+ exitCode: () => received === null ? null : toExitCode(received),
278
+ dispose
279
+ };
280
+ };
281
+ //#endregion
282
+ //#region ../../node_modules/.pnpm/jg-process@1.6.2/node_modules/jg-process/dist/command-line/stdin.js
283
+ var readStdin = ({ maxBytes, signal }) => new Promise((resolve, reject) => {
284
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {
285
+ reject(new Exception("The stdin limit must be a positive safe integer.", {
286
+ code: ERRORS$1.INVALID_PROCESS_OPTIONS,
287
+ data: { maxBytes: String(maxBytes) }
288
+ }));
289
+ return;
290
+ }
291
+ const { stdin } = process;
292
+ const chunks = [];
293
+ let byteLength = 0;
294
+ const cleanUp = () => {
295
+ stdin.off("data", onData);
296
+ stdin.off("end", onEnd);
297
+ stdin.off("error", onError);
298
+ signal?.removeEventListener("abort", onAbort);
299
+ };
300
+ const fail = (error) => {
301
+ cleanUp();
302
+ stdin.destroy();
303
+ reject(error);
304
+ };
305
+ const onData = (chunk) => {
306
+ byteLength += chunk.length;
307
+ if (byteLength > maxBytes) {
308
+ fail(new Exception(`The input on stdin is larger than ${maxBytes} bytes.`, {
309
+ code: ERRORS$1.STDIN_TOO_LARGE,
310
+ data: { maxBytes }
311
+ }));
312
+ return;
313
+ }
314
+ chunks.push(chunk);
315
+ };
316
+ const onEnd = () => {
317
+ cleanUp();
318
+ resolve(Buffer.concat(chunks));
319
+ };
320
+ const onError = (error) => {
321
+ fail(error);
322
+ };
323
+ const onAbort = () => {
324
+ fail(signal?.reason);
325
+ };
326
+ if (signal?.aborted) {
327
+ fail(signal.reason);
328
+ return;
329
+ }
330
+ signal?.addEventListener("abort", onAbort, { once: true });
331
+ stdin.on("data", onData);
332
+ stdin.once("end", onEnd);
333
+ stdin.once("error", onError);
334
+ });
335
+ //#endregion
336
+ //#region src/cli-execution/constants.ts
337
+ var MOLDEA_CLI_EXIT_CODES = {
338
+ Interrupted: 130,
339
+ OperationalError: 3,
340
+ StructuralInvalid: 1,
341
+ Success: 0,
342
+ Terminated: 143,
343
+ UsageError: 2
344
+ };
345
+ //#endregion
346
+ //#region ../../node_modules/.pnpm/jg-crypto@0.3.0/node_modules/jg-crypto/dist/hmac/utilities.js
347
+ var SIGNATURE_PATTERN = /^[0-9a-f]{64}$/;
348
+ var computeHmac = (message, secret, { domain }) => {
349
+ if (!(typeof secret === "string" ? secret.length > 0 : secret instanceof Uint8Array && secret.length > 0)) throw new Exception("The HMAC secret must be a non-empty string or byte array.", { code: ERRORS$2.INVALID_HMAC_SECRET });
350
+ if (domain !== void 0 && (typeof domain !== "string" || domain.length === 0)) throw new Exception("The HMAC domain must be a non-empty string when it's given.", { code: ERRORS$2.INVALID_HMAC_DOMAIN });
351
+ const key = domain === void 0 ? secret : createHmac("sha256", secret).update(domain).digest();
352
+ return createHmac("sha256", key).update(message).digest();
353
+ };
354
+ //#endregion
355
+ //#region ../../node_modules/.pnpm/jg-crypto@0.3.0/node_modules/jg-crypto/dist/hmac/hmac.js
356
+ var signHmac = (message, secret, options = {}) => computeHmac(message, secret, options).toString("hex");
357
+ var verifyHmac = (message, signature, secret, options = {}) => {
358
+ const expected = computeHmac(message, secret, options);
359
+ if (typeof signature !== "string" || !SIGNATURE_PATTERN.test(signature)) return false;
360
+ return timingSafeEqual(Buffer.from(signature, "hex"), expected);
361
+ };
362
+ //#endregion
363
+ //#region src/json-output-contract/guard.ts
364
+ var assertMoldeaCliJsonResultIsContentFree = (value, canonicalBodies = []) => {
365
+ const pending = [value];
366
+ const visited = new Set();
367
+ const bodies = new Set(canonicalBodies.filter((body) => body.length > 0));
368
+ while (pending.length > 0) {
369
+ const current = pending.pop();
370
+ if (typeof current === "string") {
371
+ if (bodies.has(current)) throw new TypeError("A non-content CLI result contains canonical document text.");
372
+ continue;
373
+ }
374
+ if (typeof current !== "object" || current === null || visited.has(current)) continue;
375
+ visited.add(current);
376
+ if (Array.isArray(current)) {
377
+ for (const item of current) pending.push(item);
378
+ continue;
379
+ }
380
+ const record = current;
381
+ if (Object.hasOwn(record, "content")) throw new TypeError("A non-content CLI result contains a content property.");
382
+ pending.push(...Object.values(record));
383
+ }
384
+ };
385
+ //#endregion
386
+ //#region src/git-working-tree/constants.ts
387
+ var MAX_GIT_DISCOVERY_OUTPUT_BYTES = 262144;
388
+ //#endregion
389
+ //#region src/git-working-tree/parser.ts
390
+ var UTF8_BYTE_ORDER_MARK = [
391
+ 239,
392
+ 187,
393
+ 191
394
+ ];
395
+ var decodeGitOutput = (output) => {
396
+ if (output.byteLength === 0 || output.byteLength > 262144 || UTF8_BYTE_ORDER_MARK.every((byte, index) => output[index] === byte)) return null;
397
+ let decodedOutput;
398
+ try {
399
+ decodedOutput = new TextDecoder("utf-8", {
400
+ fatal: true,
401
+ ignoreBOM: true
402
+ }).decode(output);
403
+ } catch {
404
+ return null;
405
+ }
406
+ if (decodedOutput.includes("\0") || !decodedOutput.isWellFormed()) return null;
407
+ return decodedOutput;
408
+ };
409
+ var parseGitPathOutput = (output) => {
410
+ const decodedOutput = decodeGitOutput(output);
411
+ if (decodedOutput === null || !decodedOutput.endsWith("\n")) return null;
412
+ const gitPath = process$1.platform === "win32" && decodedOutput.endsWith("\r\n") ? decodedOutput.slice(0, -2) : decodedOutput.slice(0, -1);
413
+ return gitPath.length === 0 ? null : gitPath;
414
+ };
415
+ var parseGitAbsolutePathOutput = (output) => {
416
+ const gitPath = parseGitPathOutput(output);
417
+ if (gitPath === null || !path.isAbsolute(gitPath)) return null;
418
+ return gitPath;
419
+ };
420
+ //#endregion
421
+ //#region src/git-working-tree/starting-directory.ts
422
+ var mapFilesystemFailure$3 = (error) => {
423
+ const errorCode = error?.code?.toUpperCase();
424
+ if (errorCode === "ENOENT" || errorCode === "ENOTDIR") return Object.freeze({
425
+ errorCode: "GIT_REPOSITORY_NOT_FOUND",
426
+ kind: "failed"
427
+ });
428
+ if (errorCode === "EACCES" || errorCode === "EPERM") return Object.freeze({
429
+ errorCode: "GIT_ACCESS_DENIED",
430
+ kind: "failed"
431
+ });
432
+ return Object.freeze({
433
+ errorCode: "GIT_COMMAND_FAILED",
434
+ kind: "failed"
435
+ });
436
+ };
437
+ var createGitStartingDirectoryInspector = (inspectPath = stat) => async (input) => {
438
+ if (!path.isAbsolute(input.invocationDirectory) || input.invocationDirectory.includes("\0") || !input.invocationDirectory.isWellFormed() || input.repositoryDirectory !== null && !isRepositoryDirectoryInputValid(input.repositoryDirectory)) return Object.freeze({
439
+ errorCode: "GIT_REPOSITORY_NOT_FOUND",
440
+ kind: "failed"
441
+ });
442
+ const selectedDirectory = input.repositoryDirectory === null ? input.invocationDirectory : path.isAbsolute(input.repositoryDirectory) ? input.repositoryDirectory : path.resolve(input.invocationDirectory, input.repositoryDirectory);
443
+ try {
444
+ if (!(await inspectPath(selectedDirectory)).isDirectory()) return Object.freeze({
445
+ errorCode: "GIT_REPOSITORY_NOT_FOUND",
446
+ kind: "failed"
447
+ });
448
+ } catch (error) {
449
+ return mapFilesystemFailure$3(error);
450
+ }
451
+ return Object.freeze({
452
+ directory: selectedDirectory,
453
+ kind: "found"
454
+ });
455
+ };
456
+ var inspectGitStartingDirectory = createGitStartingDirectoryInspector();
457
+ //#endregion
458
+ //#region src/git-command/run-git-command.ts
459
+ var runGitCommand = async (args, { cwd, input, maxOutputBytes, signal }) => {
460
+ const subcommand = args[0];
461
+ const execution = await readGit(() => runGit(args, {
462
+ cwd,
463
+ encoding: "buffer",
464
+ maxOutputBytes,
465
+ timeoutSeconds: 300,
466
+ ...input === void 0 ? {} : { input },
467
+ ...signal === void 0 ? {} : { signal }
468
+ }), signal, subcommand);
469
+ if (execution.kind === "failed") return execution;
470
+ const reason = checkGitResult(execution.value, subcommand ?? "");
471
+ return reason === null ? Object.freeze({
472
+ kind: "completed",
473
+ value: execution.value.stdout
474
+ }) : createGitFailure(reason, subcommand);
475
+ };
476
+ //#endregion
477
+ //#region src/git-working-tree/discovery.ts
478
+ var GIT_DISCOVERY_READS = Object.freeze({
479
+ readConfigBoolean,
480
+ readTopLevel
481
+ });
482
+ var mapGitFailure$5 = (reason) => {
483
+ switch (reason) {
484
+ case "aborted": return "GIT_OPERATION_ABORTED";
485
+ case "not-found": return "GIT_NOT_FOUND";
486
+ case "repository-not-found": return "GIT_REPOSITORY_NOT_FOUND";
487
+ case "access-denied": return "GIT_ACCESS_DENIED";
488
+ case "output-limit-exceeded":
489
+ case "output-invalid": return "GIT_OUTPUT_INVALID";
490
+ case "command-failed": return "GIT_COMMAND_FAILED";
491
+ }
492
+ };
493
+ var createDiscoveryFailure = (errorCode) => Object.freeze({
494
+ errorCode,
495
+ kind: "failed"
496
+ });
497
+ var createGitWorkingTreeDiscovery = (git = GIT_DISCOVERY_READS, startingDirectoryInspector = inspectGitStartingDirectory, gitVersionPreflight = createGitVersionPreflight()) => async (input) => {
498
+ const startingDirectoryResult = await startingDirectoryInspector(input);
499
+ if (startingDirectoryResult.kind === "failed") return createDiscoveryFailure(startingDirectoryResult.errorCode);
500
+ const gitOptions = {
501
+ maxOutputBytes: MAX_GIT_DISCOVERY_OUTPUT_BYTES,
502
+ timeoutSeconds: 300,
503
+ ...input.signal === void 0 ? {} : { signal: input.signal }
504
+ };
505
+ const rootResult = await readGit(() => git.readTopLevel(startingDirectoryResult.directory, gitOptions), input.signal);
506
+ if (rootResult.kind === "failed") return createDiscoveryFailure(mapGitFailure$5(rootResult.reason));
507
+ if (rootResult.value === null) return createDiscoveryFailure("GIT_WORK_TREE_REQUIRED");
508
+ const repositoryRoot = rootResult.value;
509
+ if (!path.isAbsolute(repositoryRoot)) return createDiscoveryFailure("GIT_OUTPUT_INVALID");
510
+ const rootDirectoryResult = await startingDirectoryInspector({
511
+ invocationDirectory: startingDirectoryResult.directory,
512
+ repositoryDirectory: repositoryRoot
513
+ });
514
+ if (rootDirectoryResult.kind === "failed") return createDiscoveryFailure(rootDirectoryResult.errorCode);
515
+ const versionResult = await gitVersionPreflight(rootDirectoryResult.directory, input.signal);
516
+ if (versionResult.kind === "failed") return createDiscoveryFailure(versionResult.errorCode);
517
+ const sparseCheckoutResult = await readGit(() => git.readConfigBoolean(rootDirectoryResult.directory, "core.sparseCheckout", false, gitOptions), input.signal);
518
+ if (sparseCheckoutResult.kind === "failed") return createDiscoveryFailure(mapGitFailure$5(sparseCheckoutResult.reason));
519
+ if (sparseCheckoutResult.value) return createDiscoveryFailure("GIT_SPARSE_CHECKOUT_UNSUPPORTED");
520
+ return Object.freeze({
521
+ kind: "discovered",
522
+ repositoryRoot
523
+ });
524
+ };
525
+ var discoverGitWorkingTree = createGitWorkingTreeDiscovery();
526
+ //#endregion
527
+ //#region src/host-path-identity/utilities.ts
528
+ var areHostPathsEquivalent = (left, right, hostPathOperations = path) => hostPathOperations.relative(hostPathOperations.resolve(left), hostPathOperations.resolve(right)) === "";
529
+ var haveSameHostPathIdentity = (left, right) => left.ino !== 0n && left.dev === right.dev && left.ino === right.ino;
530
+ //#endregion
531
+ //#region src/git-working-tree/identity/comparator.ts
532
+ var areLocationsEqual = (left, right) => haveSameHostPathIdentity(left, right);
533
+ var areGitWorkingTreeIdentitiesEqual = (left, right) => areLocationsEqual(left.repositoryRoot, right.repositoryRoot) && areLocationsEqual(left.gitDirectory, right.gitDirectory) && areLocationsEqual(left.commonDirectory, right.commonDirectory);
534
+ //#endregion
535
+ //#region src/git-working-tree/identity/constants.ts
536
+ var GIT_WORKING_TREE_IDENTITY_ARGUMENTS = Object.freeze({
537
+ CommonDirectory: Object.freeze(["rev-parse", "--git-common-dir"]),
538
+ GitDirectory: Object.freeze(["rev-parse", "--absolute-git-dir"]),
539
+ RepositoryRoot: Object.freeze(["rev-parse", "--show-toplevel"])
540
+ });
541
+ //#endregion
542
+ //#region src/git-working-tree/identity/inspector.ts
543
+ var inspectDirectoryIdentity = async (hostPath) => stat(hostPath, { bigint: true });
544
+ var createInspectionFailure$2 = (errorCode) => Object.freeze({
545
+ errorCode,
546
+ kind: "failed"
547
+ });
548
+ var mapGitFailure$4 = (reason) => {
549
+ switch (reason) {
550
+ case "aborted": return "GIT_OPERATION_ABORTED";
551
+ case "not-found": return "GIT_NOT_FOUND";
552
+ case "repository-not-found": return "GIT_REPOSITORY_NOT_FOUND";
553
+ case "access-denied": return "GIT_ACCESS_DENIED";
554
+ case "output-limit-exceeded":
555
+ case "output-invalid": return "GIT_OUTPUT_INVALID";
556
+ case "command-failed": return "GIT_COMMAND_FAILED";
557
+ }
558
+ };
559
+ var mapFilesystemFailure$2 = (error) => {
560
+ let errorCode;
561
+ try {
562
+ if (typeof error === "object" && error !== null && "code" in error) {
563
+ const unknownCode = error.code;
564
+ errorCode = typeof unknownCode === "string" ? unknownCode.toUpperCase() : void 0;
565
+ }
566
+ } catch {
567
+ return "GIT_COMMAND_FAILED";
568
+ }
569
+ if (errorCode === "ENOENT" || errorCode === "ENOTDIR") return "GIT_REPOSITORY_NOT_FOUND";
570
+ if (errorCode === "EACCES" || errorCode === "EPERM") return "GIT_ACCESS_DENIED";
571
+ return "GIT_COMMAND_FAILED";
572
+ };
573
+ var queryGitPath = async (runGit, repositoryRoot, arguments_, isAbsoluteRequired, signal) => {
574
+ const result = await runGit(arguments_, {
575
+ cwd: repositoryRoot,
576
+ maxOutputBytes: MAX_GIT_DISCOVERY_OUTPUT_BYTES,
577
+ ...signal === void 0 ? {} : { signal }
578
+ });
579
+ if (result.kind === "failed") return createInspectionFailure$2(mapGitFailure$4(result.reason));
580
+ return (isAbsoluteRequired ? parseGitAbsolutePathOutput(result.value) : parseGitPathOutput(result.value)) ?? createInspectionFailure$2("GIT_OUTPUT_INVALID");
581
+ };
582
+ var captureLocation = async (inspectPath, hostPath, invalidTypeCode) => {
583
+ try {
584
+ const statistics = await inspectPath(hostPath);
585
+ if (!statistics.isDirectory() || statistics.ino === 0n) return createInspectionFailure$2(invalidTypeCode);
586
+ return Object.freeze({
587
+ dev: statistics.dev,
588
+ ino: statistics.ino,
589
+ path: hostPath
590
+ });
591
+ } catch (error) {
592
+ return createInspectionFailure$2(mapFilesystemFailure$2(error));
593
+ }
594
+ };
595
+ var isInspectionFailure$1 = (result) => typeof result === "object" && "kind" in result && result.kind === "failed";
596
+ var createGitWorkingTreeIdentityInspector = (runGit = runGitCommand, inspectPath = inspectDirectoryIdentity) => {
597
+ return async (input) => {
598
+ if (!path.isAbsolute(input.repositoryRoot) || input.repositoryRoot.includes("\0") || !input.repositoryRoot.isWellFormed()) return createInspectionFailure$2("GIT_OUTPUT_INVALID");
599
+ const discoveredRoot = await queryGitPath(runGit, input.repositoryRoot, GIT_WORKING_TREE_IDENTITY_ARGUMENTS.RepositoryRoot, true, input.signal);
600
+ if (isInspectionFailure$1(discoveredRoot)) return discoveredRoot;
601
+ const repositoryRoot = await captureLocation(inspectPath, discoveredRoot, "GIT_WORK_TREE_REQUIRED");
602
+ if (input.signal?.aborted) return createInspectionFailure$2("GIT_OPERATION_ABORTED");
603
+ if (isInspectionFailure$1(repositoryRoot)) return repositoryRoot;
604
+ if (!areHostPathsEquivalent(discoveredRoot, input.repositoryRoot)) {
605
+ const selectedRepositoryRoot = await captureLocation(inspectPath, input.repositoryRoot, "GIT_WORK_TREE_REQUIRED");
606
+ if (input.signal?.aborted) return createInspectionFailure$2("GIT_OPERATION_ABORTED");
607
+ if (isInspectionFailure$1(selectedRepositoryRoot)) return selectedRepositoryRoot;
608
+ if (!haveSameHostPathIdentity(repositoryRoot, selectedRepositoryRoot)) return Object.freeze({ kind: "mismatched" });
609
+ }
610
+ const gitDirectoryPath = await queryGitPath(runGit, input.repositoryRoot, GIT_WORKING_TREE_IDENTITY_ARGUMENTS.GitDirectory, true, input.signal);
611
+ if (isInspectionFailure$1(gitDirectoryPath)) return gitDirectoryPath;
612
+ const commonDirectoryOutput = await queryGitPath(runGit, input.repositoryRoot, GIT_WORKING_TREE_IDENTITY_ARGUMENTS.CommonDirectory, false, input.signal);
613
+ if (isInspectionFailure$1(commonDirectoryOutput)) return commonDirectoryOutput;
614
+ const commonDirectoryPath = path.isAbsolute(commonDirectoryOutput) ? commonDirectoryOutput : path.resolve(input.repositoryRoot, commonDirectoryOutput);
615
+ const gitDirectory = await captureLocation(inspectPath, gitDirectoryPath, "GIT_OUTPUT_INVALID");
616
+ if (input.signal?.aborted) return createInspectionFailure$2("GIT_OPERATION_ABORTED");
617
+ if (isInspectionFailure$1(gitDirectory)) return gitDirectory;
618
+ const commonDirectory = await captureLocation(inspectPath, commonDirectoryPath, "GIT_OUTPUT_INVALID");
619
+ if (input.signal?.aborted) return createInspectionFailure$2("GIT_OPERATION_ABORTED");
620
+ if (isInspectionFailure$1(commonDirectory)) return commonDirectory;
621
+ return Object.freeze({
622
+ identity: Object.freeze({
623
+ commonDirectory,
624
+ gitDirectory,
625
+ repositoryRoot
626
+ }),
627
+ kind: "inspected"
628
+ });
629
+ };
630
+ };
631
+ var inspectGitWorkingTreeIdentity = createGitWorkingTreeIdentityInspector();
632
+ //#endregion
633
+ //#region src/project-content/exception.ts
634
+ var MoldeaCliProjectContentException = class extends Error {
635
+ code;
636
+ constructor(code) {
637
+ super(code);
638
+ this.code = code;
639
+ this.name = "MoldeaCliProjectContentException";
640
+ }
641
+ };
642
+ //#endregion
643
+ //#region src/project-content/validations.ts
644
+ var CONTEXT_PATH_PATTERN = /^\/moldea\/context\/(?:[^/]+\/)*[^/]+\.md$/u;
645
+ var DECISION_PATH_PATTERN = /^\/moldea\/decisions\/[^/]+\.md$/u;
646
+ var AGENT_PATH_PATTERN = /^\/moldea\/agents\/[^/]+\/(?:description|instruction)\.md$/u;
647
+ var isMoldeaCliCanonicalContentPath = (path) => {
648
+ if (/[?*[\]{}]/u.test(path)) return false;
649
+ return path === "/moldea/moldea.yaml" || path === "/moldea/project.md" || CONTEXT_PATH_PATTERN.test(path) || DECISION_PATH_PATTERN.test(path) || AGENT_PATH_PATTERN.test(path);
650
+ };
651
+ var parseMoldeaCliCanonicalContentPath = (input) => {
652
+ let path;
653
+ try {
654
+ path = parseRepositoryPath(input);
655
+ } catch {
656
+ throw new MoldeaCliProjectContentException("CONTENT_PATH_INVALID");
657
+ }
658
+ if (!isMoldeaCliCanonicalContentPath(path)) throw new MoldeaCliProjectContentException("CONTENT_PATH_INVALID");
659
+ return path;
660
+ };
661
+ //#endregion
662
+ //#region src/project-content/executor.ts
663
+ var createMoldeaCliProjectContentExecutor = (coreFactory = createCore) => {
664
+ return async (input) => {
665
+ return coreFactory({ limits: Object.freeze({
666
+ maxDiagnostics: input.resourceLimits.maxDiagnostics,
667
+ maxEntries: input.resourceLimits.maxEntries,
668
+ maxCoverage: input.resourceLimits.maxCoverage,
669
+ maxFileBytes: input.resourceLimits.maxFileBytes,
670
+ maxManifestBytes: input.resourceLimits.maxManifestBytes,
671
+ maxTotalBytesRead: input.resourceLimits.maxTotalBytes
672
+ }) }).readCanonicalContentPage({
673
+ maxBytes: input.maxBytes,
674
+ offset: input.offset,
675
+ path: input.path,
676
+ repository: input.repository,
677
+ ...input.signal === void 0 ? {} : { signal: input.signal }
678
+ });
679
+ };
680
+ };
681
+ var executeMoldeaCliProjectContent = createMoldeaCliProjectContentExecutor();
682
+ //#endregion
683
+ //#region src/project-content/page.ts
684
+ var createCandidate = (input, scalars, scalarEnd, snapshotDigest) => {
685
+ const content = scalars.slice(0, scalarEnd).join("");
686
+ const byteEnd = input.page.byteStart + Buffer.byteLength(content, "utf8");
687
+ const isComplete = byteEnd === input.page.totalBytes;
688
+ return {
689
+ asset: {
690
+ contentIdentity: input.page.contentIdentity,
691
+ path: input.page.path,
692
+ totalBytes: input.page.totalBytes
693
+ },
694
+ chunk: {
695
+ byteEnd,
696
+ byteStart: input.page.byteStart,
697
+ content
698
+ },
699
+ cursor: isComplete ? null : encodeMoldeaCliCursor("content", { path: input.page.path }, snapshotDigest, `byte:${byteEnd}`, `byte:${byteEnd}`),
700
+ snapshotDigest
701
+ };
702
+ };
703
+ var createSnapshotDigest = (input) => calculateMoldeaCliJsonDigest({
704
+ contentIdentity: input.page.contentIdentity,
705
+ path: input.page.path,
706
+ totalBytes: input.page.totalBytes
707
+ });
708
+ var createMoldeaCliContentPage = (input) => {
709
+ const snapshotDigest = createSnapshotDigest(input);
710
+ const cursorState = input.cursor === null ? null : decodeMoldeaCliCursor({
711
+ command: "content",
712
+ cursor: input.cursor,
713
+ filters: { path: input.page.path },
714
+ snapshotDigest
715
+ });
716
+ const expectedSourceCursor = `byte:${input.page.byteStart}`;
717
+ if (cursorState === null && input.page.byteStart !== 0 || cursorState !== null && cursorState.sourceCursor !== expectedSourceCursor) throw new MoldeaCliOutputPageException("CURSOR_INVALID");
718
+ const scalars = Array.from(input.page.content);
719
+ const emptyResult = createCandidate(input, scalars, 0, snapshotDigest);
720
+ if (scalars.length === 0) {
721
+ if (!input.page.isComplete || input.measure(emptyResult) > input.maxOutputBytes) throw new MoldeaCliOutputPageException("OUTPUT_BUDGET_TOO_SMALL");
722
+ return Object.freeze({
723
+ ...emptyResult,
724
+ asset: Object.freeze(emptyResult.asset),
725
+ chunk: Object.freeze(emptyResult.chunk)
726
+ });
727
+ }
728
+ let lower = 1;
729
+ let upper = scalars.length;
730
+ let selected = null;
731
+ while (lower <= upper) {
732
+ const scalarEnd = lower + Math.floor((upper - lower) / 2);
733
+ const candidate = createCandidate(input, scalars, scalarEnd, snapshotDigest);
734
+ if (input.measure(candidate) <= input.maxOutputBytes) {
735
+ selected = candidate;
736
+ lower = scalarEnd + 1;
737
+ } else upper = scalarEnd - 1;
738
+ }
739
+ if (selected === null) throw new MoldeaCliOutputPageException("OUTPUT_BUDGET_TOO_SMALL");
740
+ return Object.freeze({
741
+ ...selected,
742
+ asset: Object.freeze(selected.asset),
743
+ chunk: Object.freeze(selected.chunk)
744
+ });
745
+ };
746
+ //#endregion
747
+ //#region src/project-scope/constants.ts
748
+ var MOLDEA_MANIFEST_PATH = parseRepositoryPath("/moldea/moldea.yaml");
749
+ //#endregion
750
+ //#region src/project-scope/exception.ts
751
+ var MoldeaCliProjectScopeException = class extends Error {
752
+ code;
753
+ constructor(code) {
754
+ super(code);
755
+ this.code = code;
756
+ this.name = "MoldeaCliProjectScopeException";
757
+ }
758
+ };
759
+ //#endregion
760
+ //#region src/project-scope/paths.ts
761
+ var parseMoldeaCliScopePathBytes = (input, maxEntries) => {
762
+ if (input.byteLength === 0) return Object.freeze([]);
763
+ let text;
764
+ try {
765
+ text = new TextDecoder("utf-8", { fatal: true }).decode(input);
766
+ } catch {
767
+ throw new MoldeaCliProjectScopeException("PATH_INPUT_INVALID");
768
+ }
769
+ if (!text.endsWith("\0")) throw new MoldeaCliProjectScopeException("PATH_INPUT_INVALID");
770
+ const paths = text.slice(0, -1).split("\0");
771
+ if (paths.length > maxEntries || paths.some((path) => path.length === 0)) throw new MoldeaCliProjectScopeException("PATH_INPUT_INVALID");
772
+ return Object.freeze(paths);
773
+ };
774
+ //#endregion
775
+ //#region src/project-scope/executor.ts
776
+ var readBoundedManifest = async (input) => {
777
+ const operationOptions = input.signal === void 0 ? void 0 : { signal: input.signal };
778
+ const entry = await input.repository.getEntry(MOLDEA_MANIFEST_PATH, operationOptions);
779
+ if (entry === null) throw new RepositorySourceException({
780
+ code: "ENTRY_NOT_FOUND",
781
+ operation: "read-file-page",
782
+ path: MOLDEA_MANIFEST_PATH,
783
+ retryable: false
784
+ });
785
+ if (entry.type !== "file" || entry.byteLength === null) throw new RepositorySourceException({
786
+ code: "ENTRY_NOT_FILE",
787
+ operation: "read-file-page",
788
+ path: MOLDEA_MANIFEST_PATH,
789
+ retryable: false
790
+ });
791
+ const maxBytes = Math.min(input.resourceLimits.maxManifestBytes, input.resourceLimits.maxTotalBytes);
792
+ if (entry.byteLength > maxBytes) throw new RepositorySourceException({
793
+ code: "RESOURCE_LIMIT_EXCEEDED",
794
+ operation: "read-file-page",
795
+ path: MOLDEA_MANIFEST_PATH,
796
+ retryable: false
797
+ });
798
+ const chunks = [];
799
+ let byteLength = 0;
800
+ let nextOffset = 0;
801
+ let isComplete = false;
802
+ while (!isComplete) {
803
+ const page = await input.repository.readFilePage(MOLDEA_MANIFEST_PATH, {
804
+ maxBytes: Math.max(1, entry.byteLength - byteLength),
805
+ offset: nextOffset,
806
+ ...input.signal === void 0 ? {} : { signal: input.signal }
807
+ });
808
+ if (page.snapshot.id !== input.repository.snapshot.id || page.offset !== nextOffset || page.totalBytes !== entry.byteLength || page.bytes.byteLength > entry.byteLength - byteLength || page.bytes.byteLength === 0 && !page.isComplete || !page.isComplete && page.nextOffset !== page.offset + page.bytes.byteLength) throw new RepositorySourceException({
809
+ code: "INVALID_SOURCE_DATA",
810
+ operation: "read-file-page",
811
+ path: MOLDEA_MANIFEST_PATH,
812
+ retryable: false
813
+ });
814
+ chunks.push(page.bytes);
815
+ byteLength += page.bytes.byteLength;
816
+ nextOffset = page.nextOffset ?? byteLength;
817
+ isComplete = page.isComplete;
818
+ }
819
+ if (byteLength !== entry.byteLength) throw new RepositorySourceException({
820
+ code: "PROVIDER_INCOMPLETE",
821
+ operation: "read-file-page",
822
+ path: MOLDEA_MANIFEST_PATH,
823
+ retryable: false
824
+ });
825
+ const manifestBytes = new Uint8Array(byteLength);
826
+ let writeOffset = 0;
827
+ for (const chunk of chunks) {
828
+ manifestBytes.set(chunk, writeOffset);
829
+ writeOffset += chunk.byteLength;
830
+ }
831
+ return manifestBytes;
832
+ };
833
+ var createMoldeaCliProjectScopeExecutor = (coreFactory = createCore) => {
834
+ return async (input) => {
835
+ const manifestBytes = await readBoundedManifest(input);
836
+ const scope = await coreFactory({ limits: Object.freeze({
837
+ maxDiagnostics: input.resourceLimits.maxDiagnostics,
838
+ maxEntries: input.resourceLimits.maxEntries,
839
+ maxCoverage: input.resourceLimits.maxCoverage,
840
+ maxFileBytes: input.resourceLimits.maxFileBytes,
841
+ maxManifestBytes: input.resourceLimits.maxManifestBytes,
842
+ maxTotalBytesRead: input.resourceLimits.maxTotalBytes
843
+ }) }).matchManifestScope({
844
+ manifest: {
845
+ content: manifestBytes,
846
+ path: MOLDEA_MANIFEST_PATH
847
+ },
848
+ paths: input.paths
849
+ });
850
+ return Object.freeze({
851
+ manifestContent: new TextDecoder("utf-8").decode(manifestBytes),
852
+ scope
853
+ });
854
+ };
855
+ };
856
+ var executeMoldeaCliProjectScope = createMoldeaCliProjectScopeExecutor();
857
+ //#endregion
858
+ //#region src/project-scope/transformers.ts
859
+ var compareKeys = (left, right) => left.key < right.key ? -1 : left.key > right.key ? 1 : 0;
860
+ var createMatchKey = (match) => JSON.stringify([
861
+ "match",
862
+ match.owner.kind,
863
+ match.owner.agentId,
864
+ match.owner.id,
865
+ match.field,
866
+ match.declaration.kind === "exact" ? match.declaration.path : match.declaration.pattern,
867
+ match.inputPath,
868
+ match.pointer
869
+ ]);
870
+ var createMoldeaCliScopeProjection = (execution) => {
871
+ const records = [...execution.scope.diagnostics.map((diagnostic, index) => createMoldeaCliDiagnosticRecord(diagnostic, index)), ...execution.scope.matches.map((match) => ({
872
+ key: createMatchKey(match),
873
+ kind: "match",
874
+ match
875
+ }))].sort(compareKeys);
876
+ const snapshotDigest = calculateMoldeaCliJsonDigest({
877
+ inputDigest: execution.scope.inputDigest,
878
+ manifestDigest: execution.scope.manifestDigest,
879
+ records,
880
+ valid: execution.scope.valid
881
+ });
882
+ return Object.freeze({
883
+ canonicalBodies: Object.freeze([execution.manifestContent]),
884
+ counts: Object.freeze({
885
+ ...execution.scope.counts,
886
+ diagnostics: execution.scope.diagnostics.length
887
+ }),
888
+ inputDigest: execution.scope.inputDigest,
889
+ manifestDigest: execution.scope.manifestDigest,
890
+ records: Object.freeze(records),
891
+ relevant: execution.scope.relevant,
892
+ snapshotDigest,
893
+ valid: execution.scope.valid
894
+ });
895
+ };
896
+ //#endregion
897
+ //#region src/repository-content-transformation-guard/exception.ts
898
+ var GitContentTransformUnsupportedException = class extends RepositorySourceException {
899
+ constructor(path) {
900
+ super({
901
+ code: "SOURCE_UNAVAILABLE",
902
+ operation: "read-file-page",
903
+ path,
904
+ retryable: false
905
+ });
906
+ this.name = "GitContentTransformUnsupportedException";
907
+ }
908
+ };
909
+ //#endregion
910
+ //#region src/repository-content-transformation-guard/reader.ts
911
+ var throwIfAborted$2 = (signal, path) => {
912
+ if (!signal?.aborted) return;
913
+ throw new RepositorySourceException({
914
+ cause: signal.reason,
915
+ code: "ABORTED",
916
+ operation: "read-file-page",
917
+ path,
918
+ retryable: false
919
+ });
920
+ };
921
+ var createInvalidSourceException = (path) => new RepositorySourceException({
922
+ code: "INVALID_SOURCE_DATA",
923
+ operation: "read-file-page",
924
+ path,
925
+ retryable: false
926
+ });
927
+ var GitContentTransformationGuardRepositoryReader = class {
928
+ snapshot;
929
+ #guardedPaths;
930
+ #reader;
931
+ constructor(reader, guardedPaths) {
932
+ this.#reader = reader;
933
+ this.#guardedPaths = guardedPaths;
934
+ this.snapshot = reader.snapshot;
935
+ }
936
+ compare(candidate, options) {
937
+ return createRepositoryComparison(this, candidate, options);
938
+ }
939
+ getEntry(path, options) {
940
+ return this.#reader.getEntry(path, options);
941
+ }
942
+ async readFilePage(path, options) {
943
+ const parsedPath = parseRepositoryPath(path);
944
+ if (!this.#guardedPaths.has(parsedPath)) return this.#reader.readFilePage(parsedPath, options);
945
+ throwIfAborted$2(options?.signal, parsedPath);
946
+ const entry = await this.#reader.getEntry(parsedPath, options);
947
+ throwIfAborted$2(options?.signal, parsedPath);
948
+ if (entry !== null && (entry.path !== parsedPath || entry.type !== "file" && entry.type !== "directory" && entry.type !== "symlink")) throw createInvalidSourceException(parsedPath);
949
+ if (entry?.type !== "file") return this.#reader.readFilePage(parsedPath, options);
950
+ throw new GitContentTransformUnsupportedException(parsedPath);
951
+ }
952
+ readLinkText(path, options) {
953
+ return this.#reader.readLinkText(path, options);
954
+ }
955
+ listEntriesPage(options) {
956
+ return this.#reader.listEntriesPage(options);
957
+ }
958
+ };
959
+ var createGitContentTransformationGuardRepositoryReader = (reader, guardedPaths) => {
960
+ const parsedGuardedPaths = new Set();
961
+ for (const guardedPath of guardedPaths) {
962
+ const parsedPath = parseRepositoryPath(guardedPath);
963
+ if (parsedPath === REPOSITORY_ROOT) throw new RepositorySourceException({
964
+ code: "INVALID_SOURCE_DATA",
965
+ operation: "create-reader",
966
+ path: parsedPath,
967
+ retryable: false
968
+ });
969
+ parsedGuardedPaths.add(parsedPath);
970
+ }
971
+ return Object.freeze(new GitContentTransformationGuardRepositoryReader(reader, parsedGuardedPaths));
972
+ };
973
+ //#endregion
974
+ //#region src/operational-error/constants.ts
975
+ var REPOSITORY_SOURCE_ERROR_MESSAGES = Object.freeze({
976
+ ABORTED: "The repository operation was aborted.",
977
+ ACCESS_DENIED: "Access to the repository source was denied.",
978
+ ENTRY_NOT_DIRECTORY: "The requested repository entry is not a directory.",
979
+ ENTRY_NOT_FILE: "The requested repository entry is not a file.",
980
+ ENTRY_NOT_FOUND: "The requested repository entry was not found.",
981
+ ENTRY_NOT_LINK: "The requested repository entry is not a symlink.",
982
+ INVALID_PAGE_REQUEST: "The repository page request is invalid.",
983
+ INVALID_SOURCE_DATA: "The repository source returned invalid data.",
984
+ PROVIDER_INCOMPLETE: "The repository provider could not expose a complete result.",
985
+ RESOURCE_LIMIT_EXCEEDED: "A repository reading resource limit was exceeded.",
986
+ SNAPSHOT_CHANGED: "The repository snapshot changed during the operation.",
987
+ SOURCE_UNAVAILABLE: "The repository source is unavailable."
988
+ });
989
+ var CORE_CONFIGURATION_ERROR_MESSAGES = Object.freeze({ INVALID_RESOURCE_LIMIT: "A Core resource limit is invalid." });
990
+ var CORE_OPERATION_ERROR_MESSAGES = Object.freeze({
991
+ ABORTED: "The Core operation was aborted.",
992
+ CONTENT_INVALID: "The requested canonical content is invalid.",
993
+ INVALID_ARGUMENT: "The Core operation received an invalid argument.",
994
+ INSPECTION_BUSY: "Project inspection capacity is busy. Try again shortly.",
995
+ INSPECTION_TIMEOUT: "The isolated project inspection timed out.",
996
+ INSPECTION_PROCESS_FAILED: "The isolated project inspection failed.",
997
+ RESOURCE_LIMIT_EXCEEDED: "A Core resource limit was exceeded."
998
+ });
999
+ //#endregion
1000
+ //#region src/operational-error/mapper.ts
1001
+ var EMPTY_ERROR_DETAILS = Object.freeze({});
1002
+ var createCoreErrorDetails = (error) => {
1003
+ const details = { operation: error.operation };
1004
+ if (error instanceof CoreOperationException) {
1005
+ if (error.limit !== null) details["limit"] = error.limit;
1006
+ if (error.limitMaximum !== null) details["limitMaximum"] = error.limitMaximum;
1007
+ if (error.nextAction !== null) details["nextAction"] = error.nextAction;
1008
+ if (error.observedUsage !== null || error.nextAction === "review-inspection-capacity") details["observedUsage"] = error.observedUsage;
1009
+ }
1010
+ return Object.freeze(details);
1011
+ };
1012
+ var mapMoldeaCliOperationalError = (error) => {
1013
+ if (error instanceof MoldeaCliCompositionException || error instanceof MoldeaCliOutputPageException || error instanceof MoldeaCliProjectContentException || error instanceof MoldeaCliProjectScopeException) return createMoldeaCliOwnedError(error.code);
1014
+ if (error instanceof GitContentTransformUnsupportedException) return Object.freeze({
1015
+ ...createMoldeaCliOwnedError("GIT_CONTENT_TRANSFORM_UNSUPPORTED"),
1016
+ path: isRepositoryPath(error.path) ? error.path : null
1017
+ });
1018
+ if (error instanceof RepositorySourceException) return Object.freeze({
1019
+ code: error.code,
1020
+ details: EMPTY_ERROR_DETAILS,
1021
+ message: REPOSITORY_SOURCE_ERROR_MESSAGES[error.code],
1022
+ path: error.path !== null && isRepositoryPath(error.path) ? error.path : null,
1023
+ retryable: error.retryable,
1024
+ source: "repository"
1025
+ });
1026
+ if (error instanceof CoreConfigurationException) return Object.freeze({
1027
+ code: error.code,
1028
+ details: createCoreErrorDetails(error),
1029
+ message: CORE_CONFIGURATION_ERROR_MESSAGES[error.code],
1030
+ path: null,
1031
+ retryable: false,
1032
+ source: "core"
1033
+ });
1034
+ if (error instanceof CoreOperationException) return Object.freeze({
1035
+ code: error.code,
1036
+ details: createCoreErrorDetails(error),
1037
+ message: CORE_OPERATION_ERROR_MESSAGES[error.code],
1038
+ path: null,
1039
+ retryable: error.retryable,
1040
+ source: "core"
1041
+ });
1042
+ return createMoldeaCliOwnedError("INTERNAL_ERROR");
1043
+ };
1044
+ //#endregion
1045
+ //#region src/git-inventory/constants.ts
1046
+ var GIT_IGNORED_INVENTORY_ARGUMENTS = [
1047
+ "ls-files",
1048
+ "--others",
1049
+ "--ignored",
1050
+ "--exclude-standard",
1051
+ "--full-name",
1052
+ "--no-recurse-submodules",
1053
+ "-z",
1054
+ "--"
1055
+ ];
1056
+ var GIT_INVENTORY_LISTING_SUBCOMMAND = "ls-files";
1057
+ var INSTRUCTION_PATHS = Object.freeze([
1058
+ "/AGENTS.md",
1059
+ "/CLAUDE.md",
1060
+ "/.claude/CLAUDE.md",
1061
+ "/CLAUDE.local.md"
1062
+ ].map((path) => parseRepositoryPath(path)));
1063
+ var GIT_TRACKED_ENTRY_MODES = [
1064
+ "100644",
1065
+ "100755",
1066
+ "120000",
1067
+ "160000"
1068
+ ];
1069
+ //#endregion
1070
+ //#region src/git-inventory/content-transformation/constants.ts
1071
+ var GIT_CONTENT_TRANSFORMATION_ATTRIBUTES = [
1072
+ "filter",
1073
+ "working-tree-encoding",
1074
+ "ident"
1075
+ ];
1076
+ var GIT_CONTENT_TRANSFORMATION_ARGUMENTS = [
1077
+ "check-attr",
1078
+ "--stdin",
1079
+ "-z",
1080
+ ...GIT_CONTENT_TRANSFORMATION_ATTRIBUTES
1081
+ ];
1082
+ //#endregion
1083
+ //#region src/git-inventory/content-transformation/parser.ts
1084
+ var concatenateField = (fragments, byteLength) => {
1085
+ const field = new Uint8Array(byteLength);
1086
+ let offset = 0;
1087
+ for (const fragment of fragments) {
1088
+ field.set(fragment, offset);
1089
+ offset += fragment.byteLength;
1090
+ }
1091
+ return field;
1092
+ };
1093
+ var decodeField = (field) => {
1094
+ try {
1095
+ return new TextDecoder("utf-8", {
1096
+ fatal: true,
1097
+ ignoreBOM: true
1098
+ }).decode(field);
1099
+ } catch {
1100
+ return null;
1101
+ }
1102
+ };
1103
+ var resolveAttribute = (candidate) => {
1104
+ return GIT_CONTENT_TRANSFORMATION_ATTRIBUTES.find((attribute) => attribute === candidate) ?? null;
1105
+ };
1106
+ var storeAttribute = (values, attribute, value) => {
1107
+ const property = attribute === "working-tree-encoding" ? "workingTreeEncoding" : attribute;
1108
+ if (Object.hasOwn(values, property)) return false;
1109
+ values[property] = value;
1110
+ return true;
1111
+ };
1112
+ var hasCompleteValues = (values) => Object.hasOwn(values, "filter") && Object.hasOwn(values, "ident") && Object.hasOwn(values, "workingTreeEncoding");
1113
+ var createGitContentTransformationParser = (input) => {
1114
+ const paths = [...input.paths];
1115
+ const valuesByPath = new Map();
1116
+ let fields = [];
1117
+ let isFailed = false;
1118
+ let pendingByteLength = 0;
1119
+ let pendingFragments = [];
1120
+ for (const path of paths) {
1121
+ if (path.length === 0 || path.includes("\0") || valuesByPath.has(path)) {
1122
+ isFailed = true;
1123
+ continue;
1124
+ }
1125
+ valuesByPath.set(path, {});
1126
+ }
1127
+ const consumeRecord = () => {
1128
+ if (isFailed || fields.length !== 3) return;
1129
+ const path = decodeField(fields[0] ?? new Uint8Array());
1130
+ const attributeCandidate = decodeField(fields[1] ?? new Uint8Array());
1131
+ const value = decodeField(fields[2] ?? new Uint8Array());
1132
+ fields = [];
1133
+ if (path === null || attributeCandidate === null || value === null) {
1134
+ isFailed = true;
1135
+ return;
1136
+ }
1137
+ const attribute = resolveAttribute(attributeCandidate);
1138
+ const values = valuesByPath.get(path);
1139
+ if (attribute === null || values === void 0 || !storeAttribute(values, attribute, value)) isFailed = true;
1140
+ };
1141
+ const consumeField = () => {
1142
+ if (isFailed) return;
1143
+ fields.push(concatenateField(pendingFragments, pendingByteLength));
1144
+ pendingByteLength = 0;
1145
+ pendingFragments = [];
1146
+ if (fields.length === 3) consumeRecord();
1147
+ };
1148
+ return {
1149
+ consume: (chunk) => {
1150
+ if (isFailed) return;
1151
+ let fragmentStart = 0;
1152
+ for (let index = 0; index < chunk.byteLength; index += 1) {
1153
+ if (chunk[index] !== 0) continue;
1154
+ const fragment = chunk.subarray(fragmentStart, index);
1155
+ pendingFragments.push(Uint8Array.from(fragment));
1156
+ pendingByteLength += fragment.byteLength;
1157
+ consumeField();
1158
+ if (isFailed) return;
1159
+ fragmentStart = index + 1;
1160
+ }
1161
+ const trailingFragment = chunk.subarray(fragmentStart);
1162
+ if (trailingFragment.byteLength > 0) {
1163
+ pendingFragments.push(Uint8Array.from(trailingFragment));
1164
+ pendingByteLength += trailingFragment.byteLength;
1165
+ }
1166
+ },
1167
+ finish: () => {
1168
+ if (isFailed || pendingByteLength > 0 || fields.length > 0) return Object.freeze({ kind: "failed" });
1169
+ const attributes = [];
1170
+ for (const path of paths) {
1171
+ const values = valuesByPath.get(path);
1172
+ if (values === void 0 || !hasCompleteValues(values)) return Object.freeze({ kind: "failed" });
1173
+ attributes.push(Object.freeze({
1174
+ filter: values.filter,
1175
+ ident: values.ident,
1176
+ path,
1177
+ workingTreeEncoding: values.workingTreeEncoding
1178
+ }));
1179
+ }
1180
+ return Object.freeze({
1181
+ attributes: Object.freeze(attributes),
1182
+ kind: "completed"
1183
+ });
1184
+ }
1185
+ };
1186
+ };
1187
+ //#endregion
1188
+ //#region src/git-inventory/content-transformation/classifier.ts
1189
+ var createClassificationFailure = (errorCode, subcommand) => Object.freeze({
1190
+ errorCode,
1191
+ kind: "failed",
1192
+ ...subcommand === void 0 ? {} : { subcommand }
1193
+ });
1194
+ var mapGitFailure$3 = (reason) => {
1195
+ switch (reason) {
1196
+ case "aborted": return "GIT_OPERATION_ABORTED";
1197
+ case "not-found": return "GIT_NOT_FOUND";
1198
+ case "access-denied": return "GIT_ACCESS_DENIED";
1199
+ case "repository-not-found": return "GIT_REPOSITORY_NOT_FOUND";
1200
+ case "output-limit-exceeded": return "RESOURCE_LIMIT_EXCEEDED";
1201
+ case "output-invalid": return "GIT_OUTPUT_INVALID";
1202
+ case "command-failed": return "GIT_COMMAND_FAILED";
1203
+ }
1204
+ };
1205
+ var isGuardedAttributeValue = (attributeValue) => attributeValue !== "unset" && attributeValue !== "unspecified";
1206
+ var encodePaths = (paths) => {
1207
+ const encoder = new TextEncoder();
1208
+ const encodedPaths = [];
1209
+ let byteLength = 0;
1210
+ for (const path of paths) {
1211
+ if (path.length === 0 || path.includes("\0")) return null;
1212
+ const encodedPath = encoder.encode(path);
1213
+ if (!Number.isSafeInteger(byteLength + encodedPath.byteLength + 1)) return null;
1214
+ encodedPaths.push(encodedPath);
1215
+ byteLength += encodedPath.byteLength + 1;
1216
+ }
1217
+ const stdin = new Uint8Array(byteLength);
1218
+ let offset = 0;
1219
+ for (const encodedPath of encodedPaths) {
1220
+ stdin.set(encodedPath, offset);
1221
+ offset += encodedPath.byteLength + 1;
1222
+ }
1223
+ return stdin;
1224
+ };
1225
+ var createClassification = (filter, ident, workingTreeEncoding) => Object.freeze({
1226
+ filter,
1227
+ ident,
1228
+ isGuarded: isGuardedAttributeValue(filter) || isGuardedAttributeValue(ident) || isGuardedAttributeValue(workingTreeEncoding),
1229
+ workingTreeEncoding
1230
+ });
1231
+ var createGitContentTransformationClassifier = (runGit = runGitCommand) => {
1232
+ return async (input) => {
1233
+ if (input.signal?.aborted) return createClassificationFailure("GIT_OPERATION_ABORTED");
1234
+ if (!Number.isSafeInteger(input.maxMetadataBytes) || input.maxMetadataBytes < 0) return createClassificationFailure("RESOURCE_LIMIT_EXCEEDED");
1235
+ if (input.entries.length === 0) return Object.freeze({
1236
+ entries: Object.freeze([]),
1237
+ gitMetadataBytes: 0,
1238
+ kind: "classified"
1239
+ });
1240
+ const paths = input.entries.map((entry) => entry.path);
1241
+ const stdin = encodePaths(paths);
1242
+ if (stdin === null) return createClassificationFailure("GIT_OUTPUT_INVALID");
1243
+ const result = await runGit(GIT_CONTENT_TRANSFORMATION_ARGUMENTS, {
1244
+ cwd: input.repositoryRoot,
1245
+ input: stdin,
1246
+ maxOutputBytes: Math.max(input.maxMetadataBytes, 1),
1247
+ ...input.signal === void 0 ? {} : { signal: input.signal }
1248
+ });
1249
+ if (result.kind === "failed") return createClassificationFailure(mapGitFailure$3(result.reason), result.subcommand);
1250
+ if (result.value.byteLength > input.maxMetadataBytes) return createClassificationFailure("RESOURCE_LIMIT_EXCEEDED");
1251
+ const parser = createGitContentTransformationParser({ paths });
1252
+ parser.consume(result.value);
1253
+ const parserResult = parser.finish();
1254
+ if (parserResult.kind === "failed" || parserResult.attributes.length !== input.entries.length) return createClassificationFailure("GIT_OUTPUT_INVALID");
1255
+ const entries = input.entries.map((entry, index) => {
1256
+ const attributes = parserResult.attributes[index];
1257
+ if (attributes === void 0 || attributes.path !== entry.path) return null;
1258
+ return Object.freeze({
1259
+ ...entry,
1260
+ contentTransformation: createClassification(attributes.filter, attributes.ident, attributes.workingTreeEncoding)
1261
+ });
1262
+ });
1263
+ if (entries.some((entry) => entry === null)) return createClassificationFailure("GIT_OUTPUT_INVALID");
1264
+ return Object.freeze({
1265
+ entries: Object.freeze(entries.filter((entry) => entry !== null)),
1266
+ gitMetadataBytes: result.value.byteLength,
1267
+ kind: "classified"
1268
+ });
1269
+ };
1270
+ };
1271
+ //#endregion
1272
+ //#region src/git-inventory/entry-type/candidate-collapser.ts
1273
+ var createCollapseFailure = () => Object.freeze({ kind: "failed" });
1274
+ var collapseGitInventoryCandidates = (candidates) => {
1275
+ const candidatesByPath = new Map();
1276
+ for (const candidate of candidates) {
1277
+ const existingCandidate = candidatesByPath.get(candidate.path);
1278
+ if (candidate.kind === "untracked") {
1279
+ if (existingCandidate !== void 0) return createCollapseFailure();
1280
+ candidatesByPath.set(candidate.path, {
1281
+ kind: "untracked",
1282
+ path: candidate.path
1283
+ });
1284
+ continue;
1285
+ }
1286
+ if (candidate.mode === "160000" || existingCandidate?.kind === "untracked") return createCollapseFailure();
1287
+ const trackedCandidate = existingCandidate ?? {
1288
+ indexEntriesByStage: new Map(),
1289
+ kind: "tracked",
1290
+ path: candidate.path
1291
+ };
1292
+ if (trackedCandidate.indexEntriesByStage.has(candidate.stage)) return createCollapseFailure();
1293
+ trackedCandidate.indexEntriesByStage.set(candidate.stage, Object.freeze({
1294
+ mode: candidate.mode,
1295
+ stage: candidate.stage
1296
+ }));
1297
+ candidatesByPath.set(candidate.path, trackedCandidate);
1298
+ }
1299
+ const collapsedCandidates = [];
1300
+ for (const candidate of candidatesByPath.values()) {
1301
+ if (candidate.kind === "untracked") {
1302
+ collapsedCandidates.push(Object.freeze(candidate));
1303
+ continue;
1304
+ }
1305
+ if (candidate.indexEntriesByStage.has(0) && candidate.indexEntriesByStage.size !== 1) return createCollapseFailure();
1306
+ const indexEntries = [...candidate.indexEntriesByStage.values()].sort((left, right) => left.stage - right.stage);
1307
+ if (indexEntries.length === 0) return createCollapseFailure();
1308
+ collapsedCandidates.push(Object.freeze({
1309
+ indexEntries: Object.freeze(indexEntries),
1310
+ kind: "tracked",
1311
+ path: candidate.path
1312
+ }));
1313
+ }
1314
+ return Object.freeze({
1315
+ candidates: Object.freeze(collapsedCandidates),
1316
+ kind: "collapsed"
1317
+ });
1318
+ };
1319
+ //#endregion
1320
+ //#region src/git-inventory/entry-type/entry-inspector.ts
1321
+ var createInspectionFailure$1 = (errorCode) => Object.freeze({
1322
+ errorCode,
1323
+ kind: "failed"
1324
+ });
1325
+ var mapFilesystemFailure$1 = (error) => {
1326
+ const errorCode = error?.code?.toUpperCase();
1327
+ if (errorCode === "ENOENT" || errorCode === "ENOTDIR") return null;
1328
+ if (errorCode === "EACCES" || errorCode === "EPERM") return createInspectionFailure$1("GIT_ACCESS_DENIED");
1329
+ if (errorCode === "ELOOP") return createInspectionFailure$1("GIT_OUTPUT_INVALID");
1330
+ return createInspectionFailure$1("GIT_COMMAND_FAILED");
1331
+ };
1332
+ var inspectHostEntry = async (hostPath) => lstat(hostPath);
1333
+ var createGitInventoryEntryInspector = (inspectEntry = inspectHostEntry) => {
1334
+ return async (repositoryRoot, candidatePath) => {
1335
+ let statistics;
1336
+ try {
1337
+ statistics = await inspectEntry(path.join(repositoryRoot, candidatePath));
1338
+ } catch (error) {
1339
+ return mapFilesystemFailure$1(error) ?? Object.freeze({ kind: "missing" });
1340
+ }
1341
+ if (statistics.isSymbolicLink()) return Object.freeze({
1342
+ entryType: "symlink",
1343
+ kind: "inspected"
1344
+ });
1345
+ if (statistics.isFile()) return Object.freeze({
1346
+ entryType: "file",
1347
+ kind: "inspected"
1348
+ });
1349
+ return Object.freeze({
1350
+ entryType: "unsupported",
1351
+ kind: "inspected"
1352
+ });
1353
+ };
1354
+ };
1355
+ var inspectGitInventoryEntry = createGitInventoryEntryInspector();
1356
+ //#endregion
1357
+ //#region src/git-inventory/entry-type/symlink-configuration.ts
1358
+ var GIT_CONFIG_SUBCOMMAND = "config";
1359
+ var createConfigurationFailure = (errorCode, subcommand) => Object.freeze({
1360
+ errorCode,
1361
+ kind: "failed",
1362
+ ...subcommand === void 0 ? {} : { subcommand }
1363
+ });
1364
+ var mapGitFailure$2 = (reason) => {
1365
+ switch (reason) {
1366
+ case "aborted": return "GIT_OPERATION_ABORTED";
1367
+ case "not-found": return "GIT_NOT_FOUND";
1368
+ case "access-denied": return "GIT_ACCESS_DENIED";
1369
+ case "output-limit-exceeded": return "RESOURCE_LIMIT_EXCEEDED";
1370
+ case "repository-not-found":
1371
+ case "output-invalid": return "GIT_OUTPUT_INVALID";
1372
+ case "command-failed": return "GIT_COMMAND_FAILED";
1373
+ }
1374
+ };
1375
+ var createGitSymlinkConfigurationResolver = (readBoolean = readConfigBoolean) => {
1376
+ return async (input) => {
1377
+ if (input.signal?.aborted) return createConfigurationFailure("GIT_OPERATION_ABORTED");
1378
+ if (!Number.isSafeInteger(input.maxMetadataBytes) || input.maxMetadataBytes < 0) return createConfigurationFailure("RESOURCE_LIMIT_EXCEEDED");
1379
+ const result = await readGit(() => readBoolean(input.repositoryRoot, "core.symlinks", true, {
1380
+ maxOutputBytes: Math.max(input.maxMetadataBytes, 1),
1381
+ timeoutSeconds: 300,
1382
+ ...input.signal === void 0 ? {} : { signal: input.signal }
1383
+ }), input.signal, GIT_CONFIG_SUBCOMMAND);
1384
+ if (result.kind === "failed") return createConfigurationFailure(mapGitFailure$2(result.reason), result.subcommand);
1385
+ const gitMetadataBytes = result.value ? 5 : 6;
1386
+ if (gitMetadataBytes > input.maxMetadataBytes) return createConfigurationFailure("RESOURCE_LIMIT_EXCEEDED");
1387
+ return Object.freeze({
1388
+ gitMetadataBytes,
1389
+ isEnabled: result.value,
1390
+ kind: "resolved"
1391
+ });
1392
+ };
1393
+ };
1394
+ var resolveGitSymlinkConfiguration = createGitSymlinkConfigurationResolver();
1395
+ //#endregion
1396
+ //#region src/git-inventory/entry-type/normalizer.ts
1397
+ var createNormalizationFailure = (errorCode) => Object.freeze({
1398
+ errorCode,
1399
+ kind: "failed"
1400
+ });
1401
+ var hasSymlinkMode = (candidate) => candidate.indexEntries.some(({ mode }) => mode === "120000");
1402
+ var hasRegularFileMode = (candidate) => candidate.indexEntries.some(({ mode }) => mode === "100644" || mode === "100755");
1403
+ var createGitInventoryEntryTypeNormalizer = (entryInspector = inspectGitInventoryEntry, symlinkConfigurationResolver = resolveGitSymlinkConfiguration) => {
1404
+ return async (input) => {
1405
+ if (input.signal?.aborted) return createNormalizationFailure("GIT_OPERATION_ABORTED");
1406
+ if (!Number.isSafeInteger(input.maxMetadataBytes) || input.maxMetadataBytes < 0) return createNormalizationFailure("RESOURCE_LIMIT_EXCEEDED");
1407
+ const collapseResult = collapseGitInventoryCandidates(input.candidates);
1408
+ if (collapseResult.kind === "failed") return createNormalizationFailure("GIT_OUTPUT_INVALID");
1409
+ const entries = [];
1410
+ let symlinkConfiguration = null;
1411
+ for (const candidate of collapseResult.candidates) {
1412
+ if (input.signal?.aborted) return createNormalizationFailure("GIT_OPERATION_ABORTED");
1413
+ const inspectionResult = await entryInspector(input.repositoryRoot, candidate.path);
1414
+ if (input.signal?.aborted) return createNormalizationFailure("GIT_OPERATION_ABORTED");
1415
+ if (inspectionResult.kind === "failed") return inspectionResult;
1416
+ if (inspectionResult.kind === "missing") continue;
1417
+ if (inspectionResult.entryType === "unsupported") return createNormalizationFailure("GIT_OUTPUT_INVALID");
1418
+ if (candidate.kind === "untracked") {
1419
+ entries.push(Object.freeze({
1420
+ entryType: inspectionResult.entryType,
1421
+ kind: "untracked",
1422
+ path: candidate.path,
1423
+ requiresSymlinkOverlay: false
1424
+ }));
1425
+ continue;
1426
+ }
1427
+ if (inspectionResult.entryType === "symlink" || !hasSymlinkMode(candidate)) {
1428
+ entries.push(Object.freeze({
1429
+ entryType: inspectionResult.entryType,
1430
+ indexEntries: candidate.indexEntries,
1431
+ kind: "tracked",
1432
+ path: candidate.path,
1433
+ requiresSymlinkOverlay: false
1434
+ }));
1435
+ continue;
1436
+ }
1437
+ symlinkConfiguration ??= await symlinkConfigurationResolver({
1438
+ maxMetadataBytes: input.maxMetadataBytes,
1439
+ repositoryRoot: input.repositoryRoot,
1440
+ ...input.signal === void 0 ? {} : { signal: input.signal }
1441
+ });
1442
+ if (symlinkConfiguration.kind === "failed") return symlinkConfiguration;
1443
+ if (!Number.isSafeInteger(symlinkConfiguration.gitMetadataBytes) || symlinkConfiguration.gitMetadataBytes < 0 || symlinkConfiguration.gitMetadataBytes > input.maxMetadataBytes) return createNormalizationFailure("GIT_OUTPUT_INVALID");
1444
+ if (!symlinkConfiguration.isEnabled && hasRegularFileMode(candidate)) return createNormalizationFailure("GIT_OUTPUT_INVALID");
1445
+ const requiresSymlinkOverlay = !symlinkConfiguration.isEnabled;
1446
+ entries.push(Object.freeze({
1447
+ entryType: requiresSymlinkOverlay ? "symlink" : "file",
1448
+ indexEntries: candidate.indexEntries,
1449
+ kind: "tracked",
1450
+ path: candidate.path,
1451
+ requiresSymlinkOverlay
1452
+ }));
1453
+ }
1454
+ return Object.freeze({
1455
+ entries: Object.freeze(entries),
1456
+ gitMetadataBytes: symlinkConfiguration?.kind === "resolved" ? symlinkConfiguration.gitMetadataBytes : 0,
1457
+ kind: "normalized"
1458
+ });
1459
+ };
1460
+ };
1461
+ //#endregion
1462
+ //#region src/git-inventory/link-ancestors/shadower.ts
1463
+ var createAbortedFailure = () => Object.freeze({
1464
+ errorCode: "GIT_OPERATION_ABORTED",
1465
+ kind: "failed"
1466
+ });
1467
+ var listProperAncestors = (candidatePath) => {
1468
+ const segments = candidatePath.replace(/\/$/u, "").split("/");
1469
+ return segments.slice(0, -1).map((_segment, index) => segments.slice(0, index + 1).join("/"));
1470
+ };
1471
+ var isBeneathLink = (candidatePath, links) => listProperAncestors(candidatePath).some((ancestor) => links.has(ancestor));
1472
+ var createGitLinkAncestorShadower = (inspectEntry = inspectGitInventoryEntry) => {
1473
+ return async (input) => {
1474
+ if (input.signal?.aborted) return createAbortedFailure();
1475
+ const ancestors = [...new Set(input.candidates.flatMap(({ path }) => listProperAncestors(path)))].sort((left, right) => left.split("/").length - right.split("/").length);
1476
+ const links = new Set();
1477
+ for (const ancestor of ancestors) {
1478
+ if (isBeneathLink(ancestor, links)) continue;
1479
+ const inspection = await inspectEntry(input.repositoryRoot, ancestor);
1480
+ if (input.signal?.aborted) return createAbortedFailure();
1481
+ if (inspection.kind === "failed") return inspection;
1482
+ if (inspection.kind === "inspected" && inspection.entryType === "symlink") links.add(ancestor);
1483
+ }
1484
+ if (links.size === 0) return Object.freeze({
1485
+ candidates: input.candidates,
1486
+ kind: "shadowed"
1487
+ });
1488
+ const remainingCandidates = input.candidates.filter(({ path }) => !isBeneathLink(path, links));
1489
+ const remainingPaths = new Set(remainingCandidates.map(({ path }) => path));
1490
+ const linkCandidates = [...links].filter((link) => !remainingPaths.has(link)).map((link) => Object.freeze({
1491
+ kind: "untracked",
1492
+ path: link
1493
+ }));
1494
+ return Object.freeze({
1495
+ candidates: Object.freeze([...remainingCandidates, ...linkCandidates]),
1496
+ kind: "shadowed"
1497
+ });
1498
+ };
1499
+ };
1500
+ var shadowGitLinkAncestors = createGitLinkAncestorShadower();
1501
+ //#endregion
1502
+ //#region src/git-inventory/logical-path/normalizer.ts
1503
+ var createLogicalPathFailure = () => Object.freeze({
1504
+ errorCode: "GIT_OUTPUT_INVALID",
1505
+ kind: "failed"
1506
+ });
1507
+ var resolveRepositoryPath = (gitPath) => {
1508
+ const logicalPath = `/${gitPath}`;
1509
+ return logicalPath !== "/" && isRepositoryPath(logicalPath) ? logicalPath : null;
1510
+ };
1511
+ var resolveCandidateRepositoryPath = (candidate) => {
1512
+ return resolveRepositoryPath(candidate.kind === "untracked" && candidate.path.endsWith("/") ? candidate.path.slice(0, -1) : candidate.path);
1513
+ };
1514
+ var compareRepositoryPaths = (left, right) => {
1515
+ const leftScalars = left[Symbol.iterator]();
1516
+ const rightScalars = right[Symbol.iterator]();
1517
+ while (true) {
1518
+ const leftScalar = leftScalars.next();
1519
+ const rightScalar = rightScalars.next();
1520
+ if (leftScalar.done === true) return rightScalar.done === true ? 0 : -1;
1521
+ if (rightScalar.done === true) return 1;
1522
+ const leftCodePoint = leftScalar.value.codePointAt(0) ?? 0;
1523
+ const rightCodePoint = rightScalar.value.codePointAt(0) ?? 0;
1524
+ if (leftCodePoint !== rightCodePoint) return leftCodePoint < rightCodePoint ? -1 : 1;
1525
+ }
1526
+ };
1527
+ var filterGitInventoryCandidateLogicalPaths = (input) => {
1528
+ const candidates = [];
1529
+ for (const candidate of input.candidates) {
1530
+ if (resolveCandidateRepositoryPath(candidate) === null) {
1531
+ if (candidate.path === "moldea" || candidate.path.startsWith("moldea/")) return createLogicalPathFailure();
1532
+ continue;
1533
+ }
1534
+ candidates.push(candidate);
1535
+ }
1536
+ return Object.freeze({
1537
+ candidates: Object.freeze(candidates),
1538
+ kind: "filtered"
1539
+ });
1540
+ };
1541
+ var normalizeGitInventoryLogicalPaths = (input) => {
1542
+ const entries = [];
1543
+ const logicalPaths = new Set();
1544
+ for (const entry of input.entries) {
1545
+ const logicalPath = resolveRepositoryPath(entry.path);
1546
+ if (logicalPath === null || logicalPaths.has(logicalPath)) return createLogicalPathFailure();
1547
+ logicalPaths.add(logicalPath);
1548
+ entries.push(Object.freeze({
1549
+ ...entry,
1550
+ path: logicalPath
1551
+ }));
1552
+ }
1553
+ entries.sort((left, right) => compareRepositoryPaths(left.path, right.path));
1554
+ return Object.freeze({
1555
+ entries: Object.freeze(entries),
1556
+ kind: "normalized"
1557
+ });
1558
+ };
1559
+ //#endregion
1560
+ //#region src/git-inventory/parser.ts
1561
+ var decodeGitPath = (pathBytes) => {
1562
+ if (pathBytes.byteLength === 0) return null;
1563
+ try {
1564
+ return new TextDecoder("utf-8", {
1565
+ fatal: true,
1566
+ ignoreBOM: true
1567
+ }).decode(pathBytes);
1568
+ } catch {
1569
+ return null;
1570
+ }
1571
+ };
1572
+ var concatenateRecord = (fragments, byteLength) => {
1573
+ const record = new Uint8Array(byteLength);
1574
+ let offset = 0;
1575
+ for (const fragment of fragments) {
1576
+ record.set(fragment, offset);
1577
+ offset += fragment.byteLength;
1578
+ }
1579
+ return record;
1580
+ };
1581
+ var parseUntrackedCandidate = (record) => {
1582
+ const path = decodeGitPath(record);
1583
+ if (path === null || !path.isWellFormed()) return null;
1584
+ return Object.freeze({
1585
+ kind: "untracked",
1586
+ path
1587
+ });
1588
+ };
1589
+ var createGitInventoryParser = (maxEntries, parseCandidate) => {
1590
+ const candidates = [];
1591
+ let failureReason = null;
1592
+ let pendingByteLength = 0;
1593
+ let pendingFragments = [];
1594
+ const consumeRecord = () => {
1595
+ if (failureReason !== null) return;
1596
+ if (candidates.length >= maxEntries) {
1597
+ failureReason = "entry-limit-exceeded";
1598
+ pendingByteLength = 0;
1599
+ pendingFragments = [];
1600
+ return;
1601
+ }
1602
+ const candidate = parseCandidate(concatenateRecord(pendingFragments, pendingByteLength));
1603
+ pendingByteLength = 0;
1604
+ pendingFragments = [];
1605
+ if (candidate === null) {
1606
+ failureReason = "invalid";
1607
+ return;
1608
+ }
1609
+ candidates.push(candidate);
1610
+ };
1611
+ return {
1612
+ consume: (chunk) => {
1613
+ if (failureReason !== null) return;
1614
+ let fragmentStart = 0;
1615
+ for (let index = 0; index < chunk.byteLength; index += 1) {
1616
+ if (chunk[index] !== 0) continue;
1617
+ const fragment = chunk.subarray(fragmentStart, index);
1618
+ pendingFragments.push(fragment);
1619
+ pendingByteLength += fragment.byteLength;
1620
+ consumeRecord();
1621
+ if (failureReason !== null) return;
1622
+ fragmentStart = index + 1;
1623
+ }
1624
+ const trailingFragment = chunk.subarray(fragmentStart);
1625
+ if (trailingFragment.byteLength > 0) {
1626
+ pendingFragments.push(trailingFragment);
1627
+ pendingByteLength += trailingFragment.byteLength;
1628
+ }
1629
+ },
1630
+ finish: () => {
1631
+ if (failureReason === null && pendingByteLength > 0) failureReason = "invalid";
1632
+ if (failureReason !== null) return Object.freeze({
1633
+ kind: "failed",
1634
+ reason: failureReason
1635
+ });
1636
+ return Object.freeze({
1637
+ candidates: Object.freeze([...candidates]),
1638
+ kind: "completed"
1639
+ });
1640
+ }
1641
+ };
1642
+ };
1643
+ var createUntrackedGitInventoryParser = (maxEntries) => createGitInventoryParser(maxEntries, parseUntrackedCandidate);
1644
+ //#endregion
1645
+ //#region src/git-inventory/repository-ownership/boundary-inspector.ts
1646
+ var GIT_CONTROL_SEGMENT = ".git";
1647
+ var TOP_LEVEL_OUTPUT_OVERHEAD_BYTES = 6;
1648
+ var isInspectionFailure = (result) => "kind" in result;
1649
+ var createInspectionFailure = (errorCode) => Object.freeze({
1650
+ errorCode,
1651
+ kind: "failed"
1652
+ });
1653
+ var mapFilesystemFailure = (error) => {
1654
+ const errorCode = error?.code?.toUpperCase();
1655
+ if (errorCode === "EACCES" || errorCode === "EPERM") return "GIT_ACCESS_DENIED";
1656
+ if (errorCode === "ENOENT" || errorCode === "ENOTDIR" || errorCode === "ELOOP") return "GIT_OUTPUT_INVALID";
1657
+ return "GIT_COMMAND_FAILED";
1658
+ };
1659
+ var mapGitFailure$1 = (reason) => {
1660
+ switch (reason) {
1661
+ case "aborted": return "GIT_OPERATION_ABORTED";
1662
+ case "not-found": return "GIT_NOT_FOUND";
1663
+ case "access-denied": return "GIT_ACCESS_DENIED";
1664
+ case "output-limit-exceeded": return "RESOURCE_LIMIT_EXCEEDED";
1665
+ case "repository-not-found":
1666
+ case "output-invalid": return "GIT_OUTPUT_INVALID";
1667
+ case "command-failed": return "GIT_COMMAND_FAILED";
1668
+ }
1669
+ };
1670
+ var readDirectoryNames = async (hostPath, readDirectory) => {
1671
+ try {
1672
+ const encodedNames = await readDirectory(hostPath);
1673
+ return Object.freeze({
1674
+ encodedNameKeys: new Set(encodedNames.map((encodedName) => encodedName.toString("hex"))),
1675
+ kind: "read"
1676
+ });
1677
+ } catch (error) {
1678
+ return createInspectionFailure(mapFilesystemFailure(error));
1679
+ }
1680
+ };
1681
+ var inspectPath = async (hostPath, inspectHostPath) => {
1682
+ try {
1683
+ return Object.freeze({
1684
+ kind: "inspected",
1685
+ statistics: await inspectHostPath(hostPath)
1686
+ });
1687
+ } catch (error) {
1688
+ return createInspectionFailure(mapFilesystemFailure(error));
1689
+ }
1690
+ };
1691
+ var hasExactDirectoryName = (encodedNameKeys, segment) => encodedNameKeys.has(Buffer$1.from(segment, "utf8").toString("hex"));
1692
+ var hasStableDirectoryIdentity = (initialStatistics, revalidatedStatistics) => initialStatistics.isDirectory() && !initialStatistics.isSymbolicLink() && revalidatedStatistics.isDirectory() && !revalidatedStatistics.isSymbolicLink() && initialStatistics.dev === revalidatedStatistics.dev && initialStatistics.ino === revalidatedStatistics.ino;
1693
+ var validateGitBoundary = async (directory, repositoryRoot, directoryStatistics, maxMetadataBytes, readRoot, inspectHostPath, signal) => {
1694
+ if (signal?.aborted) return createInspectionFailure("GIT_OPERATION_ABORTED");
1695
+ if (!Number.isSafeInteger(maxMetadataBytes) || maxMetadataBytes < 0) return createInspectionFailure("RESOURCE_LIMIT_EXCEEDED");
1696
+ const rootResult = await readGit(() => readRoot(directory, {
1697
+ maxOutputBytes: Math.max(maxMetadataBytes, 1),
1698
+ timeoutSeconds: 300,
1699
+ ...signal === void 0 ? {} : { signal }
1700
+ }), signal);
1701
+ if (rootResult.kind === "failed") return createInspectionFailure(mapGitFailure$1(rootResult.reason));
1702
+ if (rootResult.value === null) return createInspectionFailure("GIT_COMMAND_FAILED");
1703
+ const discoveredRoot = rootResult.value;
1704
+ const gitMetadataBytes = TOP_LEVEL_OUTPUT_OVERHEAD_BYTES + countUtf8Bytes(discoveredRoot);
1705
+ if (gitMetadataBytes > maxMetadataBytes) return createInspectionFailure("RESOURCE_LIMIT_EXCEEDED");
1706
+ if (!path.isAbsolute(discoveredRoot)) return createInspectionFailure("GIT_OUTPUT_INVALID");
1707
+ if (areHostPathsEquivalent(discoveredRoot, directory)) return Object.freeze({
1708
+ gitMetadataBytes,
1709
+ kind: "validated",
1710
+ ownership: "nested-repository"
1711
+ });
1712
+ if (areHostPathsEquivalent(discoveredRoot, repositoryRoot)) return Object.freeze({
1713
+ gitMetadataBytes,
1714
+ kind: "validated",
1715
+ ownership: "selected-repository"
1716
+ });
1717
+ const discoveredRootInspection = await inspectPath(discoveredRoot, inspectHostPath);
1718
+ if (signal?.aborted) return createInspectionFailure("GIT_OPERATION_ABORTED");
1719
+ if (discoveredRootInspection.kind === "failed") return discoveredRootInspection;
1720
+ if (!discoveredRootInspection.statistics.isDirectory() || discoveredRootInspection.statistics.isSymbolicLink()) return createInspectionFailure("GIT_OUTPUT_INVALID");
1721
+ if (haveSameHostPathIdentity(discoveredRootInspection.statistics, directoryStatistics)) return Object.freeze({
1722
+ gitMetadataBytes,
1723
+ kind: "validated",
1724
+ ownership: "nested-repository"
1725
+ });
1726
+ const repositoryRootInspection = await inspectPath(repositoryRoot, inspectHostPath);
1727
+ if (signal?.aborted) return createInspectionFailure("GIT_OPERATION_ABORTED");
1728
+ if (repositoryRootInspection.kind === "failed") return repositoryRootInspection;
1729
+ if (repositoryRootInspection.statistics.isDirectory() && !repositoryRootInspection.statistics.isSymbolicLink() && haveSameHostPathIdentity(discoveredRootInspection.statistics, repositoryRootInspection.statistics)) return Object.freeze({
1730
+ gitMetadataBytes,
1731
+ kind: "validated",
1732
+ ownership: "selected-repository"
1733
+ });
1734
+ return createInspectionFailure("GIT_OUTPUT_INVALID");
1735
+ };
1736
+ var inspectOwnershipPath = async (hostPath) => lstat(hostPath, { bigint: true });
1737
+ var readOwnershipDirectory = async (hostPath) => readdir(hostPath, { encoding: "buffer" });
1738
+ var createGitInventoryBoundaryInspector = (readRoot = readTopLevel, inspectHostPath = inspectOwnershipPath, readDirectory = readOwnershipDirectory) => {
1739
+ return async (input) => {
1740
+ if (input.signal?.aborted) return createInspectionFailure("GIT_OPERATION_ABORTED");
1741
+ const directoryObservations = new Map();
1742
+ const ownership = [];
1743
+ let gitMetadataBytes = 0;
1744
+ let rootEncodedNameKeys = null;
1745
+ const getRootEncodedNames = async () => {
1746
+ if (input.signal?.aborted) return createInspectionFailure("GIT_OPERATION_ABORTED");
1747
+ if (rootEncodedNameKeys !== null) return Object.freeze({
1748
+ encodedNameKeys: rootEncodedNameKeys,
1749
+ kind: "read"
1750
+ });
1751
+ const readResult = await readDirectoryNames(input.repositoryRoot, readDirectory);
1752
+ if (input.signal?.aborted) return createInspectionFailure("GIT_OPERATION_ABORTED");
1753
+ if (readResult.kind === "read") rootEncodedNameKeys = readResult.encodedNameKeys;
1754
+ return readResult;
1755
+ };
1756
+ const inspectDirectory = async (parentObservation, parentPrefix, segment) => {
1757
+ if (input.signal?.aborted) return createInspectionFailure("GIT_OPERATION_ABORTED");
1758
+ const prefix = parentPrefix.length === 0 ? segment : `${parentPrefix}/${segment}`;
1759
+ const cachedObservation = directoryObservations.get(prefix);
1760
+ if (cachedObservation !== void 0) return cachedObservation;
1761
+ const parentNamesResult = parentObservation === null ? await getRootEncodedNames() : Object.freeze({
1762
+ encodedNameKeys: parentObservation.encodedNameKeys,
1763
+ kind: "read"
1764
+ });
1765
+ if (parentNamesResult.kind === "failed") return parentNamesResult;
1766
+ if (!hasExactDirectoryName(parentNamesResult.encodedNameKeys, segment)) return createInspectionFailure("GIT_OUTPUT_INVALID");
1767
+ const parentHostPath = parentObservation?.hostPath ?? input.repositoryRoot;
1768
+ const hostPath = path.join(parentHostPath, segment);
1769
+ const initialInspection = await inspectPath(hostPath, inspectHostPath);
1770
+ if (input.signal?.aborted) return createInspectionFailure("GIT_OPERATION_ABORTED");
1771
+ if (initialInspection.kind === "failed") return initialInspection;
1772
+ if (!initialInspection.statistics.isDirectory() || initialInspection.statistics.isSymbolicLink()) return createInspectionFailure("GIT_OUTPUT_INVALID");
1773
+ const directoryNamesResult = await readDirectoryNames(hostPath, readDirectory);
1774
+ if (input.signal?.aborted) return createInspectionFailure("GIT_OPERATION_ABORTED");
1775
+ if (directoryNamesResult.kind === "failed") return directoryNamesResult;
1776
+ const revalidatedInspection = await inspectPath(hostPath, inspectHostPath);
1777
+ if (input.signal?.aborted) return createInspectionFailure("GIT_OPERATION_ABORTED");
1778
+ if (revalidatedInspection.kind === "failed") return revalidatedInspection;
1779
+ if (!hasStableDirectoryIdentity(initialInspection.statistics, revalidatedInspection.statistics)) return createInspectionFailure("GIT_OUTPUT_INVALID");
1780
+ const gitControlPath = path.join(hostPath, GIT_CONTROL_SEGMENT);
1781
+ const hasExactGitControlSegment = hasExactDirectoryName(directoryNamesResult.encodedNameKeys, GIT_CONTROL_SEGMENT);
1782
+ let directoryOwnership = "selected-repository";
1783
+ if (!hasExactGitControlSegment) try {
1784
+ await inspectHostPath(gitControlPath);
1785
+ if (input.signal?.aborted) return createInspectionFailure("GIT_OPERATION_ABORTED");
1786
+ return createInspectionFailure("GIT_OUTPUT_INVALID");
1787
+ } catch (error) {
1788
+ const errorCode = error?.code?.toUpperCase();
1789
+ if (errorCode !== "ENOENT" && errorCode !== "ENOTDIR") return createInspectionFailure(mapFilesystemFailure(error));
1790
+ }
1791
+ else {
1792
+ const gitControlInspection = await inspectPath(gitControlPath, inspectHostPath);
1793
+ if (input.signal?.aborted) return createInspectionFailure("GIT_OPERATION_ABORTED");
1794
+ if (gitControlInspection.kind === "failed") return gitControlInspection;
1795
+ if (gitControlInspection.statistics.isSymbolicLink() || !gitControlInspection.statistics.isDirectory() && !gitControlInspection.statistics.isFile()) return createInspectionFailure("GIT_OUTPUT_INVALID");
1796
+ const boundaryValidation = await validateGitBoundary(hostPath, input.repositoryRoot, revalidatedInspection.statistics, input.maxMetadataBytes - gitMetadataBytes, readRoot, inspectHostPath, input.signal);
1797
+ if (boundaryValidation.kind === "failed") return boundaryValidation;
1798
+ gitMetadataBytes += boundaryValidation.gitMetadataBytes;
1799
+ directoryOwnership = boundaryValidation.ownership;
1800
+ }
1801
+ const observation = Object.freeze({
1802
+ encodedNameKeys: directoryNamesResult.encodedNameKeys,
1803
+ hostPath,
1804
+ ownership: directoryOwnership
1805
+ });
1806
+ directoryObservations.set(prefix, observation);
1807
+ return observation;
1808
+ };
1809
+ for (const plan of input.plans) {
1810
+ if (input.signal?.aborted) return createInspectionFailure("GIT_OPERATION_ABORTED");
1811
+ let candidateOwnership = "selected-repository";
1812
+ let parentObservation = null;
1813
+ let parentPrefix = "";
1814
+ for (const segment of plan.directorySegments) {
1815
+ if (input.signal?.aborted) return createInspectionFailure("GIT_OPERATION_ABORTED");
1816
+ const observation = await inspectDirectory(parentObservation, parentPrefix, segment);
1817
+ if (isInspectionFailure(observation)) return observation;
1818
+ parentObservation = observation;
1819
+ parentPrefix = parentPrefix.length === 0 ? segment : `${parentPrefix}/${segment}`;
1820
+ if (observation.ownership === "nested-repository") {
1821
+ candidateOwnership = "nested-repository";
1822
+ break;
1823
+ }
1824
+ }
1825
+ if (plan.isDirectoryRecord && candidateOwnership !== "nested-repository") return createInspectionFailure("GIT_OUTPUT_INVALID");
1826
+ ownership.push(candidateOwnership);
1827
+ }
1828
+ return Object.freeze({
1829
+ gitMetadataBytes,
1830
+ kind: "inspected",
1831
+ ownership: Object.freeze([...ownership])
1832
+ });
1833
+ };
1834
+ };
1835
+ var inspectGitInventoryBoundaries = createGitInventoryBoundaryInspector();
1836
+ //#endregion
1837
+ //#region src/git-inventory/repository-ownership/path-planner.ts
1838
+ var planGitInventoryOwnershipPath = (candidate) => {
1839
+ const isDirectoryRecord = candidate.path.endsWith("/");
1840
+ if (candidate.path.length === 0 || candidate.path.startsWith("/") || candidate.path.includes("\\") || candidate.kind === "tracked" && isDirectoryRecord) return Object.freeze({ kind: "failed" });
1841
+ const segments = (isDirectoryRecord ? candidate.path.slice(0, -1) : candidate.path).split("/");
1842
+ if (segments.length === 0 || segments.some((segment) => segment.length === 0 || segment === "." || segment === "..")) return Object.freeze({ kind: "failed" });
1843
+ const frozenSegments = Object.freeze([...segments]);
1844
+ const directorySegments = Object.freeze(isDirectoryRecord ? [...segments] : segments.slice(0, -1));
1845
+ return Object.freeze({
1846
+ kind: "planned",
1847
+ plan: Object.freeze({
1848
+ candidate,
1849
+ directorySegments,
1850
+ hasGitControlSegment: segments.includes(".git"),
1851
+ isDirectoryRecord,
1852
+ segments: frozenSegments
1853
+ })
1854
+ });
1855
+ };
1856
+ //#endregion
1857
+ //#region src/git-inventory/repository-ownership/ownership-filter.ts
1858
+ var createOwnershipFailure = (errorCode = "GIT_OUTPUT_INVALID") => Object.freeze({
1859
+ errorCode,
1860
+ kind: "failed"
1861
+ });
1862
+ var createGitlinkTrie = (rootSegments) => {
1863
+ const trie = {
1864
+ children: new Map(),
1865
+ isRoot: false
1866
+ };
1867
+ for (const segments of rootSegments) {
1868
+ let node = trie;
1869
+ for (const segment of segments) {
1870
+ let childNode = node.children.get(segment);
1871
+ if (childNode === void 0) {
1872
+ childNode = {
1873
+ children: new Map(),
1874
+ isRoot: false
1875
+ };
1876
+ node.children.set(segment, childNode);
1877
+ }
1878
+ node = childNode;
1879
+ }
1880
+ node.isRoot = true;
1881
+ }
1882
+ return trie;
1883
+ };
1884
+ var isAtOrBelowGitlink = (candidateSegments, gitlinkTrie) => {
1885
+ let node = gitlinkTrie;
1886
+ for (const segment of candidateSegments) {
1887
+ const childNode = node.children.get(segment);
1888
+ if (childNode === void 0) return false;
1889
+ if (childNode.isRoot) return true;
1890
+ node = childNode;
1891
+ }
1892
+ return false;
1893
+ };
1894
+ var createGitInventoryOwnershipFilter = (boundaryInspector = inspectGitInventoryBoundaries) => {
1895
+ return async (input) => {
1896
+ const plannedCandidates = [];
1897
+ for (const [candidateIndex, candidate] of input.candidates.entries()) {
1898
+ if (input.signal?.aborted) return createOwnershipFailure("GIT_OPERATION_ABORTED");
1899
+ const planResult = planGitInventoryOwnershipPath(candidate);
1900
+ if (planResult.kind === "failed") return createOwnershipFailure();
1901
+ plannedCandidates.push({
1902
+ candidateIndex,
1903
+ plan: planResult.plan
1904
+ });
1905
+ }
1906
+ const gitlinkTrie = createGitlinkTrie(plannedCandidates.filter(({ plan }) => !plan.hasGitControlSegment && plan.candidate.kind === "tracked" && plan.candidate.mode === "160000").map(({ plan }) => plan.segments));
1907
+ const includedCandidates = Array.from({ length: input.candidates.length }, () => false);
1908
+ const untrackedPlans = [];
1909
+ for (const { candidateIndex, plan } of plannedCandidates) {
1910
+ if (plan.hasGitControlSegment || isAtOrBelowGitlink(plan.segments, gitlinkTrie)) continue;
1911
+ if (plan.candidate.kind === "tracked") {
1912
+ includedCandidates[candidateIndex] = true;
1913
+ continue;
1914
+ }
1915
+ untrackedPlans.push({
1916
+ candidate: plan.candidate,
1917
+ candidateIndex,
1918
+ plan
1919
+ });
1920
+ }
1921
+ const boundaryResult = await boundaryInspector({
1922
+ maxMetadataBytes: input.maxMetadataBytes,
1923
+ plans: untrackedPlans.map(({ plan }) => plan),
1924
+ repositoryRoot: input.repositoryRoot,
1925
+ ...input.signal === void 0 ? {} : { signal: input.signal }
1926
+ });
1927
+ if (boundaryResult.kind === "failed") return boundaryResult;
1928
+ if (boundaryResult.ownership.length !== untrackedPlans.length) return createOwnershipFailure();
1929
+ for (const [ownershipIndex, ownership] of boundaryResult.ownership.entries()) {
1930
+ if (input.signal?.aborted) return createOwnershipFailure("GIT_OPERATION_ABORTED");
1931
+ const untrackedPlan = untrackedPlans[ownershipIndex];
1932
+ if (untrackedPlan === void 0) return createOwnershipFailure();
1933
+ if (ownership === "selected-repository") includedCandidates[untrackedPlan.candidateIndex] = true;
1934
+ }
1935
+ const candidates = input.candidates.filter((_candidate, candidateIndex) => includedCandidates[candidateIndex] === true);
1936
+ return Object.freeze({
1937
+ candidates: Object.freeze(candidates),
1938
+ gitMetadataBytes: boundaryResult.gitMetadataBytes,
1939
+ kind: "filtered"
1940
+ });
1941
+ };
1942
+ };
1943
+ //#endregion
1944
+ //#region src/git-inventory/probe.ts
1945
+ var GIT_INVENTORY_LISTING_READS = Object.freeze({
1946
+ listUntrackedFiles,
1947
+ readIndexEntries,
1948
+ runGit: runGitCommand
1949
+ });
1950
+ var mapGitFailure = (reason) => {
1951
+ switch (reason) {
1952
+ case "aborted": return "GIT_OPERATION_ABORTED";
1953
+ case "not-found": return "GIT_NOT_FOUND";
1954
+ case "repository-not-found": return "GIT_REPOSITORY_NOT_FOUND";
1955
+ case "access-denied": return "GIT_ACCESS_DENIED";
1956
+ case "output-invalid": return "GIT_OUTPUT_INVALID";
1957
+ case "output-limit-exceeded": return "RESOURCE_LIMIT_EXCEEDED";
1958
+ case "command-failed": return "GIT_COMMAND_FAILED";
1959
+ }
1960
+ };
1961
+ var isTrackedEntryMode = (mode) => GIT_TRACKED_ENTRY_MODES.includes(mode);
1962
+ var toTrackedCandidates = (entries) => {
1963
+ const candidates = [];
1964
+ for (const { mode, path, stage } of entries) {
1965
+ if (!isTrackedEntryMode(mode)) return null;
1966
+ candidates.push(Object.freeze({
1967
+ kind: "tracked",
1968
+ mode,
1969
+ path,
1970
+ stage
1971
+ }));
1972
+ }
1973
+ return Object.freeze(candidates);
1974
+ };
1975
+ var measureTrackedOutput = (entries) => entries.reduce((bytes, { path }) => bytes + 75 + countUtf8Bytes(path), 0);
1976
+ var measureUntrackedOutput = (paths) => paths.reduce((bytes, path) => bytes + countUtf8Bytes(path) + 1, 0);
1977
+ var createProbeFailure = (errorCode, subcommand) => Object.freeze({
1978
+ errorCode,
1979
+ kind: "failed",
1980
+ ...subcommand === void 0 ? {} : { subcommand }
1981
+ });
1982
+ var resolveParserResult = (parserResult) => {
1983
+ if (parserResult.kind === "completed") return parserResult.candidates;
1984
+ return createProbeFailure(parserResult.reason === "entry-limit-exceeded" ? "RESOURCE_LIMIT_EXCEEDED" : "GIT_OUTPUT_INVALID");
1985
+ };
1986
+ var isProbeFailure = (result) => !Array.isArray(result);
1987
+ var createGitInventoryProbe = (git = GIT_INVENTORY_LISTING_READS, ownershipFilter = createGitInventoryOwnershipFilter(createGitInventoryBoundaryInspector()), entryTypeNormalizer = createGitInventoryEntryTypeNormalizer(inspectGitInventoryEntry, createGitSymlinkConfigurationResolver()), contentTransformationClassifier = createGitContentTransformationClassifier(), logicalPathNormalizer = normalizeGitInventoryLogicalPaths, linkAncestorShadower = shadowGitLinkAncestors) => async (input) => {
1988
+ if (input.signal?.aborted) return createProbeFailure("GIT_OPERATION_ABORTED");
1989
+ const selectionPaths = (input.selectionPaths ?? []).map((selectionPath) => selectionPath.slice(1));
1990
+ let remainingMetadataBytes = input.maxMetadataBytes;
1991
+ const createReadOptions = () => ({
1992
+ maxOutputBytes: Math.max(remainingMetadataBytes, 1),
1993
+ timeoutSeconds: 300,
1994
+ ...selectionPaths.length === 0 ? {} : { paths: selectionPaths },
1995
+ ...input.signal === void 0 ? {} : { signal: input.signal }
1996
+ });
1997
+ const trackedResult = await readGit(() => git.readIndexEntries(input.repositoryRoot, createReadOptions()), input.signal, GIT_INVENTORY_LISTING_SUBCOMMAND);
1998
+ if (trackedResult.kind === "failed") return createProbeFailure(mapGitFailure(trackedResult.reason), trackedResult.subcommand);
1999
+ remainingMetadataBytes -= measureTrackedOutput(trackedResult.value);
2000
+ if (trackedResult.value.length > input.maxEntries || remainingMetadataBytes < 0) return createProbeFailure("RESOURCE_LIMIT_EXCEEDED");
2001
+ const trackedCandidates = toTrackedCandidates(trackedResult.value);
2002
+ if (trackedCandidates === null) return createProbeFailure("GIT_OUTPUT_INVALID");
2003
+ const untrackedResult = await readGit(() => git.listUntrackedFiles(input.repositoryRoot, createReadOptions()), input.signal, GIT_INVENTORY_LISTING_SUBCOMMAND);
2004
+ if (untrackedResult.kind === "failed") return createProbeFailure(mapGitFailure(untrackedResult.reason), untrackedResult.subcommand);
2005
+ remainingMetadataBytes -= measureUntrackedOutput(untrackedResult.value);
2006
+ if (trackedCandidates.length + untrackedResult.value.length > input.maxEntries || remainingMetadataBytes < 0) return createProbeFailure("RESOURCE_LIMIT_EXCEEDED");
2007
+ if (untrackedResult.value.some((path) => path.length === 0)) return createProbeFailure("GIT_OUTPUT_INVALID");
2008
+ const untrackedCandidates = Object.freeze(untrackedResult.value.map((path) => Object.freeze({
2009
+ kind: "untracked",
2010
+ path
2011
+ })));
2012
+ let ignoredCandidates = [];
2013
+ if (input.includeIgnored === true && selectionPaths.length > 0) {
2014
+ const ignoredResult = await git.runGit([...GIT_IGNORED_INVENTORY_ARGUMENTS, ...selectionPaths], {
2015
+ cwd: input.repositoryRoot,
2016
+ maxOutputBytes: Math.max(remainingMetadataBytes, 1),
2017
+ ...input.signal === void 0 ? {} : { signal: input.signal }
2018
+ });
2019
+ if (ignoredResult.kind === "failed") return createProbeFailure(mapGitFailure(ignoredResult.reason), ignoredResult.subcommand);
2020
+ remainingMetadataBytes -= ignoredResult.value.byteLength;
2021
+ if (remainingMetadataBytes < 0) return createProbeFailure("RESOURCE_LIMIT_EXCEEDED");
2022
+ const ignoredParser = createUntrackedGitInventoryParser(input.maxEntries - trackedCandidates.length - untrackedCandidates.length);
2023
+ ignoredParser.consume(ignoredResult.value);
2024
+ const parsedIgnoredCandidates = resolveParserResult(ignoredParser.finish());
2025
+ if (isProbeFailure(parsedIgnoredCandidates)) return parsedIgnoredCandidates;
2026
+ const untrackedPaths = new Set(untrackedCandidates.map((candidate) => candidate.path));
2027
+ ignoredCandidates = parsedIgnoredCandidates.filter((candidate) => !untrackedPaths.has(candidate.path));
2028
+ }
2029
+ const logicalPathFilterResult = filterGitInventoryCandidateLogicalPaths({ candidates: Object.freeze([
2030
+ ...trackedCandidates,
2031
+ ...untrackedCandidates,
2032
+ ...ignoredCandidates
2033
+ ]) });
2034
+ if (logicalPathFilterResult.kind === "failed") return logicalPathFilterResult;
2035
+ const shadowResult = await linkAncestorShadower({
2036
+ candidates: logicalPathFilterResult.candidates,
2037
+ repositoryRoot: input.repositoryRoot,
2038
+ ...input.signal === void 0 ? {} : { signal: input.signal }
2039
+ });
2040
+ if (shadowResult.kind === "failed") return shadowResult;
2041
+ const ownershipResult = await ownershipFilter({
2042
+ candidates: shadowResult.candidates,
2043
+ maxMetadataBytes: remainingMetadataBytes,
2044
+ repositoryRoot: input.repositoryRoot,
2045
+ ...input.signal === void 0 ? {} : { signal: input.signal }
2046
+ });
2047
+ if (ownershipResult.kind === "failed") return ownershipResult;
2048
+ const entryTypeResult = await entryTypeNormalizer({
2049
+ candidates: ownershipResult.candidates,
2050
+ maxMetadataBytes: remainingMetadataBytes - ownershipResult.gitMetadataBytes,
2051
+ repositoryRoot: input.repositoryRoot,
2052
+ ...input.signal === void 0 ? {} : { signal: input.signal }
2053
+ });
2054
+ if (entryTypeResult.kind === "failed") return entryTypeResult;
2055
+ const contentTransformationResult = await contentTransformationClassifier({
2056
+ entries: entryTypeResult.entries,
2057
+ maxMetadataBytes: remainingMetadataBytes - ownershipResult.gitMetadataBytes - entryTypeResult.gitMetadataBytes,
2058
+ repositoryRoot: input.repositoryRoot,
2059
+ ...input.signal === void 0 ? {} : { signal: input.signal }
2060
+ });
2061
+ if (contentTransformationResult.kind === "failed") return contentTransformationResult;
2062
+ const logicalPathResult = logicalPathNormalizer({ entries: contentTransformationResult.entries });
2063
+ if (logicalPathResult.kind === "failed") return logicalPathResult;
2064
+ return Object.freeze({
2065
+ entries: logicalPathResult.entries,
2066
+ kind: "probed"
2067
+ });
2068
+ };
2069
+ var probeGitInventory = createGitInventoryProbe();
2070
+ //#endregion
2071
+ //#region src/git-inventory/comparison/comparator.ts
2072
+ var areContentTransformationsEqual = (left, right) => left.filter === right.filter && left.ident === right.ident && left.isGuarded === right.isGuarded && left.workingTreeEncoding === right.workingTreeEncoding;
2073
+ var areIndexEntriesEqual = (left, right) => left.length === right.length && left.every((leftEntry, index) => leftEntry.mode === right[index]?.mode && leftEntry.stage === right[index]?.stage);
2074
+ var areInventoryEntriesEqual = (left, right) => {
2075
+ if (left.kind !== right.kind || left.path !== right.path || left.entryType !== right.entryType || left.requiresSymlinkOverlay !== right.requiresSymlinkOverlay || !areContentTransformationsEqual(left.contentTransformation, right.contentTransformation)) return false;
2076
+ if (left.kind === "untracked" || right.kind === "untracked") return left.kind === right.kind;
2077
+ return areIndexEntriesEqual(left.indexEntries, right.indexEntries);
2078
+ };
2079
+ var areGitInventoriesEqual = (left, right) => left.length === right.length && left.every((leftEntry, index) => {
2080
+ const rightEntry = right[index];
2081
+ return rightEntry !== void 0 && areInventoryEntriesEqual(leftEntry, rightEntry);
2082
+ });
2083
+ //#endregion
2084
+ //#region ../repository-fs/dist/index.js
2085
+ var DEFAULT_FILESYSTEM_REPOSITORY_RESOURCE_LIMITS = Object.freeze({
2086
+ maxCachedBytes: 67108864,
2087
+ maxConcurrentOperations: 16,
2088
+ maxDirectoryEntries: 131072,
2089
+ maxEntries: 131072,
2090
+ maxPageEntries: 4096,
2091
+ maxQueuedOperations: 256,
2092
+ maxReadBytes: 1048576
2093
+ });
2094
+ var isAbsoluteHostRootDirectory = (candidate) => {
2095
+ return typeof candidate === "string" && candidate.length > 0 && !candidate.includes("\0") && candidate.isWellFormed() && path.isAbsolute(candidate);
2096
+ };
2097
+ var OPTION_PROPERTY_NAMES = new Set([
2098
+ "limits",
2099
+ "rootDirectory",
2100
+ "selection",
2101
+ "signal"
2102
+ ]);
2103
+ var DIRECTORY_SELECTION_PROPERTY_NAMES = new Set(["kind"]);
2104
+ var PATH_SELECTION_PROPERTY_NAMES = new Set(["kind", "paths"]);
2105
+ var LIMIT_PROPERTY_NAMES = [
2106
+ "maxCachedBytes",
2107
+ "maxConcurrentOperations",
2108
+ "maxDirectoryEntries",
2109
+ "maxEntries",
2110
+ "maxPageEntries",
2111
+ "maxQueuedOperations",
2112
+ "maxReadBytes"
2113
+ ];
2114
+ var LIMIT_PROPERTY_NAME_SET = new Set(LIMIT_PROPERTY_NAMES);
2115
+ var throwInvalidSourceData = (path = null) => {
2116
+ throw new RepositorySourceException({
2117
+ code: "INVALID_SOURCE_DATA",
2118
+ operation: "create-reader",
2119
+ path,
2120
+ retryable: false
2121
+ });
2122
+ };
2123
+ var isArray = (candidate) => {
2124
+ try {
2125
+ return Array.isArray(candidate);
2126
+ } catch {
2127
+ return throwInvalidSourceData();
2128
+ }
2129
+ };
2130
+ var isUnknownRecord = (candidate) => {
2131
+ return typeof candidate === "object" && candidate !== null && !isArray(candidate);
2132
+ };
2133
+ var hasExactOwnProperties = (candidate, allowedPropertyNames) => {
2134
+ try {
2135
+ return Reflect.ownKeys(candidate).every((propertyName) => typeof propertyName === "string" && allowedPropertyNames.has(propertyName));
2136
+ } catch {
2137
+ return throwInvalidSourceData();
2138
+ }
2139
+ };
2140
+ var hasOwnProperty = (candidate, propertyName) => {
2141
+ try {
2142
+ return Object.hasOwn(candidate, propertyName);
2143
+ } catch {
2144
+ return throwInvalidSourceData();
2145
+ }
2146
+ };
2147
+ var readOwnProperty = (candidate, propertyName) => {
2148
+ try {
2149
+ return Reflect.get(candidate, propertyName);
2150
+ } catch {
2151
+ return throwInvalidSourceData();
2152
+ }
2153
+ };
2154
+ var parseSelectedPath = (candidate) => {
2155
+ if (typeof candidate !== "string") throw new RepositoryPathException();
2156
+ return parseRepositoryPath(candidate);
2157
+ };
2158
+ var normalizePathSelection = (selection) => {
2159
+ if (!hasExactOwnProperties(selection, PATH_SELECTION_PROPERTY_NAMES) || !hasOwnProperty(selection, "paths")) return throwInvalidSourceData();
2160
+ const pathCandidates = readOwnProperty(selection, "paths");
2161
+ if (!isArray(pathCandidates)) return throwInvalidSourceData();
2162
+ const pathCount = readOwnProperty(pathCandidates, "length");
2163
+ if (typeof pathCount !== "number" || !Number.isSafeInteger(pathCount) || pathCount < 0) return throwInvalidSourceData();
2164
+ const paths = [];
2165
+ for (let index = 0; index < pathCount; index += 1) {
2166
+ const propertyName = String(index);
2167
+ if (!hasOwnProperty(pathCandidates, propertyName)) return throwInvalidSourceData();
2168
+ paths.push(parseSelectedPath(readOwnProperty(pathCandidates, propertyName)));
2169
+ }
2170
+ const uniquePaths = new Set();
2171
+ for (const selectedPath of paths) {
2172
+ if (selectedPath === REPOSITORY_ROOT || uniquePaths.has(selectedPath)) return throwInvalidSourceData();
2173
+ uniquePaths.add(selectedPath);
2174
+ }
2175
+ paths.sort();
2176
+ return Object.freeze({
2177
+ kind: "paths",
2178
+ paths: Object.freeze(paths)
2179
+ });
2180
+ };
2181
+ var normalizeSelection = (candidate) => {
2182
+ if (!isUnknownRecord(candidate) || !hasOwnProperty(candidate, "kind")) return throwInvalidSourceData();
2183
+ const kind = readOwnProperty(candidate, "kind");
2184
+ if (kind === "directory") {
2185
+ if (!hasExactOwnProperties(candidate, DIRECTORY_SELECTION_PROPERTY_NAMES)) return throwInvalidSourceData();
2186
+ return Object.freeze({ kind: "directory" });
2187
+ }
2188
+ if (kind === "paths") return normalizePathSelection(candidate);
2189
+ return throwInvalidSourceData();
2190
+ };
2191
+ var isPositiveSafeInteger = (candidate) => {
2192
+ return typeof candidate === "number" && Number.isSafeInteger(candidate) && candidate > 0;
2193
+ };
2194
+ var normalizeLimits = (candidate) => {
2195
+ if (candidate === void 0) return DEFAULT_FILESYSTEM_REPOSITORY_RESOURCE_LIMITS;
2196
+ if (!isUnknownRecord(candidate) || !hasExactOwnProperties(candidate, LIMIT_PROPERTY_NAME_SET)) return throwInvalidSourceData();
2197
+ const limits = {
2198
+ maxCachedBytes: DEFAULT_FILESYSTEM_REPOSITORY_RESOURCE_LIMITS.maxCachedBytes,
2199
+ maxConcurrentOperations: DEFAULT_FILESYSTEM_REPOSITORY_RESOURCE_LIMITS.maxConcurrentOperations,
2200
+ maxDirectoryEntries: DEFAULT_FILESYSTEM_REPOSITORY_RESOURCE_LIMITS.maxDirectoryEntries,
2201
+ maxEntries: DEFAULT_FILESYSTEM_REPOSITORY_RESOURCE_LIMITS.maxEntries,
2202
+ maxPageEntries: DEFAULT_FILESYSTEM_REPOSITORY_RESOURCE_LIMITS.maxPageEntries,
2203
+ maxQueuedOperations: DEFAULT_FILESYSTEM_REPOSITORY_RESOURCE_LIMITS.maxQueuedOperations,
2204
+ maxReadBytes: DEFAULT_FILESYSTEM_REPOSITORY_RESOURCE_LIMITS.maxReadBytes
2205
+ };
2206
+ for (const propertyName of LIMIT_PROPERTY_NAMES) {
2207
+ if (!hasOwnProperty(candidate, propertyName)) continue;
2208
+ const configuredLimit = readOwnProperty(candidate, propertyName);
2209
+ if (!isPositiveSafeInteger(configuredLimit)) return throwInvalidSourceData();
2210
+ limits[propertyName] = configuredLimit;
2211
+ }
2212
+ return Object.freeze(limits);
2213
+ };
2214
+ var normalizeSignal = (candidate) => {
2215
+ try {
2216
+ if (candidate === void 0 || candidate instanceof AbortSignal) return candidate;
2217
+ } catch {
2218
+ return throwInvalidSourceData();
2219
+ }
2220
+ return throwInvalidSourceData();
2221
+ };
2222
+ var normalizeFilesystemRepositoryOptions = (candidate) => {
2223
+ let normalizedOptions;
2224
+ try {
2225
+ if (!isUnknownRecord(candidate) || !hasExactOwnProperties(candidate, OPTION_PROPERTY_NAMES) || !hasOwnProperty(candidate, "rootDirectory") || !hasOwnProperty(candidate, "selection")) return throwInvalidSourceData();
2226
+ const rootDirectory = readOwnProperty(candidate, "rootDirectory");
2227
+ const selection = readOwnProperty(candidate, "selection");
2228
+ const limits = hasOwnProperty(candidate, "limits") ? readOwnProperty(candidate, "limits") : void 0;
2229
+ const signal = hasOwnProperty(candidate, "signal") ? readOwnProperty(candidate, "signal") : void 0;
2230
+ if (!isAbsoluteHostRootDirectory(rootDirectory)) return throwInvalidSourceData();
2231
+ normalizedOptions = {
2232
+ limits: normalizeLimits(limits),
2233
+ rootDirectory,
2234
+ selection: normalizeSelection(selection),
2235
+ signal: normalizeSignal(signal)
2236
+ };
2237
+ } catch (cause) {
2238
+ if (cause instanceof RepositoryPathException) throw cause;
2239
+ return throwInvalidSourceData();
2240
+ }
2241
+ if (normalizedOptions.selection.kind === "paths") {
2242
+ for (const selectedPath of normalizedOptions.selection.paths) if (selectedPath.slice(1).split("/").includes(".git")) return throwInvalidSourceData(selectedPath);
2243
+ }
2244
+ return Object.freeze(normalizedOptions);
2245
+ };
2246
+ var decoder$1 = new TextDecoder$1("utf-8", {
2247
+ fatal: true,
2248
+ ignoreBOM: true
2249
+ });
2250
+ var MAX_CURSOR_BYTES = 65536;
2251
+ var DIRECTORY_CURSOR_KEYS = new Set([
2252
+ "frames",
2253
+ "kind",
2254
+ "prefix",
2255
+ "snapshotId",
2256
+ "version"
2257
+ ]);
2258
+ var CURSOR_FRAME_KEYS = new Set([
2259
+ "lastName",
2260
+ "namesIdentity",
2261
+ "path",
2262
+ "pathIdentity"
2263
+ ]);
2264
+ var PATH_CURSOR_KEYS = new Set([
2265
+ "kind",
2266
+ "lastPath",
2267
+ "prefix",
2268
+ "snapshotId",
2269
+ "version"
2270
+ ]);
2271
+ var hasOnlyKeys = (record, keys) => Reflect.ownKeys(record).every((key) => typeof key === "string" && keys.has(key));
2272
+ var hashParts = (parts) => {
2273
+ const hash = createHash("sha256");
2274
+ for (const part of parts) {
2275
+ hash.update(part);
2276
+ hash.update("\0");
2277
+ }
2278
+ return `sha256:${hash.digest("hex")}`;
2279
+ };
2280
+ var getErrorCode = (cause) => {
2281
+ if (typeof cause !== "object" || cause === null || !("code" in cause)) return;
2282
+ const code = cause.code;
2283
+ return typeof code === "string" ? code : void 0;
2284
+ };
2285
+ var throwSource = (code, operation, logicalPath, retryable, cause, resource) => {
2286
+ throw new RepositorySourceException({
2287
+ cause,
2288
+ code,
2289
+ operation,
2290
+ path: logicalPath,
2291
+ ...resource === void 0 ? {} : { resource },
2292
+ retryable
2293
+ });
2294
+ };
2295
+ var throwMappedHostError = (cause, operation, logicalPath) => {
2296
+ const code = getErrorCode(cause);
2297
+ if (code === "EACCES" || code === "EPERM") return throwSource("ACCESS_DENIED", operation, logicalPath, true, cause);
2298
+ if (operation !== "create-reader" && (code === "ENOENT" || code === "ENOTDIR" || code === "ELOOP")) return throwSource("SNAPSHOT_CHANGED", operation, logicalPath, true, cause);
2299
+ if (operation === "create-reader" && (code === "ENOENT" || code === "ENOTDIR")) return throwSource("ENTRY_NOT_FOUND", operation, logicalPath, true, cause);
2300
+ return throwSource("SOURCE_UNAVAILABLE", operation, logicalPath, true, cause);
2301
+ };
2302
+ var throwIfAborted$1 = (signal, operation, logicalPath) => {
2303
+ if (signal?.aborted) throwSource("ABORTED", operation, logicalPath, false, signal.reason);
2304
+ };
2305
+ var getStatisticsIdentity = (statistics, type) => {
2306
+ return hashParts([
2307
+ type,
2308
+ statistics.dev.toString(),
2309
+ statistics.ino.toString(),
2310
+ statistics.mode.toString(),
2311
+ statistics.size.toString(),
2312
+ statistics.mtimeNs.toString(),
2313
+ statistics.ctimeNs.toString()
2314
+ ]);
2315
+ };
2316
+ var classifyStatistics = (statistics, operation, logicalPath) => {
2317
+ if (statistics.isFile()) return "file";
2318
+ if (statistics.isDirectory()) return "directory";
2319
+ if (statistics.isSymbolicLink()) return "symlink";
2320
+ return throwSource("INVALID_SOURCE_DATA", operation, logicalPath, false);
2321
+ };
2322
+ var decodeName = (encodedName, operation, parentPath) => {
2323
+ try {
2324
+ const name = decoder$1.decode(encodedName);
2325
+ parseRepositoryPath(parentPath === REPOSITORY_ROOT ? `/${name}` : `${parentPath}/${name}`);
2326
+ return name;
2327
+ } catch (cause) {
2328
+ return throwSource("INVALID_SOURCE_DATA", operation, parentPath, false, cause);
2329
+ }
2330
+ };
2331
+ var openBufferDirectory = async (hostPath) => {
2332
+ return await opendir(hostPath, { encoding: "buffer" });
2333
+ };
2334
+ var getParentPaths = (logicalPath) => {
2335
+ const segments = logicalPath.slice(1).split("/");
2336
+ const parents = [REPOSITORY_ROOT];
2337
+ for (let index = 1; index < segments.length; index += 1) parents.push(parseRepositoryPath(`/${segments.slice(0, index).join("/")}`));
2338
+ return parents;
2339
+ };
2340
+ var findFirstPathAfter = (paths, logicalPath) => {
2341
+ let lowerIndex = 0;
2342
+ let upperIndex = paths.length;
2343
+ while (lowerIndex < upperIndex) {
2344
+ const middleIndex = lowerIndex + Math.floor((upperIndex - lowerIndex) / 2);
2345
+ const middlePath = paths[middleIndex];
2346
+ if (middlePath !== void 0 && compareRepositoryPaths$1(middlePath, logicalPath) <= 0) lowerIndex = middleIndex + 1;
2347
+ else upperIndex = middleIndex;
2348
+ }
2349
+ return lowerIndex;
2350
+ };
2351
+ var findSortedName = (names, target) => {
2352
+ let lowerIndex = 0;
2353
+ let upperIndex = names.length;
2354
+ while (lowerIndex < upperIndex) {
2355
+ const middleIndex = lowerIndex + Math.floor((upperIndex - lowerIndex) / 2);
2356
+ const middleName = names[middleIndex];
2357
+ if (middleName !== void 0 && middleName < target) lowerIndex = middleIndex + 1;
2358
+ else upperIndex = middleIndex;
2359
+ }
2360
+ return names[lowerIndex] === target ? lowerIndex : -1;
2361
+ };
2362
+ var FilesystemRepositoryReader = class {
2363
+ snapshot;
2364
+ #cache;
2365
+ #cursorKey = randomBytes(32);
2366
+ #coordinator;
2367
+ #limits;
2368
+ #observations = new Map();
2369
+ #rootDirectory;
2370
+ #selection;
2371
+ #selectedPaths;
2372
+ #selectedPathSet;
2373
+ #explicitSelectedPaths;
2374
+ #selectedNamesByParent = new Map();
2375
+ #selectedDirectoryProofs = new Map();
2376
+ constructor(options, rootDirectory, rootIdentity) {
2377
+ this.#limits = options.limits;
2378
+ this.#rootDirectory = rootDirectory;
2379
+ this.#selection = options.selection;
2380
+ this.#cache = createByteCache({
2381
+ maxBytes: options.limits.maxCachedBytes,
2382
+ maxEntries: 4096
2383
+ });
2384
+ this.#coordinator = createRequestCoordinator({
2385
+ maxConcurrent: options.limits.maxConcurrentOperations,
2386
+ maxQueued: options.limits.maxQueuedOperations
2387
+ });
2388
+ this.snapshot = Object.freeze({
2389
+ id: hashParts([rootIdentity, randomBytes(32)]),
2390
+ sourceKind: "filesystem"
2391
+ });
2392
+ this.#observations.set(REPOSITORY_ROOT, rootIdentity);
2393
+ this.#selectedPaths = options.selection.kind === "paths" ? this.#createVisibleSelectedPaths(options.selection.paths) : [];
2394
+ this.#selectedPathSet = new Set(this.#selectedPaths);
2395
+ this.#explicitSelectedPaths = new Set(options.selection.kind === "paths" ? options.selection.paths : []);
2396
+ for (const logicalPath of this.#selectedPaths) {
2397
+ if (logicalPath === REPOSITORY_ROOT) continue;
2398
+ const separatorIndex = logicalPath.lastIndexOf("/");
2399
+ const parentPath = parseRepositoryPath(logicalPath.slice(0, separatorIndex) || "/");
2400
+ const names = this.#selectedNamesByParent.get(parentPath) ?? new Set();
2401
+ names.add(logicalPath.slice(separatorIndex + 1));
2402
+ this.#selectedNamesByParent.set(parentPath, names);
2403
+ }
2404
+ }
2405
+ async initialize(signal) {
2406
+ if (this.#selection.kind !== "paths") return;
2407
+ for (const logicalPath of this.#selectedPaths) {
2408
+ throwIfAborted$1(signal, "create-reader", logicalPath);
2409
+ const entry = await this.#observeEntry(logicalPath, "create-reader", void 0, signal);
2410
+ if (entry === null) return throwSource("ENTRY_NOT_FOUND", "create-reader", logicalPath, true);
2411
+ if (logicalPath !== REPOSITORY_ROOT && !this.#explicitSelectedPaths.has(logicalPath) && entry.type !== "directory") throwSource("ENTRY_NOT_DIRECTORY", "create-reader", logicalPath, false);
2412
+ }
2413
+ }
2414
+ async compare(candidate, options) {
2415
+ return createRepositoryComparison(this, candidate, options);
2416
+ }
2417
+ async getEntry(logicalPath, options) {
2418
+ const parsedPath = parseRepositoryPath(logicalPath);
2419
+ if (!this.#isVisible(parsedPath)) return null;
2420
+ return this.#run("get-entry", parsedPath, options?.signal, () => this.#observeEntry(parsedPath, "get-entry", void 0, options?.signal));
2421
+ }
2422
+ async listEntriesPage(options) {
2423
+ const prefix = options.prefix === void 0 ? REPOSITORY_ROOT : parseRepositoryPath(options.prefix);
2424
+ return this.#run("list-entries-page", prefix, options.signal, async () => {
2425
+ const maxEntries = this.#parseBoundedPositiveInteger(options.maxEntries, this.#limits.maxPageEntries, "pageEntries", "list-entries-page", prefix);
2426
+ const prefixEntry = await this.#observeEntry(prefix, "list-entries-page", void 0, options.signal);
2427
+ if (prefixEntry === null || !this.#isVisible(prefix)) return throwSource("ENTRY_NOT_FOUND", "list-entries-page", prefix, false);
2428
+ if (prefixEntry.type !== "directory") throwSource("ENTRY_NOT_DIRECTORY", "list-entries-page", prefix, false);
2429
+ return this.#selection.kind === "paths" ? this.#listSelectedEntries(prefix, maxEntries, options.cursor, options.signal) : this.#listDirectoryEntries(prefix, maxEntries, options.cursor, options.signal);
2430
+ });
2431
+ }
2432
+ async readFilePage(logicalPath, options) {
2433
+ const parsedPath = parseRepositoryPath(logicalPath);
2434
+ return this.#run("read-file-page", parsedPath, options.signal, async () => {
2435
+ const offset = this.#parseOffset(options.offset, parsedPath);
2436
+ const maxBytes = this.#parseBoundedPositiveInteger(options.maxBytes, this.#limits.maxReadBytes, "readBytes", "read-file-page", parsedPath);
2437
+ if (!this.#isVisible(parsedPath)) throwSource("ENTRY_NOT_FOUND", "read-file-page", parsedPath, false);
2438
+ const entry = await this.#observeEntry(parsedPath, "read-file-page", void 0, options.signal);
2439
+ if (entry === null) return throwSource("ENTRY_NOT_FOUND", "read-file-page", parsedPath, false);
2440
+ if (entry.type !== "file" || entry.byteLength === null) return throwSource("ENTRY_NOT_FILE", "read-file-page", parsedPath, false);
2441
+ const entryIdentity = this.#observations.get(parsedPath);
2442
+ if (entryIdentity === void 0) return throwSource("INVALID_SOURCE_DATA", "read-file-page", parsedPath, false);
2443
+ if (offset > entry.byteLength) throwSource("INVALID_PAGE_REQUEST", "read-file-page", parsedPath, false);
2444
+ const bytesToRead = Math.min(maxBytes, entry.byteLength - offset);
2445
+ const cacheKey = `${parsedPath}\0${entryIdentity}\0${offset}\0${bytesToRead}`;
2446
+ const cached = this.#cache.get(cacheKey);
2447
+ if (cached !== void 0) return this.#createFilePage(cached, entry.byteLength, offset);
2448
+ const bytes = await this.#readExactRange(parsedPath, entryIdentity, offset, bytesToRead, options.signal);
2449
+ if (bytes.byteLength > 0) this.#cache.set(cacheKey, bytes);
2450
+ return this.#createFilePage(bytes, entry.byteLength, offset);
2451
+ });
2452
+ }
2453
+ async readLinkText(logicalPath, options) {
2454
+ const parsedPath = parseRepositoryPath(logicalPath);
2455
+ return this.#run("read-link-text", parsedPath, options?.signal, async () => {
2456
+ if (!this.#isVisible(parsedPath)) return throwSource("ENTRY_NOT_FOUND", "read-link-text", parsedPath, false);
2457
+ const entry = await this.#observeEntry(parsedPath, "read-link-text", void 0, options?.signal);
2458
+ if (entry === null) return throwSource("ENTRY_NOT_FOUND", "read-link-text", parsedPath, false);
2459
+ if (entry.type !== "symlink") return throwSource("ENTRY_NOT_LINK", "read-link-text", parsedPath, false);
2460
+ let text;
2461
+ try {
2462
+ text = await readlink(this.#getHostPath(parsedPath), { encoding: "buffer" });
2463
+ } catch (cause) {
2464
+ return throwMappedHostError(cause, "read-link-text", parsedPath);
2465
+ }
2466
+ await this.#observeEntry(parsedPath, "read-link-text", void 0, options?.signal);
2467
+ if (text.byteLength > 4096) return null;
2468
+ let decodedText;
2469
+ try {
2470
+ decodedText = decoder$1.decode(text);
2471
+ } catch {
2472
+ return null;
2473
+ }
2474
+ return process.platform === "win32" ? decodedText.replaceAll("\\", "/") : decodedText;
2475
+ });
2476
+ }
2477
+ #createFilePage(bytes, totalBytes, offset) {
2478
+ const nextOffset = offset + bytes.byteLength;
2479
+ const isComplete = nextOffset === totalBytes;
2480
+ return {
2481
+ bytes,
2482
+ isComplete,
2483
+ nextOffset: isComplete ? null : nextOffset,
2484
+ offset,
2485
+ snapshot: this.snapshot,
2486
+ totalBytes
2487
+ };
2488
+ }
2489
+ #createVisibleSelectedPaths(selectedPaths) {
2490
+ const visiblePaths = new Set([REPOSITORY_ROOT]);
2491
+ for (const selectedPath of selectedPaths) {
2492
+ visiblePaths.add(selectedPath);
2493
+ for (const parentPath of getParentPaths(selectedPath)) visiblePaths.add(parentPath);
2494
+ }
2495
+ if (visiblePaths.size - 1 > this.#limits.maxEntries) throwSource("RESOURCE_LIMIT_EXCEEDED", "create-reader", null, false, void 0, {
2496
+ dimension: "selectedEntries",
2497
+ limit: this.#limits.maxEntries,
2498
+ observed: visiblePaths.size - 1
2499
+ });
2500
+ return Object.freeze([...visiblePaths].sort(compareRepositoryPaths$1));
2501
+ }
2502
+ #decodeCursor(cursor, prefix) {
2503
+ try {
2504
+ if (Buffer.byteLength(cursor, "utf8") > MAX_CURSOR_BYTES) throw new Error("cursor exceeds the encoded limit");
2505
+ const separatorIndex = cursor.lastIndexOf(".");
2506
+ if (separatorIndex <= 0) throw new Error("cursor signature is missing");
2507
+ const encodedPayload = cursor.slice(0, separatorIndex);
2508
+ if (!verifyHmac(encodedPayload, cursor.slice(separatorIndex + 1), this.#cursorKey)) throw new Error("cursor signature does not match");
2509
+ const parsed = JSON.parse(Buffer.from(encodedPayload, "base64url").toString("utf8"));
2510
+ if (!isObjectValid(parsed, true) || parsed["version"] !== 1 || parsed["snapshotId"] !== this.snapshot.id || parsed["prefix"] !== prefix) throw new Error("cursor belongs to another snapshot or prefix");
2511
+ if (parsed["kind"] === "paths" && hasOnlyKeys(parsed, PATH_CURSOR_KEYS)) {
2512
+ const lastPath = parseRepositoryPath(parsed["lastPath"]);
2513
+ const descendantPrefix = prefix === REPOSITORY_ROOT ? REPOSITORY_ROOT : `${prefix}/`;
2514
+ if (lastPath === prefix || !lastPath.startsWith(descendantPrefix)) throw new Error("cursor path is outside the requested prefix");
2515
+ return {
2516
+ kind: "paths",
2517
+ lastPath,
2518
+ prefix,
2519
+ snapshotId: this.snapshot.id,
2520
+ version: 1
2521
+ };
2522
+ }
2523
+ if (parsed["kind"] === "directory" && hasOnlyKeys(parsed, DIRECTORY_CURSOR_KEYS) && Array.isArray(parsed["frames"])) return {
2524
+ frames: parsed["frames"].map((candidate) => {
2525
+ if (!isObjectValid(candidate, true)) throw new Error("cursor frame is invalid");
2526
+ const frame = candidate;
2527
+ if (!hasOnlyKeys(frame, CURSOR_FRAME_KEYS) || typeof frame["lastName"] !== "string" && frame["lastName"] !== null || typeof frame["namesIdentity"] !== "string" || typeof frame["path"] !== "string" || typeof frame["pathIdentity"] !== "string") throw new Error("cursor frame is invalid");
2528
+ return {
2529
+ lastName: frame["lastName"],
2530
+ namesIdentity: frame["namesIdentity"],
2531
+ path: parseRepositoryPath(frame["path"]),
2532
+ pathIdentity: frame["pathIdentity"]
2533
+ };
2534
+ }),
2535
+ kind: "directory",
2536
+ prefix,
2537
+ snapshotId: this.snapshot.id,
2538
+ version: 1
2539
+ };
2540
+ throw new Error("cursor payload is invalid");
2541
+ } catch (cause) {
2542
+ return throwSource("INVALID_PAGE_REQUEST", "list-entries-page", prefix, false, cause);
2543
+ }
2544
+ }
2545
+ #encodeCursor(cursor) {
2546
+ const encodedPayload = Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url");
2547
+ const encodedCursor = `${encodedPayload}.${signHmac(encodedPayload, this.#cursorKey)}`;
2548
+ if (Buffer.byteLength(encodedCursor, "utf8") > MAX_CURSOR_BYTES) throwSource("RESOURCE_LIMIT_EXCEEDED", "list-entries-page", cursor.prefix, false, void 0, {
2549
+ dimension: "cursorBytes",
2550
+ limit: MAX_CURSOR_BYTES,
2551
+ observed: Buffer.byteLength(encodedCursor, "utf8")
2552
+ });
2553
+ return encodedCursor;
2554
+ }
2555
+ #getHostPath(logicalPath) {
2556
+ if (logicalPath === REPOSITORY_ROOT) return this.#rootDirectory;
2557
+ const hostPath = path.resolve(this.#rootDirectory, ...logicalPath.slice(1).split("/"));
2558
+ const relativePath = path.relative(this.#rootDirectory, hostPath);
2559
+ if (relativePath === "" || relativePath === ".." || relativePath.startsWith(`..${path.sep}`) || path.isAbsolute(relativePath)) throwSource("INVALID_SOURCE_DATA", "get-entry", logicalPath, false);
2560
+ return hostPath;
2561
+ }
2562
+ #isVisible(logicalPath) {
2563
+ return this.#selection.kind === "directory" || this.#selectedPathSet.has(logicalPath);
2564
+ }
2565
+ async #listDirectoryEntries(prefix, maxEntries, encodedCursor, signal) {
2566
+ let frames;
2567
+ const directoryFrames = new Map();
2568
+ if (encodedCursor === void 0) {
2569
+ const initialFrame = await this.#createDirectoryFrame(prefix, null, "list-entries-page", directoryFrames, signal);
2570
+ frames = [initialFrame];
2571
+ directoryFrames.set(prefix, initialFrame);
2572
+ } else {
2573
+ const cursor = this.#decodeCursor(encodedCursor, prefix);
2574
+ if (cursor.kind !== "directory" || cursor.frames.length === 0) return throwSource("INVALID_PAGE_REQUEST", "list-entries-page", prefix, false);
2575
+ frames = [];
2576
+ for (const frame of cursor.frames) {
2577
+ const restored = await this.#restoreDirectoryFrame(frame, directoryFrames, signal);
2578
+ frames.push(restored);
2579
+ directoryFrames.set(restored.path, restored);
2580
+ }
2581
+ }
2582
+ const entries = [];
2583
+ while (frames.length > 0 && entries.length < maxEntries) {
2584
+ throwIfAborted$1(signal, "list-entries-page", prefix);
2585
+ const frame = frames.at(-1);
2586
+ if (frame === void 0) break;
2587
+ if (frame.nextIndex >= frame.names.length) {
2588
+ frames.pop();
2589
+ directoryFrames.delete(frame.path);
2590
+ continue;
2591
+ }
2592
+ const name = frame.names[frame.nextIndex];
2593
+ if (name === void 0) return throwSource("INVALID_SOURCE_DATA", "list-entries-page", frame.path, false);
2594
+ frames[frames.length - 1] = {
2595
+ ...frame,
2596
+ lastName: name,
2597
+ nextIndex: frame.nextIndex + 1
2598
+ };
2599
+ const childPath = parseRepositoryPath(frame.path === REPOSITORY_ROOT ? `/${name}` : `${frame.path}/${name}`);
2600
+ const entry = await this.#observeEntry(childPath, "list-entries-page", directoryFrames, signal);
2601
+ if (entry === null) return throwSource("SNAPSHOT_CHANGED", "list-entries-page", childPath, true);
2602
+ entries.push(entry);
2603
+ if (entry.type === "directory") {
2604
+ const childFrame = await this.#createDirectoryFrame(childPath, null, "list-entries-page", directoryFrames, signal);
2605
+ frames.push(childFrame);
2606
+ directoryFrames.set(childPath, childFrame);
2607
+ }
2608
+ }
2609
+ const isComplete = frames.length === 0;
2610
+ return {
2611
+ entries,
2612
+ isComplete,
2613
+ nextCursor: isComplete ? null : this.#encodeCursor({
2614
+ frames: frames.map(({ lastName, namesIdentity, path: framePath, pathIdentity }) => ({
2615
+ lastName,
2616
+ namesIdentity,
2617
+ path: framePath,
2618
+ pathIdentity
2619
+ })),
2620
+ kind: "directory",
2621
+ prefix,
2622
+ snapshotId: this.snapshot.id,
2623
+ version: 1
2624
+ }),
2625
+ snapshot: this.snapshot
2626
+ };
2627
+ }
2628
+ async #listSelectedEntries(prefix, maxEntries, encodedCursor, signal) {
2629
+ let lastPath = null;
2630
+ if (encodedCursor !== void 0) {
2631
+ const cursor = this.#decodeCursor(encodedCursor, prefix);
2632
+ if (cursor.kind !== "paths" || !this.#selectedPathSet.has(cursor.lastPath)) return throwSource("INVALID_PAGE_REQUEST", "list-entries-page", prefix, false);
2633
+ lastPath = cursor.lastPath;
2634
+ }
2635
+ const descendantPrefix = prefix === REPOSITORY_ROOT ? REPOSITORY_ROOT : `${prefix}/`;
2636
+ let pathIndex = findFirstPathAfter(this.#selectedPaths, lastPath ?? prefix);
2637
+ const entries = [];
2638
+ while (entries.length < maxEntries) {
2639
+ throwIfAborted$1(signal, "list-entries-page", prefix);
2640
+ const logicalPath = this.#selectedPaths[pathIndex];
2641
+ if (logicalPath === void 0 || !logicalPath.startsWith(descendantPrefix)) break;
2642
+ const entry = await this.#observeEntry(logicalPath, "list-entries-page", void 0, signal);
2643
+ if (entry === null) return throwSource("SNAPSHOT_CHANGED", "list-entries-page", logicalPath, true);
2644
+ entries.push(entry);
2645
+ pathIndex += 1;
2646
+ }
2647
+ const nextPath = this.#selectedPaths[pathIndex];
2648
+ const isComplete = nextPath === void 0 || !nextPath.startsWith(descendantPrefix);
2649
+ const finalEntry = entries.at(-1);
2650
+ if (!isComplete && finalEntry === void 0) return throwSource("INVALID_SOURCE_DATA", "list-entries-page", prefix, false);
2651
+ return {
2652
+ entries,
2653
+ isComplete,
2654
+ nextCursor: isComplete ? null : this.#encodeCursor({
2655
+ kind: "paths",
2656
+ lastPath: finalEntry?.path ?? prefix,
2657
+ prefix,
2658
+ snapshotId: this.snapshot.id,
2659
+ version: 1
2660
+ }),
2661
+ snapshot: this.snapshot
2662
+ };
2663
+ }
2664
+ #parseBoundedPositiveInteger(candidate, limit, dimension, operation, logicalPath) {
2665
+ if (!Number.isSafeInteger(candidate) || candidate <= 0) throwSource("INVALID_PAGE_REQUEST", operation, logicalPath, false);
2666
+ if (candidate > limit) throwSource("RESOURCE_LIMIT_EXCEEDED", operation, logicalPath, false, void 0, {
2667
+ dimension,
2668
+ limit,
2669
+ observed: candidate
2670
+ });
2671
+ return candidate;
2672
+ }
2673
+ #parseOffset(candidate, logicalPath) {
2674
+ if (!Number.isSafeInteger(candidate) || candidate < 0) throwSource("INVALID_PAGE_REQUEST", "read-file-page", logicalPath, false);
2675
+ return candidate;
2676
+ }
2677
+ async #createDirectoryFrame(logicalPath, lastName, operation, directoryFrames, signal) {
2678
+ const entry = await this.#observeEntry(logicalPath, operation, directoryFrames, signal);
2679
+ if (entry === null || entry.type !== "directory") throwSource("SNAPSHOT_CHANGED", operation, logicalPath, true);
2680
+ const names = await this.#readDirectoryNames(logicalPath, operation, directoryFrames, signal);
2681
+ const nextIndex = lastName === null ? 0 : findSortedName(names, lastName) + 1;
2682
+ if (nextIndex === 0 && lastName !== null) throwSource("SNAPSHOT_CHANGED", operation, logicalPath, true);
2683
+ return {
2684
+ lastName,
2685
+ names,
2686
+ namesIdentity: hashParts(names),
2687
+ nextIndex,
2688
+ path: logicalPath,
2689
+ pathIdentity: this.#observations.get(logicalPath) ?? ""
2690
+ };
2691
+ }
2692
+ async #restoreDirectoryFrame(frame, directoryFrames, signal) {
2693
+ const restored = await this.#createDirectoryFrame(parseRepositoryPath(frame.path), frame.lastName, "list-entries-page", directoryFrames, signal);
2694
+ if (restored.pathIdentity !== frame.pathIdentity || restored.namesIdentity !== frame.namesIdentity) throwSource("SNAPSHOT_CHANGED", "list-entries-page", frame.path, true);
2695
+ return restored;
2696
+ }
2697
+ async #readDirectoryNames(logicalPath, operation, directoryFrames, signal) {
2698
+ try {
2699
+ const directory = await openBufferDirectory(this.#getHostPath(logicalPath));
2700
+ const names = [];
2701
+ let observedEntries = 0;
2702
+ for await (const directoryEntry of directory) {
2703
+ throwIfAborted$1(signal, operation, logicalPath);
2704
+ observedEntries += 1;
2705
+ if (observedEntries > this.#limits.maxDirectoryEntries) throwSource("RESOURCE_LIMIT_EXCEEDED", operation, logicalPath, false, void 0, {
2706
+ dimension: "directoryEntries",
2707
+ limit: this.#limits.maxDirectoryEntries,
2708
+ observed: observedEntries
2709
+ });
2710
+ const name = decodeName(directoryEntry.name, operation, logicalPath);
2711
+ if (name !== ".git") names.push(name);
2712
+ }
2713
+ await this.#observeEntry(logicalPath, operation, directoryFrames, signal);
2714
+ return names.sort();
2715
+ } catch (cause) {
2716
+ if (cause instanceof RepositorySourceException) throw cause;
2717
+ return throwMappedHostError(cause, operation, logicalPath);
2718
+ }
2719
+ }
2720
+ async #hasExactChildName(logicalPath, targetName, operation, parentIdentity, directoryFrames, signal) {
2721
+ const frame = directoryFrames?.get(logicalPath);
2722
+ if (frame !== void 0) {
2723
+ if (frame.pathIdentity !== parentIdentity) throwSource("SNAPSHOT_CHANGED", operation, logicalPath, true);
2724
+ return findSortedName(frame.names, targetName) >= 0;
2725
+ }
2726
+ const selectedNames = this.#selectedNamesByParent.get(logicalPath);
2727
+ const isSelectedName = selectedNames?.has(targetName) === true;
2728
+ const proof = isSelectedName ? this.#selectedDirectoryProofs.get(logicalPath) : void 0;
2729
+ if (proof !== void 0) {
2730
+ if (proof.identity !== parentIdentity) throwSource("SNAPSHOT_CHANGED", operation, logicalPath, true);
2731
+ throwIfAborted$1(signal, operation, logicalPath);
2732
+ return proof.names.has(targetName);
2733
+ }
2734
+ try {
2735
+ const directory = await openBufferDirectory(this.#getHostPath(logicalPath));
2736
+ const targets = isSelectedName && selectedNames !== void 0 ? selectedNames : new Set([targetName]);
2737
+ const names = new Set();
2738
+ let observedEntries = 0;
2739
+ for await (const directoryEntry of directory) {
2740
+ throwIfAborted$1(signal, operation, logicalPath);
2741
+ observedEntries += 1;
2742
+ if (observedEntries > this.#limits.maxDirectoryEntries) throwSource("RESOURCE_LIMIT_EXCEEDED", operation, logicalPath, false, void 0, {
2743
+ dimension: "directoryEntries",
2744
+ limit: this.#limits.maxDirectoryEntries,
2745
+ observed: observedEntries
2746
+ });
2747
+ let name;
2748
+ try {
2749
+ name = decodeName(directoryEntry.name, operation, logicalPath);
2750
+ } catch (cause) {
2751
+ if (cause instanceof RepositorySourceException && cause.code === "INVALID_SOURCE_DATA") continue;
2752
+ throw cause;
2753
+ }
2754
+ if (name !== ".git" && targets.has(name)) {
2755
+ names.add(name);
2756
+ if (names.size === targets.size) break;
2757
+ }
2758
+ }
2759
+ if (isSelectedName) {
2760
+ const statistics = await lstat(this.#getHostPath(logicalPath), { bigint: true });
2761
+ if (!statistics.isDirectory() || getStatisticsIdentity(statistics, "directory") !== parentIdentity) throwSource("SNAPSHOT_CHANGED", operation, logicalPath, true);
2762
+ this.#selectedDirectoryProofs.set(logicalPath, {
2763
+ identity: parentIdentity,
2764
+ names
2765
+ });
2766
+ }
2767
+ throwIfAborted$1(signal, operation, logicalPath);
2768
+ return names.has(targetName);
2769
+ } catch (cause) {
2770
+ if (cause instanceof RepositorySourceException) throw cause;
2771
+ return throwMappedHostError(cause, operation, logicalPath);
2772
+ }
2773
+ }
2774
+ async #readExactEntryStatistics(logicalPath, operation, directoryFrames, signal) {
2775
+ const rootStatistics = await this.#assertRootUnchanged(operation, logicalPath);
2776
+ if (logicalPath === REPOSITORY_ROOT) return rootStatistics;
2777
+ const segments = logicalPath.slice(1).split("/");
2778
+ let currentPath = REPOSITORY_ROOT;
2779
+ let statistics = null;
2780
+ const parentIdentities = [];
2781
+ for (const [index, segment] of segments.entries()) {
2782
+ throwIfAborted$1(signal, operation, logicalPath);
2783
+ const parentIdentity = getStatisticsIdentity(statistics ?? rootStatistics, "directory");
2784
+ if (!await this.#hasExactChildName(currentPath, segment, operation, parentIdentity, directoryFrames, signal)) return null;
2785
+ currentPath = parseRepositoryPath(currentPath === REPOSITORY_ROOT ? `/${segment}` : `${currentPath}/${segment}`);
2786
+ try {
2787
+ statistics = await lstat(this.#getHostPath(currentPath), { bigint: true });
2788
+ } catch (cause) {
2789
+ return throwMappedHostError(cause, operation, currentPath);
2790
+ }
2791
+ if (index < segments.length - 1 && !statistics.isDirectory()) return null;
2792
+ if (index < segments.length - 1) parentIdentities.push({
2793
+ identity: getStatisticsIdentity(statistics, "directory"),
2794
+ path: currentPath
2795
+ });
2796
+ }
2797
+ for (const parent of parentIdentities) {
2798
+ throwIfAborted$1(signal, operation, logicalPath);
2799
+ let currentStatistics;
2800
+ try {
2801
+ currentStatistics = await lstat(this.#getHostPath(parent.path), { bigint: true });
2802
+ } catch (cause) {
2803
+ return throwMappedHostError(cause, operation, parent.path);
2804
+ }
2805
+ if (!currentStatistics.isDirectory() || getStatisticsIdentity(currentStatistics, "directory") !== parent.identity) return throwSource("SNAPSHOT_CHANGED", operation, parent.path, true);
2806
+ }
2807
+ await this.#assertRootUnchanged(operation, logicalPath);
2808
+ return statistics;
2809
+ }
2810
+ async #assertRootUnchanged(operation, logicalPath) {
2811
+ try {
2812
+ const statistics = await lstat(this.#rootDirectory, { bigint: true });
2813
+ const rootIdentity = this.#observations.get(REPOSITORY_ROOT);
2814
+ if (!statistics.isDirectory() || rootIdentity === void 0 || getStatisticsIdentity(statistics, "directory") !== rootIdentity) return throwSource("SNAPSHOT_CHANGED", operation, logicalPath, true);
2815
+ return statistics;
2816
+ } catch (cause) {
2817
+ if (cause instanceof RepositorySourceException) throw cause;
2818
+ return throwMappedHostError(cause, operation, logicalPath);
2819
+ }
2820
+ }
2821
+ async #observeEntry(logicalPath, operation, directoryFrames, signal) {
2822
+ const statistics = await this.#readExactEntryStatistics(logicalPath, operation, directoryFrames, signal);
2823
+ throwIfAborted$1(signal, operation, logicalPath);
2824
+ if (statistics === null) return this.#observations.has(logicalPath) ? throwSource("SNAPSHOT_CHANGED", operation, logicalPath, true) : null;
2825
+ const type = classifyStatistics(statistics, operation, logicalPath);
2826
+ const identity = getStatisticsIdentity(statistics, type);
2827
+ const previousIdentity = this.#observations.get(logicalPath);
2828
+ if (previousIdentity !== void 0 && previousIdentity !== identity) throwSource("SNAPSHOT_CHANGED", operation, logicalPath, true);
2829
+ if (previousIdentity === void 0) {
2830
+ if (this.#observations.size - 1 >= this.#limits.maxEntries) throwSource("RESOURCE_LIMIT_EXCEEDED", operation, logicalPath, false, void 0, {
2831
+ dimension: "observedEntries",
2832
+ limit: this.#limits.maxEntries,
2833
+ observed: this.#observations.size
2834
+ });
2835
+ this.#observations.set(logicalPath, identity);
2836
+ }
2837
+ return {
2838
+ byteLength: type === "file" ? Number(statistics.size) : null,
2839
+ contentIdentity: null,
2840
+ path: logicalPath,
2841
+ type
2842
+ };
2843
+ }
2844
+ async #readExactRange(logicalPath, entryIdentity, offset, bytesToRead, signal) {
2845
+ let handle;
2846
+ try {
2847
+ const noFollow = "O_NOFOLLOW" in constants ? constants.O_NOFOLLOW : 0;
2848
+ handle = await open(this.#getHostPath(logicalPath), constants.O_RDONLY | noFollow);
2849
+ const before = await handle.stat({ bigint: true });
2850
+ if (getStatisticsIdentity(before, classifyStatistics(before, "read-file-page", logicalPath)) !== entryIdentity) throwSource("SNAPSHOT_CHANGED", "read-file-page", logicalPath, true);
2851
+ const bytes = new Uint8Array(bytesToRead);
2852
+ let totalRead = 0;
2853
+ while (totalRead < bytesToRead) {
2854
+ throwIfAborted$1(signal, "read-file-page", logicalPath);
2855
+ const result = await handle.read(bytes, totalRead, bytesToRead - totalRead, offset + totalRead);
2856
+ if (result.bytesRead === 0) throwSource("SNAPSHOT_CHANGED", "read-file-page", logicalPath, true);
2857
+ totalRead += result.bytesRead;
2858
+ }
2859
+ const after = await handle.stat({ bigint: true });
2860
+ if (getStatisticsIdentity(after, classifyStatistics(after, "read-file-page", logicalPath)) !== entryIdentity) throwSource("SNAPSHOT_CHANGED", "read-file-page", logicalPath, true);
2861
+ await this.#observeEntry(logicalPath, "read-file-page");
2862
+ return bytes;
2863
+ } catch (cause) {
2864
+ if (cause instanceof RepositorySourceException) throw cause;
2865
+ return throwMappedHostError(cause, "read-file-page", logicalPath);
2866
+ } finally {
2867
+ await handle?.close().catch(() => void 0);
2868
+ }
2869
+ }
2870
+ async #run(operation, logicalPath, signal, callback) {
2871
+ let isStarted = false;
2872
+ try {
2873
+ return await this.#coordinator.run(async () => {
2874
+ isStarted = true;
2875
+ throwIfAborted$1(signal, operation, logicalPath);
2876
+ return callback();
2877
+ }, signal === void 0 ? {} : { signal });
2878
+ } catch (cause) {
2879
+ if (isStarted) throw cause;
2880
+ if (getErrorCode(cause) === ERRORS.REQUEST_QUEUE_FULL) return throwSource("RESOURCE_LIMIT_EXCEEDED", operation, logicalPath, true, void 0, {
2881
+ dimension: "queuedOperations",
2882
+ limit: this.#limits.maxQueuedOperations,
2883
+ observed: this.#limits.maxQueuedOperations + 1
2884
+ });
2885
+ return throwSource("ABORTED", operation, logicalPath, false, cause);
2886
+ }
2887
+ }
2888
+ };
2889
+ var prepareRoot = async (options) => {
2890
+ throwIfAborted$1(options.signal, "create-reader", null);
2891
+ try {
2892
+ const rootDirectory = await realpath(options.rootDirectory);
2893
+ const statistics = await lstat(rootDirectory, { bigint: true });
2894
+ if (!statistics.isDirectory()) throwSource("ENTRY_NOT_DIRECTORY", "create-reader", null, false);
2895
+ return {
2896
+ identity: getStatisticsIdentity(statistics, "directory"),
2897
+ rootDirectory
2898
+ };
2899
+ } catch (cause) {
2900
+ if (cause instanceof RepositorySourceException) throw cause;
2901
+ return throwMappedHostError(cause, "create-reader", null);
2902
+ }
2903
+ };
2904
+ var createFilesystemRepositoryReader = async (rawOptions) => {
2905
+ const options = normalizeFilesystemRepositoryOptions(rawOptions);
2906
+ const root = await prepareRoot(options);
2907
+ const reader = new FilesystemRepositoryReader(options, root.rootDirectory, root.identity);
2908
+ await reader.initialize(options.signal);
2909
+ throwIfAborted$1(options.signal, "create-reader", null);
2910
+ return Object.freeze(reader);
2911
+ };
2912
+ //#endregion
2913
+ //#region src/repository-symlink-overlay/reader.ts
2914
+ var decoder = new TextDecoder("utf-8", {
2915
+ fatal: true,
2916
+ ignoreBOM: true
2917
+ });
2918
+ var throwIfAborted = (signal, operation, path) => {
2919
+ if (!signal?.aborted) return;
2920
+ throw new RepositorySourceException({
2921
+ cause: signal.reason,
2922
+ code: "ABORTED",
2923
+ operation,
2924
+ path,
2925
+ retryable: false
2926
+ });
2927
+ };
2928
+ var createInvalidOverlayException = (operation, path) => new RepositorySourceException({
2929
+ code: "INVALID_SOURCE_DATA",
2930
+ operation,
2931
+ path,
2932
+ retryable: false
2933
+ });
2934
+ var validateOverlayEntry = (entry, operation, path) => {
2935
+ if (entry?.type !== "file" || entry.path !== path) throw createInvalidOverlayException(operation, path);
2936
+ };
2937
+ var overlayEntry = (entry, operation, path) => {
2938
+ validateOverlayEntry(entry, operation, path);
2939
+ return Object.freeze({
2940
+ byteLength: null,
2941
+ contentIdentity: null,
2942
+ path,
2943
+ type: "symlink"
2944
+ });
2945
+ };
2946
+ var GitSymlinkOverlayRepositoryReader = class {
2947
+ snapshot;
2948
+ #overlayPaths;
2949
+ #reader;
2950
+ constructor(reader, overlayPaths) {
2951
+ this.#reader = reader;
2952
+ this.#overlayPaths = overlayPaths;
2953
+ this.snapshot = reader.snapshot;
2954
+ }
2955
+ compare(candidate, options) {
2956
+ return createRepositoryComparison(this, candidate, options);
2957
+ }
2958
+ async getEntry(path, options) {
2959
+ const entry = await this.#reader.getEntry(path, options);
2960
+ if (!this.#overlayPaths.has(path)) return entry;
2961
+ return overlayEntry(entry, "get-entry", path);
2962
+ }
2963
+ async readFilePage(path, options) {
2964
+ const parsedPath = parseRepositoryPath(path);
2965
+ if (!this.#overlayPaths.has(parsedPath)) return this.#reader.readFilePage(parsedPath, options);
2966
+ throwIfAborted(options.signal, "read-file-page", parsedPath);
2967
+ validateOverlayEntry(await this.#reader.getEntry(parsedPath, options), "read-file-page", parsedPath);
2968
+ throwIfAborted(options.signal, "read-file-page", parsedPath);
2969
+ throw new RepositorySourceException({
2970
+ code: "ENTRY_NOT_FILE",
2971
+ operation: "read-file-page",
2972
+ path: parsedPath,
2973
+ retryable: false
2974
+ });
2975
+ }
2976
+ async readLinkText(path, options) {
2977
+ const parsedPath = parseRepositoryPath(path);
2978
+ if (!this.#overlayPaths.has(parsedPath)) return this.#reader.readLinkText(parsedPath, options);
2979
+ throwIfAborted(options?.signal, "read-link-text", parsedPath);
2980
+ const entry = await this.#reader.getEntry(parsedPath, options);
2981
+ validateOverlayEntry(entry, "read-link-text", parsedPath);
2982
+ throwIfAborted(options?.signal, "read-link-text", parsedPath);
2983
+ const byteLength = entry?.byteLength ?? null;
2984
+ if (byteLength === null) throw createInvalidOverlayException("read-link-text", parsedPath);
2985
+ if (byteLength > 4096) return null;
2986
+ if (byteLength === 0) return "";
2987
+ const page = await this.#reader.readFilePage(parsedPath, {
2988
+ maxBytes: byteLength,
2989
+ offset: 0,
2990
+ ...options?.signal === void 0 ? {} : { signal: options.signal }
2991
+ });
2992
+ throwIfAborted(options?.signal, "read-link-text", parsedPath);
2993
+ if (!page.isComplete || page.totalBytes !== byteLength || page.bytes.byteLength !== byteLength) throw createInvalidOverlayException("read-link-text", parsedPath);
2994
+ try {
2995
+ return decoder.decode(page.bytes);
2996
+ } catch {
2997
+ return null;
2998
+ }
2999
+ }
3000
+ async listEntriesPage(options) {
3001
+ const prefix = options.prefix === void 0 ? REPOSITORY_ROOT : parseRepositoryPath(options.prefix);
3002
+ if (this.#overlayPaths.has(prefix)) {
3003
+ throwIfAborted(options.signal, "list-entries-page", prefix);
3004
+ const operationOptions = options.signal === void 0 ? void 0 : { signal: options.signal };
3005
+ validateOverlayEntry(await this.#reader.getEntry(prefix, operationOptions), "list-entries-page", prefix);
3006
+ throwIfAborted(options.signal, "list-entries-page", prefix);
3007
+ throw new RepositorySourceException({
3008
+ code: "ENTRY_NOT_DIRECTORY",
3009
+ operation: "list-entries-page",
3010
+ path: prefix,
3011
+ retryable: false
3012
+ });
3013
+ }
3014
+ const page = await this.#reader.listEntriesPage(options);
3015
+ const entries = page.entries.map((entry) => this.#overlayPaths.has(entry.path) ? overlayEntry(entry, "list-entries-page", entry.path) : entry);
3016
+ return Object.freeze({
3017
+ entries: Object.freeze(entries),
3018
+ isComplete: page.isComplete,
3019
+ nextCursor: page.nextCursor,
3020
+ snapshot: this.snapshot
3021
+ });
3022
+ }
3023
+ };
3024
+ var createGitSymlinkOverlayRepositoryReader = (reader, symlinkPaths) => {
3025
+ const overlayPaths = new Set();
3026
+ for (const symlinkPath of symlinkPaths) {
3027
+ const parsedPath = parseRepositoryPath(symlinkPath);
3028
+ if (parsedPath === REPOSITORY_ROOT) throw new RepositorySourceException({
3029
+ code: "INVALID_SOURCE_DATA",
3030
+ operation: "create-reader",
3031
+ path: parsedPath,
3032
+ retryable: false
3033
+ });
3034
+ overlayPaths.add(parsedPath);
3035
+ }
3036
+ return Object.freeze(new GitSymlinkOverlayRepositoryReader(reader, overlayPaths));
3037
+ };
3038
+ //#endregion
3039
+ //#region src/repository-reader/factory.ts
3040
+ var composeWorkingTreeReader = async (input, filesystemReaderFactory, symlinkOverlayFactory, contentTransformationGuardFactory) => {
3041
+ const selectedPaths = Object.freeze(input.entries.map((entry) => entry.path));
3042
+ const symlinkOverlayPaths = Object.freeze(input.entries.reduce((paths, entry) => {
3043
+ if (entry.requiresSymlinkOverlay) paths.push(entry.path);
3044
+ return paths;
3045
+ }, []));
3046
+ const guardedPaths = Object.freeze(input.entries.reduce((paths, entry) => {
3047
+ if (entry.contentTransformation.isGuarded) paths.push(entry.path);
3048
+ return paths;
3049
+ }, []));
3050
+ return contentTransformationGuardFactory(symlinkOverlayFactory(await filesystemReaderFactory({
3051
+ limits: Object.freeze({
3052
+ maxCachedBytes: input.resourceLimits.maxTotalBytes,
3053
+ maxDirectoryEntries: input.resourceLimits.maxEntries,
3054
+ maxEntries: input.resourceLimits.maxEntries,
3055
+ maxPageEntries: Math.min(4096, input.resourceLimits.maxEntries),
3056
+ maxReadBytes: input.resourceLimits.maxFileBytes
3057
+ }),
3058
+ rootDirectory: input.repositoryRoot,
3059
+ selection: Object.freeze({
3060
+ kind: "paths",
3061
+ paths: selectedPaths
3062
+ }),
3063
+ ...input.signal === void 0 ? {} : { signal: input.signal }
3064
+ }), symlinkOverlayPaths), guardedPaths);
3065
+ };
3066
+ var createWorkingTreeRepositoryReaderFactory = (filesystemReaderFactory = createFilesystemRepositoryReader, symlinkOverlayFactory = createGitSymlinkOverlayRepositoryReader, contentTransformationGuardFactory = createGitContentTransformationGuardRepositoryReader) => (input) => composeWorkingTreeReader(input, filesystemReaderFactory, symlinkOverlayFactory, contentTransformationGuardFactory);
3067
+ var createWorkingTreeRepositoryReader = createWorkingTreeRepositoryReaderFactory();
3068
+ var createWorkingTreeInstructionSourceFactory = (filesystemReaderFactory = createFilesystemRepositoryReader, symlinkOverlayFactory = createGitSymlinkOverlayRepositoryReader, contentTransformationGuardFactory = createGitContentTransformationGuardRepositoryReader) => (input) => composeWorkingTreeReader(input, filesystemReaderFactory, symlinkOverlayFactory, contentTransformationGuardFactory);
3069
+ var createWorkingTreeInstructionSource = createWorkingTreeInstructionSourceFactory();
3070
+ //#endregion
3071
+ //#region src/working-tree-snapshot/executor.ts
3072
+ var createSnapshotFailure = (errorCode, subcommand) => Object.freeze({
3073
+ errorCode,
3074
+ kind: "failed",
3075
+ ...subcommand === void 0 ? {} : { subcommand }
3076
+ });
3077
+ var isSnapshotChanged = (error) => error instanceof RepositorySourceException && error.code === "SNAPSHOT_CHANGED";
3078
+ var isCreationInventoryRace = (error) => error instanceof RepositorySourceException && error.operation === "create-reader" && (error.code === "ENTRY_NOT_FOUND" || error.code === "ENTRY_NOT_DIRECTORY");
3079
+ var isPinnedIdentityUnavailable = (errorCode) => errorCode === "GIT_REPOSITORY_NOT_FOUND" || errorCode === "GIT_WORK_TREE_REQUIRED";
3080
+ var createWorkingTreeSnapshotExecutor = (identityInspector = inspectGitWorkingTreeIdentity, inventoryProbe = probeGitInventory, repositoryReaderFactory = createWorkingTreeRepositoryReader, compareInventories = areGitInventoriesEqual, instructionSourceFactory = createWorkingTreeInstructionSource) => {
3081
+ const executeSnapshot = async (input) => {
3082
+ if (input.signal?.aborted) return createSnapshotFailure("GIT_OPERATION_ABORTED");
3083
+ const repositoryRoot = input.repositoryRoot;
3084
+ const resourceLimits = Object.freeze({ ...input.resourceLimits });
3085
+ const pinnedIdentityResult = await identityInspector({
3086
+ repositoryRoot,
3087
+ ...input.signal === void 0 ? {} : { signal: input.signal }
3088
+ });
3089
+ if (input.signal?.aborted) return createSnapshotFailure("GIT_OPERATION_ABORTED");
3090
+ if (pinnedIdentityResult.kind === "failed") return createSnapshotFailure(pinnedIdentityResult.errorCode);
3091
+ if (pinnedIdentityResult.kind === "mismatched") return createSnapshotFailure("GIT_OUTPUT_INVALID");
3092
+ const pinnedIdentity = pinnedIdentityResult.identity;
3093
+ const probeInventory = async () => {
3094
+ const result = await inventoryProbe({
3095
+ maxEntries: resourceLimits.maxEntries,
3096
+ maxMetadataBytes: resourceLimits.maxTotalBytes,
3097
+ repositoryRoot,
3098
+ ...input.selectionPaths === void 0 ? {} : { selectionPaths: input.selectionPaths },
3099
+ ...input.signal === void 0 ? {} : { signal: input.signal }
3100
+ });
3101
+ return result.kind === "failed" ? createSnapshotFailure(result.errorCode, result.subcommand) : result;
3102
+ };
3103
+ const probeInstructions = async () => {
3104
+ if (input.includeInstructions !== true) return null;
3105
+ const result = await inventoryProbe({
3106
+ includeIgnored: true,
3107
+ maxEntries: resourceLimits.maxEntries,
3108
+ maxMetadataBytes: resourceLimits.maxTotalBytes,
3109
+ repositoryRoot,
3110
+ selectionPaths: INSTRUCTION_PATHS,
3111
+ ...input.signal === void 0 ? {} : { signal: input.signal }
3112
+ });
3113
+ return result.kind === "failed" ? createSnapshotFailure(result.errorCode, result.subcommand) : result;
3114
+ };
3115
+ for (let attempt = 0; attempt < 3; attempt += 1) {
3116
+ if (input.signal?.aborted) return createSnapshotFailure("GIT_OPERATION_ABORTED");
3117
+ const currentIdentityResult = await identityInspector({
3118
+ repositoryRoot,
3119
+ ...input.signal === void 0 ? {} : { signal: input.signal }
3120
+ });
3121
+ if (input.signal?.aborted) return createSnapshotFailure("GIT_OPERATION_ABORTED");
3122
+ if (currentIdentityResult.kind === "failed") return createSnapshotFailure(isPinnedIdentityUnavailable(currentIdentityResult.errorCode) ? "WORKING_TREE_UNSTABLE" : currentIdentityResult.errorCode);
3123
+ if (currentIdentityResult.kind === "mismatched" || !areGitWorkingTreeIdentitiesEqual(pinnedIdentity, currentIdentityResult.identity)) return createSnapshotFailure("WORKING_TREE_UNSTABLE");
3124
+ const firstInventoryResult = await probeInventory();
3125
+ if (input.signal?.aborted) return createSnapshotFailure("GIT_OPERATION_ABORTED");
3126
+ if (firstInventoryResult.kind === "failed") return firstInventoryResult;
3127
+ const firstInstructionResult = await probeInstructions();
3128
+ if (input.signal?.aborted) return createSnapshotFailure("GIT_OPERATION_ABORTED");
3129
+ if (firstInstructionResult?.kind === "failed") return firstInstructionResult;
3130
+ let reader;
3131
+ let instructions;
3132
+ try {
3133
+ reader = await repositoryReaderFactory({
3134
+ entries: firstInventoryResult.entries,
3135
+ repositoryRoot,
3136
+ resourceLimits,
3137
+ ...input.signal === void 0 ? {} : { signal: input.signal }
3138
+ });
3139
+ instructions = firstInstructionResult === null ? void 0 : await instructionSourceFactory({
3140
+ entries: firstInstructionResult.entries,
3141
+ repositoryRoot,
3142
+ resourceLimits,
3143
+ ...input.signal === void 0 ? {} : { signal: input.signal }
3144
+ });
3145
+ } catch (error) {
3146
+ if (input.signal?.aborted) return createSnapshotFailure("GIT_OPERATION_ABORTED");
3147
+ if (isSnapshotChanged(error)) continue;
3148
+ if (!isCreationInventoryRace(error)) throw error;
3149
+ const freshInventoryResult = await probeInventory();
3150
+ if (input.signal?.aborted) return createSnapshotFailure("GIT_OPERATION_ABORTED");
3151
+ if (freshInventoryResult.kind === "failed") return freshInventoryResult;
3152
+ const freshInstructionResult = await probeInstructions();
3153
+ if (input.signal?.aborted) return createSnapshotFailure("GIT_OPERATION_ABORTED");
3154
+ if (freshInstructionResult?.kind === "failed") return freshInstructionResult;
3155
+ if (!compareInventories(firstInventoryResult.entries, freshInventoryResult.entries) || firstInstructionResult !== null && freshInstructionResult !== null && !compareInventories(firstInstructionResult.entries, freshInstructionResult.entries)) continue;
3156
+ throw error;
3157
+ }
3158
+ const secondInventoryResult = await probeInventory();
3159
+ if (input.signal?.aborted) return createSnapshotFailure("GIT_OPERATION_ABORTED");
3160
+ if (secondInventoryResult.kind === "failed") return secondInventoryResult;
3161
+ if (!compareInventories(firstInventoryResult.entries, secondInventoryResult.entries)) continue;
3162
+ const secondInstructionResult = await probeInstructions();
3163
+ if (input.signal?.aborted) return createSnapshotFailure("GIT_OPERATION_ABORTED");
3164
+ if (secondInstructionResult?.kind === "failed") return secondInstructionResult;
3165
+ if (firstInstructionResult !== null && secondInstructionResult !== null && !compareInventories(firstInstructionResult.entries, secondInstructionResult.entries)) continue;
3166
+ try {
3167
+ if (input.signal?.aborted) return createSnapshotFailure("GIT_OPERATION_ABORTED");
3168
+ const result = instructions !== void 0 ? await input.operation(reader, input.signal, instructions) : input.signal === void 0 ? await input.operation(reader) : await input.operation(reader, input.signal);
3169
+ if (input.signal?.aborted) return createSnapshotFailure("GIT_OPERATION_ABORTED");
3170
+ return Object.freeze({
3171
+ kind: "completed",
3172
+ result
3173
+ });
3174
+ } catch (error) {
3175
+ if (input.signal?.aborted) return createSnapshotFailure("GIT_OPERATION_ABORTED");
3176
+ if (!isSnapshotChanged(error)) throw error;
3177
+ }
3178
+ }
3179
+ return createSnapshotFailure("WORKING_TREE_UNSTABLE");
3180
+ };
3181
+ return executeSnapshot;
3182
+ };
3183
+ var executeWorkingTreeSnapshot = createWorkingTreeSnapshotExecutor();
3184
+ //#endregion
3185
+ //#region src/cli-execution/results.ts
3186
+ var measureOutput = (output) => Buffer.byteLength(output, "utf8");
3187
+ var measurePagedOutput = (page, serializedRecordsUtf8Bytes, isJson, formatJson, formatHuman) => {
3188
+ if (!isJson) return measureOutput(formatHuman(page));
3189
+ return measureOutput(formatJson(Object.freeze({
3190
+ cursor: page.cursor,
3191
+ records: Object.freeze([])
3192
+ }))) - 2 + serializedRecordsUtf8Bytes;
3193
+ };
3194
+ var createMoldeaCliCompositionExecutionResult = (result, cliVersion, isJson) => Object.freeze({
3195
+ exitCode: MOLDEA_CLI_EXIT_CODES.Success,
3196
+ stderr: "",
3197
+ stdout: isJson ? formatMoldeaCliJsonCompositionResult(result, cliVersion) : formatMoldeaCliHumanCompositionResult(result, cliVersion)
3198
+ });
3199
+ var createMoldeaCliErrorResult = (error, command, cliVersion, isJson, exitCode) => Object.freeze(isJson ? {
3200
+ exitCode,
3201
+ stderr: "",
3202
+ stdout: formatMoldeaCliJsonError(error, command, cliVersion)
3203
+ } : {
3204
+ exitCode,
3205
+ stderr: formatMoldeaCliHumanError(error),
3206
+ stdout: ""
3207
+ });
3208
+ var createMoldeaCliValidateExecutionResult = (inspection, cliVersion, isJson, cursor, maxOutputBytes) => {
3209
+ const projection = createMoldeaCliValidateProjection(inspection);
3210
+ const createResult = (page) => ({
3211
+ diagnosticCount: projection.diagnosticCount,
3212
+ acceptedWarningCount: projection.acceptedWarningCount,
3213
+ errorCount: projection.errorCount,
3214
+ formatVersion: projection.formatVersion,
3215
+ page,
3216
+ snapshotDigest: projection.snapshotDigest,
3217
+ source: projection.source,
3218
+ coverageCounts: projection.coverageCounts,
3219
+ valid: projection.valid,
3220
+ warningCount: projection.warningCount
3221
+ });
3222
+ const page = createMoldeaCliOutputPage({
3223
+ command: "validate",
3224
+ cursor,
3225
+ filters: {},
3226
+ maxOutputBytes,
3227
+ measure: (candidate, serializedRecordsUtf8Bytes) => measurePagedOutput(candidate, serializedRecordsUtf8Bytes, isJson, (page) => formatMoldeaCliJsonValidateResult(createResult(page), cliVersion), (page) => formatMoldeaCliHumanValidateResult(createResult(page))),
3228
+ records: projection.records,
3229
+ snapshotDigest: projection.snapshotDigest
3230
+ });
3231
+ const result = Object.freeze(createResult(page));
3232
+ assertMoldeaCliJsonResultIsContentFree(result);
3233
+ return Object.freeze({
3234
+ exitCode: result.valid ? MOLDEA_CLI_EXIT_CODES.Success : MOLDEA_CLI_EXIT_CODES.StructuralInvalid,
3235
+ stderr: "",
3236
+ stdout: isJson ? formatMoldeaCliJsonValidateResult(result, cliVersion) : formatMoldeaCliHumanValidateResult(result)
3237
+ });
3238
+ };
3239
+ var createMoldeaCliInspectExecutionResult = (inspection, cliVersion, isJson, cursor, maxOutputBytes) => {
3240
+ const projection = createMoldeaCliInspectProjection(inspection);
3241
+ const createResult = (page) => ({
3242
+ counts: projection.counts,
3243
+ formatVersion: projection.formatVersion,
3244
+ page,
3245
+ project: projection.project,
3246
+ snapshotDigest: projection.snapshotDigest,
3247
+ source: projection.source,
3248
+ coverageCounts: projection.coverageCounts,
3249
+ valid: projection.valid,
3250
+ view: projection.view
3251
+ });
3252
+ const page = createMoldeaCliOutputPage({
3253
+ command: "inspect",
3254
+ cursor,
3255
+ filters: {},
3256
+ maxOutputBytes,
3257
+ measure: (candidate, serializedRecordsUtf8Bytes) => measurePagedOutput(candidate, serializedRecordsUtf8Bytes, isJson, (page) => formatMoldeaCliJsonInspectResult(createResult(page), cliVersion), (page) => formatMoldeaCliHumanInspectResult(createResult(page))),
3258
+ records: projection.records,
3259
+ sourceCursorForRecord: projection.getSourceCursor,
3260
+ snapshotDigest: projection.snapshotDigest
3261
+ });
3262
+ const result = Object.freeze(createResult(page));
3263
+ assertMoldeaCliJsonResultIsContentFree(result);
3264
+ return Object.freeze({
3265
+ exitCode: inspection.valid ? MOLDEA_CLI_EXIT_CODES.Success : MOLDEA_CLI_EXIT_CODES.StructuralInvalid,
3266
+ stderr: "",
3267
+ stdout: isJson ? formatMoldeaCliJsonInspectResult(result, cliVersion) : formatMoldeaCliHumanInspectResult(result)
3268
+ });
3269
+ };
3270
+ var createMoldeaCliScopeExecutionResult = (execution, cliVersion, isJson, cursor, maxOutputBytes) => {
3271
+ const projection = createMoldeaCliScopeProjection(execution);
3272
+ const createResult = (page) => ({
3273
+ counts: projection.counts,
3274
+ inputDigest: projection.inputDigest,
3275
+ manifestDigest: projection.manifestDigest,
3276
+ page,
3277
+ relevant: projection.relevant,
3278
+ snapshotDigest: projection.snapshotDigest,
3279
+ source: MOLDEA_CLI_GIT_WORKING_TREE_SOURCE,
3280
+ valid: projection.valid
3281
+ });
3282
+ const page = createMoldeaCliOutputPage({
3283
+ command: "scope",
3284
+ cursor,
3285
+ filters: { inputDigest: projection.inputDigest },
3286
+ maxOutputBytes,
3287
+ measure: (candidate, serializedRecordsUtf8Bytes) => measurePagedOutput(candidate, serializedRecordsUtf8Bytes, isJson, (page) => formatMoldeaCliJsonScopeResult(createResult(page), cliVersion), (page) => formatMoldeaCliHumanScopeResult(createResult(page))),
3288
+ records: projection.records,
3289
+ snapshotDigest: projection.snapshotDigest
3290
+ });
3291
+ const result = Object.freeze(createResult(page));
3292
+ assertMoldeaCliJsonResultIsContentFree(result, projection.canonicalBodies);
3293
+ return Object.freeze({
3294
+ exitCode: projection.valid ? MOLDEA_CLI_EXIT_CODES.Success : MOLDEA_CLI_EXIT_CODES.StructuralInvalid,
3295
+ stderr: "",
3296
+ stdout: isJson ? formatMoldeaCliJsonScopeResult(result, cliVersion) : formatMoldeaCliHumanScopeResult(result)
3297
+ });
3298
+ };
3299
+ var createMoldeaCliContentExecutionResult = (pageResult, cliVersion, isJson, cursor, maxOutputBytes) => {
3300
+ const result = createMoldeaCliContentPage({
3301
+ cursor,
3302
+ maxOutputBytes,
3303
+ measure: (candidate) => measureOutput(isJson ? formatMoldeaCliJsonContentResult(candidate, cliVersion) : formatMoldeaCliHumanContentResult(candidate)),
3304
+ page: pageResult
3305
+ });
3306
+ return Object.freeze({
3307
+ exitCode: MOLDEA_CLI_EXIT_CODES.Success,
3308
+ stderr: "",
3309
+ stdout: isJson ? formatMoldeaCliJsonContentResult(result, cliVersion) : formatMoldeaCliHumanContentResult(result)
3310
+ });
3311
+ };
3312
+ //#endregion
3313
+ //#region src/cli-execution/command-executor.ts
3314
+ var executeLazyCoreInspection = async (input) => {
3315
+ const { executeMoldeaCliCoreInspection } = await import("./chunk-c13db66a.mjs");
3316
+ return executeMoldeaCliCoreInspection(input);
3317
+ };
3318
+ var loadInstalledComposition = async (input) => {
3319
+ const { resolveInstalledMoldeaCliComposition } = await import("./chunk-90403e67.mjs");
3320
+ return resolveInstalledMoldeaCliComposition(input);
3321
+ };
3322
+ var createOperationalErrorResult = (code, input, details) => createMoldeaCliErrorResult(createMoldeaCliOwnedError(code, details), input.invocation.command, input.packageMetadata.version, input.invocation.options.isJson, MOLDEA_CLI_EXIT_CODES.OperationalError);
3323
+ var createMoldeaCliCommandExecutor = (workingTreeDiscovery = discoverGitWorkingTree, workingTreeSnapshotExecutor = executeWorkingTreeSnapshot, coreInspectionExecutor = executeLazyCoreInspection, compositionLoader = loadInstalledComposition, projectScopeExecutor = executeMoldeaCliProjectScope, projectContentExecutor = executeMoldeaCliProjectContent) => {
3324
+ return async (input) => {
3325
+ const command = input.invocation.command;
3326
+ const options = input.invocation.options;
3327
+ try {
3328
+ if (command === MOLDEA_CLI_COMMANDS.Composition || command === MOLDEA_CLI_COMMANDS.Inspect || command === MOLDEA_CLI_COMMANDS.Validate) {
3329
+ const compositionResolution = await compositionLoader({
3330
+ packageMetadata: input.packageMetadata,
3331
+ ...input.signal === void 0 ? {} : { signal: input.signal }
3332
+ });
3333
+ if (compositionResolution.kind === "invalid") return createOperationalErrorResult("COMPOSITION_STATE_INVALID", input);
3334
+ if (command === MOLDEA_CLI_COMMANDS.Composition) return createMoldeaCliCompositionExecutionResult(compositionResolution.result, input.packageMetadata.version, options.isJson);
3335
+ }
3336
+ let scopePaths = null;
3337
+ let contentPath = null;
3338
+ let contentOffset = 0;
3339
+ const inspectionCursor = command === MOLDEA_CLI_COMMANDS.Inspect && options.cursor !== null ? decodeMoldeaCliCursor({
3340
+ command: "inspect",
3341
+ cursor: options.cursor,
3342
+ filters: {}
3343
+ }).sourceCursor : null;
3344
+ if (command === MOLDEA_CLI_COMMANDS.Scope) {
3345
+ if (options.pathsInput === "path" && options.path !== null) scopePaths = Object.freeze([options.path]);
3346
+ else if (options.pathsInput === "stdin" && input.stdin !== void 0) {
3347
+ if (input.stdin.byteLength > options.resourceLimits.maxTotalBytes) return createOperationalErrorResult("RESOURCE_LIMIT_EXCEEDED", input);
3348
+ scopePaths = parseMoldeaCliScopePathBytes(input.stdin, options.resourceLimits.maxEntries);
3349
+ } else return createOperationalErrorResult("PATH_INPUT_INVALID", input);
3350
+ if (scopePaths.some((path) => !isRepositoryPath(path))) return createOperationalErrorResult("PATH_INPUT_INVALID", input);
3351
+ }
3352
+ if (command === MOLDEA_CLI_COMMANDS.Content) {
3353
+ if (options.path === null) return createOperationalErrorResult("CONTENT_PATH_INVALID", input);
3354
+ contentPath = parseMoldeaCliCanonicalContentPath(options.path);
3355
+ if (options.cursor !== null) {
3356
+ const sourceCursor = decodeMoldeaCliCursor({
3357
+ command: "content",
3358
+ cursor: options.cursor,
3359
+ filters: { path: contentPath }
3360
+ }).sourceCursor;
3361
+ const match = sourceCursor === null ? null : /^byte:(0|[1-9][0-9]*)$/u.exec(sourceCursor);
3362
+ if (match === null) throw new MoldeaCliOutputPageException("CURSOR_INVALID");
3363
+ contentOffset = Number(match[1]);
3364
+ if (!Number.isSafeInteger(contentOffset)) throw new MoldeaCliOutputPageException("CURSOR_INVALID");
3365
+ }
3366
+ }
3367
+ const discoveryResult = await workingTreeDiscovery({
3368
+ invocationDirectory: input.invocationDirectory,
3369
+ repositoryDirectory: options.repositoryDirectory,
3370
+ ...input.signal === void 0 ? {} : { signal: input.signal }
3371
+ });
3372
+ if (discoveryResult.kind === "failed") return createOperationalErrorResult(discoveryResult.errorCode, input);
3373
+ const resourceLimits = options.resourceLimits;
3374
+ const snapshotResult = await workingTreeSnapshotExecutor({
3375
+ operation: async (repository, signal, instructions) => {
3376
+ if (command === MOLDEA_CLI_COMMANDS.Scope && scopePaths !== null) return projectScopeExecutor({
3377
+ paths: scopePaths,
3378
+ repository,
3379
+ resourceLimits,
3380
+ ...signal === void 0 ? {} : { signal }
3381
+ });
3382
+ if (command === MOLDEA_CLI_COMMANDS.Content && contentPath !== null) return projectContentExecutor({
3383
+ maxBytes: Math.min(resourceLimits.maxFileBytes, resourceLimits.maxTotalBytes, Math.max(1, Math.floor(options.maxOutputBytes / 2))),
3384
+ offset: contentOffset,
3385
+ path: contentPath,
3386
+ repository,
3387
+ resourceLimits,
3388
+ ...signal === void 0 ? {} : { signal }
3389
+ });
3390
+ return coreInspectionExecutor({
3391
+ packageMetadata: input.packageMetadata,
3392
+ command: command === MOLDEA_CLI_COMMANDS.Inspect ? "inspect" : "validate",
3393
+ ...inspectionCursor === null ? {} : { cursor: inspectionCursor },
3394
+ ...instructions === void 0 ? {} : { instructions },
3395
+ repository,
3396
+ resourceLimits,
3397
+ ...signal === void 0 ? {} : { signal }
3398
+ });
3399
+ },
3400
+ repositoryRoot: discoveryResult.repositoryRoot,
3401
+ resourceLimits,
3402
+ ...command === MOLDEA_CLI_COMMANDS.Validate || command === MOLDEA_CLI_COMMANDS.Inspect ? { includeInstructions: true } : {},
3403
+ ...command === MOLDEA_CLI_COMMANDS.Scope ? { selectionPaths: [MOLDEA_MANIFEST_PATH] } : contentPath === null ? {} : { selectionPaths: [contentPath] },
3404
+ ...input.signal === void 0 ? {} : { signal: input.signal }
3405
+ });
3406
+ if (snapshotResult.kind === "failed") return createOperationalErrorResult(snapshotResult.errorCode, input, snapshotResult.subcommand === void 0 ? void 0 : { subcommand: snapshotResult.subcommand });
3407
+ if (command === MOLDEA_CLI_COMMANDS.Validate) return createMoldeaCliValidateExecutionResult(snapshotResult.result, input.packageMetadata.version, options.isJson, options.cursor, options.maxOutputBytes);
3408
+ if (command === MOLDEA_CLI_COMMANDS.Inspect) return createMoldeaCliInspectExecutionResult(snapshotResult.result, input.packageMetadata.version, options.isJson, options.cursor, options.maxOutputBytes);
3409
+ if (command === MOLDEA_CLI_COMMANDS.Scope) return createMoldeaCliScopeExecutionResult(snapshotResult.result, input.packageMetadata.version, options.isJson, options.cursor, options.maxOutputBytes);
3410
+ return createMoldeaCliContentExecutionResult(snapshotResult.result, input.packageMetadata.version, options.isJson, options.cursor, options.maxOutputBytes);
3411
+ } catch (error) {
3412
+ return createMoldeaCliErrorResult(mapMoldeaCliOperationalError(error), command, input.packageMetadata.version, options.isJson, MOLDEA_CLI_EXIT_CODES.OperationalError);
3413
+ }
3414
+ };
3415
+ };
3416
+ var executeMoldeaCliCommand = createMoldeaCliCommandExecutor();
3417
+ //#endregion
3418
+ //#region src/cli-execution/runner.ts
3419
+ var runMoldeaCli = async (options) => {
3420
+ const parseResult = parseMoldeaCliArguments(options.commandLineArguments);
3421
+ if (parseResult.kind === "help") return {
3422
+ exitCode: MOLDEA_CLI_EXIT_CODES.Success,
3423
+ stderr: "",
3424
+ stdout: formatMoldeaCliHelp(parseResult.command)
3425
+ };
3426
+ if (parseResult.kind === "version") return {
3427
+ exitCode: MOLDEA_CLI_EXIT_CODES.Success,
3428
+ stderr: "",
3429
+ stdout: `${options.packageMetadata.version}\n`
3430
+ };
3431
+ if (parseResult.kind === "error") return createMoldeaCliErrorResult(createMoldeaCliOwnedError(parseResult.code), parseResult.command, options.packageMetadata.version, parseResult.isJson, MOLDEA_CLI_EXIT_CODES.UsageError);
3432
+ const executeCommand = options.executeCommand ?? executeMoldeaCliCommand;
3433
+ try {
3434
+ let stdin;
3435
+ if (parseResult.invocation.options.pathsInput === "stdin") {
3436
+ if (options.readStdin === void 0) return createMoldeaCliErrorResult(createMoldeaCliOwnedError("PATH_INPUT_INVALID"), parseResult.invocation.command, options.packageMetadata.version, parseResult.invocation.options.isJson, MOLDEA_CLI_EXIT_CODES.UsageError);
3437
+ const stdinResult = await options.readStdin(parseResult.invocation.options.resourceLimits.maxTotalBytes, options.signal);
3438
+ if (stdinResult.kind === "limit-exceeded") return createMoldeaCliErrorResult(createMoldeaCliOwnedError("RESOURCE_LIMIT_EXCEEDED"), parseResult.invocation.command, options.packageMetadata.version, parseResult.invocation.options.isJson, MOLDEA_CLI_EXIT_CODES.OperationalError);
3439
+ stdin = stdinResult.bytes;
3440
+ }
3441
+ return await executeCommand({
3442
+ invocationDirectory: options.invocationDirectory,
3443
+ invocation: parseResult.invocation,
3444
+ packageMetadata: options.packageMetadata,
3445
+ ...options.signal === void 0 ? {} : { signal: options.signal },
3446
+ ...stdin === void 0 ? {} : { stdin }
3447
+ });
3448
+ } catch {
3449
+ return createMoldeaCliErrorResult(createMoldeaCliOwnedError("INTERNAL_ERROR"), parseResult.invocation.command, options.packageMetadata.version, parseResult.invocation.options.isJson, MOLDEA_CLI_EXIT_CODES.OperationalError);
3450
+ }
3451
+ };
3452
+ require_semver();
3453
+ //#endregion
3454
+ //#region src/bin/index.ts
3455
+ var executableDirectory = path.dirname(fileURLToPath(import.meta.url));
3456
+ path.resolve(executableDirectory, "..", "package.json");
3457
+ var shutdown = createShutdownSignal({ setExitCode: false });
3458
+ var readProcessStdin = async (maxBytes, signal) => {
3459
+ try {
3460
+ return {
3461
+ bytes: await readStdin({
3462
+ maxBytes,
3463
+ signal
3464
+ }),
3465
+ kind: "completed"
3466
+ };
3467
+ } catch (error) {
3468
+ if (hasErrorCode(error, ERRORS$1.STDIN_TOO_LARGE)) return { kind: "limit-exceeded" };
3469
+ if (signal?.aborted === true) return {
3470
+ bytes: new Uint8Array(),
3471
+ kind: "completed"
3472
+ };
3473
+ throw error;
3474
+ }
3475
+ };
3476
+ var writeProcessOutput = async (outputStream, output) => {
3477
+ if (output.length === 0) return;
3478
+ await new Promise((resolve, reject) => {
3479
+ outputStream.write(output, (error) => {
3480
+ if (error) {
3481
+ reject(error);
3482
+ return;
3483
+ }
3484
+ resolve();
3485
+ });
3486
+ });
3487
+ };
3488
+ try {
3489
+ const invocationDirectory = process$1.cwd();
3490
+ const executionResult = await runMoldeaCli({
3491
+ commandLineArguments: process$1.argv.slice(2),
3492
+ invocationDirectory,
3493
+ packageMetadata: {
3494
+ "dependencies": {
3495
+ "@moldea.ai/core": "workspace:^10.0.0",
3496
+ "@moldea.ai/repository": "workspace:^4.0.0",
3497
+ "@moldea.ai/repository-fs": "workspace:^4.0.0",
3498
+ "jg-crypto": "0.3.0",
3499
+ "jg-exception": "1.7.1",
3500
+ "jg-git-commands": "0.4.0",
3501
+ "jg-process": "1.6.2",
3502
+ "jg-utilities": "1.7.2",
3503
+ "semver": "7.8.5"
3504
+ },
3505
+ "installedPackageVersions": {
3506
+ "@moldea.ai/core": "10.0.0",
3507
+ "@moldea.ai/repository": "4.0.1",
3508
+ "@moldea.ai/repository-fs": "4.0.1"
3509
+ },
3510
+ "supportedNodeRange": ">=22.17.0",
3511
+ "version": "14.0.0"
3512
+ },
3513
+ readStdin: readProcessStdin,
3514
+ signal: shutdown.signal
3515
+ });
3516
+ if (shutdown.receivedSignal() === null) {
3517
+ await writeProcessOutput(process$1.stdout, executionResult.stdout);
3518
+ if (shutdown.receivedSignal() === null) await writeProcessOutput(process$1.stderr, executionResult.stderr);
3519
+ }
3520
+ process$1.exitCode = shutdown.exitCode() ?? executionResult.exitCode;
3521
+ } catch {
3522
+ const signalExitCode = shutdown.exitCode();
3523
+ if (signalExitCode === null) await writeProcessOutput(process$1.stderr, formatMoldeaCliHumanError(createMoldeaCliOwnedError("INTERNAL_ERROR"))).catch(() => void 0);
3524
+ process$1.exitCode = signalExitCode ?? 3;
3525
+ } finally {
3526
+ shutdown.dispose();
3527
+ }
3528
+ //#endregion
3529
+ export {};