@radheim/util 0.0.0-stage → 2.4.3

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 (98) hide show
  1. package/dist/abort.d.ts +1 -0
  2. package/dist/abort.js +8 -0
  3. package/dist/activity-calendar.d.ts +21 -0
  4. package/dist/activity-calendar.js +42 -0
  5. package/dist/artifact.d.ts +4 -0
  6. package/dist/artifact.js +85 -0
  7. package/dist/base64.d.ts +4 -0
  8. package/dist/base64.js +24 -0
  9. package/dist/binary.d.ts +7 -0
  10. package/dist/binary.js +34 -0
  11. package/dist/bom.d.ts +22 -0
  12. package/dist/bom.js +36 -0
  13. package/dist/cross-spawn-spawner.d.ts +9 -0
  14. package/dist/cross-spawn-spawner.js +548 -0
  15. package/dist/duration.d.ts +2 -0
  16. package/dist/duration.js +22 -0
  17. package/dist/effect/app-node-platform.d.ts +13 -0
  18. package/dist/effect/app-node-platform.js +29 -0
  19. package/dist/effect/app-node.d.ts +16 -0
  20. package/dist/effect/app-node.js +8 -0
  21. package/dist/effect/layer-node.d.ts +178 -0
  22. package/dist/effect/layer-node.js +248 -0
  23. package/dist/effect-flock.d.ts +31 -0
  24. package/dist/effect-flock.js +186 -0
  25. package/dist/encode.d.ts +4 -0
  26. package/dist/encode.js +38 -0
  27. package/dist/execute-output.d.ts +10 -0
  28. package/dist/execute-output.js +22 -0
  29. package/dist/flock.d.ts +28 -0
  30. package/dist/flock.js +267 -0
  31. package/dist/fs-util.d.ts +54 -0
  32. package/dist/fs-util.js +200 -0
  33. package/dist/glob.d.ts +18 -0
  34. package/dist/glob.js +29 -0
  35. package/dist/global-roots.d.ts +8 -0
  36. package/dist/global-roots.js +17 -0
  37. package/dist/global-roots.workerd.d.ts +7 -0
  38. package/dist/global-roots.workerd.js +15 -0
  39. package/dist/global.d.ts +30 -0
  40. package/dist/global.js +54 -0
  41. package/dist/hash.d.ts +4 -0
  42. package/dist/hash.js +12 -0
  43. package/dist/heap-snapshot.d.ts +19 -0
  44. package/dist/heap-snapshot.js +38 -0
  45. package/dist/no-timeout-fetch.d.ts +1 -0
  46. package/dist/no-timeout-fetch.js +4 -0
  47. package/dist/npm-config.d.ts +4 -0
  48. package/dist/npm-config.js +34 -0
  49. package/dist/npm.d.ts +45 -0
  50. package/dist/npm.js +441 -0
  51. package/dist/observability/logging.d.ts +14 -0
  52. package/dist/observability/logging.js +151 -0
  53. package/dist/observability/otlp.d.ts +19 -0
  54. package/dist/observability/otlp.js +63 -0
  55. package/dist/observability/shared.d.ts +1 -0
  56. package/dist/observability/shared.js +7 -0
  57. package/dist/observability/tracing.d.ts +2 -0
  58. package/dist/observability/tracing.js +3 -0
  59. package/dist/observability.d.ts +13 -0
  60. package/dist/observability.js +37 -0
  61. package/dist/open.d.ts +2 -0
  62. package/dist/open.js +10 -0
  63. package/dist/patch.d.ts +43 -0
  64. package/dist/patch.js +332 -0
  65. package/dist/path.d.ts +20 -0
  66. package/dist/path.js +134 -0
  67. package/dist/process-signal.d.ts +5 -0
  68. package/dist/process-signal.js +22 -0
  69. package/dist/process.d.ts +54 -0
  70. package/dist/process.js +167 -0
  71. package/dist/qr.d.ts +15 -0
  72. package/dist/qr.js +295 -0
  73. package/dist/record.d.ts +2 -0
  74. package/dist/record.js +2 -0
  75. package/dist/retry.d.ts +8 -0
  76. package/dist/retry.js +45 -0
  77. package/dist/runtime/import.bun.d.ts +2 -0
  78. package/dist/runtime/import.bun.js +8 -0
  79. package/dist/runtime/import.node.d.ts +2 -0
  80. package/dist/runtime/import.node.js +62 -0
  81. package/dist/runtime/import.workerd.d.ts +2 -0
  82. package/dist/runtime/import.workerd.js +7 -0
  83. package/dist/runtime-import.d.ts +1 -0
  84. package/dist/runtime-import.js +1 -0
  85. package/dist/session-mention.d.ts +11 -0
  86. package/dist/session-mention.js +18 -0
  87. package/dist/session-title-fallback.d.ts +16 -0
  88. package/dist/session-title-fallback.js +23 -0
  89. package/dist/session-turn.d.ts +37 -0
  90. package/dist/session-turn.js +56 -0
  91. package/dist/teardown.d.ts +8 -0
  92. package/dist/teardown.js +16 -0
  93. package/dist/text-boundary.d.ts +11 -0
  94. package/dist/text-boundary.js +22 -0
  95. package/dist/uuid.d.ts +1 -0
  96. package/dist/uuid.js +14 -0
  97. package/package.json +71 -4
  98. package/README.md +0 -3
package/dist/npm.js ADDED
@@ -0,0 +1,441 @@
1
+ export * as Npm from "./npm.js";
2
+ import path from "path";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { Clock, Effect, Schema, Context, Layer, Option, FileSystem } from "effect";
5
+ import { FSUtil } from "./fs-util.js";
6
+ import { Global } from "./global.js";
7
+ import { EffectFlock } from "./effect-flock.js";
8
+ import { makeGlobalNode } from "./effect/app-node.js";
9
+ import { filesystem } from "./effect/app-node-platform.js";
10
+ import { NpmConfig } from "./npm-config.js";
11
+ export class InstallFailedError extends Schema.TaggedError()("NpmInstallFailedError", {
12
+ add: Schema.Array(Schema.String).pipe(Schema.optional),
13
+ dir: Schema.String,
14
+ cause: Schema.optional(Schema.Defect()),
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
+ }
26
+ }
27
+ export class Service extends Context.Service()("@radheim/Npm") {
28
+ }
29
+ const illegal = process.platform === "win32" ? new Set(["<", ">", ":", '"', "|", "?", "*"]) : undefined;
30
+ export function sanitize(pkg) {
31
+ if (!illegal)
32
+ return pkg;
33
+ return Array.from(pkg, (char) => (illegal.has(char) || char.charCodeAt(0) < 32 ? "_" : char)).join("");
34
+ }
35
+ export async function isRegistryPackage(pkg) {
36
+ return (await parse(pkg))?.type === "registry";
37
+ }
38
+ export async function isInstallablePackage(pkg) {
39
+ return (await parse(pkg)) !== undefined;
40
+ }
41
+ export async function cacheKey(pkg) {
42
+ return key(pkg, await parse(pkg));
43
+ }
44
+ async function parse(pkg) {
45
+ const { default: npa } = await import("npm-package-arg");
46
+ try {
47
+ const result = npa(pkg);
48
+ if (result.type === "git") {
49
+ const mutable = !isCommit(result.gitCommittish);
50
+ return {
51
+ type: "git",
52
+ ...(result.name ? { name: result.name } : {}),
53
+ slug: gitSlug(pkg),
54
+ mutable,
55
+ follows: Boolean(result.gitRange),
56
+ ...(mutable && result.gitCommittish ? { ref: result.gitCommittish } : {}),
57
+ };
58
+ }
59
+ if (!result.name || !["version", "range", "tag"].includes(result.type))
60
+ return;
61
+ return {
62
+ type: "registry",
63
+ name: result.name,
64
+ spec: result.raw === result.name ? "latest" : result.rawSpec,
65
+ mutable: result.type !== "version",
66
+ // npm parses a bare name as the range `*`; only a written `@latest` or range follows.
67
+ follows: result.raw !== result.name &&
68
+ (result.type === "range" || (result.type === "tag" && result.rawSpec === "latest")),
69
+ };
70
+ }
71
+ catch {
72
+ return;
73
+ }
74
+ }
75
+ function key(pkg, target) {
76
+ if (target?.type === "git")
77
+ return `git-${target.slug}-${createHash("sha256").update(pkg).digest("hex").slice(0, 12)}`;
78
+ if (target?.type === "registry")
79
+ return sanitize(`${target.name}@${target.spec}`);
80
+ return sanitize(pkg);
81
+ }
82
+ function gitSlug(pkg) {
83
+ const target = (() => {
84
+ try {
85
+ return decodeURIComponent(pkg.split("#")[0]);
86
+ }
87
+ catch {
88
+ return pkg.split("#")[0];
89
+ }
90
+ })();
91
+ return (target
92
+ .replace(/\.git$/i, "")
93
+ .split(/[/:\\]/)
94
+ .at(-1)
95
+ ?.replace(/[^a-zA-Z0-9._-]+/g, "-")
96
+ .replace(/^-+|-+$/g, "") || "repository");
97
+ }
98
+ const PackageJson = Schema.Struct({
99
+ dependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
100
+ version: Schema.optional(Schema.String),
101
+ });
102
+ const PackageLock = Schema.Struct({
103
+ packages: Schema.optional(Schema.Record(Schema.String, Schema.Struct({ resolved: Schema.optional(Schema.String) }))),
104
+ });
105
+ const retention = 7 * 24 * 60 * 60 * 1_000;
106
+ const stagingRetention = 60 * 60 * 1_000;
107
+ const layer = Layer.effect(Service, Effect.gen(function* () {
108
+ const afs = yield* FSUtil.Service;
109
+ const global = yield* Global.Service;
110
+ const fs = yield* FileSystem.FileSystem;
111
+ const flock = yield* EffectFlock.Service;
112
+ const directory = (pkg, target) => path.join(global.cache, "npm", key(pkg, target));
113
+ const generations = Effect.fnUntraced(function* (dir) {
114
+ return yield* fs.readDirectory(dir).pipe(Effect.orElseSucceed(() => []), Effect.map((entries) => entries
115
+ .filter((entry) => /^\d+$/.test(entry) && !entries.includes(`${entry}.rejected`))
116
+ .toSorted((a, b) => Number(a) - Number(b))));
117
+ });
118
+ const current = Effect.fnUntraced(function* (dir) {
119
+ const latest = (yield* generations(dir)).at(-1);
120
+ return latest ? path.join(dir, latest) : undefined;
121
+ });
122
+ const mkdir = (dir) => fs.makeDirectory(dir, { recursive: true }).pipe(Effect.mapError((cause) => new InstallFailedError({ dir, cause })));
123
+ const remove = (target, dir) => fs.remove(target, { recursive: true, force: true }).pipe(Effect.mapError((cause) => new InstallFailedError({ dir, cause })));
124
+ const rename = (from, to, dir) => fs.rename(from, to).pipe(Effect.mapError((cause) => new InstallFailedError({ dir, cause })));
125
+ const installedName = Effect.fnUntraced(function* (pkg, dir, target) {
126
+ if (target?.name)
127
+ return target.name;
128
+ const manifest = yield* afs
129
+ .readJson(path.join(dir, "package.json"))
130
+ .pipe(Effect.flatMap(Schema.decodeUnknownEffect(PackageJson)), Effect.option);
131
+ if (Option.isSome(manifest)) {
132
+ const name = Object.keys(manifest.value.dependencies ?? {})[0];
133
+ if (name)
134
+ return name;
135
+ }
136
+ return pkg;
137
+ });
138
+ const installedRevision = Effect.fnUntraced(function* (root, name, target) {
139
+ const dir = path.join(root, "node_modules", name);
140
+ if (target.type === "registry") {
141
+ const manifest = yield* afs
142
+ .readJson(path.join(dir, "package.json"))
143
+ .pipe(Effect.flatMap(Schema.decodeUnknownEffect(PackageJson)), Effect.option);
144
+ return Option.isSome(manifest) ? manifest.value.version : undefined;
145
+ }
146
+ for (const file of [path.join(root, "package-lock.json"), path.join(root, "node_modules", ".package-lock.json")]) {
147
+ const lock = yield* afs
148
+ .readJson(file)
149
+ .pipe(Effect.flatMap(Schema.decodeUnknownEffect(PackageLock)), Effect.option);
150
+ const revision = gitRevision(Option.isSome(lock) ? lock.value.packages?.[`node_modules/${name}`]?.resolved : undefined);
151
+ if (revision)
152
+ return revision;
153
+ }
154
+ });
155
+ const metadata = Effect.fnUntraced(function* (root, name, dir, target) {
156
+ const manifest = yield* afs
157
+ .readJson(path.join(dir, "package.json"))
158
+ .pipe(Effect.flatMap(Schema.decodeUnknownEffect(PackageJson)), Effect.option);
159
+ const manifestVersion = Option.isSome(manifest) ? manifest.value.version : undefined;
160
+ const revision = target ? (yield* installedRevision(root, name, target)) ?? manifestVersion : undefined;
161
+ const version = target?.type === "git" ? revision : manifestVersion;
162
+ return {
163
+ directory: dir,
164
+ name,
165
+ ...(version ? { version } : {}),
166
+ ...(revision ? { revision } : {}),
167
+ };
168
+ });
169
+ const reify = (input) => Effect.gen(function* () {
170
+ const { Arborist } = yield* Effect.promise(() => import("@npmcli/arborist"));
171
+ const add = input.add ?? [];
172
+ const options = {
173
+ ...(yield* NpmConfig.load(input.config ?? input.dir)),
174
+ ...(input.update ? { preferOnline: true, noGitRevCache: true } : {}),
175
+ // Audit reports are unused here, but Arborist waits for them before completing an install.
176
+ audit: false,
177
+ windowsHide: true,
178
+ };
179
+ const arborist = new Arborist({
180
+ ...options,
181
+ path: input.dir,
182
+ binLinks: true,
183
+ progress: false,
184
+ savePrefix: "",
185
+ ignoreScripts: true,
186
+ });
187
+ return yield* Effect.tryPromise({
188
+ try: () => arborist.reify({
189
+ ...options,
190
+ add,
191
+ update: input.update,
192
+ save: true,
193
+ saveType: "prod",
194
+ }),
195
+ catch: (cause) => new InstallFailedError({
196
+ cause,
197
+ add,
198
+ dir: input.dir,
199
+ }),
200
+ });
201
+ }).pipe(Effect.withSpan("Npm.reify", {
202
+ attributes: input,
203
+ }));
204
+ const install = Effect.fnUntraced(function* (pkg, target, dir, update) {
205
+ yield* flock.acquire(`npm-install:${dir}`);
206
+ const active = yield* current(dir);
207
+ const name = yield* installedName(pkg, active ?? dir, target);
208
+ if (active && !update && (yield* afs.existsSafe(path.join(active, "node_modules", name)))) {
209
+ return yield* metadata(active, name, path.join(active, "node_modules", name), target);
210
+ }
211
+ yield* mkdir(dir);
212
+ const startedAt = yield* Clock.currentTimeMillis;
213
+ // Arborist keys lockfile entries relative to the root's real path. When the cache
214
+ // directory is reached through a symlink (macOS `/var` → `/private/var`, a linked
215
+ // XDG cache), the keys become `../../…` paths that installedRevision never finds,
216
+ // so Git checks report "not installed" and updates go undetected. Stage under the
217
+ // resolved directory so the root path and real path agree.
218
+ const root = yield* fs.realPath(dir).pipe(Effect.mapError((cause) => new InstallFailedError({ dir, cause })));
219
+ const staging = path.join(root, `.staging-${startedAt}-${randomUUID()}`);
220
+ const staged = yield* Effect.gen(function* () {
221
+ const tree = yield* reify({ dir: staging, config: dir, add: [pkg], update });
222
+ const installed = tree.edgesOut.values().next().value?.to;
223
+ const installedNameValue = installed?.name ?? (yield* installedName(pkg, staging, target));
224
+ const result = yield* metadata(staging, installedNameValue, installed?.path ?? path.join(staging, "node_modules", installedNameValue), target);
225
+ if (!installed && !(yield* afs.isDir(result.directory)))
226
+ return yield* new InstallFailedError({ add: [pkg], dir: staging });
227
+ const links = process.platform === "win32"
228
+ ? Array.from(tree.inventory.values()).filter((node) => node.isLink && FSUtil.contains(staging, node.path) && FSUtil.contains(staging, node.realpath))
229
+ : [];
230
+ return { result, links };
231
+ }).pipe(Effect.onError(() => remove(staging, dir).pipe(Effect.ignore)));
232
+ if (active) {
233
+ const activeEntry = yield* metadata(active, name, path.join(active, "node_modules", name), target);
234
+ if (activeEntry.revision && activeEntry.revision === staged.result.revision) {
235
+ yield* remove(staging, dir);
236
+ return activeEntry;
237
+ }
238
+ }
239
+ const completedAt = yield* Clock.currentTimeMillis;
240
+ const newest = Number((yield* generations(dir)).at(-1) ?? 0);
241
+ const generation = path.join(dir, String(Math.max(completedAt, newest + 1)));
242
+ // Windows junctions use absolute targets, so rebase internal links before publishing the generation.
243
+ if (staged.links.length > 0) {
244
+ const { unlink, symlink } = yield* Effect.promise(() => import("node:fs/promises"));
245
+ yield* Effect.forEach(staged.links, (link) => Effect.tryPromise({
246
+ try: async () => {
247
+ await unlink(link.path);
248
+ await symlink(path.join(generation, path.relative(staging, link.realpath)), link.path, "junction");
249
+ },
250
+ catch: (cause) => new InstallFailedError({ dir, cause }),
251
+ }), { discard: true }).pipe(Effect.onError(() => remove(staging, dir).pipe(Effect.ignore)));
252
+ }
253
+ yield* rename(staging, generation, dir);
254
+ return { ...staged.result, directory: path.join(generation, "node_modules", staged.result.name) };
255
+ });
256
+ const collect = Effect.fnUntraced(function* (dir) {
257
+ const now = yield* Clock.currentTimeMillis;
258
+ const completed = yield* generations(dir);
259
+ const keep = new Set(completed.slice(-2));
260
+ const entries = yield* fs.readDirectory(dir).pipe(Effect.orElseSucceed(() => []));
261
+ yield* Effect.forEach(entries, (name) => {
262
+ const timestamp = /^\d+(\.rejected)?$/.test(name)
263
+ ? Number(name.split(".")[0])
264
+ : Number(name.match(/^\.staging-(\d+)-/)?.[1] ?? Number.NaN);
265
+ const maximumAge = name.startsWith(".staging-") ? stagingRetention : retention;
266
+ if (!Number.isFinite(timestamp) || keep.has(name) || now - timestamp <= maximumAge)
267
+ return Effect.void;
268
+ return remove(path.join(dir, name), dir).pipe(Effect.catchCause((cause) => Effect.logWarning("failed to remove stale npm generation", { dir, name, cause })));
269
+ }, { concurrency: "unbounded", discard: true });
270
+ });
271
+ const add = Effect.fn("Npm.add")(function* (pkg) {
272
+ const target = yield* Effect.promise(() => parse(pkg));
273
+ const dir = directory(pkg, target);
274
+ return yield* install(pkg, target, dir, false);
275
+ }, Effect.scoped);
276
+ const resolve = Effect.fn("Npm.resolve")(function* (pkg) {
277
+ const target = yield* Effect.promise(() => parse(pkg));
278
+ const root = directory(pkg, target);
279
+ const generation = yield* current(root);
280
+ const name = yield* installedName(pkg, generation ?? root, target);
281
+ const dir = path.join(generation ?? root, "node_modules", name);
282
+ if (!(yield* afs.existsSafe(dir)))
283
+ return { directory: dir, name };
284
+ return yield* metadata(generation ?? root, name, dir, target);
285
+ });
286
+ const check = Effect.fn("Npm.check")(function* (pkg) {
287
+ const target = yield* Effect.promise(() => parse(pkg));
288
+ const root = directory(pkg, target);
289
+ if (!target)
290
+ return yield* new InstallFailedError({
291
+ dir: root,
292
+ cause: new Error("Package checks only support registry and Git package specs"),
293
+ });
294
+ if (!target.mutable)
295
+ return false;
296
+ const generation = yield* current(root);
297
+ const name = yield* installedName(pkg, generation ?? root, target);
298
+ const installed = generation ? yield* installedRevision(generation, name, target) : undefined;
299
+ if (!installed)
300
+ return yield* new InstallFailedError({ dir: root, cause: new Error(`Package is not installed: ${pkg}`) });
301
+ const { manifest, resolve } = yield* Effect.promise(() => import("pacote"));
302
+ const options = {
303
+ ...(yield* NpmConfig.load(root)),
304
+ preferOnline: true,
305
+ noGitRevCache: true,
306
+ ignoreScripts: true,
307
+ // Pacote spawns Git directly rather than through AppProcess.
308
+ windowsHide: true,
309
+ };
310
+ const available = yield* Effect.tryPromise({
311
+ try: async () => target.type === "git" ? gitRevision(await resolve(pkg, options)) : (await manifest(pkg, options)).version,
312
+ catch: (cause) => new InstallFailedError({ dir: root, cause }),
313
+ });
314
+ if (!available)
315
+ return yield* new InstallFailedError({ dir: root, cause: new Error(`Package revision not found: ${pkg}`) });
316
+ return installed !== available;
317
+ });
318
+ const update = Effect.fn("Npm.update")(function* (pkg) {
319
+ const target = yield* Effect.promise(() => parse(pkg));
320
+ const dir = directory(pkg, target);
321
+ if (!target)
322
+ return yield* new InstallFailedError({
323
+ dir,
324
+ cause: new Error("Package updates only support registry and Git package specs"),
325
+ });
326
+ if (!target.mutable)
327
+ return yield* add(pkg);
328
+ const installed = yield* install(pkg, target, dir, true);
329
+ yield* collect(dir);
330
+ return installed;
331
+ }, Effect.scoped);
332
+ const follows = Effect.fn("Npm.follows")(function* (pkg) {
333
+ const target = yield* Effect.promise(() => parse(pkg));
334
+ if (target?.type !== "git" || !target.ref)
335
+ return target?.follows ?? false;
336
+ const root = directory(pkg, target);
337
+ // Only the remote knows whether a ref is a branch or a tag. pacote keeps the ref it resolved, and Git reuses the
338
+ // refs the update check just listed for a few minutes, so this usually doesn't ask the remote again.
339
+ const { GitFetcher } = (yield* Effect.promise(() => import("pacote")));
340
+ const fetcher = new GitFetcher(pkg, { ...(yield* NpmConfig.load(root)), ignoreScripts: true, windowsHide: true });
341
+ yield* Effect.tryPromise({
342
+ try: () => fetcher.resolve(),
343
+ catch: (cause) => new InstallFailedError({ dir: root, cause }),
344
+ });
345
+ return fetcher.resolvedRef?.type === "branch";
346
+ });
347
+ const reject = Effect.fn("Npm.reject")(function* (pkg, version) {
348
+ const target = yield* Effect.promise(() => parse(pkg));
349
+ const dir = directory(pkg, target);
350
+ yield* flock.acquire(`npm-install:${dir}`);
351
+ const completed = yield* generations(dir);
352
+ const newest = completed.at(-1);
353
+ if (completed.length < 2 || !newest)
354
+ return false;
355
+ const root = path.join(dir, newest);
356
+ const name = yield* installedName(pkg, root, target);
357
+ if ((yield* metadata(root, name, path.join(root, "node_modules", name), target)).version !== version)
358
+ return false;
359
+ yield* fs
360
+ .writeFileString(path.join(dir, `${newest}.rejected`), "")
361
+ .pipe(Effect.mapError((cause) => new InstallFailedError({ dir, cause })));
362
+ return true;
363
+ }, Effect.scoped);
364
+ const which = Effect.fn("Npm.which")(function* (pkg, bin) {
365
+ const target = yield* Effect.promise(() => parse(pkg));
366
+ const root = directory(pkg, target);
367
+ const pick = Effect.fnUntraced(function* (dir) {
368
+ const binDir = path.join(dir, "node_modules", ".bin");
369
+ const files = yield* fs.readDirectory(binDir).pipe(Effect.orElseSucceed(() => []));
370
+ if (files.length === 0)
371
+ return Option.none();
372
+ // Caller picked a specific bin (e.g. pyright exposes both `pyright` and
373
+ // `pyright-langserver`); trust the hint if the package provides it.
374
+ if (bin)
375
+ return files.includes(bin) ? Option.some(path.join(binDir, bin)) : Option.none();
376
+ if (files.length === 1)
377
+ return Option.some(path.join(binDir, files[0]));
378
+ const packageName = target?.name ?? pkg;
379
+ const pkgJson = yield* afs.readJson(path.join(dir, "node_modules", packageName, "package.json")).pipe(Effect.option);
380
+ if (Option.isSome(pkgJson)) {
381
+ const parsed = pkgJson.value;
382
+ if (parsed?.bin) {
383
+ const unscoped = packageName.startsWith("@") ? packageName.split("/")[1] : packageName;
384
+ const parsedBin = parsed.bin;
385
+ if (typeof parsedBin === "string")
386
+ return Option.some(path.join(binDir, unscoped));
387
+ const keys = Object.keys(parsedBin);
388
+ const selected = parsedBin[unscoped] ? unscoped : keys[0];
389
+ return selected ? Option.some(path.join(binDir, selected)) : Option.none();
390
+ }
391
+ }
392
+ return Option.some(path.join(binDir, files[0]));
393
+ });
394
+ return Option.getOrUndefined(yield* Effect.gen(function* () {
395
+ const generation = yield* current(root);
396
+ const selected = generation ? yield* pick(generation) : Option.none();
397
+ if (Option.isSome(selected))
398
+ return selected;
399
+ yield* add(pkg);
400
+ const installed = yield* current(root);
401
+ if (!installed)
402
+ return Option.none();
403
+ return yield* pick(installed);
404
+ }).pipe(Effect.scoped, Effect.orElseSucceed(() => Option.none())));
405
+ });
406
+ return Service.of({
407
+ add,
408
+ resolve,
409
+ check,
410
+ update,
411
+ follows,
412
+ reject,
413
+ which,
414
+ });
415
+ }));
416
+ const unsupported = (what, pkg) => Effect.fail(new InstallFailedError({
417
+ add: [pkg],
418
+ dir: "",
419
+ cause: new Error(`${what} is not supported in this runtime`),
420
+ }));
421
+ export const unsupportedService = Service.of({
422
+ add: (pkg) => unsupported("Npm.add", pkg),
423
+ resolve: (name) => Effect.succeed({ directory: "", name }),
424
+ check: () => Effect.succeed(false),
425
+ update: (pkg) => unsupported("Npm.update", pkg),
426
+ follows: () => Effect.succeed(false),
427
+ reject: () => Effect.succeed(false),
428
+ which: () => Effect.undefined,
429
+ });
430
+ export const unsupportedLayer = Layer.succeed(Service, unsupportedService);
431
+ export const node = makeGlobalNode({
432
+ service: Service,
433
+ layer: layer,
434
+ deps: [FSUtil.node, Global.node, filesystem, EffectFlock.node],
435
+ });
436
+ function gitRevision(resolved) {
437
+ return resolved?.match(/#([a-f0-9]{40}|[a-f0-9]{64})(?=::|$)/i)?.[1];
438
+ }
439
+ function isCommit(value) {
440
+ return /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(value ?? "");
441
+ }
@@ -0,0 +1,14 @@
1
+ import { Effect, FileSystem, Logger } from "effect";
2
+ export declare const LOG_MAX_BYTES: number;
3
+ export declare const LOG_KEEP_BYTES: number;
4
+ export declare const LOG_TRIM_INTERVAL = "1 hour";
5
+ export declare const LOG_TRIM_LOCK_STALE_MS: number;
6
+ export declare function file(local?: boolean, channel?: string): string;
7
+ export declare function fileLogger(target?: string, id?: string): Effect.Effect<Logger.Logger<unknown, void>, import("effect/PlatformError").PlatformError, FileSystem.FileSystem | import("effect/Scope").Scope>;
8
+ export declare const trim: (target: string, options?: {
9
+ max?: number;
10
+ keep?: number;
11
+ } | undefined) => Effect.Effect<void, import("effect/PlatformError").PlatformError, FileSystem.FileSystem>;
12
+ export declare function minimumLogLevel(): "Debug" | "Error" | "Info" | "Warn";
13
+ export declare function loggers(local?: boolean, channel?: string): (Effect.Effect<Logger.Logger<unknown, void>, import("effect/PlatformError").PlatformError, FileSystem.FileSystem | import("effect/Scope").Scope> | Logger.Logger<unknown, void>)[];
14
+ export * as Logging from "./logging.js";
@@ -0,0 +1,151 @@
1
+ import { Effect, FileSystem, Formatter, Logger, Option, Schedule, Stream } from "effect";
2
+ import path from "path";
3
+ import { Global } from "../global.js";
4
+ import { runID } from "./shared.js";
5
+ // One log file is shared by every opencode process on the machine and only ever appended to, so it
6
+ // is bounded by compacting in place instead of rotating: once it passes LOG_MAX_BYTES the head is
7
+ // dropped so roughly LOG_KEEP_BYTES remain, rounded forward to the next line boundary.
8
+ export const LOG_MAX_BYTES = 50 * 1024 * 1024;
9
+ export const LOG_KEEP_BYTES = 25 * 1024 * 1024;
10
+ export const LOG_TRIM_INTERVAL = "1 hour";
11
+ // A trim of a 1 GB log takes well under a second, so a lock older than this belongs to a dead process.
12
+ export const LOG_TRIM_LOCK_STALE_MS = 5 * 60 * 1000;
13
+ const LOG_TRIM_CHUNK = 64 * 1024;
14
+ function formatter(id = runID()) {
15
+ return Logger.map(Logger.formatStructured, (output) => {
16
+ const messages = Array.isArray(output.message) ? output.message : [output.message];
17
+ return [
18
+ ["timestamp", output.timestamp],
19
+ ["level", output.level],
20
+ ["run", id],
21
+ ...messages.flatMap((value) => (plain(value) ? flatten(value) : [["message", value]])),
22
+ ...(output.cause === undefined ? [] : [["cause", output.cause]]),
23
+ ...flatten(output.spans),
24
+ ...flatten(output.annotations),
25
+ ]
26
+ .map(([key, value]) => `${key}=${format(value)}`)
27
+ .join(" ");
28
+ });
29
+ }
30
+ function flatten(input, prefix = "", seen = new WeakSet()) {
31
+ if (seen.has(input))
32
+ return [[prefix, "[Circular]"]];
33
+ seen.add(input);
34
+ const entries = Object.entries(input);
35
+ if (entries.length === 0 && prefix)
36
+ return [[prefix, input]];
37
+ return entries.flatMap(([key, value]) => {
38
+ const path = prefix ? `${prefix}.${key}` : key;
39
+ return plain(value) ? flatten(value, path, seen) : [[path, value]];
40
+ });
41
+ }
42
+ function plain(input) {
43
+ if (input === null || typeof input !== "object" || Array.isArray(input))
44
+ return false;
45
+ const prototype = Object.getPrototypeOf(input);
46
+ return prototype === Object.prototype || prototype === null;
47
+ }
48
+ function format(input) {
49
+ const value = typeof input === "string" ? input : Formatter.format(input);
50
+ return /^[^\s="\\]+$/.test(value) ? value : JSON.stringify(value);
51
+ }
52
+ export function file(local = true, channel = "local") {
53
+ if (!local)
54
+ return path.join(Global.Path.log, "opencode.log");
55
+ return path.join(Global.Path.log, `opencode-${channel.replace(/[^a-zA-Z0-9._-]/g, "-")}.log`);
56
+ }
57
+ export function fileLogger(target = file(), id = runID()) {
58
+ // Do not set batchWindow to 0; it causes high idle CPU usage.
59
+ return Effect.gen(function* () {
60
+ const fs = yield* FileSystem.FileSystem;
61
+ yield* fs.makeDirectory(path.dirname(target), { recursive: true });
62
+ const logger = yield* Logger.toFile(formatter(id), target, { flag: "a" });
63
+ yield* trim(target).pipe(Effect.ignore, Effect.repeat(Schedule.spaced(LOG_TRIM_INTERVAL)), Effect.forkScoped({ startImmediately: true }));
64
+ return logger;
65
+ });
66
+ }
67
+ // Compacts in place rather than writing a temp file and renaming over the log. Other processes hold
68
+ // the same file open with O_APPEND, so they keep appending to the compacted file, whereas a rename
69
+ // would strand them on the unlinked inode and lose their output.
70
+ //
71
+ // Appenders are not coordinated with the final truncate, so a batch flushed by another process
72
+ // between the last read and the truncate is lost. That window is a few milliseconds once per trim,
73
+ // which is an accepted trade for not wrapping every log write in a cross-process lock.
74
+ export const trim = Effect.fn("Logging.trim")(function* (target, options = {}) {
75
+ const max = options.max ?? LOG_MAX_BYTES;
76
+ const keep = options.keep ?? LOG_KEEP_BYTES;
77
+ const fs = yield* FileSystem.FileSystem;
78
+ // Every opencode process on the machine runs this against the same file. Two trimmers racing
79
+ // would have one compute its cut from a size the other already shrank, so only one may proceed
80
+ // and the rest skip until the next interval. mkdir is the atomic primitive on every platform.
81
+ // acquireRelease keeps the mkdir uninterruptible, so a scope closing mid-call cannot leave a lock
82
+ // on disk with no finalizer registered to remove it.
83
+ const lock = `${target}.trim`;
84
+ const acquired = yield* Effect.acquireRelease(fs.makeDirectory(lock).pipe(Effect.as(true), Effect.catchIf((error) => error.reason._tag === "AlreadyExists", () => breakStaleLock(fs, lock))), (acquired) => (acquired ? fs.remove(lock, { recursive: true }).pipe(Effect.ignore) : Effect.void));
85
+ if (!acquired)
86
+ return;
87
+ const size = Number((yield* fs.stat(target)).size);
88
+ if (size <= max)
89
+ return;
90
+ const handle = yield* fs.open(target, { flag: "r+" });
91
+ const start = yield* lineStart(handle, size - keep);
92
+ yield* handle.seek(0n, "start");
93
+ // Reads run to the current EOF so lines appended since the stat survive; the write cursor always
94
+ // trails the read cursor so the forward copy never overwrites unread bytes.
95
+ const written = yield* fs.stream(target, { offset: start, chunkSize: LOG_TRIM_CHUNK }).pipe(Stream.runFoldEffect(() => 0, (total, chunk) => handle.writeAll(chunk).pipe(Effect.as(total + chunk.length))));
96
+ yield* handle.truncate(written);
97
+ }, Effect.scoped);
98
+ // Removes a lock left by a process that died mid-trim. Still yields this round: the next interval
99
+ // acquires cleanly, and a process that is legitimately trimming right now keeps its lock.
100
+ //
101
+ // Two processes that both observe the same stale lock can race here: one removes it, a third
102
+ // acquires fresh, and the other removes that fresh lock. That needs a crash inside a sub-second trim
103
+ // followed by three processes ticking within the same few milliseconds, and the consequence is the
104
+ // same bounded tail loss documented on `trim`. Not worth a breaker protocol; see EffectFlock if it is.
105
+ function breakStaleLock(fs, lock) {
106
+ return Effect.gen(function* () {
107
+ const info = yield* fs.stat(lock).pipe(Effect.option);
108
+ const modified = Option.flatMap(info, (value) => value.mtime);
109
+ if (Option.isNone(modified))
110
+ return false;
111
+ if (Date.now() - modified.value.getTime() < LOG_TRIM_LOCK_STALE_MS)
112
+ return false;
113
+ yield* fs.remove(lock, { recursive: true }).pipe(Effect.ignore);
114
+ return false;
115
+ });
116
+ }
117
+ // First byte after the first newline at or beyond `from`, or EOF when the tail has no newline.
118
+ function lineStart(handle, from) {
119
+ return Effect.gen(function* () {
120
+ let cursor = from;
121
+ while (true) {
122
+ yield* handle.seek(BigInt(cursor), "start");
123
+ const chunk = yield* handle.readAlloc(LOG_TRIM_CHUNK);
124
+ if (Option.isNone(chunk))
125
+ return cursor;
126
+ const newline = chunk.value.indexOf(10);
127
+ if (newline !== -1)
128
+ return cursor + newline + 1;
129
+ cursor += chunk.value.length;
130
+ }
131
+ });
132
+ }
133
+ const stderrLogger = Logger.make((options) => {
134
+ if (process.env.OPENCODE_PRINT_LOGS !== "1")
135
+ return;
136
+ process.stderr.write(formatter().log(options) + "\n");
137
+ });
138
+ export function minimumLogLevel() {
139
+ const value = process.env.OPENCODE_LOG_LEVEL?.toUpperCase();
140
+ const levels = {
141
+ DEBUG: "Debug",
142
+ INFO: "Info",
143
+ WARN: "Warn",
144
+ ERROR: "Error",
145
+ };
146
+ return value && value in levels ? levels[value] : levels.INFO;
147
+ }
148
+ export function loggers(local = true, channel = "local") {
149
+ return [fileLogger(file(local, channel)), stderrLogger];
150
+ }
151
+ export * as Logging from "./logging.js";
@@ -0,0 +1,19 @@
1
+ import { Layer } from "effect";
2
+ import { OtlpExporter, OtlpSerialization } from "effect/observability";
3
+ export interface Options {
4
+ readonly endpoint?: string;
5
+ readonly headers?: string;
6
+ }
7
+ export interface App {
8
+ readonly client: string;
9
+ readonly version: string;
10
+ readonly channel: string;
11
+ }
12
+ export declare function resource(app?: App): {
13
+ serviceName: string;
14
+ serviceVersion: string;
15
+ attributes: Record<string, string>;
16
+ };
17
+ export declare function loggers(options: Options | undefined, app: App): import("effect/Effect").Effect<import("effect/Logger").Logger<unknown, void>, never, OtlpExporter.Flusher | import("effect/http/HttpClient").HttpClient | OtlpSerialization.OtlpSerialization | import("effect/Scope").Scope>[];
18
+ export declare function tracingLayer(options: Options | undefined, app: App): Layer.Layer<never, never, never>;
19
+ export * as Otlp from "./otlp.js";