@zyro-sec/util 1.0.2 → 1.0.4

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 -155
  2. package/package.json +1 -1
  3. package/script/build.ts +9 -9
  4. package/script/pack.ts +5 -5
  5. package/src/abort.ts +9 -9
  6. package/src/activity-calendar.ts +50 -50
  7. package/src/artifact.ts +95 -95
  8. package/src/base64.ts +29 -29
  9. package/src/binary.ts +30 -30
  10. package/src/bom.ts +46 -46
  11. package/src/cross-spawn-spawner.ts +694 -694
  12. package/src/duration.ts +22 -22
  13. package/src/effect/app-node-platform.ts +40 -40
  14. package/src/effect/app-node.ts +14 -14
  15. package/src/effect/layer-node.ts +360 -360
  16. package/src/effect-flock.ts +313 -313
  17. package/src/encode.ts +39 -39
  18. package/src/execute-output.ts +23 -23
  19. package/src/flock.ts +346 -346
  20. package/src/fs-util.ts +271 -271
  21. package/src/glob.ts +38 -38
  22. package/src/global-roots.ts +19 -19
  23. package/src/global-roots.workerd.ts +16 -16
  24. package/src/global.ts +88 -88
  25. package/src/hash.ts +11 -11
  26. package/src/heap-snapshot.ts +44 -44
  27. package/src/no-timeout-fetch.ts +5 -5
  28. package/src/npm-config.ts +41 -41
  29. package/src/npm.ts +557 -557
  30. package/src/observability/logging.ts +179 -179
  31. package/src/observability/otlp.ts +109 -109
  32. package/src/observability/shared.ts +8 -8
  33. package/src/observability.ts +60 -60
  34. package/src/open.ts +12 -12
  35. package/src/patch.ts +382 -382
  36. package/src/path.ts +149 -149
  37. package/src/process-signal.ts +23 -23
  38. package/src/process.ts +270 -270
  39. package/src/qr.ts +323 -323
  40. package/src/record.ts +3 -3
  41. package/src/retry.ts +51 -51
  42. package/src/runtime/import.bun.ts +10 -10
  43. package/src/runtime/import.node.ts +61 -61
  44. package/src/runtime/import.workerd.ts +9 -9
  45. package/src/runtime-import.ts +1 -1
  46. package/src/session-mention.ts +24 -24
  47. package/src/session-title-fallback.ts +36 -36
  48. package/src/session-turn.ts +82 -82
  49. package/src/teardown.ts +19 -19
  50. package/src/text-boundary.ts +36 -36
  51. package/src/uuid.ts +15 -15
  52. package/test/fixtures/qr.json +625 -625
  53. package/tsconfig.build.json +12 -12
  54. package/tsconfig.dist.json +10 -10
  55. package/tsconfig.json +14 -14
  56. package/src/abort.test.ts +0 -16
  57. package/src/activity-calendar.test.ts +0 -136
  58. package/src/artifact.test.ts +0 -29
  59. package/src/base64.test.ts +0 -12
  60. package/src/binary.test.ts +0 -19
  61. package/src/bom.test.ts +0 -21
  62. package/src/encode.test.ts +0 -32
  63. package/src/execute-output.test.ts +0 -36
  64. package/src/no-timeout-fetch.test.ts +0 -33
  65. package/src/open.test.ts +0 -16
  66. package/src/path.test.ts +0 -89
  67. package/src/process-signal.test.ts +0 -38
  68. package/src/retry.test.ts +0 -87
  69. package/src/session-mention.test.ts +0 -19
  70. package/src/session-turn.test.ts +0 -131
  71. package/src/text-boundary.test.ts +0 -39
  72. package/src/uuid.test.ts +0 -80
  73. package/test/glob.test.ts +0 -11
  74. package/test/global-roots.test.ts +0 -62
  75. package/test/global.test.ts +0 -99
  76. package/test/observability-otlp.test.ts +0 -45
  77. package/test/qr.test.ts +0 -113
  78. package/test/session-title-fallback.test.ts +0 -49
@@ -1,12 +1,12 @@
1
- {
2
- "$schema": "https://json.schemastore.org/tsconfig",
3
- "extends": "./tsconfig.json",
4
- "compilerOptions": {
5
- "rootDir": "src",
6
- "outDir": "dist",
7
- "noEmit": false,
8
- "declaration": true
9
- },
10
- "include": ["src"],
11
- "exclude": ["src/**/*.test.ts"]
12
- }
1
+ {
2
+ "$schema": "https://json.schemastore.org/tsconfig",
3
+ "extends": "./tsconfig.json",
4
+ "compilerOptions": {
5
+ "rootDir": "src",
6
+ "outDir": "dist",
7
+ "noEmit": false,
8
+ "declaration": true
9
+ },
10
+ "include": ["src"],
11
+ "exclude": ["src/**/*.test.ts"]
12
+ }
@@ -1,10 +1,10 @@
1
- {
2
- "extends": "./tsconfig.json",
3
- "compilerOptions": {
4
- "paths": {
5
- "@zyro-sec/util/effect/layer-node": ["./dist/effect/layer-node.d.ts"],
6
- "@zyro-sec/util/effect/app-node": ["./dist/effect/app-node.d.ts"]
7
- }
8
- },
9
- "include": ["../core/test/effect/layer-node/layer-node-types.test.ts"]
10
- }
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "paths": {
5
+ "@zyro-sec/util/effect/layer-node": ["./dist/effect/layer-node.d.ts"],
6
+ "@zyro-sec/util/effect/app-node": ["./dist/effect/app-node.d.ts"]
7
+ }
8
+ },
9
+ "include": ["../core/test/effect/layer-node/layer-node-types.test.ts"]
10
+ }
package/tsconfig.json CHANGED
@@ -1,14 +1,14 @@
1
- {
2
- "$schema": "https://json.schemastore.org/tsconfig",
3
- "extends": "@tsconfig/bun/tsconfig.json",
4
- "compilerOptions": {
5
- "types": ["bun"],
6
- "noUnusedLocals": true,
7
- "lib": ["ESNext", "DOM", "DOM.Iterable"],
8
- "module": "NodeNext",
9
- "moduleResolution": "NodeNext",
10
- "allowImportingTsExtensions": false,
11
- "allowJs": false,
12
- "noUncheckedIndexedAccess": false
13
- }
14
- }
1
+ {
2
+ "$schema": "https://json.schemastore.org/tsconfig",
3
+ "extends": "@tsconfig/bun/tsconfig.json",
4
+ "compilerOptions": {
5
+ "types": ["bun"],
6
+ "noUnusedLocals": true,
7
+ "lib": ["ESNext", "DOM", "DOM.Iterable"],
8
+ "module": "NodeNext",
9
+ "moduleResolution": "NodeNext",
10
+ "allowImportingTsExtensions": false,
11
+ "allowJs": false,
12
+ "noUncheckedIndexedAccess": false
13
+ }
14
+ }
package/src/abort.test.ts DELETED
@@ -1,16 +0,0 @@
1
- import { expect, test } from "bun:test"
2
- import { abort } from "./abort.js"
3
-
4
- test("aborts with an AbortError that does not record the caller's stack", () => {
5
- const controller = new AbortController()
6
- function disposeComponent() {
7
- abort(controller)
8
- }
9
-
10
- disposeComponent()
11
-
12
- expect(controller.signal.aborted).toBe(true)
13
- expect(controller.signal.reason).toBeInstanceOf(DOMException)
14
- expect(controller.signal.reason.name).toBe("AbortError")
15
- expect(String(controller.signal.reason.stack)).not.toContain("disposeComponent")
16
- })
@@ -1,136 +0,0 @@
1
- import { describe, expect, test } from "bun:test"
2
- import { activityCalendar } from "./activity-calendar.js"
3
-
4
- const input = {
5
- from: new Date(2026, 0, 1).getTime(),
6
- to: new Date(2026, 0, 8).getTime(),
7
- maxWeeks: 53,
8
- activity: [
9
- { date: "2026-01-01", steps: 1 },
10
- { date: "2026-01-02", steps: 50 },
11
- ],
12
- }
13
-
14
- describe("activity calendar", () => {
15
- test("aligns Monday-first weeks and excludes cells outside the end-exclusive range", () => {
16
- const calendar = activityCalendar(input)
17
- expect(calendar.clipped).toBe(false)
18
- expect(calendar.weeks).toHaveLength(2)
19
- expect(calendar.weeks[0][0]).toEqual({ date: "2025-12-29", steps: 0, level: -1 })
20
- expect(calendar.weeks[0][3]).toEqual({ date: "2026-01-01", steps: 1, level: 2 })
21
- expect(calendar.weeks[0][4]).toEqual({ date: "2026-01-02", steps: 50, level: 4 })
22
- expect(calendar.weeks[1][2]).toEqual({ date: "2026-01-07", steps: 0, level: 0 })
23
- expect(calendar.weeks[1][3].level).toBe(-1)
24
- expect(calendar.months).toEqual([{ week: 0, label: "Jan", span: 2 }])
25
- })
26
-
27
- test("clips to the latest weeks and keeps empty days distinct from out-of-range cells", () => {
28
- const calendar = activityCalendar({ ...input, activity: [], maxWeeks: 1 })
29
- expect(calendar.clipped).toBe(true)
30
- expect(calendar.weeks).toHaveLength(1)
31
- expect(calendar.weeks[0][0]).toEqual({ date: "2026-01-05", steps: 0, level: 0 })
32
- expect(calendar.weeks[0][3].level).toBe(-1)
33
- })
34
-
35
- test("caps long histories at 53 weeks", () => {
36
- const calendar = activityCalendar({ ...input, from: new Date(2020, 0, 1).getTime(), maxWeeks: 200 })
37
- expect(calendar.clipped).toBe(true)
38
- expect(calendar.weeks).toHaveLength(53)
39
- expect(calendar.weeks.at(-1)?.[2].date).toBe("2026-01-07")
40
- expect(calendar.months.reduce((sum, month) => sum + month.span, 0)).toBe(53)
41
- })
42
-
43
- test("returns month positions and spans for partial first and last months", () => {
44
- const calendar = activityCalendar({
45
- ...input,
46
- from: new Date(2026, 3, 29).getTime(),
47
- to: new Date(2026, 4, 20).getTime(),
48
- })
49
- expect(calendar.months).toEqual([
50
- { week: 0, label: "Apr", span: 1 },
51
- { week: 1, label: "May", span: 3 },
52
- ])
53
- const partial = activityCalendar({
54
- ...input,
55
- from: new Date(2026, 3, 1).getTime(),
56
- to: new Date(2026, 3, 2).getTime(),
57
- })
58
- expect(partial.months).toEqual([{ week: 0, label: "Apr", span: 1 }])
59
- })
60
-
61
- test("places month labels across a year boundary", () => {
62
- const calendar = activityCalendar({
63
- ...input,
64
- from: new Date(2025, 11, 22).getTime(),
65
- to: new Date(2026, 0, 12).getTime(),
66
- })
67
- expect(calendar.months).toEqual([
68
- { week: 0, label: "Dec", span: 1 },
69
- { week: 1, label: "Jan", span: 2 },
70
- ])
71
- })
72
-
73
- test("keeps exactly seven distinct cells per week across DST and leap days", () => {
74
- const calendar = activityCalendar({
75
- from: new Date(2024, 1, 26).getTime(),
76
- to: new Date(2024, 2, 12).getTime(),
77
- maxWeeks: 53,
78
- activity: [
79
- { date: "2024-02-29", steps: 1 },
80
- { date: "2024-03-10", steps: 1 },
81
- ],
82
- })
83
- expect(calendar.weeks).toHaveLength(3)
84
- expect(
85
- calendar.weeks
86
- .flat()
87
- .filter((day) => day.steps > 0)
88
- .map((day) => day.date),
89
- ).toEqual(["2024-02-29", "2024-03-10"])
90
- expect(new Set(calendar.weeks.flat().map((day) => day.date)).size).toBe(21)
91
- })
92
-
93
- test("uses the highest intensity for a single distinct positive count", () => {
94
- const calendar = activityCalendar({ ...input, activity: input.activity.map((day) => ({ ...day, steps: 10 })) })
95
- expect(
96
- calendar.weeks
97
- .flat()
98
- .filter((day) => day.steps > 0)
99
- .map((day) => day.level),
100
- ).toEqual([4, 4])
101
- })
102
-
103
- test("ranks distinct activity counts in four levels", () => {
104
- const calendar = activityCalendar({
105
- ...input,
106
- to: new Date(2026, 0, 10).getTime(),
107
- activity: Array.from({ length: 8 }, (_, index) => ({ date: `2026-01-0${index + 1}`, steps: index + 1 })),
108
- })
109
- expect(
110
- calendar.weeks
111
- .flat()
112
- .filter((day) => day.steps > 0)
113
- .map((day) => day.level),
114
- ).toEqual([1, 1, 2, 2, 3, 3, 4, 4])
115
- })
116
-
117
- test("keeps intensity relative to the requested range when older weeks are clipped", () => {
118
- const calendar = activityCalendar({
119
- ...input,
120
- maxWeeks: 1,
121
- activity: [
122
- { date: "2026-01-01", steps: 50 },
123
- { date: "2026-01-05", steps: 1 },
124
- ],
125
- })
126
- expect(calendar.weeks[0][0].level).toBe(2)
127
- })
128
-
129
- test("returns an empty calendar for an empty range", () => {
130
- expect(activityCalendar({ ...input, to: input.from, activity: [] })).toEqual({
131
- weeks: [],
132
- months: [],
133
- clipped: false,
134
- })
135
- })
136
- })
@@ -1,29 +0,0 @@
1
- import { describe, expect, test } from "bun:test"
2
- import { artifactKind } from "./artifact.js"
3
-
4
- describe("artifactKind", () => {
5
- test.each([
6
- ["shot.PNG", "image"],
7
- ["logo.svg", "svg"],
8
- ["song.mp3", "audio"],
9
- ["demo.mp4", "video"],
10
- ["clip.webm", "video"],
11
- ["paper.pdf", "pdf"],
12
- ["out/index.html", "html"],
13
- ["README.md", "markdown"],
14
- ["flow.mmd", "mermaid"],
15
- ["data.csv", "table"],
16
- ["data.tsv", "table"],
17
- ["Inter.woff2", "font"],
18
- ["report.docx", "document"],
19
- ["budget.XLSX", "spreadsheet"],
20
- ["deck.pptx", "presentation"],
21
- ["legacy.doc", "text"],
22
- ["src/app.ts", "text"],
23
- ["Makefile", "text"],
24
- [".env", "text"],
25
- ["archive.tar.gz", "text"],
26
- ] as const)("classifies %s as %s", (path, kind) => {
27
- expect(artifactKind(path)).toBe(kind)
28
- })
29
- })
@@ -1,12 +0,0 @@
1
- import { describe, expect, test } from "bun:test"
2
- import { base64ToBytes, bytesToBase64 } from "./base64.js"
3
-
4
- describe("base64", () => {
5
- test("encodes as standard base64 and decodes back to the same bytes", () => {
6
- const bytes = Uint8Array.from({ length: 70_000 }, (_, index) => index % 256)
7
- const encoded = bytesToBase64(bytes)
8
-
9
- expect(encoded).toBe(Buffer.from(bytes).toString("base64"))
10
- expect(base64ToBytes(encoded)).toEqual(bytes)
11
- })
12
- })
@@ -1,19 +0,0 @@
1
- import { describe, expect, test } from "bun:test"
2
- import { Binary } from "./binary.js"
3
-
4
- describe("binary search", () => {
5
- test("finds sorted values and their insertion points", () => {
6
- const values = [{ id: "a" }, { id: "c" }, { id: "e" }]
7
- expect(Binary.search(values, "c", (item) => item.id)).toEqual({ found: true, index: 1 })
8
- expect(Binary.search(values, "d", (item) => item.id)).toEqual({ found: false, index: 2 })
9
- expect(Binary.search(values, "0", (item) => item.id)).toEqual({ found: false, index: 0 })
10
- })
11
-
12
- test("inserts before the first matching sorted value", () => {
13
- const values = [{ id: "a" }, { id: "c" }, { id: "c" }, { id: "e" }]
14
- const item = { id: "c" }
15
-
16
- expect(Binary.insert(values, item, (value) => value.id)).toBe(values)
17
- expect(values).toEqual([{ id: "a" }, item, { id: "c" }, { id: "c" }, { id: "e" }])
18
- })
19
- })
package/src/bom.test.ts DELETED
@@ -1,21 +0,0 @@
1
- import { expect, test } from "bun:test"
2
- import { Bom } from "./bom.js"
3
-
4
- test.each([
5
- { prefix: "", bom: false, expected: undefined },
6
- { prefix: "", bom: true, expected: "\uFEFF" },
7
- { prefix: "\uFEFF", bom: false, expected: "" },
8
- { prefix: "\uFEFF", bom: true, expected: undefined },
9
- { prefix: "\uFEFF\uFEFF", bom: false, expected: "" },
10
- { prefix: "\uFEFF\uFEFF", bom: true, expected: "\uFEFF" },
11
- ])("syncBytes(%j)", (row) => {
12
- const encoder = new TextEncoder()
13
- const text = "a\uFEFF\u00e9"
14
- const input = encoder.encode(row.prefix + text)
15
-
16
- expect(Bom.syncBytes(input, row.bom)).toEqual({
17
- text,
18
- bytes: row.expected === undefined ? undefined : encoder.encode(row.expected + text),
19
- })
20
- expect(input).toEqual(encoder.encode(row.prefix + text))
21
- })
@@ -1,32 +0,0 @@
1
- import { describe, expect, test } from "bun:test"
2
- import { base64Decode, base64Encode, checksum, sampledChecksum } from "./encode.js"
3
-
4
- describe("frontend encoding", () => {
5
- test("uses unpadded URL-safe UTF-8 base64", () => {
6
- expect(base64Encode("hello")).toBe("aGVsbG8")
7
- expect(base64Encode("✓ à la mode")).toBe("4pyTIMOgIGxhIG1vZGU")
8
- expect(base64Decode("4pyTIMOgIGxhIG1vZGU")).toBe("✓ à la mode")
9
- expect(base64Decode("dXNlcjpwYXNz")).toBe("user:pass")
10
- })
11
-
12
- test("rejects invalid base64", () => {
13
- expect(() => base64Decode("%%%")).toThrow()
14
- })
15
-
16
- test("keeps stable FNV checksums", () => {
17
- expect(checksum("")).toBeUndefined()
18
- expect(checksum("hello")).toBe("m3bicr")
19
- expect(checksum("✓ à la mode")).toBe("jmczk0")
20
- })
21
-
22
- test("samples large values without changing the size boundary", () => {
23
- const value = "abcdef".repeat(100)
24
- expect(sampledChecksum(value, value.length)).toBe(checksum(value))
25
- expect(sampledChecksum(value, value.length - 1)).toBe("600:1isj1k5:1isj1k5:1isj1k5:1isj1k5:1isj1k5")
26
- })
27
-
28
- test("hashes the end of large values", () => {
29
- const value = "a".repeat(500_001)
30
- expect(sampledChecksum(`${value.slice(0, -1)}b`)).not.toBe(sampledChecksum(value))
31
- })
32
- })
@@ -1,36 +0,0 @@
1
- import { describe, expect, test } from "bun:test"
2
- import { formatExecuteOutput } from "./execute-output.js"
3
-
4
- describe("execute output", () => {
5
- test("indents a JSON result", () => {
6
- expect(formatExecuteOutput('{"a":1,"b":[2]}')).toEqual({
7
- json: '{\n "a": 1,\n "b": [\n 2\n ]\n}',
8
- rest: undefined,
9
- text: '{\n "a": 1,\n "b": [\n 2\n ]\n}',
10
- })
11
- })
12
-
13
- test("indents a JSON result followed by warnings and logs", () => {
14
- expect(formatExecuteOutput('["x"]\n\nWarnings:\n- [unhandled] boom\n\nLogs:\nhi')).toEqual({
15
- json: '[\n "x"\n]',
16
- rest: "Warnings:\n- [unhandled] boom\n\nLogs:\nhi",
17
- text: '[\n "x"\n]\n\nWarnings:\n- [unhandled] boom\n\nLogs:\nhi',
18
- })
19
- })
20
-
21
- test("leaves other results as they are", () => {
22
- expect(formatExecuteOutput("exit 0\nok\n\nLogs:\nhi")).toEqual({
23
- json: undefined,
24
- rest: "Logs:\nhi",
25
- text: "exit 0\nok\n\nLogs:\nhi",
26
- })
27
- expect(formatExecuteOutput("{not json")).toEqual({ json: undefined, rest: undefined, text: "{not json" })
28
- })
29
-
30
- test("keeps output without a result line as it is", () => {
31
- expect(formatExecuteOutput("Logs:\nhi").text).toBe("Logs:\nhi")
32
- expect(formatExecuteOutput("Warnings:\n- [unhandled] boom\n\nLogs:\nhi").text).toBe(
33
- "Warnings:\n- [unhandled] boom\n\nLogs:\nhi",
34
- )
35
- })
36
- })
@@ -1,33 +0,0 @@
1
- import { afterAll, expect, test } from "bun:test"
2
- import { noTimeoutFetch } from "./no-timeout-fetch.js"
3
-
4
- const pending = Promise.withResolvers<void>()
5
- const server = Bun.serve({
6
- port: 0,
7
- fetch: async (request) => {
8
- if (new URL(request.url).pathname === "/hang") {
9
- pending.resolve()
10
- return new Promise<Response>(() => {})
11
- }
12
- return Response.json({ method: request.method, header: request.headers.get("x-test"), body: await request.text() })
13
- },
14
- })
15
-
16
- afterAll(() => server.stop(true))
17
-
18
- test("preserves the request init", async () => {
19
- const response = await noTimeoutFetch(new URL("/echo", server.url), {
20
- method: "POST",
21
- headers: { "x-test": "value" },
22
- body: "payload",
23
- })
24
- expect(await response.json()).toEqual({ method: "POST", header: "value", body: "payload" })
25
- })
26
-
27
- test("still honours an abort signal", async () => {
28
- const controller = new AbortController()
29
- const request = noTimeoutFetch(new URL("/hang", server.url), { signal: controller.signal })
30
- await pending.promise
31
- controller.abort()
32
- await expect(request).rejects.toMatchObject({ name: "AbortError" })
33
- })
package/src/open.test.ts DELETED
@@ -1,16 +0,0 @@
1
- import { describe, expect, test } from "bun:test"
2
- import { openUrl } from "./open.js"
3
-
4
- describe("openUrl", () => {
5
- test("rejects values that are not URLs", async () => {
6
- await expect(openUrl("not a url")).rejects.toThrow("Only http and https links")
7
- await expect(openUrl("")).rejects.toThrow("Only http and https links")
8
- })
9
-
10
- test("rejects non-http schemes", async () => {
11
- await expect(openUrl("file:///etc/hosts")).rejects.toThrow("Only http and https links")
12
- await expect(openUrl("javascript:alert(1)")).rejects.toThrow("Only http and https links")
13
- await expect(openUrl("ms-msdt:/id PCWDiagnostic")).rejects.toThrow("Only http and https links")
14
- await expect(openUrl("\\\\server\\share\\file.html")).rejects.toThrow("Only http and https links")
15
- })
16
- })
package/src/path.test.ts DELETED
@@ -1,89 +0,0 @@
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
- })
@@ -1,38 +0,0 @@
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
- )
package/src/retry.test.ts DELETED
@@ -1,87 +0,0 @@
1
- import { describe, expect, test } from "bun:test"
2
- import { retry } from "./retry.js"
3
-
4
- describe("client retry", () => {
5
- test("retries transient failures up to the configured attempt count", async () => {
6
- const failures: string[] = []
7
- const value = await retry(
8
- async () => {
9
- failures.push("attempt")
10
- if (failures.length < 3) throw new Error("Failed to fetch")
11
- return "ready"
12
- },
13
- { delay: 0 },
14
- )
15
-
16
- expect(value).toBe("ready")
17
- expect(failures).toHaveLength(3)
18
- })
19
-
20
- test("retries a real network failure wrapped as the cause of a transport error", async () => {
21
- const server = Bun.listen({
22
- hostname: "127.0.0.1",
23
- port: 0,
24
- socket: {
25
- // Reset only once the request has arrived. Resetting on accept races the client's request
26
- // write, and on Windows a lost race surfaces as a write or connect failure instead of a
27
- // connection reset.
28
- data(socket) {
29
- socket.terminate()
30
- },
31
- },
32
- })
33
- const failures: unknown[] = []
34
- try {
35
- await expect(
36
- retry(
37
- () =>
38
- fetch(`http://127.0.0.1:${server.port}/api/project`).catch((cause) => {
39
- failures.push(cause)
40
- throw new Error("Transport", { cause })
41
- }),
42
- { delay: 0 },
43
- ),
44
- ).rejects.toThrow("Transport")
45
- } finally {
46
- server.stop(true)
47
- }
48
- expect(failures).toHaveLength(3)
49
- expect(failures.every((cause) => cause instanceof TypeError)).toBe(true)
50
- })
51
-
52
- test("does not retry a transport error whose cause is not transient", async () => {
53
- const failures: string[] = []
54
- await expect(
55
- retry(async () => {
56
- failures.push("attempt")
57
- throw new Error("Transport", { cause: new Error("invalid response") })
58
- }),
59
- ).rejects.toThrow("Transport")
60
- expect(failures).toHaveLength(1)
61
- })
62
-
63
- test("does not retry other failures", async () => {
64
- const failures: string[] = []
65
- await expect(
66
- retry(async () => {
67
- failures.push("attempt")
68
- throw new Error("invalid response")
69
- }),
70
- ).rejects.toThrow("invalid response")
71
- expect(failures).toHaveLength(1)
72
- })
73
-
74
- test("uses a caller-owned retry condition", async () => {
75
- const failures: string[] = []
76
- await expect(
77
- retry(
78
- async () => {
79
- failures.push("attempt")
80
- throw new Error("retry me")
81
- },
82
- { attempts: 2, delay: 0, retryIf: () => true },
83
- ),
84
- ).rejects.toThrow("retry me")
85
- expect(failures).toHaveLength(2)
86
- })
87
- })