@effect/platform-deno 4.0.2 → 4.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/DenoDns.ts ADDED
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Deno-backed implementation of Effect's `Dns` service.
3
+ *
4
+ * Address lookups use the operating system resolver through Deno's `node:dns`
5
+ * compatibility layer, so they also read the hosts file. Record queries and
6
+ * reverse lookups use `Deno.resolveDns` and can be cancelled by interruption.
7
+ * Records whose data cannot be represented, such as names that are not valid
8
+ * `Host.DomainName` values, are skipped, and a query fails with
9
+ * `InvalidResponse` when every record is skipped.
10
+ *
11
+ * **Gotchas**
12
+ *
13
+ * `Deno.resolveDns` reports every error response from the name server with the
14
+ * same error as a missing name, so refused queries and server failures
15
+ * (`REFUSED`, `SERVFAIL`, `FORMERR`, `NOTIMP`) fail with `NotFound` instead of
16
+ * `Refused`, `ServerFailure`, `InvalidResponse`, or `Unsupported`. Server
17
+ * failures are therefore not reported as temporary. `Deno.resolveDns` cannot
18
+ * query TLSA records, so TLSA queries fail with `Unsupported`. Queries require
19
+ * the `--allow-net` permission.
20
+ *
21
+ * @stability experimental
22
+ * @since 4.0.0
23
+ */
24
+ import * as NodeDns from "@effect/platform-node-shared/NodeDns"
25
+ import type * as Arr from "effect/Array"
26
+ import * as Config from "effect/Config"
27
+ import * as Duration from "effect/Duration"
28
+ import * as Effect from "effect/Effect"
29
+ import * as Layer from "effect/Layer"
30
+ import * as Dns from "effect/net/Dns"
31
+ import * as NetAddress from "effect/net/NetAddress"
32
+ import * as Result from "effect/Result"
33
+
34
+ /**
35
+ * Options for the Deno `Dns` service.
36
+ *
37
+ * **Details**
38
+ *
39
+ * `nameServer` replaces the system name server for record queries and reverse
40
+ * lookups and is converted like `Dns.nameServerFromInput`. Address
41
+ * lookups always use the operating system resolver.
42
+ *
43
+ * **Gotchas**
44
+ *
45
+ * Invalid name servers fail with a `NetAddress.NetAddressError` when the
46
+ * service is created, and so do IPv6 name servers with a scope ID, such as
47
+ * link-local addresses.
48
+ *
49
+ * @stability experimental
50
+ * @category models
51
+ * @since 4.0.0
52
+ */
53
+ export interface Options {
54
+ readonly nameServer?: NetAddress.IpAddressInput | NetAddress.InetAddressInput | undefined
55
+ }
56
+
57
+ const reasons: Record<string, Dns.DnsErrorReason> = {
58
+ NotFound: "NotFound",
59
+ TimedOut: "Timeout",
60
+ ConnectionRefused: "Refused",
61
+ InvalidData: "InvalidResponse",
62
+ NotSupported: "Unsupported"
63
+ }
64
+
65
+ const toDnsError = (cause: unknown, name: string, type: Dns.RecordType): Dns.DnsError =>
66
+ new Dns.DnsError({
67
+ reason: (cause instanceof Error ? reasons[cause.name] : undefined) ?? "Unknown",
68
+ method: "resolve",
69
+ hostname: name,
70
+ recordType: type,
71
+ cause
72
+ })
73
+
74
+ const queries: {
75
+ readonly [K in Dns.RecordType]: (
76
+ name: string,
77
+ options: Deno.ResolveDnsOptions
78
+ ) => Promise<Result.Result<Array<Dns.DnsRecord>, Dns.DnsError>>
79
+ } = {
80
+ A: async (name, options) =>
81
+ NodeDns.recordsFromResolver(name, "A", await Deno.resolveDns(name, "A", options), (address) => ({
82
+ address: NetAddress.ipFromStringUnsafe(address) as NetAddress.Ipv4Address
83
+ })),
84
+ AAAA: async (name, options) =>
85
+ NodeDns.recordsFromResolver(name, "AAAA", await Deno.resolveDns(name, "AAAA", options), (address) => ({
86
+ address: NetAddress.ipFromStringUnsafe(address) as NetAddress.Ipv6Address
87
+ })),
88
+ CAA: async (name, options) =>
89
+ NodeDns.recordsFromResolver(name, "CAA", await Deno.resolveDns(name, "CAA", options), (caa) => ({
90
+ critical: caa.critical,
91
+ tag: caa.tag,
92
+ value: caa.value
93
+ })),
94
+ CNAME: async (name, options) =>
95
+ NodeDns.recordsFromResolver(name, "CNAME", await Deno.resolveDns(name, "CNAME", options), (target) => ({
96
+ target: NodeDns.domainNameFromResolverUnsafe(target)
97
+ })),
98
+ MX: async (name, options) =>
99
+ NodeDns.recordsFromResolver(name, "MX", await Deno.resolveDns(name, "MX", options), (mx) => ({
100
+ exchange: NodeDns.domainNameFromResolverUnsafe(mx.exchange),
101
+ priority: mx.preference
102
+ })),
103
+ NAPTR: async (name, options) =>
104
+ NodeDns.recordsFromResolver(name, "NAPTR", await Deno.resolveDns(name, "NAPTR", options), (naptr) => ({
105
+ order: naptr.order,
106
+ preference: naptr.preference,
107
+ flags: naptr.flags,
108
+ service: naptr.services,
109
+ regexp: naptr.regexp,
110
+ replacement: NodeDns.domainNameFromResolverUnsafe(naptr.replacement)
111
+ })),
112
+ NS: async (name, options) =>
113
+ NodeDns.recordsFromResolver(name, "NS", await Deno.resolveDns(name, "NS", options), (host) => ({
114
+ host: NodeDns.domainNameFromResolverUnsafe(host)
115
+ })),
116
+ PTR: async (name, options) =>
117
+ NodeDns.recordsFromResolver(name, "PTR", await Deno.resolveDns(name, "PTR", options), (host) => ({
118
+ host: NodeDns.nameTextFromResolver(host, 8)
119
+ })),
120
+ SOA: async (name, options) =>
121
+ NodeDns.recordsFromResolver(name, "SOA", await Deno.resolveDns(name, "SOA", options), (soa) => ({
122
+ primary: NodeDns.domainNameFromResolverUnsafe(soa.mname),
123
+ admin: NodeDns.nameTextFromResolver(soa.rname, 8),
124
+ serial: soa.serial,
125
+ refresh: NodeDns.secondsFromInt32(soa.refresh),
126
+ retry: NodeDns.secondsFromInt32(soa.retry),
127
+ expire: NodeDns.secondsFromInt32(soa.expire),
128
+ minimum: Duration.seconds(soa.minimum)
129
+ })),
130
+ SRV: async (name, options) =>
131
+ NodeDns.recordsFromResolver(name, "SRV", await Deno.resolveDns(name, "SRV", options), (srv) => ({
132
+ target: NodeDns.domainNameFromResolverUnsafe(srv.target),
133
+ port: srv.port,
134
+ priority: srv.priority,
135
+ weight: srv.weight
136
+ })),
137
+ TLSA: async (name) =>
138
+ Result.fail(new Dns.DnsError({ reason: "Unsupported", method: "resolve", hostname: name, recordType: "TLSA" })),
139
+ TXT: async (name, options) =>
140
+ NodeDns.recordsFromResolver(name, "TXT", await Deno.resolveDns(name, "TXT", options), (chunks) => ({
141
+ chunks: chunks.map(NodeDns.utf8FromLatin1) as unknown as Arr.NonEmptyReadonlyArray<string>
142
+ }))
143
+ }
144
+
145
+ /**
146
+ * Creates a Deno `Dns` service.
147
+ *
148
+ * @stability experimental
149
+ * @category constructors
150
+ * @since 4.0.0
151
+ */
152
+ export const make = Effect.fnUntraced(function*(options?: Options) {
153
+ const input = options?.nameServer
154
+ const server = input === undefined ? undefined : yield* Effect.fromResult(Dns.nameServerFromInput(input))
155
+ if (server !== undefined && NetAddress.isInetAddressV6(server) && server.scopeId !== 0) {
156
+ return yield* new NetAddress.NetAddressError({
157
+ input: input!,
158
+ message: "IPv6 name servers with a scope ID are not supported"
159
+ })
160
+ }
161
+ const nameServer: Deno.ResolveDnsOptions["nameServer"] = server === undefined
162
+ ? undefined
163
+ : { ipAddr: NetAddress.formatHost(server), port: server.port }
164
+
165
+ return Dns.make({
166
+ lookup: NodeDns.lookup,
167
+ resolve: (name, type) =>
168
+ Effect.tryPromise({
169
+ try: (signal) => queries[type](name, nameServer === undefined ? { signal } : { nameServer, signal }),
170
+ catch: (cause) => toDnsError(cause, name, type)
171
+ }).pipe(Effect.flatMap(Effect.fromResult))
172
+ })
173
+ })
174
+
175
+ /**
176
+ * Layer that provides the Deno `Dns` service using the system resolver
177
+ * configuration.
178
+ *
179
+ * @stability experimental
180
+ * @category layers
181
+ * @since 4.0.0
182
+ */
183
+ export const layer: Layer.Layer<Dns.Dns> = Layer.effect(Dns.Dns, Effect.orDie(make()))
184
+
185
+ /**
186
+ * Creates a layer that provides the Deno `Dns` service with options read
187
+ * from configuration.
188
+ *
189
+ * @stability experimental
190
+ * @category layers
191
+ * @since 4.0.0
192
+ */
193
+ export const layerConfig = (
194
+ options: Config.Wrap<Options>
195
+ ): Layer.Layer<Dns.Dns, Config.ConfigError | NetAddress.NetAddressError> =>
196
+ Layer.effect(Dns.Dns, Effect.flatMap(Config.unwrap(options), make))
@@ -182,13 +182,18 @@ const makeFileInfo = (info: Deno.FileInfo): FileSystem.File.Info => ({
182
182
  blocks: Option.fromNullishOr(info.blocks)
183
183
  })
184
184
 
185
- /** A file handle is stateful and must not be used concurrently. */
185
+ /**
186
+ * Deno lacks positional reads, so `native` serializes seek + I/O. Cancelled
187
+ * entries are skipped; started I/O holds the queue until it settles, even
188
+ * after interruption. Cursor operations must not run concurrently.
189
+ */
186
190
  class FileImpl implements FileSystem.File {
187
191
  readonly [FileSystem.FileTypeId]: typeof FileSystem.FileTypeId = FileSystem.FileTypeId
188
192
  private readonly file: Deno.FsFile
189
193
  private readonly append: boolean
190
194
  private position = BigInt(0)
191
195
  private nativePosition: bigint | undefined = undefined
196
+ private nativeQueue: Promise<unknown> = Promise.resolve()
192
197
 
193
198
  constructor(
194
199
  file: Deno.FsFile,
@@ -224,41 +229,59 @@ class FileImpl implements FileSystem.File {
224
229
  })
225
230
  }
226
231
 
227
- private readChunk(method: string, buffer: Uint8Array) {
232
+ private native<A>(signal: AbortSignal, evaluate: () => Promise<A>): Promise<A> {
233
+ const result = this.nativeQueue.then(() => signal.aborted ? Promise.reject(signal.reason) : evaluate())
234
+ this.nativeQueue = result.catch(() => undefined)
235
+ return result
236
+ }
237
+
238
+ private readChunk(method: string, buffer: Uint8Array, explicit: bigint | undefined) {
228
239
  return Effect.suspend(() => {
229
- const position = this.position
240
+ if (explicit !== undefined && explicit < BigInt(0)) {
241
+ return Effect.fail(PlatformError.badArgument({
242
+ module: "FileSystem",
243
+ method,
244
+ description: "Cannot read before the start of the file"
245
+ }))
246
+ }
247
+ const position = explicit ?? this.position
230
248
  return Effect.map(
231
249
  tryPromise(
232
250
  method,
233
251
  undefined,
234
- async () => {
235
- if (this.nativePosition !== position) {
236
- this.file.seekSync(position, Deno.SeekMode.Start)
237
- }
238
- this.nativePosition = undefined
239
- return await this.file.read(buffer)
240
- }
252
+ (signal) =>
253
+ this.native(signal, async () => {
254
+ if (this.nativePosition !== position) {
255
+ this.file.seekSync(position, Deno.SeekMode.Start)
256
+ }
257
+ this.nativePosition = undefined
258
+ const bytesRead = (await this.file.read(buffer)) ?? 0
259
+ this.nativePosition = position + BigInt(bytesRead)
260
+ return bytesRead
261
+ })
241
262
  ),
242
263
  (bytesRead) => {
243
- this.position = this.nativePosition = position + BigInt(bytesRead ?? 0)
244
- return bytesRead ?? 0
264
+ if (explicit === undefined) {
265
+ this.position = position + BigInt(bytesRead)
266
+ }
267
+ return bytesRead
245
268
  }
246
269
  )
247
270
  })
248
271
  }
249
272
 
250
- read(buffer: Uint8Array) {
251
- return this.readChunk("read", buffer)
273
+ read(buffer: Uint8Array, options?: FileSystem.File.ReadOptions) {
274
+ return this.readChunk("read", buffer, options?.position)
252
275
  }
253
276
 
254
- readAlloc(size: number) {
277
+ readAlloc(size: number, options?: FileSystem.File.ReadOptions) {
255
278
  return Effect.suspend(() => {
256
279
  try {
257
280
  if (!Number.isInteger(size) || size < 0) {
258
281
  throw new RangeError("size must be a non-negative integer")
259
282
  }
260
283
  const buffer = new Uint8Array(size)
261
- return Effect.map(this.readChunk("readAlloc", buffer), (bytesRead) => {
284
+ return Effect.map(this.readChunk("readAlloc", buffer, options?.position), (bytesRead) => {
262
285
  if (bytesRead === 0) {
263
286
  return Option.none()
264
287
  }
@@ -294,19 +317,22 @@ class FileImpl implements FileSystem.File {
294
317
  tryPromise(
295
318
  method,
296
319
  undefined,
297
- async () => {
298
- if (!this.append && this.nativePosition !== position) {
299
- this.file.seekSync(position, Deno.SeekMode.Start)
300
- }
301
- this.nativePosition = undefined
302
- return await this.file.write(buffer)
303
- }
320
+ (signal) =>
321
+ this.native(signal, async () => {
322
+ if (!this.append && this.nativePosition !== position) {
323
+ this.file.seekSync(position, Deno.SeekMode.Start)
324
+ }
325
+ this.nativePosition = undefined
326
+ const bytesWritten = await this.file.write(buffer)
327
+ if (!this.append) {
328
+ this.nativePosition = position + BigInt(bytesWritten)
329
+ }
330
+ return bytesWritten
331
+ })
304
332
  ),
305
333
  (bytesWritten) => {
306
- if (this.append) {
307
- this.nativePosition = undefined
308
- } else {
309
- this.position = this.nativePosition = position + BigInt(bytesWritten)
334
+ if (!this.append) {
335
+ this.position = position + BigInt(bytesWritten)
310
336
  }
311
337
  return bytesWritten
312
338
  }
@@ -340,6 +366,13 @@ class FileImpl implements FileSystem.File {
340
366
  }
341
367
 
342
368
  const open: FileSystem.FileSystem["open"] = (path, options) => {
369
+ if (options?.noFollow === true) {
370
+ return Effect.fail(PlatformError.badArgument({
371
+ module: "FileSystem",
372
+ method: "open",
373
+ description: "noFollow is not supported by Deno"
374
+ }))
375
+ }
343
376
  const append = options?.flag?.startsWith("a") ?? false
344
377
  return Effect.map(
345
378
  Effect.acquireRelease(
package/src/DenoStdio.ts CHANGED
@@ -44,6 +44,7 @@ export const layer: Layer.Layer<Stdio.Stdio> = Layer.succeed(
44
44
  args: Effect.sync(() => Deno.args),
45
45
  stdinIsTerminal: Effect.sync(() => Deno.stdin.isTerminal()),
46
46
  stdoutIsTerminal: Effect.sync(() => Deno.stdout.isTerminal()),
47
+ stderrIsTerminal: Effect.sync(() => Deno.stderr.isTerminal()),
47
48
  stdout: (options) => output(() => Deno.stdout.writable, "stdout", options),
48
49
  stderr: (options) => output(() => Deno.stderr.writable, "stderr", options),
49
50
  stdin: Stream.fromReadableStream({
@@ -15,8 +15,9 @@ import type { Scope } from "effect/Scope"
15
15
  import type { Terminal, UserInput } from "effect/Terminal"
16
16
 
17
17
  /**
18
- * Creates a scoped `Terminal` service backed by process stdin/stdout, using the
19
- * optional predicate to decide when key input should end the input stream.
18
+ * Creates a scoped `Terminal` service backed by process stdin/stdout.
19
+ * By default, Esc, Ctrl+C, and Ctrl+D end key input. Supply `shouldQuit` to
20
+ * override these quit keys.
20
21
  *
21
22
  * @stability unstable
22
23
  * @category constructors
@@ -26,7 +27,7 @@ export const make: (shouldQuit?: (input: UserInput) => boolean) => Effect<Termin
26
27
 
27
28
  /**
28
29
  * Provides the default process-backed `Terminal` service, ending key input on
29
- * the default quit keys.
30
+ * bare Esc, Ctrl+C, or Ctrl+D.
30
31
  *
31
32
  * @stability unstable
32
33
  * @category layers
package/src/index.ts CHANGED
@@ -5,6 +5,12 @@
5
5
 
6
6
  // @barrel: Auto-generated exports. Do not edit manually.
7
7
 
8
+ /**
9
+ * @stability experimental
10
+ * @since 4.0.0
11
+ */
12
+ export * as DenoAddressResolver from "./DenoAddressResolver.ts"
13
+
8
14
  /**
9
15
  * @stability unstable
10
16
  * @since 4.0.0
@@ -29,6 +35,18 @@ export * as DenoClusterSocket from "./DenoClusterSocket.ts"
29
35
  */
30
36
  export * as DenoCrypto from "./DenoCrypto.ts"
31
37
 
38
+ /**
39
+ * @stability experimental
40
+ * @since 4.0.0
41
+ */
42
+ export * as DenoDatagramSocket from "./DenoDatagramSocket.ts"
43
+
44
+ /**
45
+ * @stability experimental
46
+ * @since 4.0.0
47
+ */
48
+ export * as DenoDns from "./DenoDns.ts"
49
+
32
50
  /**
33
51
  * @stability unstable
34
52
  * @since 4.0.0