@moldea.ai/cli 12.0.0 → 13.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.
@@ -1,8 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import process$1 from "node:process";
3
- import { createHash, timingSafeEqual } from "node:crypto";
4
- import { execFile, spawn } from "node:child_process";
5
- import { TextDecoder as TextDecoder$1 } from "node:util";
2
+ import { getErrorCode } from "jg-exception";
3
+ import { ERRORS } from "jg-process";
4
+ import { timingSafeEqual } from "node:crypto";
5
+ import { hashValue } from "jg-crypto";
6
+ import { deepFreeze, stringifyJsonDeterministically, takeWithinByteBudget } from "jg-utilities";
7
+ import { ERRORS as ERRORS$1, assertGitSucceeded, readGitVersion, runGit } from "jg-git-commands";
6
8
  import { SUPPORTED_REPOSITORY_FORMAT_VERSIONS } from "@moldea.ai/core";
7
9
  //#region \0rolldown/runtime.js
8
10
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
@@ -54,59 +56,6 @@ var MoldeaCliOutputPageException = class extends Error {
54
56
  }
55
57
  };
56
58
  //#endregion
57
- //#region src/json-serialization/serializer.ts
58
- /** Compares strings by Unicode code point rather than UTF-16 code unit. */
59
- var compareUnicodeCodePoints = (left, right) => {
60
- const leftCodePoints = [...left];
61
- const rightCodePoints = [...right];
62
- const sharedLength = Math.min(leftCodePoints.length, rightCodePoints.length);
63
- for (let index = 0; index < sharedLength; index += 1) {
64
- const leftCodePoint = leftCodePoints[index]?.codePointAt(0);
65
- const rightCodePoint = rightCodePoints[index]?.codePointAt(0);
66
- if (leftCodePoint === void 0 || rightCodePoint === void 0) throw new TypeError("The JSON object key could not be compared.");
67
- if (leftCodePoint !== rightCodePoint) return leftCodePoint - rightCodePoint;
68
- }
69
- return leftCodePoints.length - rightCodePoints.length;
70
- };
71
- /** Serializes one validated JSON value with recursively sorted object keys. */
72
- var serializeJsonValue = (value, ancestors) => {
73
- if (value === null || typeof value === "boolean" || typeof value === "string") return JSON.stringify(value);
74
- if (typeof value === "number") {
75
- if (!Number.isFinite(value)) throw new TypeError("The JSON number must be finite.");
76
- return JSON.stringify(Object.is(value, -0) ? 0 : value);
77
- }
78
- if (typeof value !== "object") throw new TypeError("The value is not supported by the CLI JSON contract.");
79
- if (ancestors.has(value)) throw new TypeError("The CLI JSON value must not contain a cycle.");
80
- ancestors.add(value);
81
- try {
82
- if (Array.isArray(value)) {
83
- const serializedEntries = [];
84
- for (let index = 0; index < value.length; index += 1) {
85
- if (!Object.hasOwn(value, index)) throw new TypeError("The CLI JSON array must not contain empty slots.");
86
- serializedEntries.push(serializeJsonValue(value[index], ancestors));
87
- }
88
- return `[${serializedEntries.join(",")}]`;
89
- }
90
- const prototype = Object.getPrototypeOf(value);
91
- if (prototype !== Object.prototype && prototype !== null) throw new TypeError("The CLI JSON object must be a plain record.");
92
- if (Object.getOwnPropertySymbols(value).length > 0) throw new TypeError("The CLI JSON object must not contain symbol keys.");
93
- const record = value;
94
- return `{${Object.keys(record).sort(compareUnicodeCodePoints).map((key) => `${JSON.stringify(key)}:${serializeJsonValue(record[key], ancestors)}`).join(",")}}`;
95
- } finally {
96
- ancestors.delete(value);
97
- }
98
- };
99
- /**
100
- * Serializes one CLI JSON value with exact recursive Unicode code-point key ordering.
101
- * @param value The closed JSON value to serialize.
102
- * @returns Compact deterministic JSON without a trailing line feed.
103
- * @throws
104
- * - If the value contains unsupported, non-finite, symbolic, class-backed, or cyclic data
105
- */
106
- var serializeJsonDeterministically = (value) => {
107
- return serializeJsonValue(value, /* @__PURE__ */ new Set());
108
- };
109
- //#endregion
110
59
  //#region src/output-page/cursor.ts
111
60
  var SHA256_PATTERN = /^sha256:[0-9a-f]{64}$/u;
112
61
  var BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/u;
@@ -121,7 +70,7 @@ var CURSOR_DOCUMENT_KEYS = Object.freeze([
121
70
  ]);
122
71
  /** Calculates one stable SHA-256 identifier for deterministic JSON text. */
123
72
  var calculateMoldeaCliJsonDigest = (value) => {
124
- return `sha256:${createHash("sha256").update(serializeJsonDeterministically(value), "utf8").digest("hex")}`;
73
+ return `sha256:${hashValue(stringifyJsonDeterministically(value, { strict: true }))}`;
125
74
  };
126
75
  /** Calculates the checksum for one cursor payload without its checksum field. */
127
76
  var calculateCursorChecksum = (payload) => {
@@ -154,7 +103,7 @@ var encodeMoldeaCliCursor = (command, filters, snapshotDigest, lastKey, sourceCu
154
103
  ...payload,
155
104
  checksum: calculateCursorChecksum(payload)
156
105
  };
157
- return Buffer.from(serializeJsonDeterministically(document), "utf8").toString("base64url");
106
+ return Buffer.from(stringifyJsonDeterministically(document, { strict: true }), "utf8").toString("base64url");
158
107
  };
159
108
  /**
160
109
  * Decodes and validates one opaque continuation cursor.
@@ -223,56 +172,29 @@ var createMoldeaCliOutputPage = (input) => {
223
172
  if (input.measure(emptyPage, 2) > input.maxOutputBytes) throw new MoldeaCliOutputPageException("OUTPUT_BUDGET_TOO_SMALL");
224
173
  return emptyPage;
225
174
  }
226
- const selectedRecords = [];
227
- let selectedCursor = null;
228
- let serializedRecordsUtf8Bytes = 2;
229
- for (let endIndex = startIndex + 1; endIndex <= input.records.length; endIndex += 1) {
230
- const record = input.records[endIndex - 1];
231
- if (record === void 0) throw new TypeError("An output page record is missing.");
232
- const serializedRecordUtf8Bytes = Buffer.byteLength(serializeJsonDeterministically(record), "utf8");
233
- serializedRecordsUtf8Bytes += serializedRecordUtf8Bytes + (endIndex > startIndex + 1 ? 1 : 0);
234
- selectedRecords.push(record);
175
+ /** Creates the cursor that continues after a page ending with the record at this end index. */
176
+ const createCursor = (record, endIndex) => {
235
177
  const sourceCursor = input.sourceCursorForRecord?.(record) ?? null;
236
- const cursor = (input.sourceCursorForRecord === void 0 ? endIndex < input.records.length : sourceCursor !== null) ? encodeMoldeaCliCursor(input.command, input.filters, input.snapshotDigest, record.key, sourceCursor) : null;
237
- const candidate = Object.freeze({
238
- cursor,
239
- records: selectedRecords
240
- });
241
- if (input.measure(candidate, serializedRecordsUtf8Bytes) > input.maxOutputBytes) {
242
- selectedRecords.pop();
243
- break;
244
- }
245
- selectedCursor = cursor;
246
- }
247
- if (selectedRecords.length === 0) throw new MoldeaCliOutputPageException("OUTPUT_BUDGET_TOO_SMALL");
178
+ return (input.sourceCursorForRecord === void 0 ? endIndex < input.records.length : sourceCursor !== null) ? encodeMoldeaCliCursor(input.command, input.filters, input.snapshotDigest, record.key, sourceCursor) : null;
179
+ };
180
+ const selectedRecords = takeWithinByteBudget(input.records.slice(startIndex), {
181
+ maxBytes: input.maxOutputBytes,
182
+ measurePage: (page, itemsBytes) => input.measure(Object.freeze({
183
+ cursor: createCursor(page[page.length - 1], startIndex + page.length),
184
+ records: page
185
+ }), itemsBytes)
186
+ });
187
+ const lastRecord = selectedRecords[selectedRecords.length - 1];
188
+ if (lastRecord === void 0) throw new MoldeaCliOutputPageException("OUTPUT_BUDGET_TOO_SMALL");
248
189
  return Object.freeze({
249
- cursor: selectedCursor,
250
- records: Object.freeze([...selectedRecords])
190
+ cursor: createCursor(lastRecord, startIndex + selectedRecords.length),
191
+ records: Object.freeze(selectedRecords)
251
192
  });
252
193
  };
253
194
  //#endregion
254
195
  //#region src/command-line/validations.ts
255
196
  var POSITIVE_INTEGER_PATTERN = /^\d+$/u;
256
197
  /**
257
- * Determines whether text contains only Unicode scalar values.
258
- * @param text The text to validate.
259
- * @returns Whether the text contains no unpaired UTF-16 surrogate.
260
- */
261
- var hasOnlyUnicodeScalarValues = (text) => {
262
- for (let index = 0; index < text.length; index += 1) {
263
- const codeUnit = text.charCodeAt(index);
264
- if (codeUnit >= 55296 && codeUnit <= 56319) {
265
- if (index + 1 >= text.length) return false;
266
- const trailingCodeUnit = text.charCodeAt(index + 1);
267
- if (trailingCodeUnit < 56320 || trailingCodeUnit > 57343) return false;
268
- index += 1;
269
- continue;
270
- }
271
- if (codeUnit >= 56320 && codeUnit <= 57343) return false;
272
- }
273
- return true;
274
- };
275
- /**
276
198
  * Parses one strict base-10 positive safe integer option value.
277
199
  * @param input The untrusted command-line token.
278
200
  * @returns The parsed integer, or null when the token is invalid.
@@ -301,11 +223,11 @@ var areMoldeaCliResourceLimitsConsistent = (limits) => {
301
223
  * @returns Whether the token is non-empty scalar text without NUL.
302
224
  */
303
225
  var isRepositoryDirectoryInputValid = (input) => {
304
- return input.length > 0 && !input.includes("\0") && hasOnlyUnicodeScalarValues(input);
226
+ return input.length > 0 && !input.includes("\0") && input.isWellFormed();
305
227
  };
306
228
  /** Determines whether one opaque cursor token is bounded safe scalar text. */
307
229
  var isMoldeaCliCursorInputValid = (input) => {
308
- return input.length > 0 && input.length <= 16384 && !input.includes("\0") && hasOnlyUnicodeScalarValues(input);
230
+ return input.length > 0 && input.length <= 16384 && !input.includes("\0") && input.isWellFormed();
309
231
  };
310
232
  //#endregion
311
233
  //#region src/command-line/parser.ts
@@ -666,8 +588,8 @@ var createMoldeaCliJsonEnvelope = (input) => Object.freeze({
666
588
  schemaVersion: 7,
667
589
  status: input.status
668
590
  });
669
- /** Serializes one schema 7 envelope with its required trailing line feed. */
670
- var serializeMoldeaCliJsonEnvelope = (input) => `${serializeJsonDeterministically(createMoldeaCliJsonEnvelope(input))}\n`;
591
+ /** Serializes one schema 7 envelope, keys in RFC 8785 order, with its trailing line feed. */
592
+ var serializeMoldeaCliJsonEnvelope = (input) => `${stringifyJsonDeterministically(createMoldeaCliJsonEnvelope(input), { strict: true })}\n`;
671
593
  //#endregion
672
594
  //#region src/presentation/formatters.ts
673
595
  var DIAGNOSTIC_ENTITY_KEYS = [
@@ -941,346 +863,114 @@ var createMoldeaCliInspectProjection = (inspection) => {
941
863
  });
942
864
  };
943
865
  //#endregion
944
- //#region src/git-process/constants.ts
945
- var GIT_PROCESS_GLOBAL_ARGUMENTS = [
946
- "--no-pager",
947
- "-c",
948
- "color.ui=false",
949
- "-c",
950
- "core.fsmonitor=false",
951
- "-c",
952
- "submodule.recurse=false"
953
- ];
954
- var MAX_GIT_PROCESS_DIAGNOSTIC_BYTES = 4096;
955
- var GIT_PROCESS_REMOVED_ENVIRONMENT_NAMES = [
956
- "GIT_DIR",
957
- "GIT_WORK_TREE",
958
- "GIT_INDEX_FILE",
959
- "GIT_OBJECT_DIRECTORY",
960
- "GIT_ALTERNATE_OBJECT_DIRECTORIES",
961
- "GIT_COMMON_DIR",
962
- "GIT_CEILING_DIRECTORIES",
963
- "GIT_DISCOVERY_ACROSS_FILESYSTEM",
964
- "GIT_NAMESPACE",
965
- "GIT_SHALLOW_FILE",
966
- "GIT_ATTR_SOURCE",
967
- "GIT_CONFIG",
968
- "GIT_CONFIG_SYSTEM",
969
- "GIT_CONFIG_GLOBAL",
970
- "GIT_CONFIG_NOSYSTEM",
971
- "GIT_CONFIG_PARAMETERS",
972
- "GIT_CONFIG_COUNT",
973
- "GIT_EXEC_PATH",
974
- "GIT_LITERAL_PATHSPECS",
975
- "GIT_GLOB_PATHSPECS",
976
- "GIT_NOGLOB_PATHSPECS",
977
- "GIT_ICASE_PATHSPECS"
978
- ];
979
- var GIT_PROCESS_REMOVED_ENVIRONMENT_PREFIXES = [
980
- "GIT_CONFIG_KEY_",
981
- "GIT_CONFIG_VALUE_",
982
- "GIT_TRACE"
983
- ];
984
- var GIT_PROCESS_ENVIRONMENT_OVERRIDES = Object.freeze({
985
- LC_ALL: "C",
986
- LANG: "C",
987
- LANGUAGE: "C",
988
- GIT_OPTIONAL_LOCKS: "0",
989
- GIT_PAGER: "",
990
- PAGER: "",
991
- GIT_TERMINAL_PROMPT: "0",
992
- NO_COLOR: "1"
866
+ //#region src/git-command/utilities.ts
867
+ /** Creates one immutable Git failure. */
868
+ var createGitFailure = (reason) => Object.freeze({
869
+ kind: "failed",
870
+ reason
993
871
  });
994
- //#endregion
995
- //#region src/git-process/environment.ts
996
- var REMOVED_ENVIRONMENT_NAMES = new Set(GIT_PROCESS_REMOVED_ENVIRONMENT_NAMES.map((name) => name.toUpperCase()));
997
872
  /**
998
- * Determines whether an inherited environment variable can alter Git behavior.
999
- * @param name The environment variable name.
1000
- * @returns Whether the variable must be removed.
873
+ * Classifies one Git error by its code, without retaining its diagnostics.
874
+ * @param error The error a Git command or read rejected with.
875
+ * @param signal The command's cancellation signal, whose abort takes precedence.
876
+ * @returns The failure reason.
1001
877
  */
1002
- var isRemovedEnvironmentVariable = (name) => {
1003
- const normalizedName = name.toUpperCase();
1004
- return REMOVED_ENVIRONMENT_NAMES.has(normalizedName) || GIT_PROCESS_REMOVED_ENVIRONMENT_PREFIXES.some((prefix) => normalizedName.startsWith(prefix));
878
+ var classifyGitFailure = (error, signal) => {
879
+ if (signal?.aborted === true) return "aborted";
880
+ switch (getErrorCode(error)) {
881
+ case ERRORS$1.GIT_NOT_FOUND: return "not-found";
882
+ case ERRORS$1.GIT_REPOSITORY_NOT_FOUND: return "repository-not-found";
883
+ case ERRORS$1.GIT_ACCESS_DENIED: return "access-denied";
884
+ case ERRORS$1.GIT_OUTPUT_INVALID: return "output-invalid";
885
+ case ERRORS.PROCESS_OUTPUT_TOO_LARGE: return "output-limit-exceeded";
886
+ case ERRORS.PROCESS_START_FAILED: {
887
+ const causeCode = getErrorCode(error.cause);
888
+ return causeCode === "EACCES" || causeCode === "EPERM" ? "access-denied" : "command-failed";
889
+ }
890
+ default: return "command-failed";
891
+ }
1005
892
  };
1006
893
  /**
1007
- * Creates the immutable, deterministic environment used by Git subprocesses.
1008
- * @param environment The host environment to sanitize.
1009
- * @returns A frozen environment that preserves unrelated variables.
894
+ * Runs one typed Git read and turns its rejection into a failure reason.
895
+ * @param read The read, such as one of jg-git-commands' typed commands.
896
+ * @param signal The read's cancellation signal.
897
+ * @returns A promise resolving to the read's value, or why it failed.
1010
898
  */
1011
- var createGitProcessEnvironment = (environment) => {
1012
- const sanitizedEnvironment = {};
1013
- for (const [name, environmentValue] of Object.entries(environment)) if (environmentValue !== void 0 && !isRemovedEnvironmentVariable(name) && !(name.toUpperCase() in GIT_PROCESS_ENVIRONMENT_OVERRIDES)) sanitizedEnvironment[name] = environmentValue;
1014
- return Object.freeze({
1015
- ...sanitizedEnvironment,
1016
- ...GIT_PROCESS_ENVIRONMENT_OVERRIDES
1017
- });
899
+ var readGit = async (read, signal) => {
900
+ try {
901
+ return Object.freeze({
902
+ kind: "completed",
903
+ value: await read()
904
+ });
905
+ } catch (error) {
906
+ return createGitFailure(classifyGitFailure(error, signal));
907
+ }
1018
908
  };
1019
- //#endregion
1020
- //#region src/git-process/utilities.ts
1021
909
  /**
1022
- * Classifies a subprocess error without retaining provider diagnostics.
1023
- * @param error The Node.js subprocess error, or null for a nonzero exit.
1024
- * @param stderr The bounded process diagnostic used only for classification.
1025
- * @returns The normalized failure reason.
910
+ * Checks one finished Git command. Git exits with 0 after warning on stderr that it skipped
911
+ * something, so any diagnostic fails a command that otherwise succeeded.
912
+ * @param result The command's result, as bytes.
913
+ * @param subcommand The Git subcommand that ran.
914
+ * @returns Why the command failed, or null when it succeeded without diagnostics.
1026
915
  */
1027
- var classifyGitProcessError = (error, stderr) => {
1028
- const errorCode = error instanceof Error && "code" in error && typeof error.code === "string" ? error.code.toUpperCase() : "";
1029
- if (errorCode === "ENOENT") return "not-found";
1030
- if (errorCode === "EACCES" || errorCode === "EPERM") return "access-denied";
1031
- if (errorCode === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") return "output-limit-exceeded";
1032
- const diagnostic = new TextDecoder().decode(stderr);
1033
- if (diagnostic.startsWith("fatal: not a git repository")) return "repository-not-found";
1034
- if (diagnostic.startsWith("fatal: detected dubious ownership in repository at ") || diagnostic.startsWith("fatal: ") && /: Permission denied(?:\r?\n)?$/u.test(diagnostic)) return "access-denied";
1035
- return "command-failed";
916
+ var checkGitResult = (result, subcommand) => {
917
+ if (result.stderr.byteLength > 4096) return "output-invalid";
918
+ try {
919
+ assertGitSucceeded(result, subcommand);
920
+ } catch (error) {
921
+ return classifyGitFailure(error);
922
+ }
923
+ return result.stderr.byteLength === 0 ? null : "output-invalid";
1036
924
  };
1037
925
  //#endregion
1038
- //#region src/git-process/executor.ts
926
+ //#region src/git-command/run-git-command.ts
1039
927
  /**
1040
- * Executes Git directly with trusted arguments, a sanitized environment, and bounded output.
1041
- * @param options The trusted arguments, environment, output limit, and optional signal.
1042
- * @returns A promise that resolves to normalized process output or failure.
928
+ * Runs one read-only Git command through jg-git-commands, bounded by the caller's combined output
929
+ * limit and the CLI's timeout, and refuses any stderr.
930
+ * @param args The command's trusted arguments, its subcommand first.
931
+ * @param options The working directory, output limit, stdin, and cancellation.
932
+ * @returns A promise resolving to the command's stdout, or why it failed.
1043
933
  */
1044
- var executeGitProcess = async (options) => new Promise((resolve) => {
1045
- if (options.signal?.aborted) {
1046
- resolve(Object.freeze({
1047
- kind: "failed",
1048
- reason: "aborted"
1049
- }));
1050
- return;
1051
- }
1052
- execFile("git", [...GIT_PROCESS_GLOBAL_ARGUMENTS, ...options.arguments], {
934
+ var runGitCommand = async (args, { cwd, input, maxOutputBytes, signal }) => {
935
+ const execution = await readGit(() => runGit(args, {
936
+ cwd,
1053
937
  encoding: "buffer",
1054
- env: createGitProcessEnvironment(options.environment ?? process$1.env),
1055
- maxBuffer: options.maxBufferBytes,
1056
- shell: false,
1057
- ...options.signal === void 0 ? {} : { signal: options.signal },
1058
- windowsHide: true
1059
- }, (error, stdout, stderr) => {
1060
- if (options.signal?.aborted) {
1061
- resolve(Object.freeze({
1062
- kind: "failed",
1063
- reason: "aborted"
1064
- }));
1065
- return;
1066
- }
1067
- if (error) {
1068
- resolve(Object.freeze({
1069
- kind: "failed",
1070
- reason: classifyGitProcessError(error, stderr)
1071
- }));
1072
- return;
1073
- }
1074
- resolve(Object.freeze({
1075
- kind: "completed",
1076
- stdout: Uint8Array.from(stdout),
1077
- stderr: Uint8Array.from(stderr)
1078
- }));
1079
- });
1080
- });
1081
- //#endregion
1082
- //#region src/git-process/streaming-executor.ts
1083
- /** Concatenates the bounded stderr chunks retained for classification. */
1084
- var concatenateChunks = (chunks, byteLength) => Uint8Array.from(Buffer.concat(chunks, byteLength));
1085
- /**
1086
- * Executes Git directly while consuming bounded stdout incrementally.
1087
- * @param options The trusted arguments, optional stdin and signal, consumer, environment, and limits.
1088
- * @returns A promise that resolves to a normalized streamed process result.
1089
- */
1090
- var executeGitStreamingProcess = async (options) => new Promise((resolve, reject) => {
1091
- if (options.signal?.aborted) {
1092
- resolve(Object.freeze({
1093
- kind: "failed",
1094
- reason: "aborted"
1095
- }));
1096
- return;
1097
- }
1098
- const stdin = options.stdin === void 0 ? null : Uint8Array.from(options.stdin);
1099
- const stderrChunks = [];
1100
- let failureReason = null;
1101
- let isSettled = false;
1102
- let stderrBytes = 0;
1103
- let stdoutBytes = 0;
1104
- const childProcess = spawn("git", [...GIT_PROCESS_GLOBAL_ARGUMENTS, ...options.arguments], {
1105
- env: createGitProcessEnvironment(options.environment ?? process$1.env),
1106
- shell: false,
1107
- ...options.signal === void 0 ? {} : { signal: options.signal },
1108
- stdio: [
1109
- stdin === null ? "ignore" : "pipe",
1110
- "pipe",
1111
- "pipe"
1112
- ],
1113
- windowsHide: true
1114
- });
1115
- const { stderr, stdout } = childProcess;
1116
- if (stderr === null || stdout === null) {
1117
- childProcess.on("error", () => void 0);
1118
- childProcess.kill();
1119
- resolve(Object.freeze({
1120
- kind: "failed",
1121
- reason: "command-failed"
1122
- }));
1123
- return;
1124
- }
1125
- stdout.on("data", (chunk) => {
1126
- if (failureReason !== null || isSettled) return;
1127
- if (stdoutBytes + chunk.byteLength > options.maxStdoutBytes) {
1128
- failureReason = "stdout-limit-exceeded";
1129
- childProcess.kill();
1130
- return;
1131
- }
1132
- stdoutBytes += chunk.byteLength;
1133
- try {
1134
- options.consumeStdout(Uint8Array.from(chunk));
1135
- } catch (error) {
1136
- isSettled = true;
1137
- childProcess.kill();
1138
- reject(error instanceof Error ? error : new Error("The Git stdout consumer failed.", { cause: error }));
1139
- }
1140
- });
1141
- stderr.on("data", (chunk) => {
1142
- if (failureReason !== null || isSettled) return;
1143
- if (stderrBytes + chunk.byteLength > options.maxStderrBytes) {
1144
- failureReason = "stderr-limit-exceeded";
1145
- childProcess.kill();
1146
- return;
1147
- }
1148
- stderrBytes += chunk.byteLength;
1149
- stderrChunks.push(chunk);
1150
- });
1151
- childProcess.on("error", (error) => {
1152
- if (failureReason !== null || isSettled) return;
1153
- isSettled = true;
1154
- resolve(Object.freeze({
1155
- kind: "failed",
1156
- reason: options.signal?.aborted ? "aborted" : classifyGitProcessError(error, concatenateChunks(stderrChunks, stderrBytes))
1157
- }));
1158
- });
1159
- childProcess.on("close", (exitCode) => {
1160
- if (isSettled) return;
1161
- isSettled = true;
1162
- if (failureReason !== null) {
1163
- resolve(Object.freeze({
1164
- kind: "failed",
1165
- reason: failureReason
1166
- }));
1167
- return;
1168
- }
1169
- if (options.signal?.aborted) {
1170
- resolve(Object.freeze({
1171
- kind: "failed",
1172
- reason: "aborted"
1173
- }));
1174
- return;
1175
- }
1176
- const stderr = concatenateChunks(stderrChunks, stderrBytes);
1177
- if (exitCode !== 0) {
1178
- resolve(Object.freeze({
1179
- kind: "failed",
1180
- reason: classifyGitProcessError(null, stderr)
1181
- }));
1182
- return;
1183
- }
1184
- resolve(Object.freeze({
1185
- kind: "completed",
1186
- stderr,
1187
- stdoutBytes
1188
- }));
1189
- });
1190
- if (stdin !== null) {
1191
- if (childProcess.stdin === null) {
1192
- failureReason = "command-failed";
1193
- childProcess.kill();
1194
- return;
1195
- }
1196
- childProcess.stdin.on("error", () => {
1197
- if (failureReason !== null || isSettled) return;
1198
- failureReason = "command-failed";
1199
- childProcess.kill();
1200
- });
1201
- try {
1202
- childProcess.stdin.end(stdin);
1203
- } catch {
1204
- failureReason = "command-failed";
1205
- childProcess.kill();
1206
- }
1207
- }
1208
- });
938
+ maxOutputBytes,
939
+ timeoutSeconds: 300,
940
+ ...input === void 0 ? {} : { input },
941
+ ...signal === void 0 ? {} : { signal }
942
+ }), signal);
943
+ if (execution.kind === "failed") return execution;
944
+ const reason = checkGitResult(execution.value, args[0] ?? "");
945
+ return reason === null ? Object.freeze({
946
+ kind: "completed",
947
+ value: execution.value.stdout
948
+ }) : createGitFailure(reason);
949
+ };
1209
950
  //#endregion
1210
951
  //#region src/git-version/constants.ts
1211
952
  var MINIMUM_GIT_VERSION_COMPONENTS = Object.freeze({
1212
953
  major: 2,
1213
- minor: 30,
954
+ minor: 32,
1214
955
  patch: 0
1215
956
  });
1216
957
  var MINIMUM_GIT_VERSION = `${MINIMUM_GIT_VERSION_COMPONENTS.major}.${MINIMUM_GIT_VERSION_COMPONENTS.minor}.${MINIMUM_GIT_VERSION_COMPONENTS.patch}`;
1217
958
  var MAX_GIT_VERSION_OUTPUT_BYTES = 4096;
1218
959
  //#endregion
1219
- //#region src/git-version/parser.ts
1220
- var GIT_VERSION_PATTERN = /^git version (0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:[.-][0-9A-Za-z]+)*(?: \([0-9A-Za-z](?:[0-9A-Za-z ._+/-]*[0-9A-Za-z])?\))?$/;
1221
- var UTF8_DECODER = new TextDecoder$1("utf-8", {
1222
- fatal: true,
1223
- ignoreBOM: true
1224
- });
1225
- /**
1226
- * Decodes one terminated Git version line as strict UTF-8.
1227
- * @param output The bounded stdout bytes from `git --version`.
1228
- * @returns The line without its terminator, or null when invalid.
1229
- */
1230
- var decodeGitVersionLine = (output) => {
1231
- let decodedOutput;
1232
- try {
1233
- decodedOutput = UTF8_DECODER.decode(output);
1234
- } catch {
1235
- return null;
1236
- }
1237
- if (decodedOutput.startsWith("")) return null;
1238
- if (decodedOutput.endsWith("\r\n")) return decodedOutput.slice(0, -2);
1239
- if (decodedOutput.endsWith("\n")) return decodedOutput.slice(0, -1);
1240
- return null;
1241
- };
1242
- /**
1243
- * Parses a strict `git --version` response without accepting arbitrary prose.
1244
- * @param output The bounded stdout bytes from Git.
1245
- * @returns The frozen numeric version, or null when the output is invalid.
1246
- */
1247
- var parseGitVersionOutput = (output) => {
1248
- const versionLine = decodeGitVersionLine(output);
1249
- if (versionLine === null || versionLine.includes("\r") || versionLine.includes("\n")) return null;
1250
- const match = GIT_VERSION_PATTERN.exec(versionLine);
1251
- if (match === null) return null;
1252
- const majorText = match[1];
1253
- const minorText = match[2];
1254
- const patchText = match[3];
1255
- if (majorText === void 0 || minorText === void 0 || patchText === void 0) return null;
1256
- const major = Number(majorText);
1257
- const minor = Number(minorText);
1258
- const patch = Number(patchText);
1259
- if (![
1260
- major,
1261
- minor,
1262
- patch
1263
- ].every(Number.isSafeInteger)) return null;
1264
- return Object.freeze({
1265
- major,
1266
- minor,
1267
- patch
1268
- });
1269
- };
1270
- //#endregion
1271
960
  //#region src/git-version/preflight.ts
1272
961
  /**
1273
- * Maps process failures to stable safe CLI errors.
1274
- * @param reason The normalized subprocess failure reason.
962
+ * Maps Git failures to stable safe CLI errors.
963
+ * @param reason The normalized Git failure reason.
1275
964
  * @returns The public Git error code.
1276
965
  */
1277
- var mapGitProcessFailure = (reason) => {
966
+ var mapGitFailure = (reason) => {
1278
967
  switch (reason) {
1279
968
  case "aborted": return "GIT_OPERATION_ABORTED";
1280
969
  case "not-found": return "GIT_NOT_FOUND";
1281
- case "repository-not-found": return "GIT_COMMAND_FAILED";
1282
970
  case "access-denied": return "GIT_ACCESS_DENIED";
1283
- case "output-limit-exceeded": return "GIT_VERSION_INVALID";
971
+ case "output-limit-exceeded":
972
+ case "output-invalid": return "GIT_VERSION_INVALID";
973
+ case "repository-not-found":
1284
974
  case "command-failed": return "GIT_COMMAND_FAILED";
1285
975
  }
1286
976
  };
@@ -1295,36 +985,27 @@ var isGitVersionSupported = (version) => {
1295
985
  return version.patch >= MINIMUM_GIT_VERSION_COMPONENTS.patch;
1296
986
  };
1297
987
  /**
1298
- * Creates a Git prerequisite check around an injectable process boundary.
1299
- * @param processExecutor The normalized Git subprocess executor.
988
+ * Creates a Git prerequisite check around an injectable typed version read.
989
+ * @param readVersion The installed Git version read.
1300
990
  * @returns A preflight that validates the installed Git version.
1301
991
  */
1302
- var createGitVersionPreflight = (processExecutor = executeGitProcess) => async (signal) => {
1303
- const processResult = await processExecutor({
1304
- arguments: ["--version"],
1305
- maxBufferBytes: MAX_GIT_VERSION_OUTPUT_BYTES,
992
+ var createGitVersionPreflight = (readVersion = readGitVersion) => async (directory, signal) => {
993
+ const versionResult = await readGit(() => readVersion(directory, {
994
+ maxOutputBytes: MAX_GIT_VERSION_OUTPUT_BYTES,
995
+ timeoutSeconds: 300,
1306
996
  ...signal === void 0 ? {} : { signal }
1307
- });
1308
- if (processResult.kind === "failed") return Object.freeze({
1309
- errorCode: mapGitProcessFailure(processResult.reason),
1310
- kind: "failed"
1311
- });
1312
- if (processResult.stderr.byteLength > 0) return Object.freeze({
1313
- errorCode: "GIT_VERSION_INVALID",
997
+ }), signal);
998
+ if (versionResult.kind === "failed") return Object.freeze({
999
+ errorCode: mapGitFailure(versionResult.reason),
1314
1000
  kind: "failed"
1315
1001
  });
1316
- const version = parseGitVersionOutput(processResult.stdout);
1317
- if (version === null) return Object.freeze({
1318
- errorCode: "GIT_VERSION_INVALID",
1319
- kind: "failed"
1320
- });
1321
- if (!isGitVersionSupported(version)) return Object.freeze({
1002
+ if (!isGitVersionSupported(versionResult.value)) return Object.freeze({
1322
1003
  errorCode: "GIT_VERSION_UNSUPPORTED",
1323
1004
  kind: "failed"
1324
1005
  });
1325
1006
  return Object.freeze({
1326
1007
  kind: "supported",
1327
- version
1008
+ version: Object.freeze({ ...versionResult.value })
1328
1009
  });
1329
1010
  };
1330
1011
  //#endregion
@@ -2740,9 +2421,9 @@ var MOLDEA_CLI_FOUNDATIONAL_PACKAGE_NAMES = Object.freeze([
2740
2421
  "@moldea.ai/repository-fs"
2741
2422
  ]);
2742
2423
  var MOLDEA_CLI_FIRST_CLASS_PACKAGE_RANGES = Object.freeze({
2743
- "@moldea.ai/core": "^8.0.0",
2744
- "@moldea.ai/repository": "^3.0.0",
2745
- "@moldea.ai/repository-fs": "^3.0.0"
2424
+ "@moldea.ai/core": "^9.0.0",
2425
+ "@moldea.ai/repository": "^4.0.0",
2426
+ "@moldea.ai/repository-fs": "^4.0.0"
2746
2427
  });
2747
2428
  //#endregion
2748
2429
  //#region src/composition/validations.ts
@@ -2774,19 +2455,6 @@ var isMoldeaCliCompositionStateValid = (input) => {
2774
2455
  //#endregion
2775
2456
  //#region src/composition/transformers.ts
2776
2457
  var compareIdentifiers = (left, right) => left < right ? -1 : left > right ? 1 : 0;
2777
- /** Recursively freezes a composition result without retaining mutable input ownership. */
2778
- var freezeCompositionValue = (value) => {
2779
- const pendingValues = [value];
2780
- const visitedValues = /* @__PURE__ */ new Set();
2781
- while (pendingValues.length > 0) {
2782
- const currentValue = pendingValues.pop();
2783
- if (currentValue === void 0 || visitedValues.has(currentValue)) continue;
2784
- visitedValues.add(currentValue);
2785
- for (const nestedValue of Object.values(currentValue)) if (typeof nestedValue === "object" && nestedValue !== null) pendingValues.push(nestedValue);
2786
- Object.freeze(currentValue);
2787
- }
2788
- return value;
2789
- };
2790
2458
  /**
2791
2459
  * Creates the compact immutable composition result from validated installed state.
2792
2460
  * @param input The already validated installed and executable composition.
@@ -2797,7 +2465,7 @@ var createMoldeaCliCompositionResult = (input) => {
2797
2465
  name,
2798
2466
  version
2799
2467
  })).sort((left, right) => compareIdentifiers(left.name, right.name));
2800
- return freezeCompositionValue({
2468
+ return deepFreeze({
2801
2469
  minimumGitVersion: input.minimumGitVersion,
2802
2470
  packages,
2803
2471
  repositoryFormatVersions: [...input.coreSupportedRepositoryFormatVersions].sort((left, right) => left - right),
@@ -2835,6 +2503,6 @@ var resolveInstalledMoldeaCliComposition = (input) => resolveMoldeaCliCompositio
2835
2503
  packageMetadata: input.packageMetadata
2836
2504
  });
2837
2505
  //#endregion
2838
- export { hasOnlyUnicodeScalarValues as A, formatMoldeaCliJsonError as C, createMoldeaCliOwnedError as D, formatMoldeaCliJsonValidateResult as E, encodeMoldeaCliCursor as F, MoldeaCliOutputPageException as I, MOLDEA_CLI_COMMANDS as L, createMoldeaCliOutputPage as M, calculateMoldeaCliJsonDigest as N, MOLDEA_CLI_GIT_WORKING_TREE_SOURCE as O, decodeMoldeaCliCursor as P, formatMoldeaCliJsonContentResult as S, formatMoldeaCliJsonScopeResult as T, formatMoldeaCliHumanError as _, require_semver as a, formatMoldeaCliHumanValidateResult as b, executeGitStreamingProcess as c, createMoldeaCliDiagnosticRecord as d, createMoldeaCliInspectProjection as f, formatMoldeaCliHumanContentResult as g, formatMoldeaCliHumanCompositionResult as h, isMoldeaCliCompositionStateValid as i, isRepositoryDirectoryInputValid as j, parseMoldeaCliArguments as k, executeGitProcess as l, formatMoldeaCliHelp as m, resolveMoldeaCliComposition as n, MoldeaCliCompositionException as o, createMoldeaCliValidateProjection as p, createMoldeaCliCompositionResult as r, createGitVersionPreflight as s, resolveInstalledMoldeaCliComposition as t, MAX_GIT_PROCESS_DIAGNOSTIC_BYTES as u, formatMoldeaCliHumanInspectResult as v, formatMoldeaCliJsonInspectResult as w, formatMoldeaCliJsonCompositionResult as x, formatMoldeaCliHumanScopeResult as y };
2506
+ export { createMoldeaCliOutputPage as A, formatMoldeaCliJsonInspectResult as C, MOLDEA_CLI_GIT_WORKING_TREE_SOURCE as D, createMoldeaCliOwnedError as E, MOLDEA_CLI_COMMANDS as F, decodeMoldeaCliCursor as M, encodeMoldeaCliCursor as N, parseMoldeaCliArguments as O, MoldeaCliOutputPageException as P, formatMoldeaCliJsonError as S, formatMoldeaCliJsonValidateResult as T, formatMoldeaCliHumanInspectResult as _, require_semver as a, formatMoldeaCliJsonCompositionResult as b, runGitCommand as c, createMoldeaCliInspectProjection as d, createMoldeaCliValidateProjection as f, formatMoldeaCliHumanError as g, formatMoldeaCliHumanContentResult as h, isMoldeaCliCompositionStateValid as i, calculateMoldeaCliJsonDigest as j, isRepositoryDirectoryInputValid as k, readGit as l, formatMoldeaCliHumanCompositionResult as m, resolveMoldeaCliComposition as n, MoldeaCliCompositionException as o, formatMoldeaCliHelp as p, createMoldeaCliCompositionResult as r, createGitVersionPreflight as s, resolveInstalledMoldeaCliComposition as t, createMoldeaCliDiagnosticRecord as u, formatMoldeaCliHumanScopeResult as v, formatMoldeaCliJsonScopeResult as w, formatMoldeaCliJsonContentResult as x, formatMoldeaCliHumanValidateResult as y };
2839
2507
 
2840
- //# sourceMappingURL=composition-DX66KnuP.js.map
2508
+ //# sourceMappingURL=composition-cVui-wF_.js.map