@zyro-sec/util 1.0.0 → 1.0.2

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.
Files changed (78) hide show
  1. package/docs/layer-node.md +155 -0
  2. package/package.json +12 -15
  3. package/script/build.ts +9 -0
  4. package/script/pack.ts +5 -0
  5. package/src/abort.test.ts +16 -0
  6. package/src/abort.ts +9 -0
  7. package/src/activity-calendar.test.ts +136 -0
  8. package/src/activity-calendar.ts +50 -0
  9. package/src/artifact.test.ts +29 -0
  10. package/src/artifact.ts +95 -0
  11. package/src/base64.test.ts +12 -0
  12. package/src/base64.ts +29 -0
  13. package/src/binary.test.ts +19 -0
  14. package/src/binary.ts +30 -0
  15. package/src/bom.test.ts +21 -0
  16. package/src/bom.ts +46 -0
  17. package/src/cross-spawn-spawner.ts +694 -0
  18. package/src/duration.ts +22 -0
  19. package/src/effect/app-node-platform.ts +40 -0
  20. package/src/effect/app-node.ts +14 -0
  21. package/src/effect/layer-node.ts +360 -0
  22. package/src/effect-flock.ts +313 -0
  23. package/src/encode.test.ts +32 -0
  24. package/src/encode.ts +39 -0
  25. package/src/execute-output.test.ts +36 -0
  26. package/src/execute-output.ts +23 -0
  27. package/src/flock.ts +346 -0
  28. package/src/fs-util.ts +271 -0
  29. package/src/glob.ts +38 -0
  30. package/src/global-roots.ts +19 -0
  31. package/src/global-roots.workerd.ts +16 -0
  32. package/src/global.ts +88 -0
  33. package/src/hash.ts +11 -0
  34. package/src/heap-snapshot.ts +44 -0
  35. package/src/no-timeout-fetch.test.ts +33 -0
  36. package/src/no-timeout-fetch.ts +5 -0
  37. package/src/npm-config.ts +41 -0
  38. package/src/npm.ts +557 -0
  39. package/src/observability/logging.ts +179 -0
  40. package/src/observability/otlp.ts +109 -0
  41. package/src/observability/shared.ts +8 -0
  42. package/src/observability.ts +60 -0
  43. package/src/open.test.ts +16 -0
  44. package/src/open.ts +12 -0
  45. package/src/patch.ts +382 -0
  46. package/src/path.test.ts +89 -0
  47. package/src/path.ts +149 -0
  48. package/src/process-signal.test.ts +38 -0
  49. package/src/process-signal.ts +23 -0
  50. package/src/process.ts +270 -0
  51. package/src/qr.ts +323 -0
  52. package/src/record.ts +3 -0
  53. package/src/retry.test.ts +87 -0
  54. package/src/retry.ts +51 -0
  55. package/src/runtime/import.bun.ts +10 -0
  56. package/src/runtime/import.node.ts +61 -0
  57. package/src/runtime/import.workerd.ts +9 -0
  58. package/src/runtime-import.ts +1 -0
  59. package/src/session-mention.test.ts +19 -0
  60. package/src/session-mention.ts +24 -0
  61. package/src/session-title-fallback.ts +36 -0
  62. package/src/session-turn.test.ts +131 -0
  63. package/src/session-turn.ts +82 -0
  64. package/src/teardown.ts +19 -0
  65. package/src/text-boundary.test.ts +39 -0
  66. package/src/text-boundary.ts +36 -0
  67. package/src/uuid.test.ts +80 -0
  68. package/src/uuid.ts +15 -0
  69. package/test/fixtures/qr.json +625 -0
  70. package/test/glob.test.ts +11 -0
  71. package/test/global-roots.test.ts +62 -0
  72. package/test/global.test.ts +99 -0
  73. package/test/observability-otlp.test.ts +45 -0
  74. package/test/qr.test.ts +113 -0
  75. package/test/session-title-fallback.test.ts +49 -0
  76. package/tsconfig.build.json +12 -0
  77. package/tsconfig.dist.json +10 -0
  78. package/tsconfig.json +14 -0
package/src/patch.ts ADDED
@@ -0,0 +1,382 @@
1
+ export * as Patch from "./patch.js"
2
+
3
+ import { Result, Schema } from "effect"
4
+ import { Bom } from "./bom.js"
5
+
6
+ export class BoundaryError extends Schema.TaggedError<BoundaryError>()("Patch.BoundaryError", {
7
+ boundary: Schema.Literals(["first", "last"]),
8
+ }) {
9
+ override get message() {
10
+ return `The ${this.boundary} line of the patch must be '${this.boundary === "first" ? "*** Begin Patch" : "*** End Patch"}'`
11
+ }
12
+ }
13
+
14
+ export class InvalidHunkError extends Schema.TaggedError<InvalidHunkError>()("Patch.InvalidHunkError", {
15
+ line: Schema.String,
16
+ lineNumber: Schema.Number,
17
+ reason: Schema.optional(Schema.String),
18
+ }) {
19
+ override get message() {
20
+ if (this.reason) return `Invalid hunk at line ${this.lineNumber}: ${this.reason}`
21
+ 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}'`
22
+ }
23
+ }
24
+
25
+ export type ParseError = BoundaryError | InvalidHunkError
26
+
27
+ export type Hunk =
28
+ | { readonly type: "add"; readonly path: string; readonly contents: string }
29
+ | { readonly type: "delete"; readonly path: string }
30
+ | {
31
+ readonly type: "update"
32
+ readonly path: string
33
+ readonly movePath?: string
34
+ readonly chunks: ReadonlyArray<UpdateFileChunk>
35
+ }
36
+
37
+ export interface UpdateFileChunk {
38
+ readonly oldLines: ReadonlyArray<string>
39
+ readonly newLines: ReadonlyArray<string>
40
+ readonly changeContext?: string
41
+ readonly endOfFile?: boolean
42
+ }
43
+
44
+ export interface FileUpdate {
45
+ readonly content: string
46
+ readonly bom: boolean
47
+ }
48
+
49
+ export function parse(patchText: string): Result.Result<ReadonlyArray<Hunk>, ParseError> {
50
+ const lines = stripHeredoc(patchText.trim())
51
+ .split("\n")
52
+ .map((line) => (line.endsWith("\r") ? line.slice(0, -1) : line))
53
+ const begin = lines[0]?.trim() === "*** Begin Patch" ? 0 : -1
54
+ const end = lines.at(-1)?.trim() === "*** End Patch" ? lines.length - 1 : -1
55
+ if (begin === -1) return Result.fail(new BoundaryError({ boundary: "first" }))
56
+ if (end === -1 || begin >= end) return Result.fail(new BoundaryError({ boundary: "last" }))
57
+
58
+ const hunks: Hunk[] = []
59
+ let index = begin + 1
60
+ while (index < end) {
61
+ const line = lines[index]!
62
+ const header = line.trim()
63
+ if (
64
+ index === begin + 1 &&
65
+ header.startsWith("*** Environment ID:") &&
66
+ header.slice("*** Environment ID:".length).trim()
67
+ ) {
68
+ index++
69
+ continue
70
+ }
71
+ if (header.startsWith("*** Add File: ")) {
72
+ const path = header.slice("*** Add File: ".length).trim()
73
+ const parsed = parseAdd(lines, index + 1, end, path)
74
+ if ("error" in parsed) return Result.fail(parsed.error)
75
+ hunks.push({ type: "add", path, contents: parsed.content })
76
+ index = parsed.next
77
+ continue
78
+ }
79
+ if (header.startsWith("*** Delete File: ")) {
80
+ const path = header.slice("*** Delete File: ".length).trim()
81
+ const next = lines[index + 1]?.trim()
82
+ if (index + 1 < end && next !== undefined && !isBoundary(next)) {
83
+ if (next.startsWith("*** ")) {
84
+ return Result.fail(new InvalidHunkError({ line: next, lineNumber: index + 2 }))
85
+ }
86
+ return Result.fail(
87
+ new InvalidHunkError({
88
+ line: next,
89
+ lineNumber: index + 2,
90
+ reason: `Unexpected line after Delete File '${path}': '${next}'. Delete hunks do not contain body lines`,
91
+ }),
92
+ )
93
+ }
94
+ hunks.push({ type: "delete", path })
95
+ index++
96
+ continue
97
+ }
98
+ if (header.startsWith("*** Update File: ")) {
99
+ const path = header.slice("*** Update File: ".length).trim()
100
+ let next = index + 1
101
+ let movePath: string | undefined
102
+ while (lines[next]?.trimEnd() === "*** End of File") next++
103
+ const move = lines[next]?.trimEnd()
104
+ if (move === "*** Move to:" || move?.startsWith("*** Move to: ")) {
105
+ movePath = move.slice("*** Move to: ".length).trim()
106
+ if (!movePath) {
107
+ return Result.fail(
108
+ new InvalidHunkError({
109
+ line: lines[next]!.trim(),
110
+ lineNumber: next + 1,
111
+ reason: `Move destination for '${path}' must not be empty`,
112
+ }),
113
+ )
114
+ }
115
+ next++
116
+ }
117
+ const parsed = parseUpdate(lines, next, end, path, index)
118
+ if ("error" in parsed) return Result.fail(parsed.error)
119
+ hunks.push({ type: "update", path, movePath, chunks: parsed.chunks })
120
+ index = parsed.next
121
+ continue
122
+ }
123
+ return Result.fail(new InvalidHunkError({ line: header, lineNumber: index + 1 }))
124
+ }
125
+ return Result.succeed(hunks)
126
+ }
127
+
128
+ export function derive(path: string, chunks: ReadonlyArray<UpdateFileChunk>, original: string): FileUpdate {
129
+ const source = Bom.split(original)
130
+ const lines = source.text.split("\n")
131
+ if (lines.at(-1) === "") lines.pop()
132
+ const replacements = computeReplacements(lines, path, chunks)
133
+ for (const [start, remove, insert] of replacements.reverse()) lines.splice(start, remove, ...insert)
134
+ if (lines.at(-1) !== "") lines.push("")
135
+ const next = Bom.split(lines.join("\n"))
136
+ return { content: next.text, bom: source.bom || next.bom }
137
+ }
138
+
139
+ export function joinBom(text: string, bom: boolean) {
140
+ return Bom.join(text, bom)
141
+ }
142
+
143
+ function parseAdd(
144
+ lines: ReadonlyArray<string>,
145
+ start: number,
146
+ end: number,
147
+ path: string,
148
+ ): { content: string; next: number } | { error: InvalidHunkError } {
149
+ const content: string[] = []
150
+ let index = start
151
+ while (index < end && !isBoundary(lines[index]!.trim())) {
152
+ if (!lines[index]!.startsWith("+")) {
153
+ const line = lines[index]!.trim()
154
+ return {
155
+ error: new InvalidHunkError({
156
+ line,
157
+ lineNumber: index + 1,
158
+ reason: `Invalid Add File line for '${path}': expected a line starting with '+', got '${line}'`,
159
+ }),
160
+ }
161
+ }
162
+ // Every + line is a whole line of the file, as in Codex, so a final empty + line is a blank last line.
163
+ content.push(`${lines[index]!.slice(1)}\n`)
164
+ index++
165
+ }
166
+ return { content: content.join(""), next: index }
167
+ }
168
+
169
+ function parseUpdate(
170
+ lines: ReadonlyArray<string>,
171
+ start: number,
172
+ end: number,
173
+ path: string,
174
+ hunk: number,
175
+ ): { chunks: ReadonlyArray<UpdateFileChunk>; next: number } | { error: InvalidHunkError } {
176
+ const chunks: Array<{
177
+ oldLines: string[]
178
+ newLines: string[]
179
+ changeContext?: string
180
+ endOfFile?: boolean
181
+ }> = []
182
+ let index = start
183
+ let afterEndOfFile = false
184
+ while (index < end) {
185
+ const line = lines[index]!
186
+ const updateLine = line.trimEnd()
187
+ if (afterEndOfFile) {
188
+ if (updateLine === "") {
189
+ index++
190
+ continue
191
+ }
192
+ if (updateLine === "@@" || updateLine.startsWith("@@ ")) afterEndOfFile = false
193
+ else if (isBoundary(updateLine)) break
194
+ else {
195
+ return {
196
+ error: new InvalidHunkError({
197
+ line,
198
+ lineNumber: index + 1,
199
+ reason: `Expected update hunk to start with a @@ context marker, got: '${line}'`,
200
+ }),
201
+ }
202
+ }
203
+ }
204
+ if (updateLine === "*** End of File") {
205
+ const chunk = chunks.at(-1)
206
+ if (chunk && chunk.oldLines.length === 0 && chunk.newLines.length === 0) {
207
+ return {
208
+ error: new InvalidHunkError({
209
+ line: updateLine,
210
+ lineNumber: index + 1,
211
+ reason: "Update hunk does not contain any lines",
212
+ }),
213
+ }
214
+ }
215
+ if (chunk) {
216
+ chunk.endOfFile = true
217
+ afterEndOfFile = true
218
+ }
219
+ index++
220
+ continue
221
+ }
222
+ if (isBoundary(updateLine)) break
223
+ if (updateLine === "@@" || updateLine.startsWith("@@ ")) {
224
+ const previous = chunks.at(-1)
225
+ if (previous && previous.oldLines.length === 0 && previous.newLines.length === 0) {
226
+ return {
227
+ error: new InvalidHunkError({
228
+ line,
229
+ lineNumber: index + 1,
230
+ reason: `Unexpected line found in update hunk: '${line}'. Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)`,
231
+ }),
232
+ }
233
+ }
234
+ chunks.push({
235
+ oldLines: [],
236
+ newLines: [],
237
+ changeContext: updateLine === "@@" ? undefined : updateLine.slice("@@ ".length),
238
+ })
239
+ index++
240
+ continue
241
+ }
242
+ if (chunks.length === 0) chunks.push({ oldLines: [], newLines: [] })
243
+ const chunk = chunks.at(-1)!
244
+ if (line === "") {
245
+ chunk.oldLines.push("")
246
+ chunk.newLines.push("")
247
+ index++
248
+ continue
249
+ }
250
+ if (line.startsWith(" ")) {
251
+ chunk.oldLines.push(line.slice(1))
252
+ chunk.newLines.push(line.slice(1))
253
+ index++
254
+ continue
255
+ }
256
+ if (line.startsWith("-")) {
257
+ chunk.oldLines.push(line.slice(1))
258
+ index++
259
+ continue
260
+ }
261
+ if (line.startsWith("+")) {
262
+ chunk.newLines.push(line.slice(1))
263
+ index++
264
+ continue
265
+ }
266
+ const populated = chunk.oldLines.length > 0 || chunk.newLines.length > 0
267
+ return {
268
+ error: new InvalidHunkError({
269
+ line,
270
+ lineNumber: index + 1,
271
+ reason: populated
272
+ ? `Expected update hunk to start with a @@ context marker, got: '${line}'`
273
+ : `Unexpected line found in update hunk: '${line}'. Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)`,
274
+ }),
275
+ }
276
+ }
277
+ if (chunks.length === 0) {
278
+ return {
279
+ error: new InvalidHunkError({
280
+ line: lines[hunk]!.trim(),
281
+ lineNumber: hunk + 1,
282
+ reason: `Update file hunk for path '${path}' is empty`,
283
+ }),
284
+ }
285
+ }
286
+ const last = chunks.at(-1)!
287
+ if (last.oldLines.length === 0 && last.newLines.length === 0) {
288
+ const line = lines[index]!.trim()
289
+ return {
290
+ error: new InvalidHunkError({
291
+ line,
292
+ lineNumber: index + 1,
293
+ reason:
294
+ line === "*** End Patch"
295
+ ? "Update hunk does not contain any lines"
296
+ : `Unexpected line found in update hunk: '${line}'. Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)`,
297
+ }),
298
+ }
299
+ }
300
+ return { chunks, next: index }
301
+ }
302
+
303
+ function isBoundary(line: string) {
304
+ return (
305
+ line === "*** End Patch" ||
306
+ line.startsWith("*** Add File: ") ||
307
+ line.startsWith("*** Delete File: ") ||
308
+ line.startsWith("*** Update File: ")
309
+ )
310
+ }
311
+
312
+ function computeReplacements(lines: ReadonlyArray<string>, path: string, chunks: ReadonlyArray<UpdateFileChunk>) {
313
+ const replacements: Array<readonly [start: number, remove: number, insert: ReadonlyArray<string>]> = []
314
+ let lineIndex = 0
315
+ for (const chunk of chunks) {
316
+ if (chunk.changeContext) {
317
+ const context = seek(lines, [chunk.changeContext], lineIndex)
318
+ if (context === -1) throw new Error(`Failed to find context '${chunk.changeContext}' in ${path}`)
319
+ lineIndex = context + 1
320
+ }
321
+ if (chunk.oldLines.length === 0) {
322
+ replacements.push([lines.length, 0, chunk.newLines])
323
+ continue
324
+ }
325
+ let oldLines = chunk.oldLines
326
+ let newLines = chunk.newLines
327
+ let found = seek(lines, oldLines, lineIndex, chunk.endOfFile)
328
+ if (found === -1 && oldLines.at(-1) === "") {
329
+ oldLines = oldLines.slice(0, -1)
330
+ if (newLines.at(-1) === "") newLines = newLines.slice(0, -1)
331
+ found = seek(lines, oldLines, lineIndex, chunk.endOfFile)
332
+ }
333
+ if (found === -1 && chunk.oldLines.every((line) => line === "")) {
334
+ const expected =
335
+ chunk.oldLines.length === 1 ? "an expected blank line" : `${chunk.oldLines.length} consecutive blank lines`
336
+ throw new Error(`Failed to find ${expected} in ${path}`)
337
+ }
338
+ if (found === -1) throw new Error(`Failed to find expected lines in ${path}:\n${chunk.oldLines.join("\n")}`)
339
+ replacements.push([found, oldLines.length, newLines])
340
+ lineIndex = found + oldLines.length
341
+ }
342
+ return replacements.sort((left, right) => left[0] - right[0])
343
+ }
344
+
345
+ function seek(lines: ReadonlyArray<string>, pattern: ReadonlyArray<string>, start: number, eof = false) {
346
+ if (pattern.length === 0) return -1
347
+ if (eof) {
348
+ const offset = lines.length - pattern.length
349
+ if (offset < start) return -1
350
+ for (const compare of [exact, rstrip, trim, normalized]) {
351
+ if (matches(lines, pattern, offset, compare)) return offset
352
+ }
353
+ return -1
354
+ }
355
+ for (const compare of [exact, rstrip, trim, normalized]) {
356
+ for (let offset = start; offset <= lines.length - pattern.length; offset++) {
357
+ if (matches(lines, pattern, offset, compare)) return offset
358
+ }
359
+ }
360
+ return -1
361
+ }
362
+
363
+ function matches(
364
+ lines: ReadonlyArray<string>,
365
+ pattern: ReadonlyArray<string>,
366
+ offset: number,
367
+ compare: (left: string, right: string) => boolean,
368
+ ) {
369
+ return pattern.every((line, index) => compare(lines[offset + index]!, line))
370
+ }
371
+
372
+ const exact = (left: string, right: string) => left === right
373
+ const rstrip = (left: string, right: string) => left.trimEnd() === right.trimEnd()
374
+ const trim = (left: string, right: string) => left.trim() === right.trim()
375
+ const normalized = (left: string, right: string) => normalize(left.trim()) === normalize(right.trim())
376
+ const normalize = (value: string) =>
377
+ value
378
+ .replace(/[‘’‚‛]/g, "'")
379
+ .replace(/[“”„‟]/g, '"')
380
+ .replace(/[‐‑‒–—―−]/g, "-")
381
+ .replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g, " ")
382
+ const stripHeredoc = (input: string) => input.match(/^(?:cat\s+)?<<(['"]?)(\w+)\1\s*\n([\s\S]*?)\n\2\s*$/)?.[3] ?? input
@@ -0,0 +1,89 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import { encodeFilePath, getDirectory, getFilename, getFilenameTruncated, truncateMiddle } from "./path.js"
3
+
4
+ describe("client paths", () => {
5
+ test("reads POSIX and Windows paths with the same rules", () => {
6
+ expect(getFilename("/repo/src/index.ts")).toBe("index.ts")
7
+ expect(getFilename("C:\\repo\\src\\index.ts\\")).toBe("index.ts")
8
+ expect(getDirectory("/repo/src/index.ts")).toBe("/repo/src/")
9
+ expect(getDirectory("C:\\repo\\src\\index.ts")).toBe("C:/repo/src/")
10
+ })
11
+
12
+ test("preserves root, UNC, mixed, and single-segment behavior", () => {
13
+ expect(getFilename("\\\\server\\share\\file")).toBe("file")
14
+ expect(getDirectory("\\\\server\\share\\file")).toBe("//server/share/")
15
+ expect(getDirectory("C:\\repo/src\\file")).toBe("C:/repo/src/")
16
+ expect(getDirectory("file")).toBe("/")
17
+ expect(getFilename(undefined)).toBe("")
18
+ expect(getDirectory("")).toBe("")
19
+ })
20
+
21
+ test.each([
22
+ ["/repo/src/index.ts///", "index.ts"],
23
+ ["C:\\repo\\src\\index.ts", "index.ts"],
24
+ ["C:\\repo/src\\file", "file"],
25
+ ["C:/repo\\src/file/\\", "file"],
26
+ ["/", ""],
27
+ ["\\", ""],
28
+ ["/\\/\\", ""],
29
+ ["C:\\", "C:"],
30
+ ["file", "file"],
31
+ ["", ""],
32
+ ])("reads the filename from %j", (path, filename) => {
33
+ expect(getFilename(path)).toBe(filename)
34
+ })
35
+
36
+ test("keeps filename truncation stable", () => {
37
+ expect(getFilenameTruncated("/repo/long-component-name.tsx", 16)).toBe("long-compon….tsx")
38
+ expect(truncateMiddle("abcdefghijklmnop", 9)).toBe("abcd…mnop")
39
+ })
40
+
41
+ test("truncates in the middle without overflowing small widths", () => {
42
+ expect(truncateMiddle("abcdefghij", 0)).toBe("")
43
+ expect(truncateMiddle("abcdefghij", 1)).toBe("…")
44
+ expect(truncateMiddle("abcdefghij", 2)).toBe("a…")
45
+ expect(truncateMiddle("abcdefghij", 3)).toBe("a…j")
46
+ expect(truncateMiddle("abcdefghij", 4)).toBe("ab…j")
47
+ expect(truncateMiddle("abcd", 4)).toBe("abcd")
48
+ expect(truncateMiddle("abcd", 10)).toBe("abcd")
49
+ expect(truncateMiddle("a", 1)).toBe("a")
50
+ })
51
+ })
52
+
53
+ describe("encodeFilePath", () => {
54
+ const rows = [
55
+ ["/home/user/project/README.md", "/home/user/project/README.md"],
56
+ ["/home/user/file#name with spaces.txt", "/home/user/file%23name%20with%20spaces.txt"],
57
+ ["/path/to/file#with?special%chars&more.txt", "/path/to/file%23with%3Fspecial%25chars%26more.txt"],
58
+ ["/path/to/file?name.txt", "/path/to/file%3Fname.txt"],
59
+ ["/path/to/file%name.txt", "/path/to/file%25name.txt"],
60
+ ["/home/user/文档/README.md", "/home/user/%E6%96%87%E6%A1%A3/README.md"],
61
+ ["/", "/"],
62
+ ["", ""],
63
+ ["//path//to///file.txt", "//path//to///file.txt"],
64
+ ["src/components/App.tsx", "src/components/App.tsx"],
65
+ ["src\\components\\App.tsx", "src/components/App.tsx"],
66
+ ["D:\\dev\\projects\\opencode\\README.bs.md", "/D:/dev/projects/opencode/README.bs.md"],
67
+ ["D:\\dev\\projects\\opencode/README.bs.md", "/D:/dev/projects/opencode/README.bs.md"],
68
+ ["C:\\Program Files\\MyApp\\file with spaces.txt", "/C:/Program%20Files/MyApp/file%20with%20spaces.txt"],
69
+ ["D:\\projects\\file#name with ?marks.txt", "/D:/projects/file%23name%20with%20%3Fmarks.txt"],
70
+ ["C:\\", "/C:/"],
71
+ ["c:\\users\\test\\file.txt", "/c:/users/test/file.txt"],
72
+ ["D:", "/D:"],
73
+ ["C:\\Users\\test\\", "/C:/Users/test/"],
74
+ ["C:\\Users\\..\\test\\.\\file.txt", "/C:/Users/../test/./file.txt"],
75
+ ["/D:/path/file.txt", "/D:/path/file.txt"],
76
+ ] as const
77
+
78
+ test.each(rows)("encodes %p as %p", (input, expected) => {
79
+ expect(encodeFilePath(input)).toBe(expected)
80
+ })
81
+
82
+ test("every encoded path forms a file URL that keeps its query", () => {
83
+ rows.forEach(([input]) => {
84
+ const url = new URL(`file://${encodeFilePath(input)}?start=10`)
85
+ expect(url.protocol).toBe("file:")
86
+ expect(url.searchParams.get("start")).toBe("10")
87
+ })
88
+ })
89
+ })
package/src/path.ts ADDED
@@ -0,0 +1,149 @@
1
+ export function getFilename(path: string | undefined) {
2
+ if (!path) return ""
3
+ const trimmed = path.replace(/[/\\]+$/, "")
4
+ const index = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"))
5
+ return trimmed.slice(index + 1)
6
+ }
7
+
8
+ export function getDirectory(path: string | undefined) {
9
+ if (!path) return ""
10
+ const trimmed = path.replace(/[/\\]+$/, "")
11
+ const parts = trimmed.split(/[/\\]/)
12
+ return parts.slice(0, parts.length - 1).join("/") + "/"
13
+ }
14
+
15
+ export function getFilenameTruncated(path: string | undefined, maxLength = 20) {
16
+ const filename = getFilename(path)
17
+ if (filename.length <= maxLength) return filename
18
+ const lastDot = filename.lastIndexOf(".")
19
+ const extension = lastDot <= 0 ? "" : filename.slice(lastDot)
20
+ const available = maxLength - extension.length - 1
21
+ if (available <= 0) return filename.slice(0, maxLength - 1) + "…"
22
+ return filename.slice(0, available) + "…" + extension
23
+ }
24
+
25
+ export function truncateMiddle(text: string, maxLength = 20) {
26
+ if (maxLength <= 0) return ""
27
+ if (text.length <= maxLength) return text
28
+ const available = maxLength - 1
29
+ const start = Math.ceil(available / 2)
30
+ const end = Math.floor(available / 2)
31
+ if (end <= 0) return text.slice(0, start) + "…"
32
+ return text.slice(0, start) + "…" + text.slice(-end)
33
+ }
34
+
35
+ const isDrive = (value: string) => {
36
+ if (value.length !== 2) return false
37
+ const code = value.charCodeAt(0)
38
+ return value[1] === ":" && ((code >= 65 && code <= 90) || (code >= 97 && code <= 122))
39
+ }
40
+
41
+ const trimTrailingSlashes = (value: string) => {
42
+ for (let i = value.length - 1; i >= 0; i--) {
43
+ if (value[i] !== "/") return value.slice(0, i + 1)
44
+ }
45
+ return ""
46
+ }
47
+
48
+ const isWindowsPath = (value: string) => value[1] === ":" || value.startsWith("\\\\")
49
+
50
+ /** A comparable form of a directory path: forward slashes for Windows paths, no trailing slash except on roots. */
51
+ export function comparablePath(path: string) {
52
+ const value = isWindowsPath(path) ? path.replaceAll("\\", "/") : path
53
+ const trimmed = trimTrailingSlashes(value)
54
+ if (!trimmed && value.startsWith("/")) return "/"
55
+ if (isDrive(trimmed)) return `${trimmed}/`
56
+ return trimmed
57
+ }
58
+
59
+ /** `child` is `parent` or inside it. Windows drive and UNC paths compare case-insensitively. */
60
+ export function containsDirectory(parent: string, child: string) {
61
+ const normalize = (value: string) => {
62
+ const key = comparablePath(value)
63
+ return /^[a-z]:\//i.test(key) || key.startsWith("//") ? key.toLowerCase() : key
64
+ }
65
+ const root = normalize(parent)
66
+ const target = normalize(child)
67
+ return target === root || target.startsWith(root.endsWith("/") ? root : `${root}/`)
68
+ }
69
+
70
+ export function sameDirectory(a: string, b: string) {
71
+ return containsDirectory(a, b) && containsDirectory(b, a)
72
+ }
73
+
74
+ export function encodeFilePath(filepath: string): string {
75
+ // Normalize Windows paths: convert backslashes to forward slashes
76
+ const normalized = filepath.replace(/\\/g, "/")
77
+
78
+ // Handle Windows absolute paths (D:/path -> /D:/path for proper file:// URLs)
79
+ const rooted = /^[A-Za-z]:/.test(normalized) ? "/" + normalized : normalized
80
+
81
+ // Encode each path segment (preserving forward slashes as path separators)
82
+ // Keep the colon in Windows drive letters (`/C:/...`) so downstream file URL parsers
83
+ // can reliably detect drives.
84
+ return rooted
85
+ .split("/")
86
+ .map((segment, index) => {
87
+ if (index === 1 && /^[A-Za-z]:$/.test(segment)) return segment
88
+ return encodeURIComponent(segment)
89
+ })
90
+ .join("/")
91
+ }
92
+
93
+ const MAX_LINE_NUMBER = 1_000_000
94
+
95
+ const lineHashPattern = /^#L(\d+)(?:C\d+)?(?:-L?(\d+)(?:C\d+)?)?$/i
96
+
97
+ const lineHashSuffixPattern = /^(.*?)#L(\d+)(?:C\d+)?(?:-L?(\d+)(?:C\d+)?)?$/i
98
+
99
+ const lineColonSuffixPattern = /^(.*?):(\d+)(?::\d+)?(?:-(\d+)(?::\d+)?)?:?$/
100
+
101
+ function toLineRange(first: number, second: number) {
102
+ if (
103
+ !Number.isSafeInteger(first) ||
104
+ !Number.isSafeInteger(second) ||
105
+ first < 1 ||
106
+ second < 1 ||
107
+ first > MAX_LINE_NUMBER ||
108
+ second > MAX_LINE_NUMBER
109
+ ) {
110
+ return undefined
111
+ }
112
+
113
+ return {
114
+ start: Math.min(first, second),
115
+ end: Math.max(first, second),
116
+ }
117
+ }
118
+
119
+ export function isLineRangeHash(hash: string) {
120
+ return lineHashPattern.test(hash)
121
+ }
122
+
123
+ export function parsePathLineSuffix(input: string) {
124
+ const hashMatch = input.match(lineHashSuffixPattern)
125
+
126
+ if (hashMatch) {
127
+ const first = Number(hashMatch[2])
128
+ const second = hashMatch[3] ? Number(hashMatch[3]) : first
129
+
130
+ return {
131
+ path: hashMatch[1] ?? "",
132
+ selection: toLineRange(first, second),
133
+ }
134
+ }
135
+
136
+ const colonMatch = input.match(lineColonSuffixPattern)
137
+
138
+ if (colonMatch && !/^[a-z]:?$/i.test(colonMatch[1] ?? "")) {
139
+ const first = Number(colonMatch[2])
140
+ const second = colonMatch[3] ? Number(colonMatch[3]) : first
141
+
142
+ return {
143
+ path: colonMatch[1] ?? "",
144
+ selection: toLineRange(first, second),
145
+ }
146
+ }
147
+
148
+ return { path: input, selection: undefined }
149
+ }
@@ -0,0 +1,38 @@
1
+ import { expect, test } from "bun:test"
2
+
3
+ // Windows does not deliver POSIX user signals.
4
+ test.skipIf(process.platform === "win32")(
5
+ "an installed signal survives absent and removed subscribers",
6
+ async () => {
7
+ const child = Bun.spawn(
8
+ [
9
+ process.execPath,
10
+ "-e",
11
+ `
12
+ import { ProcessSignal } from ${JSON.stringify(new URL("./process-signal.ts", import.meta.url).pathname)};
13
+ const deadline = setTimeout(() => process.exit(2), 10000);
14
+ let ignored = 0;
15
+ ProcessSignal.install("SIGUSR2", () => {
16
+ console.log("ignored");
17
+ if (++ignored === 2) {
18
+ clearTimeout(deadline);
19
+ process.exit(0);
20
+ }
21
+ const remove = ProcessSignal.subscribe("SIGUSR2", () => {
22
+ console.log("captured");
23
+ remove();
24
+ process.kill(process.pid, "SIGUSR2");
25
+ });
26
+ process.kill(process.pid, "SIGUSR2");
27
+ });
28
+ process.kill(process.pid, "SIGUSR2");
29
+ `,
30
+ ],
31
+ { stdout: "pipe", stderr: "pipe" },
32
+ )
33
+ expect(await new Response(child.stderr).text()).toBe("")
34
+ expect(await child.exited).toBe(0)
35
+ expect((await new Response(child.stdout).text()).trim().split("\n")).toEqual(["ignored", "captured", "ignored"])
36
+ },
37
+ 15000,
38
+ )
@@ -0,0 +1,23 @@
1
+ export * as ProcessSignal from "./process-signal.js"
2
+
3
+ const handlers = new Map<NodeJS.Signals, Set<() => void>>()
4
+
5
+ /** Install once at process startup. Removing subscribers never restores the signal's default action. */
6
+ export function install(signal: NodeJS.Signals, unavailable: () => void) {
7
+ if (handlers.has(signal)) return
8
+ const listeners = new Set<() => void>()
9
+ handlers.set(signal, listeners)
10
+ process.on(signal, () => {
11
+ if (!listeners.size) return unavailable()
12
+ listeners.forEach((listener) => listener())
13
+ })
14
+ }
15
+
16
+ /** Subscribe only to an installed signal. The returned cleanup removes this subscriber, not the process handler. */
17
+ export function subscribe(signal: NodeJS.Signals, listener: () => void) {
18
+ const listeners = handlers.get(signal)
19
+ listeners?.add(listener)
20
+ return () => {
21
+ listeners?.delete(listener)
22
+ }
23
+ }