@radheim/util 0.0.0-stage → 2.4.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/dist/abort.d.ts +1 -0
- package/dist/abort.js +8 -0
- package/dist/activity-calendar.d.ts +21 -0
- package/dist/activity-calendar.js +42 -0
- package/dist/artifact.d.ts +4 -0
- package/dist/artifact.js +85 -0
- package/dist/base64.d.ts +4 -0
- package/dist/base64.js +24 -0
- package/dist/binary.d.ts +7 -0
- package/dist/binary.js +34 -0
- package/dist/bom.d.ts +22 -0
- package/dist/bom.js +36 -0
- package/dist/cross-spawn-spawner.d.ts +9 -0
- package/dist/cross-spawn-spawner.js +548 -0
- package/dist/duration.d.ts +2 -0
- package/dist/duration.js +22 -0
- package/dist/effect/app-node-platform.d.ts +13 -0
- package/dist/effect/app-node-platform.js +29 -0
- package/dist/effect/app-node.d.ts +16 -0
- package/dist/effect/app-node.js +8 -0
- package/dist/effect/layer-node.d.ts +178 -0
- package/dist/effect/layer-node.js +248 -0
- package/dist/effect-flock.d.ts +31 -0
- package/dist/effect-flock.js +186 -0
- package/dist/encode.d.ts +4 -0
- package/dist/encode.js +38 -0
- package/dist/execute-output.d.ts +10 -0
- package/dist/execute-output.js +22 -0
- package/dist/flock.d.ts +28 -0
- package/dist/flock.js +267 -0
- package/dist/fs-util.d.ts +54 -0
- package/dist/fs-util.js +200 -0
- package/dist/glob.d.ts +18 -0
- package/dist/glob.js +29 -0
- package/dist/global-roots.d.ts +8 -0
- package/dist/global-roots.js +17 -0
- package/dist/global-roots.workerd.d.ts +7 -0
- package/dist/global-roots.workerd.js +15 -0
- package/dist/global.d.ts +30 -0
- package/dist/global.js +54 -0
- package/dist/hash.d.ts +4 -0
- package/dist/hash.js +12 -0
- package/dist/heap-snapshot.d.ts +19 -0
- package/dist/heap-snapshot.js +38 -0
- package/dist/no-timeout-fetch.d.ts +1 -0
- package/dist/no-timeout-fetch.js +4 -0
- package/dist/npm-config.d.ts +4 -0
- package/dist/npm-config.js +34 -0
- package/dist/npm.d.ts +45 -0
- package/dist/npm.js +441 -0
- package/dist/observability/logging.d.ts +14 -0
- package/dist/observability/logging.js +151 -0
- package/dist/observability/otlp.d.ts +19 -0
- package/dist/observability/otlp.js +63 -0
- package/dist/observability/shared.d.ts +1 -0
- package/dist/observability/shared.js +7 -0
- package/dist/observability/tracing.d.ts +2 -0
- package/dist/observability/tracing.js +3 -0
- package/dist/observability.d.ts +13 -0
- package/dist/observability.js +37 -0
- package/dist/open.d.ts +2 -0
- package/dist/open.js +10 -0
- package/dist/patch.d.ts +43 -0
- package/dist/patch.js +332 -0
- package/dist/path.d.ts +20 -0
- package/dist/path.js +134 -0
- package/dist/process-signal.d.ts +5 -0
- package/dist/process-signal.js +22 -0
- package/dist/process.d.ts +54 -0
- package/dist/process.js +167 -0
- package/dist/qr.d.ts +15 -0
- package/dist/qr.js +295 -0
- package/dist/record.d.ts +2 -0
- package/dist/record.js +2 -0
- package/dist/retry.d.ts +8 -0
- package/dist/retry.js +45 -0
- package/dist/runtime/import.bun.d.ts +2 -0
- package/dist/runtime/import.bun.js +8 -0
- package/dist/runtime/import.node.d.ts +2 -0
- package/dist/runtime/import.node.js +62 -0
- package/dist/runtime/import.workerd.d.ts +2 -0
- package/dist/runtime/import.workerd.js +7 -0
- package/dist/runtime-import.d.ts +1 -0
- package/dist/runtime-import.js +1 -0
- package/dist/session-mention.d.ts +11 -0
- package/dist/session-mention.js +18 -0
- package/dist/session-title-fallback.d.ts +16 -0
- package/dist/session-title-fallback.js +23 -0
- package/dist/session-turn.d.ts +37 -0
- package/dist/session-turn.js +56 -0
- package/dist/teardown.d.ts +8 -0
- package/dist/teardown.js +16 -0
- package/dist/text-boundary.d.ts +11 -0
- package/dist/text-boundary.js +22 -0
- package/dist/uuid.d.ts +1 -0
- package/dist/uuid.js +14 -0
- package/package.json +71 -4
- package/README.md +0 -3
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { Layer, Tracer } from "effect";
|
|
2
|
+
import { FetchHttpClient } from "effect/http";
|
|
3
|
+
import { OtlpExporter, OtlpLogger, OtlpSerialization, OtlpTracer } from "effect/observability";
|
|
4
|
+
import { runID } from "./shared.js";
|
|
5
|
+
function parseHeaders(value) {
|
|
6
|
+
return value
|
|
7
|
+
? value.split(",").reduce((acc, entry) => {
|
|
8
|
+
const [key, ...value] = entry.split("=");
|
|
9
|
+
acc[key] = value.join("=");
|
|
10
|
+
return acc;
|
|
11
|
+
}, {})
|
|
12
|
+
: undefined;
|
|
13
|
+
}
|
|
14
|
+
function resourceAttributes() {
|
|
15
|
+
const value = process.env.OTEL_RESOURCE_ATTRIBUTES;
|
|
16
|
+
if (!value)
|
|
17
|
+
return {};
|
|
18
|
+
try {
|
|
19
|
+
return Object.fromEntries(value.split(",").map((entry) => {
|
|
20
|
+
const index = entry.indexOf("=");
|
|
21
|
+
if (index < 1)
|
|
22
|
+
throw new Error("Invalid OTEL_RESOURCE_ATTRIBUTES entry");
|
|
23
|
+
return [decodeURIComponent(entry.slice(0, index)), decodeURIComponent(entry.slice(index + 1))];
|
|
24
|
+
}));
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return {};
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export function resource(app = { client: "opencode", version: "unknown", channel: "local" }) {
|
|
31
|
+
return {
|
|
32
|
+
serviceName: "opencode",
|
|
33
|
+
serviceVersion: app.version,
|
|
34
|
+
attributes: {
|
|
35
|
+
...resourceAttributes(),
|
|
36
|
+
"deployment.environment.name": app.channel,
|
|
37
|
+
"opencode.client": app.client,
|
|
38
|
+
"opencode.run": runID(),
|
|
39
|
+
"service.instance.id": runID(),
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
export function loggers(options, app) {
|
|
44
|
+
if (!options?.endpoint)
|
|
45
|
+
return [];
|
|
46
|
+
return [
|
|
47
|
+
OtlpLogger.make({
|
|
48
|
+
url: `${options.endpoint}/v1/logs`,
|
|
49
|
+
resource: resource(app),
|
|
50
|
+
headers: parseHeaders(options.headers),
|
|
51
|
+
}),
|
|
52
|
+
];
|
|
53
|
+
}
|
|
54
|
+
export function tracingLayer(options, app) {
|
|
55
|
+
if (!options?.endpoint)
|
|
56
|
+
return Layer.empty;
|
|
57
|
+
return Layer.effect(Tracer.Tracer, OtlpTracer.make({
|
|
58
|
+
url: `${options.endpoint}/v1/traces`,
|
|
59
|
+
resource: resource(app),
|
|
60
|
+
headers: parseHeaders(options.headers),
|
|
61
|
+
})).pipe(Layer.provide(OtlpSerialization.layerJson), Layer.provide(FetchHttpClient.layer), Layer.provide(OtlpExporter.layerFlusher));
|
|
62
|
+
}
|
|
63
|
+
export * as Otlp from "./otlp.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function runID(): string;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// Lazy: workerd forbids generating random values in global scope, so the id
|
|
2
|
+
// materializes on first call (inside a handler) and stays stable afterwards.
|
|
3
|
+
let generated;
|
|
4
|
+
export function runID() {
|
|
5
|
+
generated ??= crypto.randomUUID().slice(0, 8);
|
|
6
|
+
return generated;
|
|
7
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { Context, Effect, Tracer } from "effect";
|
|
2
|
+
// ParentSpan is optional, so removing it never takes away a requirement of the effect.
|
|
3
|
+
export const withoutParentSpan = (effect) => effect.pipe(Effect.updateContext((context) => Context.omit(Tracer.ParentSpan)(context)));
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export * as Observability from "./observability.js";
|
|
2
|
+
import { LayerNode } from "./effect/layer-node.js";
|
|
3
|
+
import { Layer, Schema } from "effect";
|
|
4
|
+
export declare const Options: Schema.Struct<{
|
|
5
|
+
readonly endpoint: Schema.optional<Schema.String>;
|
|
6
|
+
readonly headers: Schema.optional<Schema.String>;
|
|
7
|
+
readonly client: Schema.optional<Schema.String>;
|
|
8
|
+
readonly version: Schema.optional<Schema.String>;
|
|
9
|
+
readonly channel: Schema.optional<Schema.String>;
|
|
10
|
+
}>;
|
|
11
|
+
export type Options = typeof Options.Type;
|
|
12
|
+
export declare function layer(options?: Options): Layer.Layer<never, never, never>;
|
|
13
|
+
export declare const node: LayerNode.Provider<never, never, undefined, false>;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export * as Observability from "./observability.js";
|
|
2
|
+
import { filesystem } from "./effect/app-node-platform.js";
|
|
3
|
+
import { LayerNode } from "./effect/layer-node.js";
|
|
4
|
+
import { Layer, Logger, References, Schema } from "effect";
|
|
5
|
+
import { FetchHttpClient } from "effect/http";
|
|
6
|
+
import { OtlpExporter, OtlpSerialization } from "effect/observability";
|
|
7
|
+
import { Logging } from "./observability/logging.js";
|
|
8
|
+
import { Otlp } from "./observability/otlp.js";
|
|
9
|
+
export const Options = Schema.Struct({
|
|
10
|
+
endpoint: Schema.optional(Schema.String),
|
|
11
|
+
headers: Schema.optional(Schema.String),
|
|
12
|
+
client: Schema.optional(Schema.String),
|
|
13
|
+
version: Schema.optional(Schema.String),
|
|
14
|
+
channel: Schema.optional(Schema.String),
|
|
15
|
+
});
|
|
16
|
+
export function layer(options = {
|
|
17
|
+
endpoint: process.env.OTEL_EXPORTER_OTLP_ENDPOINT,
|
|
18
|
+
headers: process.env.OTEL_EXPORTER_OTLP_HEADERS,
|
|
19
|
+
}) {
|
|
20
|
+
const app = {
|
|
21
|
+
client: options.client ?? "opencode",
|
|
22
|
+
version: options.version ?? "unknown",
|
|
23
|
+
channel: options.channel ?? "local",
|
|
24
|
+
};
|
|
25
|
+
const local = Logger.layer(Logging.loggers(app.channel === "local", app.channel), { mergeWithExisting: false }).pipe(Layer.provide(LayerNode.compile(filesystem)), Layer.orDie, Layer.merge(Layer.succeed(References.MinimumLogLevel, Logging.minimumLogLevel())));
|
|
26
|
+
if (!options.endpoint)
|
|
27
|
+
return local;
|
|
28
|
+
const logs = Logger.layer([...Logging.loggers(app.channel === "local", app.channel), ...Otlp.loggers(options, app)], { mergeWithExisting: false }).pipe(Layer.provide(LayerNode.compile(filesystem)), Layer.provide(OtlpSerialization.layerJson), Layer.provide(FetchHttpClient.layer), Layer.provide(OtlpExporter.layerFlusher), Layer.orDie, Layer.merge(Layer.succeed(References.MinimumLogLevel, Logging.minimumLogLevel())));
|
|
29
|
+
return Layer.merge(logs, Otlp.tracingLayer(options, app)).pipe(Layer.catchCause(() => local));
|
|
30
|
+
}
|
|
31
|
+
// Layer.suspend: constructing the loggers eagerly at module scope performs
|
|
32
|
+
// I/O (file logger, run id) that workerd forbids in global scope.
|
|
33
|
+
export const node = LayerNode.make({
|
|
34
|
+
name: "observability",
|
|
35
|
+
layer: Layer.suspend(() => layer()),
|
|
36
|
+
deps: [],
|
|
37
|
+
});
|
package/dist/open.d.ts
ADDED
package/dist/open.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import open from "open";
|
|
2
|
+
export function openUrl(input) {
|
|
3
|
+
const url = URL.canParse(input) ? new URL(input) : undefined;
|
|
4
|
+
if (!url || (url.protocol !== "http:" && url.protocol !== "https:"))
|
|
5
|
+
return Promise.reject(new Error(`Only http and https links can be opened in the browser: ${input}`));
|
|
6
|
+
return open(url.href);
|
|
7
|
+
}
|
|
8
|
+
export function openPath(path) {
|
|
9
|
+
return open(path);
|
|
10
|
+
}
|
package/dist/patch.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
export * as Patch from "./patch.js";
|
|
2
|
+
import { Result, Schema } from "effect";
|
|
3
|
+
declare const BoundaryError_base: Schema.Class<BoundaryError, Schema.TaggedStruct<"Patch.BoundaryError", {
|
|
4
|
+
readonly boundary: Schema.Literals<readonly ["first", "last"]>;
|
|
5
|
+
}>, import("effect/Cause").YieldableError>;
|
|
6
|
+
export declare class BoundaryError extends BoundaryError_base {
|
|
7
|
+
get message(): string;
|
|
8
|
+
}
|
|
9
|
+
declare const InvalidHunkError_base: Schema.Class<InvalidHunkError, Schema.TaggedStruct<"Patch.InvalidHunkError", {
|
|
10
|
+
readonly line: Schema.String;
|
|
11
|
+
readonly lineNumber: Schema.Number;
|
|
12
|
+
readonly reason: Schema.optional<Schema.String>;
|
|
13
|
+
}>, import("effect/Cause").YieldableError>;
|
|
14
|
+
export declare class InvalidHunkError extends InvalidHunkError_base {
|
|
15
|
+
get message(): string;
|
|
16
|
+
}
|
|
17
|
+
export type ParseError = BoundaryError | InvalidHunkError;
|
|
18
|
+
export type Hunk = {
|
|
19
|
+
readonly type: "add";
|
|
20
|
+
readonly path: string;
|
|
21
|
+
readonly contents: string;
|
|
22
|
+
} | {
|
|
23
|
+
readonly type: "delete";
|
|
24
|
+
readonly path: string;
|
|
25
|
+
} | {
|
|
26
|
+
readonly type: "update";
|
|
27
|
+
readonly path: string;
|
|
28
|
+
readonly movePath?: string;
|
|
29
|
+
readonly chunks: ReadonlyArray<UpdateFileChunk>;
|
|
30
|
+
};
|
|
31
|
+
export interface UpdateFileChunk {
|
|
32
|
+
readonly oldLines: ReadonlyArray<string>;
|
|
33
|
+
readonly newLines: ReadonlyArray<string>;
|
|
34
|
+
readonly changeContext?: string;
|
|
35
|
+
readonly endOfFile?: boolean;
|
|
36
|
+
}
|
|
37
|
+
export interface FileUpdate {
|
|
38
|
+
readonly content: string;
|
|
39
|
+
readonly bom: boolean;
|
|
40
|
+
}
|
|
41
|
+
export declare function parse(patchText: string): Result.Result<ReadonlyArray<Hunk>, ParseError>;
|
|
42
|
+
export declare function derive(path: string, chunks: ReadonlyArray<UpdateFileChunk>, original: string): FileUpdate;
|
|
43
|
+
export declare function joinBom(text: string, bom: boolean): string;
|
package/dist/patch.js
ADDED
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
export * as Patch from "./patch.js";
|
|
2
|
+
import { Result, Schema } from "effect";
|
|
3
|
+
import { Bom } from "./bom.js";
|
|
4
|
+
export class BoundaryError extends Schema.TaggedError()("Patch.BoundaryError", {
|
|
5
|
+
boundary: Schema.Literals(["first", "last"]),
|
|
6
|
+
}) {
|
|
7
|
+
get message() {
|
|
8
|
+
return `The ${this.boundary} line of the patch must be '${this.boundary === "first" ? "*** Begin Patch" : "*** End Patch"}'`;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
export class InvalidHunkError extends Schema.TaggedError()("Patch.InvalidHunkError", {
|
|
12
|
+
line: Schema.String,
|
|
13
|
+
lineNumber: Schema.Number,
|
|
14
|
+
reason: Schema.optional(Schema.String),
|
|
15
|
+
}) {
|
|
16
|
+
get message() {
|
|
17
|
+
if (this.reason)
|
|
18
|
+
return `Invalid hunk at line ${this.lineNumber}: ${this.reason}`;
|
|
19
|
+
return `Invalid hunk at line ${this.lineNumber}: '${this.line}' is not a valid hunk header. Valid hunk headers: '*** Add File: {path}', '*** Delete File: {path}', '*** Update File: {path}'`;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export function parse(patchText) {
|
|
23
|
+
const lines = stripHeredoc(patchText.trim())
|
|
24
|
+
.split("\n")
|
|
25
|
+
.map((line) => (line.endsWith("\r") ? line.slice(0, -1) : line));
|
|
26
|
+
const begin = lines[0]?.trim() === "*** Begin Patch" ? 0 : -1;
|
|
27
|
+
const end = lines.at(-1)?.trim() === "*** End Patch" ? lines.length - 1 : -1;
|
|
28
|
+
if (begin === -1)
|
|
29
|
+
return Result.fail(new BoundaryError({ boundary: "first" }));
|
|
30
|
+
if (end === -1 || begin >= end)
|
|
31
|
+
return Result.fail(new BoundaryError({ boundary: "last" }));
|
|
32
|
+
const hunks = [];
|
|
33
|
+
let index = begin + 1;
|
|
34
|
+
while (index < end) {
|
|
35
|
+
const line = lines[index];
|
|
36
|
+
const header = line.trim();
|
|
37
|
+
if (index === begin + 1 &&
|
|
38
|
+
header.startsWith("*** Environment ID:") &&
|
|
39
|
+
header.slice("*** Environment ID:".length).trim()) {
|
|
40
|
+
index++;
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
if (header.startsWith("*** Add File: ")) {
|
|
44
|
+
const path = header.slice("*** Add File: ".length).trim();
|
|
45
|
+
const parsed = parseAdd(lines, index + 1, end, path);
|
|
46
|
+
if ("error" in parsed)
|
|
47
|
+
return Result.fail(parsed.error);
|
|
48
|
+
hunks.push({ type: "add", path, contents: parsed.content });
|
|
49
|
+
index = parsed.next;
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
if (header.startsWith("*** Delete File: ")) {
|
|
53
|
+
const path = header.slice("*** Delete File: ".length).trim();
|
|
54
|
+
const next = lines[index + 1]?.trim();
|
|
55
|
+
if (index + 1 < end && next !== undefined && !isBoundary(next)) {
|
|
56
|
+
if (next.startsWith("*** ")) {
|
|
57
|
+
return Result.fail(new InvalidHunkError({ line: next, lineNumber: index + 2 }));
|
|
58
|
+
}
|
|
59
|
+
return Result.fail(new InvalidHunkError({
|
|
60
|
+
line: next,
|
|
61
|
+
lineNumber: index + 2,
|
|
62
|
+
reason: `Unexpected line after Delete File '${path}': '${next}'. Delete hunks do not contain body lines`,
|
|
63
|
+
}));
|
|
64
|
+
}
|
|
65
|
+
hunks.push({ type: "delete", path });
|
|
66
|
+
index++;
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
if (header.startsWith("*** Update File: ")) {
|
|
70
|
+
const path = header.slice("*** Update File: ".length).trim();
|
|
71
|
+
let next = index + 1;
|
|
72
|
+
let movePath;
|
|
73
|
+
while (lines[next]?.trimEnd() === "*** End of File")
|
|
74
|
+
next++;
|
|
75
|
+
const move = lines[next]?.trimEnd();
|
|
76
|
+
if (move === "*** Move to:" || move?.startsWith("*** Move to: ")) {
|
|
77
|
+
movePath = move.slice("*** Move to: ".length).trim();
|
|
78
|
+
if (!movePath) {
|
|
79
|
+
return Result.fail(new InvalidHunkError({
|
|
80
|
+
line: lines[next].trim(),
|
|
81
|
+
lineNumber: next + 1,
|
|
82
|
+
reason: `Move destination for '${path}' must not be empty`,
|
|
83
|
+
}));
|
|
84
|
+
}
|
|
85
|
+
next++;
|
|
86
|
+
}
|
|
87
|
+
const parsed = parseUpdate(lines, next, end, path, index);
|
|
88
|
+
if ("error" in parsed)
|
|
89
|
+
return Result.fail(parsed.error);
|
|
90
|
+
hunks.push({ type: "update", path, movePath, chunks: parsed.chunks });
|
|
91
|
+
index = parsed.next;
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
return Result.fail(new InvalidHunkError({ line: header, lineNumber: index + 1 }));
|
|
95
|
+
}
|
|
96
|
+
return Result.succeed(hunks);
|
|
97
|
+
}
|
|
98
|
+
export function derive(path, chunks, original) {
|
|
99
|
+
const source = Bom.split(original);
|
|
100
|
+
const lines = source.text.split("\n");
|
|
101
|
+
if (lines.at(-1) === "")
|
|
102
|
+
lines.pop();
|
|
103
|
+
const replacements = computeReplacements(lines, path, chunks);
|
|
104
|
+
for (const [start, remove, insert] of replacements.reverse())
|
|
105
|
+
lines.splice(start, remove, ...insert);
|
|
106
|
+
if (lines.at(-1) !== "")
|
|
107
|
+
lines.push("");
|
|
108
|
+
const next = Bom.split(lines.join("\n"));
|
|
109
|
+
return { content: next.text, bom: source.bom || next.bom };
|
|
110
|
+
}
|
|
111
|
+
export function joinBom(text, bom) {
|
|
112
|
+
return Bom.join(text, bom);
|
|
113
|
+
}
|
|
114
|
+
function parseAdd(lines, start, end, path) {
|
|
115
|
+
const content = [];
|
|
116
|
+
let index = start;
|
|
117
|
+
while (index < end && !isBoundary(lines[index].trim())) {
|
|
118
|
+
if (!lines[index].startsWith("+")) {
|
|
119
|
+
const line = lines[index].trim();
|
|
120
|
+
return {
|
|
121
|
+
error: new InvalidHunkError({
|
|
122
|
+
line,
|
|
123
|
+
lineNumber: index + 1,
|
|
124
|
+
reason: `Invalid Add File line for '${path}': expected a line starting with '+', got '${line}'`,
|
|
125
|
+
}),
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
// Every + line is a whole line of the file, as in Codex, so a final empty + line is a blank last line.
|
|
129
|
+
content.push(`${lines[index].slice(1)}\n`);
|
|
130
|
+
index++;
|
|
131
|
+
}
|
|
132
|
+
return { content: content.join(""), next: index };
|
|
133
|
+
}
|
|
134
|
+
function parseUpdate(lines, start, end, path, hunk) {
|
|
135
|
+
const chunks = [];
|
|
136
|
+
let index = start;
|
|
137
|
+
let afterEndOfFile = false;
|
|
138
|
+
while (index < end) {
|
|
139
|
+
const line = lines[index];
|
|
140
|
+
const updateLine = line.trimEnd();
|
|
141
|
+
if (afterEndOfFile) {
|
|
142
|
+
if (updateLine === "") {
|
|
143
|
+
index++;
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
if (updateLine === "@@" || updateLine.startsWith("@@ "))
|
|
147
|
+
afterEndOfFile = false;
|
|
148
|
+
else if (isBoundary(updateLine))
|
|
149
|
+
break;
|
|
150
|
+
else {
|
|
151
|
+
return {
|
|
152
|
+
error: new InvalidHunkError({
|
|
153
|
+
line,
|
|
154
|
+
lineNumber: index + 1,
|
|
155
|
+
reason: `Expected update hunk to start with a @@ context marker, got: '${line}'`,
|
|
156
|
+
}),
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
if (updateLine === "*** End of File") {
|
|
161
|
+
const chunk = chunks.at(-1);
|
|
162
|
+
if (chunk && chunk.oldLines.length === 0 && chunk.newLines.length === 0) {
|
|
163
|
+
return {
|
|
164
|
+
error: new InvalidHunkError({
|
|
165
|
+
line: updateLine,
|
|
166
|
+
lineNumber: index + 1,
|
|
167
|
+
reason: "Update hunk does not contain any lines",
|
|
168
|
+
}),
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
if (chunk) {
|
|
172
|
+
chunk.endOfFile = true;
|
|
173
|
+
afterEndOfFile = true;
|
|
174
|
+
}
|
|
175
|
+
index++;
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
if (isBoundary(updateLine))
|
|
179
|
+
break;
|
|
180
|
+
if (updateLine === "@@" || updateLine.startsWith("@@ ")) {
|
|
181
|
+
const previous = chunks.at(-1);
|
|
182
|
+
if (previous && previous.oldLines.length === 0 && previous.newLines.length === 0) {
|
|
183
|
+
return {
|
|
184
|
+
error: new InvalidHunkError({
|
|
185
|
+
line,
|
|
186
|
+
lineNumber: index + 1,
|
|
187
|
+
reason: `Unexpected line found in update hunk: '${line}'. Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)`,
|
|
188
|
+
}),
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
chunks.push({
|
|
192
|
+
oldLines: [],
|
|
193
|
+
newLines: [],
|
|
194
|
+
changeContext: updateLine === "@@" ? undefined : updateLine.slice("@@ ".length),
|
|
195
|
+
});
|
|
196
|
+
index++;
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
if (chunks.length === 0)
|
|
200
|
+
chunks.push({ oldLines: [], newLines: [] });
|
|
201
|
+
const chunk = chunks.at(-1);
|
|
202
|
+
if (line === "") {
|
|
203
|
+
chunk.oldLines.push("");
|
|
204
|
+
chunk.newLines.push("");
|
|
205
|
+
index++;
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
if (line.startsWith(" ")) {
|
|
209
|
+
chunk.oldLines.push(line.slice(1));
|
|
210
|
+
chunk.newLines.push(line.slice(1));
|
|
211
|
+
index++;
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
if (line.startsWith("-")) {
|
|
215
|
+
chunk.oldLines.push(line.slice(1));
|
|
216
|
+
index++;
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
if (line.startsWith("+")) {
|
|
220
|
+
chunk.newLines.push(line.slice(1));
|
|
221
|
+
index++;
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
const populated = chunk.oldLines.length > 0 || chunk.newLines.length > 0;
|
|
225
|
+
return {
|
|
226
|
+
error: new InvalidHunkError({
|
|
227
|
+
line,
|
|
228
|
+
lineNumber: index + 1,
|
|
229
|
+
reason: populated
|
|
230
|
+
? `Expected update hunk to start with a @@ context marker, got: '${line}'`
|
|
231
|
+
: `Unexpected line found in update hunk: '${line}'. Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)`,
|
|
232
|
+
}),
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
if (chunks.length === 0) {
|
|
236
|
+
return {
|
|
237
|
+
error: new InvalidHunkError({
|
|
238
|
+
line: lines[hunk].trim(),
|
|
239
|
+
lineNumber: hunk + 1,
|
|
240
|
+
reason: `Update file hunk for path '${path}' is empty`,
|
|
241
|
+
}),
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
const last = chunks.at(-1);
|
|
245
|
+
if (last.oldLines.length === 0 && last.newLines.length === 0) {
|
|
246
|
+
const line = lines[index].trim();
|
|
247
|
+
return {
|
|
248
|
+
error: new InvalidHunkError({
|
|
249
|
+
line,
|
|
250
|
+
lineNumber: index + 1,
|
|
251
|
+
reason: line === "*** End Patch"
|
|
252
|
+
? "Update hunk does not contain any lines"
|
|
253
|
+
: `Unexpected line found in update hunk: '${line}'. Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)`,
|
|
254
|
+
}),
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
return { chunks, next: index };
|
|
258
|
+
}
|
|
259
|
+
function isBoundary(line) {
|
|
260
|
+
return (line === "*** End Patch" ||
|
|
261
|
+
line.startsWith("*** Add File: ") ||
|
|
262
|
+
line.startsWith("*** Delete File: ") ||
|
|
263
|
+
line.startsWith("*** Update File: "));
|
|
264
|
+
}
|
|
265
|
+
function computeReplacements(lines, path, chunks) {
|
|
266
|
+
const replacements = [];
|
|
267
|
+
let lineIndex = 0;
|
|
268
|
+
for (const chunk of chunks) {
|
|
269
|
+
if (chunk.changeContext) {
|
|
270
|
+
const context = seek(lines, [chunk.changeContext], lineIndex);
|
|
271
|
+
if (context === -1)
|
|
272
|
+
throw new Error(`Failed to find context '${chunk.changeContext}' in ${path}`);
|
|
273
|
+
lineIndex = context + 1;
|
|
274
|
+
}
|
|
275
|
+
if (chunk.oldLines.length === 0) {
|
|
276
|
+
replacements.push([lines.length, 0, chunk.newLines]);
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
let oldLines = chunk.oldLines;
|
|
280
|
+
let newLines = chunk.newLines;
|
|
281
|
+
let found = seek(lines, oldLines, lineIndex, chunk.endOfFile);
|
|
282
|
+
if (found === -1 && oldLines.at(-1) === "") {
|
|
283
|
+
oldLines = oldLines.slice(0, -1);
|
|
284
|
+
if (newLines.at(-1) === "")
|
|
285
|
+
newLines = newLines.slice(0, -1);
|
|
286
|
+
found = seek(lines, oldLines, lineIndex, chunk.endOfFile);
|
|
287
|
+
}
|
|
288
|
+
if (found === -1 && chunk.oldLines.every((line) => line === "")) {
|
|
289
|
+
const expected = chunk.oldLines.length === 1 ? "an expected blank line" : `${chunk.oldLines.length} consecutive blank lines`;
|
|
290
|
+
throw new Error(`Failed to find ${expected} in ${path}`);
|
|
291
|
+
}
|
|
292
|
+
if (found === -1)
|
|
293
|
+
throw new Error(`Failed to find expected lines in ${path}:\n${chunk.oldLines.join("\n")}`);
|
|
294
|
+
replacements.push([found, oldLines.length, newLines]);
|
|
295
|
+
lineIndex = found + oldLines.length;
|
|
296
|
+
}
|
|
297
|
+
return replacements.sort((left, right) => left[0] - right[0]);
|
|
298
|
+
}
|
|
299
|
+
function seek(lines, pattern, start, eof = false) {
|
|
300
|
+
if (pattern.length === 0)
|
|
301
|
+
return -1;
|
|
302
|
+
if (eof) {
|
|
303
|
+
const offset = lines.length - pattern.length;
|
|
304
|
+
if (offset < start)
|
|
305
|
+
return -1;
|
|
306
|
+
for (const compare of [exact, rstrip, trim, normalized]) {
|
|
307
|
+
if (matches(lines, pattern, offset, compare))
|
|
308
|
+
return offset;
|
|
309
|
+
}
|
|
310
|
+
return -1;
|
|
311
|
+
}
|
|
312
|
+
for (const compare of [exact, rstrip, trim, normalized]) {
|
|
313
|
+
for (let offset = start; offset <= lines.length - pattern.length; offset++) {
|
|
314
|
+
if (matches(lines, pattern, offset, compare))
|
|
315
|
+
return offset;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
return -1;
|
|
319
|
+
}
|
|
320
|
+
function matches(lines, pattern, offset, compare) {
|
|
321
|
+
return pattern.every((line, index) => compare(lines[offset + index], line));
|
|
322
|
+
}
|
|
323
|
+
const exact = (left, right) => left === right;
|
|
324
|
+
const rstrip = (left, right) => left.trimEnd() === right.trimEnd();
|
|
325
|
+
const trim = (left, right) => left.trim() === right.trim();
|
|
326
|
+
const normalized = (left, right) => normalize(left.trim()) === normalize(right.trim());
|
|
327
|
+
const normalize = (value) => value
|
|
328
|
+
.replace(/[‘’‚‛]/g, "'")
|
|
329
|
+
.replace(/[“”„‟]/g, '"')
|
|
330
|
+
.replace(/[‐‑‒–—―−]/g, "-")
|
|
331
|
+
.replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g, " ");
|
|
332
|
+
const stripHeredoc = (input) => input.match(/^(?:cat\s+)?<<(['"]?)(\w+)\1\s*\n([\s\S]*?)\n\2\s*$/)?.[3] ?? input;
|
package/dist/path.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export declare function getFilename(path: string | undefined): string;
|
|
2
|
+
export declare function getDirectory(path: string | undefined): string;
|
|
3
|
+
export declare function getFilenameTruncated(path: string | undefined, maxLength?: number): string;
|
|
4
|
+
export declare function truncateMiddle(text: string, maxLength?: number): string;
|
|
5
|
+
/** A comparable form of a directory path: forward slashes for Windows paths, no trailing slash except on roots. */
|
|
6
|
+
export declare function comparablePath(path: string): string;
|
|
7
|
+
/** Like `comparablePath`, plus case-insensitive normalization for Windows drive and UNC paths. */
|
|
8
|
+
export declare function comparablePathKey(path: string): string;
|
|
9
|
+
/** `child` is `parent` or inside it. Windows drive and UNC paths compare case-insensitively. */
|
|
10
|
+
export declare function containsDirectory(parent: string, child: string): boolean;
|
|
11
|
+
export declare function sameDirectory(a: string, b: string): boolean;
|
|
12
|
+
export declare function encodeFilePath(filepath: string): string;
|
|
13
|
+
export declare function isLineRangeHash(hash: string): boolean;
|
|
14
|
+
export declare function parsePathLineSuffix(input: string): {
|
|
15
|
+
path: string;
|
|
16
|
+
selection: {
|
|
17
|
+
start: number;
|
|
18
|
+
end: number;
|
|
19
|
+
} | undefined;
|
|
20
|
+
};
|