alink-cli 0.7.2 → 0.7.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.
@@ -0,0 +1,1984 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { Cn as __exportAll } from "./NodeSocket-08w4osAf.mjs";
4
+ import { $d as isNotNull, $i as makeUnsafe, $n as WatchBackend, Ba as catch_, Bi as poll, Br as run, Cd as match, Ci as fromTransform, Cs as void_, Da as as, Fi as failCauseUnsafe, Hc as failCause, Ho as raceFirst, Ic as isDone, Ii as make$10, Io as orDie, Jn as Path$1, Ju as succeed, Ka as effectify, Ko as runFork, Li as offer, Lr as pipeThroughChannelOrFail, Ma as catchCause, Md as Prototype, Mr as mkString, Ni as endUnsafe, Qa as flatMap, Qc as UnknownError, Qd as hasProperty, Qn as Size, Rc as makeUnsafe$1, Rd as BaseProto, Sa as andThen, So as map, Td as some, Tr as isStream, Ui as take, Us as catchDone, Va as clockWith, Vc as fail$1, Vr as runCollect, Ws as isDoneCause, Xn as FileSystem, Ya as fail, Yc as Done, Yn as TypeId$4, Zi as make$8, Zn as FileTypeId, Zo as scoped, Zu as Service, _d as getOrElse, _f as pipe, _i as fromChannel, _r as fromChannel$1, af as isUndefined, ai as make$11, as as suspend, ba as addFinalizer$1, d as ErrorClass, dc as provideMerge, ef as isNotUndefined, ei as transduce, er as make$9, es as serviceOption, fc as succeed$3, ga as systemError, gd as fromUndefinedOr, gf as identity, gs as try_, ha as badArgument, hd as fromNullishOr, hi as drain, hs as tryPromise, id as getUnsafe, ii as get, io as forever, ja as callback, jc as doneUnsafe, jr as merge, jt as tag, ka as asVoid, kc as _await, ko as matchEffect, ku as of, lc as mergeAll, lo as gen, lr as empty, mf as dual, ms as timeoutOrElse, ni as unwrap, nl as fail$2, no as fnUntraced, ns as succeed$1, oo as forkIn, or as decodeText, os as sync, pa as BadArgument, pd as flatMap$1, qc as succeed$2, qr as splitLines, rc as effect, ro as forEach, so as forkScoped, tf as isNullish, tl as done, tr as callback$1, uo as ignore, va as acquireRelease, vc as addFinalizer, vi as isSink, wd as none, wi as mapDone, wo as mapError, ys as uninterruptible, zi as offerUnsafe } from "./Schema-B3i-HrZQ.mjs";
5
+ import * as NodeChildProcess from "node:child_process";
6
+ import { PassThrough } from "node:stream";
7
+ import * as NodeCrypto from "node:crypto";
8
+ import * as NFS from "node:fs";
9
+ import * as OS from "node:os";
10
+ import * as Path from "node:path";
11
+ import * as NodeUrl from "node:url";
12
+ import * as readline from "node:readline";
13
+ //#region ../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/Brand.js
14
+ /**
15
+ * Returns a `Constructor` that **does not apply any runtime checks** and just
16
+ * returns the provided value.
17
+ *
18
+ * **When to use**
19
+ *
20
+ * Use to create nominal types that allow distinguishing between two values
21
+ * of the same type but with different meanings.
22
+ *
23
+ * @see {@link make} for constructing branded values with validation.
24
+ * @see {@link check} for constructing branded values from schema checks.
25
+ *
26
+ * @category constructors
27
+ * @since 2.0.0
28
+ */
29
+ function nominal() {
30
+ return Object.assign((input) => input, {
31
+ option: (input) => some(input),
32
+ result: (input) => succeed(input),
33
+ is: (_) => true
34
+ });
35
+ }
36
+ //#endregion
37
+ //#region ../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/process/ChildProcessSpawner.js
38
+ /**
39
+ * Service boundary for starting and controlling child processes.
40
+ *
41
+ * `ChildProcessSpawner` is the service used by `ChildProcess` commands to start
42
+ * operating-system processes. A spawner turns a command description into a
43
+ * handle that can write to stdin, read stdout and stderr, wait for exit, kill
44
+ * the process, and manage whether the process keeps its parent alive. Platform
45
+ * backends implement this service, while most application code uses the higher
46
+ * level `ChildProcess` module.
47
+ *
48
+ * @since 4.0.0
49
+ */
50
+ /**
51
+ * Constructs branded child process `ExitCode` values.
52
+ *
53
+ * @category constructors
54
+ * @since 4.0.0
55
+ */
56
+ const ExitCode = /*#__PURE__*/ nominal();
57
+ /**
58
+ * Constructs branded child process `ProcessId` values.
59
+ *
60
+ * @category constructors
61
+ * @since 4.0.0
62
+ */
63
+ const ProcessId = /*#__PURE__*/ nominal();
64
+ const HandleTypeId = "~effect/ChildProcessSpawner/ChildProcessHandle";
65
+ const HandleProto = {
66
+ [HandleTypeId]: HandleTypeId,
67
+ ...BaseProto,
68
+ toJSON() {
69
+ return {
70
+ _id: "ChildProcessHandle",
71
+ pid: this.pid
72
+ };
73
+ }
74
+ };
75
+ /**
76
+ * Constructs a new `ChildProcessHandle`.
77
+ *
78
+ * @category constructors
79
+ * @since 4.0.0
80
+ */
81
+ const makeHandle = (params) => Object.setPrototypeOf({ ...params }, HandleProto);
82
+ /**
83
+ * Creates a `ChildProcessSpawner` service from a `spawn` function, deriving
84
+ * helpers for exit codes and output collection from that implementation.
85
+ *
86
+ * @category constructors
87
+ * @since 4.0.0
88
+ */
89
+ const make$7 = (spawn) => {
90
+ const streamString = (command, options) => spawn(command).pipe(map((handle) => decodeText(options?.includeStderr === true ? handle.all : handle.stdout)), unwrap);
91
+ const streamLines = (command, options) => splitLines(streamString(command, options));
92
+ return ChildProcessSpawner.of({
93
+ spawn,
94
+ exitCode: (command) => scoped(flatMap(spawn(command), (handle) => handle.exitCode)),
95
+ streamString,
96
+ streamLines,
97
+ lines: (command, options) => runCollect(streamLines(command, options)),
98
+ string: (command, options) => mkString(streamString(command, options))
99
+ });
100
+ };
101
+ /**
102
+ * Service tag for child process spawning.
103
+ *
104
+ * @category services
105
+ * @since 4.0.0
106
+ */
107
+ var ChildProcessSpawner = class extends Service()("effect/process/ChildProcessSpawner") {};
108
+ //#endregion
109
+ //#region ../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/process/ChildProcess.js
110
+ /**
111
+ * Describes child processes before they are started.
112
+ *
113
+ * A `Command` stores the executable, arguments, environment, standard streams,
114
+ * working directory, and other process options. Commands can also be piped
115
+ * together. A command is an `Effect`; running it asks the
116
+ * `ChildProcessSpawner` service to start the process and returns a
117
+ * `ChildProcessHandle`.
118
+ *
119
+ * @since 4.0.0
120
+ */
121
+ const TypeId$3 = "~effect/unstable/process/ChildProcess";
122
+ const Proto = {
123
+ .../*#__PURE__*/ Prototype({
124
+ label: "Command",
125
+ evaluate(fiber) {
126
+ return getUnsafe(fiber.context, ChildProcessSpawner).spawn(this);
127
+ }
128
+ }),
129
+ [TypeId$3]: TypeId$3
130
+ };
131
+ const makeStandardCommand = (command, args, options) => Object.assign(Object.create(Proto), {
132
+ _tag: "StandardCommand",
133
+ command,
134
+ args,
135
+ options
136
+ });
137
+ /**
138
+ * Create a command from a template literal, options + template, or array form.
139
+ *
140
+ * **Details**
141
+ *
142
+ * This function supports three calling conventions:
143
+ * 1. Template literal: `make\`npm run build\``
144
+ * 2. Options + template literal: `make({ cwd: "/app" })\`npm run build\``
145
+ * 3. Array form: `make("npm", ["run", "build"], options?)`
146
+ *
147
+ * Template literals are not parsed until execution time, allowing parsing
148
+ * errors to flow through Effect's error channel.
149
+ *
150
+ * **Example** (Creating commands)
151
+ *
152
+ * ```ts import.meta.vitest
153
+ * import { ChildProcess } from "effect/unstable/process"
154
+ *
155
+ * // Template literal form
156
+ * const cmd1 = ChildProcess.make`echo "hello"`
157
+ *
158
+ * // With options
159
+ * const cmd2 = ChildProcess.make({ cwd: "/tmp" })`ls -la`
160
+ *
161
+ * // Array form
162
+ * const cmd3 = ChildProcess.make("git", ["status"])
163
+ *
164
+ * const result = [cmd1.command, cmd2.options.cwd, cmd3.args[0]] // => ["echo", "/tmp", "status"]
165
+ * ```
166
+ *
167
+ * @category constructors
168
+ * @since 4.0.0
169
+ */
170
+ const make$6 = function make(...args) {
171
+ if (isTemplateString(args[0])) {
172
+ const [templates, ...expressions] = args;
173
+ const tokens = parseTemplates(templates, expressions);
174
+ return makeStandardCommand(tokens[0] ?? "", tokens.slice(1), {});
175
+ }
176
+ if (typeof args[0] === "object" && !Array.isArray(args[0]) && !isTemplateString(args[0])) {
177
+ const options = args[0];
178
+ return function(templates, ...expressions) {
179
+ const tokens = parseTemplates(templates, expressions);
180
+ return makeStandardCommand(tokens[0] ?? "", tokens.slice(1), options);
181
+ };
182
+ }
183
+ if (typeof args[0] === "string" && !Array.isArray(args[1])) {
184
+ const [command, options = {}] = args;
185
+ return makeStandardCommand(command, [], options);
186
+ }
187
+ const [command, cmdArgs = [], options = {}] = args;
188
+ return makeStandardCommand(command, cmdArgs, options);
189
+ };
190
+ const isTemplateString = (u) => Array.isArray(u) && "raw" in u && Array.isArray(u.raw);
191
+ /**
192
+ * Parses an fd name like "fd3" to its numeric index.
193
+ * Returns undefined if the name is invalid.
194
+ *
195
+ * @category converting
196
+ * @since 4.0.0
197
+ */
198
+ const parseFdName = (name) => {
199
+ const match = /^fd(\d+)$/.exec(name);
200
+ if (match === null) return void 0;
201
+ const fd = parseInt(match[1], 10);
202
+ return fd >= 3 ? fd : void 0;
203
+ };
204
+ /**
205
+ * Create an fd name from its numeric index.
206
+ *
207
+ * @category converting
208
+ * @since 4.0.0
209
+ */
210
+ const fdName = (fd) => `fd${fd}`;
211
+ const parseTemplates = (templates, expressions) => {
212
+ let tokens = [];
213
+ for (const [index, template] of templates.entries()) tokens = parseTemplate(templates, expressions, tokens, template, index);
214
+ return tokens;
215
+ };
216
+ const parseTemplate = (templates, expressions, prevTokens, template, index) => {
217
+ const rawTemplate = templates.raw[index];
218
+ if (rawTemplate === void 0) throw new Error(`Invalid backslash sequence: ${templates.raw[index]}`);
219
+ const { hasLeadingWhitespace, hasTrailingWhitespace, tokens } = splitByWhitespaces(template, rawTemplate);
220
+ const nextTokens = concatTokens(prevTokens, tokens, hasLeadingWhitespace);
221
+ if (index === expressions.length) return nextTokens;
222
+ const expression = expressions[index];
223
+ const expressionTokens = Array.isArray(expression) ? expression.map((expression) => parseExpression(expression)) : [parseExpression(expression)];
224
+ return concatTokens(nextTokens, expressionTokens, hasTrailingWhitespace);
225
+ };
226
+ /**
227
+ * Convert valid expressions defined in a template string command (i.e. using
228
+ * `${expression}` into strings.
229
+ */
230
+ const parseExpression = (expression) => {
231
+ if (typeof expression === "string") return expression;
232
+ return String(expression);
233
+ };
234
+ const DELIMITERS = /*#__PURE__*/ new Set([
235
+ " ",
236
+ " ",
237
+ "\r",
238
+ "\n"
239
+ ]);
240
+ /**
241
+ * Number of characters in backslash escape sequences: \0 \xXX or \uXXXX
242
+ * \cX is allowed in RegExps but not in strings
243
+ * Octal sequences are not allowed in strict mode
244
+ */
245
+ const ESCAPE_LENGTH = {
246
+ x: 3,
247
+ u: 5
248
+ };
249
+ /**
250
+ * Splits a template string by whitespace while also properly handling escape
251
+ * sequences.
252
+ *
253
+ * As an example, let's review the following valid commands:
254
+ *
255
+ * ```ts
256
+ * ChildProcess.exec`echo foo\n bar`
257
+ * // We should run `["echo", "foo\n", "bar"]`
258
+ *
259
+ * ChildProcess.exec`echo foo
260
+ * bar`
261
+ * // We should run `["echo", "foo", "bar]`
262
+ * ```
263
+ *
264
+ * The problem is that when we evaluate the template string for both of the above
265
+ * commands, we will end up with the same string "echo foo\n bar".
266
+ *
267
+ * What we really want is to include the escaped character in the arguments for
268
+ * the first command, since it was written explicitly by the user.
269
+ *
270
+ * This is why also having access to the raw template string is useful - in a
271
+ * template string, there are two representations of the same string:
272
+ * 1. `template` - The processed string (escape sequences are evaluated).
273
+ * 2. `template.raw` - The raw string (escape sequences are literal).
274
+ */
275
+ const splitByWhitespaces = (template, rawTemplate) => {
276
+ if (rawTemplate.length === 0) return {
277
+ tokens: [],
278
+ hasLeadingWhitespace: false,
279
+ hasTrailingWhitespace: false
280
+ };
281
+ const hasLeadingWhitespace = DELIMITERS.has(rawTemplate[0]);
282
+ const tokens = [];
283
+ let templateCursor = 0;
284
+ for (let templateIndex = 0, rawIndex = 0; templateIndex < template.length; templateIndex += 1, rawIndex += 1) {
285
+ const rawCharacter = rawTemplate[rawIndex];
286
+ if (DELIMITERS.has(rawCharacter)) {
287
+ if (templateCursor !== templateIndex) tokens.push(template.slice(templateCursor, templateIndex));
288
+ templateCursor = templateIndex + 1;
289
+ } else if (rawCharacter === "\\") {
290
+ const nextRawCharacter = rawTemplate[rawIndex + 1];
291
+ if (nextRawCharacter === "\n") {
292
+ templateIndex -= 1;
293
+ rawIndex += 1;
294
+ } else if (nextRawCharacter === "u" && rawTemplate[rawIndex + 2] === "{") rawIndex = rawTemplate.indexOf("}", rawIndex + 3);
295
+ else rawIndex += ESCAPE_LENGTH[nextRawCharacter] ?? 1;
296
+ }
297
+ }
298
+ const hasTrailingWhitespace = templateCursor === template.length;
299
+ if (!hasTrailingWhitespace) tokens.push(template.slice(templateCursor));
300
+ return {
301
+ tokens,
302
+ hasLeadingWhitespace,
303
+ hasTrailingWhitespace
304
+ };
305
+ };
306
+ /**
307
+ * Concatenates two separate sets of string tokens together.
308
+ *
309
+ * If either set is empty or `isSeparated=false`, the last element of `prevTokens`
310
+ * and the first element of `nextTokens` will be joined into a single token.
311
+ */
312
+ const concatTokens = (prevTokens, nextTokens, isSeparated) => isSeparated || prevTokens.length === 0 || nextTokens.length === 0 ? [...prevTokens, ...nextTokens] : [
313
+ ...prevTokens.slice(0, -1),
314
+ `${prevTokens.at(-1)}${nextTokens.at(0)}`,
315
+ ...nextTokens.slice(1)
316
+ ];
317
+ //#endregion
318
+ //#region ../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-beta.103_bufferutil@4.1.0_effect@4.0.0-beta.103_patc_c414c3b6e1e822e230993f828f7aeb31/node_modules/@effect/platform-node-shared/dist/internal/utils.js
319
+ /** @internal */
320
+ const handleErrnoException = (module, method) => (err, [path]) => {
321
+ let reason = "Unknown";
322
+ switch (err.code) {
323
+ case "ENOENT":
324
+ reason = "NotFound";
325
+ break;
326
+ case "EACCES":
327
+ reason = "PermissionDenied";
328
+ break;
329
+ case "EEXIST":
330
+ reason = "AlreadyExists";
331
+ break;
332
+ case "EISDIR":
333
+ reason = "BadResource";
334
+ break;
335
+ case "ENOTDIR":
336
+ reason = "BadResource";
337
+ break;
338
+ case "EBUSY":
339
+ reason = "Busy";
340
+ break;
341
+ case "ELOOP":
342
+ reason = "BadResource";
343
+ break;
344
+ }
345
+ return systemError({
346
+ _tag: reason,
347
+ module,
348
+ method,
349
+ pathOrDescriptor: path,
350
+ syscall: err.syscall,
351
+ cause: err
352
+ });
353
+ };
354
+ //#endregion
355
+ //#region ../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-beta.103_bufferutil@4.1.0_effect@4.0.0-beta.103_patc_c414c3b6e1e822e230993f828f7aeb31/node_modules/@effect/platform-node-shared/dist/NodeSink.js
356
+ /**
357
+ * Creates a `Sink` that writes chunks to a Node writable stream, respecting
358
+ * backpressure, mapping writable errors with `onError`, and ending the stream
359
+ * on completion unless `endOnDone` is `false`.
360
+ *
361
+ * @category constructors
362
+ * @since 4.0.0
363
+ */
364
+ const fromWritable = (options) => fromChannel(mapDone(fromWritableChannel(options), (_) => [_]));
365
+ /**
366
+ * Creates a `Channel` that pulls chunks from upstream and writes them to a
367
+ * Node writable stream, respecting backpressure and optionally ending the
368
+ * writable when upstream is done.
369
+ *
370
+ * @category constructors
371
+ * @since 4.0.0
372
+ */
373
+ const fromWritableChannel = (options) => fromTransform((pull) => {
374
+ const writable = options.evaluate();
375
+ return succeed$1(pullIntoWritable({
376
+ ...options,
377
+ writable,
378
+ pull
379
+ }));
380
+ });
381
+ /**
382
+ * Writes Effect chunks into a Node writable stream.
383
+ *
384
+ * **When to use**
385
+ *
386
+ * Use to implement custom Node stream adapters that already have an upstream
387
+ * pull and need direct control over a writable stream.
388
+ *
389
+ * **Details**
390
+ *
391
+ * The loop waits for `drain` when needed, fails on writable errors, and ends
392
+ * the writable on upstream completion unless `endOnDone` is `false`.
393
+ *
394
+ * @category converting
395
+ * @since 4.0.0
396
+ */
397
+ const pullIntoWritable = (options) => options.pull.pipe(flatMap((chunk) => {
398
+ let i = 0;
399
+ return callback(function loop(resume) {
400
+ for (; i < chunk.length;) if (!options.writable.write(chunk[i++], options.encoding)) {
401
+ options.writable.once("drain", () => loop(resume));
402
+ return;
403
+ }
404
+ resume(void_);
405
+ });
406
+ }), forever({ disableYield: true }), raceFirst(callback((resume) => {
407
+ const onError = (error) => resume(fail(options.onError(error)));
408
+ options.writable.once("error", onError);
409
+ return sync(() => {
410
+ options.writable.off("error", onError);
411
+ });
412
+ })), options.endOnDone !== false ? catchDone((_) => {
413
+ if ("closed" in options.writable && options.writable.closed) return done(_);
414
+ return callback((resume) => {
415
+ options.writable.once("finish", () => resume(done(_)));
416
+ options.writable.end();
417
+ });
418
+ }) : identity);
419
+ //#endregion
420
+ //#region ../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-beta.103_bufferutil@4.1.0_effect@4.0.0-beta.103_patc_c414c3b6e1e822e230993f828f7aeb31/node_modules/@effect/platform-node-shared/dist/NodeStream.js
421
+ /**
422
+ * Adapters between Node streams and Effect streams, channels, and readables.
423
+ *
424
+ * This module is the stream boundary for Node APIs. It wraps `Readable` and
425
+ * `Duplex` values as Effect `Stream`s and `Channel`s, pipes Effect streams
426
+ * through Node duplex streams, exposes an Effect `Stream` back to Node as a
427
+ * `Readable`, and collects readable payloads into strings, array buffers, or
428
+ * `Uint8Array`s with optional byte limits.
429
+ *
430
+ * @since 4.0.0
431
+ */
432
+ /**
433
+ * Converts a Node readable stream into an Effect `Stream`, reading chunks with
434
+ * an optional chunk size, mapping stream errors with `onError`, and destroying
435
+ * the readable on completion unless `closeOnDone` is `false`.
436
+ *
437
+ * @category constructors
438
+ * @since 4.0.0
439
+ */
440
+ const fromReadable = (options) => fromChannel$1(fromReadableChannel(options));
441
+ /**
442
+ * Creates a `Channel` that pulls chunks from a Node readable stream, mapping
443
+ * errors with `onError` and destroying the readable on completion unless
444
+ * `closeOnDone` is `false`.
445
+ *
446
+ * @category constructors
447
+ * @since 4.0.0
448
+ */
449
+ const fromReadableChannel = (options) => fromTransform((_, scope) => readableToPullUnsafe({
450
+ scope,
451
+ readable: options.evaluate(),
452
+ onError: options.onError ?? defaultOnError,
453
+ chunkSize: options.chunkSize,
454
+ closeOnDone: options.closeOnDone
455
+ }));
456
+ /**
457
+ * Creates a `Channel` over a Node `Duplex`, writing upstream chunks with
458
+ * backpressure while emitting chunks read from the duplex and optionally ending
459
+ * the writable side when upstream completes.
460
+ *
461
+ * @category constructors
462
+ * @since 4.0.0
463
+ */
464
+ const fromDuplex = (options) => fromTransform((upstream, scope) => {
465
+ const duplex = options.evaluate();
466
+ const exit = make$8(void 0);
467
+ return pullIntoWritable({
468
+ pull: upstream,
469
+ writable: duplex,
470
+ onError: options.onError ?? defaultOnError,
471
+ endOnDone: options.endOnDone,
472
+ encoding: options.encoding
473
+ }).pipe(catchCause((cause) => {
474
+ if (isDoneCause(cause)) return void_;
475
+ exit.current = failCause(cause);
476
+ return void_;
477
+ }), forkIn(scope), flatMap(() => readableToPullUnsafe({
478
+ scope,
479
+ exit,
480
+ readable: duplex,
481
+ onError: options.onError ?? defaultOnError,
482
+ chunkSize: options.chunkSize
483
+ })));
484
+ });
485
+ /**
486
+ * Pipes an Effect `Stream` through a Node `Duplex`, writing the stream's
487
+ * chunks to the duplex and emitting chunks read back from it.
488
+ *
489
+ * @category combinators
490
+ * @since 4.0.0
491
+ */
492
+ const pipeThroughDuplex = /*#__PURE__*/ dual(2, (self, options) => pipeThroughChannelOrFail(self, fromDuplex(options)));
493
+ /**
494
+ * Consumes a Node readable stream into a string using the selected encoding,
495
+ * failing through `onError` on stream errors or when `maxBytes` is exceeded
496
+ * and destroying the stream on interruption or failure.
497
+ *
498
+ * @category converting
499
+ * @since 4.0.0
500
+ */
501
+ const toString = (readable, options) => {
502
+ const maxBytesNumber = options?.maxBytes ? Number(options.maxBytes) : void 0;
503
+ const onError = options?.onError ?? defaultOnError;
504
+ const encoding = options?.encoding ?? "utf8";
505
+ return callback((resume) => {
506
+ const stream = readable();
507
+ stream.setEncoding(encoding);
508
+ stream.once("error", (err) => {
509
+ if ("closed" in stream && !stream.closed) stream.destroy();
510
+ resume(fail(onError(err)));
511
+ });
512
+ stream.once("error", (err) => {
513
+ resume(fail(onError(err)));
514
+ });
515
+ let string = "";
516
+ let bytes = 0;
517
+ stream.once("end", () => {
518
+ resume(succeed$1(string));
519
+ });
520
+ stream.on("data", (chunk) => {
521
+ string += chunk;
522
+ bytes += Buffer.byteLength(chunk);
523
+ if (maxBytesNumber && bytes > maxBytesNumber) resume(fail(onError(/* @__PURE__ */ new Error("maxBytes exceeded"))));
524
+ });
525
+ return sync(() => {
526
+ if ("closed" in stream && !stream.closed) stream.destroy();
527
+ });
528
+ });
529
+ };
530
+ /**
531
+ * Consumes a Node readable stream into an `ArrayBuffer`, failing through
532
+ * `onError` on stream errors or when `maxBytes` is exceeded and destroying the
533
+ * stream on interruption or failure.
534
+ *
535
+ * @category converting
536
+ * @since 4.0.0
537
+ */
538
+ const toArrayBuffer = (readable, options) => {
539
+ const maxBytesNumber = options?.maxBytes ? Number(options.maxBytes) : void 0;
540
+ const onError = options?.onError ?? defaultOnError;
541
+ return callback((resume) => {
542
+ const stream = readable();
543
+ const buffers = [];
544
+ let bytes = 0;
545
+ stream.once("error", (err) => {
546
+ if ("closed" in stream && !stream.closed) stream.destroy();
547
+ resume(fail(onError(err)));
548
+ });
549
+ stream.once("end", () => {
550
+ const buffer = buffers.length === 1 ? buffers[0] : Buffer.concat(buffers);
551
+ if (buffer.byteOffset === 0 && buffer.buffer.byteLength === buffer.byteLength) return resume(succeed$1(buffer.buffer));
552
+ resume(succeed$1(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength)));
553
+ });
554
+ stream.on("data", (chunk) => {
555
+ buffers.push(chunk);
556
+ bytes += chunk.length;
557
+ if (maxBytesNumber && bytes > maxBytesNumber) resume(fail(onError(/* @__PURE__ */ new Error("maxBytes exceeded"))));
558
+ });
559
+ return sync(() => {
560
+ if ("closed" in stream && !stream.closed) stream.destroy();
561
+ });
562
+ });
563
+ };
564
+ /**
565
+ * Consumes a Node readable stream into a `Uint8Array`, using the same error
566
+ * mapping and `maxBytes` handling as `toArrayBuffer`.
567
+ *
568
+ * @category converting
569
+ * @since 4.0.0
570
+ */
571
+ const toUint8Array = (readable, options) => map(toArrayBuffer(readable, options), (buffer) => new Uint8Array(buffer));
572
+ const readableToPullUnsafe = (options) => {
573
+ const readable = options.readable;
574
+ const closeOnDone = options.closeOnDone ?? true;
575
+ const exit = options.exit ?? make$8(void 0);
576
+ const latch = makeUnsafe(false);
577
+ function onReadable() {
578
+ latch.openUnsafe();
579
+ }
580
+ function onError(error) {
581
+ exit.current = fail$1(options.onError(error));
582
+ latch.openUnsafe();
583
+ }
584
+ function onEnd() {
585
+ exit.current = fail$1(Done());
586
+ latch.openUnsafe();
587
+ }
588
+ readable.on("readable", onReadable);
589
+ readable.once("error", onError);
590
+ readable.once("end", onEnd);
591
+ const pull = suspend(function loop() {
592
+ let item = options.readable.read(options.chunkSize);
593
+ if (item === null) {
594
+ if (exit.current) return exit.current;
595
+ if (readable.readableEnded) return fail(Done());
596
+ latch.closeUnsafe();
597
+ return flatMap(latch.await, loop);
598
+ }
599
+ const chunk = of(item);
600
+ while (true) {
601
+ item = options.readable.read(options.chunkSize);
602
+ if (item === null) break;
603
+ chunk.push(item);
604
+ }
605
+ return succeed$1(chunk);
606
+ });
607
+ return as(addFinalizer(options.scope, sync(() => {
608
+ readable.off("readable", onReadable);
609
+ readable.off("error", onError);
610
+ readable.off("end", onEnd);
611
+ if (closeOnDone && "closed" in options.readable && !options.readable.closed) options.readable.destroy();
612
+ })), pull);
613
+ };
614
+ const defaultOnError = (error) => new UnknownError(error);
615
+ //#endregion
616
+ //#region ../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-beta.103_bufferutil@4.1.0_effect@4.0.0-beta.103_patc_c414c3b6e1e822e230993f828f7aeb31/node_modules/@effect/platform-node-shared/dist/NodeChildProcessSpawner.js
617
+ const toError = (error) => error instanceof globalThis.Error ? error : new globalThis.Error(String(error));
618
+ const toPlatformError = (method, error, command) => {
619
+ const { commands } = flattenCommand(command);
620
+ const commandStr = commands.reduce((acc, curr) => {
621
+ const cmd = `${curr.command} ${curr.args.join(" ")}`;
622
+ return acc.length === 0 ? cmd : `${acc} | ${cmd}`;
623
+ }, "");
624
+ return handleErrnoException("ChildProcess", method)(error, [commandStr]);
625
+ };
626
+ /**
627
+ * Layer that provides the `NodeChildProcessSpawner` implementation.
628
+ *
629
+ * @category layers
630
+ * @since 4.0.0
631
+ */
632
+ const layer$11 = /*#__PURE__*/ effect(ChildProcessSpawner, /* @__PURE__ */ gen(function* () {
633
+ const fs = yield* FileSystem;
634
+ const path = yield* Path$1;
635
+ const resolveWorkingDirectory = fnUntraced(function* (options) {
636
+ if (isUndefined(options.cwd)) return void 0;
637
+ yield* fs.access(options.cwd);
638
+ return path.resolve(options.cwd);
639
+ });
640
+ const resolveEnvironment = (options) => {
641
+ return options.extendEnv ? {
642
+ ...globalThis.process.env,
643
+ ...options.env
644
+ } : options.env;
645
+ };
646
+ const inputToStdioOption = (input) => isStream(input) ? "pipe" : input;
647
+ const outputToStdioOption = (input) => isSink(input) ? "pipe" : input;
648
+ const resolveStdinOption = (options) => {
649
+ const defaultConfig = {
650
+ stream: "pipe",
651
+ encoding: "utf-8",
652
+ endOnDone: true
653
+ };
654
+ if (isUndefined(options.stdin)) return defaultConfig;
655
+ if (typeof options.stdin === "string") return {
656
+ ...defaultConfig,
657
+ stream: options.stdin
658
+ };
659
+ if (isStream(options.stdin)) return {
660
+ ...defaultConfig,
661
+ stream: options.stdin
662
+ };
663
+ return {
664
+ stream: options.stdin.stream,
665
+ encoding: options.stdin.encoding ?? defaultConfig.encoding,
666
+ endOnDone: options.stdin.endOnDone ?? defaultConfig.endOnDone
667
+ };
668
+ };
669
+ const resolveOutputOption = (options, streamName) => {
670
+ const option = options[streamName];
671
+ if (isUndefined(option)) return { stream: "pipe" };
672
+ if (typeof option === "string") return { stream: option };
673
+ if (isSink(option)) return { stream: option };
674
+ return { stream: option.stream };
675
+ };
676
+ const resolveAdditionalFds = (options) => {
677
+ if (isUndefined(options.additionalFds)) return [];
678
+ const result = [];
679
+ for (const [name, config] of Object.entries(options.additionalFds)) {
680
+ const fd = parseFdName(name);
681
+ if (isNotUndefined(fd)) result.push({
682
+ fd,
683
+ config
684
+ });
685
+ }
686
+ return result.sort((a, b) => a.fd - b.fd);
687
+ };
688
+ const buildStdioArray = (stdinConfig, stdoutConfig, stderrConfig, additionalFds) => {
689
+ const stdio = [
690
+ inputToStdioOption(stdinConfig.stream),
691
+ outputToStdioOption(stdoutConfig.stream),
692
+ outputToStdioOption(stderrConfig.stream)
693
+ ];
694
+ if (additionalFds.length === 0) return stdio;
695
+ const maxFd = additionalFds.reduce((max, { fd }) => Math.max(max, fd), 2);
696
+ for (let i = 3; i <= maxFd; i++) stdio[i] = "ignore";
697
+ for (const { fd } of additionalFds) stdio[fd] = "pipe";
698
+ return stdio;
699
+ };
700
+ const setupAdditionalFds = fnUntraced(function* (command, childProcess, additionalFds) {
701
+ if (additionalFds.length === 0) return {
702
+ getInputFd: () => drain,
703
+ getOutputFd: () => empty
704
+ };
705
+ const inputSinks = /* @__PURE__ */ new Map();
706
+ const outputStreams = /* @__PURE__ */ new Map();
707
+ for (const { config, fd } of additionalFds) {
708
+ const nodeStream = childProcess.stdio[fd];
709
+ switch (config.type) {
710
+ case "input": {
711
+ let sink = drain;
712
+ if (nodeStream && "write" in nodeStream) sink = fromWritable({
713
+ evaluate: () => nodeStream,
714
+ onError: (error) => toPlatformError(`fromWritable(fd${fd})`, toError(error), command)
715
+ });
716
+ if (config.stream) yield* forkScoped(run(config.stream, sink));
717
+ inputSinks.set(fd, sink);
718
+ break;
719
+ }
720
+ case "output": {
721
+ let stream = empty;
722
+ if (nodeStream && "read" in nodeStream) {
723
+ const passThrough = new PassThrough();
724
+ nodeStream.on("error", (error) => passThrough.destroy(error));
725
+ nodeStream.pipe(passThrough);
726
+ stream = fromReadable({
727
+ evaluate: () => passThrough,
728
+ onError: (error) => toPlatformError(`fromReadable(fd${fd})`, toError(error), command)
729
+ });
730
+ }
731
+ if (config.sink) stream = transduce(stream, config.sink);
732
+ outputStreams.set(fd, stream);
733
+ break;
734
+ }
735
+ }
736
+ }
737
+ return {
738
+ getInputFd: (fd) => inputSinks.get(fd) ?? drain,
739
+ getOutputFd: (fd) => outputStreams.get(fd) ?? empty
740
+ };
741
+ });
742
+ const setupChildStdin = (command, childProcess, config) => suspend(() => {
743
+ let sink = drain;
744
+ if (isNotNull(childProcess.stdin)) sink = fromWritable({
745
+ evaluate: () => childProcess.stdin,
746
+ onError: (error) => toPlatformError("fromWritable(stdin)", toError(error), command),
747
+ endOnDone: config.endOnDone,
748
+ encoding: config.encoding
749
+ });
750
+ if (isStream(config.stream)) return as(forkScoped(run(config.stream, sink)), sink);
751
+ return succeed$1(sink);
752
+ });
753
+ const setupChildOutputStreams = (command, childProcess, stdoutConfig, stderrConfig) => {
754
+ let stdout = childProcess.stdout ? (() => {
755
+ const passThrough = new PassThrough();
756
+ childProcess.stdout.on("error", (error) => passThrough.destroy(error));
757
+ childProcess.stdout.pipe(passThrough);
758
+ return fromReadable({
759
+ evaluate: () => passThrough,
760
+ onError: (error) => toPlatformError("fromReadable(stdout)", toError(error), command)
761
+ });
762
+ })() : empty;
763
+ let stderr = childProcess.stderr ? (() => {
764
+ const passThrough = new PassThrough();
765
+ childProcess.stderr.on("error", (error) => passThrough.destroy(error));
766
+ childProcess.stderr.pipe(passThrough);
767
+ return fromReadable({
768
+ evaluate: () => passThrough,
769
+ onError: (error) => toPlatformError("fromReadable(stderr)", toError(error), command)
770
+ });
771
+ })() : empty;
772
+ if (isSink(stdoutConfig.stream)) stdout = transduce(stdout, stdoutConfig.stream);
773
+ if (isSink(stderrConfig.stream)) stderr = transduce(stderr, stderrConfig.stream);
774
+ const all = merge(stdout, stderr);
775
+ return {
776
+ stdout,
777
+ stderr,
778
+ all
779
+ };
780
+ };
781
+ const spawn = (command, spawnOptions) => callback((resume) => {
782
+ const deferred = makeUnsafe$1();
783
+ const handle = NodeChildProcess.spawn(command.command, command.args, spawnOptions);
784
+ handle.on("error", (error) => {
785
+ resume(fail(toPlatformError("spawn", error, command)));
786
+ });
787
+ handle.on("exit", (...args) => {
788
+ doneUnsafe(deferred, succeed$2(args));
789
+ });
790
+ handle.on("spawn", () => {
791
+ resume(succeed$1([handle, deferred]));
792
+ });
793
+ return sync(() => {
794
+ handle.kill("SIGTERM");
795
+ });
796
+ });
797
+ const killProcessGroup = (command, childProcess, signal) => {
798
+ if (globalThis.process.platform === "win32") return callback((resume) => {
799
+ NodeChildProcess.exec(`taskkill /pid ${childProcess.pid} /T /F`, (error) => {
800
+ if (error) resume(fail(toPlatformError("kill", toError(error), command)));
801
+ else resume(void_);
802
+ });
803
+ });
804
+ return try_({
805
+ try: () => {
806
+ globalThis.process.kill(-childProcess.pid, signal);
807
+ },
808
+ catch: (error) => toPlatformError("kill", toError(error), command)
809
+ });
810
+ };
811
+ const killProcessGroupOnExit = (childProcess, signal) => {
812
+ if (globalThis.process.platform === "win32") {
813
+ NodeChildProcess.exec(`taskkill /pid ${childProcess.pid} /T /F`, () => {});
814
+ return;
815
+ }
816
+ try {
817
+ globalThis.process.kill(-childProcess.pid, signal);
818
+ } catch {}
819
+ };
820
+ const killProcess = (command, childProcess, signal) => suspend(() => {
821
+ if (!childProcess.kill(signal)) {
822
+ const error = new globalThis.Error("Failed to kill child process");
823
+ return fail(toPlatformError("kill", error, command));
824
+ }
825
+ return void_;
826
+ });
827
+ const withTimeout = (childProcess, command, options) => (kill) => {
828
+ const killSignal = options?.killSignal ?? "SIGTERM";
829
+ return isUndefined(options?.forceKillAfter) ? kill(command, childProcess, killSignal) : timeoutOrElse(kill(command, childProcess, killSignal), {
830
+ duration: options.forceKillAfter,
831
+ orElse: () => kill(command, childProcess, "SIGKILL")
832
+ });
833
+ };
834
+ /**
835
+ * Get the appropriate source stream from a process handle based on the
836
+ * `from` pipe option.
837
+ */
838
+ const getSourceStream = (handle, from) => {
839
+ const fromOption = from ?? "stdout";
840
+ switch (fromOption) {
841
+ case "stdout": return handle.stdout;
842
+ case "stderr": return handle.stderr;
843
+ case "all": return handle.all;
844
+ default: {
845
+ const fd = parseFdName(fromOption);
846
+ if (isNotUndefined(fd)) return handle.getOutputFd(fd);
847
+ return handle.stdout;
848
+ }
849
+ }
850
+ };
851
+ const spawnCommand = fnUntraced(function* (cmd) {
852
+ switch (cmd._tag) {
853
+ case "StandardCommand": {
854
+ const stdinConfig = resolveStdinOption(cmd.options);
855
+ const stdoutConfig = resolveOutputOption(cmd.options, "stdout");
856
+ const stderrConfig = resolveOutputOption(cmd.options, "stderr");
857
+ const resolvedAdditionalFds = resolveAdditionalFds(cmd.options);
858
+ let isReferenced = true;
859
+ const cwd = yield* resolveWorkingDirectory(cmd.options);
860
+ const env = resolveEnvironment(cmd.options);
861
+ const stdio = buildStdioArray(stdinConfig, stdoutConfig, stderrConfig, resolvedAdditionalFds);
862
+ const [childProcess, exitSignal] = yield* acquireRelease(spawn(cmd, {
863
+ cwd,
864
+ env,
865
+ stdio,
866
+ detached: cmd.options.detached ?? process.platform !== "win32",
867
+ shell: cmd.options.shell
868
+ }), fnUntraced(function* ([childProcess, exitSignal]) {
869
+ const exited = yield* isDone(exitSignal);
870
+ const killWithTimeout = withTimeout(childProcess, cmd, cmd.options);
871
+ if (exited) {
872
+ const [code] = yield* _await(exitSignal);
873
+ if (code !== 0 && isNotNull(code)) return yield* ignore(killWithTimeout(killProcessGroup));
874
+ return yield* void_;
875
+ }
876
+ if (!isReferenced) return yield* void_;
877
+ return yield* killWithTimeout((command, childProcess, signal) => killProcessGroup(command, childProcess, signal).pipe(catch_(() => killProcess(command, childProcess, signal)), andThen(_await(exitSignal)))).pipe(ignore);
878
+ }));
879
+ const pid = ProcessId(childProcess.pid);
880
+ childProcess.on("exit", (code) => {
881
+ if (code !== 0 && isNotNull(code)) killProcessGroupOnExit(childProcess, cmd.options.killSignal ?? "SIGTERM");
882
+ });
883
+ const reref = sync(() => {
884
+ if (!isReferenced) {
885
+ childProcess.ref();
886
+ isReferenced = true;
887
+ }
888
+ });
889
+ const unref = sync(() => {
890
+ if (isReferenced) {
891
+ childProcess.unref();
892
+ isReferenced = false;
893
+ }
894
+ return reref;
895
+ });
896
+ const stdin = yield* setupChildStdin(cmd, childProcess, stdinConfig);
897
+ const { all, stderr, stdout } = setupChildOutputStreams(cmd, childProcess, stdoutConfig, stderrConfig);
898
+ const { getInputFd, getOutputFd } = yield* setupAdditionalFds(cmd, childProcess, resolvedAdditionalFds);
899
+ const isRunning = map(isDone(exitSignal), (done) => !done);
900
+ const exitCode = flatMap(_await(exitSignal), ([code, signal]) => {
901
+ if (isNotNull(code)) return succeed$1(ExitCode(code));
902
+ const error = new globalThis.Error(`Process interrupted due to receipt of signal: '${signal}'`);
903
+ return fail(toPlatformError("exitCode", error, cmd));
904
+ });
905
+ const kill = (options) => {
906
+ return withTimeout(childProcess, cmd, options)((command, childProcess, signal) => killProcessGroup(command, childProcess, signal).pipe(catch_(() => killProcess(command, childProcess, signal)), andThen(_await(exitSignal)))).pipe(asVoid);
907
+ };
908
+ return makeHandle({
909
+ pid,
910
+ exitCode,
911
+ isRunning,
912
+ kill,
913
+ stdin,
914
+ stdout,
915
+ stderr,
916
+ all,
917
+ getInputFd,
918
+ getOutputFd,
919
+ unref
920
+ });
921
+ }
922
+ case "PipedCommand": {
923
+ const { commands, pipeOptions } = flattenCommand(cmd);
924
+ const [root, ...pipeline] = commands;
925
+ const handles = [yield* spawnCommand(root)];
926
+ for (let i = 0; i < pipeline.length; i++) {
927
+ const command = pipeline[i];
928
+ const options = pipeOptions[i] ?? {};
929
+ const stdinConfig = resolveStdinOption(command.options);
930
+ const sourceStream = unwrap(succeed$1(getSourceStream(handles[handles.length - 1], options.from)));
931
+ const toOption = options.to ?? "stdin";
932
+ if (toOption === "stdin") handles.push(yield* spawnCommand(make$6(command.command, command.args, {
933
+ ...command.options,
934
+ stdin: {
935
+ ...stdinConfig,
936
+ stream: sourceStream
937
+ }
938
+ })));
939
+ else {
940
+ const fd = parseFdName(toOption);
941
+ if (isNotUndefined(fd)) {
942
+ const fdName$1 = fdName(fd);
943
+ const existingFds = command.options.additionalFds ?? {};
944
+ handles.push(yield* spawnCommand(make$6(command.command, command.args, {
945
+ ...command.options,
946
+ additionalFds: {
947
+ ...existingFds,
948
+ [fdName$1]: {
949
+ type: "input",
950
+ stream: sourceStream
951
+ }
952
+ }
953
+ })));
954
+ } else handles.push(yield* spawnCommand(make$6(command.command, command.args, {
955
+ ...command.options,
956
+ stdin: {
957
+ ...stdinConfig,
958
+ stream: sourceStream
959
+ }
960
+ })));
961
+ }
962
+ }
963
+ const handle = handles[handles.length - 1];
964
+ const unref = gen(function* () {
965
+ const rerefs = [];
966
+ for (const handle of handles) rerefs.push(yield* handle.unref);
967
+ return forEach([...rerefs].reverse(), (reref) => reref, { discard: true });
968
+ });
969
+ return makeHandle({
970
+ pid: handle.pid,
971
+ exitCode: handle.exitCode,
972
+ isRunning: handle.isRunning,
973
+ kill: handle.kill,
974
+ stdin: handle.stdin,
975
+ stdout: handle.stdout,
976
+ stderr: handle.stderr,
977
+ all: handle.all,
978
+ getInputFd: handle.getInputFd,
979
+ getOutputFd: handle.getOutputFd,
980
+ unref
981
+ });
982
+ }
983
+ }
984
+ });
985
+ return make$7(spawnCommand);
986
+ }));
987
+ /**
988
+ * Flattens a `Command` into an array of `StandardCommand`s along with pipe
989
+ * options for each connection.
990
+ *
991
+ * @category transforming
992
+ * @since 4.0.0
993
+ */
994
+ const flattenCommand = (command) => {
995
+ const commands = [];
996
+ const pipeOptions = [];
997
+ const flatten = (cmd) => {
998
+ switch (cmd._tag) {
999
+ case "StandardCommand":
1000
+ commands.push(cmd);
1001
+ break;
1002
+ case "PipedCommand":
1003
+ flatten(cmd.left);
1004
+ pipeOptions.push(cmd.options);
1005
+ flatten(cmd.right);
1006
+ break;
1007
+ }
1008
+ };
1009
+ flatten(command);
1010
+ if (commands.length === 0) throw new Error("flattenCommand produced empty commands array");
1011
+ const [first, ...rest] = commands;
1012
+ return {
1013
+ commands: [first, ...rest],
1014
+ pipeOptions
1015
+ };
1016
+ };
1017
+ //#endregion
1018
+ //#region ../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/Crypto.js
1019
+ /**
1020
+ * Defines a platform-independent service for cryptographic operations.
1021
+ *
1022
+ * Runtime packages provide concrete implementations backed by the host
1023
+ * platform's cryptography APIs. This module defines the service interface and a
1024
+ * constructor from random-byte and digest primitives. The service provides
1025
+ * secure random bytes and numbers, UUIDv4 and UUIDv7 generation, shuffling, and
1026
+ * SHA message digests.
1027
+ *
1028
+ * @since 4.0.0
1029
+ */
1030
+ const TypeId$2 = "~effect/platform/Crypto";
1031
+ /**
1032
+ * Service tag for platform cryptography.
1033
+ *
1034
+ * **When to use**
1035
+ *
1036
+ * Use when you need to provide or retrieve the full platform cryptography
1037
+ * service from an effect's context.
1038
+ *
1039
+ * **Details**
1040
+ *
1041
+ * Providing this service supplies platform-agnostic cryptographic operations
1042
+ * such as hashing, UUID generation, and secure random values.
1043
+ *
1044
+ * @see {@link make} for constructing a Crypto service from primitive operations
1045
+ *
1046
+ * @category services
1047
+ * @since 4.0.0
1048
+ */
1049
+ const Crypto = /*#__PURE__*/ Service("effect/Crypto");
1050
+ /**
1051
+ * Creates a `Crypto` service from the primitive implementation, deriving the
1052
+ * random generator helpers and UUID generation from those primitives.
1053
+ *
1054
+ * **When to use**
1055
+ *
1056
+ * Use to build a Crypto service for a platform integration, test layer, or
1057
+ * custom runtime from primitive random-byte and digest operations.
1058
+ *
1059
+ * **Details**
1060
+ *
1061
+ * The constructor derives random numbers, booleans, integer ranges, shuffling,
1062
+ * and UUID generation from `impl.randomBytes`. Digest operations delegate to
1063
+ * `impl.digest`.
1064
+ *
1065
+ * **Gotchas**
1066
+ *
1067
+ * `impl.randomBytes` must return cryptographically secure bytes of the
1068
+ * requested length. UUID formatting mutates the byte array returned for UUID
1069
+ * generation, so the implementation should return a fresh array for each call.
1070
+ *
1071
+ * **Example** (Creating a Crypto service)
1072
+ *
1073
+ * ```ts import.meta.vitest
1074
+ * import { Crypto, Effect } from "effect"
1075
+ *
1076
+ * const testCrypto = Crypto.make({
1077
+ * randomBytes: (size) => new Uint8Array(size),
1078
+ * digest: (_algorithm, data) => Effect.succeed(data)
1079
+ * })
1080
+ *
1081
+ * await Effect.runPromise(testCrypto.randomBytes(4)) // => new Uint8Array([0, 0, 0, 0])
1082
+ * ```
1083
+ *
1084
+ * @category constructors
1085
+ * @since 4.0.0
1086
+ */
1087
+ const make$4 = (impl) => {
1088
+ const randomBytesUnsafe = impl.randomBytes;
1089
+ const randomBytes = (size) => map(validateSize("randomBytes", size), randomBytesUnsafe);
1090
+ const nextDoubleUnsafe = () => {
1091
+ const bytes = randomBytesUnsafe(7);
1092
+ return ((bytes[0] & 31) * 2 ** 48 + bytes[1] * 2 ** 40 + bytes[2] * 2 ** 32 + bytes[3] * 2 ** 24 + bytes[4] * 2 ** 16 + bytes[5] * 2 ** 8 + bytes[6]) / 2 ** 53;
1093
+ };
1094
+ const nextIntUnsafe = () => Math.floor(nextDoubleUnsafe() * (Number.MAX_SAFE_INTEGER - Number.MIN_SAFE_INTEGER + 1)) + Number.MIN_SAFE_INTEGER;
1095
+ return Crypto.of({
1096
+ [TypeId$2]: TypeId$2,
1097
+ randomBytes,
1098
+ nextDoubleUnsafe,
1099
+ nextIntUnsafe,
1100
+ digest: impl.digest,
1101
+ random: sync(() => nextDoubleUnsafe()),
1102
+ randomBoolean: sync(() => nextDoubleUnsafe() > .5),
1103
+ randomInt: sync(() => nextIntUnsafe()),
1104
+ randomBetween: (min, max) => sync(() => nextDoubleUnsafe() * (max - min) + min),
1105
+ randomIntBetween(min, max, options) {
1106
+ const extra = options?.halfOpen === true ? 0 : 1;
1107
+ return sync(() => {
1108
+ const minInt = Math.ceil(min);
1109
+ const maxInt = Math.floor(max);
1110
+ return Math.floor(nextDoubleUnsafe() * (maxInt - minInt + extra)) + minInt;
1111
+ });
1112
+ },
1113
+ randomShuffle: (elements) => sync(() => {
1114
+ const buffer = Array.from(elements);
1115
+ for (let i = buffer.length - 1; i >= 1; i = i - 1) {
1116
+ const index = Math.min(i, Math.floor(nextDoubleUnsafe() * (i + 1)));
1117
+ const value = buffer[i];
1118
+ buffer[i] = buffer[index];
1119
+ buffer[index] = value;
1120
+ }
1121
+ return buffer;
1122
+ }),
1123
+ randomUUIDv4: sync(() => formatUUIDv4(randomBytesUnsafe(16))),
1124
+ randomUUIDv7: clockWith((clock) => succeed$1(formatUUIDv7(clock.currentTimeMillisUnsafe(), randomBytesUnsafe(16))))
1125
+ });
1126
+ };
1127
+ const validateSize = (method, size) => Number.isSafeInteger(size) && size >= 0 ? succeed$1(size) : fail(badArgument({
1128
+ module: "Crypto",
1129
+ method,
1130
+ description: "size must be a non-negative safe integer"
1131
+ }));
1132
+ const hex = (byte) => byte.toString(16).padStart(2, "0");
1133
+ const formatUUID = (bytes) => {
1134
+ return [
1135
+ bytes.subarray(0, 4),
1136
+ bytes.subarray(4, 6),
1137
+ bytes.subarray(6, 8),
1138
+ bytes.subarray(8, 10),
1139
+ bytes.subarray(10, 16)
1140
+ ].map((segment) => Array.from(segment, hex).join("")).join("-");
1141
+ };
1142
+ const formatUUIDv4 = (bytes) => {
1143
+ bytes[6] = bytes[6] & 15 | 64;
1144
+ bytes[8] = bytes[8] & 63 | 128;
1145
+ return formatUUID(bytes);
1146
+ };
1147
+ const maxUUIDv7Timestamp = 2 ** 48 - 1;
1148
+ const formatUUIDv7 = (timestampMillis, bytes) => {
1149
+ const timestamp = Math.min(Math.max(0, Math.trunc(timestampMillis)), maxUUIDv7Timestamp);
1150
+ bytes[0] = Math.floor(timestamp / 2 ** 40);
1151
+ bytes[1] = Math.floor(timestamp / 2 ** 32) & 255;
1152
+ bytes[2] = Math.floor(timestamp / 2 ** 24) & 255;
1153
+ bytes[3] = Math.floor(timestamp / 2 ** 16) & 255;
1154
+ bytes[4] = Math.floor(timestamp / 2 ** 8) & 255;
1155
+ bytes[5] = timestamp & 255;
1156
+ bytes[6] = bytes[6] & 15 | 112;
1157
+ bytes[8] = bytes[8] & 63 | 128;
1158
+ return formatUUID(bytes);
1159
+ };
1160
+ //#endregion
1161
+ //#region ../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-beta.103_bufferutil@4.1.0_effect@4.0.0-beta.103_patc_c414c3b6e1e822e230993f828f7aeb31/node_modules/@effect/platform-node-shared/dist/NodeCrypto.js
1162
+ /**
1163
+ * Node-compatible implementation of Effect's `Crypto` service.
1164
+ *
1165
+ * This module builds the service from `node:crypto`, using `randomBytes` for
1166
+ * random data and `createHash` for supported digest algorithms. It exports
1167
+ * `make` as the concrete service value and `layer` for providing it through
1168
+ * Effect context.
1169
+ *
1170
+ * @since 1.0.0
1171
+ */
1172
+ const toHashAlgorithm = (algorithm) => {
1173
+ switch (algorithm) {
1174
+ case "SHA-1": return "sha1";
1175
+ case "SHA-256": return "sha256";
1176
+ case "SHA-384": return "sha384";
1177
+ case "SHA-512": return "sha512";
1178
+ }
1179
+ };
1180
+ const digest = (algorithm, data) => try_({
1181
+ try: () => Uint8Array.from(NodeCrypto.createHash(toHashAlgorithm(algorithm)).update(data).digest()),
1182
+ catch: (cause) => systemError({
1183
+ module: "Crypto",
1184
+ method: "digest",
1185
+ _tag: "Unknown",
1186
+ description: "Could not compute digest",
1187
+ cause
1188
+ })
1189
+ });
1190
+ //#endregion
1191
+ //#region ../../node_modules/.pnpm/@effect+platform-node@4.0.0-beta.103_bufferutil@4.1.0_effect@4.0.0-beta.103_patch_hash=_7eec308fcf6351488fccaf9a0edac255/node_modules/@effect/platform-node/dist/NodeCrypto.js
1192
+ /**
1193
+ * The `NodeCrypto` module provides the Node.js `Crypto` service layer for
1194
+ * Effect programs. Provide {@link layer} at the edge of a Node application,
1195
+ * CLI, script, or test to satisfy `effect/Crypto` with Node's `node:crypto`
1196
+ * implementation for secure random bytes, UUID generation, random values, and
1197
+ * SHA digest operations.
1198
+ *
1199
+ * This module is the public Node adapter around the shared Node-compatible
1200
+ * implementation. Digest failures are reported as platform errors, and SHA-1
1201
+ * remains available only for interoperability with existing protocols.
1202
+ *
1203
+ * @since 1.0.0
1204
+ */
1205
+ /**
1206
+ * Layer that provides the Node.js Crypto service implementation.
1207
+ *
1208
+ * @category layers
1209
+ * @since 1.0.0
1210
+ */
1211
+ const layer$9 = /* @__PURE__ */ succeed$3(Crypto, /* @__PURE__ */ make$4({
1212
+ randomBytes: NodeCrypto.randomBytes,
1213
+ digest
1214
+ }));
1215
+ //#endregion
1216
+ //#region ../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-beta.103_bufferutil@4.1.0_effect@4.0.0-beta.103_patc_c414c3b6e1e822e230993f828f7aeb31/node_modules/@effect/platform-node-shared/dist/NodeFileSystem.js
1217
+ /**
1218
+ * Shared Node-compatible implementation of Effect's `FileSystem` service.
1219
+ *
1220
+ * This module adapts Node's `node:fs`, `node:os`, and `node:path` APIs into a
1221
+ * `FileSystem` layer for Effect programs running on Node-compatible runtimes.
1222
+ * Platform packages use it to provide file and directory I/O, permissions,
1223
+ * links, metadata, temporary files and directories, and file watching through
1224
+ * the shared `FileSystem` service.
1225
+ *
1226
+ * @since 4.0.0
1227
+ */
1228
+ const handleBadArgument = (method) => (err) => badArgument({
1229
+ module: "FileSystem",
1230
+ method,
1231
+ description: err.message ?? String(err)
1232
+ });
1233
+ const access = /*#__PURE__*/ (() => {
1234
+ const nodeAccess = /*#__PURE__*/ effectify(NFS.access, /*#__PURE__*/ handleErrnoException("FileSystem", "access"), /*#__PURE__*/ handleBadArgument("access"));
1235
+ return (path, options) => {
1236
+ let mode = NFS.constants.F_OK;
1237
+ if (options?.readable) mode |= NFS.constants.R_OK;
1238
+ if (options?.writable) mode |= NFS.constants.W_OK;
1239
+ return nodeAccess(path, mode);
1240
+ };
1241
+ })();
1242
+ const copy = /*#__PURE__*/ (() => {
1243
+ const nodeCp = /*#__PURE__*/ effectify(NFS.cp, /*#__PURE__*/ handleErrnoException("FileSystem", "copy"), /*#__PURE__*/ handleBadArgument("copy"));
1244
+ return (fromPath, toPath, options) => nodeCp(fromPath, toPath, {
1245
+ force: options?.overwrite ?? false,
1246
+ preserveTimestamps: options?.preserveTimestamps ?? false,
1247
+ recursive: true
1248
+ });
1249
+ })();
1250
+ const copyFile = /*#__PURE__*/ (() => {
1251
+ const nodeCopyFile = /*#__PURE__*/ effectify(NFS.copyFile, /*#__PURE__*/ handleErrnoException("FileSystem", "copyFile"), /*#__PURE__*/ handleBadArgument("copyFile"));
1252
+ return (fromPath, toPath) => nodeCopyFile(fromPath, toPath);
1253
+ })();
1254
+ const chmod = /*#__PURE__*/ (() => {
1255
+ const nodeChmod = /*#__PURE__*/ effectify(NFS.chmod, /*#__PURE__*/ handleErrnoException("FileSystem", "chmod"), /*#__PURE__*/ handleBadArgument("chmod"));
1256
+ return (path, mode) => nodeChmod(path, mode);
1257
+ })();
1258
+ const chown = /*#__PURE__*/ (() => {
1259
+ const nodeChown = /*#__PURE__*/ effectify(NFS.chown, /*#__PURE__*/ handleErrnoException("FileSystem", "chown"), /*#__PURE__*/ handleBadArgument("chown"));
1260
+ return (path, uid, gid) => nodeChown(path, uid, gid);
1261
+ })();
1262
+ const glob = /*#__PURE__*/ (() => {
1263
+ const nodeGlob = /*#__PURE__*/ effectify(NFS.glob, /*#__PURE__*/ handleErrnoException("FileSystem", "glob"), /*#__PURE__*/ handleBadArgument("glob"));
1264
+ return (pattern, options) => nodeGlob(pattern, {
1265
+ cwd: options?.root,
1266
+ exclude: options?.exclude
1267
+ });
1268
+ })();
1269
+ const link = /*#__PURE__*/ (() => {
1270
+ const nodeLink = /*#__PURE__*/ effectify(NFS.link, /*#__PURE__*/ handleErrnoException("FileSystem", "link"), /*#__PURE__*/ handleBadArgument("link"));
1271
+ return (existingPath, newPath) => nodeLink(existingPath, newPath);
1272
+ })();
1273
+ const makeDirectory = /*#__PURE__*/ (() => {
1274
+ const nodeMkdir = /*#__PURE__*/ effectify(NFS.mkdir, /*#__PURE__*/ handleErrnoException("FileSystem", "makeDirectory"), /*#__PURE__*/ handleBadArgument("makeDirectory"));
1275
+ return (path, options) => nodeMkdir(path, {
1276
+ recursive: options?.recursive ?? false,
1277
+ mode: options?.mode
1278
+ });
1279
+ })();
1280
+ const makeTempDirectoryFactory = (method) => {
1281
+ const nodeMkdtemp = effectify(NFS.mkdtemp, handleErrnoException("FileSystem", method), handleBadArgument(method));
1282
+ return (options) => suspend(() => {
1283
+ const prefix = options?.prefix ?? "";
1284
+ const directory = typeof options?.directory === "string" ? Path.join(options.directory, ".") : OS.tmpdir();
1285
+ return nodeMkdtemp(prefix ? Path.join(directory, prefix) : directory + "/");
1286
+ });
1287
+ };
1288
+ const makeTempDirectory = /*#__PURE__*/ makeTempDirectoryFactory("makeTempDirectory");
1289
+ const removeFactory = (method) => {
1290
+ const nodeRm = effectify(NFS.rm, handleErrnoException("FileSystem", method), handleBadArgument(method));
1291
+ return (path, options) => nodeRm(path, {
1292
+ recursive: options?.recursive ?? false,
1293
+ force: options?.force ?? false
1294
+ });
1295
+ };
1296
+ const remove = /*#__PURE__*/ removeFactory("remove");
1297
+ const makeTempDirectoryScoped = /*#__PURE__*/ (() => {
1298
+ const makeDirectory = /*#__PURE__*/ makeTempDirectoryFactory("makeTempDirectoryScoped");
1299
+ const removeDirectory = /*#__PURE__*/ removeFactory("makeTempDirectoryScoped");
1300
+ return (options) => acquireRelease(makeDirectory(options), (directory) => orDie(removeDirectory(directory, { recursive: true })));
1301
+ })();
1302
+ const openFactory = (method) => {
1303
+ const nodeOpen = effectify(NFS.open, handleErrnoException("FileSystem", method), handleBadArgument(method));
1304
+ const nodeClose = effectify(NFS.close, handleErrnoException("FileSystem", method), handleBadArgument(method));
1305
+ return (path, options) => pipe(acquireRelease(nodeOpen(path, options?.flag ?? "r", options?.mode), (fd) => orDie(nodeClose(fd))), map((fd) => makeFile(fd, options?.flag?.startsWith("a") ?? false)));
1306
+ };
1307
+ const open = /*#__PURE__*/ openFactory("open");
1308
+ const makeFile = /*#__PURE__*/ (() => {
1309
+ const nodeReadFactory = (method) => effectify(NFS.read, handleErrnoException("FileSystem", method), handleBadArgument(method));
1310
+ const nodeRead = /*#__PURE__*/ nodeReadFactory("read");
1311
+ const nodeReadAlloc = /*#__PURE__*/ nodeReadFactory("readAlloc");
1312
+ const nodeStat = /*#__PURE__*/ effectify(NFS.fstat, /*#__PURE__*/ handleErrnoException("FileSystem", "stat"), /*#__PURE__*/ handleBadArgument("stat"));
1313
+ const nodeTruncate = /*#__PURE__*/ effectify(NFS.ftruncate, /*#__PURE__*/ handleErrnoException("FileSystem", "truncate"), /*#__PURE__*/ handleBadArgument("truncate"));
1314
+ const nodeSync = /*#__PURE__*/ effectify(NFS.fsync, /*#__PURE__*/ handleErrnoException("FileSystem", "sync"), /*#__PURE__*/ handleBadArgument("sync"));
1315
+ const nodeWriteFactory = (method) => effectify(NFS.write, handleErrnoException("FileSystem", method), handleBadArgument(method));
1316
+ const nodeWrite = /*#__PURE__*/ nodeWriteFactory("write");
1317
+ const nodeWriteAll = /*#__PURE__*/ nodeWriteFactory("writeAll");
1318
+ class FileImpl {
1319
+ [FileTypeId];
1320
+ fd;
1321
+ append;
1322
+ position = /*#__PURE__*/ BigInt(0);
1323
+ constructor(fd, append) {
1324
+ this[FileTypeId] = FileTypeId;
1325
+ this.fd = fd;
1326
+ this.append = append;
1327
+ }
1328
+ get stat() {
1329
+ return map(nodeStat(this.fd), makeFileInfo);
1330
+ }
1331
+ get sync() {
1332
+ return nodeSync(this.fd);
1333
+ }
1334
+ seek(offset, from) {
1335
+ const offsetSize = Size(offset);
1336
+ return sync(() => {
1337
+ if (from === "start") this.position = offsetSize;
1338
+ else if (from === "current") this.position = this.position + offsetSize;
1339
+ return this.position;
1340
+ });
1341
+ }
1342
+ read(buffer) {
1343
+ return suspend(() => {
1344
+ const position = this.position;
1345
+ return map(nodeRead(this.fd, {
1346
+ buffer,
1347
+ position
1348
+ }), (bytesRead) => {
1349
+ const sizeRead = Size(bytesRead);
1350
+ this.position = position + sizeRead;
1351
+ return sizeRead;
1352
+ });
1353
+ });
1354
+ }
1355
+ readAlloc(size) {
1356
+ const sizeNumber = Number(size);
1357
+ return suspend(() => {
1358
+ const buffer = Buffer.allocUnsafeSlow(sizeNumber);
1359
+ const position = this.position;
1360
+ return map(nodeReadAlloc(this.fd, {
1361
+ buffer,
1362
+ position
1363
+ }), (bytesRead) => {
1364
+ if (bytesRead === 0) return none();
1365
+ this.position = position + BigInt(bytesRead);
1366
+ if (bytesRead === sizeNumber) return some(buffer);
1367
+ const dst = Buffer.allocUnsafeSlow(bytesRead);
1368
+ buffer.copy(dst, 0, 0, bytesRead);
1369
+ return some(dst);
1370
+ });
1371
+ });
1372
+ }
1373
+ truncate(length) {
1374
+ return map(nodeTruncate(this.fd, length ? Number(length) : void 0), () => {
1375
+ if (!this.append) {
1376
+ const len = BigInt(length ?? 0);
1377
+ if (this.position > len) this.position = len;
1378
+ }
1379
+ });
1380
+ }
1381
+ write(buffer) {
1382
+ return suspend(() => {
1383
+ const position = this.position;
1384
+ return map(nodeWrite(this.fd, buffer, void 0, void 0, this.append ? void 0 : Number(position)), (bytesWritten) => {
1385
+ const sizeWritten = Size(bytesWritten);
1386
+ if (!this.append) this.position = position + sizeWritten;
1387
+ return sizeWritten;
1388
+ });
1389
+ });
1390
+ }
1391
+ writeAllChunk(buffer) {
1392
+ return suspend(() => {
1393
+ const position = this.position;
1394
+ return flatMap(nodeWriteAll(this.fd, buffer, void 0, void 0, this.append ? void 0 : Number(position)), (bytesWritten) => {
1395
+ if (bytesWritten === 0) return fail(systemError({
1396
+ module: "FileSystem",
1397
+ method: "writeAll",
1398
+ _tag: "WriteZero",
1399
+ pathOrDescriptor: this.fd,
1400
+ description: "write returned 0 bytes written"
1401
+ }));
1402
+ if (!this.append) this.position = position + BigInt(bytesWritten);
1403
+ return bytesWritten < buffer.length ? this.writeAllChunk(buffer.subarray(bytesWritten)) : void_;
1404
+ });
1405
+ });
1406
+ }
1407
+ writeAll(buffer) {
1408
+ return this.writeAllChunk(buffer);
1409
+ }
1410
+ }
1411
+ return (fd, append) => new FileImpl(fd, append);
1412
+ })();
1413
+ const makeTempFileFactory = (method) => {
1414
+ const makeDirectory = makeTempDirectoryFactory(method);
1415
+ return fnUntraced(function* (options) {
1416
+ const directory = yield* makeDirectory(options);
1417
+ const random = NodeCrypto.randomBytes(6).toString("hex");
1418
+ const name = Path.join(directory, options?.suffix ? `${random}${options.suffix}` : random);
1419
+ yield* writeFile(name, /* @__PURE__ */ new Uint8Array(0));
1420
+ return name;
1421
+ });
1422
+ };
1423
+ const makeTempFile = /*#__PURE__*/ makeTempFileFactory("makeTempFile");
1424
+ const makeTempFileScoped = /*#__PURE__*/ (() => {
1425
+ const makeFile = /*#__PURE__*/ makeTempFileFactory("makeTempFileScoped");
1426
+ const removeDirectory = /*#__PURE__*/ removeFactory("makeTempFileScoped");
1427
+ return (options) => acquireRelease(makeFile(options), (file) => orDie(removeDirectory(Path.dirname(file), { recursive: true })));
1428
+ })();
1429
+ const readDirectory = (path, options) => tryPromise({
1430
+ try: () => NFS.promises.readdir(path, options),
1431
+ catch: (err) => handleErrnoException("FileSystem", "readDirectory")(err, [path])
1432
+ });
1433
+ const readFile = (path) => callback((resume, signal) => {
1434
+ try {
1435
+ NFS.readFile(path, { signal }, (err, data) => {
1436
+ if (err) resume(fail(handleErrnoException("FileSystem", "readFile")(err, [path])));
1437
+ else resume(succeed$1(data));
1438
+ });
1439
+ } catch (err) {
1440
+ resume(fail(handleBadArgument("readFile")(err)));
1441
+ }
1442
+ });
1443
+ const readLink = /*#__PURE__*/ (() => {
1444
+ const nodeReadLink = /*#__PURE__*/ effectify(NFS.readlink, /*#__PURE__*/ handleErrnoException("FileSystem", "readLink"), /*#__PURE__*/ handleBadArgument("readLink"));
1445
+ return (path) => nodeReadLink(path);
1446
+ })();
1447
+ const realPath = /*#__PURE__*/ (() => {
1448
+ const nodeRealPath = /*#__PURE__*/ effectify(NFS.realpath, /*#__PURE__*/ handleErrnoException("FileSystem", "realPath"), /*#__PURE__*/ handleBadArgument("realPath"));
1449
+ return (path) => nodeRealPath(path);
1450
+ })();
1451
+ const rename = /*#__PURE__*/ (() => {
1452
+ const nodeRename = /*#__PURE__*/ effectify(NFS.rename, /*#__PURE__*/ handleErrnoException("FileSystem", "rename"), /*#__PURE__*/ handleBadArgument("rename"));
1453
+ return (oldPath, newPath) => nodeRename(oldPath, newPath);
1454
+ })();
1455
+ const makeFileInfo = (stat) => ({
1456
+ type: stat.isFile() ? "File" : stat.isDirectory() ? "Directory" : stat.isSymbolicLink() ? "SymbolicLink" : stat.isBlockDevice() ? "BlockDevice" : stat.isCharacterDevice() ? "CharacterDevice" : stat.isFIFO() ? "FIFO" : stat.isSocket() ? "Socket" : "Unknown",
1457
+ mtime: fromNullishOr(stat.mtime),
1458
+ atime: fromNullishOr(stat.atime),
1459
+ birthtime: fromNullishOr(stat.birthtime),
1460
+ dev: stat.dev,
1461
+ rdev: fromNullishOr(stat.rdev),
1462
+ ino: fromNullishOr(stat.ino),
1463
+ mode: stat.mode,
1464
+ nlink: fromNullishOr(stat.nlink),
1465
+ uid: fromNullishOr(stat.uid),
1466
+ gid: fromNullishOr(stat.gid),
1467
+ size: Size(stat.size),
1468
+ blksize: stat.blksize !== void 0 ? some(Size(stat.blksize)) : none(),
1469
+ blocks: fromNullishOr(stat.blocks)
1470
+ });
1471
+ const stat = /*#__PURE__*/ (() => {
1472
+ const nodeStat = /*#__PURE__*/ effectify(NFS.stat, /*#__PURE__*/ handleErrnoException("FileSystem", "stat"), /*#__PURE__*/ handleBadArgument("stat"));
1473
+ return (path) => map(nodeStat(path), makeFileInfo);
1474
+ })();
1475
+ const symlink = /*#__PURE__*/ (() => {
1476
+ const nodeSymlink = /*#__PURE__*/ effectify(NFS.symlink, /*#__PURE__*/ handleErrnoException("FileSystem", "symlink"), /*#__PURE__*/ handleBadArgument("symlink"));
1477
+ return (target, path) => nodeSymlink(target, path);
1478
+ })();
1479
+ const truncate = /*#__PURE__*/ (() => {
1480
+ const nodeTruncate = /*#__PURE__*/ effectify(NFS.truncate, /*#__PURE__*/ handleErrnoException("FileSystem", "truncate"), /*#__PURE__*/ handleBadArgument("truncate"));
1481
+ return (path, length) => nodeTruncate(path, length !== void 0 ? Number(length) : void 0);
1482
+ })();
1483
+ const utimes = /*#__PURE__*/ (() => {
1484
+ const nodeUtimes = /*#__PURE__*/ effectify(NFS.utimes, /*#__PURE__*/ handleErrnoException("FileSystem", "utime"), /*#__PURE__*/ handleBadArgument("utime"));
1485
+ return (path, atime, mtime) => nodeUtimes(path, atime, mtime);
1486
+ })();
1487
+ const watchNode = (path, options) => callback$1((queue) => acquireRelease(sync(() => {
1488
+ const watcher = NFS.watch(path, { recursive: options?.recursive ?? false }, (event, path) => {
1489
+ if (!path) return;
1490
+ switch (event) {
1491
+ case "rename":
1492
+ runFork(matchEffect(stat(path), {
1493
+ onSuccess: (_) => offer(queue, {
1494
+ _tag: "Create",
1495
+ path
1496
+ }),
1497
+ onFailure: (_) => offer(queue, {
1498
+ _tag: "Remove",
1499
+ path
1500
+ })
1501
+ }));
1502
+ return;
1503
+ case "change":
1504
+ offerUnsafe(queue, {
1505
+ _tag: "Update",
1506
+ path
1507
+ });
1508
+ return;
1509
+ }
1510
+ });
1511
+ watcher.on("error", (error) => {
1512
+ failCauseUnsafe(queue, fail$2(systemError({
1513
+ module: "FileSystem",
1514
+ _tag: "Unknown",
1515
+ method: "watch",
1516
+ pathOrDescriptor: path,
1517
+ cause: error
1518
+ })));
1519
+ });
1520
+ watcher.on("close", () => {
1521
+ endUnsafe(queue);
1522
+ });
1523
+ return watcher;
1524
+ }), (watcher) => sync(() => watcher.close())));
1525
+ const watch = (backend, path, options) => stat(path).pipe(map((stat) => backend.pipe(flatMap$1((_) => _.register(path, stat, options)), getOrElse(() => watchNode(path, options)))), unwrap);
1526
+ const writeFile = (path, data, options) => callback((resume, signal) => {
1527
+ try {
1528
+ NFS.writeFile(path, data, {
1529
+ signal,
1530
+ flag: options?.flag,
1531
+ mode: options?.mode
1532
+ }, (err) => {
1533
+ if (err) resume(fail(handleErrnoException("FileSystem", "writeFile")(err, [path])));
1534
+ else resume(void_);
1535
+ });
1536
+ } catch (err) {
1537
+ resume(fail(handleBadArgument("writeFile")(err)));
1538
+ }
1539
+ });
1540
+ const makeFileSystem = /*#__PURE__*/ map(/*#__PURE__*/ serviceOption(WatchBackend), (backend) => make$9({
1541
+ access,
1542
+ chmod,
1543
+ chown,
1544
+ copy,
1545
+ copyFile,
1546
+ glob,
1547
+ link,
1548
+ makeDirectory,
1549
+ makeTempDirectory,
1550
+ makeTempDirectoryScoped,
1551
+ makeTempFile,
1552
+ makeTempFileScoped,
1553
+ open,
1554
+ readDirectory,
1555
+ readFile,
1556
+ readLink,
1557
+ realPath,
1558
+ remove,
1559
+ rename,
1560
+ stat,
1561
+ symlink,
1562
+ truncate,
1563
+ utimes,
1564
+ watch(path, options) {
1565
+ return watch(backend, path, options);
1566
+ },
1567
+ writeFile
1568
+ }));
1569
+ //#endregion
1570
+ //#region ../../node_modules/.pnpm/@effect+platform-node@4.0.0-beta.103_bufferutil@4.1.0_effect@4.0.0-beta.103_patch_hash=_7eec308fcf6351488fccaf9a0edac255/node_modules/@effect/platform-node/dist/NodeFileSystem.js
1571
+ /**
1572
+ * Node.js `FileSystem` layer for programs that perform real filesystem I/O.
1573
+ *
1574
+ * The exported layer satisfies the platform-independent `FileSystem` service
1575
+ * with Node-backed operations for files, directories, metadata, permissions,
1576
+ * links, temporary paths, and path watching. Effects still call the service from
1577
+ * `effect/FileSystem`; this module only chooses the Node implementation.
1578
+ *
1579
+ * @since 4.0.0
1580
+ */
1581
+ /**
1582
+ * Provides the `FileSystem` service backed by Node filesystem APIs.
1583
+ *
1584
+ * @category layers
1585
+ * @since 4.0.0
1586
+ */
1587
+ const layer$7 = /* @__PURE__ */ effect(FileSystem)(makeFileSystem);
1588
+ //#endregion
1589
+ //#region ../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-beta.103_bufferutil@4.1.0_effect@4.0.0-beta.103_patc_c414c3b6e1e822e230993f828f7aeb31/node_modules/@effect/platform-node-shared/dist/NodePath.js
1590
+ /**
1591
+ * Node-backed provider for Effect's `Path` service.
1592
+ *
1593
+ * This module turns Node's `node:path` and `node:url` APIs into `Path` layers.
1594
+ * `layer` uses the host platform path implementation, while `layerPosix` and
1595
+ * `layerWin32` provide fixed POSIX and Windows variants. All three layers also
1596
+ * include helpers for converting between file paths and file URLs.
1597
+ *
1598
+ * @since 4.0.0
1599
+ */
1600
+ const fileUrlOps = (windows) => ({
1601
+ fromFileUrl: (url) => try_({
1602
+ try: () => NodeUrl.fileURLToPath(url, { windows }),
1603
+ catch: (cause) => new BadArgument({
1604
+ module: "Path",
1605
+ method: "fromFileUrl",
1606
+ cause
1607
+ })
1608
+ }),
1609
+ toFileUrl: (path) => try_({
1610
+ try: () => NodeUrl.pathToFileURL(path, { windows }),
1611
+ catch: (cause) => new BadArgument({
1612
+ module: "Path",
1613
+ method: "toFileUrl",
1614
+ cause
1615
+ })
1616
+ })
1617
+ });
1618
+ ({
1619
+ ...Path.posix,
1620
+ .../*#__PURE__*/ fileUrlOps(false)
1621
+ });
1622
+ ({
1623
+ ...Path.win32,
1624
+ .../*#__PURE__*/ fileUrlOps(true)
1625
+ });
1626
+ //#endregion
1627
+ //#region ../../node_modules/.pnpm/@effect+platform-node@4.0.0-beta.103_bufferutil@4.1.0_effect@4.0.0-beta.103_patch_hash=_7eec308fcf6351488fccaf9a0edac255/node_modules/@effect/platform-node/dist/NodePath.js
1628
+ /**
1629
+ * Node.js layers for Effect's `Path` service.
1630
+ *
1631
+ * This module provides the default, POSIX, and Windows variants of the
1632
+ * platform-independent `Path` service by reusing the shared Node path
1633
+ * implementation. The provided path services include Node file URL conversion
1634
+ * behavior.
1635
+ *
1636
+ * @since 4.0.0
1637
+ */
1638
+ /**
1639
+ * Provides the default Node `Path` service using the platform's `node:path`
1640
+ * implementation.
1641
+ *
1642
+ * @category layers
1643
+ * @since 4.0.0
1644
+ */
1645
+ const layer$5 = /* @__PURE__ */ succeed$3(Path$1)({
1646
+ [TypeId$4]: TypeId$4,
1647
+ ...Path,
1648
+ .../*#__PURE__*/ fileUrlOps(void 0)
1649
+ });
1650
+ //#endregion
1651
+ //#region ../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/Stdio.js
1652
+ /**
1653
+ * Service contract for command-line arguments and standard input, output, and
1654
+ * error output. It lets programs depend on standard I/O through the Effect
1655
+ * environment instead of reading from or writing to global process handles
1656
+ * directly.
1657
+ *
1658
+ * The service exposes arguments as an `Effect`, stdout and stderr as `Sink`s
1659
+ * that accept strings or bytes, and stdin as a byte `Stream`. This module also
1660
+ * provides a constructor for service values and a small test layer with
1661
+ * overridable defaults.
1662
+ *
1663
+ * @since 4.0.0
1664
+ */
1665
+ /**
1666
+ * Runtime identifier stored on `Stdio` service implementations.
1667
+ *
1668
+ * **Details**
1669
+ *
1670
+ * This marker is part of the runtime representation of `Stdio` service
1671
+ * implementations.
1672
+ *
1673
+ * @category type IDs
1674
+ * @since 4.0.0
1675
+ */
1676
+ const TypeId$1 = "~effect/Stdio";
1677
+ /**
1678
+ * Service tag for process standard I/O.
1679
+ *
1680
+ * **When to use**
1681
+ *
1682
+ * Use when you need command-line arguments or standard I/O streams supplied by
1683
+ * an effect's environment.
1684
+ *
1685
+ * @see {@link make} for constructing a `Stdio` service directly
1686
+ * @see {@link layerTest} for a test layer with defaults and overrides
1687
+ *
1688
+ * @category services
1689
+ * @since 4.0.0
1690
+ */
1691
+ const Stdio = /*#__PURE__*/ Service(TypeId$1);
1692
+ /**
1693
+ * Creates a `Stdio` service implementation from the provided fields and
1694
+ * attaches the `Stdio` type identifier.
1695
+ *
1696
+ * **When to use**
1697
+ *
1698
+ * Use when you need to assemble a concrete `Stdio` service from command-line
1699
+ * arguments and standard I/O implementations.
1700
+ *
1701
+ * **Details**
1702
+ *
1703
+ * The returned service reuses the supplied fields unchanged and only adds the
1704
+ * `Stdio` type identifier; it does not create a `Layer` or provide defaults.
1705
+ *
1706
+ * @see {@link layerTest} for a test layer with default fields that can be overridden
1707
+ *
1708
+ * @category constructors
1709
+ * @since 4.0.0
1710
+ */
1711
+ const make$2 = (options) => ({
1712
+ [TypeId$1]: TypeId$1,
1713
+ ...options
1714
+ });
1715
+ //#endregion
1716
+ //#region ../../node_modules/.pnpm/@effect+platform-node@4.0.0-beta.103_bufferutil@4.1.0_effect@4.0.0-beta.103_patch_hash=_7eec308fcf6351488fccaf9a0edac255/node_modules/@effect/platform-node/dist/NodeStdio.js
1717
+ /**
1718
+ * Node.js `Stdio` layer for the current process.
1719
+ *
1720
+ * The exported layer reuses the shared Node stdio implementation. It satisfies
1721
+ * the platform-independent `Stdio` service by reading command-line arguments
1722
+ * from `process.argv`, consuming input from `process.stdin`, and writing output
1723
+ * streams to `process.stdout` and `process.stderr`.
1724
+ *
1725
+ * @since 4.0.0
1726
+ */
1727
+ /**
1728
+ * Provides the `Stdio` service backed by the current process arguments,
1729
+ * stdin, stdout, and stderr streams.
1730
+ *
1731
+ * @category layers
1732
+ * @since 4.0.0
1733
+ */
1734
+ const layer$3 = /* @__PURE__ */ succeed$3(Stdio, /*#__PURE__*/ make$2({
1735
+ args: /*#__PURE__*/ sync(() => process.argv.slice(2)),
1736
+ stdout: (options) => fromWritable({
1737
+ evaluate: () => process.stdout,
1738
+ onError: (cause) => systemError({
1739
+ module: "Stdio",
1740
+ method: "stdout",
1741
+ _tag: "Unknown",
1742
+ cause
1743
+ }),
1744
+ endOnDone: options?.endOnDone ?? false
1745
+ }),
1746
+ stderr: (options) => fromWritable({
1747
+ evaluate: () => process.stderr,
1748
+ onError: (cause) => systemError({
1749
+ module: "Stdio",
1750
+ method: "stderr",
1751
+ _tag: "Unknown",
1752
+ cause
1753
+ }),
1754
+ endOnDone: options?.endOnDone ?? false
1755
+ }),
1756
+ stdin: /*#__PURE__*/ fromReadable({
1757
+ evaluate: () => process.stdin,
1758
+ onError: (cause) => systemError({
1759
+ module: "Stdio",
1760
+ method: "stdin",
1761
+ _tag: "Unknown",
1762
+ cause
1763
+ }),
1764
+ closeOnDone: false
1765
+ })
1766
+ }));
1767
+ //#endregion
1768
+ //#region ../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/Terminal.js
1769
+ const TypeId = "~effect/platform/Terminal";
1770
+ const QuitErrorTypeId = "effect/platform/Terminal/QuitError";
1771
+ /**
1772
+ * Represents an error that occurs when a user attempts to
1773
+ * quit out of a `Terminal` prompt for input (usually by entering `ctrl`+`c`).
1774
+ *
1775
+ * **When to use**
1776
+ *
1777
+ * Use when implementing terminal input or prompts that need to signal
1778
+ * user-requested cancellation through the typed error channel.
1779
+ *
1780
+ * @see {@link isQuitError} for checking unknown errors when handling terminal cancellation
1781
+ *
1782
+ * @category errors
1783
+ * @since 4.0.0
1784
+ */
1785
+ var QuitError = class extends ErrorClass("QuitError")({ _tag: /*#__PURE__*/ tag("QuitError") }) {
1786
+ /**
1787
+ * Marks this value as a terminal quit error for runtime guards.
1788
+ *
1789
+ * @since 4.0.0
1790
+ */
1791
+ [QuitErrorTypeId] = QuitErrorTypeId;
1792
+ };
1793
+ /**
1794
+ * Returns `true` if the provided value is a `Terminal.QuitError`.
1795
+ *
1796
+ * **When to use**
1797
+ *
1798
+ * Use to narrow unknown failures to `QuitError` when handling terminal input
1799
+ * cancellation.
1800
+ *
1801
+ * **Details**
1802
+ *
1803
+ * Returns `true` when the value carries the `QuitError` runtime marker and
1804
+ * narrows it to `QuitError`.
1805
+ *
1806
+ * @see {@link QuitError} for the error value produced when terminal input is quit
1807
+ *
1808
+ * @category guards
1809
+ * @since 4.0.0
1810
+ */
1811
+ const isQuitError = (u) => hasProperty(u, QuitErrorTypeId);
1812
+ /**
1813
+ * Service tag for command-line input and output services.
1814
+ *
1815
+ * **When to use**
1816
+ *
1817
+ * Use to access or provide platform terminal capabilities such as reading
1818
+ * input, writing output, and inspecting terminal dimensions.
1819
+ *
1820
+ * @category services
1821
+ * @since 4.0.0
1822
+ */
1823
+ const Terminal = /*#__PURE__*/ Service("effect/platform/Terminal");
1824
+ /**
1825
+ * Creates a `Terminal` service implementation.
1826
+ *
1827
+ * **When to use**
1828
+ *
1829
+ * Use to construct a custom `Terminal` service implementation from concrete
1830
+ * terminal capabilities when writing a platform adapter, test implementation,
1831
+ * or custom runtime service.
1832
+ *
1833
+ * **Details**
1834
+ *
1835
+ * The implementation object supplies `columns`, `rows`, `readInput`,
1836
+ * `readLine`, and `display`; `make` attaches the `Terminal` service marker so
1837
+ * the result can be provided through the `Terminal` context service.
1838
+ *
1839
+ * @category constructors
1840
+ * @since 4.0.0
1841
+ */
1842
+ const make$1 = (impl) => Terminal.of({
1843
+ ...impl,
1844
+ [TypeId]: TypeId
1845
+ });
1846
+ /**
1847
+ * Provides the default process-backed `Terminal` service, ending key input on
1848
+ * Ctrl+C or Ctrl+D.
1849
+ *
1850
+ * @category layers
1851
+ * @since 4.0.0
1852
+ */
1853
+ const layer$2 = /*#__PURE__*/ effect(Terminal, /*#__PURE__*/ (/* @__PURE__ */ fnUntraced(function* (shouldQuit = defaultShouldQuit) {
1854
+ const stdin = process.stdin;
1855
+ const stdout = process.stdout;
1856
+ const lines = yield* make$10();
1857
+ let inputEnded = stdin.readableEnded;
1858
+ let readlineActive = false;
1859
+ const onStdinEnd = () => {
1860
+ inputEnded = true;
1861
+ if (!readlineActive) endUnsafe(lines);
1862
+ };
1863
+ stdin.once("end", onStdinEnd);
1864
+ yield* addFinalizer$1(() => sync(() => stdin.off("end", onStdinEnd)));
1865
+ const rlRef = yield* make$11({ acquire: acquireRelease(sync(() => {
1866
+ const rl = readline.createInterface({
1867
+ input: stdin,
1868
+ escapeCodeTimeout: 50
1869
+ });
1870
+ const onLine = (line) => offerUnsafe(lines, line);
1871
+ const onClose = () => {
1872
+ readlineActive = false;
1873
+ endUnsafe(lines);
1874
+ };
1875
+ readlineActive = true;
1876
+ readline.emitKeypressEvents(stdin, rl);
1877
+ rl.on("line", onLine);
1878
+ rl.once("close", onClose);
1879
+ if (stdin.isTTY) stdin.setRawMode(true);
1880
+ return {
1881
+ rl,
1882
+ onClose,
1883
+ onLine
1884
+ };
1885
+ }), ({ rl, onClose, onLine }) => sync(() => {
1886
+ readlineActive = false;
1887
+ rl.off("line", onLine);
1888
+ rl.off("close", onClose);
1889
+ if (stdin.isTTY) stdin.setRawMode(false);
1890
+ rl.close();
1891
+ if (inputEnded) endUnsafe(lines);
1892
+ })) });
1893
+ const columns = sync(() => stdout.columns ?? 0);
1894
+ const rows = sync(() => stdout.rows ?? 0);
1895
+ const readInput = gen(function* () {
1896
+ const queue = yield* make$10();
1897
+ const handleKeypress = (s, k) => {
1898
+ const userInput = {
1899
+ input: fromUndefinedOr(s),
1900
+ key: {
1901
+ name: k.name ?? "",
1902
+ ctrl: !!k.ctrl,
1903
+ meta: !!k.meta,
1904
+ shift: !!k.shift
1905
+ }
1906
+ };
1907
+ offerUnsafe(queue, userInput);
1908
+ if (shouldQuit(userInput)) endUnsafe(queue);
1909
+ };
1910
+ const keepAlive = setInterval(() => {}, 2147483647);
1911
+ const handleEnd = () => {
1912
+ clearInterval(keepAlive);
1913
+ endUnsafe(queue);
1914
+ };
1915
+ yield* addFinalizer$1(() => sync(() => {
1916
+ clearInterval(keepAlive);
1917
+ stdin.off("keypress", handleKeypress);
1918
+ stdin.off("end", handleEnd);
1919
+ }));
1920
+ stdin.on("keypress", handleKeypress);
1921
+ if (inputEnded) handleEnd();
1922
+ else {
1923
+ yield* get(rlRef);
1924
+ stdin.once("end", handleEnd);
1925
+ }
1926
+ return queue;
1927
+ });
1928
+ const readLine = suspend(() => poll(lines).pipe(flatMap(match({
1929
+ onNone: () => scoped(andThen(get(rlRef), take(lines))),
1930
+ onSome: succeed$1
1931
+ })), mapError(() => new QuitError({}))));
1932
+ const display = (prompt) => uninterruptible(callback((resume) => {
1933
+ stdout.write(prompt, (err) => isNullish(err) ? resume(void_) : resume(fail(badArgument({
1934
+ module: "Terminal",
1935
+ method: "display",
1936
+ description: "Failed to write prompt to stdout",
1937
+ cause: err
1938
+ }))));
1939
+ }));
1940
+ return make$1({
1941
+ columns,
1942
+ rows,
1943
+ readInput,
1944
+ readLine,
1945
+ display
1946
+ });
1947
+ }))(defaultShouldQuit));
1948
+ function defaultShouldQuit(input) {
1949
+ return input.key.ctrl && (input.key.name === "c" || input.key.name === "d");
1950
+ }
1951
+ //#endregion
1952
+ //#region ../../node_modules/.pnpm/@effect+platform-node@4.0.0-beta.103_bufferutil@4.1.0_effect@4.0.0-beta.103_patch_hash=_7eec308fcf6351488fccaf9a0edac255/node_modules/@effect/platform-node/dist/NodeTerminal.js
1953
+ /**
1954
+ * Node.js implementation of the Effect `Terminal` service.
1955
+ *
1956
+ * This module reuses the shared Node terminal implementation. `make` creates a
1957
+ * scoped process-backed `Terminal` service, and `layer` provides the default
1958
+ * service with the standard quit behavior for key input.
1959
+ *
1960
+ * @since 4.0.0
1961
+ */
1962
+ /**
1963
+ * Provides the default process-backed `Terminal` service, ending key input on
1964
+ * the default quit keys.
1965
+ *
1966
+ * @category layers
1967
+ * @since 4.0.0
1968
+ */
1969
+ const layer$1 = layer$2;
1970
+ //#endregion
1971
+ //#region ../../node_modules/.pnpm/@effect+platform-node@4.0.0-beta.103_bufferutil@4.1.0_effect@4.0.0-beta.103_patch_hash=_7eec308fcf6351488fccaf9a0edac255/node_modules/@effect/platform-node/dist/NodeServices.js
1972
+ var NodeServices_exports = /* @__PURE__ */ __exportAll({ layer: () => layer });
1973
+ /**
1974
+ * Provides the default Node implementations for child process spawning,
1975
+ * filesystem, path, stdio, and terminal services.
1976
+ *
1977
+ * @category layers
1978
+ * @since 4.0.0
1979
+ */
1980
+ const layer = /*#__PURE__*/ provideMerge(layer$11, /*#__PURE__*/ mergeAll(layer$7, layer$9, layer$5, layer$3, layer$1));
1981
+ //#endregion
1982
+ export { isQuitError as a, layer$7 as c, pipeThroughDuplex as d, toArrayBuffer as f, ChildProcessSpawner as g, make$6 as h, Terminal as i, Crypto as l, toUint8Array as m, layer as n, Stdio as o, toString as p, QuitError as r, make$2 as s, NodeServices_exports as t, fromReadable as u };
1983
+
1984
+ //# sourceMappingURL=NodeServices-DDZTiw5K.mjs.map