@effect/platform-deno 4.0.0-rc.112 → 4.0.0-rc.114

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 (57) hide show
  1. package/AGENTS.md +24 -9
  2. package/CLAUDE.md +24 -9
  3. package/ai-docs/package.json +2 -2
  4. package/ai-docs/src/01_effect/01_basics/02_effect-fn.ts +18 -5
  5. package/ai-docs/src/01_effect/01_basics/index.md +5 -3
  6. package/ai-docs/src/01_effect/03_services/20_layer-composition.ts +1 -1
  7. package/ai-docs/src/01_effect/03_services/20_layer-unwrap.ts +2 -2
  8. package/ai-docs/src/01_effect/05_resources/10_acquire-release.ts +2 -2
  9. package/ai-docs/src/03_stream/30_encoding.ts +5 -7
  10. package/ai-docs/src/08_observability/10_logging.ts +1 -1
  11. package/ai-docs/src/70_cli/10_basics.ts +7 -7
  12. package/ai-docs/src/71_ai/10_language-model.ts +2 -2
  13. package/ai-docs/src/71_ai/20_tools.ts +1 -1
  14. package/ai-docs/src/71_ai/30_chat.ts +1 -1
  15. package/dist/DenoClusterHttp.d.ts +1 -1
  16. package/dist/DenoClusterHttp.d.ts.map +1 -1
  17. package/dist/DenoClusterHttp.js +1 -1
  18. package/dist/DenoClusterHttp.js.map +1 -1
  19. package/dist/DenoClusterSocket.d.ts +2 -2
  20. package/dist/DenoClusterSocket.d.ts.map +1 -1
  21. package/dist/DenoClusterSocket.js +5 -3
  22. package/dist/DenoClusterSocket.js.map +1 -1
  23. package/dist/DenoFileSystem.d.ts.map +1 -1
  24. package/dist/DenoFileSystem.js +41 -29
  25. package/dist/DenoFileSystem.js.map +1 -1
  26. package/dist/DenoHttpPlatform.d.ts +6 -6
  27. package/dist/DenoHttpPlatform.js +4 -4
  28. package/dist/DenoHttpPlatform.js.map +1 -1
  29. package/dist/DenoHttpServer.d.ts +7 -5
  30. package/dist/DenoHttpServer.d.ts.map +1 -1
  31. package/dist/DenoHttpServer.js +85 -48
  32. package/dist/DenoHttpServer.js.map +1 -1
  33. package/dist/DenoRedis.d.ts.map +1 -1
  34. package/dist/DenoRedis.js +3 -0
  35. package/dist/DenoRedis.js.map +1 -1
  36. package/dist/DenoSocket.d.ts +16 -3
  37. package/dist/DenoSocket.d.ts.map +1 -1
  38. package/dist/DenoSocket.js +128 -39
  39. package/dist/DenoSocket.js.map +1 -1
  40. package/dist/DenoSocketServer.d.ts +1 -63
  41. package/dist/DenoSocketServer.d.ts.map +1 -1
  42. package/dist/DenoSocketServer.js +1 -61
  43. package/dist/DenoSocketServer.js.map +1 -1
  44. package/package.json +5 -5
  45. package/src/DenoClusterHttp.ts +2 -2
  46. package/src/DenoClusterSocket.ts +6 -4
  47. package/src/DenoFileSystem.ts +43 -31
  48. package/src/DenoHttpPlatform.ts +4 -4
  49. package/src/DenoHttpServer.ts +98 -60
  50. package/src/DenoRedis.ts +3 -0
  51. package/src/DenoSocket.ts +162 -82
  52. package/src/DenoSocketServer.ts +1 -113
  53. package/dist/internal/denoSocketServer.d.ts +0 -7
  54. package/dist/internal/denoSocketServer.d.ts.map +0 -1
  55. package/dist/internal/denoSocketServer.js +0 -55
  56. package/dist/internal/denoSocketServer.js.map +0 -1
  57. package/src/internal/denoSocketServer.ts +0 -89
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { copy as denoCopy, expandGlob, walk } from "@std/fs"
7
7
  import { relative } from "@std/path"
8
+ import * as ByteSize from "effect/ByteSize"
8
9
  import * as Effect from "effect/Effect"
9
10
  import * as FileSystem from "effect/FileSystem"
10
11
  import * as Layer from "effect/Layer"
@@ -175,8 +176,8 @@ const makeFileInfo = (info: Deno.FileInfo): FileSystem.File.Info => ({
175
176
  nlink: Option.fromNullishOr(info.nlink),
176
177
  uid: Option.fromNullishOr(info.uid),
177
178
  gid: Option.fromNullishOr(info.gid),
178
- size: FileSystem.Size(info.size),
179
- blksize: Option.map(Option.fromNullishOr(info.blksize), FileSystem.Size),
179
+ size: ByteSize.bytes(BigInt(info.size)),
180
+ blksize: Option.map(Option.fromNullishOr(info.blksize), (size) => ByteSize.bytes(BigInt(size))),
180
181
  blocks: Option.fromNullishOr(info.blocks)
181
182
  })
182
183
 
@@ -207,15 +208,18 @@ class FileImpl implements FileSystem.File {
207
208
  return tryPromise("sync", undefined, () => this.file.sync())
208
209
  }
209
210
 
210
- seek(offset: FileSystem.SizeInput, from: FileSystem.SeekMode) {
211
- const size = FileSystem.Size(offset)
212
- return Effect.sync(() => {
213
- if (from === "start") {
214
- this.position = size
215
- } else {
216
- this.position += size
211
+ seek(offset: bigint, from: FileSystem.SeekMode) {
212
+ return Effect.suspend(() => {
213
+ const position = from === "start" ? offset : this.position + offset
214
+ if (position < BigInt(0)) {
215
+ return Effect.fail(PlatformError.badArgument({
216
+ module: "FileSystem",
217
+ method: "seek",
218
+ description: "Cannot seek before the start of the file"
219
+ }))
217
220
  }
218
- return FileSystem.Size(this.position)
221
+ this.position = position
222
+ return Effect.succeed(position)
219
223
  })
220
224
  }
221
225
 
@@ -235,9 +239,8 @@ class FileImpl implements FileSystem.File {
235
239
  }
236
240
  ),
237
241
  (bytesRead) => {
238
- const sizeRead = FileSystem.Size(bytesRead ?? 0)
239
- this.position = this.nativePosition = position + sizeRead
240
- return sizeRead
242
+ this.position = this.nativePosition = position + BigInt(bytesRead ?? 0)
243
+ return bytesRead ?? 0
241
244
  }
242
245
  )
243
246
  })
@@ -247,21 +250,32 @@ class FileImpl implements FileSystem.File {
247
250
  return this.readChunk("read", buffer)
248
251
  }
249
252
 
250
- readAlloc(size: FileSystem.SizeInput) {
251
- const sizeNumber = Number(size)
253
+ readAlloc(size: number) {
252
254
  return Effect.suspend(() => {
253
- const buffer = new Uint8Array(sizeNumber)
254
- return Effect.map(this.readChunk("readAlloc", buffer), (bytesRead) => {
255
- if (bytesRead === BigInt(0)) {
256
- return Option.none()
255
+ try {
256
+ if (!Number.isInteger(size) || size < 0) {
257
+ throw new RangeError("size must be a non-negative integer")
257
258
  }
258
- return Option.some(bytesRead === BigInt(sizeNumber) ? buffer : buffer.subarray(0, Number(bytesRead)))
259
- })
259
+ const buffer = new Uint8Array(size)
260
+ return Effect.map(this.readChunk("readAlloc", buffer), (bytesRead) => {
261
+ if (bytesRead === 0) {
262
+ return Option.none()
263
+ }
264
+ return Option.some(bytesRead === size ? buffer : buffer.subarray(0, bytesRead))
265
+ })
266
+ } catch (cause) {
267
+ return Effect.fail(PlatformError.badArgument({
268
+ module: "FileSystem",
269
+ method: "readAlloc",
270
+ description: `Could not allocate a buffer of size ${size}`,
271
+ cause
272
+ }))
273
+ }
260
274
  })
261
275
  }
262
276
 
263
- truncate(length?: FileSystem.SizeInput) {
264
- const size = FileSystem.Size(length ?? 0)
277
+ truncate(length?: number) {
278
+ const size = BigInt(length ?? 0)
265
279
  return Effect.map(
266
280
  tryPromise("truncate", undefined, () => this.file.truncate(Number(size))),
267
281
  () => {
@@ -288,13 +302,12 @@ class FileImpl implements FileSystem.File {
288
302
  }
289
303
  ),
290
304
  (bytesWritten) => {
291
- const sizeWritten = FileSystem.Size(bytesWritten)
292
305
  if (this.append) {
293
306
  this.nativePosition = undefined
294
307
  } else {
295
- this.position = this.nativePosition = position + sizeWritten
308
+ this.position = this.nativePosition = position + BigInt(bytesWritten)
296
309
  }
297
- return sizeWritten
310
+ return bytesWritten
298
311
  }
299
312
  )
300
313
  })
@@ -306,7 +319,7 @@ class FileImpl implements FileSystem.File {
306
319
 
307
320
  private writeAllChunk(buffer: Uint8Array): Effect.Effect<void, PlatformError.PlatformError> {
308
321
  return Effect.flatMap(this.writeChunk("writeAll", buffer), (bytesWritten) => {
309
- if (bytesWritten === BigInt(0)) {
322
+ if (bytesWritten === 0) {
310
323
  return Effect.fail(PlatformError.systemError({
311
324
  module: "FileSystem",
312
325
  method: "writeAll",
@@ -315,7 +328,7 @@ class FileImpl implements FileSystem.File {
315
328
  }))
316
329
  }
317
330
  return bytesWritten < buffer.length
318
- ? this.writeAllChunk(buffer.subarray(Number(bytesWritten)))
331
+ ? this.writeAllChunk(buffer.subarray(bytesWritten))
319
332
  : Effect.void
320
333
  })
321
334
  }
@@ -385,7 +398,7 @@ const symlink: FileSystem.FileSystem["symlink"] = (target, path) =>
385
398
  tryPromise("symlink", target, () => Deno.symlink(target, path))
386
399
 
387
400
  const truncate: FileSystem.FileSystem["truncate"] = (path, length) =>
388
- tryPromise("truncate", path, () => Deno.truncate(path, length === undefined ? undefined : Number(length)))
401
+ tryPromise("truncate", path, () => Deno.truncate(path, length))
389
402
 
390
403
  const utimes: FileSystem.FileSystem["utimes"] = (path, atime, mtime) =>
391
404
  tryPromise("utimes", path, () => Deno.utime(path, atime, mtime))
@@ -441,12 +454,11 @@ const watch = (
441
454
 
442
455
  const writeFile: FileSystem.FileSystem["writeFile"] = (path, data, options) => {
443
456
  const flag = options?.flag ?? "w"
444
- if (flag === "w" || flag === "wx" || flag === "a" || flag === "ax") {
457
+ if (options?.mode === undefined && (flag === "w" || flag === "wx" || flag === "a" || flag === "ax")) {
445
458
  return tryPromise("writeFile", path, (signal) =>
446
459
  Deno.writeFile(path, data, {
447
460
  append: flag.startsWith("a"),
448
461
  createNew: flag.includes("x"),
449
- ...(options?.mode === undefined ? {} : { mode: options.mode }),
450
462
  signal
451
463
  }))
452
464
  }
@@ -44,7 +44,7 @@ export const make = Platform.make({
44
44
  compression,
45
45
  fileResponse(path, status, statusText, headers, start, end, contentLength) {
46
46
  let body: ReadableStream<Uint8Array>
47
- if (contentLength === 0) {
47
+ if (contentLength === BigInt(0)) {
48
48
  body = new ReadableStream<Uint8Array>({
49
49
  start(controller) {
50
50
  controller.close()
@@ -55,7 +55,7 @@ export const make = Platform.make({
55
55
  file.seekSync(start, Deno.SeekMode.Start)
56
56
  body = end === undefined
57
57
  ? file.readable
58
- : file.readable.pipeThrough(new ByteSliceStream(0, contentLength - 1))
58
+ : file.readable.pipeThrough(new ByteSliceStream(0, end - start - 1))
59
59
  }
60
60
  return Response.raw(body, {
61
61
  headers: {
@@ -68,11 +68,11 @@ export const make = Platform.make({
68
68
  })
69
69
  },
70
70
  fileWebResponse(file, status, statusText, headers, options) {
71
- const offset = Number(options?.offset ?? 0)
71
+ const offset = options?.offset ?? 0
72
72
  const available = Math.max(0, file.size - offset)
73
73
  const contentLength = options?.bytesToRead === undefined
74
74
  ? available
75
- : Math.min(available, Math.max(0, Number(options.bytesToRead)))
75
+ : Math.min(available, Math.max(0, options.bytesToRead))
76
76
  let body: typeof file | ReadableStream<Uint8Array> = file
77
77
  if (contentLength === 0) {
78
78
  body = new ReadableStream<Uint8Array>({
@@ -35,6 +35,7 @@ import * as ServerRequest from "effect/unstable/http/HttpServerRequest"
35
35
  import type * as ServerResponse from "effect/unstable/http/HttpServerResponse"
36
36
  import type * as Multipart from "effect/unstable/http/Multipart"
37
37
  import * as UrlParams from "effect/unstable/http/UrlParams"
38
+ import * as NetAddress from "effect/unstable/net/NetAddress"
38
39
  import * as Socket from "effect/unstable/socket/Socket"
39
40
  import * as Platform from "./DenoHttpPlatform.ts"
40
41
  import * as DenoMultipart from "./DenoMultipart.ts"
@@ -95,13 +96,12 @@ export const make = Effect.fnUntraced(function*(
95
96
  yield* Scope.addFinalizer(scope, shutdown)
96
97
 
97
98
  const serverAddress = server.addr
98
- const address: Server.Address = serverAddress.transport === "unix"
99
- ? { _tag: "UnixAddress", path: serverAddress.path }
100
- : {
101
- _tag: "TcpAddress",
102
- port: (serverAddress as Deno.NetAddr).port,
103
- hostname: (serverAddress as Deno.NetAddr).hostname
104
- }
99
+ const address = yield* (serverAddress.transport === "unix"
100
+ ? Effect.succeed(NetAddress.unixPathAddress(serverAddress.path))
101
+ : Effect.fromResult(NetAddress.inetAddressFromIpString(
102
+ (serverAddress as Deno.NetAddr).hostname,
103
+ (serverAddress as Deno.NetAddr).port
104
+ )).pipe(Effect.mapError((cause) => new Error.ServeError({ cause }))))
105
105
 
106
106
  return Server.make({
107
107
  address,
@@ -216,7 +216,7 @@ export const layerServer: (
216
216
  readonly gracefulShutdownTimeout?: Duration.Input | undefined
217
217
  readonly websocket?: Deno.UpgradeWebSocketOptions | undefined
218
218
  }
219
- ) => Layer.Layer<Server.HttpServer> = flow(
219
+ ) => Layer.Layer<Server.HttpServer, Error.ServeError> = flow(
220
220
  make,
221
221
  Layer.effect(Server.HttpServer)
222
222
  )
@@ -245,7 +245,7 @@ export const layer = (
245
245
  readonly gracefulShutdownTimeout?: Duration.Input | undefined
246
246
  readonly websocket?: Deno.UpgradeWebSocketOptions | undefined
247
247
  }
248
- ): Layer.Layer<Server.HttpServer | HttpPlatform | Etag.Generator | DenoServices.DenoServices> =>
248
+ ): Layer.Layer<Server.HttpServer | HttpPlatform | Etag.Generator | DenoServices.DenoServices, Error.ServeError> =>
249
249
  Layer.mergeAll(layerServer(options), layerHttpServices)
250
250
 
251
251
  /**
@@ -260,7 +260,7 @@ export const layerTest: Layer.Layer<
260
260
  Layer.provide(FetchHttpClient.layer.pipe(
261
261
  Layer.provide(Layer.succeed(FetchHttpClient.RequestInit)({ keepalive: false }))
262
262
  )),
263
- Layer.provideMerge(layer({ hostname: "127.0.0.1", port: 0, onListen: () => {} }))
263
+ Layer.provideMerge(Layer.orDie(layer({ hostname: "127.0.0.1", port: 0, onListen: () => {} })))
264
264
  )
265
265
 
266
266
  /**
@@ -279,7 +279,7 @@ export const layerConfig = (
279
279
  >
280
280
  ): Layer.Layer<
281
281
  Server.HttpServer | HttpPlatform | FileSystem.FileSystem | Etag.Generator | Path.Path,
282
- ConfigError
282
+ ConfigError | Error.ServeError
283
283
  > =>
284
284
  Layer.mergeAll(
285
285
  Layer.effect(Server.HttpServer)(Effect.flatMap(Config.unwrap(options), make)),
@@ -457,62 +457,100 @@ class DenoServerRequest extends Inspectable.Class implements ServerRequest.HttpS
457
457
  })
458
458
  }),
459
459
  (upgrade) => {
460
- const buffered: Array<MessageEvent> = []
461
- const buffer = (event: MessageEvent) => buffered.push(event)
462
- upgrade.socket.addEventListener("message", buffer)
460
+ const ws = bufferedWebSocket(upgrade.socket)
463
461
  this.upgraded = true
464
462
  this.resolve(upgrade.response)
465
-
466
- return Effect.callback<Socket.Socket, Error.HttpServerError>((resume) => {
467
- const cleanup = () => {
468
- upgrade.socket.removeEventListener("open", onOpen)
469
- upgrade.socket.removeEventListener("error", onFailure)
470
- upgrade.socket.removeEventListener("close", onFailure)
471
- }
472
- const onFailure = (cause: Event) => {
473
- cleanup()
474
- upgrade.socket.removeEventListener("message", buffer)
475
- buffered.length = 0
476
- resume(Effect.fail(
477
- new Error.HttpServerError({
478
- reason: new Error.RequestParseError({
479
- request: this,
480
- cause,
481
- description: "WebSocket upgrade failed before open"
482
- })
483
- })
484
- ))
485
- }
486
- const onOpen = () => {
487
- cleanup()
488
- resume(Socket.fromWebSocket(
489
- Effect.acquireRelease(
490
- Effect.succeed(upgrade.socket),
491
- (socket) => Effect.sync(() => socket.close(1000))
492
- ),
493
- {
494
- onInitialRun: (socket) => {
495
- socket.removeEventListener("message", buffer)
496
- return buffered.splice(0)
497
- }
498
- }
499
- ))
500
- }
501
- upgrade.socket.addEventListener("open", onOpen, { once: true })
502
- upgrade.socket.addEventListener("error", onFailure, { once: true })
503
- upgrade.socket.addEventListener("close", onFailure, { once: true })
504
- return Effect.sync(() => {
505
- cleanup()
506
- upgrade.socket.removeEventListener("message", buffer)
507
- buffered.length = 0
508
- upgrade.socket.close()
509
- })
510
- })
463
+ return Socket.fromWebSocket(
464
+ Effect.acquireRelease(
465
+ Effect.succeed(ws),
466
+ () => Effect.sync(() => upgrade.socket.close(1000))
467
+ )
468
+ )
511
469
  }
512
470
  )
513
471
  }
514
472
  }
515
473
 
474
+ // Deno's WebSocket cannot be paused, so events that arrive between the
475
+ // upgrade and the first reader acquisition would be lost. This facade buffers
476
+ // message, error, and close events until listeners attach, then replays them
477
+ // so they come out of the first pull.
478
+ const bufferedWebSocket = (ws: WebSocket): Socket.WebSocketLike => {
479
+ interface Entry {
480
+ readonly listener: (event: Socket.WebSocketEvent) => void
481
+ readonly once: boolean
482
+ }
483
+ const listeners = new Map<string, Array<Entry>>()
484
+ const buffered: Array<[string, Socket.WebSocketEvent]> = []
485
+ let buffering = true
486
+
487
+ ws.binaryType = "arraybuffer"
488
+
489
+ function removeListener(type: string, listener: (event: Socket.WebSocketEvent) => void) {
490
+ const entries = listeners.get(type)
491
+ if (!entries) return
492
+ const index = entries.findIndex((entry) => entry.listener === listener)
493
+ if (index >= 0) entries.splice(index, 1)
494
+ }
495
+ function dispatch(type: string, event: Socket.WebSocketEvent) {
496
+ const entries = listeners.get(type)
497
+ if (!entries || entries.length === 0) return
498
+ for (const entry of entries.slice()) {
499
+ if (entry.once) removeListener(type, entry.listener)
500
+ entry.listener(event)
501
+ }
502
+ }
503
+ function onEvent(type: string) {
504
+ return (event: Event) => {
505
+ const wsEvent = event as unknown as Socket.WebSocketEvent
506
+ if (buffering) {
507
+ buffered.push([type, wsEvent])
508
+ } else {
509
+ dispatch(type, wsEvent)
510
+ }
511
+ }
512
+ }
513
+ ws.addEventListener("message", onEvent("message"))
514
+ ws.addEventListener("error", onEvent("error"))
515
+ ws.addEventListener("close", onEvent("close"))
516
+
517
+ function replay() {
518
+ if (!buffering) return
519
+ buffering = false
520
+ for (const [type, event] of buffered.splice(0)) {
521
+ dispatch(type, event)
522
+ }
523
+ }
524
+
525
+ return {
526
+ get readyState() {
527
+ return ws.readyState
528
+ },
529
+ addEventListener(type, listener, options) {
530
+ if (type === "open") {
531
+ ws.addEventListener(type, listener as EventListener, options as AddEventListenerOptions)
532
+ return
533
+ }
534
+ let entries = listeners.get(type)
535
+ if (!entries) {
536
+ entries = []
537
+ listeners.set(type, entries)
538
+ }
539
+ entries.push({ listener, once: options?.once === true })
540
+ if (buffering) queueMicrotask(replay)
541
+ },
542
+ removeEventListener(type, listener) {
543
+ if (type === "open") {
544
+ ws.removeEventListener(type, listener as EventListener)
545
+ return
546
+ }
547
+ removeListener(type, listener)
548
+ },
549
+ close: (code, reason) => ws.close(code, reason),
550
+ send: (data) => ws.send(data)
551
+ }
552
+ }
553
+
516
554
  const cancelResponseBody = (body: HttpBody.HttpBody): Effect.Effect<void> => {
517
555
  const stream = (body as any).body
518
556
  if ((body._tag === "Raw" || body._tag === "Uint8Array") && stream instanceof ReadableStream) {
package/src/DenoRedis.ts CHANGED
@@ -46,10 +46,13 @@ export class DenoRedis extends Context.Service<DenoRedis, {
46
46
  const make = Effect.fnUntraced(function*(options: RedisOptions = {}) {
47
47
  const connectClient = () => {
48
48
  const { url, ...connectOptions } = options
49
+ const parsedUrl = url === undefined ? undefined : new URL(url)
49
50
  const { name, ...parsed } = url === undefined ? { hostname: "localhost" } : parseURL(url)
50
51
  return connect({
51
52
  ...parsed,
52
53
  ...(name === undefined ? {} : { username: name }),
54
+ ...(parsedUrl?.username ? { username: decodeURIComponent(parsedUrl.username) } : {}),
55
+ ...(parsedUrl?.password ? { password: decodeURIComponent(parsedUrl.password) } : {}),
53
56
  ...Record.filter(connectOptions, Predicate.isNotUndefined)
54
57
  })
55
58
  }