@effect/platform-deno 4.0.0-beta.104

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 (123) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +13 -0
  3. package/dist/DenoChildProcessSpawner.d.ts +39 -0
  4. package/dist/DenoChildProcessSpawner.d.ts.map +1 -0
  5. package/dist/DenoChildProcessSpawner.js +311 -0
  6. package/dist/DenoChildProcessSpawner.js.map +1 -0
  7. package/dist/DenoClusterHttp.d.ts +60 -0
  8. package/dist/DenoClusterHttp.d.ts.map +1 -0
  9. package/dist/DenoClusterHttp.js +78 -0
  10. package/dist/DenoClusterHttp.js.map +1 -0
  11. package/dist/DenoClusterSocket.d.ts +65 -0
  12. package/dist/DenoClusterSocket.d.ts.map +1 -0
  13. package/dist/DenoClusterSocket.js +101 -0
  14. package/dist/DenoClusterSocket.js.map +1 -0
  15. package/dist/DenoCrypto.d.ts +25 -0
  16. package/dist/DenoCrypto.d.ts.map +1 -0
  17. package/dist/DenoCrypto.js +52 -0
  18. package/dist/DenoCrypto.js.map +1 -0
  19. package/dist/DenoFileSystem.d.ts +10 -0
  20. package/dist/DenoFileSystem.d.ts.map +1 -0
  21. package/dist/DenoFileSystem.js +331 -0
  22. package/dist/DenoFileSystem.js.map +1 -0
  23. package/dist/DenoHttpClient.d.ts +9 -0
  24. package/dist/DenoHttpClient.d.ts.map +1 -0
  25. package/dist/DenoHttpClient.js +9 -0
  26. package/dist/DenoHttpClient.js.map +1 -0
  27. package/dist/DenoHttpPlatform.d.ts +34 -0
  28. package/dist/DenoHttpPlatform.d.ts.map +1 -0
  29. package/dist/DenoHttpPlatform.js +88 -0
  30. package/dist/DenoHttpPlatform.js.map +1 -0
  31. package/dist/DenoHttpServer.d.ts +99 -0
  32. package/dist/DenoHttpServer.d.ts.map +1 -0
  33. package/dist/DenoHttpServer.js +353 -0
  34. package/dist/DenoHttpServer.js.map +1 -0
  35. package/dist/DenoHttpServerRequest.d.ts +18 -0
  36. package/dist/DenoHttpServerRequest.d.ts.map +1 -0
  37. package/dist/DenoHttpServerRequest.js +8 -0
  38. package/dist/DenoHttpServerRequest.js.map +1 -0
  39. package/dist/DenoKeyValueStore.d.ts +22 -0
  40. package/dist/DenoKeyValueStore.d.ts.map +1 -0
  41. package/dist/DenoKeyValueStore.js +21 -0
  42. package/dist/DenoKeyValueStore.js.map +1 -0
  43. package/dist/DenoMultipart.d.ts +32 -0
  44. package/dist/DenoMultipart.d.ts.map +1 -0
  45. package/dist/DenoMultipart.js +25 -0
  46. package/dist/DenoMultipart.js.map +1 -0
  47. package/dist/DenoPath.d.ts +43 -0
  48. package/dist/DenoPath.d.ts.map +1 -0
  49. package/dist/DenoPath.js +81 -0
  50. package/dist/DenoPath.js.map +1 -0
  51. package/dist/DenoRedis.d.ts +60 -0
  52. package/dist/DenoRedis.d.ts.map +1 -0
  53. package/dist/DenoRedis.js +76 -0
  54. package/dist/DenoRedis.js.map +1 -0
  55. package/dist/DenoRuntime.d.ts +36 -0
  56. package/dist/DenoRuntime.d.ts.map +1 -0
  57. package/dist/DenoRuntime.js +35 -0
  58. package/dist/DenoRuntime.js.map +1 -0
  59. package/dist/DenoServices.d.ts +34 -0
  60. package/dist/DenoServices.d.ts.map +1 -0
  61. package/dist/DenoServices.js +16 -0
  62. package/dist/DenoServices.js.map +1 -0
  63. package/dist/DenoSocket.d.ts +99 -0
  64. package/dist/DenoSocket.d.ts.map +1 -0
  65. package/dist/DenoSocket.js +192 -0
  66. package/dist/DenoSocket.js.map +1 -0
  67. package/dist/DenoSocketServer.d.ts +70 -0
  68. package/dist/DenoSocketServer.d.ts.map +1 -0
  69. package/dist/DenoSocketServer.js +68 -0
  70. package/dist/DenoSocketServer.js.map +1 -0
  71. package/dist/DenoStdio.d.ts +11 -0
  72. package/dist/DenoStdio.d.ts.map +1 -0
  73. package/dist/DenoStdio.js +39 -0
  74. package/dist/DenoStdio.js.map +1 -0
  75. package/dist/DenoTerminal.d.ts +21 -0
  76. package/dist/DenoTerminal.d.ts.map +1 -0
  77. package/dist/DenoTerminal.js +27 -0
  78. package/dist/DenoTerminal.js.map +1 -0
  79. package/dist/DenoWorker.d.ts +17 -0
  80. package/dist/DenoWorker.d.ts.map +1 -0
  81. package/dist/DenoWorker.js +54 -0
  82. package/dist/DenoWorker.js.map +1 -0
  83. package/dist/DenoWorkerRunner.d.ts +24 -0
  84. package/dist/DenoWorkerRunner.d.ts.map +1 -0
  85. package/dist/DenoWorkerRunner.js +150 -0
  86. package/dist/DenoWorkerRunner.js.map +1 -0
  87. package/dist/index.d.ts +88 -0
  88. package/dist/index.d.ts.map +1 -0
  89. package/dist/index.js +89 -0
  90. package/dist/index.js.map +1 -0
  91. package/dist/internal/denoSocketServer.d.ts +7 -0
  92. package/dist/internal/denoSocketServer.d.ts.map +1 -0
  93. package/dist/internal/denoSocketServer.js +55 -0
  94. package/dist/internal/denoSocketServer.js.map +1 -0
  95. package/dist/internal/error.d.ts +4 -0
  96. package/dist/internal/error.d.ts.map +1 -0
  97. package/dist/internal/error.js +46 -0
  98. package/dist/internal/error.js.map +1 -0
  99. package/package.json +72 -0
  100. package/src/DenoChildProcessSpawner.ts +439 -0
  101. package/src/DenoClusterHttp.ts +156 -0
  102. package/src/DenoClusterSocket.ts +197 -0
  103. package/src/DenoCrypto.ts +63 -0
  104. package/src/DenoFileSystem.ts +497 -0
  105. package/src/DenoHttpClient.ts +9 -0
  106. package/src/DenoHttpPlatform.ts +93 -0
  107. package/src/DenoHttpServer.ts +535 -0
  108. package/src/DenoHttpServerRequest.ts +18 -0
  109. package/src/DenoKeyValueStore.ts +28 -0
  110. package/src/DenoMultipart.ts +53 -0
  111. package/src/DenoPath.ts +102 -0
  112. package/src/DenoRedis.ts +113 -0
  113. package/src/DenoRuntime.ts +73 -0
  114. package/src/DenoServices.ts +49 -0
  115. package/src/DenoSocket.ts +318 -0
  116. package/src/DenoSocketServer.ts +120 -0
  117. package/src/DenoStdio.ts +51 -0
  118. package/src/DenoTerminal.ts +32 -0
  119. package/src/DenoWorker.ts +75 -0
  120. package/src/DenoWorkerRunner.ts +175 -0
  121. package/src/index.ts +110 -0
  122. package/src/internal/denoSocketServer.ts +89 -0
  123. package/src/internal/error.ts +63 -0
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Path service layers backed by the Deno Standard Library.
3
+ *
4
+ * **Example** (Using Deno path operations)
5
+ *
6
+ * ```ts import.meta.vitest
7
+ * import { Effect, Path } from "effect"
8
+ * import { DenoPath } from "@effect/platform-deno"
9
+ *
10
+ * const program = Effect.gen(function*() {
11
+ * const path = yield* Path.Path
12
+ * return path.extname("file.txt")
13
+ * }).pipe(Effect.provide(DenoPath.layer))
14
+ *
15
+ * Effect.runSync(program) // => ".txt"
16
+ * ```
17
+ *
18
+ * @since 4.0.0
19
+ */
20
+
21
+ import * as DenoPath from "@std/path"
22
+ import * as DenoPathPosix from "@std/path/posix"
23
+ import * as DenoPathWin from "@std/path/windows"
24
+ import * as Effect from "effect/Effect"
25
+ import * as Layer from "effect/Layer"
26
+ import * as Path from "effect/Path"
27
+ import * as PlatformError from "effect/PlatformError"
28
+
29
+ const fileUrlOps = (impl: {
30
+ readonly fromFileUrl: typeof DenoPath.fromFileUrl
31
+ readonly toFileUrl: typeof DenoPath.toFileUrl
32
+ }) => ({
33
+ fromFileUrl: (url: URL): Effect.Effect<string, PlatformError.BadArgument> =>
34
+ Effect.try({
35
+ try: () => impl.fromFileUrl(url),
36
+ catch: (cause) =>
37
+ new PlatformError.BadArgument({
38
+ module: "Path",
39
+ method: "fromFileUrl",
40
+ cause
41
+ })
42
+ }),
43
+ toFileUrl: (path: string): Effect.Effect<URL, PlatformError.BadArgument> =>
44
+ Effect.try({
45
+ try: (): URL => impl.toFileUrl(path),
46
+ catch: (cause): PlatformError.BadArgument =>
47
+ new PlatformError.BadArgument({
48
+ module: "Path",
49
+ method: "toFileUrl",
50
+ cause
51
+ })
52
+ })
53
+ })
54
+
55
+ /**
56
+ * A {@linkplain Layer.Layer | layer} that provides POSIX path operations.
57
+ *
58
+ * @category layers
59
+ * @since 4.0.0
60
+ */
61
+ export const layerPosix: Layer.Layer<Path.Path> = Layer.succeed(Path.Path)(
62
+ Path.Path.of({
63
+ [Path.TypeId]: Path.TypeId,
64
+ ...DenoPathPosix,
65
+ sep: DenoPathPosix.SEPARATOR,
66
+ ...fileUrlOps(DenoPathPosix)
67
+ })
68
+ )
69
+
70
+ /**
71
+ * A {@linkplain Layer.Layer | layer} that provides Windows path operations.
72
+ *
73
+ * @category layers
74
+ * @since 4.0.0
75
+ */
76
+ export const layerWin32: Layer.Layer<Path.Path> = Layer.succeed(
77
+ Path.Path
78
+ )(
79
+ Path.Path.of({
80
+ [Path.TypeId]: Path.TypeId,
81
+ ...DenoPathWin,
82
+ sep: DenoPathWin.SEPARATOR,
83
+ ...fileUrlOps(DenoPathWin)
84
+ })
85
+ )
86
+
87
+ /**
88
+ * A {@linkplain Layer.Layer | layer} that provides OS-agnostic path operations.
89
+ *
90
+ * @category layers
91
+ * @since 4.0.0
92
+ */
93
+ export const layer: Layer.Layer<Path.Path> = Layer.succeed(
94
+ Path.Path
95
+ )(
96
+ Path.Path.of({
97
+ [Path.TypeId]: Path.TypeId,
98
+ ...DenoPath,
99
+ sep: DenoPath.SEPARATOR,
100
+ ...fileUrlOps(DenoPath)
101
+ })
102
+ )
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Deno Redis integration backed by `@db/redis`.
3
+ *
4
+ * This module creates a scoped, native Deno Redis client and exposes it as
5
+ * both the portable `Redis` service and the Deno-specific {@link DenoRedis}
6
+ * service for direct access to the raw client. Unlike Bun's built-in client,
7
+ * `@db/redis` connects eagerly using RESP2, so layer construction can fail
8
+ * with a `RedisError`.
9
+ *
10
+ * @since 4.0.0
11
+ */
12
+ import { connect, parseURL, type Redis as RedisClient, type RedisConnectOptions } from "@db/redis"
13
+ import * as Config from "effect/Config"
14
+ import * as Context from "effect/Context"
15
+ import * as Effect from "effect/Effect"
16
+ import * as Fn from "effect/Function"
17
+ import * as Layer from "effect/Layer"
18
+ import * as Predicate from "effect/Predicate"
19
+ import * as Record from "effect/Record"
20
+ import * as Redis from "effect/unstable/persistence/Redis"
21
+
22
+ /**
23
+ * Options for connecting to Redis, including a Redis URL or individual
24
+ * connection settings. Explicit settings override values from the URL.
25
+ *
26
+ * @category models
27
+ * @since 4.0.0
28
+ */
29
+ export type RedisOptions = Omit<RedisConnectOptions, "hostname"> & {
30
+ readonly hostname?: string
31
+ readonly url?: string
32
+ }
33
+
34
+ /**
35
+ * Service tag for Deno Redis integration, exposing the raw `@db/redis` client
36
+ * and a `use` helper that maps client promise failures to `RedisError`.
37
+ *
38
+ * @category services
39
+ * @since 4.0.0
40
+ */
41
+ export class DenoRedis extends Context.Service<DenoRedis, {
42
+ readonly client: RedisClient
43
+ readonly use: <A>(f: (client: RedisClient) => Promise<A>) => Effect.Effect<A, Redis.RedisError>
44
+ }>()("@effect/platform-deno/DenoRedis") {}
45
+
46
+ const make = Effect.fnUntraced(function*(options: RedisOptions = {}) {
47
+ const client = yield* Effect.acquireRelease(
48
+ Effect.tryPromise({
49
+ try: () => {
50
+ const { url, ...connectOptions } = options
51
+ const { name, ...parsed } = url === undefined ? { hostname: "localhost" } : parseURL(url)
52
+ return connect({
53
+ ...parsed,
54
+ ...(name === undefined ? {} : { username: name }),
55
+ ...Record.filter(connectOptions, Predicate.isNotUndefined)
56
+ })
57
+ },
58
+ catch: (cause) => new Redis.RedisError({ cause })
59
+ }),
60
+ (client) => Effect.sync(() => client.close())
61
+ )
62
+
63
+ const use = <A>(f: (client: RedisClient) => Promise<A>) =>
64
+ Effect.tryPromise({
65
+ try: () => f(client),
66
+ catch: (cause) => new Redis.RedisError({ cause })
67
+ })
68
+
69
+ const redis = yield* Redis.make({
70
+ send: <A = unknown>(command: string, ...args: ReadonlyArray<string>) =>
71
+ Effect.tryPromise({
72
+ try: () => client.sendCommand(command, args as Array<string>) as Promise<A>,
73
+ catch: (cause) => new Redis.RedisError({ cause })
74
+ })
75
+ })
76
+
77
+ const denoRedis = Fn.identity<DenoRedis["Service"]>({
78
+ client,
79
+ use
80
+ })
81
+
82
+ return Context.make(DenoRedis, denoRedis).pipe(
83
+ Context.add(Redis.Redis, redis)
84
+ )
85
+ })
86
+
87
+ /**
88
+ * Provides `Redis` and `DenoRedis` services backed by an `@db/redis` client,
89
+ * closing the client when the layer scope ends. URL-derived options can be
90
+ * overridden by other supplied options.
91
+ *
92
+ * @category layers
93
+ * @since 4.0.0
94
+ */
95
+ export const layer = (
96
+ options?: RedisOptions | undefined
97
+ ): Layer.Layer<Redis.Redis | DenoRedis, Redis.RedisError> => Layer.effectContext(make(options))
98
+
99
+ /**
100
+ * Provides `Redis` and `DenoRedis` services from `Config`-backed options,
101
+ * closing the client when the layer scope ends.
102
+ *
103
+ * @category layers
104
+ * @since 4.0.0
105
+ */
106
+ export const layerConfig = (
107
+ options: Config.Wrap<RedisOptions>
108
+ ): Layer.Layer<Redis.Redis | DenoRedis, Redis.RedisError | Config.ConfigError> =>
109
+ Layer.effectContext(
110
+ Config.unwrap(options).pipe(
111
+ Effect.flatMap(make)
112
+ )
113
+ )
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Deno helper for running a root Effect program.
3
+ *
4
+ * @since 4.0.0
5
+ */
6
+
7
+ import type { Effect } from "effect/Effect"
8
+ import * as Runtime from "effect/Runtime"
9
+
10
+ /**
11
+ * Run an Effect as the entrypoint to a Deno application.
12
+ *
13
+ * @category running
14
+ * @since 4.0.0
15
+ */
16
+
17
+ export const runMain: {
18
+ /**
19
+ * Run an Effect as the entrypoint to a Deno application.
20
+ *
21
+ * @category running
22
+ * @since 4.0.0
23
+ */
24
+
25
+ (
26
+ options?: {
27
+ readonly disableErrorReporting?: boolean | undefined
28
+ readonly teardown?: Runtime.Teardown | undefined
29
+ }
30
+ ): <E, A>(effect: Effect<A, E>) => void
31
+ /**
32
+ * Run an Effect as the entrypoint to a Deno application.
33
+ *
34
+ * @category running
35
+ * @since 4.0.0
36
+ */
37
+
38
+ <E, A>(
39
+ effect: Effect<A, E>,
40
+ options?: {
41
+ readonly disableErrorReporting?: boolean | undefined
42
+ readonly teardown?: Runtime.Teardown | undefined
43
+ }
44
+ ): void
45
+ } = Runtime.makeRunMain(({
46
+ fiber,
47
+ teardown
48
+ }) => {
49
+ let receivedSignal = false
50
+
51
+ fiber.addObserver((exit) => {
52
+ if (!receivedSignal) {
53
+ Deno.removeSignalListener("SIGINT", onSigint)
54
+ Deno.removeSignalListener("SIGTERM", onSigint)
55
+ }
56
+
57
+ teardown(exit, (code) => {
58
+ if (receivedSignal || code !== 0) {
59
+ Deno.exit(code)
60
+ }
61
+ })
62
+ })
63
+
64
+ function onSigint(): void {
65
+ receivedSignal = true
66
+ Deno.removeSignalListener("SIGINT", onSigint)
67
+ Deno.removeSignalListener("SIGTERM", onSigint)
68
+ fiber.interruptUnsafe(fiber.id)
69
+ }
70
+
71
+ Deno.addSignalListener("SIGINT", onSigint)
72
+ Deno.addSignalListener("SIGTERM", onSigint)
73
+ })
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Aggregate Deno platform services layer.
3
+ *
4
+ * This module defines the `DenoServices` union and a single `layer` that
5
+ * provides Deno-backed child process spawning, crypto, filesystem, path, stdio,
6
+ * and terminal services. Use the layer when a Deno program wants the standard
7
+ * platform services from one place.
8
+ *
9
+ * @since 4.0.0
10
+ */
11
+ import type { Crypto } from "effect/Crypto"
12
+ import type { FileSystem } from "effect/FileSystem"
13
+ import * as Layer from "effect/Layer"
14
+ import type { Path } from "effect/Path"
15
+ import type { Stdio } from "effect/Stdio"
16
+ import type { Terminal } from "effect/Terminal"
17
+ import type { ChildProcessSpawner } from "effect/unstable/process/ChildProcessSpawner"
18
+ import * as DenoChildProcessSpawner from "./DenoChildProcessSpawner.ts"
19
+ import * as DenoCrypto from "./DenoCrypto.ts"
20
+ import * as DenoFileSystem from "./DenoFileSystem.ts"
21
+ import * as DenoPath from "./DenoPath.ts"
22
+ import * as DenoStdio from "./DenoStdio.ts"
23
+ import * as DenoTerminal from "./DenoTerminal.ts"
24
+
25
+ /**
26
+ * The union of core services provided by the Deno platform layer, including
27
+ * child process spawning, crypto, filesystem, path, stdio, and terminal services.
28
+ *
29
+ * @category models
30
+ * @since 4.0.0
31
+ */
32
+ export type DenoServices = ChildProcessSpawner | Crypto | FileSystem | Path | Terminal | Stdio
33
+
34
+ /**
35
+ * Provides the default Deno implementations for child process spawning,
36
+ * crypto, filesystem, path, stdio, and terminal services.
37
+ *
38
+ * @category layers
39
+ * @since 4.0.0
40
+ */
41
+ export const layer: Layer.Layer<DenoServices> = DenoChildProcessSpawner.layer.pipe(
42
+ Layer.provideMerge(Layer.mergeAll(
43
+ DenoFileSystem.layer,
44
+ DenoCrypto.layer,
45
+ DenoPath.layer,
46
+ DenoStdio.layer,
47
+ DenoTerminal.layer
48
+ ))
49
+ )
@@ -0,0 +1,318 @@
1
+ /**
2
+ * Native Deno socket adapters for Effect sockets.
3
+ *
4
+ * This module uses Deno-specific names: `makeTcp`, `makeTcpChannel`,
5
+ * `layerTcp`, and `fromConn` correspond to the Node platform's net and duplex
6
+ * APIs. Deno does not support `keepAliveInitialDelay`, and the `noDelay` and
7
+ * `keepAlive` options have no effect on Unix connections. A `CloseEvent` always
8
+ * closes gracefully because Deno has no equivalent of Node's reset-on-close.
9
+ *
10
+ * @since 4.0.0
11
+ */
12
+ import type { Array } from "effect"
13
+ import * as Channel from "effect/Channel"
14
+ import * as Context from "effect/Context"
15
+ import * as Deferred from "effect/Deferred"
16
+ import type * as Duration from "effect/Duration"
17
+ import * as Effect from "effect/Effect"
18
+ import * as FiberSet from "effect/FiberSet"
19
+ import * as Function from "effect/Function"
20
+ import * as Latch from "effect/Latch"
21
+ import * as Layer from "effect/Layer"
22
+ import * as Scope from "effect/Scope"
23
+ import * as Socket from "effect/unstable/socket/Socket"
24
+
25
+ /**
26
+ * Options for opening a TCP or Unix connection.
27
+ *
28
+ * @category options
29
+ * @since 4.0.0
30
+ */
31
+ export type ConnectOptions = (Deno.ConnectOptions | Deno.UnixConnectOptions) & {
32
+ readonly noDelay?: boolean | undefined
33
+ readonly keepAlive?: boolean | undefined
34
+ }
35
+
36
+ /**
37
+ * Options for opening a TCP or Unix connection.
38
+ *
39
+ * @category options
40
+ * @since 4.0.0
41
+ */
42
+ export type TcpOptions = ConnectOptions & {
43
+ readonly openTimeout?: Duration.Input | undefined
44
+ }
45
+
46
+ /**
47
+ * Service tag for the underlying Deno connection.
48
+ *
49
+ * @category services
50
+ * @since 4.0.0
51
+ */
52
+ export class Conn extends Context.Service<Conn, Deno.Conn>()(
53
+ "@effect/platform-deno/DenoSocket/Conn"
54
+ ) {}
55
+
56
+ /**
57
+ * Adapts a Deno connection into an Effect socket.
58
+ *
59
+ * @category constructors
60
+ * @since 4.0.0
61
+ */
62
+ export const fromConn = <RO>(
63
+ open: Effect.Effect<Deno.Conn, Socket.SocketError, RO>
64
+ ): Effect.Effect<Socket.Socket, never, Exclude<RO, Scope.Scope>> =>
65
+ Effect.withFiber<Socket.Socket, never, Exclude<RO, Scope.Scope>>((fiber) => {
66
+ let current: {
67
+ readonly conn: Deno.Conn
68
+ readonly writer: WritableStreamDefaultWriter<Uint8Array>
69
+ } | undefined
70
+ let tearingDown = false
71
+ let writeClosed = false
72
+ const latch = Latch.makeUnsafe(false)
73
+ const openServices = fiber.context as Context.Context<RO>
74
+
75
+ const run = <R, E, _>(handler: (_: Uint8Array) => Effect.Effect<_, E, R> | void, options?: {
76
+ readonly onOpen?: Effect.Effect<void> | undefined
77
+ }) =>
78
+ Effect.scopedWith(Effect.fnUntraced(function*(scope) {
79
+ const fiberSet = yield* FiberSet.make<any, E | Socket.SocketError>().pipe(
80
+ Scope.provide(scope)
81
+ )
82
+ let conn: Deno.Conn | undefined
83
+ yield* Scope.addFinalizer(
84
+ scope,
85
+ Effect.suspend(() => {
86
+ tearingDown = true
87
+ return conn === undefined ? Effect.void : close(conn)
88
+ })
89
+ )
90
+ conn = yield* Scope.provide(open, scope)
91
+ const reader = conn.readable.getReader()
92
+ const writer = conn.writable.getWriter()
93
+ const runFork = yield* Effect.provideService(FiberSet.runtime(fiberSet)<R>(), Conn, conn)
94
+
95
+ current = { conn, writer }
96
+ tearingDown = false
97
+ if (writeClosed) {
98
+ writeClosed = false
99
+ writer.releaseLock()
100
+ yield* closeWrite(conn)
101
+ }
102
+ latch.openUnsafe()
103
+
104
+ const read = Effect.tryPromise(
105
+ () => reader.read()
106
+ ).pipe(
107
+ Effect.catchIf(
108
+ (error) => tearingDown && isTeardownError(error.cause),
109
+ () => Effect.succeed({ done: true, value: undefined } as ReadableStreamReadDoneResult<Uint8Array>)
110
+ ),
111
+ Effect.mapError((error) =>
112
+ new Socket.SocketError({
113
+ reason: new Socket.SocketReadError({ cause: error.cause })
114
+ })
115
+ )
116
+ )
117
+ const readLoop: Effect.Effect<void, Socket.SocketError> = Effect.suspend(() =>
118
+ Effect.flatMap(read, ({ done, value }) => {
119
+ if (done) {
120
+ Deferred.doneUnsafe(fiberSet.deferred, Effect.void)
121
+ return Effect.void
122
+ }
123
+ const result = handler(value)
124
+ if (Effect.isEffect(result)) {
125
+ runFork(result)
126
+ }
127
+ return readLoop
128
+ })
129
+ )
130
+ yield* FiberSet.run(fiberSet, readLoop)
131
+
132
+ if (options?.onOpen) {
133
+ yield* options.onOpen
134
+ }
135
+ return yield* FiberSet.join(fiberSet)
136
+ })).pipe(
137
+ Effect.updateContext((input: Context.Context<R>) => Context.merge(openServices, input)),
138
+ Effect.onExit(() =>
139
+ Effect.sync(() => {
140
+ tearingDown = true
141
+ latch.closeUnsafe()
142
+ current = undefined
143
+ })
144
+ )
145
+ )
146
+
147
+ const write = (chunk: Uint8Array | string | Socket.CloseEvent) =>
148
+ latch.whenOpen(Effect.suspend(() => {
149
+ const { conn, writer } = current!
150
+ if (Socket.isCloseEvent(chunk)) {
151
+ tearingDown = true
152
+ return close(conn)
153
+ }
154
+ const bytes = typeof chunk === "string" ? encoder.encode(chunk) : chunk
155
+ return Effect.tryPromise({
156
+ try: () => writer.ready.then(() => writer.write(bytes)),
157
+ catch: (cause) =>
158
+ new Socket.SocketError({
159
+ reason: new Socket.SocketWriteError({ cause })
160
+ })
161
+ })
162
+ }))
163
+
164
+ const writer = Effect.acquireRelease(
165
+ Effect.sync(() => {
166
+ writeClosed = false
167
+ return write
168
+ }),
169
+ () =>
170
+ Effect.suspend(() => {
171
+ if (current === undefined) {
172
+ writeClosed = true
173
+ return Effect.void
174
+ }
175
+ const { conn, writer } = current
176
+ writer.releaseLock()
177
+ return closeWrite(conn)
178
+ })
179
+ )
180
+
181
+ return Effect.succeed(Socket.make({
182
+ run,
183
+ runRaw: run,
184
+ writer
185
+ }))
186
+ })
187
+
188
+ /**
189
+ * Opens a native Deno TCP or Unix connection as an Effect socket.
190
+ *
191
+ * **Details**
192
+ *
193
+ * An `openTimeout` interrupts acquisition but cannot cancel the in-flight
194
+ * `Deno.connect` promise. The scope finalizer closes a connection that arrives
195
+ * after the timeout.
196
+ *
197
+ * @category constructors
198
+ * @since 4.0.0
199
+ */
200
+ export const makeTcp = (options: TcpOptions): Effect.Effect<Socket.Socket> => {
201
+ const { keepAlive, noDelay, openTimeout, ...connectOptions } = options
202
+ const acquire = Effect.contextWith((context: Context.Context<Scope.Scope>) => {
203
+ let conn: Deno.Conn | undefined
204
+ let finalized = false
205
+ return Scope.addFinalizer(
206
+ Context.get(context, Scope.Scope),
207
+ Effect.suspend(() => {
208
+ finalized = true
209
+ return conn === undefined ? Effect.void : close(conn)
210
+ })
211
+ ).pipe(
212
+ Effect.andThen(Effect.tryPromise({
213
+ try: () => {
214
+ const connecting = connectOptions.transport === "unix"
215
+ ? Deno.connect(connectOptions)
216
+ : Deno.connect(connectOptions)
217
+ return connecting.then((connection) => {
218
+ conn = connection
219
+ if (finalized) connection.close()
220
+ return connection
221
+ })
222
+ },
223
+ catch: (cause) =>
224
+ new Socket.SocketError({
225
+ reason: new Socket.SocketOpenError({ kind: "Unknown", cause })
226
+ })
227
+ })),
228
+ Effect.tap((connection) =>
229
+ Effect.sync(() => {
230
+ if ("setNoDelay" in connection && noDelay !== undefined) {
231
+ connection.setNoDelay(noDelay)
232
+ }
233
+ if ("setKeepAlive" in connection && keepAlive !== undefined) {
234
+ connection.setKeepAlive(keepAlive)
235
+ }
236
+ })
237
+ )
238
+ )
239
+ }).pipe(
240
+ openTimeout === undefined
241
+ ? Function.identity
242
+ : Effect.timeoutOrElse({
243
+ duration: openTimeout,
244
+ orElse: () =>
245
+ Effect.fail(
246
+ new Socket.SocketError({
247
+ reason: new Socket.SocketOpenError({ kind: "Timeout", cause: new Error("Connection timed out") })
248
+ })
249
+ )
250
+ })
251
+ )
252
+ return fromConn(acquire)
253
+ }
254
+
255
+ /**
256
+ * Creates a channel over a native Deno TCP or Unix connection.
257
+ *
258
+ * @category constructors
259
+ * @since 4.0.0
260
+ */
261
+ export const makeTcpChannel = <IE = never>(
262
+ options: ConnectOptions
263
+ ): Channel.Channel<
264
+ Array.NonEmptyReadonlyArray<Uint8Array>,
265
+ Socket.SocketError | IE,
266
+ void,
267
+ Array.NonEmptyReadonlyArray<Uint8Array | string | Socket.CloseEvent>,
268
+ IE
269
+ > => Channel.unwrap(Effect.map(makeTcp(options), Socket.toChannelWith<IE>()))
270
+
271
+ /**
272
+ * Provides a socket by opening a native Deno TCP or Unix connection.
273
+ *
274
+ * @category layers
275
+ * @since 4.0.0
276
+ */
277
+ export const layerTcp: (options: ConnectOptions) => Layer.Layer<
278
+ Socket.Socket,
279
+ Socket.SocketError
280
+ > = Function.flow(makeTcp, Layer.effect(Socket.Socket))
281
+
282
+ /**
283
+ * Creates a socket layer connected to a URL with Deno's global WebSocket.
284
+ *
285
+ * @category layers
286
+ * @since 4.0.0
287
+ */
288
+ export const layerWebSocket = (url: string, options?: {
289
+ readonly closeCodeIsError?: (code: number) => boolean
290
+ }): Layer.Layer<Socket.Socket> =>
291
+ Layer.effect(Socket.Socket, Socket.makeWebSocket(url, options)).pipe(
292
+ Layer.provide(layerWebSocketConstructor)
293
+ )
294
+
295
+ /**
296
+ * Provides the WebSocket constructor backed by `globalThis.WebSocket`.
297
+ *
298
+ * @category layers
299
+ * @since 4.0.0
300
+ */
301
+ export const layerWebSocketConstructor: Layer.Layer<Socket.WebSocketConstructor> =
302
+ Socket.layerWebSocketConstructorGlobal
303
+
304
+ const encoder = new TextEncoder()
305
+
306
+ const isBadResource = (cause: unknown): cause is Deno.errors.BadResource => cause instanceof Deno.errors.BadResource
307
+
308
+ const isTeardownError = (cause: unknown): boolean => cause instanceof Deno.errors.Interrupted || isBadResource(cause)
309
+
310
+ const close = (conn: Deno.Conn): Effect.Effect<void> =>
311
+ Effect.try(() => conn.close()).pipe(
312
+ Effect.catch(({ cause }) => isBadResource(cause) ? Effect.void : Effect.die(cause))
313
+ )
314
+
315
+ const closeWrite = (conn: Deno.Conn): Effect.Effect<void> =>
316
+ Effect.tryPromise(() => conn.closeWrite()).pipe(
317
+ Effect.catch((error) => isBadResource(error) ? Effect.void : Effect.die(error))
318
+ )