@leolastforce/chalice-hashline-edit 0.0.0-stage → 4.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +153 -2
- package/index.ts +282 -0
- package/package.json +79 -4
- package/prompts/find-guidelines.md +2 -0
- package/prompts/find-snippet.md +1 -0
- package/prompts/find.md +1 -0
- package/prompts/grep-guidelines.md +2 -0
- package/prompts/grep-snippet.md +1 -0
- package/prompts/grep.md +1 -0
- package/prompts/insert-guidelines.md +1 -0
- package/prompts/insert-snippet.md +1 -0
- package/prompts/insert.md +1 -0
- package/prompts/read-guidelines.md +2 -0
- package/prompts/read-snippet.md +1 -0
- package/prompts/read.md +1 -0
- package/prompts/replace-guidelines.md +4 -0
- package/prompts/replace-snippet.md +1 -0
- package/prompts/replace.md +1 -0
- package/prompts/undo-last-change-guidelines.md +1 -0
- package/prompts/undo-last-change-snippet.md +1 -0
- package/prompts/undo-last-change.md +1 -0
- package/src/anchor-registry.ts +977 -0
- package/src/auto-read-all-state.ts +27 -0
- package/src/auto-read-all.ts +477 -0
- package/src/batch.ts +767 -0
- package/src/commit.ts +137 -0
- package/src/config-ui.ts +212 -0
- package/src/config.ts +235 -0
- package/src/constants.ts +26 -0
- package/src/edit-common.ts +206 -0
- package/src/file-kind.ts +191 -0
- package/src/file-reader.ts +135 -0
- package/src/find.ts +244 -0
- package/src/fs-write.ts +231 -0
- package/src/glob.ts +186 -0
- package/src/grep.ts +690 -0
- package/src/hash-store/cache.ts +18 -0
- package/src/hash-store/retry.ts +44 -0
- package/src/hash-store/validation.ts +62 -0
- package/src/hash-store.ts +609 -0
- package/src/hashline/alphabet.ts +21 -0
- package/src/hashline/anchor-table.json +1 -0
- package/src/hashline/apply.ts +297 -0
- package/src/hashline/hash.ts +119 -0
- package/src/hashline/hasher.ts +47 -0
- package/src/hashline/index.ts +50 -0
- package/src/hashline/parse.ts +84 -0
- package/src/hashline/resolve.ts +373 -0
- package/src/insert.ts +258 -0
- package/src/normalize.ts +27 -0
- package/src/paths.ts +56 -0
- package/src/payload-contract.ts +133 -0
- package/src/prompts.ts +13 -0
- package/src/read.ts +286 -0
- package/src/replace-diff.ts +610 -0
- package/src/replace-render.ts +390 -0
- package/src/replace-response.ts +166 -0
- package/src/replace-undo.ts +270 -0
- package/src/replace.ts +318 -0
- package/src/served.ts +36 -0
- package/src/utils.ts +387 -0
- package/src/validation.ts +45 -0
- package/src/write-hook.ts +53 -0
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { resolveInCwd } from "./fs-write";
|
|
3
|
+
import { abortIf, makePrepareArguments } from "./utils";
|
|
4
|
+
import { ownerOf } from "./anchor-registry";
|
|
5
|
+
import { parseHashRef, stripAnchorRow } from "./hashline";
|
|
6
|
+
import { readConfig } from "./config";
|
|
7
|
+
import { makeRenderCall, renderEditResult, type RPreview, type FgT } from "./replace-render";
|
|
8
|
+
import type { ReplaceDetails } from "./replace";
|
|
9
|
+
export const editPrepare = makePrepareArguments();
|
|
10
|
+
|
|
11
|
+
export interface EditToolFlags {
|
|
12
|
+
requirePath: boolean;
|
|
13
|
+
strictInput: boolean;
|
|
14
|
+
autoRead: boolean;
|
|
15
|
+
autoReadAllActive: boolean;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const DEFAULT_EDIT_FLAGS: EditToolFlags = {
|
|
19
|
+
requirePath: false,
|
|
20
|
+
strictInput: false,
|
|
21
|
+
autoRead: true,
|
|
22
|
+
autoReadAllActive: false
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export async function currentEditFlags(): Promise<EditToolFlags> {
|
|
26
|
+
const config = await readConfig();
|
|
27
|
+
return {
|
|
28
|
+
requirePath: config.requirePath === true,
|
|
29
|
+
strictInput: config.strictInput === true,
|
|
30
|
+
autoRead: config.autoRead !== false,
|
|
31
|
+
autoReadAllActive: (config.autoReadAll ?? "off") !== "off"
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function withReplacePrompts(base: { description: string; snippet: string; guidelines: string[] }, flags: EditToolFlags): { description: string; snippet: string; guidelines: string[] } {
|
|
36
|
+
let description = base.description;
|
|
37
|
+
const snippetParts = [base.snippet];
|
|
38
|
+
let guidelines = [...base.guidelines];
|
|
39
|
+
if (!flags.autoRead) {
|
|
40
|
+
description = description.replace(" Anchor follow-up edits on the `+anchor│` and ` anchor│` rows of the post-edit diff instead of re-reading.", "");
|
|
41
|
+
guidelines = guidelines.filter((guideline) => !guideline.includes("post-edit diff"));
|
|
42
|
+
description = description.replace("and the last call shows the combined diff,", "and the last call shows the combined result,");
|
|
43
|
+
}
|
|
44
|
+
const descriptionParts = [description];
|
|
45
|
+
if (flags.requirePath) {
|
|
46
|
+
descriptionParts.push("Also give `path` matching the file the anchors were served for; it is required and must match anchor ownership.");
|
|
47
|
+
snippetParts.push("; include `path` (required)");
|
|
48
|
+
guidelines.push("`replace`: include `path` matching the file the anchors were served for; it is required.");
|
|
49
|
+
} else {
|
|
50
|
+
descriptionParts.push("Path resolution is anchor-only; do not pass `path`.");
|
|
51
|
+
guidelines.push("`replace`: path resolution is anchor-only; don't pass `path`.");
|
|
52
|
+
}
|
|
53
|
+
if (flags.strictInput) {
|
|
54
|
+
descriptionParts.push("Strict-input mode is on: auto-fixable slips are rejected instead of fixed with warnings.");
|
|
55
|
+
guidelines.push("`replace`: strict-input is on: auto-fixable slips are rejected instead of fixed.");
|
|
56
|
+
}
|
|
57
|
+
return { description: descriptionParts.join(" "), snippet: snippetParts.join(""), guidelines };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function withReadPrompts(base: { description: string; snippet: string; guidelines: string[] }, flags: EditToolFlags): { description: string; snippet: string; guidelines: string[] } {
|
|
61
|
+
if (flags.autoReadAllActive) {
|
|
62
|
+
const rewritten = base.guidelines
|
|
63
|
+
.filter((guideline) => !guideline.includes("call again after an edit"))
|
|
64
|
+
return { description: base.description, snippet: base.snippet, guidelines: [...rewritten] };
|
|
65
|
+
}
|
|
66
|
+
const withoutAutoReadAll = base.guidelines.filter((guideline) => !guideline.includes("E_AUTO_READ_ALL"))
|
|
67
|
+
if (flags.autoRead) return { description: base.description, snippet: base.snippet, guidelines: [...withoutAutoReadAll] };
|
|
68
|
+
const guidelines = [...withoutAutoReadAll];
|
|
69
|
+
const mapped = guidelines.map((guideline) => guideline.startsWith("`read`: call again after an edit") ? "`read`: call again after an edit when you need anchors you lack." : guideline);
|
|
70
|
+
return { description: base.description, snippet: base.snippet, guidelines: mapped };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function withInsertPrompts(base: { description: string; snippet: string; guidelines: string[] }, flags: EditToolFlags): { description: string; snippet: string; guidelines: string[] } {
|
|
74
|
+
const baseDescription = flags.autoRead ? base.description : base.description.replace("and the last call shows the combined diff,", "and the last call shows the combined result,");
|
|
75
|
+
const descriptionParts = [baseDescription];
|
|
76
|
+
const snippetParts = [base.snippet];
|
|
77
|
+
const guidelines = [...base.guidelines];
|
|
78
|
+
if (flags.requirePath) {
|
|
79
|
+
descriptionParts.push("Also give `path` matching the file the anchor was served for; it is required and must match anchor ownership.");
|
|
80
|
+
snippetParts.push("; include `path` (required)");
|
|
81
|
+
guidelines.push("`insert`: include `path` matching the file the anchor was served for; it is required.");
|
|
82
|
+
} else {
|
|
83
|
+
descriptionParts.push("Path resolution is anchor-only; do not pass `path`.");
|
|
84
|
+
guidelines.push("`insert`: path resolution is anchor-only; don't pass `path`.");
|
|
85
|
+
}
|
|
86
|
+
if (flags.strictInput) {
|
|
87
|
+
descriptionParts.push("Strict-input mode is on: auto-fixable slips are rejected instead of fixed with warnings.");
|
|
88
|
+
guidelines.push("`insert`: strict-input is on: auto-fixable slips are rejected instead of fixed.");
|
|
89
|
+
}
|
|
90
|
+
return { description: descriptionParts.join(" "), snippet: snippetParts.join(""), guidelines };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function withUndoPrompts(base: { description: string; snippet: string; guidelines: string[] }, flags: EditToolFlags): { description: string; snippet: string; guidelines: string[] } {
|
|
94
|
+
if (flags.autoRead) return { description: base.description, snippet: base.snippet, guidelines: [...base.guidelines] };
|
|
95
|
+
const guidelines = base.guidelines.map((guideline) => guideline.includes("bad diff") ? "`undo_last_change`: only the last `replace`/`insert` per file is undoable; a `write` clears it, so undo right after a bad edit — review what you're restoring." : guideline);
|
|
96
|
+
return { description: base.description, snippet: base.snippet, guidelines };
|
|
97
|
+
}
|
|
98
|
+
export function resolveEditTarget(removeFrom: string, removeTo?: string): string {
|
|
99
|
+
const refs = [removeFrom, removeTo].filter((value): value is string => typeof value === "string");
|
|
100
|
+
const owners = refs.map((ref) => ownerOf(parseHashRef(stripAnchorRow(ref.trim(), "anchor entry")).hash));
|
|
101
|
+
const missing = owners.findIndex((owner) => !owner);
|
|
102
|
+
if (missing >= 0) {
|
|
103
|
+
throw new Error(
|
|
104
|
+
`[E_STALE_ANCHOR] "${refs[missing]!}" is not owned in this session. Call read() on the target file first.`,
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
const paths = new Set(owners.map((owner) => owner!.path));
|
|
108
|
+
if (paths.size > 1) {
|
|
109
|
+
throw new Error(
|
|
110
|
+
`[E_BAD_SHAPE] The anchors are owned by different files (${owners.map((owner) => owner!.path).join(", ")}); edit one file per call.`,
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
return owners[0]!.path;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function tryResolveEditTarget(removeFrom: string | undefined, removeTo?: string): string | undefined {
|
|
117
|
+
if (typeof removeFrom !== "string") return undefined;
|
|
118
|
+
try {
|
|
119
|
+
return resolveEditTarget(removeFrom, removeTo);
|
|
120
|
+
} catch {
|
|
121
|
+
return undefined;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export interface PathRequirementInput {
|
|
126
|
+
removeFrom?: string;
|
|
127
|
+
removeTo?: string;
|
|
128
|
+
anchor?: string;
|
|
129
|
+
providedPath?: unknown;
|
|
130
|
+
cwd: string;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export async function resolveEditTargetWithRequirement(input: PathRequirementInput): Promise<string> {
|
|
134
|
+
const { requirePath } = await readConfig();
|
|
135
|
+
if (!requirePath && input.providedPath !== undefined) {
|
|
136
|
+
throw new Error("[E_BAD_SHAPE] Edit request contains unknown or unsupported fields: path. Path resolution is anchor-only; retry without `path`.");
|
|
137
|
+
}
|
|
138
|
+
if (requirePath && (typeof input.providedPath !== "string" || input.providedPath.length === 0)) {
|
|
139
|
+
throw new Error('[E_BAD_SHAPE] Edit request requires a non-empty "path" string when require-path mode is on. Provide `path` matching the file the anchors were served for.');
|
|
140
|
+
}
|
|
141
|
+
const anchorTarget = typeof input.anchor === "string"
|
|
142
|
+
? resolveEditTarget(input.anchor)
|
|
143
|
+
: resolveEditTarget(input.removeFrom as string, input.removeTo);
|
|
144
|
+
if (requirePath) {
|
|
145
|
+
const { resolved } = await resolveInCwd(input.providedPath as string, input.cwd);
|
|
146
|
+
if (resolved !== anchorTarget) {
|
|
147
|
+
throw new Error(`[E_BAD_SHAPE] Provided "path" "${input.providedPath}" does not match anchor ownership "${anchorTarget}".`);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return anchorTarget;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export async function throwIfStrictInput(warnings: string[]): Promise<void> {
|
|
154
|
+
const fixes = warnings.filter((warning) => warning.startsWith("[W_"));
|
|
155
|
+
if (fixes.length === 0) return;
|
|
156
|
+
const { strictInput } = await readConfig();
|
|
157
|
+
if (strictInput === true) {
|
|
158
|
+
throw new Error(`[E_BAD_SHAPE] Strict-input mode rejects auto-fixable input:\n${fixes.join("\n")}`);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function editRenderCallWrapper(
|
|
163
|
+
preview: (args: unknown, cwd: string, signal?: AbortSignal) => Promise<RPreview>,
|
|
164
|
+
getInput?: (args: unknown) => { path?: string } | null,
|
|
165
|
+
toolName?: string,
|
|
166
|
+
) {
|
|
167
|
+
return makeRenderCall(preview, {
|
|
168
|
+
getInput,
|
|
169
|
+
toolName,
|
|
170
|
+
resolveTarget: (input) => {
|
|
171
|
+
if (typeof input.remove_from === "string") return tryResolveEditTarget(input.remove_from, input.remove_to);
|
|
172
|
+
if (typeof input.anchor === "string") return tryResolveEditTarget(input.anchor);
|
|
173
|
+
return undefined;
|
|
174
|
+
},
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export function editRenderResultWrapper(
|
|
179
|
+
result: { content?: Array<{ type: string; text?: string }>; details?: ReplaceDetails },
|
|
180
|
+
opts: { isPartial: boolean; expanded?: boolean } | boolean,
|
|
181
|
+
theme: FgT,
|
|
182
|
+
context: any,
|
|
183
|
+
) {
|
|
184
|
+
return renderEditResult(result, opts, theme, context);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export const editToolBase = {
|
|
188
|
+
prepareArguments: editPrepare,
|
|
189
|
+
executionMode: "sequential" as const,
|
|
190
|
+
renderShell: "default" as const,
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
export async function queuedEdit<T>(
|
|
194
|
+
path: string,
|
|
195
|
+
cwd: string,
|
|
196
|
+
signal: AbortSignal | undefined,
|
|
197
|
+
work: (absolute: string, resolved: string) => Promise<T>,
|
|
198
|
+
): Promise<T> {
|
|
199
|
+
abortIf(signal);
|
|
200
|
+
const { absolute, resolved } = await resolveInCwd(path, cwd);
|
|
201
|
+
return withFileMutationQueue(resolved, async () => {
|
|
202
|
+
abortIf(signal);
|
|
203
|
+
return work(absolute, resolved);
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
|
package/src/file-kind.ts
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { open as fsOpen, stat as fsStat } from "node:fs/promises";
|
|
2
|
+
import { fileTypeFromBuffer } from "file-type";
|
|
3
|
+
import { SNIFF_BYTES, MAX_BYTES } from "./constants";
|
|
4
|
+
import { assertLineLimit, lineLimitMoreThanMessage } from "./utils";
|
|
5
|
+
import type { FileIdentity } from "./fs-write";
|
|
6
|
+
|
|
7
|
+
const IMG_TYPES = new Set<string>([
|
|
8
|
+
"image/bmp",
|
|
9
|
+
"image/gif",
|
|
10
|
+
"image/jpeg",
|
|
11
|
+
"image/png",
|
|
12
|
+
"image/webp",
|
|
13
|
+
]);
|
|
14
|
+
|
|
15
|
+
const TEXT_TYPES = new Set<string>([
|
|
16
|
+
"application/rtf",
|
|
17
|
+
"application/xml",
|
|
18
|
+
"application/x-ms-regedit",
|
|
19
|
+
]);
|
|
20
|
+
|
|
21
|
+
function detectTextBom(sample: Uint8Array): string | undefined {
|
|
22
|
+
if (
|
|
23
|
+
sample.length >= 4 &&
|
|
24
|
+
sample[0] === 0xff &&
|
|
25
|
+
sample[1] === 0xfe &&
|
|
26
|
+
sample[2] === 0x00 &&
|
|
27
|
+
sample[3] === 0x00
|
|
28
|
+
) return "UTF-32LE";
|
|
29
|
+
if (
|
|
30
|
+
sample.length >= 4 &&
|
|
31
|
+
sample[0] === 0x00 &&
|
|
32
|
+
sample[1] === 0x00 &&
|
|
33
|
+
sample[2] === 0xfe &&
|
|
34
|
+
sample[3] === 0xff
|
|
35
|
+
) return "UTF-32BE";
|
|
36
|
+
if (sample.length >= 2 && sample[0] === 0xff && sample[1] === 0xfe) return "UTF-16LE";
|
|
37
|
+
if (sample.length >= 2 && sample[0] === 0xfe && sample[1] === 0xff) return "UTF-16BE";
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function isTextType(mimeType: string): boolean {
|
|
42
|
+
return mimeType.startsWith("text/") || TEXT_TYPES.has(mimeType);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function looksLikeText(sample: Uint8Array): boolean {
|
|
46
|
+
if (sample.includes(0)) return false;
|
|
47
|
+
try {
|
|
48
|
+
new TextDecoder("utf-8", { fatal: true }).decode(sample);
|
|
49
|
+
return true;
|
|
50
|
+
} catch {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export type LFile =
|
|
56
|
+
| { kind: "directory" }
|
|
57
|
+
| { kind: "image"; mimeType: string }
|
|
58
|
+
| { kind: "text"; text: string; identity?: FileIdentity; hadUtf8DecodeErrors?: true }
|
|
59
|
+
| { kind: "binary"; description: string }
|
|
60
|
+
| { kind: "too_large"; description: string };
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
export interface LoadFileOptions {
|
|
64
|
+
maxLines?: number;
|
|
65
|
+
displayPath?: string;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export async function loadFileKindAndText(
|
|
69
|
+
filePath: string,
|
|
70
|
+
options?: LoadFileOptions,
|
|
71
|
+
): Promise<LFile> {
|
|
72
|
+
const pathStat = await fsStat(filePath);
|
|
73
|
+
if (pathStat.isDirectory()) {
|
|
74
|
+
return { kind: "directory" };
|
|
75
|
+
}
|
|
76
|
+
if (!pathStat.isFile()) {
|
|
77
|
+
return {
|
|
78
|
+
kind: "binary",
|
|
79
|
+
description: "unsupported file type",
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
if (pathStat.size > MAX_BYTES) {
|
|
83
|
+
return {
|
|
84
|
+
kind: "too_large",
|
|
85
|
+
description: `exceeds the ${MAX_BYTES / (1024 * 1024)}MB size limit`,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const fileHandle = await fsOpen(filePath, "r");
|
|
90
|
+
try {
|
|
91
|
+
const openedStats = await fileHandle.stat();
|
|
92
|
+
const identity = { dev: openedStats.dev, ino: openedStats.ino };
|
|
93
|
+
const buffer = Buffer.alloc(SNIFF_BYTES);
|
|
94
|
+
const { bytesRead } = await fileHandle.read(
|
|
95
|
+
buffer,
|
|
96
|
+
0,
|
|
97
|
+
SNIFF_BYTES,
|
|
98
|
+
0,
|
|
99
|
+
);
|
|
100
|
+
if (bytesRead === 0) {
|
|
101
|
+
return { kind: "text", text: "", identity };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const sample = buffer.subarray(0, bytesRead);
|
|
105
|
+
const textBom = detectTextBom(sample);
|
|
106
|
+
if (textBom) {
|
|
107
|
+
return {
|
|
108
|
+
kind: "binary",
|
|
109
|
+
description: `${textBom} encoded text`
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
const detectedMimeType = (await fileTypeFromBuffer(sample))?.mime;
|
|
113
|
+
if (
|
|
114
|
+
detectedMimeType !== undefined &&
|
|
115
|
+
!isTextType(detectedMimeType) &&
|
|
116
|
+
!looksLikeText(sample)
|
|
117
|
+
) {
|
|
118
|
+
if (IMG_TYPES.has(detectedMimeType)) {
|
|
119
|
+
return { kind: "image", mimeType: detectedMimeType };
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
kind: "binary",
|
|
123
|
+
description: detectedMimeType,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
if (detectedMimeType === undefined && sample.includes(0)) {
|
|
127
|
+
return { kind: "binary", description: "contains NUL bytes" };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const decoder = new TextDecoder("utf-8", { fatal: false, ignoreBOM: true });
|
|
131
|
+
let hadUtf8DecodeErrors = false;
|
|
132
|
+
let containsNul = false;
|
|
133
|
+
let newlineCount = 0;
|
|
134
|
+
const parts: string[] = [];
|
|
135
|
+
|
|
136
|
+
function decodeChunk(chunk: Uint8Array, stream: boolean): string {
|
|
137
|
+
const decoded = decoder.decode(chunk, { stream });
|
|
138
|
+
if (!hadUtf8DecodeErrors && decoded.includes("\uFFFD")) {
|
|
139
|
+
hadUtf8DecodeErrors = true;
|
|
140
|
+
}
|
|
141
|
+
if (!containsNul && decoded.includes("\0")) {
|
|
142
|
+
containsNul = true;
|
|
143
|
+
}
|
|
144
|
+
if (options?.maxLines !== undefined) {
|
|
145
|
+
for (let i = 0; i < decoded.length; i++) {
|
|
146
|
+
if (decoded.charCodeAt(i) === 10) newlineCount++;
|
|
147
|
+
}
|
|
148
|
+
if (newlineCount > options.maxLines) throw new Error(lineLimitMoreThanMessage(options.displayPath ?? filePath, options.maxLines));
|
|
149
|
+
}
|
|
150
|
+
return decoded;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
parts.push(decodeChunk(sample, true));
|
|
154
|
+
|
|
155
|
+
let position = bytesRead;
|
|
156
|
+
while (true) {
|
|
157
|
+
const { bytesRead: chunkBytesRead } = await fileHandle.read(
|
|
158
|
+
buffer,
|
|
159
|
+
0,
|
|
160
|
+
SNIFF_BYTES,
|
|
161
|
+
position,
|
|
162
|
+
);
|
|
163
|
+
if (chunkBytesRead === 0) {
|
|
164
|
+
break;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const chunk = buffer.subarray(0, chunkBytesRead);
|
|
168
|
+
parts.push(decodeChunk(chunk, true));
|
|
169
|
+
position += chunkBytesRead;
|
|
170
|
+
}
|
|
171
|
+
parts.push(decodeChunk(new Uint8Array(0), false));
|
|
172
|
+
const text = parts.join("");
|
|
173
|
+
if (options?.maxLines !== undefined && text.length > 0) {
|
|
174
|
+
const normalized = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
175
|
+
assertLineLimit(normalized, options.displayPath ?? filePath, options.maxLines);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
if (containsNul) {
|
|
179
|
+
return { kind: "binary", description: "contains NUL bytes" };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
return {
|
|
183
|
+
kind: "text",
|
|
184
|
+
text,
|
|
185
|
+
identity,
|
|
186
|
+
...(hadUtf8DecodeErrors ? { hadUtf8DecodeErrors: true as const } : {}),
|
|
187
|
+
};
|
|
188
|
+
} finally {
|
|
189
|
+
await fileHandle.close();
|
|
190
|
+
}
|
|
191
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import { stat } from "node:fs/promises";
|
|
3
|
+
import { lineHashes } from "./hashline";
|
|
4
|
+
import { loadFileKindAndText, type LFile } from "./file-kind";
|
|
5
|
+
import { resolveTarget, type FileIdentity } from "./fs-write";
|
|
6
|
+
import { toCwd, toDisplayPath } from "./paths";
|
|
7
|
+
import { detectEnding, toLF, stripBOM, type LineEnding } from "./normalize";
|
|
8
|
+
import { abortIf, errCode, assertLineLimit } from "./utils";
|
|
9
|
+
import { ANCHOR_POOL_EXHAUSTED_PREFIX } from "./constants";
|
|
10
|
+
import { valKind, valAccess } from "./validation";
|
|
11
|
+
import type { HashStore } from "./hash-store";
|
|
12
|
+
export interface NormFile {
|
|
13
|
+
absolutePath: string;
|
|
14
|
+
normalized: string;
|
|
15
|
+
bom: string;
|
|
16
|
+
originalEnding: LineEnding;
|
|
17
|
+
fileHashes: string[];
|
|
18
|
+
hadUtf8DecodeErrors: boolean;
|
|
19
|
+
identity: FileIdentity;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export type SnapInfo = {
|
|
23
|
+
snapshotId: string;
|
|
24
|
+
ino: number;
|
|
25
|
+
mtimeMs: number;
|
|
26
|
+
ctimeMs: number;
|
|
27
|
+
size: number;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
function fmtSnapId(
|
|
31
|
+
canonicalPath: string,
|
|
32
|
+
info: { ino: number; mtimeMs: number; ctimeMs: number; size: number },
|
|
33
|
+
): string {
|
|
34
|
+
return `v2|${canonicalPath}|${info.ino}|${info.mtimeMs}|${info.ctimeMs}|${info.size}`;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function fileSnap(absolutePath: string): Promise<SnapInfo> {
|
|
38
|
+
const canonicalPath = await resolveTarget(absolutePath);
|
|
39
|
+
const stats = await stat(canonicalPath);
|
|
40
|
+
return {
|
|
41
|
+
snapshotId: fmtSnapId(canonicalPath, stats),
|
|
42
|
+
ino: stats.ino,
|
|
43
|
+
mtimeMs: stats.mtimeMs,
|
|
44
|
+
ctimeMs: stats.ctimeMs,
|
|
45
|
+
size: stats.size,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function safeSnapId(
|
|
50
|
+
absolutePath: string,
|
|
51
|
+
context: string,
|
|
52
|
+
): Promise<string | undefined> {
|
|
53
|
+
try {
|
|
54
|
+
return (await fileSnap(absolutePath)).snapshotId;
|
|
55
|
+
} catch (error) {
|
|
56
|
+
console.error(`[safeSnapId] ${context}: failed to stat "${absolutePath}" (code=${errCode(error) ?? "?"}):`, error);
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface ReadNormOptions {
|
|
62
|
+
signal?: AbortSignal;
|
|
63
|
+
accessMode?: number;
|
|
64
|
+
preloadedFile?: LFile;
|
|
65
|
+
preloadedNorm?: NormFile;
|
|
66
|
+
maxLines?: number;
|
|
67
|
+
store?: HashStore;
|
|
68
|
+
noPersist?: boolean;
|
|
69
|
+
allocation?: "real" | "shadow";
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export async function readNormFile(
|
|
73
|
+
path: string,
|
|
74
|
+
cwd: string,
|
|
75
|
+
options?: ReadNormOptions,
|
|
76
|
+
): Promise<NormFile> {
|
|
77
|
+
const absolutePath = toCwd(path, cwd);
|
|
78
|
+
const resolvedPath = await resolveTarget(absolutePath);
|
|
79
|
+
const signal = options?.signal;
|
|
80
|
+
const accessMode = options?.accessMode ?? constants.R_OK;
|
|
81
|
+
|
|
82
|
+
abortIf(signal);
|
|
83
|
+
await valAccess(resolvedPath, path, accessMode);
|
|
84
|
+
|
|
85
|
+
abortIf(signal);
|
|
86
|
+
const preloadedNorm = options?.preloadedNorm;
|
|
87
|
+
if (preloadedNorm) return preloadedNorm;
|
|
88
|
+
|
|
89
|
+
const file = options?.preloadedFile ?? (await loadFileKindAndText(resolvedPath, { maxLines: options?.maxLines, displayPath: path }));
|
|
90
|
+
valKind(file, path);
|
|
91
|
+
abortIf(signal);
|
|
92
|
+
const { bom, text: rawContent } = stripBOM(file.text);
|
|
93
|
+
const originalEnding = detectEnding(rawContent);
|
|
94
|
+
const normalized = toLF(rawContent);
|
|
95
|
+
|
|
96
|
+
if (options?.maxLines !== undefined) assertLineLimit(normalized, path, options.maxLines);
|
|
97
|
+
|
|
98
|
+
const fileHashes = await lineHashes(normalized, resolvedPath, undefined, options?.store, options?.noPersist !== true, options?.allocation === "shadow");
|
|
99
|
+
let identity = file.identity;
|
|
100
|
+
if (!identity) {
|
|
101
|
+
const { dev, ino } = await stat(resolvedPath);
|
|
102
|
+
identity = { dev, ino };
|
|
103
|
+
}
|
|
104
|
+
return {
|
|
105
|
+
absolutePath: resolvedPath,
|
|
106
|
+
normalized,
|
|
107
|
+
bom,
|
|
108
|
+
originalEnding,
|
|
109
|
+
fileHashes,
|
|
110
|
+
identity,
|
|
111
|
+
hadUtf8DecodeErrors: file.hadUtf8DecodeErrors === true,
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export async function tryReadNormFile(
|
|
116
|
+
absPath: string,
|
|
117
|
+
cwd: string,
|
|
118
|
+
options?: ReadNormOptions,
|
|
119
|
+
): Promise<NormFile | undefined> {
|
|
120
|
+
try {
|
|
121
|
+
const displayPath = toDisplayPath(cwd, absPath);
|
|
122
|
+
const file = await loadFileKindAndText(absPath, { maxLines: options?.maxLines, displayPath });
|
|
123
|
+
if (file.kind !== "text") return undefined;
|
|
124
|
+
return await readNormFile(absPath, cwd, { ...options, preloadedFile: file });
|
|
125
|
+
} catch (error) {
|
|
126
|
+
const code = errCode(error);
|
|
127
|
+
if (code === "EACCES" || code === "EPERM" || code === "ENOENT" || code === "ELOOP") return undefined;
|
|
128
|
+
if (error instanceof Error) {
|
|
129
|
+
const msg = error.message;
|
|
130
|
+
if (msg.startsWith(ANCHOR_POOL_EXHAUSTED_PREFIX)) throw error;
|
|
131
|
+
if (msg.startsWith("[E_FILE_TOO_LARGE]") || msg.startsWith("[E_NOT_FOUND]") || msg.startsWith("[E_ACCESS]") || msg.startsWith("[E_NOT_TEXT]")) return undefined;
|
|
132
|
+
}
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
}
|