@zyro-sec/util 0.0.0-stage → 1.0.1
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/docs/layer-node.md +155 -0
- package/package.json +68 -4
- package/script/build.ts +9 -0
- package/script/pack.ts +5 -0
- package/src/abort.test.ts +16 -0
- package/src/abort.ts +9 -0
- package/src/activity-calendar.test.ts +136 -0
- package/src/activity-calendar.ts +50 -0
- package/src/artifact.test.ts +29 -0
- package/src/artifact.ts +95 -0
- package/src/base64.test.ts +12 -0
- package/src/base64.ts +29 -0
- package/src/binary.test.ts +19 -0
- package/src/binary.ts +30 -0
- package/src/bom.test.ts +21 -0
- package/src/bom.ts +46 -0
- package/src/cross-spawn-spawner.ts +694 -0
- package/src/duration.ts +22 -0
- package/src/effect/app-node-platform.ts +40 -0
- package/src/effect/app-node.ts +14 -0
- package/src/effect/layer-node.ts +360 -0
- package/src/effect-flock.ts +313 -0
- package/src/encode.test.ts +32 -0
- package/src/encode.ts +39 -0
- package/src/execute-output.test.ts +36 -0
- package/src/execute-output.ts +23 -0
- package/src/flock.ts +346 -0
- package/src/fs-util.ts +271 -0
- package/src/glob.ts +38 -0
- package/src/global-roots.ts +19 -0
- package/src/global-roots.workerd.ts +16 -0
- package/src/global.ts +88 -0
- package/src/hash.ts +11 -0
- package/src/heap-snapshot.ts +44 -0
- package/src/no-timeout-fetch.test.ts +33 -0
- package/src/no-timeout-fetch.ts +5 -0
- package/src/npm-config.ts +41 -0
- package/src/npm.ts +557 -0
- package/src/observability/logging.ts +179 -0
- package/src/observability/otlp.ts +109 -0
- package/src/observability/shared.ts +8 -0
- package/src/observability.ts +60 -0
- package/src/open.test.ts +16 -0
- package/src/open.ts +12 -0
- package/src/patch.ts +382 -0
- package/src/path.test.ts +89 -0
- package/src/path.ts +149 -0
- package/src/process-signal.test.ts +38 -0
- package/src/process-signal.ts +23 -0
- package/src/process.ts +270 -0
- package/src/qr.ts +323 -0
- package/src/record.ts +3 -0
- package/src/retry.test.ts +87 -0
- package/src/retry.ts +51 -0
- package/src/runtime/import.bun.ts +10 -0
- package/src/runtime/import.node.ts +61 -0
- package/src/runtime/import.workerd.ts +9 -0
- package/src/runtime-import.ts +1 -0
- package/src/session-mention.test.ts +19 -0
- package/src/session-mention.ts +24 -0
- package/src/session-title-fallback.ts +36 -0
- package/src/session-turn.test.ts +131 -0
- package/src/session-turn.ts +82 -0
- package/src/teardown.ts +19 -0
- package/src/text-boundary.test.ts +39 -0
- package/src/text-boundary.ts +36 -0
- package/src/uuid.test.ts +80 -0
- package/src/uuid.ts +15 -0
- package/test/fixtures/qr.json +625 -0
- package/test/glob.test.ts +11 -0
- package/test/global-roots.test.ts +62 -0
- package/test/global.test.ts +99 -0
- package/test/observability-otlp.test.ts +45 -0
- package/test/qr.test.ts +113 -0
- package/test/session-title-fallback.test.ts +49 -0
- package/tsconfig.build.json +12 -0
- package/tsconfig.dist.json +10 -0
- package/tsconfig.json +14 -0
- package/README.md +0 -3
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
import path from "path"
|
|
2
|
+
import os from "os"
|
|
3
|
+
import { randomUUID } from "crypto"
|
|
4
|
+
import { Context, Effect, Function, Layer, Option, Schedule, Schema } from "effect"
|
|
5
|
+
import type { FileSystem, Scope } from "effect"
|
|
6
|
+
import type { PlatformError } from "effect/PlatformError"
|
|
7
|
+
import { FSUtil } from "./fs-util.js"
|
|
8
|
+
import { Global } from "./global.js"
|
|
9
|
+
import { makeGlobalNode } from "./effect/app-node.js"
|
|
10
|
+
import { Hash } from "./hash.js"
|
|
11
|
+
|
|
12
|
+
export namespace EffectFlock {
|
|
13
|
+
// ---------------------------------------------------------------------------
|
|
14
|
+
// Errors
|
|
15
|
+
// ---------------------------------------------------------------------------
|
|
16
|
+
|
|
17
|
+
export class LockTimeoutError extends Schema.TaggedError<LockTimeoutError>()("LockTimeoutError", {
|
|
18
|
+
key: Schema.String,
|
|
19
|
+
}) {}
|
|
20
|
+
|
|
21
|
+
export class LockCompromisedError extends Schema.TaggedError<LockCompromisedError>()("LockCompromisedError", {
|
|
22
|
+
detail: Schema.String,
|
|
23
|
+
}) {}
|
|
24
|
+
|
|
25
|
+
class ReleaseError extends Schema.TaggedError<ReleaseError>()("ReleaseError", {
|
|
26
|
+
detail: Schema.String,
|
|
27
|
+
cause: Schema.optional(Schema.Defect()),
|
|
28
|
+
}) {
|
|
29
|
+
override get message() {
|
|
30
|
+
return this.detail
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Internal: signals "lock is held, retry later". Never leaks to callers. */
|
|
35
|
+
class NotAcquired extends Schema.TaggedError<NotAcquired>()("NotAcquired", {}) {}
|
|
36
|
+
|
|
37
|
+
export type LockError = LockTimeoutError | LockCompromisedError
|
|
38
|
+
|
|
39
|
+
export interface Options {
|
|
40
|
+
readonly staleMs?: number
|
|
41
|
+
readonly timeoutMs?: number
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// ---------------------------------------------------------------------------
|
|
45
|
+
// Timing defaults
|
|
46
|
+
// ---------------------------------------------------------------------------
|
|
47
|
+
|
|
48
|
+
const DEFAULT_STALE_MS = 60_000
|
|
49
|
+
const DEFAULT_TIMEOUT_MS = 5 * 60_000
|
|
50
|
+
const BASE_DELAY_MS = 100
|
|
51
|
+
const MAX_DELAY_MS = 2_000
|
|
52
|
+
|
|
53
|
+
const retrySchedule = (timeoutMs: number) =>
|
|
54
|
+
Schedule.min([
|
|
55
|
+
Schedule.exponential(BASE_DELAY_MS, 1.7),
|
|
56
|
+
Schedule.spaced(Math.min(MAX_DELAY_MS, Math.max(BASE_DELAY_MS, Math.floor(timeoutMs / 10)))),
|
|
57
|
+
]).pipe(
|
|
58
|
+
Schedule.jittered,
|
|
59
|
+
Schedule.while((meta) => meta.elapsed < timeoutMs),
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
// ---------------------------------------------------------------------------
|
|
63
|
+
// Lock metadata schema
|
|
64
|
+
// ---------------------------------------------------------------------------
|
|
65
|
+
|
|
66
|
+
const LockMetaJson = Schema.fromJsonString(
|
|
67
|
+
Schema.Struct({
|
|
68
|
+
token: Schema.String,
|
|
69
|
+
pid: Schema.Number,
|
|
70
|
+
hostname: Schema.String,
|
|
71
|
+
createdAt: Schema.String,
|
|
72
|
+
}),
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
const decodeMeta = Schema.decodeUnknownSync(LockMetaJson)
|
|
76
|
+
const encodeMeta = Schema.encodeSync(LockMetaJson)
|
|
77
|
+
|
|
78
|
+
// ---------------------------------------------------------------------------
|
|
79
|
+
// Service
|
|
80
|
+
// ---------------------------------------------------------------------------
|
|
81
|
+
|
|
82
|
+
export interface Interface {
|
|
83
|
+
readonly acquire: (key: string, dir?: string, options?: Options) => Effect.Effect<void, LockError, Scope.Scope>
|
|
84
|
+
readonly withLock: {
|
|
85
|
+
(key: string, dir?: string): <A, E, R>(body: Effect.Effect<A, E, R>) => Effect.Effect<A, E | LockError, R>
|
|
86
|
+
<A, E, R>(body: Effect.Effect<A, E, R>, key: string, dir?: string): Effect.Effect<A, E | LockError, R>
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export class Service extends Context.Service<Service, Interface>()("EffectFlock") {}
|
|
91
|
+
|
|
92
|
+
// ---------------------------------------------------------------------------
|
|
93
|
+
// Layer
|
|
94
|
+
// ---------------------------------------------------------------------------
|
|
95
|
+
|
|
96
|
+
function wall() {
|
|
97
|
+
return performance.timeOrigin + performance.now()
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const mtimeMs = (info: FileSystem.File.Info) => Option.getOrElse(info.mtime, () => new Date(0)).getTime()
|
|
101
|
+
|
|
102
|
+
const isPathGone = (e: PlatformError) => e.reason._tag === "NotFound" || e.reason._tag === "Unknown"
|
|
103
|
+
|
|
104
|
+
const layer: Layer.Layer<Service, never, Global.Service | FSUtil.Service> = Layer.effect(
|
|
105
|
+
Service,
|
|
106
|
+
Effect.gen(function* () {
|
|
107
|
+
const global = yield* Global.Service
|
|
108
|
+
const fs = yield* FSUtil.Service
|
|
109
|
+
const lockRoot = path.join(global.state, "locks")
|
|
110
|
+
const hostname = os.hostname()
|
|
111
|
+
const ensuredDirs = new Set<string>()
|
|
112
|
+
|
|
113
|
+
// -- helpers (close over fs) --
|
|
114
|
+
|
|
115
|
+
const safeStat = (file: string) =>
|
|
116
|
+
fs.stat(file).pipe(
|
|
117
|
+
Effect.catchIf(isPathGone, () => Effect.void),
|
|
118
|
+
Effect.orDie,
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
const forceRemove = (target: string) => fs.remove(target, { recursive: true }).pipe(Effect.ignore)
|
|
122
|
+
|
|
123
|
+
/** Atomic mkdir — returns true if created, false if already exists, dies on other errors. */
|
|
124
|
+
const atomicMkdir = (dir: string) =>
|
|
125
|
+
fs.makeDirectory(dir, { mode: 0o700 }).pipe(
|
|
126
|
+
Effect.as(true),
|
|
127
|
+
Effect.catchIf(
|
|
128
|
+
(e) => e.reason._tag === "AlreadyExists",
|
|
129
|
+
() => Effect.succeed(false),
|
|
130
|
+
),
|
|
131
|
+
Effect.orDie,
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
/** Write with exclusive create — compromised error if file already exists. */
|
|
135
|
+
const exclusiveWrite = (filePath: string, content: string, lockDir: string, detail: string) =>
|
|
136
|
+
fs.writeFileString(filePath, content, { flag: "wx" }).pipe(
|
|
137
|
+
Effect.catch(() =>
|
|
138
|
+
Effect.gen(function* () {
|
|
139
|
+
yield* forceRemove(lockDir)
|
|
140
|
+
return yield* new LockCompromisedError({ detail })
|
|
141
|
+
}),
|
|
142
|
+
),
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
const cleanStaleBreaker = Effect.fnUntraced(function* (breakerPath: string, staleMs: number) {
|
|
146
|
+
const bs = yield* safeStat(breakerPath)
|
|
147
|
+
if (bs && wall() - mtimeMs(bs) > staleMs) yield* forceRemove(breakerPath)
|
|
148
|
+
return false
|
|
149
|
+
})
|
|
150
|
+
|
|
151
|
+
const ensureDir = Effect.fnUntraced(function* (dir: string) {
|
|
152
|
+
if (ensuredDirs.has(dir)) return
|
|
153
|
+
yield* fs.makeDirectory(dir, { recursive: true }).pipe(Effect.orDie)
|
|
154
|
+
ensuredDirs.add(dir)
|
|
155
|
+
})
|
|
156
|
+
|
|
157
|
+
const isStale = Effect.fnUntraced(function* (
|
|
158
|
+
lockDir: string,
|
|
159
|
+
heartbeatPath: string,
|
|
160
|
+
metaPath: string,
|
|
161
|
+
staleMs: number,
|
|
162
|
+
) {
|
|
163
|
+
const now = wall()
|
|
164
|
+
|
|
165
|
+
const hb = yield* safeStat(heartbeatPath)
|
|
166
|
+
if (hb) return now - mtimeMs(hb) > staleMs
|
|
167
|
+
|
|
168
|
+
const meta = yield* safeStat(metaPath)
|
|
169
|
+
if (meta) return now - mtimeMs(meta) > staleMs
|
|
170
|
+
|
|
171
|
+
const dir = yield* safeStat(lockDir)
|
|
172
|
+
if (!dir) return false
|
|
173
|
+
|
|
174
|
+
return now - mtimeMs(dir) > staleMs
|
|
175
|
+
})
|
|
176
|
+
|
|
177
|
+
// -- single lock attempt --
|
|
178
|
+
|
|
179
|
+
type Handle = { token: string; metaPath: string; heartbeatPath: string; lockDir: string }
|
|
180
|
+
|
|
181
|
+
const tryAcquireLockDir = (lockDir: string, key: string, staleMs: number) =>
|
|
182
|
+
Effect.gen(function* () {
|
|
183
|
+
const token = randomUUID()
|
|
184
|
+
const metaPath = path.join(lockDir, "meta.json")
|
|
185
|
+
const heartbeatPath = path.join(lockDir, "heartbeat")
|
|
186
|
+
|
|
187
|
+
// Atomic mkdir — the POSIX lock primitive
|
|
188
|
+
const created = yield* atomicMkdir(lockDir)
|
|
189
|
+
|
|
190
|
+
if (!created) {
|
|
191
|
+
if (!(yield* isStale(lockDir, heartbeatPath, metaPath, staleMs))) return yield* new NotAcquired()
|
|
192
|
+
|
|
193
|
+
// Stale — race for breaker ownership
|
|
194
|
+
const breakerPath = lockDir + ".breaker"
|
|
195
|
+
|
|
196
|
+
const claimed = yield* fs.makeDirectory(breakerPath, { mode: 0o700 }).pipe(
|
|
197
|
+
Effect.as(true),
|
|
198
|
+
Effect.catchIf(
|
|
199
|
+
(e) => e.reason._tag === "AlreadyExists",
|
|
200
|
+
() => cleanStaleBreaker(breakerPath, staleMs),
|
|
201
|
+
),
|
|
202
|
+
Effect.catchIf(isPathGone, () => Effect.succeed(false)),
|
|
203
|
+
Effect.orDie,
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
if (!claimed) return yield* new NotAcquired()
|
|
207
|
+
|
|
208
|
+
// We own the breaker — double-check staleness, nuke, recreate
|
|
209
|
+
const recreated = yield* Effect.gen(function* () {
|
|
210
|
+
if (!(yield* isStale(lockDir, heartbeatPath, metaPath, staleMs))) return false
|
|
211
|
+
yield* forceRemove(lockDir)
|
|
212
|
+
return yield* atomicMkdir(lockDir)
|
|
213
|
+
}).pipe(Effect.ensuring(forceRemove(breakerPath)))
|
|
214
|
+
|
|
215
|
+
if (!recreated) return yield* new NotAcquired()
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// We own the lock dir — write heartbeat + meta with exclusive create
|
|
219
|
+
yield* exclusiveWrite(heartbeatPath, "", lockDir, "heartbeat already existed")
|
|
220
|
+
|
|
221
|
+
const metaJson = encodeMeta({ token, pid: process.pid, hostname, createdAt: new Date().toISOString() })
|
|
222
|
+
yield* exclusiveWrite(metaPath, metaJson, lockDir, "meta.json already existed")
|
|
223
|
+
|
|
224
|
+
return { token, metaPath, heartbeatPath, lockDir } satisfies Handle
|
|
225
|
+
}).pipe(
|
|
226
|
+
Effect.withSpan("EffectFlock.tryAcquire", {
|
|
227
|
+
attributes: { key },
|
|
228
|
+
}),
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
// -- retry wrapper (preserves Handle type) --
|
|
232
|
+
|
|
233
|
+
const acquireHandle = (
|
|
234
|
+
lockfile: string,
|
|
235
|
+
key: string,
|
|
236
|
+
options: { staleMs: number; timeoutMs: number },
|
|
237
|
+
): Effect.Effect<Handle, LockError> =>
|
|
238
|
+
tryAcquireLockDir(lockfile, key, options.staleMs).pipe(
|
|
239
|
+
Effect.retry({
|
|
240
|
+
while: (err) => err._tag === "NotAcquired",
|
|
241
|
+
schedule: retrySchedule(options.timeoutMs),
|
|
242
|
+
}),
|
|
243
|
+
Effect.catchTag("NotAcquired", () => Effect.fail(new LockTimeoutError({ key }))),
|
|
244
|
+
Effect.timeoutOrElse({
|
|
245
|
+
duration: options.timeoutMs,
|
|
246
|
+
orElse: () => Effect.fail(new LockTimeoutError({ key })),
|
|
247
|
+
}),
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
// -- release --
|
|
251
|
+
|
|
252
|
+
const release = (handle: Handle) =>
|
|
253
|
+
Effect.gen(function* () {
|
|
254
|
+
const raw = yield* fs.readFileString(handle.metaPath).pipe(
|
|
255
|
+
Effect.catch((err) => {
|
|
256
|
+
if (isPathGone(err)) return Effect.die(new ReleaseError({ detail: "metadata missing" }))
|
|
257
|
+
return Effect.die(err)
|
|
258
|
+
}),
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
const parsed = yield* Effect.try({
|
|
262
|
+
try: () => decodeMeta(raw),
|
|
263
|
+
catch: (cause) => new ReleaseError({ detail: "metadata invalid", cause }),
|
|
264
|
+
}).pipe(Effect.orDie)
|
|
265
|
+
|
|
266
|
+
if (parsed.token !== handle.token) return yield* Effect.die(new ReleaseError({ detail: "token mismatch" }))
|
|
267
|
+
|
|
268
|
+
yield* forceRemove(handle.lockDir)
|
|
269
|
+
})
|
|
270
|
+
|
|
271
|
+
// -- build service --
|
|
272
|
+
|
|
273
|
+
const acquire = Effect.fn("EffectFlock.acquire")(function* (key: string, dir?: string, options: Options = {}) {
|
|
274
|
+
const lockDir = dir ?? lockRoot
|
|
275
|
+
const staleMs = options.staleMs ?? DEFAULT_STALE_MS
|
|
276
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
|
277
|
+
yield* ensureDir(lockDir)
|
|
278
|
+
|
|
279
|
+
const lockfile = path.join(lockDir, Hash.fast(key) + ".lock")
|
|
280
|
+
|
|
281
|
+
// acquireRelease: acquire is uninterruptible, release is guaranteed
|
|
282
|
+
const handle = yield* Effect.acquireRelease(acquireHandle(lockfile, key, { staleMs, timeoutMs }), (handle) =>
|
|
283
|
+
release(handle),
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
// Heartbeat fiber — scoped, so it's interrupted before release runs
|
|
287
|
+
yield* Effect.suspend(() => {
|
|
288
|
+
const now = new Date()
|
|
289
|
+
return fs.utimes(handle.heartbeatPath, now, now)
|
|
290
|
+
}).pipe(
|
|
291
|
+
Effect.ignore,
|
|
292
|
+
Effect.repeat(Schedule.spaced(Math.max(100, Math.floor(staleMs / 3)))),
|
|
293
|
+
Effect.forkScoped,
|
|
294
|
+
)
|
|
295
|
+
})
|
|
296
|
+
|
|
297
|
+
const withLock: Interface["withLock"] = Function.dual(
|
|
298
|
+
(args) => Effect.isEffect(args[0]),
|
|
299
|
+
<A, E, R>(body: Effect.Effect<A, E, R>, key: string, dir?: string): Effect.Effect<A, E | LockError, R> =>
|
|
300
|
+
Effect.scoped(
|
|
301
|
+
Effect.gen(function* () {
|
|
302
|
+
yield* acquire(key, dir)
|
|
303
|
+
return yield* body
|
|
304
|
+
}),
|
|
305
|
+
),
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
return Service.of({ acquire, withLock })
|
|
309
|
+
}),
|
|
310
|
+
)
|
|
311
|
+
|
|
312
|
+
export const node = makeGlobalNode({ service: Service, layer: layer, deps: [Global.node, FSUtil.node] })
|
|
313
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
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
|
+
})
|
package/src/encode.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export function base64Encode(value: string) {
|
|
2
|
+
const bytes = new TextEncoder().encode(value)
|
|
3
|
+
const binary = Array.from(bytes, (byte) => String.fromCharCode(byte)).join("")
|
|
4
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "")
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function base64Decode(value: string) {
|
|
8
|
+
const binary = atob(value.replace(/-/g, "+").replace(/_/g, "/"))
|
|
9
|
+
return new TextDecoder().decode(Uint8Array.from(binary, (character) => character.charCodeAt(0)))
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function checksum(content: string): string | undefined {
|
|
13
|
+
if (!content) return
|
|
14
|
+
let hash = 0x811c9dc5
|
|
15
|
+
for (let index = 0; index < content.length; index++) {
|
|
16
|
+
hash ^= content.charCodeAt(index)
|
|
17
|
+
hash = Math.imul(hash, 0x01000193)
|
|
18
|
+
}
|
|
19
|
+
return (hash >>> 0).toString(36)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function sampledChecksum(content: string, limit = 500_000): string | undefined {
|
|
23
|
+
if (!content) return
|
|
24
|
+
if (content.length <= limit) return checksum(content)
|
|
25
|
+
|
|
26
|
+
const size = 4096
|
|
27
|
+
return `${content.length}:${[
|
|
28
|
+
0,
|
|
29
|
+
Math.floor(content.length * 0.25),
|
|
30
|
+
Math.floor(content.length * 0.5),
|
|
31
|
+
Math.floor(content.length * 0.75),
|
|
32
|
+
content.length,
|
|
33
|
+
]
|
|
34
|
+
.map((point) => {
|
|
35
|
+
const start = Math.max(0, Math.min(content.length - size, point - Math.floor(size / 2)))
|
|
36
|
+
return checksum(content.slice(start, start + size)) ?? ""
|
|
37
|
+
})
|
|
38
|
+
.join(":")}`
|
|
39
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
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
|
+
})
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { Option, Schema } from "effect"
|
|
2
|
+
|
|
3
|
+
const decodeJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown))
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Code Mode's `execute` output for display. The tool returns its result (compact JSON for structured values) followed
|
|
7
|
+
* by optional "Warnings:" and "Logs:" sections. A JSON result comes back indented as `json`, the sections as `rest`,
|
|
8
|
+
* and `text` joins them.
|
|
9
|
+
*/
|
|
10
|
+
export function formatExecuteOutput(output: string) {
|
|
11
|
+
const end = output.search(/\n\n(Warnings|Logs):\n/)
|
|
12
|
+
const result = end === -1 ? output : output.slice(0, end)
|
|
13
|
+
const rest = end === -1 ? undefined : output.slice(end).trim()
|
|
14
|
+
const json = indentedJson(result)
|
|
15
|
+
return { json, rest, text: rest === undefined ? (json ?? result) : `${json ?? result}\n\n${rest}` }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function indentedJson(text: string) {
|
|
19
|
+
if (!text.startsWith("{") && !text.startsWith("[")) return
|
|
20
|
+
const decoded = decodeJson(text)
|
|
21
|
+
if (Option.isNone(decoded)) return
|
|
22
|
+
return JSON.stringify(decoded.value, null, 2)
|
|
23
|
+
}
|