@opencode/util 2.2.5 → 2.2.7

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.
@@ -1,7 +1,7 @@
1
1
  import { isArrayNonEmpty } from "effect/Array";
2
2
  import * as NodeSink from "@effect/platform-node/NodeSink";
3
3
  import * as NodeStream from "@effect/platform-node/NodeStream";
4
- import { Deferred, Effect, Exit, FileSystem, Layer, Path, PlatformError, Predicate, Sink, Stream } from "effect";
4
+ import { Deferred, Effect, Exit, FileSystem, Layer, Path, PlatformError, Predicate, Redacted, Sink, Stream, } from "effect";
5
5
  import { ChildProcess } from "effect/process";
6
6
  import { ChildProcessSpawner, ExitCode, make, makeHandle, ProcessId, } from "effect/process/ChildProcessSpawner";
7
7
  // ast-grep-ignore: no-star-import
@@ -25,6 +25,29 @@ const killGroups = () => groups.forEach((pid) => {
25
25
  // Already gone.
26
26
  }
27
27
  });
28
+ const unwrap = (value) => Redacted.isRedacted(value) ? Redacted.value(value) : value;
29
+ // Node's own NUL check throws an error that includes the value, so NUL is rejected here to keep Redacted values
30
+ // out of errors.
31
+ const findNulCharacter = (command) => {
32
+ if (command.command.includes("\0"))
33
+ return "The command contains a NUL character";
34
+ const index = command.args.findIndex((arg) => unwrap(arg).includes("\0"));
35
+ if (index !== -1)
36
+ return `Argument ${index + 1} contains a NUL character`;
37
+ for (const [name, value] of Object.entries(command.options.env ?? {})) {
38
+ if (value !== undefined && unwrap(value).includes("\0")) {
39
+ return `The environment variable ${name} contains a NUL character`;
40
+ }
41
+ }
42
+ return undefined;
43
+ };
44
+ // Buffered writes can fail after the sink has been interrupted and removed its error listener. Keep a fallback until
45
+ // close, without replacing the sink listener that propagates errors while it is active.
46
+ const handleInputErrors = (writable) => {
47
+ const onError = () => { };
48
+ writable.on("error", onError);
49
+ writable.once("close", () => writable.off("error", onError));
50
+ };
28
51
  const toError = (err) => (err instanceof globalThis.Error ? err : new globalThis.Error(String(err)));
29
52
  const toTag = (err) => {
30
53
  switch (err.code) {
@@ -98,7 +121,18 @@ const makeCrossSpawnSpawner = Effect.gen(function* () {
98
121
  yield* fs.access(opts.cwd);
99
122
  return path.resolve(opts.cwd);
100
123
  });
101
- const env = (opts) => opts.extendEnv ? { ...globalThis.process.env, ...opts.env } : opts.env;
124
+ const env = (opts) => {
125
+ if (opts.env === undefined)
126
+ return opts.extendEnv ? globalThis.process.env : undefined;
127
+ const result = opts.extendEnv ? { ...globalThis.process.env } : {};
128
+ for (const [key, value] of Object.entries(opts.env)) {
129
+ if (value === undefined)
130
+ delete result[key];
131
+ else
132
+ result[key] = unwrap(value);
133
+ }
134
+ return result;
135
+ };
102
136
  const input = (x) => Stream.isStream(x) ? "pipe" : x;
103
137
  const output = (x) => Sink.isSink(x) ? "pipe" : x;
104
138
  const stdin = (opts) => {
@@ -160,39 +194,55 @@ const makeCrossSpawnSpawner = Effect.gen(function* () {
160
194
  }
161
195
  const ins = new Map();
162
196
  const outs = new Map();
197
+ const setupInput = Effect.fnUntraced(function* (fd, node, source) {
198
+ let sink = Sink.drain;
199
+ if (node && "write" in node) {
200
+ handleInputErrors(node);
201
+ sink = NodeSink.fromWritable({
202
+ evaluate: () => node,
203
+ onError: (err) => toPlatformError(`fromWritable(fd${fd})`, toError(err), command),
204
+ endOnDone: true,
205
+ });
206
+ }
207
+ if (source)
208
+ yield* Effect.forkScoped(Stream.run(source, sink));
209
+ ins.set(fd, sink);
210
+ });
211
+ const setupOutput = (fd, node, sink) => {
212
+ let stream = Stream.empty;
213
+ if (node && "read" in node) {
214
+ const tap = new PassThrough();
215
+ // Retain errors raised before anyone reads, e.g. a failed write on a duplex fd, so they neither go uncaught
216
+ // nor leave later readers hanging.
217
+ let error = undefined;
218
+ tap.on("error", (cause) => {
219
+ error ??= cause;
220
+ });
221
+ node.on("error", (err) => tap.destroy(toError(err)));
222
+ node.pipe(tap);
223
+ const onError = (err) => toPlatformError(`fromReadable(fd${fd})`, toError(err), command);
224
+ stream = Stream.suspend(() => error === undefined ? NodeStream.fromReadable({ evaluate: () => tap, onError }) : Stream.fail(onError(error)));
225
+ }
226
+ if (sink)
227
+ stream = Stream.transduce(stream, sink);
228
+ outs.set(fd, stream);
229
+ };
163
230
  for (const x of extra) {
164
231
  const node = proc.stdio[x.fd];
165
232
  switch (x.config.type) {
166
- case "input": {
167
- let sink = Sink.drain;
168
- if (node && "write" in node) {
169
- sink = NodeSink.fromWritable({
170
- evaluate: () => node,
171
- onError: (err) => toPlatformError(`fromWritable(fd${x.fd})`, toError(err), command),
172
- endOnDone: true,
173
- });
174
- }
175
- if (x.config.stream)
176
- yield* Effect.forkScoped(Stream.run(x.config.stream, sink));
177
- ins.set(x.fd, sink);
233
+ case "input":
234
+ yield* setupInput(x.fd, node, x.config.stream);
178
235
  break;
179
- }
180
- case "output": {
181
- let stream = Stream.empty;
182
- if (node && "read" in node) {
183
- const tap = new PassThrough();
184
- node.on("error", (err) => tap.destroy(toError(err)));
185
- node.pipe(tap);
186
- stream = NodeStream.fromReadable({
187
- evaluate: () => tap,
188
- onError: (err) => toPlatformError(`fromReadable(fd${x.fd})`, toError(err), command),
189
- });
190
- }
191
- if (x.config.sink)
192
- stream = Stream.transduce(stream, x.config.sink);
193
- outs.set(x.fd, stream);
236
+ case "output":
237
+ setupOutput(x.fd, node, x.config.sink);
238
+ break;
239
+ case "duplex":
240
+ // Keep writing possible after the child closes its write side.
241
+ if (node && "allowHalfOpen" in node)
242
+ node.allowHalfOpen = true;
243
+ setupOutput(x.fd, node, x.config.sink);
244
+ yield* setupInput(x.fd, node, x.config.stream);
194
245
  break;
195
- }
196
246
  }
197
247
  }
198
248
  return {
@@ -203,6 +253,7 @@ const makeCrossSpawnSpawner = Effect.gen(function* () {
203
253
  const setupStdin = (command, proc, cfg) => Effect.suspend(() => {
204
254
  let sink = Sink.drain;
205
255
  if (Predicate.isNotNull(proc.stdin)) {
256
+ handleInputErrors(proc.stdin);
206
257
  sink = NodeSink.fromWritable({
207
258
  evaluate: () => proc.stdin,
208
259
  onError: (err) => toPlatformError("fromWritable(stdin)", toError(err), command),
@@ -240,14 +291,29 @@ const makeCrossSpawnSpawner = Effect.gen(function* () {
240
291
  stderr = Stream.transduce(stderr, err.stream);
241
292
  return { stdout, stderr, all: Stream.merge(stdout, stderr) };
242
293
  };
243
- const launchProcess = (command, opts) => Effect.callback((resume) => {
294
+ // A Microsoft Store app execution alias, such as Store PowerShell 7 in %LOCALAPPDATA%\Microsoft\WindowsApps, is a
295
+ // reparse point that stat rejects with EACCES. cross-spawn then cannot find it and runs it through
296
+ // `cmd.exe /d /s /c`, which drops everything after the first newline of the command line. Launch the target of
297
+ // the link instead, read on every spawn because a Store update moves it.
298
+ const executable = (file) => {
299
+ if (globalThis.process.platform !== "win32" || !path.isAbsolute(file))
300
+ return Effect.succeed(file);
301
+ return fs.readLink(file).pipe(Effect.map((target) => path.resolve(path.dirname(file), target)), Effect.orElseSucceed(() => file));
302
+ };
303
+ const launchProcess = (command, file, opts) => Effect.callback((resume) => {
244
304
  const closed = Deferred.makeUnsafe();
245
305
  const exited = Deferred.makeUnsafe();
246
- const proc = launch(command.command, command.args, opts);
306
+ const proc = launch(file, command.args.map(unwrap), opts);
247
307
  let settle = () => { };
248
308
  let end = false;
249
309
  let exit;
250
310
  proc.on("error", (err) => {
311
+ // Node copies the arguments into `spawnargs`.
312
+ if (command.args.some(Redacted.isRedacted)) {
313
+ Object.assign(err, {
314
+ spawnargs: [command.command, ...command.args.map((arg) => (Redacted.isRedacted(arg) ? "<redacted>" : arg))],
315
+ });
316
+ }
251
317
  resume(Effect.fail(toPlatformError("spawn", err, command)));
252
318
  });
253
319
  proc.on("exit", (...args) => {
@@ -278,8 +344,8 @@ const makeCrossSpawnSpawner = Effect.gen(function* () {
278
344
  });
279
345
  });
280
346
  const spawn = Effect.fnUntraced(function* (command, opts) {
281
- yield* Effect.logInfo("spawning process", { command: command.command, args: command.args, cwd: opts.cwd });
282
- const [proc, closed, exited, settle] = yield* launchProcess(command, opts);
347
+ yield* Effect.logDebug("spawning process", { command: command.command, args: command.args, cwd: opts.cwd });
348
+ const [proc, closed, exited, settle] = yield* launchProcess(command, yield* executable(command.command), opts);
283
349
  const stopOutput = yield* Deferred.make();
284
350
  // Register before process release so the deadline remains active during termination.
285
351
  yield* Effect.forkScoped(Effect.gen(function* () {
@@ -361,6 +427,10 @@ const makeCrossSpawnSpawner = Effect.gen(function* () {
361
427
  const spawnCommand = Effect.fnUntraced(function* (command) {
362
428
  switch (command._tag) {
363
429
  case "StandardCommand": {
430
+ const nul = findNulCharacter(command);
431
+ if (nul !== undefined) {
432
+ return yield* Effect.fail(PlatformError.badArgument({ module: "ChildProcess", method: "spawn", description: nul }));
433
+ }
364
434
  const sin = stdin(command.options);
365
435
  const sout = stdio(command.options, "stdout");
366
436
  const serr = stdio(command.options, "stderr");
@@ -457,11 +527,13 @@ const makeCrossSpawnSpawner = Effect.gen(function* () {
457
527
  }));
458
528
  continue;
459
529
  }
530
+ const name = ChildProcess.fdName(fd);
531
+ const existing = next.options.additionalFds?.[name];
460
532
  handle = spawnCommand(ChildProcess.make(next.command, next.args, {
461
533
  ...next.options,
462
534
  additionalFds: {
463
535
  ...next.options.additionalFds,
464
- [ChildProcess.fdName(fd)]: { type: "input", stream },
536
+ [name]: existing?.type === "duplex" ? { ...existing, stream } : { type: "input", stream },
465
537
  },
466
538
  }));
467
539
  }
@@ -1,6 +1,13 @@
1
- import { FileSystem, Path } from "effect";
1
+ import { FileSystem, Layer, Path } from "effect";
2
2
  import { HttpClient } from "effect/http";
3
3
  export declare const filesystem: import("./layer-node.js").Provider<FileSystem.FileSystem, never, import("./layer-node.js").Tag<"global">>;
4
4
  export declare const path: import("./layer-node.js").Provider<Path.Path, never, import("./layer-node.js").Tag<"global">>;
5
+ export type Fetch = (input: Request | string | URL, init?: RequestInit) => Promise<Response>;
6
+ /**
7
+ * The fetch behind `httpClient`, AI SDK providers and remote MCP servers: `fetch` when given, so an embedder can route requests through
8
+ * e.g. a Service Binding, otherwise the `FetchHttpClient.Fetch` in scope when the graph is built.
9
+ */
10
+ export declare const fetchLayer: (fetch?: Fetch) => Layer.Layer<never, never, never>;
11
+ export declare const httpFetch: import("./layer-node.js").Provider<never, never, import("./layer-node.js").Tag<"global">>;
5
12
  export declare const httpClient: import("./layer-node.js").Provider<HttpClient.HttpClient, never, import("./layer-node.js").Tag<"global">>;
6
13
  export * as LayerNodePlatform from "./app-node-platform.js";
@@ -2,10 +2,28 @@
2
2
  // ioredis, and node:sqlite, which runtimes such as workerd cannot load.
3
3
  import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
4
4
  import * as NodePath from "@effect/platform-node/NodePath";
5
- import { FileSystem, Path } from "effect";
5
+ import { Effect, FileSystem, Layer, Path } from "effect";
6
6
  import { FetchHttpClient, HttpClient } from "effect/http";
7
7
  import { makeGlobalNode } from "./app-node.js";
8
8
  export const filesystem = makeGlobalNode({ service: FileSystem.FileSystem, layer: NodeFileSystem.layer, deps: [] });
9
9
  export const path = makeGlobalNode({ service: Path.Path, layer: NodePath.layer, deps: [] });
10
- export const httpClient = makeGlobalNode({ service: HttpClient.HttpClient, layer: FetchHttpClient.layer, deps: [] });
10
+ /**
11
+ * The fetch behind `httpClient`, AI SDK providers and remote MCP servers: `fetch` when given, so an embedder can route requests through
12
+ * e.g. a Service Binding, otherwise the `FetchHttpClient.Fetch` in scope when the graph is built.
13
+ */
14
+ export const fetchLayer = (fetch) => Layer.effect(FetchHttpClient.Fetch, Effect.gen(function* () {
15
+ // Bun's `typeof fetch` adds `preconnect`, which nothing here calls.
16
+ return fetch ? fetch : yield* FetchHttpClient.Fetch;
17
+ }));
18
+ export const httpFetch = makeGlobalNode({ service: FetchHttpClient.Fetch, layer: fetchLayer(), deps: [] });
19
+ // Provided per request, so a caller's context can't swap `httpFetch` for another fetch.
20
+ export const httpClient = makeGlobalNode({
21
+ service: HttpClient.HttpClient,
22
+ layer: Layer.effect(HttpClient.HttpClient, Effect.gen(function* () {
23
+ const fetch = yield* FetchHttpClient.Fetch;
24
+ const client = yield* HttpClient.HttpClient.pipe(Effect.provide(FetchHttpClient.layer));
25
+ return HttpClient.transformResponse(client, Effect.provideService(FetchHttpClient.Fetch, fetch));
26
+ })),
27
+ deps: [httpFetch],
28
+ });
11
29
  export * as LayerNodePlatform from "./app-node-platform.js";
@@ -4,7 +4,7 @@ export declare const tags: LayerNode.Tags<{
4
4
  readonly global: readonly [];
5
5
  }>;
6
6
  export type GlobalGraph<A, E = never> = LayerNode.Graph<A, E, (typeof tags.values)["global"]>;
7
- export type LocationGraph<A, E = never> = LayerNode.Graph<A, E, (typeof tags.values)["location"]>;
7
+ export type LocationGraph<A, E = never> = LayerNode.Graph<A, E, (typeof tags.values)["location" | "global"]>;
8
8
  export declare const makeGlobalNode: LayerNode.TagMaker<{
9
9
  readonly location: readonly ["global"];
10
10
  readonly global: readonly [];
package/dist/fs-util.d.ts CHANGED
@@ -10,10 +10,6 @@ export declare namespace FSUtil {
10
10
  get message(): string;
11
11
  }
12
12
  export type Error = PlatformError | FileSystemError;
13
- export interface DirEntry {
14
- readonly name: string;
15
- readonly type: "file" | "directory" | "symlink" | "other";
16
- }
17
13
  export interface UpOptions {
18
14
  readonly targets: string[];
19
15
  readonly start: string;
@@ -31,7 +27,6 @@ export declare namespace FSUtil {
31
27
  readonly writeJson: (path: string, data: unknown, mode?: number) => Effect.Effect<void, Error>;
32
28
  readonly ensureDir: (path: string) => Effect.Effect<void, Error>;
33
29
  readonly writeWithDirs: (path: string, content: string | Uint8Array, mode?: number) => Effect.Effect<void, Error>;
34
- readonly readDirectoryEntries: (path: string) => Effect.Effect<DirEntry[], Error>;
35
30
  readonly resolve: (path: string) => Effect.Effect<string>;
36
31
  readonly findUp: (target: string, start: string, stop?: string) => Effect.Effect<string[], Error>;
37
32
  readonly up: (options: UpOptions) => Effect.Effect<string[], Error>;
package/dist/fs-util.js CHANGED
@@ -1,6 +1,5 @@
1
1
  import path, { dirname, isAbsolute, join, relative, sep } from "path";
2
2
  import { realpathSync } from "fs";
3
- import { readdir } from "fs/promises";
4
3
  import { lookup } from "mime-types";
5
4
  import { Context, Effect, FileSystem, Layer, Schema } from "effect";
6
5
  import { Glob } from "./glob.js";
@@ -23,7 +22,7 @@ export var FSUtil;
23
22
  }
24
23
  FSUtil.Service = Service;
25
24
  // Exported so simulation can wrap this layer and override the methods that
26
- // bypass the injected FileSystem (readDirectoryEntries, scan, globUp).
25
+ // bypass the injected FileSystem (scan, globUp).
27
26
  FSUtil.layer = Layer.effect(Service, Effect.gen(function* () {
28
27
  const fs = yield* FileSystem.FileSystem;
29
28
  const existsSafe = Effect.fn("FileSystem.existsSafe")(function* (path) {
@@ -42,19 +41,7 @@ export var FSUtil;
42
41
  const info = yield* fs.stat(path).pipe(Effect.catch(() => Effect.void));
43
42
  return info?.type === "File";
44
43
  });
45
- const readDirectoryEntries = Effect.fn("FileSystem.readDirectoryEntries")(function* (dirPath) {
46
- return yield* Effect.tryPromise({
47
- try: async () => {
48
- const entries = await readdir(dirPath, { withFileTypes: true });
49
- return entries.map((e) => ({
50
- name: e.name,
51
- type: e.isDirectory() ? "directory" : e.isSymbolicLink() ? "symlink" : e.isFile() ? "file" : "other",
52
- }));
53
- },
54
- catch: (cause) => new FileSystemError({ method: "readDirectoryEntries", cause }),
55
- });
56
- });
57
- const resolve = Effect.fn("FileSystem.resolve")(function* (input) {
44
+ const resolve = Effect.fnUntraced(function* (input) {
58
45
  const resolved = path.resolve(windowsPath(input));
59
46
  // Sandboxes deny reads outside granted paths; canonicalize what we can see.
60
47
  return yield* fs.realPath(resolved).pipe(Effect.map((real) => process.platform === "win32" && real.toLowerCase() === resolved.toLowerCase() ? resolved : real), Effect.catchIf((error) => error.reason._tag === "NotFound" || isAccessDenied(error), () => Effect.succeed(resolved)), Effect.orDie);
@@ -141,7 +128,6 @@ export var FSUtil;
141
128
  readFileStringSafe,
142
129
  isDir,
143
130
  isFile,
144
- readDirectoryEntries,
145
131
  resolve,
146
132
  readJson,
147
133
  writeJson,
package/dist/npm.d.ts CHANGED
@@ -7,6 +7,7 @@ declare const InstallFailedError_base: Schema.Class<InstallFailedError, Schema.T
7
7
  readonly cause: Schema.optional<Schema.Defect>;
8
8
  }>, import("effect/Cause").YieldableError>;
9
9
  export declare class InstallFailedError extends InstallFailedError_base {
10
+ get message(): string;
10
11
  }
11
12
  export interface Package {
12
13
  readonly directory: string;
package/dist/npm.js CHANGED
@@ -13,6 +13,16 @@ export class InstallFailedError extends Schema.TaggedError()("NpmInstallFailedEr
13
13
  dir: Schema.String,
14
14
  cause: Schema.optional(Schema.Defect()),
15
15
  }) {
16
+ get message() {
17
+ const summary = `Failed to install ${this.add?.join(", ") || this.dir}`;
18
+ if (!(this.cause instanceof Error))
19
+ return summary;
20
+ // @npmcli/git reports most failures as "An unknown git error occurred" and keeps git's output on `stderr`.
21
+ const stderr = "stderr" in this.cause && typeof this.cause.stderr === "string" ? this.cause.stderr.trim() : "";
22
+ if (!stderr)
23
+ return `${summary}: ${this.cause.message}`;
24
+ return `${summary}: ${this.cause.message}\n${stderr}`;
25
+ }
16
26
  }
17
27
  export class Service extends Context.Service()("@opencode/Npm") {
18
28
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@opencode/util",
4
- "version": "2.2.5",
4
+ "version": "2.2.7",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -17,12 +17,12 @@
17
17
  ],
18
18
  "exports": {
19
19
  "./effect/layer-node": {
20
- "import": "./dist/effect/layer-node.js",
21
- "types": "./dist/effect/layer-node.d.ts"
20
+ "types": "./dist/effect/layer-node.d.ts",
21
+ "import": "./dist/effect/layer-node.js"
22
22
  },
23
23
  "./*": {
24
- "import": "./dist/*.js",
25
- "types": "./dist/*.d.ts"
24
+ "types": "./dist/*.d.ts",
25
+ "import": "./dist/*.js"
26
26
  }
27
27
  },
28
28
  "imports": {
@@ -46,9 +46,9 @@
46
46
  "typecheck:dist": "bun run build && bun typecheck --project tsconfig.dist.json"
47
47
  },
48
48
  "dependencies": {
49
- "@effect/opentelemetry": "4.0.6",
50
- "@effect/platform-node": "4.0.6",
51
- "@effect/platform-node-shared": "4.0.6",
49
+ "@effect/opentelemetry": "4.1.0",
50
+ "@effect/platform-node": "4.1.0",
51
+ "@effect/platform-node-shared": "4.1.0",
52
52
  "@npmcli/arborist": "9.4.0",
53
53
  "@npmcli/config": "10.8.1",
54
54
  "@opentelemetry/api": "1.9.0",
@@ -61,7 +61,7 @@
61
61
  "@opentelemetry/sdk-trace-base": "2.8.0",
62
62
  "@opentelemetry/sdk-trace-node": "2.8.0",
63
63
  "cross-spawn": "7.0.6",
64
- "effect": "4.0.6",
64
+ "effect": "4.1.0",
65
65
  "glob": "13.0.5",
66
66
  "mime-types": "3.0.2",
67
67
  "minimatch": "10.2.5",