@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.
Files changed (79) hide show
  1. package/docs/layer-node.md +155 -0
  2. package/package.json +68 -4
  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
  79. package/README.md +0 -3
package/src/global.ts ADDED
@@ -0,0 +1,88 @@
1
+ import path from "path"
2
+ import fs from "fs"
3
+ import os from "os"
4
+ import { Context, Effect, Layer } from "effect"
5
+ // XDG on runtimes with a home directory; one tmp-rooted directory on workerd.
6
+ // The variants resolve through the `workerd` bundle condition, like the
7
+ // native-module stubs, so no runtime sniffing happens here.
8
+ import { roots } from "#global-roots"
9
+ import { Flock } from "./flock.js"
10
+ import { makeGlobalNode } from "./effect/app-node.js"
11
+
12
+ const app = "zyrosec"
13
+ const { data, cache, config, state, tmp } = roots(app)
14
+
15
+ const paths = {
16
+ get home() {
17
+ return process.env.ZYROSEC_TEST_HOME ?? process.env.OPENCODE_TEST_HOME ?? os.homedir()
18
+ },
19
+ data,
20
+ bin: path.join(cache, "bin"),
21
+ log: path.join(data, "log"),
22
+ repos: path.join(data, "repos"),
23
+ cache,
24
+ config,
25
+ state,
26
+ tmp,
27
+ }
28
+
29
+ export const Path = paths
30
+
31
+ Flock.setGlobal({ state })
32
+
33
+ export class Service extends Context.Service<Service, Interface>()("@zyro-sec/Global") {}
34
+
35
+ export interface Interface {
36
+ readonly home: string
37
+ readonly data: string
38
+ readonly cache: string
39
+ readonly config: string
40
+ readonly state: string
41
+ readonly tmp: string
42
+ readonly bin: string
43
+ readonly log: string
44
+ readonly repos: string
45
+ }
46
+
47
+ export function make(input: Partial<Interface> = {}): Interface {
48
+ // The acquired service canonicalizes default tmp; use it instead of Path.tmp for path comparisons.
49
+ return {
50
+ home: Path.home,
51
+ data: Path.data,
52
+ cache: Path.cache,
53
+ config: Path.config,
54
+ state: Path.state,
55
+ tmp: input.tmp ?? Path.tmp,
56
+ bin: Path.bin,
57
+ log: Path.log,
58
+ repos: Path.repos,
59
+ ...input,
60
+ }
61
+ }
62
+
63
+ const acquire = (input: Partial<Interface>) =>
64
+ Effect.gen(function* () {
65
+ const service = Service.of(make(input))
66
+ yield* Effect.promise(() =>
67
+ Promise.all(
68
+ [service.data, service.config, service.state, service.log, service.bin, service.repos, service.tmp].map(
69
+ (directory) => fs.promises.mkdir(directory, { recursive: true }),
70
+ ),
71
+ ),
72
+ )
73
+ const canonicalTmp = yield* Effect.promise(() => fs.promises.realpath(service.tmp))
74
+ return Service.of({ ...service, tmp: input.tmp ?? canonicalTmp })
75
+ })
76
+
77
+ const layer = Layer.effect(
78
+ Service,
79
+ Effect.suspend(() =>
80
+ acquire({ config: process.env.ZYROSEC_CONFIG_DIR ?? process.env.OPENCODE_CONFIG_DIR ?? Path.config }),
81
+ ),
82
+ )
83
+
84
+ export const node = makeGlobalNode({ service: Service, layer: layer, deps: [] })
85
+
86
+ export const layerWith = (input: Partial<Interface>) => Layer.effect(Service, acquire(input))
87
+
88
+ export * as Global from "./global.js"
package/src/hash.ts ADDED
@@ -0,0 +1,11 @@
1
+ import { createHash } from "crypto"
2
+
3
+ export namespace Hash {
4
+ export function fast(input: string | Buffer): string {
5
+ return createHash("sha1").update(input).digest("hex")
6
+ }
7
+
8
+ export function sha256(input: string | Buffer): string {
9
+ return createHash("sha256").update(input).digest("hex")
10
+ }
11
+ }
@@ -0,0 +1,44 @@
1
+ import { Clock, Effect, Semaphore } from "effect"
2
+ import { mkdir, open } from "node:fs/promises"
3
+ import path from "node:path"
4
+
5
+ // One process-wide permit: the signal listener and the HTTP endpoint share it, so concurrent
6
+ // requests queue instead of serializing two heaps at once.
7
+ const lock = Semaphore.makeUnsafe(1)
8
+
9
+ /**
10
+ * Writes a V8 heap snapshot of this process into `directory` and returns once the file is complete, with the
11
+ * process's memory just before the snapshot: the snapshot holds only the garbage-collected heap, and writing it
12
+ * raises the process's memory. Blocks the event loop while the heap serializes. The file can contain secrets, so it
13
+ * is created owner-only before the runtime writes into it.
14
+ */
15
+ export const write = Effect.fn("HeapSnapshot.write")(
16
+ function* (directory: string) {
17
+ const v8 = yield* Effect.tryPromise(() => import("node:v8"))
18
+ const time = new Date(yield* Clock.currentTimeMillis).toISOString().replace(/[:.]/g, "")
19
+ const file = path.join(directory, `heap-${process.pid}-${time}.heapsnapshot`)
20
+ yield* Effect.tryPromise(async () => {
21
+ await mkdir(directory, { recursive: true })
22
+ const handle = await open(file, "wx", 0o600)
23
+ await handle.close()
24
+ })
25
+ const memory = yield* Effect.sync(() => process.memoryUsage())
26
+ yield* Effect.logInfo("writing heap snapshot", { path: file, rss: memory.rss, heapUsed: memory.heapUsed })
27
+ yield* Effect.try(() => v8.writeHeapSnapshot(file))
28
+ yield* Effect.logInfo("heap snapshot written", { path: file })
29
+ return {
30
+ path: file,
31
+ pid: process.pid,
32
+ memory: {
33
+ rss: memory.rss,
34
+ heapTotal: memory.heapTotal,
35
+ heapUsed: memory.heapUsed,
36
+ external: memory.external,
37
+ arrayBuffers: memory.arrayBuffers,
38
+ },
39
+ }
40
+ },
41
+ (effect) => lock.withPermit(effect),
42
+ )
43
+
44
+ export * as HeapSnapshot from "./heap-snapshot.js"
@@ -0,0 +1,33 @@
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
+ })
@@ -0,0 +1,5 @@
1
+ // Bun's fetch aborts requests after its default idle deadline (about five minutes). Clients that
2
+ // hold requests open for long-running work (session waits, event streams, plugin commands,
3
+ // shell calls) opt out while keeping every other init option, including `signal`.
4
+ export const noTimeoutFetch = ((request: Parameters<typeof fetch>[0], init?: RequestInit) =>
5
+ fetch(request, { ...init, timeout: false } as BunFetchRequestInit)) as typeof fetch
@@ -0,0 +1,41 @@
1
+ export * as NpmConfig from "./npm-config.js"
2
+
3
+ import { fileURLToPath } from "url"
4
+ import { Effect } from "effect"
5
+
6
+ export const load = (dir: string) =>
7
+ Effect.tryPromise({
8
+ try: async () => {
9
+ // @ts-expect-error npm does not publish types for this internal config API.
10
+ const { default: Config } = await import("@npmcli/config")
11
+ // @ts-expect-error npm does not publish types for this internal config API.
12
+ const { default: npmDefinitions } = await import("@npmcli/config/lib/definitions/index.js")
13
+ const { definitions, flatten, nerfDarts, shorthands } = npmDefinitions
14
+ const config = new Config({
15
+ // Resolved per call: on workerd import.meta.url is undefined and building
16
+ // this URL at module scope fails startup validation; npm config never runs there.
17
+ npmPath: fileURLToPath(new URL("..", import.meta.url)),
18
+ cwd: dir,
19
+ env: { ...process.env },
20
+ argv: [process.execPath, process.execPath, "--prefix", dir],
21
+ execPath: process.execPath,
22
+ platform: process.platform,
23
+ definitions,
24
+ flatten,
25
+ nerfDarts,
26
+ shorthands,
27
+ warn: false,
28
+ })
29
+ await config.load()
30
+ return config.flat as Record<string, unknown>
31
+ },
32
+ catch: (cause) => cause,
33
+ }).pipe(Effect.orElseSucceed(() => ({}) as Record<string, unknown>))
34
+
35
+ export const registry = (dir: string) =>
36
+ load(dir).pipe(
37
+ Effect.map((config) => {
38
+ const registry = typeof config.registry === "string" ? config.registry : "https://registry.npmjs.org"
39
+ return registry.endsWith("/") ? registry.slice(0, -1) : registry
40
+ }),
41
+ )