@self-review/core 2.0.4 → 2.1.3
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.
- package/README.md +441 -0
- package/dist/chunk-5SGPWHGH.cjs +106 -0
- package/dist/chunk-5SGPWHGH.cjs.map +1 -0
- package/dist/chunk-6OEFXBIZ.cjs +5212 -0
- package/dist/chunk-6OEFXBIZ.cjs.map +1 -0
- package/dist/chunk-6X3PJHP5.cjs +416 -0
- package/dist/chunk-6X3PJHP5.cjs.map +1 -0
- package/dist/chunk-CJQEOLI3.js +37 -0
- package/dist/chunk-CJQEOLI3.js.map +1 -0
- package/dist/chunk-IG2YF5LH.js +416 -0
- package/dist/chunk-IG2YF5LH.js.map +1 -0
- package/dist/chunk-IX226KG4.js +106 -0
- package/dist/chunk-IX226KG4.js.map +1 -0
- package/dist/chunk-LSLCQQBN.cjs +3684 -0
- package/dist/chunk-LSLCQQBN.cjs.map +1 -0
- package/dist/chunk-MOYO4RIX.js +3684 -0
- package/dist/chunk-MOYO4RIX.js.map +1 -0
- package/dist/chunk-TOUYY7I6.js +5212 -0
- package/dist/chunk-TOUYY7I6.js.map +1 -0
- package/dist/chunk-VOYTFLPH.cjs +37 -0
- package/dist/chunk-VOYTFLPH.cjs.map +1 -0
- package/dist/filesystem.cjs +56 -0
- package/dist/filesystem.cjs.map +1 -0
- package/dist/filesystem.d.cts +22 -0
- package/dist/filesystem.d.ts +22 -0
- package/dist/filesystem.js +56 -0
- package/dist/index.cjs +348 -6192
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +80 -1332
- package/dist/index.d.ts +80 -1332
- package/dist/index.js +234 -5172
- package/dist/index.js.map +1 -1
- package/dist/node-scan-fs-CaufzUZR.d.cts +5 -0
- package/dist/node-scan-fs-DcHI_BYB.d.ts +5 -0
- package/dist/operations-Bqhi9EBH.d.ts +765 -0
- package/dist/operations-UyiUD2Nx.d.cts +765 -0
- package/dist/operations.cjs +91 -0
- package/dist/operations.cjs.map +1 -0
- package/dist/operations.d.cts +6 -0
- package/dist/operations.d.ts +6 -0
- package/dist/operations.js +91 -0
- package/dist/resume-worker.cjs +152 -0
- package/dist/resume-worker.cjs.map +1 -0
- package/dist/resume-worker.d.cts +56 -0
- package/dist/resume-worker.d.ts +56 -0
- package/dist/resume-worker.js +152 -0
- package/dist/resume-worker.js.map +1 -0
- package/dist/review-request-validation-VJG7XZiE.d.cts +62 -0
- package/dist/review-request-validation-VJG7XZiE.d.ts +62 -0
- package/dist/review-xml-decoder-COgRtfkf.d.cts +33 -0
- package/dist/review-xml-decoder-COgRtfkf.d.ts +33 -0
- package/dist/source-identity-CQpAzugz.d.cts +959 -0
- package/dist/source-identity-CQpAzugz.d.ts +959 -0
- package/dist/validation.cjs +67 -0
- package/dist/validation.cjs.map +1 -0
- package/dist/validation.d.cts +30 -0
- package/dist/validation.d.ts +30 -0
- package/dist/validation.js +67 -0
- package/dist/validation.js.map +1 -0
- package/package.json +44 -3
- package/dist/chunk-4YO2MI6B.js +0 -269
- package/dist/chunk-4YO2MI6B.js.map +0 -1
- package/dist/chunk-QHS36X6T.js +0 -450
- package/dist/chunk-QHS36X6T.js.map +0 -1
- package/dist/diff-parser-B6S3KG5T.js +0 -9
- package/dist/git-N5HVNPKQ.js +0 -24
- /package/dist/{diff-parser-B6S3KG5T.js.map → filesystem.js.map} +0 -0
- /package/dist/{git-N5HVNPKQ.js.map → operations.js.map} +0 -0
|
@@ -0,0 +1,3684 @@
|
|
|
1
|
+
import {
|
|
2
|
+
BINARY_SNIFF_BYTES,
|
|
3
|
+
MAX_GIT_DIFF_OUTPUT_BYTES,
|
|
4
|
+
MAX_SOURCE_FILE_BYTES,
|
|
5
|
+
RepresentationLimitError,
|
|
6
|
+
createRepresentationBudget,
|
|
7
|
+
formatBytes,
|
|
8
|
+
isWellFormedUnicode,
|
|
9
|
+
resolveSourceBudgets,
|
|
10
|
+
validateLineRange,
|
|
11
|
+
validateReviewState
|
|
12
|
+
} from "./chunk-IG2YF5LH.js";
|
|
13
|
+
|
|
14
|
+
// src/forge-definitions.ts
|
|
15
|
+
var FORGE_DEFINITIONS = {
|
|
16
|
+
gitlab: {
|
|
17
|
+
urlPath: /^\/(.+)\/([^/]+)\/-\/merge_requests\/(\d+)(?=\/|$)/,
|
|
18
|
+
headRef: (number) => `refs/merge-requests/${number}/head`
|
|
19
|
+
},
|
|
20
|
+
github: {
|
|
21
|
+
urlPath: /^\/([^/]+)\/([^/]+)\/pull\/(\d+)(?=\/|$)/,
|
|
22
|
+
headRef: (number) => `refs/pull/${number}/head`
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
// src/forge-provider.ts
|
|
27
|
+
var CommandCancelledError = class extends Error {
|
|
28
|
+
constructor(reason, command, args) {
|
|
29
|
+
super(
|
|
30
|
+
reason === "timeout" ? `${command} ${args.join(" ")} timed out and was killed` : `${command} ${args.join(" ")} was cancelled`
|
|
31
|
+
);
|
|
32
|
+
this.name = "CommandCancelledError";
|
|
33
|
+
this.reason = reason;
|
|
34
|
+
this.command = command;
|
|
35
|
+
this.args = args;
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
function isCommandCancelled(error) {
|
|
39
|
+
return error instanceof CommandCancelledError || error instanceof Error && error.name === "CommandCancelledError";
|
|
40
|
+
}
|
|
41
|
+
var ForgeCliUnavailableError = class extends Error {
|
|
42
|
+
constructor(forge, cli, message) {
|
|
43
|
+
super(message);
|
|
44
|
+
this.name = "ForgeCliUnavailableError";
|
|
45
|
+
this.forge = forge;
|
|
46
|
+
this.cli = cli;
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
function parseForgeUrl(url) {
|
|
50
|
+
let parsed;
|
|
51
|
+
try {
|
|
52
|
+
parsed = new URL(url);
|
|
53
|
+
} catch {
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
for (const forge of Object.keys(FORGE_DEFINITIONS)) {
|
|
60
|
+
const match = FORGE_DEFINITIONS[forge].urlPath.exec(parsed.pathname);
|
|
61
|
+
if (match) {
|
|
62
|
+
const number = Number(match[3]);
|
|
63
|
+
if (!Number.isSafeInteger(number) || number <= 0) return null;
|
|
64
|
+
return {
|
|
65
|
+
forge,
|
|
66
|
+
host: parsed.host,
|
|
67
|
+
owner: match[1],
|
|
68
|
+
repo: match[2],
|
|
69
|
+
number
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// src/bounded-read.ts
|
|
77
|
+
import { closeSync, constants, fstatSync, openSync, read, readSync } from "fs";
|
|
78
|
+
import { open } from "fs/promises";
|
|
79
|
+
import { promisify } from "util";
|
|
80
|
+
|
|
81
|
+
// src/local-loading-lifetime.ts
|
|
82
|
+
import { setImmediate } from "timers/promises";
|
|
83
|
+
function checkLoadingCancelled(signal) {
|
|
84
|
+
if (signal?.aborted) {
|
|
85
|
+
throw new CommandCancelledError("aborted", "self-review", ["load-local-review"]);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
async function loadingCheckpoint(signal) {
|
|
89
|
+
checkLoadingCancelled(signal);
|
|
90
|
+
await setImmediate();
|
|
91
|
+
checkLoadingCancelled(signal);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// src/bounded-read.ts
|
|
95
|
+
var READ_FLAGS = constants.O_RDONLY | (constants.O_NONBLOCK ?? 0);
|
|
96
|
+
var readAsync = promisify(read);
|
|
97
|
+
function openFlags(options) {
|
|
98
|
+
return options.noFollow ? READ_FLAGS | constants.O_NOFOLLOW : READ_FLAGS;
|
|
99
|
+
}
|
|
100
|
+
async function readFileWithinBudget(path9, maxBytes, options = {}) {
|
|
101
|
+
checkLoadingCancelled(options.signal);
|
|
102
|
+
const handle = await open(path9, openFlags(options));
|
|
103
|
+
try {
|
|
104
|
+
checkLoadingCancelled(options.signal);
|
|
105
|
+
const stats = await handle.stat();
|
|
106
|
+
checkLoadingCancelled(options.signal);
|
|
107
|
+
if (!stats.isFile()) return { kind: "not-regular" };
|
|
108
|
+
return await readDescriptorWithinBudget(handle.fd, stats, maxBytes, options);
|
|
109
|
+
} finally {
|
|
110
|
+
try {
|
|
111
|
+
await handle.close();
|
|
112
|
+
} finally {
|
|
113
|
+
checkLoadingCancelled(options.signal);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
async function readDescriptorWithinBudget(fd, stats, maxBytes, options = {}) {
|
|
118
|
+
checkLoadingCancelled(options.signal);
|
|
119
|
+
if (stats.size > maxBytes) return { kind: "too-large", size: stats.size };
|
|
120
|
+
let buffer = Buffer.alloc(initialCapacity(stats.size, maxBytes));
|
|
121
|
+
let filled = 0;
|
|
122
|
+
for (; ; ) {
|
|
123
|
+
await loadingCheckpoint(options.signal);
|
|
124
|
+
const { bytesRead } = await readAsync(
|
|
125
|
+
fd,
|
|
126
|
+
buffer,
|
|
127
|
+
filled,
|
|
128
|
+
Math.min(buffer.length - filled, 64 * 1024),
|
|
129
|
+
null
|
|
130
|
+
);
|
|
131
|
+
checkLoadingCancelled(options.signal);
|
|
132
|
+
if (bytesRead === 0) break;
|
|
133
|
+
filled += bytesRead;
|
|
134
|
+
if (filled === buffer.length) {
|
|
135
|
+
if (buffer.length > maxBytes) break;
|
|
136
|
+
buffer = grow(buffer, maxBytes);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
if (filled > maxBytes) return { kind: "too-large", size: Math.max(filled, stats.size) };
|
|
140
|
+
return { kind: "ok", content: buffer.subarray(0, filled) };
|
|
141
|
+
}
|
|
142
|
+
function readFileWithinBudgetSync(path9, maxBytes, options = {}) {
|
|
143
|
+
const fd = openSync(path9, openFlags(options));
|
|
144
|
+
try {
|
|
145
|
+
const stats = fstatSync(fd);
|
|
146
|
+
if (!stats.isFile()) return { kind: "not-regular" };
|
|
147
|
+
if (stats.size > maxBytes) return { kind: "too-large", size: stats.size };
|
|
148
|
+
let buffer = Buffer.alloc(initialCapacity(stats.size, maxBytes));
|
|
149
|
+
let filled = 0;
|
|
150
|
+
for (; ; ) {
|
|
151
|
+
filled += readInto(fd, buffer, filled, buffer.length - filled);
|
|
152
|
+
if (filled < buffer.length || buffer.length > maxBytes) break;
|
|
153
|
+
buffer = grow(buffer, maxBytes);
|
|
154
|
+
}
|
|
155
|
+
if (filled > maxBytes) return { kind: "too-large", size: Math.max(filled, stats.size) };
|
|
156
|
+
return { kind: "ok", content: buffer.subarray(0, filled) };
|
|
157
|
+
} finally {
|
|
158
|
+
closeSync(fd);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
function initialCapacity(size, maxBytes) {
|
|
162
|
+
return Math.min(size, maxBytes) + 1;
|
|
163
|
+
}
|
|
164
|
+
function grow(buffer, maxBytes) {
|
|
165
|
+
const next = Buffer.alloc(Math.min(buffer.length * 2, maxBytes + 1));
|
|
166
|
+
buffer.copy(next);
|
|
167
|
+
return next;
|
|
168
|
+
}
|
|
169
|
+
function readInto(fd, buffer, offset, length) {
|
|
170
|
+
let filled = 0;
|
|
171
|
+
while (filled < length) {
|
|
172
|
+
const bytesRead = readSync(fd, buffer, offset + filled, length - filled, null);
|
|
173
|
+
if (bytesRead === 0) break;
|
|
174
|
+
filled += bytesRead;
|
|
175
|
+
}
|
|
176
|
+
return filled;
|
|
177
|
+
}
|
|
178
|
+
async function readIntoAsync(reader, buffer, offset, length, signal) {
|
|
179
|
+
checkLoadingCancelled(signal);
|
|
180
|
+
let filled = 0;
|
|
181
|
+
while (filled < length) {
|
|
182
|
+
await loadingCheckpoint(signal);
|
|
183
|
+
const { bytesRead } = await reader.read(
|
|
184
|
+
buffer,
|
|
185
|
+
offset + filled,
|
|
186
|
+
Math.min(length - filled, 64 * 1024),
|
|
187
|
+
null
|
|
188
|
+
);
|
|
189
|
+
checkLoadingCancelled(signal);
|
|
190
|
+
if (bytesRead === 0) break;
|
|
191
|
+
filled += bytesRead;
|
|
192
|
+
}
|
|
193
|
+
return filled;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// src/safe-fs-policy.ts
|
|
197
|
+
var SafeFsError = class extends Error {
|
|
198
|
+
constructor(code, path9, message, cause) {
|
|
199
|
+
super(message);
|
|
200
|
+
this.name = "SafeFsError";
|
|
201
|
+
this.code = code;
|
|
202
|
+
this.path = path9;
|
|
203
|
+
if (cause !== void 0) this.cause = cause;
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
function snapshotIdentity(stats) {
|
|
207
|
+
return {
|
|
208
|
+
dev: stats.dev,
|
|
209
|
+
ino: stats.ino,
|
|
210
|
+
mode: stats.mode & 4095,
|
|
211
|
+
nlink: stats.nlink,
|
|
212
|
+
size: stats.size,
|
|
213
|
+
mtimeMs: stats.mtimeMs,
|
|
214
|
+
uid: stats.uid,
|
|
215
|
+
gid: stats.gid
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
function sameFile(a, b) {
|
|
219
|
+
return a.dev === b.dev && a.ino === b.ino;
|
|
220
|
+
}
|
|
221
|
+
function sameStamp(a, b) {
|
|
222
|
+
return a.size === b.size && a.mtimeMs === b.mtimeMs;
|
|
223
|
+
}
|
|
224
|
+
var ERRNO_CODES = /* @__PURE__ */ new Map([
|
|
225
|
+
["ENOENT", "not-found"],
|
|
226
|
+
["ENOTDIR", "not-found"],
|
|
227
|
+
["EISDIR", "output-is-directory"],
|
|
228
|
+
["EACCES", "permission-denied"],
|
|
229
|
+
["EPERM", "permission-denied"],
|
|
230
|
+
["EROFS", "permission-denied"],
|
|
231
|
+
["ENOSPC", "no-space"],
|
|
232
|
+
["EDQUOT", "no-space"],
|
|
233
|
+
["ELOOP", "unsafe-link"]
|
|
234
|
+
]);
|
|
235
|
+
function classifyFsError(error) {
|
|
236
|
+
return ERRNO_CODES.get(errnoOf(error) ?? "") ?? "io-error";
|
|
237
|
+
}
|
|
238
|
+
function errnoOf(error) {
|
|
239
|
+
if (error && typeof error === "object" && "code" in error) {
|
|
240
|
+
const code = error.code;
|
|
241
|
+
return typeof code === "string" ? code : void 0;
|
|
242
|
+
}
|
|
243
|
+
return void 0;
|
|
244
|
+
}
|
|
245
|
+
function toSafeFsError(error, filePath, action) {
|
|
246
|
+
if (error instanceof SafeFsError) return error;
|
|
247
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
248
|
+
return new SafeFsError(
|
|
249
|
+
classifyFsError(error),
|
|
250
|
+
filePath,
|
|
251
|
+
`Cannot ${action} ${filePath}: ${reason}`,
|
|
252
|
+
error
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
function guarded(filePath, action, fn) {
|
|
256
|
+
try {
|
|
257
|
+
return fn();
|
|
258
|
+
} catch (error) {
|
|
259
|
+
throw toSafeFsError(error, filePath, action);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
function assertExpectedTarget(target, existing, options) {
|
|
263
|
+
const expected = options.expectedIdentity;
|
|
264
|
+
if (expected && (!existing || !sameFile(existing, expected))) {
|
|
265
|
+
throw new SafeFsError(
|
|
266
|
+
"identity-changed",
|
|
267
|
+
target,
|
|
268
|
+
`Refusing to replace ${target}: it is no longer the file that was checked`
|
|
269
|
+
);
|
|
270
|
+
}
|
|
271
|
+
if (expected && existing && (options.preserveMode && expected.mode !== existing.mode || options.preserveOwner && (expected.uid !== existing.uid || expected.gid !== existing.gid))) {
|
|
272
|
+
throw new SafeFsError(
|
|
273
|
+
"identity-changed",
|
|
274
|
+
target,
|
|
275
|
+
`Refusing to replace ${target}: its permissions or owner changed`
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
if (expected && options.expectUnmodified && existing && !sameStamp(existing, expected)) {
|
|
279
|
+
throw new SafeFsError(
|
|
280
|
+
"identity-changed",
|
|
281
|
+
target,
|
|
282
|
+
`Refusing to replace ${target}: it was modified after it was checked`
|
|
283
|
+
);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
function ownerToRestore(target, existing) {
|
|
287
|
+
if (typeof process.geteuid !== "function" || typeof process.getegid !== "function")
|
|
288
|
+
return void 0;
|
|
289
|
+
const me = { uid: process.geteuid(), gid: process.getegid() };
|
|
290
|
+
if (existing.uid === me.uid && existing.gid === me.gid) return void 0;
|
|
291
|
+
if (existing.uid !== me.uid && me.uid !== 0) {
|
|
292
|
+
throw new SafeFsError(
|
|
293
|
+
"unsupported-target",
|
|
294
|
+
target,
|
|
295
|
+
`Refusing to replace ${target}: it is owned by another user (uid ${existing.uid}), and replacing it would change its owner`
|
|
296
|
+
);
|
|
297
|
+
}
|
|
298
|
+
return { uid: existing.uid, gid: existing.gid };
|
|
299
|
+
}
|
|
300
|
+
function replacementIdentity(target, stats) {
|
|
301
|
+
if (stats.isSymbolicLink()) {
|
|
302
|
+
throw new SafeFsError(
|
|
303
|
+
"unsafe-link",
|
|
304
|
+
target,
|
|
305
|
+
`Refusing to write ${target}: it is a symbolic link, and this program does not follow links when saving`
|
|
306
|
+
);
|
|
307
|
+
}
|
|
308
|
+
if (stats.isDirectory()) {
|
|
309
|
+
throw new SafeFsError(
|
|
310
|
+
"output-is-directory",
|
|
311
|
+
target,
|
|
312
|
+
`Cannot write ${target}: it is a directory`
|
|
313
|
+
);
|
|
314
|
+
}
|
|
315
|
+
if (!stats.isFile()) {
|
|
316
|
+
throw new SafeFsError(
|
|
317
|
+
"unsupported-target",
|
|
318
|
+
target,
|
|
319
|
+
`Cannot write ${target}: it exists but is not a regular file`
|
|
320
|
+
);
|
|
321
|
+
}
|
|
322
|
+
if (stats.nlink > 1) {
|
|
323
|
+
throw new SafeFsError(
|
|
324
|
+
"unsupported-target",
|
|
325
|
+
target,
|
|
326
|
+
`Refusing to replace ${target}: it has ${stats.nlink} hard links, and replacing it would silently detach the others`
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
return snapshotIdentity(stats);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// src/safe-fs-read.ts
|
|
333
|
+
import * as fs from "fs/promises";
|
|
334
|
+
import { setImmediate as yieldToIo } from "timers/promises";
|
|
335
|
+
import * as path from "path";
|
|
336
|
+
var nodeReadFsLayer = {
|
|
337
|
+
readAllocation: "bounded",
|
|
338
|
+
open: (target, flags, mode) => fs.open(target, flags, mode),
|
|
339
|
+
lstat: (target) => fs.lstat(target),
|
|
340
|
+
realpath: (target) => fs.realpath(target)
|
|
341
|
+
};
|
|
342
|
+
function boundedReadFsFromSync(layer, signal) {
|
|
343
|
+
return {
|
|
344
|
+
readAllocation: "bounded",
|
|
345
|
+
async open(target, flags, mode) {
|
|
346
|
+
const fd = layer.openSync(target, flags, mode);
|
|
347
|
+
return {
|
|
348
|
+
async stat() {
|
|
349
|
+
return layer.fstatSync(fd);
|
|
350
|
+
},
|
|
351
|
+
async read(buffer, offset, length, position) {
|
|
352
|
+
await yieldToIo();
|
|
353
|
+
signal?.throwIfAborted();
|
|
354
|
+
return { bytesRead: layer.readSync(fd, buffer, offset, length, position) };
|
|
355
|
+
},
|
|
356
|
+
async close() {
|
|
357
|
+
layer.closeSync(fd);
|
|
358
|
+
}
|
|
359
|
+
};
|
|
360
|
+
},
|
|
361
|
+
async lstat(target) {
|
|
362
|
+
return layer.lstatSync(target);
|
|
363
|
+
},
|
|
364
|
+
async realpath(target) {
|
|
365
|
+
return layer.realpathSync(target);
|
|
366
|
+
}
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
async function assertNoSymlinkAncestorsAsync(root, rel, layer, signal) {
|
|
370
|
+
signal?.throwIfAborted();
|
|
371
|
+
const normalized = path.normalize(rel);
|
|
372
|
+
if (path.isAbsolute(normalized) || normalized === ".." || normalized.startsWith(`..${path.sep}`)) {
|
|
373
|
+
throw new SafeFsError(
|
|
374
|
+
"unsupported-target",
|
|
375
|
+
path.join(root, rel),
|
|
376
|
+
`Refusing ${rel}: it does not stay under ${root}`
|
|
377
|
+
);
|
|
378
|
+
}
|
|
379
|
+
let current = root;
|
|
380
|
+
for (const segment of path.dirname(normalized).split(path.sep)) {
|
|
381
|
+
if (!segment || segment === ".") continue;
|
|
382
|
+
current = path.join(current, segment);
|
|
383
|
+
let stats;
|
|
384
|
+
try {
|
|
385
|
+
stats = await layer.lstat(current);
|
|
386
|
+
} catch (error) {
|
|
387
|
+
signal?.throwIfAborted();
|
|
388
|
+
if (errnoOf(error) === "ENOENT") break;
|
|
389
|
+
throw toSafeFsError(error, current, "inspect");
|
|
390
|
+
}
|
|
391
|
+
signal?.throwIfAborted();
|
|
392
|
+
if (stats.isSymbolicLink()) {
|
|
393
|
+
throw new SafeFsError(
|
|
394
|
+
"unsafe-link",
|
|
395
|
+
current,
|
|
396
|
+
`Refusing to go through ${current}: it is a symbolic link`
|
|
397
|
+
);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// src/safe-fs-legacy.ts
|
|
403
|
+
import { setImmediate as yieldToIo2 } from "timers/promises";
|
|
404
|
+
function asyncFsFromSync(layer, signal) {
|
|
405
|
+
if (layer.asyncFs) return layer.asyncFs;
|
|
406
|
+
return {
|
|
407
|
+
async open(target, flags, mode) {
|
|
408
|
+
const fd = layer.openSync(target, flags, mode);
|
|
409
|
+
let cached;
|
|
410
|
+
let cursor = 0;
|
|
411
|
+
return {
|
|
412
|
+
async stat() {
|
|
413
|
+
return layer.fstatSync(fd);
|
|
414
|
+
},
|
|
415
|
+
async read(buffer, offset, length, position) {
|
|
416
|
+
await yieldToIo2();
|
|
417
|
+
signal?.throwIfAborted();
|
|
418
|
+
if (layer.readSync) {
|
|
419
|
+
return { bytesRead: layer.readSync(fd, buffer, offset, length, position) };
|
|
420
|
+
}
|
|
421
|
+
cached ?? (cached = layer.readFileSync(fd));
|
|
422
|
+
const start = position ?? cursor;
|
|
423
|
+
const bytesRead = cached.copy(
|
|
424
|
+
buffer,
|
|
425
|
+
offset,
|
|
426
|
+
start,
|
|
427
|
+
Math.min(start + length, cached.length)
|
|
428
|
+
);
|
|
429
|
+
if (position === null) cursor += bytesRead;
|
|
430
|
+
return { bytesRead };
|
|
431
|
+
},
|
|
432
|
+
async write(buffer) {
|
|
433
|
+
await yieldToIo2();
|
|
434
|
+
signal?.throwIfAborted();
|
|
435
|
+
return { bytesWritten: layer.writeSync(fd, buffer) };
|
|
436
|
+
},
|
|
437
|
+
async sync() {
|
|
438
|
+
layer.fsyncSync(fd);
|
|
439
|
+
},
|
|
440
|
+
async chmod(mode2) {
|
|
441
|
+
layer.fchmodSync(fd, mode2);
|
|
442
|
+
},
|
|
443
|
+
async chown(uid, gid) {
|
|
444
|
+
layer.fchownSync(fd, uid, gid);
|
|
445
|
+
},
|
|
446
|
+
async close() {
|
|
447
|
+
cached = void 0;
|
|
448
|
+
layer.closeSync(fd);
|
|
449
|
+
}
|
|
450
|
+
};
|
|
451
|
+
},
|
|
452
|
+
async lstat(target) {
|
|
453
|
+
return layer.lstatSync(target);
|
|
454
|
+
},
|
|
455
|
+
async realpath(target) {
|
|
456
|
+
return layer.realpathSync(target);
|
|
457
|
+
},
|
|
458
|
+
async rename(from, to) {
|
|
459
|
+
layer.renameSync(from, to);
|
|
460
|
+
},
|
|
461
|
+
async unlink(target) {
|
|
462
|
+
layer.unlinkSync(target);
|
|
463
|
+
}
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// src/safe-fs-async.ts
|
|
468
|
+
import * as fs2 from "fs/promises";
|
|
469
|
+
import { constants as constants2 } from "fs";
|
|
470
|
+
import * as path2 from "path";
|
|
471
|
+
import { randomBytes } from "crypto";
|
|
472
|
+
var nodeAsyncFsLayer = {
|
|
473
|
+
open: (target, flags, mode) => fs2.open(target, flags, mode),
|
|
474
|
+
lstat: (target) => fs2.lstat(target),
|
|
475
|
+
realpath: (target) => fs2.realpath(target),
|
|
476
|
+
rename: (from, to) => fs2.rename(from, to),
|
|
477
|
+
unlink: (target) => fs2.unlink(target)
|
|
478
|
+
};
|
|
479
|
+
async function readContainedFileAsync(root, rel, maxBytes, layer = nodeReadFsLayer, signal) {
|
|
480
|
+
const { handle, stats } = await openContainedFileAsync(root, rel, layer, signal);
|
|
481
|
+
const target = path2.join(root, rel);
|
|
482
|
+
const assertSize = (size) => {
|
|
483
|
+
if (size > maxBytes)
|
|
484
|
+
throw new SafeFsError(
|
|
485
|
+
"too-large",
|
|
486
|
+
target,
|
|
487
|
+
`The file is ${formatBytes(size)}, over the ${formatBytes(maxBytes)} limit`
|
|
488
|
+
);
|
|
489
|
+
};
|
|
490
|
+
try {
|
|
491
|
+
assertSize(stats.size);
|
|
492
|
+
let buffer = Buffer.alloc(Math.min(stats.size, maxBytes) + 1);
|
|
493
|
+
let filled = 0;
|
|
494
|
+
for (; ; ) {
|
|
495
|
+
signal?.throwIfAborted();
|
|
496
|
+
const { bytesRead } = await handle.read(
|
|
497
|
+
buffer,
|
|
498
|
+
filled,
|
|
499
|
+
Math.min(buffer.length - filled, 64 * 1024),
|
|
500
|
+
null
|
|
501
|
+
);
|
|
502
|
+
signal?.throwIfAborted();
|
|
503
|
+
filled += bytesRead;
|
|
504
|
+
assertSize(filled);
|
|
505
|
+
if (bytesRead === 0) break;
|
|
506
|
+
if (filled === buffer.length) {
|
|
507
|
+
const next = Buffer.alloc(Math.min(buffer.length * 2, maxBytes + 1));
|
|
508
|
+
buffer.copy(next);
|
|
509
|
+
buffer = next;
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
assertSize((await handle.stat()).size);
|
|
513
|
+
signal?.throwIfAborted();
|
|
514
|
+
return buffer.subarray(0, filled);
|
|
515
|
+
} catch (error) {
|
|
516
|
+
signal?.throwIfAborted();
|
|
517
|
+
throw toSafeFsError(error, target, "read");
|
|
518
|
+
} finally {
|
|
519
|
+
await quietly(() => handle.close());
|
|
520
|
+
signal?.throwIfAborted();
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
function readContainedFileBounded(root, rel, maxBytes, layer = nodeReadFsLayer, signal) {
|
|
524
|
+
return readContainedFileAsync(root, rel, maxBytes, layer, signal);
|
|
525
|
+
}
|
|
526
|
+
async function quietly(fn) {
|
|
527
|
+
try {
|
|
528
|
+
await fn();
|
|
529
|
+
} catch {
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
async function lstatOrNull(target, layer) {
|
|
533
|
+
try {
|
|
534
|
+
return await layer.lstat(target);
|
|
535
|
+
} catch (error) {
|
|
536
|
+
if (errnoOf(error) === "ENOENT") return null;
|
|
537
|
+
throw toSafeFsError(error, target, "inspect");
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
async function inspectTarget(target, layer) {
|
|
541
|
+
const stats = await lstatOrNull(target, layer);
|
|
542
|
+
return stats === null ? null : replacementIdentity(target, stats);
|
|
543
|
+
}
|
|
544
|
+
async function openContainedFileAsync(root, rel, layer = nodeAsyncFsLayer, signal) {
|
|
545
|
+
signal?.throwIfAborted();
|
|
546
|
+
await assertNoSymlinkAncestorsAsync(root, rel, layer, signal);
|
|
547
|
+
signal?.throwIfAborted();
|
|
548
|
+
const target = path2.join(root, rel);
|
|
549
|
+
const handle = await layer.open(target, READ_FLAGS | constants2.O_NOFOLLOW).catch((error) => {
|
|
550
|
+
signal?.throwIfAborted();
|
|
551
|
+
throw toSafeFsError(error, target, "open");
|
|
552
|
+
});
|
|
553
|
+
try {
|
|
554
|
+
signal?.throwIfAborted();
|
|
555
|
+
const stats = await handle.stat();
|
|
556
|
+
signal?.throwIfAborted();
|
|
557
|
+
if (stats.isDirectory())
|
|
558
|
+
throw new SafeFsError("output-is-directory", target, `${target} is a directory`);
|
|
559
|
+
if (!stats.isFile())
|
|
560
|
+
throw new SafeFsError("not-regular", target, `${target} is not a regular file`);
|
|
561
|
+
const named = await layer.lstat(target);
|
|
562
|
+
signal?.throwIfAborted();
|
|
563
|
+
const physical = await layer.realpath(target);
|
|
564
|
+
signal?.throwIfAborted();
|
|
565
|
+
const physicalRoot = await layer.realpath(root);
|
|
566
|
+
signal?.throwIfAborted();
|
|
567
|
+
if (!sameFile(named, stats) || physical !== path2.join(physicalRoot, rel)) {
|
|
568
|
+
throw new SafeFsError("unsafe-link", target, `${target} changed while it was being opened`);
|
|
569
|
+
}
|
|
570
|
+
return { handle, stats };
|
|
571
|
+
} catch (error) {
|
|
572
|
+
await quietly(() => handle.close());
|
|
573
|
+
signal?.throwIfAborted();
|
|
574
|
+
throw toSafeFsError(error, target, "open");
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
async function writeStagedFile(temp, bytes, layer, options, exactMode, exactOwner) {
|
|
578
|
+
options.signal?.throwIfAborted();
|
|
579
|
+
const byteLength = bytes.byteLength;
|
|
580
|
+
const assertLength = () => {
|
|
581
|
+
if (bytes.byteLength !== byteLength)
|
|
582
|
+
throw new SafeFsError(
|
|
583
|
+
"io-error",
|
|
584
|
+
temp,
|
|
585
|
+
`Cannot write ${temp}: the source buffer changed size`
|
|
586
|
+
);
|
|
587
|
+
};
|
|
588
|
+
let handle;
|
|
589
|
+
try {
|
|
590
|
+
handle = await layer.open(
|
|
591
|
+
temp,
|
|
592
|
+
constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL | constants2.O_NOFOLLOW,
|
|
593
|
+
438
|
|
594
|
+
);
|
|
595
|
+
} catch (error) {
|
|
596
|
+
if (errnoOf(error) === "EEXIST" && (await lstatOrNull(temp, layer))?.isSymbolicLink()) {
|
|
597
|
+
throw new SafeFsError(
|
|
598
|
+
"unsafe-link",
|
|
599
|
+
temp,
|
|
600
|
+
`Refusing to write ${temp}: a symbolic link already sits at that name`
|
|
601
|
+
);
|
|
602
|
+
}
|
|
603
|
+
throw toSafeFsError(error, temp, "create");
|
|
604
|
+
}
|
|
605
|
+
try {
|
|
606
|
+
let offset = 0;
|
|
607
|
+
assertLength();
|
|
608
|
+
while (offset < byteLength) {
|
|
609
|
+
options.signal?.throwIfAborted();
|
|
610
|
+
assertLength();
|
|
611
|
+
const { bytesWritten } = await handle.write(bytes.subarray(offset, offset + 64 * 1024));
|
|
612
|
+
if (bytesWritten <= 0)
|
|
613
|
+
throw new SafeFsError("io-error", temp, `Cannot write ${temp}: write made no progress`);
|
|
614
|
+
offset += bytesWritten;
|
|
615
|
+
}
|
|
616
|
+
assertLength();
|
|
617
|
+
if (exactOwner !== void 0) {
|
|
618
|
+
try {
|
|
619
|
+
await handle.chown(exactOwner.uid, exactOwner.gid);
|
|
620
|
+
} catch (error) {
|
|
621
|
+
throw new SafeFsError("unsupported-target", temp, `Cannot give ${temp} its owner`, error);
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
if (exactMode !== void 0) await handle.chmod(exactMode);
|
|
625
|
+
await handle.sync();
|
|
626
|
+
options.signal?.throwIfAborted();
|
|
627
|
+
const identity = snapshotIdentity(await handle.stat());
|
|
628
|
+
await handle.close();
|
|
629
|
+
return identity;
|
|
630
|
+
} catch (error) {
|
|
631
|
+
await quietly(() => handle.close());
|
|
632
|
+
await quietly(() => layer.unlink(temp));
|
|
633
|
+
throw error;
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
async function writeExclusiveNoFollowAsync(target, bytes, options = {}) {
|
|
637
|
+
return writeStagedFile(
|
|
638
|
+
target,
|
|
639
|
+
bytes,
|
|
640
|
+
options.fs ?? nodeAsyncFsLayer,
|
|
641
|
+
options,
|
|
642
|
+
void 0,
|
|
643
|
+
void 0
|
|
644
|
+
);
|
|
645
|
+
}
|
|
646
|
+
async function atomicReplaceAsync(target, bytes, options = {}) {
|
|
647
|
+
const layer = options.fs ?? nodeAsyncFsLayer;
|
|
648
|
+
options.signal?.throwIfAborted();
|
|
649
|
+
const parent = await layer.realpath(path2.dirname(target)).catch((error) => {
|
|
650
|
+
options.signal?.throwIfAborted();
|
|
651
|
+
throw toSafeFsError(error, target, "resolve parent");
|
|
652
|
+
});
|
|
653
|
+
const existing = await inspectTarget(target, layer);
|
|
654
|
+
assertExpectedTarget(target, existing, options);
|
|
655
|
+
const owner = options.preserveOwner && existing ? ownerToRestore(target, existing) : void 0;
|
|
656
|
+
const random = options.randomName ?? (() => randomBytes(6).toString("hex"));
|
|
657
|
+
const temp = path2.join(path2.dirname(target), `.${path2.basename(target)}.${random()}.tmp`);
|
|
658
|
+
let identity;
|
|
659
|
+
try {
|
|
660
|
+
identity = await writeStagedFile(
|
|
661
|
+
temp,
|
|
662
|
+
bytes,
|
|
663
|
+
layer,
|
|
664
|
+
options,
|
|
665
|
+
options.preserveMode && existing ? existing.mode : void 0,
|
|
666
|
+
owner
|
|
667
|
+
);
|
|
668
|
+
} catch (error) {
|
|
669
|
+
options.signal?.throwIfAborted();
|
|
670
|
+
const safe = toSafeFsError(error, target, "write");
|
|
671
|
+
if (safe.code === "unsupported-target")
|
|
672
|
+
throw new SafeFsError(
|
|
673
|
+
"unsupported-target",
|
|
674
|
+
target,
|
|
675
|
+
`Refusing to replace ${target}: its owner could not be preserved on the replacement`,
|
|
676
|
+
safe.cause
|
|
677
|
+
);
|
|
678
|
+
if (safe.code !== "unsafe-link" && safe.cause !== void 0)
|
|
679
|
+
throw toSafeFsError(safe.cause, target, "write");
|
|
680
|
+
throw safe;
|
|
681
|
+
}
|
|
682
|
+
try {
|
|
683
|
+
if (await layer.realpath(path2.dirname(target)) !== parent) {
|
|
684
|
+
throw new SafeFsError(
|
|
685
|
+
"identity-changed",
|
|
686
|
+
target,
|
|
687
|
+
`Refusing to replace ${target}: its parent directory moved`
|
|
688
|
+
);
|
|
689
|
+
}
|
|
690
|
+
assertExpectedTarget(target, await inspectTarget(target, layer), options);
|
|
691
|
+
options.signal?.throwIfAborted();
|
|
692
|
+
options.beforeCommit?.();
|
|
693
|
+
options.signal?.throwIfAborted();
|
|
694
|
+
await layer.rename(temp, target);
|
|
695
|
+
} catch (error) {
|
|
696
|
+
await quietly(() => layer.unlink(temp));
|
|
697
|
+
options.signal?.throwIfAborted();
|
|
698
|
+
throw toSafeFsError(error, target, "replace");
|
|
699
|
+
}
|
|
700
|
+
await quietly(async () => {
|
|
701
|
+
const directory = await layer.open(path2.dirname(target), constants2.O_RDONLY);
|
|
702
|
+
try {
|
|
703
|
+
await directory.sync();
|
|
704
|
+
} finally {
|
|
705
|
+
await quietly(() => directory.close());
|
|
706
|
+
}
|
|
707
|
+
});
|
|
708
|
+
return { identity, replaced: existing !== null };
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
// src/safe-fs.ts
|
|
712
|
+
import * as nodeFs from "fs";
|
|
713
|
+
import { randomBytes as randomBytes2 } from "crypto";
|
|
714
|
+
import * as path3 from "path";
|
|
715
|
+
var nodeFsLayer = {
|
|
716
|
+
accessSync: (target, mode) => nodeFs.accessSync(target, mode),
|
|
717
|
+
readSync: (fd, buffer, offset, length, position) => nodeFs.readSync(fd, buffer, offset, length, position),
|
|
718
|
+
openSync: (p, flags, mode) => nodeFs.openSync(p, flags, mode),
|
|
719
|
+
writeSync: (fd, buffer) => nodeFs.writeSync(fd, buffer),
|
|
720
|
+
fsyncSync: (fd) => nodeFs.fsyncSync(fd),
|
|
721
|
+
fchmodSync: (fd, mode) => nodeFs.fchmodSync(fd, mode),
|
|
722
|
+
fchownSync: (fd, uid, gid) => nodeFs.fchownSync(fd, uid, gid),
|
|
723
|
+
closeSync: (fd) => nodeFs.closeSync(fd),
|
|
724
|
+
renameSync: (from, to) => nodeFs.renameSync(from, to),
|
|
725
|
+
unlinkSync: (p) => nodeFs.unlinkSync(p),
|
|
726
|
+
lstatSync: (p) => nodeFs.lstatSync(p),
|
|
727
|
+
fstatSync: (fd) => nodeFs.fstatSync(fd),
|
|
728
|
+
readFileSync: (fd) => nodeFs.readFileSync(fd),
|
|
729
|
+
mkdirSync: (p, mode) => {
|
|
730
|
+
nodeFs.mkdirSync(p, { mode });
|
|
731
|
+
},
|
|
732
|
+
realpathSync: (p) => nodeFs.realpathSync(p)
|
|
733
|
+
};
|
|
734
|
+
var { O_WRONLY, O_CREAT, O_EXCL, O_NOFOLLOW, O_RDONLY } = nodeFs.constants;
|
|
735
|
+
function quietly2(fn) {
|
|
736
|
+
try {
|
|
737
|
+
fn();
|
|
738
|
+
} catch {
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
function lstatOrNull2(filePath, fs5 = nodeFsLayer) {
|
|
742
|
+
try {
|
|
743
|
+
return fs5.lstatSync(filePath);
|
|
744
|
+
} catch (error) {
|
|
745
|
+
if (errnoOf(error) === "ENOENT") return null;
|
|
746
|
+
throw toSafeFsError(error, filePath, "inspect");
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
function assertNoSymlinkAncestors(root, rel, fs5 = nodeFsLayer) {
|
|
750
|
+
const normalized = path3.normalize(rel);
|
|
751
|
+
if (path3.isAbsolute(normalized) || normalized === ".." || normalized.startsWith(`..${path3.sep}`)) {
|
|
752
|
+
throw new SafeFsError(
|
|
753
|
+
"unsupported-target",
|
|
754
|
+
path3.join(root, rel),
|
|
755
|
+
`Refusing ${rel}: it does not stay under ${root}`
|
|
756
|
+
);
|
|
757
|
+
}
|
|
758
|
+
let current = root;
|
|
759
|
+
for (const segment of path3.dirname(normalized).split(path3.sep)) {
|
|
760
|
+
if (!segment || segment === ".") continue;
|
|
761
|
+
current = path3.join(current, segment);
|
|
762
|
+
const stats = lstatOrNull2(current, fs5);
|
|
763
|
+
if (stats === null) return;
|
|
764
|
+
if (stats.isSymbolicLink()) {
|
|
765
|
+
throw new SafeFsError(
|
|
766
|
+
"unsafe-link",
|
|
767
|
+
current,
|
|
768
|
+
`Refusing to go through ${current}: it is a symbolic link`
|
|
769
|
+
);
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
function openContainedFile(root, rel, fs5 = nodeFsLayer) {
|
|
774
|
+
assertNoSymlinkAncestors(root, rel, fs5);
|
|
775
|
+
const target = path3.join(root, rel);
|
|
776
|
+
const fd = guarded(target, "open", () => fs5.openSync(target, READ_FLAGS | O_NOFOLLOW));
|
|
777
|
+
try {
|
|
778
|
+
const stats = fs5.fstatSync(fd);
|
|
779
|
+
if (stats.isDirectory()) {
|
|
780
|
+
throw new SafeFsError("output-is-directory", target, `${target} is a directory`);
|
|
781
|
+
}
|
|
782
|
+
if (!stats.isFile()) {
|
|
783
|
+
throw new SafeFsError("not-regular", target, `${target} is not a regular file`);
|
|
784
|
+
}
|
|
785
|
+
if (!sameFile(fs5.lstatSync(target), stats) || fs5.realpathSync(target) !== path3.join(fs5.realpathSync(root), rel)) {
|
|
786
|
+
throw new SafeFsError("unsafe-link", target, `${target} changed while it was being opened`);
|
|
787
|
+
}
|
|
788
|
+
return { fd, stats };
|
|
789
|
+
} catch (error) {
|
|
790
|
+
quietly2(() => fs5.closeSync(fd));
|
|
791
|
+
throw toSafeFsError(error, target, "open");
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
async function readContainedFile(root, rel, maxBytes, options = {}) {
|
|
795
|
+
const layer = options.fs;
|
|
796
|
+
return readContainedFileAsync(
|
|
797
|
+
root,
|
|
798
|
+
rel,
|
|
799
|
+
maxBytes,
|
|
800
|
+
options.readFs ?? (layer === void 0 || layer === nodeFsLayer ? void 0 : asyncFsFromSync(layer, options.signal)),
|
|
801
|
+
options.signal
|
|
802
|
+
);
|
|
803
|
+
}
|
|
804
|
+
function writeExclusiveNoFollow(filePath, bytes, options = {}) {
|
|
805
|
+
const fs5 = options.fs ?? nodeFsLayer;
|
|
806
|
+
let fd;
|
|
807
|
+
try {
|
|
808
|
+
fd = fs5.openSync(filePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, options.mode ?? 438);
|
|
809
|
+
} catch (error) {
|
|
810
|
+
if (errnoOf(error) === "EEXIST" && isSymlink(filePath, fs5)) {
|
|
811
|
+
throw new SafeFsError(
|
|
812
|
+
"unsafe-link",
|
|
813
|
+
filePath,
|
|
814
|
+
`Refusing to write ${filePath}: a symbolic link already sits at that name`
|
|
815
|
+
);
|
|
816
|
+
}
|
|
817
|
+
throw toSafeFsError(error, filePath, "create");
|
|
818
|
+
}
|
|
819
|
+
try {
|
|
820
|
+
let offset = 0;
|
|
821
|
+
while (offset < bytes.length) {
|
|
822
|
+
const written = fs5.writeSync(fd, bytes.subarray(offset));
|
|
823
|
+
if (written <= 0) {
|
|
824
|
+
throw new SafeFsError(
|
|
825
|
+
"io-error",
|
|
826
|
+
filePath,
|
|
827
|
+
`Cannot write ${filePath}: write made no progress`
|
|
828
|
+
);
|
|
829
|
+
}
|
|
830
|
+
offset += written;
|
|
831
|
+
}
|
|
832
|
+
if (options.exactOwner !== void 0) {
|
|
833
|
+
const { uid, gid } = options.exactOwner;
|
|
834
|
+
try {
|
|
835
|
+
fs5.fchownSync(fd, uid, gid);
|
|
836
|
+
} catch (error) {
|
|
837
|
+
throw new SafeFsError(
|
|
838
|
+
"unsupported-target",
|
|
839
|
+
filePath,
|
|
840
|
+
`Cannot give ${filePath} its owner (uid ${uid}, gid ${gid})`,
|
|
841
|
+
error
|
|
842
|
+
);
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
if (options.exactMode !== void 0) fs5.fchmodSync(fd, options.exactMode);
|
|
846
|
+
fs5.fsyncSync(fd);
|
|
847
|
+
const identity = snapshotIdentity(fs5.fstatSync(fd));
|
|
848
|
+
fs5.closeSync(fd);
|
|
849
|
+
return identity;
|
|
850
|
+
} catch (error) {
|
|
851
|
+
quietly2(() => fs5.closeSync(fd));
|
|
852
|
+
unlinkQuietly(filePath, fs5);
|
|
853
|
+
throw toSafeFsError(error, filePath, "write");
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
function atomicReplace(target, bytes, options = {}) {
|
|
857
|
+
const fs5 = options.fs ?? nodeFsLayer;
|
|
858
|
+
const parent = guarded(target, "resolve parent", () => fs5.realpathSync(path3.dirname(target)));
|
|
859
|
+
const existing = inspectReplaceTarget(target, fs5);
|
|
860
|
+
assertExpectedTarget(target, existing, options);
|
|
861
|
+
const exactOwner = options.preserveOwner && existing ? ownerToRestore(target, existing) : void 0;
|
|
862
|
+
const random = options.randomName ?? defaultRandomName;
|
|
863
|
+
const temp = path3.join(path3.dirname(target), `.${path3.basename(target)}.${random()}.tmp`);
|
|
864
|
+
let identity;
|
|
865
|
+
try {
|
|
866
|
+
identity = writeExclusiveNoFollow(temp, bytes, {
|
|
867
|
+
fs: fs5,
|
|
868
|
+
exactMode: options.preserveMode && existing ? existing.mode : void 0,
|
|
869
|
+
exactOwner
|
|
870
|
+
});
|
|
871
|
+
} catch (error) {
|
|
872
|
+
if (error instanceof SafeFsError && error.code === "unsupported-target") {
|
|
873
|
+
throw new SafeFsError(
|
|
874
|
+
"unsupported-target",
|
|
875
|
+
target,
|
|
876
|
+
`Refusing to replace ${target}: its owner could not be preserved on the replacement`,
|
|
877
|
+
error.cause
|
|
878
|
+
);
|
|
879
|
+
}
|
|
880
|
+
if (error instanceof SafeFsError && error.code !== "unsafe-link" && error.cause !== void 0) {
|
|
881
|
+
throw toSafeFsError(error.cause, target, "write");
|
|
882
|
+
}
|
|
883
|
+
throw error;
|
|
884
|
+
}
|
|
885
|
+
try {
|
|
886
|
+
if (fs5.realpathSync(path3.dirname(target)) !== parent) {
|
|
887
|
+
throw new SafeFsError(
|
|
888
|
+
"identity-changed",
|
|
889
|
+
target,
|
|
890
|
+
`Refusing to replace ${target}: its parent directory moved`
|
|
891
|
+
);
|
|
892
|
+
}
|
|
893
|
+
assertExpectedTarget(target, inspectReplaceTarget(target, fs5), options);
|
|
894
|
+
options.beforeCommit?.();
|
|
895
|
+
} catch (error) {
|
|
896
|
+
unlinkQuietly(temp, fs5);
|
|
897
|
+
throw toSafeFsError(error, target, "replace");
|
|
898
|
+
}
|
|
899
|
+
finishReplace(temp, target, fs5);
|
|
900
|
+
return { identity, replaced: existing !== null };
|
|
901
|
+
}
|
|
902
|
+
function finishReplace(temp, target, fs5) {
|
|
903
|
+
try {
|
|
904
|
+
fs5.renameSync(temp, target);
|
|
905
|
+
} catch (error) {
|
|
906
|
+
unlinkQuietly(temp, fs5);
|
|
907
|
+
throw toSafeFsError(error, target, "replace");
|
|
908
|
+
}
|
|
909
|
+
syncDirectoryQuietly(path3.dirname(target), fs5);
|
|
910
|
+
}
|
|
911
|
+
function inspectReplaceTarget(target, fs5 = nodeFsLayer) {
|
|
912
|
+
const stats = lstatOrNull2(target, fs5);
|
|
913
|
+
if (stats === null) return null;
|
|
914
|
+
return replacementIdentity(target, stats);
|
|
915
|
+
}
|
|
916
|
+
function defaultRandomName() {
|
|
917
|
+
return randomBytes2(6).toString("hex");
|
|
918
|
+
}
|
|
919
|
+
function isSymlink(filePath, fs5) {
|
|
920
|
+
try {
|
|
921
|
+
return fs5.lstatSync(filePath).isSymbolicLink();
|
|
922
|
+
} catch {
|
|
923
|
+
return false;
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
function unlinkQuietly(filePath, fs5 = nodeFsLayer) {
|
|
927
|
+
quietly2(() => fs5.unlinkSync(filePath));
|
|
928
|
+
}
|
|
929
|
+
function syncDirectoryQuietly(dir, fs5) {
|
|
930
|
+
quietly2(() => {
|
|
931
|
+
const fd = fs5.openSync(dir, O_RDONLY);
|
|
932
|
+
try {
|
|
933
|
+
fs5.fsyncSync(fd);
|
|
934
|
+
} finally {
|
|
935
|
+
quietly2(() => fs5.closeSync(fd));
|
|
936
|
+
}
|
|
937
|
+
});
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
// src/node-scan-fs.ts
|
|
941
|
+
import { opendir, stat, readlink } from "fs/promises";
|
|
942
|
+
var nodeScanFsLayer = {
|
|
943
|
+
...nodeReadFsLayer,
|
|
944
|
+
stat: (target) => stat(target),
|
|
945
|
+
opendir: (target) => opendir(target),
|
|
946
|
+
readlink: (target) => readlink(target, { encoding: "buffer" })
|
|
947
|
+
};
|
|
948
|
+
|
|
949
|
+
// src/publication-fs.ts
|
|
950
|
+
import { mkdir } from "fs/promises";
|
|
951
|
+
var nodePublicationFileSystem = {
|
|
952
|
+
inspection: nodeFsLayer,
|
|
953
|
+
files: nodeAsyncFsLayer,
|
|
954
|
+
mkdir: async (target, mode) => {
|
|
955
|
+
await mkdir(target, { mode });
|
|
956
|
+
},
|
|
957
|
+
currentUid: () => process.getuid?.()
|
|
958
|
+
};
|
|
959
|
+
function resolvePublicationFileSystem(options) {
|
|
960
|
+
if (options.publicationFs) return options.publicationFs;
|
|
961
|
+
const legacy = options.fs;
|
|
962
|
+
if (!legacy || legacy === nodeFsLayer) return nodePublicationFileSystem;
|
|
963
|
+
return {
|
|
964
|
+
inspection: legacy,
|
|
965
|
+
files: asyncFsFromSync(legacy, options.signal),
|
|
966
|
+
async mkdir(target, mode) {
|
|
967
|
+
legacy.mkdirSync(target, mode);
|
|
968
|
+
},
|
|
969
|
+
currentUid: () => process.getuid?.()
|
|
970
|
+
};
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
// src/remote-temp.ts
|
|
974
|
+
import * as fs3 from "fs";
|
|
975
|
+
import * as os from "os";
|
|
976
|
+
import * as path4 from "path";
|
|
977
|
+
var nodeTemporaryCloneStorage = {
|
|
978
|
+
create: () => fs3.promises.mkdtemp(path4.join(os.tmpdir(), "self-review-")),
|
|
979
|
+
remove: (directory) => fs3.promises.rm(directory, { recursive: true, force: true }),
|
|
980
|
+
removeSync: (directory) => fs3.rmSync(directory, { recursive: true, force: true })
|
|
981
|
+
};
|
|
982
|
+
|
|
983
|
+
// src/command-runner.ts
|
|
984
|
+
import { spawn } from "child_process";
|
|
985
|
+
|
|
986
|
+
// src/process-tree.ts
|
|
987
|
+
import { execFile } from "child_process";
|
|
988
|
+
import { readFile } from "fs/promises";
|
|
989
|
+
import { setTimeout as delay } from "timers/promises";
|
|
990
|
+
async function snapshot() {
|
|
991
|
+
const output = await new Promise((resolve5, reject) => {
|
|
992
|
+
execFile(
|
|
993
|
+
"ps",
|
|
994
|
+
["-axo", "pid=,ppid=,stat=,lstart="],
|
|
995
|
+
{ encoding: "utf8", timeout: 1e3, maxBuffer: 8 * 1024 * 1024 },
|
|
996
|
+
(error, stdout) => error ? reject(error) : resolve5(stdout)
|
|
997
|
+
);
|
|
998
|
+
});
|
|
999
|
+
return output.split("\n").flatMap((line) => {
|
|
1000
|
+
const match = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.+)$/.exec(line);
|
|
1001
|
+
return match ? [{ pid: Number(match[1]), parent: Number(match[2]), state: match[3], birth: match[4] }] : [];
|
|
1002
|
+
});
|
|
1003
|
+
}
|
|
1004
|
+
async function linuxBirth(pid) {
|
|
1005
|
+
const stat2 = await readFile(`/proc/${pid}/stat`, "utf8");
|
|
1006
|
+
return stat2.slice(stat2.lastIndexOf(")") + 2).split(" ")[19];
|
|
1007
|
+
}
|
|
1008
|
+
async function terminateProcessTree(child, graceMs) {
|
|
1009
|
+
if (child.pid === void 0) return;
|
|
1010
|
+
child.kill("SIGSTOP");
|
|
1011
|
+
const owned = /* @__PURE__ */ new Map();
|
|
1012
|
+
const births = /* @__PURE__ */ new Map();
|
|
1013
|
+
const signal = async (entry, name) => {
|
|
1014
|
+
try {
|
|
1015
|
+
if (process.platform === "linux" && await linuxBirth(entry.pid) !== births.get(entry.pid)) {
|
|
1016
|
+
owned.delete(entry.pid);
|
|
1017
|
+
return;
|
|
1018
|
+
}
|
|
1019
|
+
if (process.platform !== "linux") {
|
|
1020
|
+
const current = (await snapshot()).find((process2) => process2.pid === entry.pid);
|
|
1021
|
+
if (!current || current.birth !== entry.birth || current.state.startsWith("Z")) {
|
|
1022
|
+
owned.delete(entry.pid);
|
|
1023
|
+
return;
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
process.kill(entry.pid, name);
|
|
1027
|
+
} catch (error) {
|
|
1028
|
+
if (error.code !== "ESRCH" && error.code !== "ENOENT")
|
|
1029
|
+
throw error;
|
|
1030
|
+
owned.delete(entry.pid);
|
|
1031
|
+
}
|
|
1032
|
+
};
|
|
1033
|
+
try {
|
|
1034
|
+
const discoveryDeadline = Date.now() + 2e3;
|
|
1035
|
+
while (true) {
|
|
1036
|
+
const processes = await snapshot();
|
|
1037
|
+
const added = [];
|
|
1038
|
+
for (const entry of processes) {
|
|
1039
|
+
if (owned.has(entry.pid)) continue;
|
|
1040
|
+
if (entry.pid !== child.pid && !owned.has(entry.parent)) continue;
|
|
1041
|
+
if (entry.state.startsWith("Z")) continue;
|
|
1042
|
+
if (process.platform === "linux") {
|
|
1043
|
+
try {
|
|
1044
|
+
births.set(entry.pid, await linuxBirth(entry.pid));
|
|
1045
|
+
} catch {
|
|
1046
|
+
continue;
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
owned.set(entry.pid, entry);
|
|
1050
|
+
added.push(entry);
|
|
1051
|
+
await signal(entry, "SIGSTOP");
|
|
1052
|
+
}
|
|
1053
|
+
if (added.length === 0) break;
|
|
1054
|
+
if (Date.now() >= discoveryDeadline) throw new Error("Process tree discovery timed out");
|
|
1055
|
+
}
|
|
1056
|
+
for (const entry of [...owned.values()].reverse()) await signal(entry, "SIGTERM");
|
|
1057
|
+
for (const entry of [...owned.values()].reverse()) await signal(entry, "SIGCONT");
|
|
1058
|
+
const killAt = Date.now() + graceMs;
|
|
1059
|
+
const deadline = killAt + 2e3;
|
|
1060
|
+
while (owned.size > 0) {
|
|
1061
|
+
const current = new Map((await snapshot()).map((entry) => [entry.pid, entry]));
|
|
1062
|
+
for (const entry of owned.values()) {
|
|
1063
|
+
const live = current.get(entry.pid);
|
|
1064
|
+
if (!live || live.birth !== entry.birth || live.state.startsWith("Z")) {
|
|
1065
|
+
owned.delete(entry.pid);
|
|
1066
|
+
} else if (Date.now() >= killAt) {
|
|
1067
|
+
await signal(entry, "SIGKILL");
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
if (owned.size === 0) return;
|
|
1071
|
+
if (Date.now() >= deadline) throw new Error("Command process tree did not terminate");
|
|
1072
|
+
await delay(25);
|
|
1073
|
+
}
|
|
1074
|
+
} finally {
|
|
1075
|
+
child.kill("SIGKILL");
|
|
1076
|
+
for (const entry of owned.values()) await signal(entry, "SIGKILL");
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
// src/command-runner.ts
|
|
1081
|
+
var KILL_GRACE_MS = 2e3;
|
|
1082
|
+
var MAX_OUTPUT_BYTES = 50 * 1024 * 1024;
|
|
1083
|
+
var CommandOutputLimitError = class extends Error {
|
|
1084
|
+
constructor(command, maxBytes) {
|
|
1085
|
+
super(`${command} produced more than ${maxBytes} bytes`);
|
|
1086
|
+
this.code = "ERR_CHILD_PROCESS_STDIO_MAXBUFFER";
|
|
1087
|
+
this.name = "CommandOutputLimitError";
|
|
1088
|
+
}
|
|
1089
|
+
};
|
|
1090
|
+
function repositoryEnvironment(isolated = false) {
|
|
1091
|
+
const env = { ...process.env };
|
|
1092
|
+
for (const key of ["GIT_DIR", "GIT_COMMON_DIR", "GIT_WORK_TREE", "GIT_PREFIX"]) delete env[key];
|
|
1093
|
+
if (isolated) {
|
|
1094
|
+
for (const key of [
|
|
1095
|
+
"GIT_INDEX_FILE",
|
|
1096
|
+
"GIT_OBJECT_DIRECTORY",
|
|
1097
|
+
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
|
|
1098
|
+
"GIT_NAMESPACE",
|
|
1099
|
+
"GIT_CEILING_DIRECTORIES",
|
|
1100
|
+
"GIT_SHALLOW_FILE",
|
|
1101
|
+
"GIT_IMPLICIT_WORK_TREE"
|
|
1102
|
+
])
|
|
1103
|
+
delete env[key];
|
|
1104
|
+
}
|
|
1105
|
+
return env;
|
|
1106
|
+
}
|
|
1107
|
+
var runBufferedCommand = (command, args, options = {}) => new Promise((resolve5, reject) => {
|
|
1108
|
+
const { signal, timeoutMs } = options;
|
|
1109
|
+
if (signal?.aborted) {
|
|
1110
|
+
reject(new CommandCancelledError("aborted", command, args));
|
|
1111
|
+
return;
|
|
1112
|
+
}
|
|
1113
|
+
const maxOutputBytes = options.maxOutputBytes ?? MAX_OUTPUT_BYTES;
|
|
1114
|
+
if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 0) {
|
|
1115
|
+
reject(new RangeError("maxOutputBytes must be a nonnegative safe integer"));
|
|
1116
|
+
return;
|
|
1117
|
+
}
|
|
1118
|
+
if (timeoutMs !== void 0 && (!Number.isFinite(timeoutMs) || timeoutMs < 0)) {
|
|
1119
|
+
reject(new RangeError("timeoutMs must be a nonnegative finite number"));
|
|
1120
|
+
return;
|
|
1121
|
+
}
|
|
1122
|
+
const child = spawn(command, args, {
|
|
1123
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1124
|
+
cwd: options.cwd,
|
|
1125
|
+
env: command === "git" && (options.gitEnvironment === "isolated" || options.cwd !== void 0 || args.includes("-C")) ? repositoryEnvironment(options.gitEnvironment === "isolated") : void 0
|
|
1126
|
+
});
|
|
1127
|
+
const stdout = [];
|
|
1128
|
+
const stderr = [];
|
|
1129
|
+
let outputBytes = 0;
|
|
1130
|
+
let settled = false;
|
|
1131
|
+
let cancelled = null;
|
|
1132
|
+
let overflowed = false;
|
|
1133
|
+
let termination;
|
|
1134
|
+
let timeoutTimer;
|
|
1135
|
+
const killChild = () => {
|
|
1136
|
+
termination ?? (termination = terminateProcessTree(child, KILL_GRACE_MS));
|
|
1137
|
+
const closePipes = () => {
|
|
1138
|
+
child.stdout?.destroy();
|
|
1139
|
+
child.stderr?.destroy();
|
|
1140
|
+
};
|
|
1141
|
+
void termination.then(
|
|
1142
|
+
// A naturally exited parent can leave inherited pipes in a reparented helper.
|
|
1143
|
+
// Pipe closure must not hold cancellation open after tree shutdown settles.
|
|
1144
|
+
closePipes,
|
|
1145
|
+
(error) => {
|
|
1146
|
+
closePipes();
|
|
1147
|
+
settle(() => reject(error));
|
|
1148
|
+
}
|
|
1149
|
+
);
|
|
1150
|
+
};
|
|
1151
|
+
const cancel = (reason) => {
|
|
1152
|
+
if (settled || cancelled !== null) return;
|
|
1153
|
+
cancelled = reason;
|
|
1154
|
+
killChild();
|
|
1155
|
+
};
|
|
1156
|
+
const onAbort = () => cancel("aborted");
|
|
1157
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1158
|
+
if (timeoutMs !== void 0 && timeoutMs > 0) {
|
|
1159
|
+
timeoutTimer = setTimeout(() => cancel("timeout"), timeoutMs);
|
|
1160
|
+
}
|
|
1161
|
+
const settle = (outcome) => {
|
|
1162
|
+
if (settled) return;
|
|
1163
|
+
settled = true;
|
|
1164
|
+
if (timeoutTimer) clearTimeout(timeoutTimer);
|
|
1165
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1166
|
+
outcome();
|
|
1167
|
+
};
|
|
1168
|
+
const collect = (sink) => (chunk) => {
|
|
1169
|
+
outputBytes += chunk.length;
|
|
1170
|
+
if (outputBytes > maxOutputBytes) {
|
|
1171
|
+
if (!overflowed) {
|
|
1172
|
+
overflowed = true;
|
|
1173
|
+
killChild();
|
|
1174
|
+
}
|
|
1175
|
+
return;
|
|
1176
|
+
}
|
|
1177
|
+
sink.push(chunk);
|
|
1178
|
+
};
|
|
1179
|
+
child.stdout?.on("data", collect(stdout));
|
|
1180
|
+
child.stderr?.on("data", collect(stderr));
|
|
1181
|
+
child.on("error", (error) => settle(() => reject(error)));
|
|
1182
|
+
child.on("close", async (code, exitSignal) => {
|
|
1183
|
+
try {
|
|
1184
|
+
await termination;
|
|
1185
|
+
} catch (error) {
|
|
1186
|
+
settle(() => reject(error));
|
|
1187
|
+
return;
|
|
1188
|
+
}
|
|
1189
|
+
settle(() => {
|
|
1190
|
+
if (cancelled !== null) {
|
|
1191
|
+
reject(new CommandCancelledError(cancelled, command, args));
|
|
1192
|
+
return;
|
|
1193
|
+
}
|
|
1194
|
+
if (overflowed) {
|
|
1195
|
+
reject(new CommandOutputLimitError(command, maxOutputBytes));
|
|
1196
|
+
return;
|
|
1197
|
+
}
|
|
1198
|
+
let stderrBytes = Buffer.concat(stderr);
|
|
1199
|
+
if (code === null && exitSignal) {
|
|
1200
|
+
const separator = stderrBytes.length === 0 || stderrBytes[stderrBytes.length - 1] === 10 ? "" : "\n";
|
|
1201
|
+
stderrBytes = Buffer.concat([
|
|
1202
|
+
stderrBytes,
|
|
1203
|
+
Buffer.from(`${separator}(killed by ${exitSignal})
|
|
1204
|
+
`)
|
|
1205
|
+
]);
|
|
1206
|
+
}
|
|
1207
|
+
resolve5({
|
|
1208
|
+
stdout: Buffer.concat(stdout),
|
|
1209
|
+
stderr: stderrBytes,
|
|
1210
|
+
exitCode: code ?? 1
|
|
1211
|
+
});
|
|
1212
|
+
});
|
|
1213
|
+
});
|
|
1214
|
+
});
|
|
1215
|
+
var defaultGitRunner = async (command, args, options) => {
|
|
1216
|
+
const result = await runBufferedCommand(command, args, options);
|
|
1217
|
+
return {
|
|
1218
|
+
stdout: result.stdout.toString("utf-8"),
|
|
1219
|
+
stderr: result.stderr.toString("utf-8"),
|
|
1220
|
+
exitCode: result.exitCode
|
|
1221
|
+
};
|
|
1222
|
+
};
|
|
1223
|
+
|
|
1224
|
+
// src/loaded-snapshot.ts
|
|
1225
|
+
import path5 from "path";
|
|
1226
|
+
var SNAPSHOT = /* @__PURE__ */ Symbol.for("@self-review/core/loaded-snapshot");
|
|
1227
|
+
var CAPTURE = /* @__PURE__ */ Symbol.for("@self-review/core/source-capture");
|
|
1228
|
+
var RELOAD_REVIEW = "The reviewed source changed or could not be captured. Reload the review before reading more content.";
|
|
1229
|
+
function sourceStamp(stats) {
|
|
1230
|
+
return [stats.dev, stats.ino, stats.mode, stats.size, stats.mtimeMs, stats.ctimeMs].join(":");
|
|
1231
|
+
}
|
|
1232
|
+
function identityStamp(identity) {
|
|
1233
|
+
return JSON.stringify([identity, [...identity.fileSources ?? []]]);
|
|
1234
|
+
}
|
|
1235
|
+
function loadedSnapshot(identity) {
|
|
1236
|
+
return identity[SNAPSHOT];
|
|
1237
|
+
}
|
|
1238
|
+
function recordLoadedSnapshot(identity, physical, index = /* @__PURE__ */ new Map(), gitOptions, blobRunner, indexCapture) {
|
|
1239
|
+
const snapshot2 = {
|
|
1240
|
+
identityStamp: identityStamp(identity),
|
|
1241
|
+
physical,
|
|
1242
|
+
index,
|
|
1243
|
+
gitOptions,
|
|
1244
|
+
blobRunner,
|
|
1245
|
+
indexCapture
|
|
1246
|
+
};
|
|
1247
|
+
Object.defineProperty(identity, SNAPSHOT, { value: snapshot2, configurable: true });
|
|
1248
|
+
return snapshot2;
|
|
1249
|
+
}
|
|
1250
|
+
var loadedReviews = /* @__PURE__ */ new WeakMap();
|
|
1251
|
+
function createLoadedReview(identity, files, snapshot2) {
|
|
1252
|
+
const paths = new Set(files.flatMap((file) => [file.oldPath, file.newPath].filter(Boolean)));
|
|
1253
|
+
const state = { identity, reviewedPaths: paths, snapshot: snapshot2 };
|
|
1254
|
+
const review = Object.freeze({});
|
|
1255
|
+
loadedReviews.set(review, state);
|
|
1256
|
+
return review;
|
|
1257
|
+
}
|
|
1258
|
+
function restrictLoadedReview(review, files) {
|
|
1259
|
+
const state = loadedReviewState(review);
|
|
1260
|
+
for (const file of files) {
|
|
1261
|
+
for (const filePath of [file.oldPath, file.newPath]) {
|
|
1262
|
+
if (filePath && !state.reviewedPaths.has(filePath))
|
|
1263
|
+
throw new TypeError("A filtered loaded review cannot add a source path");
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
return createLoadedReview(state.identity, files, state.snapshot);
|
|
1267
|
+
}
|
|
1268
|
+
function loadedReviewState(review) {
|
|
1269
|
+
const state = loadedReviews.get(review);
|
|
1270
|
+
if (!state) throw new TypeError("Expected an original LoadedReview capability");
|
|
1271
|
+
return state;
|
|
1272
|
+
}
|
|
1273
|
+
function loadedReviewIdentity(review) {
|
|
1274
|
+
return loadedReviewState(review).identity;
|
|
1275
|
+
}
|
|
1276
|
+
function loadedReviewPaths(review) {
|
|
1277
|
+
return new Set(loadedReviewState(review).reviewedPaths);
|
|
1278
|
+
}
|
|
1279
|
+
function recordSourceCapture(file, capture) {
|
|
1280
|
+
if (capture) Object.defineProperty(file, CAPTURE, { value: capture });
|
|
1281
|
+
}
|
|
1282
|
+
function sourceCapture(file) {
|
|
1283
|
+
return file[CAPTURE];
|
|
1284
|
+
}
|
|
1285
|
+
function admitSyntheticSnapshot(identity, files) {
|
|
1286
|
+
const physical = /* @__PURE__ */ new Map();
|
|
1287
|
+
for (const file of files) {
|
|
1288
|
+
const capture = sourceCapture(file);
|
|
1289
|
+
if (capture) physical.set(file.newPath || file.oldPath, capture);
|
|
1290
|
+
}
|
|
1291
|
+
return createLoadedReview(identity, files, recordLoadedSnapshot(identity, physical));
|
|
1292
|
+
}
|
|
1293
|
+
function captureSourceReads(layer = nodeReadFsLayer, signal, onDrift = "throw") {
|
|
1294
|
+
const captures = /* @__PURE__ */ new Map();
|
|
1295
|
+
const drifted = /* @__PURE__ */ new Set();
|
|
1296
|
+
const readFs = {
|
|
1297
|
+
readAllocation: "bounded",
|
|
1298
|
+
realpath: (target) => layer.realpath(target),
|
|
1299
|
+
lstat: (target) => layer.lstat(target),
|
|
1300
|
+
async open(target, flags, mode) {
|
|
1301
|
+
const handle = await layer.open(target, flags, mode);
|
|
1302
|
+
let stamp;
|
|
1303
|
+
let physical;
|
|
1304
|
+
try {
|
|
1305
|
+
checkLoadingCancelled(signal);
|
|
1306
|
+
stamp = sourceStamp(await handle.stat());
|
|
1307
|
+
physical = await layer.realpath(target);
|
|
1308
|
+
checkLoadingCancelled(signal);
|
|
1309
|
+
} catch (error) {
|
|
1310
|
+
await handle.close();
|
|
1311
|
+
throw error;
|
|
1312
|
+
}
|
|
1313
|
+
const wrapped = {
|
|
1314
|
+
stat: () => handle.stat(),
|
|
1315
|
+
read: (buffer, offset, length, position) => handle.read(buffer, offset, length, position),
|
|
1316
|
+
async close() {
|
|
1317
|
+
try {
|
|
1318
|
+
checkLoadingCancelled(signal);
|
|
1319
|
+
const after = await handle.stat();
|
|
1320
|
+
const named = await layer.lstat(physical);
|
|
1321
|
+
checkLoadingCancelled(signal);
|
|
1322
|
+
if (sourceStamp(after) !== stamp || sourceStamp(named) !== stamp || await layer.realpath(target) !== physical) {
|
|
1323
|
+
throw new SafeFsError("identity-changed", target, RELOAD_REVIEW);
|
|
1324
|
+
}
|
|
1325
|
+
captures.set(path5.resolve(target), { target: physical, stamp, readFs: layer });
|
|
1326
|
+
} catch (error) {
|
|
1327
|
+
checkLoadingCancelled(signal);
|
|
1328
|
+
drifted.add(path5.resolve(target));
|
|
1329
|
+
if (onDrift === "throw")
|
|
1330
|
+
throw new SafeFsError("identity-changed", target, RELOAD_REVIEW, error);
|
|
1331
|
+
} finally {
|
|
1332
|
+
await handle.close();
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
};
|
|
1336
|
+
return wrapped;
|
|
1337
|
+
}
|
|
1338
|
+
};
|
|
1339
|
+
return { readFs, captures, drifted };
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
// src/synthetic-diagnostics.ts
|
|
1343
|
+
function syntheticDiagnostics(state, budgets) {
|
|
1344
|
+
const { representationOmissions, representationExhausted, tooLarge, overTotal, unreadable } = state;
|
|
1345
|
+
const diagnostics = [];
|
|
1346
|
+
if (representationOmissions.length > 0) {
|
|
1347
|
+
diagnostics.push(
|
|
1348
|
+
`${countFiles(representationOmissions.length)} listed without content because a representation budget ran out: ${listPaths(representationOmissions)}`
|
|
1349
|
+
);
|
|
1350
|
+
}
|
|
1351
|
+
if (representationExhausted) diagnostics.push(representationExhausted);
|
|
1352
|
+
if (tooLarge.length > 0) {
|
|
1353
|
+
diagnostics.push(
|
|
1354
|
+
`${countFiles(tooLarge.length)} over the ${formatBytes(budgets.maxFileBytes)} per-file read budget ${tooLarge.length === 1 ? "is" : "are"} listed without content: ` + listPaths(tooLarge)
|
|
1355
|
+
);
|
|
1356
|
+
}
|
|
1357
|
+
if (overTotal.length > 0) {
|
|
1358
|
+
diagnostics.push(
|
|
1359
|
+
`The ${formatBytes(budgets.maxTotalBytes)} total read budget for this review ran out; ${countFiles(overTotal.length)} ${overTotal.length === 1 ? "is" : "are"} listed without content: ${listPaths(overTotal)}`
|
|
1360
|
+
);
|
|
1361
|
+
}
|
|
1362
|
+
if (unreadable.length > 0) {
|
|
1363
|
+
diagnostics.push(
|
|
1364
|
+
`${countFiles(unreadable.length)} could not be read and ${unreadable.length === 1 ? "is" : "are"} not shown: ${listPaths(unreadable)}`
|
|
1365
|
+
);
|
|
1366
|
+
}
|
|
1367
|
+
return diagnostics;
|
|
1368
|
+
}
|
|
1369
|
+
function createSeparatorDiagnostics(maxDiagnostics) {
|
|
1370
|
+
let emptyBeforeNextFile;
|
|
1371
|
+
const diagnostics = [];
|
|
1372
|
+
return {
|
|
1373
|
+
diagnostics,
|
|
1374
|
+
next(filePath, lineCount) {
|
|
1375
|
+
if (emptyBeforeNextFile !== void 0) {
|
|
1376
|
+
if (diagnostics.length < maxDiagnostics)
|
|
1377
|
+
diagnostics.push(
|
|
1378
|
+
`${emptyBeforeNextFile}: line beyond the counts of hunk @@ -0,0 +1,0 @@: ""`
|
|
1379
|
+
);
|
|
1380
|
+
else if (diagnostics.length === maxDiagnostics)
|
|
1381
|
+
diagnostics.push(
|
|
1382
|
+
"Further synthetic separator diagnostics omitted: diagnostic representation budget exceeded."
|
|
1383
|
+
);
|
|
1384
|
+
}
|
|
1385
|
+
emptyBeforeNextFile = lineCount === 0 ? filePath : void 0;
|
|
1386
|
+
}
|
|
1387
|
+
};
|
|
1388
|
+
}
|
|
1389
|
+
function overTotalReason(maxTotalBytes) {
|
|
1390
|
+
return `Not loaded: the ${formatBytes(maxTotalBytes)} total read budget for this review ran out before this file.`;
|
|
1391
|
+
}
|
|
1392
|
+
var LISTED_PATHS = 10;
|
|
1393
|
+
function listPaths(paths) {
|
|
1394
|
+
const shown = paths.slice(0, LISTED_PATHS).join(", ");
|
|
1395
|
+
const rest = paths.length - LISTED_PATHS;
|
|
1396
|
+
return rest > 0 ? `${shown}, and ${rest} more` : shown;
|
|
1397
|
+
}
|
|
1398
|
+
function countFiles(count) {
|
|
1399
|
+
return `${count} ${count === 1 ? "file" : "files"}`;
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
// src/synthetic-accounting.ts
|
|
1403
|
+
function createSourceAccounting(budgets) {
|
|
1404
|
+
const representation = createRepresentationBudget(budgets);
|
|
1405
|
+
const state = {
|
|
1406
|
+
representationOmissions: [],
|
|
1407
|
+
tooLarge: [],
|
|
1408
|
+
overTotal: [],
|
|
1409
|
+
unreadable: []
|
|
1410
|
+
};
|
|
1411
|
+
const omitted = /* @__PURE__ */ new Map();
|
|
1412
|
+
let totalRead = 0;
|
|
1413
|
+
let totalExhausted = false;
|
|
1414
|
+
function admit(filePath, source) {
|
|
1415
|
+
if (state.representationExhausted) {
|
|
1416
|
+
state.representationOmissions.push(filePath);
|
|
1417
|
+
omitted.set(filePath, state.representationExhausted);
|
|
1418
|
+
return { emit: true };
|
|
1419
|
+
}
|
|
1420
|
+
if (source === null) {
|
|
1421
|
+
state.overTotal.push(filePath);
|
|
1422
|
+
omitted.set(filePath, overTotalReason(budgets.maxTotalBytes));
|
|
1423
|
+
return { emit: true };
|
|
1424
|
+
}
|
|
1425
|
+
totalRead += source.bytesRead;
|
|
1426
|
+
switch (source.kind) {
|
|
1427
|
+
case "skip":
|
|
1428
|
+
return { emit: false };
|
|
1429
|
+
case "unreadable":
|
|
1430
|
+
state.unreadable.push(`${filePath} (${source.code})`);
|
|
1431
|
+
return { emit: false };
|
|
1432
|
+
case "binary":
|
|
1433
|
+
return { emit: true, source };
|
|
1434
|
+
case "too-large":
|
|
1435
|
+
state.tooLarge.push(filePath);
|
|
1436
|
+
omitted.set(
|
|
1437
|
+
filePath,
|
|
1438
|
+
`Not loaded: this file is ${formatBytes(source.size)}, over the ${formatBytes(budgets.maxFileBytes)} per-file read budget.`
|
|
1439
|
+
);
|
|
1440
|
+
return { emit: true };
|
|
1441
|
+
case "over-total":
|
|
1442
|
+
totalExhausted = true;
|
|
1443
|
+
state.overTotal.push(filePath);
|
|
1444
|
+
omitted.set(filePath, overTotalReason(budgets.maxTotalBytes));
|
|
1445
|
+
return { emit: true };
|
|
1446
|
+
case "symlink":
|
|
1447
|
+
case "text":
|
|
1448
|
+
return { emit: true, source };
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
return {
|
|
1452
|
+
representation,
|
|
1453
|
+
omitted,
|
|
1454
|
+
admit,
|
|
1455
|
+
beginFile() {
|
|
1456
|
+
try {
|
|
1457
|
+
representation.beginFile();
|
|
1458
|
+
return true;
|
|
1459
|
+
} catch (error) {
|
|
1460
|
+
if (!(error instanceof RepresentationLimitError)) throw error;
|
|
1461
|
+
state.representationExhausted = `${error.message} Loading stopped; remaining paths were not loaded.`;
|
|
1462
|
+
return false;
|
|
1463
|
+
}
|
|
1464
|
+
},
|
|
1465
|
+
omitRepresentation(filePath, error) {
|
|
1466
|
+
if (error.aggregate) state.representationExhausted = error.message;
|
|
1467
|
+
state.representationOmissions.push(filePath);
|
|
1468
|
+
omitted.set(filePath, error.message);
|
|
1469
|
+
},
|
|
1470
|
+
remaining: () => budgets.maxTotalBytes - totalRead,
|
|
1471
|
+
exhausted: () => totalExhausted || state.representationExhausted !== void 0,
|
|
1472
|
+
diagnostics: () => syntheticDiagnostics(state, budgets)
|
|
1473
|
+
};
|
|
1474
|
+
}
|
|
1475
|
+
|
|
1476
|
+
// src/git-path-quote.ts
|
|
1477
|
+
var C_STYLE_ESCAPES = {
|
|
1478
|
+
7: "\\a",
|
|
1479
|
+
8: "\\b",
|
|
1480
|
+
9: "\\t",
|
|
1481
|
+
10: "\\n",
|
|
1482
|
+
11: "\\v",
|
|
1483
|
+
12: "\\f",
|
|
1484
|
+
13: "\\r",
|
|
1485
|
+
34: '\\"',
|
|
1486
|
+
92: "\\\\"
|
|
1487
|
+
};
|
|
1488
|
+
function needsQuoting(byte) {
|
|
1489
|
+
return byte < 32 || byte >= 127 || byte === 34 || byte === 92;
|
|
1490
|
+
}
|
|
1491
|
+
function quoteGitPath(path9) {
|
|
1492
|
+
const bytes = Buffer.from(path9, "utf-8");
|
|
1493
|
+
if (!bytes.some(needsQuoting)) return path9;
|
|
1494
|
+
let quoted = '"';
|
|
1495
|
+
for (const byte of bytes) {
|
|
1496
|
+
const escape = C_STYLE_ESCAPES[byte];
|
|
1497
|
+
if (escape) {
|
|
1498
|
+
quoted += escape;
|
|
1499
|
+
} else if (byte < 32 || byte >= 127) {
|
|
1500
|
+
quoted += `\\${byte.toString(8).padStart(3, "0")}`;
|
|
1501
|
+
} else {
|
|
1502
|
+
quoted += String.fromCharCode(byte);
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
return `${quoted}"`;
|
|
1506
|
+
}
|
|
1507
|
+
|
|
1508
|
+
// src/synthetic-emitter.ts
|
|
1509
|
+
function* projectedLines(text) {
|
|
1510
|
+
let start = 0;
|
|
1511
|
+
for (let index = 0; index < text.lineCount; index++) {
|
|
1512
|
+
const end = text.text.indexOf("\n", start);
|
|
1513
|
+
const content = text.text.slice(start, end === -1 ? void 0 : end);
|
|
1514
|
+
start = end + 1;
|
|
1515
|
+
yield { content, number: index + 1 };
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
function createFilesEmitter() {
|
|
1519
|
+
const files = [];
|
|
1520
|
+
return {
|
|
1521
|
+
*emit(filePath, source, text, _mode) {
|
|
1522
|
+
const lines = [];
|
|
1523
|
+
if (text) {
|
|
1524
|
+
for (const line of projectedLines(text)) {
|
|
1525
|
+
lines.push({
|
|
1526
|
+
type: "addition",
|
|
1527
|
+
oldLineNumber: null,
|
|
1528
|
+
newLineNumber: line.number,
|
|
1529
|
+
content: line.content
|
|
1530
|
+
});
|
|
1531
|
+
if (line.number % 256 === 0) yield;
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
files.push({
|
|
1535
|
+
oldPath: "",
|
|
1536
|
+
newPath: filePath,
|
|
1537
|
+
changeType: "added",
|
|
1538
|
+
isBinary: source?.kind === "binary",
|
|
1539
|
+
hunks: text ? [
|
|
1540
|
+
{
|
|
1541
|
+
header: text.header,
|
|
1542
|
+
oldStart: 0,
|
|
1543
|
+
oldLines: 0,
|
|
1544
|
+
newStart: 1,
|
|
1545
|
+
newLines: text.lineCount,
|
|
1546
|
+
lines
|
|
1547
|
+
}
|
|
1548
|
+
] : []
|
|
1549
|
+
});
|
|
1550
|
+
},
|
|
1551
|
+
finish: () => ({ diff: "", files })
|
|
1552
|
+
};
|
|
1553
|
+
}
|
|
1554
|
+
function createPatchEmitter() {
|
|
1555
|
+
const diffs = [];
|
|
1556
|
+
return {
|
|
1557
|
+
*emit(filePath, source, text, mode = source?.kind === "symlink" ? "120000" : "100644") {
|
|
1558
|
+
const patch = [];
|
|
1559
|
+
if (text) {
|
|
1560
|
+
for (const line of projectedLines(text)) {
|
|
1561
|
+
patch.push(`+${line.content}`);
|
|
1562
|
+
if (line.number % 256 === 0) yield;
|
|
1563
|
+
}
|
|
1564
|
+
}
|
|
1565
|
+
const oldHeaderPath = quoteGitPath(`a/${filePath}`);
|
|
1566
|
+
const newHeaderPath = quoteGitPath(`b/${filePath}`);
|
|
1567
|
+
const header = `diff --git ${oldHeaderPath} ${newHeaderPath}
|
|
1568
|
+
new file mode ${mode}`;
|
|
1569
|
+
diffs.push(
|
|
1570
|
+
text ? `${header}
|
|
1571
|
+
--- /dev/null
|
|
1572
|
+
+++ ${newHeaderPath}
|
|
1573
|
+
${text.header}
|
|
1574
|
+
` + patch.join("\n") + (text.missingNewline ? "\n\" : "") : source?.kind === "binary" ? `${header}
|
|
1575
|
+
Binary files /dev/null and ${newHeaderPath} differ` : header
|
|
1576
|
+
);
|
|
1577
|
+
},
|
|
1578
|
+
finish: () => ({ diff: diffs.join("\n"), files: [] })
|
|
1579
|
+
};
|
|
1580
|
+
}
|
|
1581
|
+
|
|
1582
|
+
// src/synthetic-text.ts
|
|
1583
|
+
function* projectText(content, representation) {
|
|
1584
|
+
let lineCount = 0;
|
|
1585
|
+
for (let start = 0; start < content.length; start += 64 * 1024) {
|
|
1586
|
+
let count = 0;
|
|
1587
|
+
const end = Math.min(start + 64 * 1024, content.length);
|
|
1588
|
+
for (let i = start; i < end; i++) if (content[i] === 10) count++;
|
|
1589
|
+
representation.addLines(count);
|
|
1590
|
+
lineCount += count;
|
|
1591
|
+
yield;
|
|
1592
|
+
}
|
|
1593
|
+
const missingNewline = content.length > 0 && content[content.length - 1] !== 10;
|
|
1594
|
+
if (missingNewline) {
|
|
1595
|
+
representation.addLines(1);
|
|
1596
|
+
lineCount++;
|
|
1597
|
+
}
|
|
1598
|
+
return {
|
|
1599
|
+
text: content.toString("utf-8"),
|
|
1600
|
+
lineCount,
|
|
1601
|
+
header: `@@ -0,0 +1,${lineCount} @@`,
|
|
1602
|
+
missingNewline
|
|
1603
|
+
};
|
|
1604
|
+
}
|
|
1605
|
+
|
|
1606
|
+
// src/synthetic-diff.ts
|
|
1607
|
+
import { realpathSync as realpathSync3 } from "fs";
|
|
1608
|
+
import { join as join6, resolve } from "path";
|
|
1609
|
+
|
|
1610
|
+
// src/synthetic-source.ts
|
|
1611
|
+
import {
|
|
1612
|
+
closeSync as closeSync3,
|
|
1613
|
+
constants as constants4,
|
|
1614
|
+
fstatSync as fstatSync3,
|
|
1615
|
+
lstatSync as lstatSync2,
|
|
1616
|
+
openSync as openSync3,
|
|
1617
|
+
readlinkSync,
|
|
1618
|
+
realpathSync as realpathSync2
|
|
1619
|
+
} from "fs";
|
|
1620
|
+
import { dirname as dirname4, join as join5, relative } from "path";
|
|
1621
|
+
function sourceOptions(options) {
|
|
1622
|
+
const budgets = resolveSourceBudgets();
|
|
1623
|
+
return {
|
|
1624
|
+
...options,
|
|
1625
|
+
maxFileBytes: options.maxFileBytes ?? budgets.maxFileBytes,
|
|
1626
|
+
remainingBytes: options.remainingBytes ?? budgets.maxTotalBytes
|
|
1627
|
+
};
|
|
1628
|
+
}
|
|
1629
|
+
function readLinkSource(fullPath, root, rel, options) {
|
|
1630
|
+
if (!options.followSymlinks) {
|
|
1631
|
+
let linkSize;
|
|
1632
|
+
try {
|
|
1633
|
+
assertNoSymlinkAncestors(root, rel);
|
|
1634
|
+
const stats = lstatSync2(fullPath);
|
|
1635
|
+
if (stats.isSymbolicLink()) linkSize = stats.size;
|
|
1636
|
+
} catch (error) {
|
|
1637
|
+
return failure(error);
|
|
1638
|
+
}
|
|
1639
|
+
if (linkSize !== void 0) {
|
|
1640
|
+
if (linkSize > options.maxFileBytes)
|
|
1641
|
+
return { kind: "too-large", size: linkSize, bytesRead: 0 };
|
|
1642
|
+
if (linkSize > options.remainingBytes)
|
|
1643
|
+
return { kind: "over-total", size: linkSize, bytesRead: 0 };
|
|
1644
|
+
try {
|
|
1645
|
+
const content = readlinkSync(fullPath, { encoding: "buffer" });
|
|
1646
|
+
assertNoSymlinkAncestors(root, rel);
|
|
1647
|
+
if (realpathSync2(dirname4(fullPath)) !== join5(realpathSync2(root), dirname4(rel))) {
|
|
1648
|
+
return { kind: "unreadable", code: "unsafe-link", bytesRead: 0 };
|
|
1649
|
+
}
|
|
1650
|
+
if (content.length > options.maxFileBytes)
|
|
1651
|
+
return { kind: "too-large", size: content.length, bytesRead: content.length };
|
|
1652
|
+
if (content.length > options.remainingBytes)
|
|
1653
|
+
return { kind: "over-total", size: content.length, bytesRead: content.length };
|
|
1654
|
+
return { kind: "symlink", content, bytesRead: content.length };
|
|
1655
|
+
} catch (error) {
|
|
1656
|
+
return failure(error);
|
|
1657
|
+
}
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
return null;
|
|
1661
|
+
}
|
|
1662
|
+
function* sourceReads(size, maxFileBytes, remainingBytes) {
|
|
1663
|
+
let bytesRead = 0;
|
|
1664
|
+
const sniffLength = Math.min(size, BINARY_SNIFF_BYTES);
|
|
1665
|
+
if (sniffLength > remainingBytes) return { kind: "over-total", size, bytesRead };
|
|
1666
|
+
const sniff = Buffer.alloc(sniffLength);
|
|
1667
|
+
bytesRead = yield { buffer: sniff, offset: 0, length: sniffLength };
|
|
1668
|
+
if (sniff.subarray(0, bytesRead).includes(0)) return { kind: "binary", bytesRead };
|
|
1669
|
+
if (size > maxFileBytes) return { kind: "too-large", size, bytesRead };
|
|
1670
|
+
if (size > remainingBytes) return { kind: "over-total", size, bytesRead };
|
|
1671
|
+
const content = Buffer.alloc(size);
|
|
1672
|
+
sniff.copy(content, 0, 0, bytesRead);
|
|
1673
|
+
bytesRead += yield { buffer: content, offset: bytesRead, length: size - bytesRead };
|
|
1674
|
+
return { kind: "text", content: content.subarray(0, bytesRead), bytesRead };
|
|
1675
|
+
}
|
|
1676
|
+
function checkGrowth(source, size, options) {
|
|
1677
|
+
if (source.kind !== "text") return source;
|
|
1678
|
+
if (size > options.maxFileBytes) return { kind: "too-large", size, bytesRead: source.bytesRead };
|
|
1679
|
+
if (size > options.remainingBytes)
|
|
1680
|
+
return { kind: "over-total", size, bytesRead: source.bytesRead };
|
|
1681
|
+
return source;
|
|
1682
|
+
}
|
|
1683
|
+
function readSyntheticSource(fullPath, input = {}) {
|
|
1684
|
+
const options = sourceOptions(input);
|
|
1685
|
+
const root = options.sourceRoot ?? dirname4(fullPath);
|
|
1686
|
+
const rel = relative(root, fullPath);
|
|
1687
|
+
const link = readLinkSource(fullPath, root, rel, options);
|
|
1688
|
+
if (link) return link;
|
|
1689
|
+
let fd;
|
|
1690
|
+
try {
|
|
1691
|
+
fd = options.followSymlinks ? openSync3(fullPath, constants4.O_RDONLY | constants4.O_NONBLOCK) : openContainedFile(root, rel).fd;
|
|
1692
|
+
} catch (error) {
|
|
1693
|
+
return failure(error);
|
|
1694
|
+
}
|
|
1695
|
+
let bytesRead = 0;
|
|
1696
|
+
try {
|
|
1697
|
+
const stats = fstatSync3(fd);
|
|
1698
|
+
if (!stats.isFile()) return { kind: "skip", bytesRead: 0 };
|
|
1699
|
+
const reads = sourceReads(stats.size, options.maxFileBytes, options.remainingBytes);
|
|
1700
|
+
let step = reads.next();
|
|
1701
|
+
while (!step.done) {
|
|
1702
|
+
const { buffer, offset, length } = step.value;
|
|
1703
|
+
const count = readInto(fd, buffer, offset, length);
|
|
1704
|
+
bytesRead += count;
|
|
1705
|
+
step = reads.next(count);
|
|
1706
|
+
}
|
|
1707
|
+
return step.value.kind === "text" ? checkGrowth(step.value, fstatSync3(fd).size, options) : step.value;
|
|
1708
|
+
} catch (error) {
|
|
1709
|
+
return failure(error, bytesRead);
|
|
1710
|
+
} finally {
|
|
1711
|
+
closeSync3(fd);
|
|
1712
|
+
}
|
|
1713
|
+
}
|
|
1714
|
+
async function readLinkSourceAsync(fullPath, root, rel, options, layer, signal) {
|
|
1715
|
+
if (options.followSymlinks) return null;
|
|
1716
|
+
await assertNoSymlinkAncestorsAsync(root, rel, layer, signal);
|
|
1717
|
+
checkLoadingCancelled(signal);
|
|
1718
|
+
const stats = await layer.lstat(fullPath);
|
|
1719
|
+
checkLoadingCancelled(signal);
|
|
1720
|
+
if (!stats.isSymbolicLink()) return null;
|
|
1721
|
+
if (stats.size > options.maxFileBytes)
|
|
1722
|
+
return { kind: "too-large", size: stats.size, bytesRead: 0 };
|
|
1723
|
+
if (stats.size > options.remainingBytes)
|
|
1724
|
+
return { kind: "over-total", size: stats.size, bytesRead: 0 };
|
|
1725
|
+
const content = await layer.readlink(fullPath);
|
|
1726
|
+
checkLoadingCancelled(signal);
|
|
1727
|
+
await assertNoSymlinkAncestorsAsync(root, rel, layer, signal);
|
|
1728
|
+
checkLoadingCancelled(signal);
|
|
1729
|
+
const parent = await layer.realpath(dirname4(fullPath));
|
|
1730
|
+
checkLoadingCancelled(signal);
|
|
1731
|
+
const physicalRoot = await layer.realpath(root);
|
|
1732
|
+
checkLoadingCancelled(signal);
|
|
1733
|
+
if (parent !== join5(physicalRoot, dirname4(rel)))
|
|
1734
|
+
return { kind: "unreadable", code: "unsafe-link", bytesRead: 0 };
|
|
1735
|
+
if (content.length > options.maxFileBytes)
|
|
1736
|
+
return { kind: "too-large", size: content.length, bytesRead: content.length };
|
|
1737
|
+
if (content.length > options.remainingBytes)
|
|
1738
|
+
return { kind: "over-total", size: content.length, bytesRead: content.length };
|
|
1739
|
+
return { kind: "symlink", content, bytesRead: content.length };
|
|
1740
|
+
}
|
|
1741
|
+
async function readSyntheticSourceAsync(fullPath, input = {}) {
|
|
1742
|
+
const { signal } = input;
|
|
1743
|
+
await loadingCheckpoint(signal);
|
|
1744
|
+
const options = sourceOptions(input);
|
|
1745
|
+
const root = options.sourceRoot ?? dirname4(fullPath);
|
|
1746
|
+
const rel = relative(root, fullPath);
|
|
1747
|
+
const layer = input.readFs ?? nodeScanFsLayer;
|
|
1748
|
+
let handle;
|
|
1749
|
+
let bytesRead = 0;
|
|
1750
|
+
try {
|
|
1751
|
+
const link = await readLinkSourceAsync(fullPath, root, rel, options, layer, signal);
|
|
1752
|
+
checkLoadingCancelled(signal);
|
|
1753
|
+
if (link) return link;
|
|
1754
|
+
handle = options.followSymlinks ? await layer.open(fullPath, constants4.O_RDONLY | constants4.O_NONBLOCK) : (await openContainedFileAsync(root, rel, layer, signal)).handle;
|
|
1755
|
+
checkLoadingCancelled(signal);
|
|
1756
|
+
const stats = await handle.stat();
|
|
1757
|
+
checkLoadingCancelled(signal);
|
|
1758
|
+
if (!stats.isFile()) return { kind: "skip", bytesRead: 0 };
|
|
1759
|
+
const reader = {
|
|
1760
|
+
read: async (buffer, offset, length, position) => {
|
|
1761
|
+
const result = await handle.read(buffer, offset, length, position);
|
|
1762
|
+
bytesRead += result.bytesRead;
|
|
1763
|
+
return result;
|
|
1764
|
+
}
|
|
1765
|
+
};
|
|
1766
|
+
const reads = sourceReads(stats.size, options.maxFileBytes, options.remainingBytes);
|
|
1767
|
+
let step = reads.next();
|
|
1768
|
+
while (!step.done) {
|
|
1769
|
+
const { buffer, offset, length } = step.value;
|
|
1770
|
+
const count = await readIntoAsync(reader, buffer, offset, length, signal);
|
|
1771
|
+
step = reads.next(count);
|
|
1772
|
+
}
|
|
1773
|
+
if (step.value.kind !== "text") return step.value;
|
|
1774
|
+
const after = await handle.stat();
|
|
1775
|
+
checkLoadingCancelled(signal);
|
|
1776
|
+
return checkGrowth(step.value, after.size, options);
|
|
1777
|
+
} catch (error) {
|
|
1778
|
+
checkLoadingCancelled(signal);
|
|
1779
|
+
return failure(error, bytesRead);
|
|
1780
|
+
} finally {
|
|
1781
|
+
try {
|
|
1782
|
+
if (handle) await handle.close();
|
|
1783
|
+
} finally {
|
|
1784
|
+
checkLoadingCancelled(signal);
|
|
1785
|
+
}
|
|
1786
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
function failure(error, bytesRead = 0) {
|
|
1789
|
+
const wrapped = error;
|
|
1790
|
+
const code = wrapped?.cause?.code ?? wrapped?.code ?? "unknown error";
|
|
1791
|
+
if (["ENOENT", "ENOTDIR", "ELOOP", "not-found", "not-regular", "output-is-directory"].includes(code)) {
|
|
1792
|
+
return { kind: "skip", bytesRead: 0 };
|
|
1793
|
+
}
|
|
1794
|
+
return { kind: "unreadable", code, bytesRead };
|
|
1795
|
+
}
|
|
1796
|
+
|
|
1797
|
+
// src/synthetic-diff.ts
|
|
1798
|
+
function generateSyntheticDiffs(paths, rootDir, options = {}) {
|
|
1799
|
+
const { diff, omitted, diagnostics } = projectSources(paths, rootDir, options, "patch");
|
|
1800
|
+
return { diff, omitted, diagnostics };
|
|
1801
|
+
}
|
|
1802
|
+
function projectSources(paths, rootDir, options, output) {
|
|
1803
|
+
const budgets = resolveSourceBudgets(options.budgets);
|
|
1804
|
+
const sourceRoot = syntheticRoot(rootDir);
|
|
1805
|
+
const projection = createProjection(budgets, output);
|
|
1806
|
+
for (const filePath of paths) {
|
|
1807
|
+
if (!projection.beginFile()) break;
|
|
1808
|
+
const steps = projection.add(
|
|
1809
|
+
filePath,
|
|
1810
|
+
projection.exhausted() ? null : readSyntheticSource(join6(sourceRoot, filePath), {
|
|
1811
|
+
sourceRoot,
|
|
1812
|
+
followSymlinks: options.followSymlinks,
|
|
1813
|
+
maxFileBytes: budgets.maxFileBytes,
|
|
1814
|
+
remainingBytes: projection.remaining()
|
|
1815
|
+
})
|
|
1816
|
+
);
|
|
1817
|
+
while (!steps.next().done) {
|
|
1818
|
+
}
|
|
1819
|
+
}
|
|
1820
|
+
return projection.finish();
|
|
1821
|
+
}
|
|
1822
|
+
async function generateSyntheticDiffsAsync(paths, rootDir, options = {}) {
|
|
1823
|
+
const { diff, omitted, diagnostics } = await projectSourcesAsync(
|
|
1824
|
+
paths,
|
|
1825
|
+
rootDir,
|
|
1826
|
+
options,
|
|
1827
|
+
"patch"
|
|
1828
|
+
);
|
|
1829
|
+
return { diff, omitted, diagnostics };
|
|
1830
|
+
}
|
|
1831
|
+
async function projectSourcesAsync(paths, rootDir, options, output) {
|
|
1832
|
+
checkLoadingCancelled(options.signal);
|
|
1833
|
+
const budgets = resolveSourceBudgets(options.budgets);
|
|
1834
|
+
const sourceRoot = options.readFs ? await options.readFs.realpath(rootDir).catch(() => {
|
|
1835
|
+
checkLoadingCancelled(options.signal);
|
|
1836
|
+
return resolve(rootDir);
|
|
1837
|
+
}) : syntheticRoot(rootDir);
|
|
1838
|
+
checkLoadingCancelled(options.signal);
|
|
1839
|
+
const originalFs = options.readFs ?? nodeScanFsLayer;
|
|
1840
|
+
const capture = captureSourceReads(originalFs, options.signal, "record");
|
|
1841
|
+
const readFs = {
|
|
1842
|
+
...capture.readFs,
|
|
1843
|
+
readlink: (target) => originalFs.readlink(target)
|
|
1844
|
+
};
|
|
1845
|
+
const projection = createProjection(budgets, output);
|
|
1846
|
+
for (const filePath of paths) {
|
|
1847
|
+
await loadingCheckpoint(options.signal);
|
|
1848
|
+
if (!projection.beginFile()) break;
|
|
1849
|
+
const source = projection.exhausted() ? null : await readSyntheticSourceAsync(join6(sourceRoot, filePath), {
|
|
1850
|
+
sourceRoot,
|
|
1851
|
+
readFs,
|
|
1852
|
+
followSymlinks: options.followSymlinks,
|
|
1853
|
+
maxFileBytes: budgets.maxFileBytes,
|
|
1854
|
+
remainingBytes: projection.remaining(),
|
|
1855
|
+
signal: options.signal
|
|
1856
|
+
});
|
|
1857
|
+
checkLoadingCancelled(options.signal);
|
|
1858
|
+
if (source && (source.kind === "text" || source.kind === "binary") && capture.drifted.has(resolve(sourceRoot, filePath)))
|
|
1859
|
+
throw new Error(RELOAD_REVIEW);
|
|
1860
|
+
const steps = projection.add(filePath, source);
|
|
1861
|
+
try {
|
|
1862
|
+
while (!steps.next().done) await loadingCheckpoint(options.signal);
|
|
1863
|
+
} finally {
|
|
1864
|
+
steps.return(void 0);
|
|
1865
|
+
}
|
|
1866
|
+
}
|
|
1867
|
+
await loadingCheckpoint(options.signal);
|
|
1868
|
+
const result = projection.finish();
|
|
1869
|
+
for (const file of result.files) {
|
|
1870
|
+
recordSourceCapture(
|
|
1871
|
+
file,
|
|
1872
|
+
capture.captures.get(resolve(sourceRoot, file.newPath || file.oldPath))
|
|
1873
|
+
);
|
|
1874
|
+
}
|
|
1875
|
+
return result;
|
|
1876
|
+
}
|
|
1877
|
+
function syntheticRoot(rootDir) {
|
|
1878
|
+
try {
|
|
1879
|
+
return realpathSync3(rootDir);
|
|
1880
|
+
} catch {
|
|
1881
|
+
return resolve(rootDir);
|
|
1882
|
+
}
|
|
1883
|
+
}
|
|
1884
|
+
function createProjection(budgets, output) {
|
|
1885
|
+
const accounting = createSourceAccounting(budgets);
|
|
1886
|
+
const emitter = output === "files" ? createFilesEmitter() : createPatchEmitter();
|
|
1887
|
+
const separators = createSeparatorDiagnostics(budgets.maxDiagnostics);
|
|
1888
|
+
function* emit(filePath, source, mode) {
|
|
1889
|
+
const text = source && source.kind !== "binary" ? yield* projectText(source.content, accounting.representation) : void 0;
|
|
1890
|
+
if (text) accounting.representation.addHunk();
|
|
1891
|
+
separators.next(filePath, text?.lineCount);
|
|
1892
|
+
yield* emitter.emit(filePath, source, text, mode);
|
|
1893
|
+
}
|
|
1894
|
+
function* add(filePath, source) {
|
|
1895
|
+
try {
|
|
1896
|
+
const admission = accounting.admit(filePath, source);
|
|
1897
|
+
if (admission.emit) yield* emit(filePath, admission.source);
|
|
1898
|
+
} catch (error) {
|
|
1899
|
+
if (!(error instanceof RepresentationLimitError)) throw error;
|
|
1900
|
+
accounting.omitRepresentation(filePath, error);
|
|
1901
|
+
yield* emit(filePath, void 0, source?.kind === "symlink" ? "120000" : "100644");
|
|
1902
|
+
}
|
|
1903
|
+
}
|
|
1904
|
+
return {
|
|
1905
|
+
beginFile: accounting.beginFile,
|
|
1906
|
+
add,
|
|
1907
|
+
remaining: accounting.remaining,
|
|
1908
|
+
exhausted: accounting.exhausted,
|
|
1909
|
+
finish() {
|
|
1910
|
+
const result = emitter.finish();
|
|
1911
|
+
for (const file of result.files) {
|
|
1912
|
+
const reason = accounting.omitted.get(file.newPath);
|
|
1913
|
+
if (reason !== void 0) file.omittedReason = reason;
|
|
1914
|
+
}
|
|
1915
|
+
const diagnostics = accounting.diagnostics();
|
|
1916
|
+
return {
|
|
1917
|
+
...result,
|
|
1918
|
+
omitted: accounting.omitted,
|
|
1919
|
+
diagnostics: output === "files" ? [...diagnostics, ...separators.diagnostics] : diagnostics
|
|
1920
|
+
};
|
|
1921
|
+
}
|
|
1922
|
+
};
|
|
1923
|
+
}
|
|
1924
|
+
function loadSyntheticFiles(paths, rootDir, options = {}) {
|
|
1925
|
+
const { files, diagnostics } = projectSources(paths, rootDir, options, "files");
|
|
1926
|
+
return { files, diagnostics };
|
|
1927
|
+
}
|
|
1928
|
+
async function loadSyntheticFilesAsync(paths, rootDir, options = {}) {
|
|
1929
|
+
const { files, diagnostics } = await projectSourcesAsync(paths, rootDir, options, "files");
|
|
1930
|
+
return { files, diagnostics };
|
|
1931
|
+
}
|
|
1932
|
+
|
|
1933
|
+
// src/git-option-policy.ts
|
|
1934
|
+
var OPTION_POLICY = {
|
|
1935
|
+
"--output": { value: "required", writeCapable: true, unsupportedOutput: "always" },
|
|
1936
|
+
"--ext-diff": { writeCapable: true },
|
|
1937
|
+
"--textconv": { writeCapable: true },
|
|
1938
|
+
"--src-prefix": { value: "required" },
|
|
1939
|
+
"--dst-prefix": { value: "required" },
|
|
1940
|
+
"--line-prefix": { value: "required", unsupportedOutput: "always" },
|
|
1941
|
+
"--output-indicator-new": { value: "required", unsupportedOutput: "always" },
|
|
1942
|
+
"--output-indicator-old": { value: "required", unsupportedOutput: "always" },
|
|
1943
|
+
"--output-indicator-context": { value: "required", unsupportedOutput: "always" },
|
|
1944
|
+
"--inter-hunk-context": { value: "required" },
|
|
1945
|
+
// Preserve the existing warning policy for these attached stat parameters.
|
|
1946
|
+
"--stat-width": { value: "required", unsupportedOutput: "attached" },
|
|
1947
|
+
"--stat-name-width": { value: "required", unsupportedOutput: "attached" },
|
|
1948
|
+
"--stat-graph-width": { value: "required", unsupportedOutput: "attached" },
|
|
1949
|
+
"--stat-count": { value: "required", unsupportedOutput: "attached" },
|
|
1950
|
+
"--diff-algorithm": { value: "required" },
|
|
1951
|
+
"--word-diff-regex": { value: "required", unsupportedOutput: "always" },
|
|
1952
|
+
"--ignore-matching-lines": { value: "required" },
|
|
1953
|
+
"--anchored": { value: "required" },
|
|
1954
|
+
"--diff-filter": { value: "required" },
|
|
1955
|
+
"--find-object": { value: "required" },
|
|
1956
|
+
"--rotate-to": { value: "required", rediff: "drop" },
|
|
1957
|
+
"--skip-to": { value: "required", rediff: "drop" },
|
|
1958
|
+
"--ws-error-highlight": { value: "required" },
|
|
1959
|
+
"--color-moved-ws": { value: "required", unsupportedOutput: "always" },
|
|
1960
|
+
"-S": { value: "required" },
|
|
1961
|
+
"-G": { value: "required" },
|
|
1962
|
+
"-O": { value: "required", rediff: "drop" },
|
|
1963
|
+
"-I": { value: "required" },
|
|
1964
|
+
"-l": { value: "required" },
|
|
1965
|
+
"-U": { value: "attached", rediff: "drop" },
|
|
1966
|
+
"-B": { value: "attached" },
|
|
1967
|
+
"-M": { value: "attached" },
|
|
1968
|
+
"-C": { value: "attached" },
|
|
1969
|
+
"-W": { rediff: "drop" },
|
|
1970
|
+
"--unified": { value: "attached", rediff: "drop" },
|
|
1971
|
+
"--function-context": { rediff: "drop" },
|
|
1972
|
+
"--no-function-context": { rediff: "drop" },
|
|
1973
|
+
"--relative": { value: "attached", rediff: "relative" },
|
|
1974
|
+
"--no-relative": { rediff: "relative" },
|
|
1975
|
+
"--stat": { value: "attached", unsupportedOutput: "always" },
|
|
1976
|
+
"--numstat": { unsupportedOutput: "always" },
|
|
1977
|
+
"--shortstat": { unsupportedOutput: "always" },
|
|
1978
|
+
"--dirstat": { value: "attached", unsupportedOutput: "always" },
|
|
1979
|
+
"--dirstat-by-file": { value: "attached", unsupportedOutput: "always" },
|
|
1980
|
+
"--cumulative": { unsupportedOutput: "always" },
|
|
1981
|
+
"--summary": { unsupportedOutput: "always" },
|
|
1982
|
+
"--name-only": { unsupportedOutput: "always" },
|
|
1983
|
+
"--name-status": { unsupportedOutput: "always" },
|
|
1984
|
+
"--raw": { unsupportedOutput: "always" },
|
|
1985
|
+
"--patch-with-stat": { unsupportedOutput: "always" },
|
|
1986
|
+
"--patch-with-raw": { unsupportedOutput: "always" },
|
|
1987
|
+
"--compact-summary": { unsupportedOutput: "always" },
|
|
1988
|
+
"--word-diff": { value: "attached", unsupportedOutput: "always" },
|
|
1989
|
+
"--color-words": { value: "attached", unsupportedOutput: "always" },
|
|
1990
|
+
"--color-moved": { value: "attached", unsupportedOutput: "always" },
|
|
1991
|
+
"--no-patch": { unsupportedOutput: "always" },
|
|
1992
|
+
"-s": { unsupportedOutput: "always" },
|
|
1993
|
+
"--exit-code": { unsupportedOutput: "always" },
|
|
1994
|
+
"--quiet": { unsupportedOutput: "always" },
|
|
1995
|
+
"--check": { unsupportedOutput: "always" }
|
|
1996
|
+
};
|
|
1997
|
+
function gitDiffOptionPolicy(name) {
|
|
1998
|
+
return Object.prototype.hasOwnProperty.call(OPTION_POLICY, name) ? OPTION_POLICY[name] : {};
|
|
1999
|
+
}
|
|
2000
|
+
|
|
2001
|
+
// src/git-argument-policy.ts
|
|
2002
|
+
function consumesNextArgument(arg) {
|
|
2003
|
+
if (arg.startsWith("--")) return gitDiffOptionPolicy(arg).value === "required";
|
|
2004
|
+
if (!arg.startsWith("-")) return false;
|
|
2005
|
+
for (let i = 1; i < arg.length; i++) {
|
|
2006
|
+
if (gitDiffOptionPolicy(`-${arg[i]}`).value === "required") return i === arg.length - 1;
|
|
2007
|
+
if (gitDiffOptionPolicy(`-${arg[i]}`).value === "attached") return false;
|
|
2008
|
+
}
|
|
2009
|
+
return false;
|
|
2010
|
+
}
|
|
2011
|
+
function parseGitDiffArgs(args) {
|
|
2012
|
+
const options = [];
|
|
2013
|
+
const positionalIndices = [];
|
|
2014
|
+
let separatorIndex = null;
|
|
2015
|
+
for (let i = 0; i < args.length; i++) {
|
|
2016
|
+
const arg = args[i];
|
|
2017
|
+
if (separatorIndex !== null) {
|
|
2018
|
+
positionalIndices.push(i);
|
|
2019
|
+
} else if (arg === "--") {
|
|
2020
|
+
separatorIndex = i;
|
|
2021
|
+
} else if (arg.startsWith("--")) {
|
|
2022
|
+
const equals = arg.indexOf("=");
|
|
2023
|
+
const option = {
|
|
2024
|
+
index: i,
|
|
2025
|
+
arg,
|
|
2026
|
+
name: equals < 0 ? arg : arg.slice(0, equals)
|
|
2027
|
+
};
|
|
2028
|
+
if (equals >= 0) option.value = arg.slice(equals + 1);
|
|
2029
|
+
else if (consumesNextArgument(arg) && i + 1 < args.length) {
|
|
2030
|
+
option.value = args[++i];
|
|
2031
|
+
}
|
|
2032
|
+
options.push(option);
|
|
2033
|
+
} else if (arg.startsWith("-")) {
|
|
2034
|
+
for (let j = 1; j < arg.length; j++) {
|
|
2035
|
+
const name = arg[j];
|
|
2036
|
+
const option = { index: i, arg, name: `-${name}` };
|
|
2037
|
+
options.push(option);
|
|
2038
|
+
if (gitDiffOptionPolicy(`-${name}`).value === "required" || gitDiffOptionPolicy(`-${name}`).value === "attached") {
|
|
2039
|
+
if (j + 1 < arg.length) option.value = arg.slice(j + 1);
|
|
2040
|
+
else if (gitDiffOptionPolicy(`-${name}`).value === "required" && i + 1 < args.length) {
|
|
2041
|
+
option.value = args[++i];
|
|
2042
|
+
}
|
|
2043
|
+
break;
|
|
2044
|
+
}
|
|
2045
|
+
}
|
|
2046
|
+
} else {
|
|
2047
|
+
positionalIndices.push(i);
|
|
2048
|
+
}
|
|
2049
|
+
}
|
|
2050
|
+
return { options, positionalIndices, separatorIndex };
|
|
2051
|
+
}
|
|
2052
|
+
function withoutDroppedShortOptions(arg) {
|
|
2053
|
+
let kept = "";
|
|
2054
|
+
for (let i = 1; i < arg.length; i++) {
|
|
2055
|
+
const option = arg[i];
|
|
2056
|
+
const rule = gitDiffOptionPolicy(`-${option}`);
|
|
2057
|
+
if (rule.rediff === "drop") {
|
|
2058
|
+
if (rule.value) break;
|
|
2059
|
+
continue;
|
|
2060
|
+
}
|
|
2061
|
+
if (rule.value === "required" || rule.value === "attached") {
|
|
2062
|
+
kept += arg.slice(i);
|
|
2063
|
+
break;
|
|
2064
|
+
}
|
|
2065
|
+
kept += option;
|
|
2066
|
+
}
|
|
2067
|
+
return kept === "" ? null : `-${kept}`;
|
|
2068
|
+
}
|
|
2069
|
+
function describeDiffPathRelativity(args) {
|
|
2070
|
+
let relative3 = { kind: "root" };
|
|
2071
|
+
for (const option of parseGitDiffArgs(args).options) {
|
|
2072
|
+
if (option.name === "--relative") {
|
|
2073
|
+
relative3 = option.value === void 0 ? { kind: "cwd" } : { kind: "directory", directory: option.value };
|
|
2074
|
+
} else if (option.name === "--no-relative") relative3 = { kind: "root" };
|
|
2075
|
+
}
|
|
2076
|
+
return relative3;
|
|
2077
|
+
}
|
|
2078
|
+
function singleFileRediffArgs(args) {
|
|
2079
|
+
const kept = [];
|
|
2080
|
+
for (let i = 0; i < args.length; i++) {
|
|
2081
|
+
const arg = args[i];
|
|
2082
|
+
if (arg === "--") break;
|
|
2083
|
+
const name = arg.split("=", 1)[0];
|
|
2084
|
+
const rule = gitDiffOptionPolicy(name);
|
|
2085
|
+
if (rule.rediff === "relative" && (arg === name || rule.value === "attached")) {
|
|
2086
|
+
continue;
|
|
2087
|
+
}
|
|
2088
|
+
const takesNext = consumesNextArgument(arg) && i + 1 < args.length;
|
|
2089
|
+
let option = arg;
|
|
2090
|
+
let keepValue = true;
|
|
2091
|
+
if (arg.startsWith("--")) {
|
|
2092
|
+
if (gitDiffOptionPolicy(name).rediff === "drop") option = null;
|
|
2093
|
+
keepValue = option !== null;
|
|
2094
|
+
} else if (arg.startsWith("-") && arg.length > 1) {
|
|
2095
|
+
option = withoutDroppedShortOptions(arg);
|
|
2096
|
+
keepValue = option !== null && consumesNextArgument(option);
|
|
2097
|
+
}
|
|
2098
|
+
if (option !== null) kept.push(option);
|
|
2099
|
+
if (takesNext) {
|
|
2100
|
+
i++;
|
|
2101
|
+
if (keepValue) kept.push(args[i]);
|
|
2102
|
+
}
|
|
2103
|
+
}
|
|
2104
|
+
return { args: kept, relative: describeDiffPathRelativity(args) };
|
|
2105
|
+
}
|
|
2106
|
+
function findWriteCapableGitDiffOptions(args) {
|
|
2107
|
+
return parseGitDiffArgs(args).options.filter((option) => gitDiffOptionPolicy(option.name).writeCapable).map((option) => option.arg);
|
|
2108
|
+
}
|
|
2109
|
+
function findUnsupportedGitDiffOptions(args) {
|
|
2110
|
+
const offending = parseGitDiffArgs(args).options.filter((option) => {
|
|
2111
|
+
const output = gitDiffOptionPolicy(option.name).unsupportedOutput;
|
|
2112
|
+
return output === "always" || output === "attached" && option.arg.includes("=");
|
|
2113
|
+
});
|
|
2114
|
+
return [...new Set(offending.map((option) => option.index))].map((index) => args[index]);
|
|
2115
|
+
}
|
|
2116
|
+
function classifyGitDiffArgs(args) {
|
|
2117
|
+
const parsed = parseGitDiffArgs(args);
|
|
2118
|
+
return {
|
|
2119
|
+
positionalIndices: parsed.positionalIndices,
|
|
2120
|
+
hasSeparator: parsed.separatorIndex !== null
|
|
2121
|
+
};
|
|
2122
|
+
}
|
|
2123
|
+
|
|
2124
|
+
// src/git-argument-text.ts
|
|
2125
|
+
function scanGitDiffArgs(value) {
|
|
2126
|
+
const args = [];
|
|
2127
|
+
let current = "";
|
|
2128
|
+
let started = false;
|
|
2129
|
+
let quote = null;
|
|
2130
|
+
let danglingEscape = false;
|
|
2131
|
+
for (let i = 0; i < value.length; i++) {
|
|
2132
|
+
const char = value[i];
|
|
2133
|
+
if (quote === "'") {
|
|
2134
|
+
if (char === "'") quote = null;
|
|
2135
|
+
else current += char;
|
|
2136
|
+
continue;
|
|
2137
|
+
}
|
|
2138
|
+
if (quote === '"') {
|
|
2139
|
+
if (char === "\\" && (value[i + 1] === '"' || value[i + 1] === "\\")) {
|
|
2140
|
+
current += value[++i];
|
|
2141
|
+
} else if (char === '"') {
|
|
2142
|
+
quote = null;
|
|
2143
|
+
} else {
|
|
2144
|
+
current += char;
|
|
2145
|
+
}
|
|
2146
|
+
continue;
|
|
2147
|
+
}
|
|
2148
|
+
if (char === "'" || char === '"') {
|
|
2149
|
+
quote = char;
|
|
2150
|
+
started = true;
|
|
2151
|
+
continue;
|
|
2152
|
+
}
|
|
2153
|
+
if (char === "\\" && i + 1 < value.length) {
|
|
2154
|
+
current += value[++i];
|
|
2155
|
+
started = true;
|
|
2156
|
+
continue;
|
|
2157
|
+
}
|
|
2158
|
+
if (/\s/.test(char)) {
|
|
2159
|
+
if (started) {
|
|
2160
|
+
args.push(current);
|
|
2161
|
+
current = "";
|
|
2162
|
+
started = false;
|
|
2163
|
+
}
|
|
2164
|
+
continue;
|
|
2165
|
+
}
|
|
2166
|
+
if (char === "\\") danglingEscape = true;
|
|
2167
|
+
current += char;
|
|
2168
|
+
started = true;
|
|
2169
|
+
}
|
|
2170
|
+
if (started) args.push(current);
|
|
2171
|
+
const syntaxError = quote !== null ? `unterminated ${quote === "'" ? "single" : "double"} quote` : danglingEscape ? "trailing escape" : null;
|
|
2172
|
+
return { args, syntaxError };
|
|
2173
|
+
}
|
|
2174
|
+
function tokenizeGitDiffArgs(value) {
|
|
2175
|
+
return scanGitDiffArgs(value).args;
|
|
2176
|
+
}
|
|
2177
|
+
function gitDiffArgsSyntaxError(value) {
|
|
2178
|
+
return scanGitDiffArgs(value).syntaxError;
|
|
2179
|
+
}
|
|
2180
|
+
function needsQuoting2(arg) {
|
|
2181
|
+
return arg.length === 0 || /[\s'"\\]/.test(arg);
|
|
2182
|
+
}
|
|
2183
|
+
function formatGitDiffArgs(args) {
|
|
2184
|
+
return args.map((arg) => needsQuoting2(arg) ? `'${arg.replace(/'/g, "'\\''")}'` : arg).join(" ");
|
|
2185
|
+
}
|
|
2186
|
+
|
|
2187
|
+
// src/git-diff-args.ts
|
|
2188
|
+
import { existsSync } from "fs";
|
|
2189
|
+
import { resolve as resolve2 } from "path";
|
|
2190
|
+
|
|
2191
|
+
// src/git-argument-paths.ts
|
|
2192
|
+
function normalizeGitDiffPaths(args, pathExists) {
|
|
2193
|
+
const { positionalIndices, hasSeparator } = classifyGitDiffArgs(args);
|
|
2194
|
+
if (hasSeparator) return args;
|
|
2195
|
+
for (const index of positionalIndices) {
|
|
2196
|
+
if (pathExists(args[index])) return [...args.slice(0, index), "--", ...args.slice(index)];
|
|
2197
|
+
}
|
|
2198
|
+
return args;
|
|
2199
|
+
}
|
|
2200
|
+
|
|
2201
|
+
// src/git-diff-args.ts
|
|
2202
|
+
function normalizeGitDiffArgs(args, cwd = process.cwd()) {
|
|
2203
|
+
return normalizeGitDiffPaths(args, (candidate) => existsSync(resolve2(cwd, candidate)));
|
|
2204
|
+
}
|
|
2205
|
+
|
|
2206
|
+
// src/diagnostics.ts
|
|
2207
|
+
var stderrReporter = (message, detail) => {
|
|
2208
|
+
if (detail === void 0) console.error(message);
|
|
2209
|
+
else console.error(message, detail);
|
|
2210
|
+
};
|
|
2211
|
+
|
|
2212
|
+
// src/effect-diagnostics.ts
|
|
2213
|
+
function isolatedReporter(report = stderrReporter) {
|
|
2214
|
+
return (message, detail) => {
|
|
2215
|
+
try {
|
|
2216
|
+
const result = detail === void 0 ? report(message) : report(message, detail);
|
|
2217
|
+
void Promise.resolve(result).catch(() => {
|
|
2218
|
+
});
|
|
2219
|
+
} catch {
|
|
2220
|
+
}
|
|
2221
|
+
};
|
|
2222
|
+
}
|
|
2223
|
+
|
|
2224
|
+
// src/git.ts
|
|
2225
|
+
var GitCommandError = class extends Error {
|
|
2226
|
+
constructor(args, exitCode, stderr) {
|
|
2227
|
+
super(`git ${args.join(" ")} failed: ${stderr.trim() || `exit ${exitCode}`}`);
|
|
2228
|
+
this.args = args;
|
|
2229
|
+
this.exitCode = exitCode;
|
|
2230
|
+
this.stderr = stderr;
|
|
2231
|
+
this.name = "GitCommandError";
|
|
2232
|
+
}
|
|
2233
|
+
};
|
|
2234
|
+
async function executeGit(args, cwd, options = {}, maxOutputBytes = 1024 * 1024) {
|
|
2235
|
+
if (options.signal?.aborted) throw new CommandCancelledError("aborted", "git", args);
|
|
2236
|
+
const result = await (options.runner ?? defaultGitRunner)("git", args, {
|
|
2237
|
+
cwd,
|
|
2238
|
+
signal: options.signal,
|
|
2239
|
+
timeoutMs: options.timeoutMs ?? 1e4,
|
|
2240
|
+
maxOutputBytes
|
|
2241
|
+
});
|
|
2242
|
+
if (options.signal?.aborted) throw new CommandCancelledError("aborted", "git", args);
|
|
2243
|
+
if (result.exitCode !== 0) throw new GitCommandError(args, result.exitCode, result.stderr);
|
|
2244
|
+
return result.stdout;
|
|
2245
|
+
}
|
|
2246
|
+
function stripTrailingNewline(text) {
|
|
2247
|
+
return text.replace(/\r?\n$/, "");
|
|
2248
|
+
}
|
|
2249
|
+
async function getRepoRootAsync(cwd, options = {}) {
|
|
2250
|
+
try {
|
|
2251
|
+
const stdout = await executeGit(["rev-parse", "--show-toplevel"], cwd, options);
|
|
2252
|
+
return stripTrailingNewline(stdout);
|
|
2253
|
+
} catch (error) {
|
|
2254
|
+
const knownError = error instanceof Error;
|
|
2255
|
+
isolatedReporter(options.reportDiagnostic)(
|
|
2256
|
+
`Error getting repository root: ${knownError ? error.message : "unknown error"}`
|
|
2257
|
+
);
|
|
2258
|
+
throw error;
|
|
2259
|
+
}
|
|
2260
|
+
}
|
|
2261
|
+
var PARSER_COMPATIBLE_GIT_CONFIG = [
|
|
2262
|
+
"-c",
|
|
2263
|
+
"color.ui=never",
|
|
2264
|
+
"-c",
|
|
2265
|
+
"diff.noprefix=false",
|
|
2266
|
+
"-c",
|
|
2267
|
+
"diff.mnemonicPrefix=false",
|
|
2268
|
+
// Untracked enumeration, context expansion and Apply all resolve paths against the root.
|
|
2269
|
+
"-c",
|
|
2270
|
+
"diff.relative=false"
|
|
2271
|
+
];
|
|
2272
|
+
var PARSER_COMPATIBLE_DIFF_FLAGS = [
|
|
2273
|
+
"--no-color",
|
|
2274
|
+
"--no-ext-diff",
|
|
2275
|
+
"--no-textconv",
|
|
2276
|
+
"--src-prefix=a/",
|
|
2277
|
+
"--dst-prefix=b/"
|
|
2278
|
+
];
|
|
2279
|
+
function withParserCompatibleDiffArgs(args) {
|
|
2280
|
+
const separator = parseGitDiffArgs(args).separatorIndex;
|
|
2281
|
+
if (separator === null) {
|
|
2282
|
+
return [...args, ...PARSER_COMPATIBLE_DIFF_FLAGS];
|
|
2283
|
+
}
|
|
2284
|
+
return [...args.slice(0, separator), ...PARSER_COMPATIBLE_DIFF_FLAGS, ...args.slice(separator)];
|
|
2285
|
+
}
|
|
2286
|
+
async function runGitDiffAsync(args, cwd, maxOutputBytes = MAX_GIT_DIFF_OUTPUT_BYTES, options = {}) {
|
|
2287
|
+
try {
|
|
2288
|
+
return await executeGit(
|
|
2289
|
+
[...PARSER_COMPATIBLE_GIT_CONFIG, "diff", ...withParserCompatibleDiffArgs(args)],
|
|
2290
|
+
cwd,
|
|
2291
|
+
{ ...options, timeoutMs: options.timeoutMs ?? 3e4 },
|
|
2292
|
+
maxOutputBytes
|
|
2293
|
+
);
|
|
2294
|
+
} catch (error) {
|
|
2295
|
+
const knownError = error instanceof Error;
|
|
2296
|
+
isolatedReporter(options.reportDiagnostic)(
|
|
2297
|
+
`Error running git diff: ${knownError ? error.message : "unknown error"}`
|
|
2298
|
+
);
|
|
2299
|
+
throw error;
|
|
2300
|
+
}
|
|
2301
|
+
}
|
|
2302
|
+
async function listUntrackedFilesAsync(repoRoot, options = {}) {
|
|
2303
|
+
const stdout = await executeGit(
|
|
2304
|
+
["ls-files", "--others", "--exclude-standard", "-z"],
|
|
2305
|
+
repoRoot,
|
|
2306
|
+
options,
|
|
2307
|
+
10 * 1024 * 1024
|
|
2308
|
+
);
|
|
2309
|
+
return stdout.split("\0").filter((name) => name.length > 0);
|
|
2310
|
+
}
|
|
2311
|
+
async function getUntrackedFilesAsync(repoRoot, options = {}) {
|
|
2312
|
+
try {
|
|
2313
|
+
return await listUntrackedFilesAsync(repoRoot, options);
|
|
2314
|
+
} catch (error) {
|
|
2315
|
+
if (isCommandCancelled(error) && error.reason === "aborted") throw error;
|
|
2316
|
+
isolatedReporter(options.reportDiagnostic)(
|
|
2317
|
+
`Warning: Failed to list untracked files: ${error instanceof Error ? error.message : "unknown error"}`
|
|
2318
|
+
);
|
|
2319
|
+
return [];
|
|
2320
|
+
}
|
|
2321
|
+
}
|
|
2322
|
+
function isOutputLimitError(error) {
|
|
2323
|
+
return error?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER";
|
|
2324
|
+
}
|
|
2325
|
+
function generateUntrackedDiffs(paths, repoRoot, options = {}) {
|
|
2326
|
+
return generateSyntheticDiffs(paths, repoRoot, { ...options, followSymlinks: false });
|
|
2327
|
+
}
|
|
2328
|
+
|
|
2329
|
+
// src/materializer.ts
|
|
2330
|
+
import { randomUUID } from "crypto";
|
|
2331
|
+
var DEFAULT_GIT_COMMAND_TIMEOUT_MS = 10 * 60 * 1e3;
|
|
2332
|
+
var CLEANUP_COMMAND_TIMEOUT_MS = 15e3;
|
|
2333
|
+
var AUTH_HINT = "Hint: if this repository is private or requires authentication, run `gh auth setup-git` (GitHub) or `glab auth git-credential` (GitLab) to wire your CLI credentials into git.";
|
|
2334
|
+
function headRefFor(url) {
|
|
2335
|
+
return FORGE_DEFINITIONS[url.forge].headRef(url.number);
|
|
2336
|
+
}
|
|
2337
|
+
function cloneUrlFor(url) {
|
|
2338
|
+
return `https://${url.host}/${url.owner}/${url.repo}.git`;
|
|
2339
|
+
}
|
|
2340
|
+
function sessionRefs() {
|
|
2341
|
+
const session = randomUUID();
|
|
2342
|
+
return {
|
|
2343
|
+
base: `refs/self-review/${session}/base`,
|
|
2344
|
+
head: `refs/self-review/${session}/head`
|
|
2345
|
+
};
|
|
2346
|
+
}
|
|
2347
|
+
function bindGit(runner, options) {
|
|
2348
|
+
const commandOptions = {
|
|
2349
|
+
signal: options.signal,
|
|
2350
|
+
gitEnvironment: "isolated",
|
|
2351
|
+
timeoutMs: options.commandTimeoutMs ?? DEFAULT_GIT_COMMAND_TIMEOUT_MS
|
|
2352
|
+
};
|
|
2353
|
+
return (args) => {
|
|
2354
|
+
if (options.signal?.aborted) {
|
|
2355
|
+
return Promise.reject(new CommandCancelledError("aborted", "git", args));
|
|
2356
|
+
}
|
|
2357
|
+
return runner("git", args, commandOptions);
|
|
2358
|
+
};
|
|
2359
|
+
}
|
|
2360
|
+
function gitFailure(what, result, withAuthHint) {
|
|
2361
|
+
const stderr = result.stderr.trim();
|
|
2362
|
+
const lines = [
|
|
2363
|
+
`git ${what} failed (exit code ${result.exitCode})${stderr ? `:
|
|
2364
|
+
${stderr}` : ""}`
|
|
2365
|
+
];
|
|
2366
|
+
if (withAuthHint) {
|
|
2367
|
+
lines.push("", AUTH_HINT);
|
|
2368
|
+
}
|
|
2369
|
+
return new Error(lines.join("\n"));
|
|
2370
|
+
}
|
|
2371
|
+
function stripRepoPath(repoPath) {
|
|
2372
|
+
return repoPath.replace(/\/+$/, "").replace(/\.git$/i, "");
|
|
2373
|
+
}
|
|
2374
|
+
function normalizeRemoteUrl(raw) {
|
|
2375
|
+
const trimmed = raw.trim();
|
|
2376
|
+
if (trimmed.includes("://")) {
|
|
2377
|
+
try {
|
|
2378
|
+
const parsed = new URL(trimmed);
|
|
2379
|
+
return {
|
|
2380
|
+
host: parsed.host.toLowerCase(),
|
|
2381
|
+
path: stripRepoPath(parsed.pathname.replace(/^\/+/, "")).toLowerCase()
|
|
2382
|
+
};
|
|
2383
|
+
} catch {
|
|
2384
|
+
return null;
|
|
2385
|
+
}
|
|
2386
|
+
}
|
|
2387
|
+
const scp = /^(?:[^@\s]+@)?([^:/\s]+):(.+)$/.exec(trimmed);
|
|
2388
|
+
if (scp) {
|
|
2389
|
+
return {
|
|
2390
|
+
host: scp[1].toLowerCase(),
|
|
2391
|
+
path: stripRepoPath(scp[2].replace(/^\/+/, "")).toLowerCase()
|
|
2392
|
+
};
|
|
2393
|
+
}
|
|
2394
|
+
return null;
|
|
2395
|
+
}
|
|
2396
|
+
function findMatchingRemote(remoteVOutput, url) {
|
|
2397
|
+
const wantedHost = url.host.toLowerCase();
|
|
2398
|
+
const wantedPath = `${url.owner}/${url.repo}`.toLowerCase();
|
|
2399
|
+
for (const line of remoteVOutput.split("\n")) {
|
|
2400
|
+
const match = /^(\S+)\t(.+?)\s+\(fetch\)$/.exec(line.trim());
|
|
2401
|
+
if (!match) continue;
|
|
2402
|
+
const normalized = normalizeRemoteUrl(match[2]);
|
|
2403
|
+
if (normalized && normalized.host === wantedHost && normalized.path === wantedPath) {
|
|
2404
|
+
return match[1];
|
|
2405
|
+
}
|
|
2406
|
+
}
|
|
2407
|
+
return null;
|
|
2408
|
+
}
|
|
2409
|
+
async function revParse(git, repoPath, ref) {
|
|
2410
|
+
const result = await git(["-C", repoPath, "rev-parse", ref]);
|
|
2411
|
+
if (result.exitCode !== 0) {
|
|
2412
|
+
throw gitFailure(`rev-parse ${ref}`, result, false);
|
|
2413
|
+
}
|
|
2414
|
+
return result.stdout.trim();
|
|
2415
|
+
}
|
|
2416
|
+
async function fetchSnapshot(git, repoPath, remote, url, baseBranch, refs, failureLabel) {
|
|
2417
|
+
const fetch = await git([
|
|
2418
|
+
"-C",
|
|
2419
|
+
repoPath,
|
|
2420
|
+
"fetch",
|
|
2421
|
+
"--refmap=",
|
|
2422
|
+
"--no-tags",
|
|
2423
|
+
"--no-write-fetch-head",
|
|
2424
|
+
"--recurse-submodules=no",
|
|
2425
|
+
remote,
|
|
2426
|
+
`+refs/heads/${baseBranch}:${refs.base}`,
|
|
2427
|
+
`+${headRefFor(url)}:${refs.head}`
|
|
2428
|
+
]);
|
|
2429
|
+
if (fetch.exitCode !== 0) {
|
|
2430
|
+
throw gitFailure(failureLabel, fetch, true);
|
|
2431
|
+
}
|
|
2432
|
+
return {
|
|
2433
|
+
baseSha: await revParse(git, repoPath, refs.base),
|
|
2434
|
+
headSha: await revParse(git, repoPath, refs.head)
|
|
2435
|
+
};
|
|
2436
|
+
}
|
|
2437
|
+
async function detectExistingClone(url, cwd, runner = defaultGitRunner, options = {}) {
|
|
2438
|
+
const git = bindGit(runner, options);
|
|
2439
|
+
const toplevel = await git(["-C", cwd, "rev-parse", "--show-toplevel"]);
|
|
2440
|
+
if (toplevel.exitCode !== 0) {
|
|
2441
|
+
return null;
|
|
2442
|
+
}
|
|
2443
|
+
const repoPath = stripTrailingNewline(toplevel.stdout);
|
|
2444
|
+
const remotes = await git(["-C", repoPath, "remote", "-v"]);
|
|
2445
|
+
if (remotes.exitCode !== 0) {
|
|
2446
|
+
return null;
|
|
2447
|
+
}
|
|
2448
|
+
const remoteName = findMatchingRemote(remotes.stdout, url);
|
|
2449
|
+
return remoteName === null ? null : { repoPath, remoteName };
|
|
2450
|
+
}
|
|
2451
|
+
async function materializeIntoExistingClone(runner, options, url, baseBranch, repoPath, remoteName) {
|
|
2452
|
+
const reportDiagnostic = isolatedReporter(options.reportDiagnostic);
|
|
2453
|
+
reportDiagnostic(`self-review: reusing existing clone at ${repoPath} (remote "${remoteName}")`);
|
|
2454
|
+
const git = bindGit(runner, options);
|
|
2455
|
+
const refs = sessionRefs();
|
|
2456
|
+
const ownedRefs = [refs.base, refs.head];
|
|
2457
|
+
const pendingRefs = new Set(ownedRefs);
|
|
2458
|
+
let releasing;
|
|
2459
|
+
const releaseRefs = async () => {
|
|
2460
|
+
for (const ref of pendingRefs) {
|
|
2461
|
+
try {
|
|
2462
|
+
const result = await runner("git", ["-C", repoPath, "update-ref", "-d", ref], {
|
|
2463
|
+
timeoutMs: CLEANUP_COMMAND_TIMEOUT_MS,
|
|
2464
|
+
gitEnvironment: "isolated"
|
|
2465
|
+
});
|
|
2466
|
+
if (result.exitCode !== 0) {
|
|
2467
|
+
reportCleanupDiagnostic(
|
|
2468
|
+
reportDiagnostic,
|
|
2469
|
+
`self-review: could not delete ${ref} in ${repoPath}: ${result.stderr.trim()}`
|
|
2470
|
+
);
|
|
2471
|
+
} else {
|
|
2472
|
+
pendingRefs.delete(ref);
|
|
2473
|
+
}
|
|
2474
|
+
} catch (error) {
|
|
2475
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2476
|
+
reportCleanupDiagnostic(
|
|
2477
|
+
reportDiagnostic,
|
|
2478
|
+
`self-review: could not delete ${ref} in ${repoPath}: ${message}`
|
|
2479
|
+
);
|
|
2480
|
+
}
|
|
2481
|
+
}
|
|
2482
|
+
};
|
|
2483
|
+
const cleanup = () => {
|
|
2484
|
+
releasing ?? (releasing = releaseRefs().finally(() => {
|
|
2485
|
+
releasing = void 0;
|
|
2486
|
+
}));
|
|
2487
|
+
return releasing;
|
|
2488
|
+
};
|
|
2489
|
+
try {
|
|
2490
|
+
const { baseSha, headSha } = await fetchSnapshot(
|
|
2491
|
+
git,
|
|
2492
|
+
repoPath,
|
|
2493
|
+
remoteName,
|
|
2494
|
+
url,
|
|
2495
|
+
baseBranch,
|
|
2496
|
+
refs,
|
|
2497
|
+
`fetch from remote "${remoteName}"`
|
|
2498
|
+
);
|
|
2499
|
+
return { repoPath, baseSha, headSha, mode: "existing-clone", ownedRefs, cleanup };
|
|
2500
|
+
} catch (error) {
|
|
2501
|
+
await cleanup();
|
|
2502
|
+
throw error;
|
|
2503
|
+
}
|
|
2504
|
+
}
|
|
2505
|
+
async function materializeIntoTempClone(runner, options, url, baseBranch) {
|
|
2506
|
+
const git = bindGit(runner, options);
|
|
2507
|
+
const reportDiagnostic = isolatedReporter(options.reportDiagnostic);
|
|
2508
|
+
const storage = options.temporaryClones ?? nodeTemporaryCloneStorage;
|
|
2509
|
+
const tempDir = await storage.create();
|
|
2510
|
+
let removed = false;
|
|
2511
|
+
let removing;
|
|
2512
|
+
const failed = (error) => {
|
|
2513
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2514
|
+
reportDiagnostic(`self-review: could not remove ${tempDir}: ${message}`);
|
|
2515
|
+
};
|
|
2516
|
+
const cleanupAsync = () => {
|
|
2517
|
+
if (removed) return Promise.resolve();
|
|
2518
|
+
removing ?? (removing = Promise.resolve().then(async () => {
|
|
2519
|
+
try {
|
|
2520
|
+
await storage.remove(tempDir);
|
|
2521
|
+
removed = true;
|
|
2522
|
+
} catch (error) {
|
|
2523
|
+
failed(error);
|
|
2524
|
+
} finally {
|
|
2525
|
+
removing = void 0;
|
|
2526
|
+
}
|
|
2527
|
+
}));
|
|
2528
|
+
return removing;
|
|
2529
|
+
};
|
|
2530
|
+
const cleanup = () => {
|
|
2531
|
+
if (removed) return Promise.resolve();
|
|
2532
|
+
if (removing) return removing;
|
|
2533
|
+
try {
|
|
2534
|
+
storage.removeSync(tempDir);
|
|
2535
|
+
removed = true;
|
|
2536
|
+
} catch (error) {
|
|
2537
|
+
failed(error);
|
|
2538
|
+
}
|
|
2539
|
+
return Promise.resolve();
|
|
2540
|
+
};
|
|
2541
|
+
try {
|
|
2542
|
+
reportDiagnostic(`self-review: created temporary blobless clone at ${tempDir}`);
|
|
2543
|
+
const cloneUrl = cloneUrlFor(url);
|
|
2544
|
+
const clone = await git(["clone", "--filter=blob:none", cloneUrl, tempDir]);
|
|
2545
|
+
if (clone.exitCode !== 0) {
|
|
2546
|
+
throw gitFailure(`clone of ${cloneUrl}`, clone, true);
|
|
2547
|
+
}
|
|
2548
|
+
const { baseSha, headSha } = await fetchSnapshot(
|
|
2549
|
+
git,
|
|
2550
|
+
tempDir,
|
|
2551
|
+
"origin",
|
|
2552
|
+
url,
|
|
2553
|
+
baseBranch,
|
|
2554
|
+
sessionRefs(),
|
|
2555
|
+
`fetch of ${headRefFor(url)}`
|
|
2556
|
+
);
|
|
2557
|
+
return {
|
|
2558
|
+
repoPath: tempDir,
|
|
2559
|
+
baseSha,
|
|
2560
|
+
headSha,
|
|
2561
|
+
mode: "temp-clone",
|
|
2562
|
+
ownedRefs: [],
|
|
2563
|
+
cleanup,
|
|
2564
|
+
cleanupAsync
|
|
2565
|
+
};
|
|
2566
|
+
} catch (error) {
|
|
2567
|
+
await cleanupAsync();
|
|
2568
|
+
throw error;
|
|
2569
|
+
}
|
|
2570
|
+
}
|
|
2571
|
+
async function materialize(url, baseBranch, cwd, runner = defaultGitRunner, existingClone, options = {}) {
|
|
2572
|
+
if (options.signal?.aborted) {
|
|
2573
|
+
throw new CommandCancelledError("aborted", "git", ["materialize", cloneUrlFor(url)]);
|
|
2574
|
+
}
|
|
2575
|
+
const existing = existingClone === void 0 ? await detectExistingClone(url, cwd, runner, options) : existingClone;
|
|
2576
|
+
if (existing) {
|
|
2577
|
+
return materializeIntoExistingClone(
|
|
2578
|
+
runner,
|
|
2579
|
+
options,
|
|
2580
|
+
url,
|
|
2581
|
+
baseBranch,
|
|
2582
|
+
existing.repoPath,
|
|
2583
|
+
existing.remoteName
|
|
2584
|
+
);
|
|
2585
|
+
}
|
|
2586
|
+
return materializeIntoTempClone(runner, options, url, baseBranch);
|
|
2587
|
+
}
|
|
2588
|
+
async function resolveRemoteDefaultBranch(url, runner = defaultGitRunner, existing = null, options = {}) {
|
|
2589
|
+
const git = bindGit(runner, options);
|
|
2590
|
+
const cloneUrl = cloneUrlFor(url);
|
|
2591
|
+
const remote = existing?.remoteName ?? cloneUrl;
|
|
2592
|
+
const label = existing ? `${remote} (${cloneUrl})` : cloneUrl;
|
|
2593
|
+
const args = existing ? ["-C", existing.repoPath, "ls-remote", "--symref", remote, "HEAD"] : ["ls-remote", "--symref", remote, "HEAD"];
|
|
2594
|
+
const result = await git(args);
|
|
2595
|
+
if (result.exitCode !== 0) {
|
|
2596
|
+
throw gitFailure(`ls-remote of ${label}`, result, true);
|
|
2597
|
+
}
|
|
2598
|
+
const match = /^ref:\s+refs\/heads\/(\S+)\s+HEAD$/m.exec(result.stdout);
|
|
2599
|
+
if (!match) {
|
|
2600
|
+
throw new Error(
|
|
2601
|
+
`Failed to resolve the default branch of ${label}: git ls-remote returned no HEAD symref.`
|
|
2602
|
+
);
|
|
2603
|
+
}
|
|
2604
|
+
return match[1];
|
|
2605
|
+
}
|
|
2606
|
+
function reportCleanupDiagnostic(report, message) {
|
|
2607
|
+
try {
|
|
2608
|
+
report(message);
|
|
2609
|
+
} catch {
|
|
2610
|
+
}
|
|
2611
|
+
}
|
|
2612
|
+
|
|
2613
|
+
// src/review-session.ts
|
|
2614
|
+
function createReviewSession() {
|
|
2615
|
+
return {
|
|
2616
|
+
reviewState: null,
|
|
2617
|
+
diffData: null,
|
|
2618
|
+
guideData: null,
|
|
2619
|
+
config: null,
|
|
2620
|
+
outputPathInfo: null,
|
|
2621
|
+
resumeComments: [],
|
|
2622
|
+
resumeViewedFiles: [],
|
|
2623
|
+
resumeRemoteDrift: null,
|
|
2624
|
+
resumeImportDiagnostics: [],
|
|
2625
|
+
applyDestinationRoot: null,
|
|
2626
|
+
reviewedPaths: emptyReviewedPaths(),
|
|
2627
|
+
sourceIdentity: null,
|
|
2628
|
+
attachmentOrigins: /* @__PURE__ */ new Map()
|
|
2629
|
+
};
|
|
2630
|
+
}
|
|
2631
|
+
function emptyReviewedPaths() {
|
|
2632
|
+
return freezeSet(/* @__PURE__ */ new Set());
|
|
2633
|
+
}
|
|
2634
|
+
function freezeSet(set) {
|
|
2635
|
+
const frozen = () => {
|
|
2636
|
+
throw new TypeError("reviewedPaths is captured when the diff is committed and cannot change");
|
|
2637
|
+
};
|
|
2638
|
+
Object.defineProperties(set, {
|
|
2639
|
+
add: { value: frozen },
|
|
2640
|
+
delete: { value: frozen },
|
|
2641
|
+
clear: { value: frozen }
|
|
2642
|
+
});
|
|
2643
|
+
return Object.freeze(set);
|
|
2644
|
+
}
|
|
2645
|
+
function reviewedPathsOf(files) {
|
|
2646
|
+
const paths = /* @__PURE__ */ new Set();
|
|
2647
|
+
for (const file of files) {
|
|
2648
|
+
if (file.newPath) paths.add(file.newPath);
|
|
2649
|
+
if (file.oldPath) paths.add(file.oldPath);
|
|
2650
|
+
}
|
|
2651
|
+
return freezeSet(paths);
|
|
2652
|
+
}
|
|
2653
|
+
function commitDiffData(session, payload, identity) {
|
|
2654
|
+
if ("loadedReview" in session)
|
|
2655
|
+
session.loadedReview = null;
|
|
2656
|
+
session.diffData = payload;
|
|
2657
|
+
session.reviewedPaths = reviewedPathsOf(payload.files);
|
|
2658
|
+
session.sourceIdentity = identity;
|
|
2659
|
+
}
|
|
2660
|
+
function commitLoadedReview(session, payload, loadedReview) {
|
|
2661
|
+
const identity = loadedReviewIdentity(loadedReview);
|
|
2662
|
+
commitDiffData(session, payload, identity);
|
|
2663
|
+
session.loadedReview = loadedReview;
|
|
2664
|
+
}
|
|
2665
|
+
function locateReviewedFile(session, filePath) {
|
|
2666
|
+
const files = session.diffData?.files ?? [];
|
|
2667
|
+
const byNewPath = files.find((f) => f.newPath !== "" && f.newPath === filePath);
|
|
2668
|
+
if (byNewPath) return { file: byNewPath, side: "new" };
|
|
2669
|
+
const byOldPath = files.find((f) => f.oldPath !== "" && f.oldPath === filePath);
|
|
2670
|
+
if (byOldPath) return { file: byOldPath, side: "old" };
|
|
2671
|
+
return null;
|
|
2672
|
+
}
|
|
2673
|
+
function preparePayload(payload) {
|
|
2674
|
+
if (payload.isLargePayload) {
|
|
2675
|
+
return {
|
|
2676
|
+
...payload,
|
|
2677
|
+
files: payload.files.map((f) => ({ ...f, hunks: [], contentLoaded: false }))
|
|
2678
|
+
};
|
|
2679
|
+
}
|
|
2680
|
+
return {
|
|
2681
|
+
...payload,
|
|
2682
|
+
files: payload.files.map((f) => ({ ...f, contentLoaded: true }))
|
|
2683
|
+
};
|
|
2684
|
+
}
|
|
2685
|
+
function getDiffLoad(session) {
|
|
2686
|
+
if (!session.diffData) {
|
|
2687
|
+
return null;
|
|
2688
|
+
}
|
|
2689
|
+
return {
|
|
2690
|
+
diff: preparePayload(session.diffData),
|
|
2691
|
+
guide: session.guideData
|
|
2692
|
+
};
|
|
2693
|
+
}
|
|
2694
|
+
function resolveSourceBaseDir(session) {
|
|
2695
|
+
return session.sourceIdentity?.sourceRoot ?? null;
|
|
2696
|
+
}
|
|
2697
|
+
function getFileHunks(session, filePath) {
|
|
2698
|
+
if (!session.diffData) return null;
|
|
2699
|
+
const file = session.diffData.files.find((f) => (f.newPath || f.oldPath) === filePath);
|
|
2700
|
+
if (!file) return null;
|
|
2701
|
+
return file.hunks;
|
|
2702
|
+
}
|
|
2703
|
+
function getConfigLoad(session) {
|
|
2704
|
+
if (!session.config) {
|
|
2705
|
+
return null;
|
|
2706
|
+
}
|
|
2707
|
+
return { config: session.config, outputPathInfo: session.outputPathInfo };
|
|
2708
|
+
}
|
|
2709
|
+
function submitReviewState(session, state, reportDiagnostic = stderrReporter) {
|
|
2710
|
+
state = validateReviewState(state);
|
|
2711
|
+
isolatedReporter(reportDiagnostic)(
|
|
2712
|
+
"[review] Review state submitted:",
|
|
2713
|
+
JSON.stringify({
|
|
2714
|
+
timestamp: state.timestamp,
|
|
2715
|
+
source: state.source,
|
|
2716
|
+
fileCount: state.files.length
|
|
2717
|
+
})
|
|
2718
|
+
);
|
|
2719
|
+
session.reviewState = state;
|
|
2720
|
+
}
|
|
2721
|
+
function takeReviewState(session) {
|
|
2722
|
+
const state = session.reviewState;
|
|
2723
|
+
session.reviewState = null;
|
|
2724
|
+
return state;
|
|
2725
|
+
}
|
|
2726
|
+
function getResumeLoad(session) {
|
|
2727
|
+
if (session.resumeComments.length > 0 || session.resumeViewedFiles.length > 0 || session.resumeRemoteDrift !== null || session.resumeImportDiagnostics.length > 0) {
|
|
2728
|
+
const payload = {
|
|
2729
|
+
comments: session.resumeComments,
|
|
2730
|
+
viewedFiles: session.resumeViewedFiles
|
|
2731
|
+
};
|
|
2732
|
+
if (session.resumeRemoteDrift !== null) {
|
|
2733
|
+
payload.remoteDrift = session.resumeRemoteDrift;
|
|
2734
|
+
}
|
|
2735
|
+
if (session.resumeImportDiagnostics.length > 0) {
|
|
2736
|
+
payload.importDiagnostics = session.resumeImportDiagnostics;
|
|
2737
|
+
}
|
|
2738
|
+
return payload;
|
|
2739
|
+
}
|
|
2740
|
+
return null;
|
|
2741
|
+
}
|
|
2742
|
+
|
|
2743
|
+
// src/source-identity.ts
|
|
2744
|
+
import { realpathSync as realpathSync4 } from "fs";
|
|
2745
|
+
import * as path6 from "path";
|
|
2746
|
+
var WORKING_TREE = { kind: "working-tree" };
|
|
2747
|
+
var INDEX = { kind: "index" };
|
|
2748
|
+
var HEAD = { kind: "revision", rev: "HEAD", implicit: true };
|
|
2749
|
+
function revision(rev) {
|
|
2750
|
+
return rev === "" ? HEAD : { kind: "revision", rev, implicit: false };
|
|
2751
|
+
}
|
|
2752
|
+
function mergeBase(left, right) {
|
|
2753
|
+
return { kind: "merge-base", left: left || "HEAD", right: right || "HEAD" };
|
|
2754
|
+
}
|
|
2755
|
+
function unknownSides(reason) {
|
|
2756
|
+
return { oldSide: { kind: "unknown", reason }, newSide: { kind: "unknown", reason } };
|
|
2757
|
+
}
|
|
2758
|
+
function describeGitDiffSides(argv) {
|
|
2759
|
+
const parsed = parseGitDiffArgs(argv);
|
|
2760
|
+
const names = new Set(parsed.options.map((option) => option.name));
|
|
2761
|
+
if (names.has("--no-index")) return unknownSides("--no-index compares paths, not snapshots");
|
|
2762
|
+
const revs = parsed.positionalIndices.filter((index) => parsed.separatorIndex === null || index < parsed.separatorIndex).map((index) => argv[index]);
|
|
2763
|
+
const cached = names.has("--cached") || names.has("--staged");
|
|
2764
|
+
const reverse = names.has("-R");
|
|
2765
|
+
const useMergeBase = names.has("--merge-base");
|
|
2766
|
+
const sides = describeRevisionSides(revs, cached, useMergeBase);
|
|
2767
|
+
return reverse ? { oldSide: sides.newSide, newSide: sides.oldSide } : sides;
|
|
2768
|
+
}
|
|
2769
|
+
function describeRevisionSides(revs, cached, useMergeBase) {
|
|
2770
|
+
if (revs.length === 0) {
|
|
2771
|
+
if (useMergeBase) return unknownSides("--merge-base requires a revision");
|
|
2772
|
+
return cached ? { oldSide: HEAD, newSide: INDEX } : { oldSide: INDEX, newSide: WORKING_TREE };
|
|
2773
|
+
}
|
|
2774
|
+
if (revs.length === 1) {
|
|
2775
|
+
const rev = revs[0];
|
|
2776
|
+
const symmetric = rev.indexOf("...");
|
|
2777
|
+
if (symmetric !== -1) {
|
|
2778
|
+
if (cached) return unknownSides("--cached does not accept a revision range");
|
|
2779
|
+
const left = rev.slice(0, symmetric);
|
|
2780
|
+
const right = rev.slice(symmetric + 3);
|
|
2781
|
+
return { oldSide: mergeBase(left, right), newSide: revision(right) };
|
|
2782
|
+
}
|
|
2783
|
+
const range = rev.indexOf("..");
|
|
2784
|
+
if (range !== -1) {
|
|
2785
|
+
if (cached) return unknownSides("--cached does not accept a revision range");
|
|
2786
|
+
return { oldSide: revision(rev.slice(0, range)), newSide: revision(rev.slice(range + 2)) };
|
|
2787
|
+
}
|
|
2788
|
+
const oldSide = useMergeBase ? mergeBase(rev, "HEAD") : revision(rev);
|
|
2789
|
+
return { oldSide, newSide: cached ? INDEX : WORKING_TREE };
|
|
2790
|
+
}
|
|
2791
|
+
if (revs.length === 2) {
|
|
2792
|
+
if (cached) return unknownSides("--cached does not accept two revisions");
|
|
2793
|
+
const [left, right] = revs;
|
|
2794
|
+
return {
|
|
2795
|
+
oldSide: useMergeBase ? mergeBase(left, right) : revision(left),
|
|
2796
|
+
newSide: revision(right)
|
|
2797
|
+
};
|
|
2798
|
+
}
|
|
2799
|
+
return unknownSides(`a combined diff of ${revs.length} revisions has no single old side`);
|
|
2800
|
+
}
|
|
2801
|
+
async function gitOutput(repository, args, options) {
|
|
2802
|
+
try {
|
|
2803
|
+
return (await executeGit(args, repository, options)).replace(/\r?\n$/, "");
|
|
2804
|
+
} catch (error) {
|
|
2805
|
+
if (isCommandCancelled(error)) throw error;
|
|
2806
|
+
return null;
|
|
2807
|
+
}
|
|
2808
|
+
}
|
|
2809
|
+
var SHA_PATTERN = /^[0-9a-f]{40,64}$/;
|
|
2810
|
+
async function resolveCommit(repository, rev, options) {
|
|
2811
|
+
const sha = await gitOutput(
|
|
2812
|
+
repository,
|
|
2813
|
+
["rev-parse", "--verify", "--quiet", "--end-of-options", `${rev}^{commit}`],
|
|
2814
|
+
options
|
|
2815
|
+
);
|
|
2816
|
+
return sha !== null && SHA_PATTERN.test(sha) ? sha : null;
|
|
2817
|
+
}
|
|
2818
|
+
async function resolveSide(repository, spec, options) {
|
|
2819
|
+
switch (spec.kind) {
|
|
2820
|
+
case "working-tree":
|
|
2821
|
+
case "index":
|
|
2822
|
+
case "unknown":
|
|
2823
|
+
return spec;
|
|
2824
|
+
case "revision": {
|
|
2825
|
+
const sha = await resolveCommit(repository, spec.rev, options);
|
|
2826
|
+
if (sha !== null) return { kind: "commit", sha };
|
|
2827
|
+
if (spec.implicit) return { kind: "none" };
|
|
2828
|
+
return { kind: "unknown", reason: `${spec.rev} does not name a commit` };
|
|
2829
|
+
}
|
|
2830
|
+
case "merge-base": {
|
|
2831
|
+
const sha = await gitOutput(repository, ["merge-base", spec.left, spec.right], options);
|
|
2832
|
+
if (sha !== null && SHA_PATTERN.test(sha)) return { kind: "commit", sha };
|
|
2833
|
+
return {
|
|
2834
|
+
kind: "unknown",
|
|
2835
|
+
reason: `no merge base between ${spec.left} and ${spec.right}`
|
|
2836
|
+
};
|
|
2837
|
+
}
|
|
2838
|
+
}
|
|
2839
|
+
}
|
|
2840
|
+
function canonicalSourcePath(target) {
|
|
2841
|
+
try {
|
|
2842
|
+
return realpathSync4(target);
|
|
2843
|
+
} catch {
|
|
2844
|
+
return path6.resolve(target);
|
|
2845
|
+
}
|
|
2846
|
+
}
|
|
2847
|
+
function resolveReviewedPathPrefix(gitDiffArgv, sourceRoot, invocationCwd, canonical = canonicalSourcePath) {
|
|
2848
|
+
const relative3 = describeDiffPathRelativity(gitDiffArgv);
|
|
2849
|
+
switch (relative3.kind) {
|
|
2850
|
+
case "root":
|
|
2851
|
+
return "";
|
|
2852
|
+
case "directory":
|
|
2853
|
+
return relative3.directory.replace(/\/+$/, "");
|
|
2854
|
+
case "cwd": {
|
|
2855
|
+
const fromRoot = path6.relative(canonical(sourceRoot), canonical(invocationCwd));
|
|
2856
|
+
if (fromRoot === "" || fromRoot.startsWith("..") || path6.isAbsolute(fromRoot)) return "";
|
|
2857
|
+
return fromRoot.split(path6.sep).join("/");
|
|
2858
|
+
}
|
|
2859
|
+
}
|
|
2860
|
+
}
|
|
2861
|
+
function rootRelativeReviewedPath(identity, filePath) {
|
|
2862
|
+
return identity.pathPrefix === "" ? filePath : `${identity.pathPrefix}/${filePath}`;
|
|
2863
|
+
}
|
|
2864
|
+
async function resolveGitSourceIdentity(options) {
|
|
2865
|
+
const sides = describeGitDiffSides(options.gitDiffArgv);
|
|
2866
|
+
const repository = options.repository;
|
|
2867
|
+
const [oldSide, newSide] = await Promise.all([
|
|
2868
|
+
resolveSide(repository, sides.oldSide, options),
|
|
2869
|
+
resolveSide(repository, sides.newSide, options)
|
|
2870
|
+
]);
|
|
2871
|
+
const emptyTreeSha = oldSide.kind === "none" || newSide.kind === "none" ? await gitOutput(repository, ["hash-object", "-t", "tree", "--stdin"], options) : null;
|
|
2872
|
+
const invocationCwd = options.invocationCwd ?? process.cwd();
|
|
2873
|
+
const sourceRoot = options.sourcePaths ? await canonicalLocalPath(repository, options.sourcePaths, options.signal) : canonicalSourcePath(repository);
|
|
2874
|
+
const physicalCwd = options.sourcePaths && describeDiffPathRelativity(options.gitDiffArgv).kind === "cwd" ? await canonicalLocalPath(invocationCwd, options.sourcePaths, options.signal) : invocationCwd;
|
|
2875
|
+
return {
|
|
2876
|
+
mode: options.mode ?? "git",
|
|
2877
|
+
...emptyTreeSha !== null && SHA_PATTERN.test(emptyTreeSha) ? { emptyTreeSha } : {},
|
|
2878
|
+
sourceRoot,
|
|
2879
|
+
invocationCwd,
|
|
2880
|
+
gitDiffArgv: [...options.gitDiffArgv],
|
|
2881
|
+
pathPrefix: resolveReviewedPathPrefix(
|
|
2882
|
+
options.gitDiffArgv,
|
|
2883
|
+
sourceRoot,
|
|
2884
|
+
physicalCwd,
|
|
2885
|
+
options.sourcePaths ? (target) => target : canonicalSourcePath
|
|
2886
|
+
),
|
|
2887
|
+
oldSide,
|
|
2888
|
+
newSide
|
|
2889
|
+
};
|
|
2890
|
+
}
|
|
2891
|
+
function resolveLocalSourceIdentity(options) {
|
|
2892
|
+
return localIdentity(options, canonicalSourcePath);
|
|
2893
|
+
}
|
|
2894
|
+
async function resolveLocalSourceIdentityAsync(options, paths, signal) {
|
|
2895
|
+
const canonical = (target) => canonicalLocalPath(target, paths, signal);
|
|
2896
|
+
const root = await canonical(
|
|
2897
|
+
options.type === "file" ? path6.dirname(options.sourcePath) : options.sourcePath
|
|
2898
|
+
);
|
|
2899
|
+
const file = options.type === "file" ? await canonical(options.sourcePath) : void 0;
|
|
2900
|
+
return localIdentity(
|
|
2901
|
+
options,
|
|
2902
|
+
(target) => target === options.sourcePath && file !== void 0 ? file : root
|
|
2903
|
+
);
|
|
2904
|
+
}
|
|
2905
|
+
function localIdentity(options, canonical) {
|
|
2906
|
+
const invocationCwd = options.invocationCwd ?? process.cwd();
|
|
2907
|
+
if (options.type === "directory") {
|
|
2908
|
+
return {
|
|
2909
|
+
mode: "directory",
|
|
2910
|
+
sourceRoot: canonical(options.sourcePath),
|
|
2911
|
+
invocationCwd,
|
|
2912
|
+
gitDiffArgv: [],
|
|
2913
|
+
pathPrefix: "",
|
|
2914
|
+
oldSide: { kind: "none" },
|
|
2915
|
+
newSide: { kind: "directory" }
|
|
2916
|
+
};
|
|
2917
|
+
}
|
|
2918
|
+
return {
|
|
2919
|
+
mode: "file",
|
|
2920
|
+
sourceRoot: canonical(path6.dirname(options.sourcePath)),
|
|
2921
|
+
invocationCwd,
|
|
2922
|
+
gitDiffArgv: [],
|
|
2923
|
+
pathPrefix: "",
|
|
2924
|
+
oldSide: { kind: "none" },
|
|
2925
|
+
newSide: { kind: "file", path: canonical(options.sourcePath) }
|
|
2926
|
+
};
|
|
2927
|
+
}
|
|
2928
|
+
async function canonicalLocalPath(target, paths, signal) {
|
|
2929
|
+
checkLoadingCancelled(signal);
|
|
2930
|
+
try {
|
|
2931
|
+
const result = await paths.realpath(target);
|
|
2932
|
+
checkLoadingCancelled(signal);
|
|
2933
|
+
return result;
|
|
2934
|
+
} catch {
|
|
2935
|
+
checkLoadingCancelled(signal);
|
|
2936
|
+
return path6.resolve(target);
|
|
2937
|
+
}
|
|
2938
|
+
}
|
|
2939
|
+
|
|
2940
|
+
// src/suggestion-read.ts
|
|
2941
|
+
function inputBudgetError(target, maxBytes) {
|
|
2942
|
+
return new SafeFsError(
|
|
2943
|
+
"too-large",
|
|
2944
|
+
target,
|
|
2945
|
+
`The destination exceeds the ${maxBytes} byte Apply input limit, so nothing was written.`
|
|
2946
|
+
);
|
|
2947
|
+
}
|
|
2948
|
+
function* boundedChunks(target, size, maxBytes) {
|
|
2949
|
+
if (size > maxBytes) throw inputBudgetError(target, maxBytes);
|
|
2950
|
+
let buffer = Buffer.alloc(Math.min(size + 1, maxBytes + 1));
|
|
2951
|
+
let filled = 0;
|
|
2952
|
+
for (; ; ) {
|
|
2953
|
+
const length = Math.min(buffer.length - filled, 64 * 1024);
|
|
2954
|
+
const read2 = yield { buffer, offset: filled, length };
|
|
2955
|
+
if (!Number.isInteger(read2) || read2 < 0 || read2 > length)
|
|
2956
|
+
throw new SafeFsError("io-error", target, "Invalid descriptor read length.");
|
|
2957
|
+
if (read2 === 0) return buffer.subarray(0, filled);
|
|
2958
|
+
filled += read2;
|
|
2959
|
+
if (filled > maxBytes) throw inputBudgetError(target, maxBytes);
|
|
2960
|
+
if (filled === buffer.length) {
|
|
2961
|
+
const next = Buffer.alloc(Math.min(Math.max(1, buffer.length * 2), maxBytes + 1));
|
|
2962
|
+
buffer.copy(next);
|
|
2963
|
+
buffer = next;
|
|
2964
|
+
}
|
|
2965
|
+
}
|
|
2966
|
+
}
|
|
2967
|
+
function readSuggestionSync(fd, target, size, maxBytes, layer) {
|
|
2968
|
+
const read2 = layer.readSync;
|
|
2969
|
+
return read2 ? readSuggestionBoundedSync(fd, target, size, maxBytes, {
|
|
2970
|
+
readSync: (...args) => read2.call(layer, ...args)
|
|
2971
|
+
}) : readLegacySuggestionSync(fd, target, size, maxBytes, layer);
|
|
2972
|
+
}
|
|
2973
|
+
function readLegacySuggestionSync(fd, target, size, maxBytes, layer) {
|
|
2974
|
+
if (size > maxBytes) throw inputBudgetError(target, maxBytes);
|
|
2975
|
+
const bytes = layer.readFileSync(fd);
|
|
2976
|
+
if (bytes.length > maxBytes) throw inputBudgetError(target, maxBytes);
|
|
2977
|
+
return bytes;
|
|
2978
|
+
}
|
|
2979
|
+
function readSuggestionBoundedSync(fd, target, size, maxBytes, layer) {
|
|
2980
|
+
const chunks = boundedChunks(target, size, maxBytes);
|
|
2981
|
+
let step = chunks.next();
|
|
2982
|
+
while (!step.done) {
|
|
2983
|
+
const { buffer, offset, length } = step.value;
|
|
2984
|
+
const read2 = layer.readSync(fd, buffer, offset, length, null);
|
|
2985
|
+
step = chunks.next(read2);
|
|
2986
|
+
}
|
|
2987
|
+
return step.value;
|
|
2988
|
+
}
|
|
2989
|
+
|
|
2990
|
+
// src/apply-suggestion.ts
|
|
2991
|
+
import * as path7 from "path";
|
|
2992
|
+
import { constants as bufferConstants } from "buffer";
|
|
2993
|
+
|
|
2994
|
+
// src/suggestion-content.ts
|
|
2995
|
+
import { isUtf8 } from "buffer";
|
|
2996
|
+
function locateAnchor(bytes, start, end) {
|
|
2997
|
+
let lineCount = 0;
|
|
2998
|
+
let startOffset = -1;
|
|
2999
|
+
let endOffset = -1;
|
|
3000
|
+
let crlf = true;
|
|
3001
|
+
for (let offset = 0; offset < bytes.length; ) {
|
|
3002
|
+
lineCount++;
|
|
3003
|
+
const newline = bytes.indexOf(10, offset);
|
|
3004
|
+
const lineEnd = newline === -1 ? bytes.length : newline;
|
|
3005
|
+
if (lineCount === start) startOffset = offset;
|
|
3006
|
+
if (lineCount >= start && lineCount <= end) {
|
|
3007
|
+
if (lineEnd === offset || bytes[lineEnd - 1] !== 13) crlf = false;
|
|
3008
|
+
}
|
|
3009
|
+
if (lineCount === end) endOffset = lineEnd;
|
|
3010
|
+
offset = newline === -1 ? bytes.length : newline + 1;
|
|
3011
|
+
}
|
|
3012
|
+
return { lineCount, startOffset, endOffset, crlf };
|
|
3013
|
+
}
|
|
3014
|
+
function proposalBody(proposed) {
|
|
3015
|
+
if (proposed.endsWith("\r\n")) return proposed.slice(0, -2);
|
|
3016
|
+
return proposed.endsWith("\n") ? proposed.slice(0, -1) : proposed;
|
|
3017
|
+
}
|
|
3018
|
+
function outputBudgetRefusal(maxBytes) {
|
|
3019
|
+
return {
|
|
3020
|
+
reason: "write-failed",
|
|
3021
|
+
detail: `The proposed file exceeds the ${maxBytes} byte Apply output limit, so nothing was written.`
|
|
3022
|
+
};
|
|
3023
|
+
}
|
|
3024
|
+
function prepareSuggestionContent(bytes, start, end, suggestion, maxOutputBytes) {
|
|
3025
|
+
if (!isUtf8(bytes))
|
|
3026
|
+
return { reason: "file-not-utf8", detail: "The file is not valid UTF-8 text." };
|
|
3027
|
+
const anchor = locateAnchor(bytes, start, end);
|
|
3028
|
+
if (end > anchor.lineCount) {
|
|
3029
|
+
return {
|
|
3030
|
+
reason: "anchor-out-of-range",
|
|
3031
|
+
detail: `Lines ${start}-${end} are outside this file, which has ${anchor.lineCount} line(s).`
|
|
3032
|
+
};
|
|
3033
|
+
}
|
|
3034
|
+
const original = bytes.subarray(anchor.startOffset, anchor.endOffset);
|
|
3035
|
+
if (suggestion.originalCode.length > original.length || Buffer.byteLength(suggestion.originalCode) !== original.length || original.toString("utf8") !== suggestion.originalCode) {
|
|
3036
|
+
return {
|
|
3037
|
+
reason: "context-mismatch",
|
|
3038
|
+
detail: `Lines ${start}-${end} no longer match the code this suggestion was written against.`
|
|
3039
|
+
};
|
|
3040
|
+
}
|
|
3041
|
+
const hasReplacement = suggestion.proposedCode !== "";
|
|
3042
|
+
const body = proposalBody(suggestion.proposedCode);
|
|
3043
|
+
if (body.length > maxOutputBytes || Buffer.byteLength(body) > maxOutputBytes)
|
|
3044
|
+
return outputBudgetRefusal(maxOutputBytes);
|
|
3045
|
+
if (!isWellFormedUnicode(body))
|
|
3046
|
+
return {
|
|
3047
|
+
reason: "write-failed",
|
|
3048
|
+
detail: "The proposed code contains an unpaired Unicode surrogate, so nothing was written."
|
|
3049
|
+
};
|
|
3050
|
+
const proposed = Buffer.from(body);
|
|
3051
|
+
let extraCrs = 0;
|
|
3052
|
+
if (hasReplacement && anchor.crlf) {
|
|
3053
|
+
for (let i = 0; i <= proposed.length; i++) {
|
|
3054
|
+
if ((i === proposed.length || proposed[i] === 10) && (i === 0 || proposed[i - 1] !== 13))
|
|
3055
|
+
extraCrs++;
|
|
3056
|
+
}
|
|
3057
|
+
}
|
|
3058
|
+
const hasPrefix = start > 1;
|
|
3059
|
+
const hasSuffix = end < anchor.lineCount;
|
|
3060
|
+
const hasOutput = hasPrefix || hasReplacement || hasSuffix;
|
|
3061
|
+
const trailingLf = bytes.length > 0 && bytes[bytes.length - 1] === 10;
|
|
3062
|
+
const logicalEnd = bytes.length - (trailingLf ? 1 : 0);
|
|
3063
|
+
const prefixEnd = hasPrefix ? anchor.startOffset - (hasReplacement || hasSuffix ? 0 : 1) : 0;
|
|
3064
|
+
const suffixStart = hasSuffix ? anchor.endOffset + 1 : logicalEnd;
|
|
3065
|
+
const separator = hasReplacement && hasSuffix ? 1 : 0;
|
|
3066
|
+
const finalLf = hasOutput && trailingLf ? 1 : 0;
|
|
3067
|
+
const size = prefixEnd + proposed.length + extraCrs + separator + (logicalEnd - suffixStart) + finalLf;
|
|
3068
|
+
if (size > maxOutputBytes) return outputBudgetRefusal(maxOutputBytes);
|
|
3069
|
+
const output = Buffer.allocUnsafe(size);
|
|
3070
|
+
let offset = bytes.copy(output, 0, 0, prefixEnd);
|
|
3071
|
+
for (let from = 0; from < proposed.length; ) {
|
|
3072
|
+
const newline = proposed.indexOf(10, from);
|
|
3073
|
+
const to = newline === -1 ? proposed.length : newline;
|
|
3074
|
+
offset += proposed.copy(output, offset, from, to);
|
|
3075
|
+
if (anchor.crlf && hasReplacement && (to === from || proposed[to - 1] !== 13))
|
|
3076
|
+
output[offset++] = 13;
|
|
3077
|
+
if (newline !== -1) output[offset++] = 10;
|
|
3078
|
+
from = newline === -1 ? proposed.length : newline + 1;
|
|
3079
|
+
}
|
|
3080
|
+
if (anchor.crlf && hasReplacement && (proposed.length === 0 || proposed[proposed.length - 1] === 10))
|
|
3081
|
+
output[offset++] = 13;
|
|
3082
|
+
if (separator) output[offset++] = 10;
|
|
3083
|
+
offset += bytes.copy(output, offset, suffixStart, logicalEnd);
|
|
3084
|
+
if (finalLf) output[offset++] = 10;
|
|
3085
|
+
return { bytes: output, replacedLines: end - start + 1 };
|
|
3086
|
+
}
|
|
3087
|
+
|
|
3088
|
+
// src/apply-suggestion.ts
|
|
3089
|
+
function isRepositoryControlPath(filePath) {
|
|
3090
|
+
return filePath.split(/[\\/]+/).some((segment) => segment.toLowerCase() === ".git");
|
|
3091
|
+
}
|
|
3092
|
+
function refuse(filePath, reason, detail) {
|
|
3093
|
+
return { status: "refused", filePath, reason, detail };
|
|
3094
|
+
}
|
|
3095
|
+
var FS_REFUSALS = {
|
|
3096
|
+
"not-found": ["file-missing", "The file is not in the destination directory."],
|
|
3097
|
+
"unsafe-link": [
|
|
3098
|
+
"unsafe-target",
|
|
3099
|
+
"The path goes through a symbolic link, and this program does not write through links."
|
|
3100
|
+
],
|
|
3101
|
+
"not-regular": ["unsafe-target", "The path is not a regular file."],
|
|
3102
|
+
"output-is-directory": ["file-unreadable", "The path is a directory, not a file."],
|
|
3103
|
+
"unsupported-target": [
|
|
3104
|
+
"unsupported-target",
|
|
3105
|
+
"The file is owned by another user, and replacing it would change its owner."
|
|
3106
|
+
],
|
|
3107
|
+
"identity-changed": [
|
|
3108
|
+
"file-changed",
|
|
3109
|
+
"The file changed on disk after it was read, so nothing was written."
|
|
3110
|
+
]
|
|
3111
|
+
};
|
|
3112
|
+
function refuseFsError(filePath, error, fallback) {
|
|
3113
|
+
const fsError = toSafeFsError(error, filePath, "access");
|
|
3114
|
+
if (fsError.code === "too-large") return refuse(filePath, fallback, fsError.message);
|
|
3115
|
+
const [reason, detail] = FS_REFUSALS[fsError.code] ?? [
|
|
3116
|
+
fallback,
|
|
3117
|
+
`The file could not be ${fallback === "write-failed" ? "written" : "read"} (${errnoOf(fsError.cause) ?? "unknown"}).`
|
|
3118
|
+
];
|
|
3119
|
+
return refuse(filePath, reason, detail);
|
|
3120
|
+
}
|
|
3121
|
+
function relativeWithinRoot(filePath) {
|
|
3122
|
+
if (filePath === "" || path7.posix.isAbsolute(filePath) || path7.win32.isAbsolute(filePath)) {
|
|
3123
|
+
return null;
|
|
3124
|
+
}
|
|
3125
|
+
if (filePath.split("/").some((segment) => segment === "..")) return null;
|
|
3126
|
+
const normalized = path7.posix.normalize(filePath);
|
|
3127
|
+
if (normalized === "." || normalized === ".." || normalized.startsWith("../")) return null;
|
|
3128
|
+
return normalized;
|
|
3129
|
+
}
|
|
3130
|
+
function openAndRead(realRoot, rel, filePath, fs5, maxInputBytes) {
|
|
3131
|
+
let opened;
|
|
3132
|
+
try {
|
|
3133
|
+
opened = openContainedFile(realRoot, rel, fs5);
|
|
3134
|
+
} catch (error) {
|
|
3135
|
+
return refuseFsError(filePath, error, "file-unreadable");
|
|
3136
|
+
}
|
|
3137
|
+
const { fd, stats } = opened;
|
|
3138
|
+
try {
|
|
3139
|
+
if (stats.nlink > 1) {
|
|
3140
|
+
return refuse(
|
|
3141
|
+
filePath,
|
|
3142
|
+
"unsafe-target",
|
|
3143
|
+
`The file has ${stats.nlink} hard links, and replacing it would silently detach the others.`
|
|
3144
|
+
);
|
|
3145
|
+
}
|
|
3146
|
+
return {
|
|
3147
|
+
identity: snapshotIdentity(stats),
|
|
3148
|
+
buffer: readSuggestionSync(fd, path7.join(realRoot, rel), stats.size, maxInputBytes, fs5)
|
|
3149
|
+
};
|
|
3150
|
+
} catch (error) {
|
|
3151
|
+
return refuseFsError(filePath, error, "file-unreadable");
|
|
3152
|
+
} finally {
|
|
3153
|
+
try {
|
|
3154
|
+
fs5.closeSync(fd);
|
|
3155
|
+
} catch {
|
|
3156
|
+
}
|
|
3157
|
+
}
|
|
3158
|
+
}
|
|
3159
|
+
function validateRequest(request) {
|
|
3160
|
+
const { destinationRoot, filePath, lineRange } = request;
|
|
3161
|
+
if (!lineRange) {
|
|
3162
|
+
return refuse(
|
|
3163
|
+
filePath,
|
|
3164
|
+
"no-anchor",
|
|
3165
|
+
"This suggestion is file-level, so there are no lines to replace."
|
|
3166
|
+
);
|
|
3167
|
+
}
|
|
3168
|
+
if (lineRange.side === "old") {
|
|
3169
|
+
return refuse(
|
|
3170
|
+
filePath,
|
|
3171
|
+
"old-side-anchor",
|
|
3172
|
+
"This suggestion is anchored to deleted lines, which are not in the working file."
|
|
3173
|
+
);
|
|
3174
|
+
}
|
|
3175
|
+
if (lineRange.side !== "new") {
|
|
3176
|
+
return refuse(filePath, "invalid-anchor", "The anchor does not name a side of the diff.");
|
|
3177
|
+
}
|
|
3178
|
+
const anchor = validateLineRange(lineRange);
|
|
3179
|
+
if (!anchor.ok) {
|
|
3180
|
+
return refuse(
|
|
3181
|
+
filePath,
|
|
3182
|
+
"invalid-anchor",
|
|
3183
|
+
`The anchor is not a usable range: ${anchor.reason}.`
|
|
3184
|
+
);
|
|
3185
|
+
}
|
|
3186
|
+
const { start, end } = anchor.anchor;
|
|
3187
|
+
if (!path7.isAbsolute(destinationRoot)) {
|
|
3188
|
+
return refuse(
|
|
3189
|
+
filePath,
|
|
3190
|
+
"destination-not-absolute",
|
|
3191
|
+
"The destination directory must be an absolute path."
|
|
3192
|
+
);
|
|
3193
|
+
}
|
|
3194
|
+
const rel = relativeWithinRoot(filePath);
|
|
3195
|
+
if (rel === null) {
|
|
3196
|
+
return refuse(
|
|
3197
|
+
filePath,
|
|
3198
|
+
"path-escapes-destination",
|
|
3199
|
+
"The file path resolves outside the destination directory."
|
|
3200
|
+
);
|
|
3201
|
+
}
|
|
3202
|
+
if (isRepositoryControlPath(rel)) {
|
|
3203
|
+
return refuse(
|
|
3204
|
+
filePath,
|
|
3205
|
+
"control-file",
|
|
3206
|
+
"The path is repository metadata (.git), which is never part of a review."
|
|
3207
|
+
);
|
|
3208
|
+
}
|
|
3209
|
+
return { rel, start, end };
|
|
3210
|
+
}
|
|
3211
|
+
function limits(options) {
|
|
3212
|
+
const maxInputBytes = options.maxInputBytes ?? MAX_SOURCE_FILE_BYTES;
|
|
3213
|
+
const maxOutputBytes = options.maxOutputBytes ?? MAX_SOURCE_FILE_BYTES;
|
|
3214
|
+
for (const [name, value] of Object.entries({ maxInputBytes, maxOutputBytes })) {
|
|
3215
|
+
if (!Number.isSafeInteger(value) || value < 0 || value >= bufferConstants.MAX_LENGTH) {
|
|
3216
|
+
throw new RangeError(
|
|
3217
|
+
`${name} must be a nonnegative safe integer below ${bufferConstants.MAX_LENGTH}`
|
|
3218
|
+
);
|
|
3219
|
+
}
|
|
3220
|
+
}
|
|
3221
|
+
return { maxInputBytes, maxOutputBytes };
|
|
3222
|
+
}
|
|
3223
|
+
function applySuggestion(request, options = {}) {
|
|
3224
|
+
const checked = validateRequest(request);
|
|
3225
|
+
if ("status" in checked) return checked;
|
|
3226
|
+
const { rel, start, end } = checked;
|
|
3227
|
+
const { destinationRoot, filePath, suggestion } = request;
|
|
3228
|
+
const fs5 = options.fs ?? nodeFsLayer;
|
|
3229
|
+
const { maxInputBytes, maxOutputBytes } = limits(options);
|
|
3230
|
+
let realRoot;
|
|
3231
|
+
try {
|
|
3232
|
+
realRoot = fs5.realpathSync(path7.resolve(destinationRoot));
|
|
3233
|
+
} catch (error) {
|
|
3234
|
+
return refuse(
|
|
3235
|
+
filePath,
|
|
3236
|
+
"destination-missing",
|
|
3237
|
+
`The destination directory could not be resolved (${errnoOf(error) ?? "unknown"}).`
|
|
3238
|
+
);
|
|
3239
|
+
}
|
|
3240
|
+
const absolutePath = path7.join(realRoot, rel);
|
|
3241
|
+
const opened = openAndRead(realRoot, rel, filePath, fs5, maxInputBytes);
|
|
3242
|
+
if ("status" in opened) return opened;
|
|
3243
|
+
const { identity, buffer } = opened;
|
|
3244
|
+
const prepared = prepareSuggestionContent(buffer, start, end, suggestion, maxOutputBytes);
|
|
3245
|
+
if ("reason" in prepared) return refuse(filePath, prepared.reason, prepared.detail);
|
|
3246
|
+
try {
|
|
3247
|
+
atomicReplace(absolutePath, prepared.bytes, {
|
|
3248
|
+
fs: fs5,
|
|
3249
|
+
preserveMode: true,
|
|
3250
|
+
preserveOwner: true,
|
|
3251
|
+
expectedIdentity: identity,
|
|
3252
|
+
expectUnmodified: true,
|
|
3253
|
+
randomName: options.randomName,
|
|
3254
|
+
beforeCommit: options.beforeCommit
|
|
3255
|
+
});
|
|
3256
|
+
} catch (error) {
|
|
3257
|
+
return refuseFsError(filePath, error, "write-failed");
|
|
3258
|
+
}
|
|
3259
|
+
return { status: "applied", filePath, absolutePath, replacedLines: prepared.replacedLines };
|
|
3260
|
+
}
|
|
3261
|
+
async function applySuggestionAsync(request, options = {}) {
|
|
3262
|
+
options = { ...options };
|
|
3263
|
+
options.signal?.throwIfAborted();
|
|
3264
|
+
request = {
|
|
3265
|
+
...request,
|
|
3266
|
+
lineRange: request.lineRange && { ...request.lineRange },
|
|
3267
|
+
suggestion: { ...request.suggestion }
|
|
3268
|
+
};
|
|
3269
|
+
const checked = validateRequest(request);
|
|
3270
|
+
if ("status" in checked) return checked;
|
|
3271
|
+
const { rel, start, end } = checked;
|
|
3272
|
+
const { destinationRoot, filePath, suggestion } = request;
|
|
3273
|
+
const { maxInputBytes, maxOutputBytes } = limits(options);
|
|
3274
|
+
const layer = options.fs ?? nodeAsyncFsLayer;
|
|
3275
|
+
let realRoot;
|
|
3276
|
+
try {
|
|
3277
|
+
realRoot = await layer.realpath(path7.resolve(destinationRoot));
|
|
3278
|
+
options.signal?.throwIfAborted();
|
|
3279
|
+
} catch (error) {
|
|
3280
|
+
options.signal?.throwIfAborted();
|
|
3281
|
+
return refuse(
|
|
3282
|
+
filePath,
|
|
3283
|
+
"destination-missing",
|
|
3284
|
+
`The destination directory could not be resolved (${errnoOf(error) ?? "unknown"}).`
|
|
3285
|
+
);
|
|
3286
|
+
}
|
|
3287
|
+
const absolutePath = path7.join(realRoot, rel);
|
|
3288
|
+
try {
|
|
3289
|
+
options.validateDestination?.(realRoot);
|
|
3290
|
+
} catch (error) {
|
|
3291
|
+
options.signal?.throwIfAborted();
|
|
3292
|
+
return refuseFsError(filePath, error, "write-failed");
|
|
3293
|
+
}
|
|
3294
|
+
let opened;
|
|
3295
|
+
try {
|
|
3296
|
+
opened = await openContainedFileAsync(realRoot, rel, layer, options.signal);
|
|
3297
|
+
} catch (error) {
|
|
3298
|
+
options.signal?.throwIfAborted();
|
|
3299
|
+
return refuseFsError(filePath, error, "file-unreadable");
|
|
3300
|
+
}
|
|
3301
|
+
const { handle, stats } = opened;
|
|
3302
|
+
let buffer;
|
|
3303
|
+
try {
|
|
3304
|
+
if (stats.nlink > 1)
|
|
3305
|
+
return refuse(
|
|
3306
|
+
filePath,
|
|
3307
|
+
"unsafe-target",
|
|
3308
|
+
`The file has ${stats.nlink} hard links, and replacing it would silently detach the others.`
|
|
3309
|
+
);
|
|
3310
|
+
const chunks = boundedChunks(absolutePath, stats.size, maxInputBytes);
|
|
3311
|
+
let step = chunks.next();
|
|
3312
|
+
while (!step.done) {
|
|
3313
|
+
options.signal?.throwIfAborted();
|
|
3314
|
+
const { buffer: buffer2, offset, length } = step.value;
|
|
3315
|
+
const { bytesRead } = await handle.read(buffer2, offset, length, null);
|
|
3316
|
+
options.signal?.throwIfAborted();
|
|
3317
|
+
step = chunks.next(bytesRead);
|
|
3318
|
+
}
|
|
3319
|
+
buffer = step.value;
|
|
3320
|
+
} catch (error) {
|
|
3321
|
+
options.signal?.throwIfAborted();
|
|
3322
|
+
return refuseFsError(filePath, error, "file-unreadable");
|
|
3323
|
+
} finally {
|
|
3324
|
+
try {
|
|
3325
|
+
await handle.close();
|
|
3326
|
+
} catch {
|
|
3327
|
+
}
|
|
3328
|
+
options.signal?.throwIfAborted();
|
|
3329
|
+
}
|
|
3330
|
+
options.signal?.throwIfAborted();
|
|
3331
|
+
const prepared = prepareSuggestionContent(buffer, start, end, suggestion, maxOutputBytes);
|
|
3332
|
+
if ("reason" in prepared) return refuse(filePath, prepared.reason, prepared.detail);
|
|
3333
|
+
try {
|
|
3334
|
+
options.validateDestination?.(realRoot);
|
|
3335
|
+
await atomicReplaceAsync(absolutePath, prepared.bytes, {
|
|
3336
|
+
fs: layer,
|
|
3337
|
+
preserveMode: true,
|
|
3338
|
+
preserveOwner: true,
|
|
3339
|
+
expectedIdentity: snapshotIdentity(stats),
|
|
3340
|
+
expectUnmodified: true,
|
|
3341
|
+
randomName: options.randomName,
|
|
3342
|
+
signal: options.signal,
|
|
3343
|
+
beforeCommit: options.beforeCommit
|
|
3344
|
+
});
|
|
3345
|
+
} catch (error) {
|
|
3346
|
+
options.signal?.throwIfAborted();
|
|
3347
|
+
return refuseFsError(filePath, error, "write-failed");
|
|
3348
|
+
}
|
|
3349
|
+
return { status: "applied", filePath, absolutePath, replacedLines: prepared.replacedLines };
|
|
3350
|
+
}
|
|
3351
|
+
|
|
3352
|
+
// src/review-suggestions.ts
|
|
3353
|
+
import * as fs4 from "fs";
|
|
3354
|
+
import path8 from "path";
|
|
3355
|
+
var nodeApplyDestinationInspection = {
|
|
3356
|
+
realpath: (target) => fs4.realpathSync(target),
|
|
3357
|
+
isDirectory: (target) => fs4.statSync(target).isDirectory()
|
|
3358
|
+
};
|
|
3359
|
+
function isTemporaryCloneSession(session) {
|
|
3360
|
+
return session.diffData?.remote?.temporaryClone === true;
|
|
3361
|
+
}
|
|
3362
|
+
function canonicalize(target, inspection) {
|
|
3363
|
+
try {
|
|
3364
|
+
return inspection.realpath(target);
|
|
3365
|
+
} catch {
|
|
3366
|
+
return path8.resolve(target);
|
|
3367
|
+
}
|
|
3368
|
+
}
|
|
3369
|
+
function isWithin(root, candidate, inspection) {
|
|
3370
|
+
const relative3 = path8.relative(
|
|
3371
|
+
canonicalize(root, inspection),
|
|
3372
|
+
canonicalize(candidate, inspection)
|
|
3373
|
+
);
|
|
3374
|
+
const escapes = relative3 === ".." || relative3.startsWith(`..${path8.sep}`);
|
|
3375
|
+
return relative3 === "" || !escapes && !path8.isAbsolute(relative3);
|
|
3376
|
+
}
|
|
3377
|
+
function resolveApplyDestination(session) {
|
|
3378
|
+
if (isTemporaryCloneSession(session)) {
|
|
3379
|
+
return session.applyDestinationRoot;
|
|
3380
|
+
}
|
|
3381
|
+
return resolveSourceBaseDir(session);
|
|
3382
|
+
}
|
|
3383
|
+
function setApplyDestination(session, directoryPath, options = {}) {
|
|
3384
|
+
const inspection = options.destinationInspection ?? nodeApplyDestinationInspection;
|
|
3385
|
+
if (!path8.isAbsolute(directoryPath)) {
|
|
3386
|
+
return {
|
|
3387
|
+
status: "rejected",
|
|
3388
|
+
reason: "destination-not-absolute",
|
|
3389
|
+
detail: "Pick a destination by its full path."
|
|
3390
|
+
};
|
|
3391
|
+
}
|
|
3392
|
+
let isDirectory = false;
|
|
3393
|
+
try {
|
|
3394
|
+
isDirectory = inspection.isDirectory(directoryPath);
|
|
3395
|
+
} catch {
|
|
3396
|
+
isDirectory = false;
|
|
3397
|
+
}
|
|
3398
|
+
if (!isDirectory) {
|
|
3399
|
+
return {
|
|
3400
|
+
status: "rejected",
|
|
3401
|
+
reason: "destination-not-a-directory",
|
|
3402
|
+
detail: "That destination is not a directory that exists."
|
|
3403
|
+
};
|
|
3404
|
+
}
|
|
3405
|
+
const clonePath = isTemporaryCloneSession(session) ? resolveSourceBaseDir(session) : null;
|
|
3406
|
+
if (clonePath && isWithin(clonePath, directoryPath, inspection)) {
|
|
3407
|
+
return {
|
|
3408
|
+
status: "rejected",
|
|
3409
|
+
reason: "destination-inside-temporary-clone",
|
|
3410
|
+
detail: "That directory is inside the temporary clone, which is deleted when the review ends."
|
|
3411
|
+
};
|
|
3412
|
+
}
|
|
3413
|
+
session.applyDestinationRoot = canonicalize(directoryPath, inspection);
|
|
3414
|
+
isolatedReporter(options.reportDiagnostic)(`[suggestion:apply] destination set for this session`);
|
|
3415
|
+
return { status: "chosen", destinationRoot: session.applyDestinationRoot };
|
|
3416
|
+
}
|
|
3417
|
+
function prepareSessionApply(session, request, reportDiagnostic) {
|
|
3418
|
+
const destinationRoot = resolveApplyDestination(session);
|
|
3419
|
+
const identity = session.sourceIdentity;
|
|
3420
|
+
if (!destinationRoot || identity === null) {
|
|
3421
|
+
const temporary = isTemporaryCloneSession(session);
|
|
3422
|
+
return {
|
|
3423
|
+
status: "refused",
|
|
3424
|
+
filePath: request.filePath,
|
|
3425
|
+
reason: temporary ? "destination-required" : "no-destination",
|
|
3426
|
+
detail: temporary ? "This pull request was cloned into a temporary directory that is deleted when the review ends. Choose a destination directory to apply into." : "This review has no working directory to write into."
|
|
3427
|
+
};
|
|
3428
|
+
}
|
|
3429
|
+
if (!session.reviewedPaths.has(request.filePath)) {
|
|
3430
|
+
reportDiagnostic(`[suggestion:apply] ${request.filePath}: refused (not-reviewed)`);
|
|
3431
|
+
return {
|
|
3432
|
+
status: "refused",
|
|
3433
|
+
filePath: request.filePath,
|
|
3434
|
+
reason: "not-reviewed",
|
|
3435
|
+
detail: "This file is not part of the reviewed diff, so nothing was written."
|
|
3436
|
+
};
|
|
3437
|
+
}
|
|
3438
|
+
return {
|
|
3439
|
+
engineRequest: {
|
|
3440
|
+
destinationRoot,
|
|
3441
|
+
filePath: rootRelativeReviewedPath(identity, request.filePath),
|
|
3442
|
+
lineRange: request.lineRange,
|
|
3443
|
+
suggestion: request.suggestion
|
|
3444
|
+
}
|
|
3445
|
+
};
|
|
3446
|
+
}
|
|
3447
|
+
function sessionApplyChecks(session, request, engineRequest, inspection) {
|
|
3448
|
+
const identity = session.sourceIdentity;
|
|
3449
|
+
const paths = session.reviewedPaths;
|
|
3450
|
+
const identityStamp2 = JSON.stringify(identity);
|
|
3451
|
+
const fileSource = JSON.stringify(identity?.fileSources?.get(request.filePath));
|
|
3452
|
+
const chosen = session.applyDestinationRoot;
|
|
3453
|
+
const temporary = isTemporaryCloneSession(session);
|
|
3454
|
+
const validateDestination = (physicalRoot) => {
|
|
3455
|
+
const destinationRoot = engineRequest.destinationRoot;
|
|
3456
|
+
if (physicalRoot !== path8.resolve(destinationRoot) || canonicalize(destinationRoot, inspection) !== physicalRoot || temporary && identity && isWithin(identity.sourceRoot, physicalRoot, inspection)) {
|
|
3457
|
+
throw new SafeFsError(
|
|
3458
|
+
"identity-changed",
|
|
3459
|
+
request.filePath,
|
|
3460
|
+
"The Apply destination no longer belongs to this review."
|
|
3461
|
+
);
|
|
3462
|
+
}
|
|
3463
|
+
};
|
|
3464
|
+
return {
|
|
3465
|
+
validateDestination,
|
|
3466
|
+
beforeCommit() {
|
|
3467
|
+
validateDestination(engineRequest.destinationRoot);
|
|
3468
|
+
if (session.sourceIdentity !== identity || session.reviewedPaths !== paths || !session.reviewedPaths.has(request.filePath) || JSON.stringify(session.sourceIdentity) !== identityStamp2 || JSON.stringify(session.sourceIdentity?.fileSources?.get(request.filePath)) !== fileSource || session.applyDestinationRoot !== chosen || isTemporaryCloneSession(session) !== temporary || resolveApplyDestination(session) !== engineRequest.destinationRoot) {
|
|
3469
|
+
throw new SafeFsError(
|
|
3470
|
+
"identity-changed",
|
|
3471
|
+
request.filePath,
|
|
3472
|
+
"The review or its Apply destination changed before the write could commit."
|
|
3473
|
+
);
|
|
3474
|
+
}
|
|
3475
|
+
}
|
|
3476
|
+
};
|
|
3477
|
+
}
|
|
3478
|
+
function applySuggestionForSession(session, request, effects = {}) {
|
|
3479
|
+
request = {
|
|
3480
|
+
...request,
|
|
3481
|
+
lineRange: request.lineRange && { ...request.lineRange },
|
|
3482
|
+
suggestion: { ...request.suggestion }
|
|
3483
|
+
};
|
|
3484
|
+
const reportDiagnostic = isolatedReporter(effects.reportDiagnostic);
|
|
3485
|
+
const prepared = prepareSessionApply(session, request, reportDiagnostic);
|
|
3486
|
+
if ("status" in prepared) return prepared;
|
|
3487
|
+
const layer = effects.fs ?? nodeFsLayer;
|
|
3488
|
+
const inspection = effects.destinationInspection ?? {
|
|
3489
|
+
realpath: (target) => layer.realpathSync(target),
|
|
3490
|
+
isDirectory: (target) => layer.lstatSync(target).isDirectory()
|
|
3491
|
+
};
|
|
3492
|
+
const checks = sessionApplyChecks(session, request, prepared.engineRequest, inspection);
|
|
3493
|
+
let destinationChanged = false;
|
|
3494
|
+
const guardedFs = new Proxy({}, {
|
|
3495
|
+
get(_target, member) {
|
|
3496
|
+
const target = layer;
|
|
3497
|
+
if (member === "realpathSync")
|
|
3498
|
+
return (value2) => {
|
|
3499
|
+
const physical = target.realpathSync(value2);
|
|
3500
|
+
if (value2 === path8.resolve(prepared.engineRequest.destinationRoot)) {
|
|
3501
|
+
try {
|
|
3502
|
+
checks.validateDestination(physical);
|
|
3503
|
+
} catch (error) {
|
|
3504
|
+
destinationChanged = true;
|
|
3505
|
+
throw error;
|
|
3506
|
+
}
|
|
3507
|
+
}
|
|
3508
|
+
return physical;
|
|
3509
|
+
};
|
|
3510
|
+
const value = Reflect.get(target, member, target);
|
|
3511
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
3512
|
+
}
|
|
3513
|
+
});
|
|
3514
|
+
let result = applySuggestion(prepared.engineRequest, {
|
|
3515
|
+
fs: guardedFs,
|
|
3516
|
+
beforeCommit: checks.beforeCommit
|
|
3517
|
+
});
|
|
3518
|
+
if (destinationChanged && result.status === "refused") {
|
|
3519
|
+
result = {
|
|
3520
|
+
status: "refused",
|
|
3521
|
+
filePath: request.filePath,
|
|
3522
|
+
reason: "file-changed",
|
|
3523
|
+
detail: "The Apply destination no longer belongs to this review."
|
|
3524
|
+
};
|
|
3525
|
+
}
|
|
3526
|
+
return projectApplyResult(request.filePath, result, reportDiagnostic);
|
|
3527
|
+
}
|
|
3528
|
+
async function applySuggestionForSessionAsync(session, request, options = {}, effects = {}) {
|
|
3529
|
+
options.signal?.throwIfAborted();
|
|
3530
|
+
request = {
|
|
3531
|
+
...request,
|
|
3532
|
+
lineRange: request.lineRange && { ...request.lineRange },
|
|
3533
|
+
suggestion: { ...request.suggestion }
|
|
3534
|
+
};
|
|
3535
|
+
const reportDiagnostic = isolatedReporter(effects.reportDiagnostic);
|
|
3536
|
+
const inspection = effects.destinationInspection ?? nodeApplyDestinationInspection;
|
|
3537
|
+
const prepared = prepareSessionApply(session, request, reportDiagnostic);
|
|
3538
|
+
options.signal?.throwIfAborted();
|
|
3539
|
+
if ("status" in prepared) return prepared;
|
|
3540
|
+
const checks = sessionApplyChecks(session, request, prepared.engineRequest, inspection);
|
|
3541
|
+
const result = await applySuggestionAsync(prepared.engineRequest, { ...options, ...checks });
|
|
3542
|
+
const outcome = projectApplyResult(request.filePath, result, reportDiagnostic);
|
|
3543
|
+
if (result.status !== "applied") options.signal?.throwIfAborted();
|
|
3544
|
+
return outcome;
|
|
3545
|
+
}
|
|
3546
|
+
function projectApplyResult(filePath, result, reportDiagnostic) {
|
|
3547
|
+
reportDiagnostic(
|
|
3548
|
+
`[suggestion:apply] ${filePath}: ${result.status === "applied" ? "applied" : `refused (${result.reason})`}`
|
|
3549
|
+
);
|
|
3550
|
+
if (result.status === "applied") {
|
|
3551
|
+
return {
|
|
3552
|
+
status: "applied",
|
|
3553
|
+
filePath,
|
|
3554
|
+
replacedLines: result.replacedLines
|
|
3555
|
+
};
|
|
3556
|
+
}
|
|
3557
|
+
return {
|
|
3558
|
+
status: "refused",
|
|
3559
|
+
filePath,
|
|
3560
|
+
reason: result.reason,
|
|
3561
|
+
detail: result.detail
|
|
3562
|
+
};
|
|
3563
|
+
}
|
|
3564
|
+
|
|
3565
|
+
export {
|
|
3566
|
+
FORGE_DEFINITIONS,
|
|
3567
|
+
CommandCancelledError,
|
|
3568
|
+
isCommandCancelled,
|
|
3569
|
+
ForgeCliUnavailableError,
|
|
3570
|
+
parseForgeUrl,
|
|
3571
|
+
checkLoadingCancelled,
|
|
3572
|
+
loadingCheckpoint,
|
|
3573
|
+
readFileWithinBudget,
|
|
3574
|
+
readFileWithinBudgetSync,
|
|
3575
|
+
SafeFsError,
|
|
3576
|
+
snapshotIdentity,
|
|
3577
|
+
sameFile,
|
|
3578
|
+
classifyFsError,
|
|
3579
|
+
errnoOf,
|
|
3580
|
+
toSafeFsError,
|
|
3581
|
+
guarded,
|
|
3582
|
+
replacementIdentity,
|
|
3583
|
+
nodeReadFsLayer,
|
|
3584
|
+
boundedReadFsFromSync,
|
|
3585
|
+
assertNoSymlinkAncestorsAsync,
|
|
3586
|
+
asyncFsFromSync,
|
|
3587
|
+
nodeAsyncFsLayer,
|
|
3588
|
+
readContainedFileAsync,
|
|
3589
|
+
readContainedFileBounded,
|
|
3590
|
+
openContainedFileAsync,
|
|
3591
|
+
writeExclusiveNoFollowAsync,
|
|
3592
|
+
atomicReplaceAsync,
|
|
3593
|
+
nodeFsLayer,
|
|
3594
|
+
lstatOrNull2 as lstatOrNull,
|
|
3595
|
+
assertNoSymlinkAncestors,
|
|
3596
|
+
openContainedFile,
|
|
3597
|
+
readContainedFile,
|
|
3598
|
+
writeExclusiveNoFollow,
|
|
3599
|
+
atomicReplace,
|
|
3600
|
+
inspectReplaceTarget,
|
|
3601
|
+
defaultRandomName,
|
|
3602
|
+
nodeScanFsLayer,
|
|
3603
|
+
nodePublicationFileSystem,
|
|
3604
|
+
resolvePublicationFileSystem,
|
|
3605
|
+
stderrReporter,
|
|
3606
|
+
isolatedReporter,
|
|
3607
|
+
nodeTemporaryCloneStorage,
|
|
3608
|
+
repositoryEnvironment,
|
|
3609
|
+
runBufferedCommand,
|
|
3610
|
+
defaultGitRunner,
|
|
3611
|
+
RELOAD_REVIEW,
|
|
3612
|
+
sourceStamp,
|
|
3613
|
+
identityStamp,
|
|
3614
|
+
loadedSnapshot,
|
|
3615
|
+
recordLoadedSnapshot,
|
|
3616
|
+
createLoadedReview,
|
|
3617
|
+
restrictLoadedReview,
|
|
3618
|
+
loadedReviewState,
|
|
3619
|
+
loadedReviewIdentity,
|
|
3620
|
+
loadedReviewPaths,
|
|
3621
|
+
sourceCapture,
|
|
3622
|
+
admitSyntheticSnapshot,
|
|
3623
|
+
captureSourceReads,
|
|
3624
|
+
generateSyntheticDiffs,
|
|
3625
|
+
generateSyntheticDiffsAsync,
|
|
3626
|
+
loadSyntheticFiles,
|
|
3627
|
+
loadSyntheticFilesAsync,
|
|
3628
|
+
consumesNextArgument,
|
|
3629
|
+
parseGitDiffArgs,
|
|
3630
|
+
describeDiffPathRelativity,
|
|
3631
|
+
singleFileRediffArgs,
|
|
3632
|
+
findWriteCapableGitDiffOptions,
|
|
3633
|
+
findUnsupportedGitDiffOptions,
|
|
3634
|
+
classifyGitDiffArgs,
|
|
3635
|
+
tokenizeGitDiffArgs,
|
|
3636
|
+
gitDiffArgsSyntaxError,
|
|
3637
|
+
formatGitDiffArgs,
|
|
3638
|
+
normalizeGitDiffArgs,
|
|
3639
|
+
GitCommandError,
|
|
3640
|
+
executeGit,
|
|
3641
|
+
stripTrailingNewline,
|
|
3642
|
+
getRepoRootAsync,
|
|
3643
|
+
PARSER_COMPATIBLE_GIT_CONFIG,
|
|
3644
|
+
PARSER_COMPATIBLE_DIFF_FLAGS,
|
|
3645
|
+
withParserCompatibleDiffArgs,
|
|
3646
|
+
runGitDiffAsync,
|
|
3647
|
+
listUntrackedFilesAsync,
|
|
3648
|
+
getUntrackedFilesAsync,
|
|
3649
|
+
isOutputLimitError,
|
|
3650
|
+
generateUntrackedDiffs,
|
|
3651
|
+
DEFAULT_GIT_COMMAND_TIMEOUT_MS,
|
|
3652
|
+
detectExistingClone,
|
|
3653
|
+
materialize,
|
|
3654
|
+
resolveRemoteDefaultBranch,
|
|
3655
|
+
createReviewSession,
|
|
3656
|
+
commitDiffData,
|
|
3657
|
+
commitLoadedReview,
|
|
3658
|
+
locateReviewedFile,
|
|
3659
|
+
preparePayload,
|
|
3660
|
+
getDiffLoad,
|
|
3661
|
+
resolveSourceBaseDir,
|
|
3662
|
+
getFileHunks,
|
|
3663
|
+
getConfigLoad,
|
|
3664
|
+
submitReviewState,
|
|
3665
|
+
takeReviewState,
|
|
3666
|
+
getResumeLoad,
|
|
3667
|
+
describeGitDiffSides,
|
|
3668
|
+
canonicalSourcePath,
|
|
3669
|
+
resolveReviewedPathPrefix,
|
|
3670
|
+
rootRelativeReviewedPath,
|
|
3671
|
+
resolveGitSourceIdentity,
|
|
3672
|
+
resolveLocalSourceIdentity,
|
|
3673
|
+
resolveLocalSourceIdentityAsync,
|
|
3674
|
+
readSuggestionBoundedSync,
|
|
3675
|
+
isRepositoryControlPath,
|
|
3676
|
+
applySuggestion,
|
|
3677
|
+
applySuggestionAsync,
|
|
3678
|
+
nodeApplyDestinationInspection,
|
|
3679
|
+
resolveApplyDestination,
|
|
3680
|
+
setApplyDestination,
|
|
3681
|
+
applySuggestionForSession,
|
|
3682
|
+
applySuggestionForSessionAsync
|
|
3683
|
+
};
|
|
3684
|
+
//# sourceMappingURL=chunk-MOYO4RIX.js.map
|