port core HttpServer modules (#267)

This commit is contained in:
Tim
2025-07-13 20:50:57 +12:00
committed by GitHub
parent 20ab04ff06
commit 7352070058
34 changed files with 5778 additions and 82 deletions
+3 -1
View File
@@ -101,6 +101,8 @@
},
"dependencies": {
"@standard-schema/spec": "^1.0.0",
"fast-check": "^4.2.0"
"fast-check": "^4.2.0",
"find-my-way-ts": "^0.1.6",
"multipasta": "^0.2.5"
}
}
+9
View File
@@ -355,6 +355,15 @@ export const fromFailures: <E>(
failures: ReadonlyArray<Failure<E>>
) => Cause<E> = core.causeFromFailures
/**
* A `Cause` that that contains no failures, representing a successful
* computation or an empty state.
*
* @category constructors
* @since 2.0.0
*/
export const empty: Cause<never> = core.causeEmpty
/**
* Creates a `Cause` that represents a typed error.
*
+43
View File
@@ -2621,6 +2621,29 @@ export {
catch_ as catch
}
/**
* Returns a new channel, which is the same as this one, except the failure
* value of the returned channel is created by applying the specified function
* to the failure value of this channel.
*
* @since 2.0.0
* @category Error handling
*/
export const mapError: {
<OutErr, OutErr2>(
f: (err: OutErr) => OutErr2
): <OutElem, OutDone, InElem, InErr, InDone, Env>(
self: Channel<OutElem, OutErr, OutDone, InElem, InErr, InDone, Env>
) => Channel<OutElem, OutErr2, OutDone, InElem, InErr, InDone, Env>
<OutElem, OutErr, OutDone, InElem, InErr, InDone, Env, OutErr2>(
self: Channel<OutElem, OutErr, OutDone, InElem, InErr, InDone, Env>,
f: (err: OutErr) => OutErr2
): Channel<OutElem, OutErr2, OutDone, InElem, InErr, InDone, Env>
} = dual(2, <OutElem, OutErr, OutDone, InElem, InErr, InDone, Env, OutErr2>(
self: Channel<OutElem, OutErr, OutDone, InElem, InErr, InDone, Env>,
f: (err: OutErr) => OutErr2
): Channel<OutElem, OutErr2, OutDone, InElem, InErr, InDone, Env> => catch_(self, (err) => fail(f(err))))
/**
* Converts all errors in the channel to defects (unrecoverable failures).
* This is useful when you want to treat errors as programming errors.
@@ -3438,6 +3461,26 @@ const runWith = <
) as any
})
/**
* @since 4.0.0
* @category Services
*/
export const provideServices: {
<R2>(
services: ServiceMap.ServiceMap<R2>
): <OutElem, OutErr, OutDone, InElem, InErr, InDone, R>(
self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, R>
) => Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Exclude<R, R2>>
<OutElem, OutErr, OutDone, InElem, InErr, InDone, R, R2>(
self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, R>,
services: ServiceMap.ServiceMap<R2>
): Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Exclude<R, R2>>
} = dual(2, <OutElem, OutErr, OutDone, InElem, InErr, InDone, R, R2>(
self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, R>,
services: ServiceMap.ServiceMap<R2>
): Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Exclude<R, R2>> =>
fromTransform((upstream, scope) => Effect.provideServices(toTransform(self)(upstream, scope), services)))
/**
* Runs a channel and counts the number of elements it outputs.
*
+26 -19
View File
@@ -1773,6 +1773,13 @@ export const flatMap: {
): Effect<B, E | E1, R | R1>
} = internal.flatMap
/**
* @since 2.0.0
* @category Sequencing
*/
export const flatten: <A, E, R, E2, R2>(self: Effect<Effect<A, E, R>, E2, R2>) => Effect<A, E | E2, R | R2> =
internal.flatten
/**
* Chains two actions, where the second action can depend on the result of the
* first.
@@ -5121,6 +5128,20 @@ export const onExit: {
): Effect<A, E, R | R2>
} = internal.onExit
/**
* @since 4.0.0
* @category Resource management & finalization
*/
export const onExitInterruptible: {
<A, E, X, R2>(
cleanup: (exit: Exit.Exit<A, E>) => Effect<X, never, R2>
): <R>(self: Effect<A, E, R>) => Effect<A, E, R2 | R>
<A, E, R, X, R2>(
self: Effect<A, E, R>,
cleanup: (exit: Exit.Exit<A, E>) => Effect<X, never, R2>
): Effect<A, E, R | R2>
} = internal.onExitInterruptible
// -----------------------------------------------------------------------------
// Caching
// -----------------------------------------------------------------------------
@@ -5188,9 +5209,7 @@ export const onExit: {
* @since 2.0.0
* @category Caching
*/
export const cached: <A, E, R>(
self: Effect<A, E, R>
) => Effect<Effect<A, E>, never, R> = internal.cached
export const cached: <A, E, R>(self: Effect<A, E, R>) => Effect<Effect<A, E, R>> = internal.cached
/**
* Returns an effect that caches its result for a specified `Duration`,
@@ -5259,13 +5278,8 @@ export const cached: <A, E, R>(
* @category Caching
*/
export const cachedWithTTL: {
(
timeToLive: Duration.DurationInput
): <A, E, R>(self: Effect<A, E, R>) => Effect<Effect<A, E>, never, R>
<A, E, R>(
self: Effect<A, E, R>,
timeToLive: Duration.DurationInput
): Effect<Effect<A, E>, never, R>
(timeToLive: Duration.DurationInput): <A, E, R>(self: Effect<A, E, R>) => Effect<Effect<A, E, R>>
<A, E, R>(self: Effect<A, E, R>, timeToLive: Duration.DurationInput): Effect<Effect<A, E, R>>
} = internal.cachedWithTTL
/**
@@ -5338,15 +5352,8 @@ export const cachedWithTTL: {
* @category Caching
*/
export const cachedInvalidateWithTTL: {
(
timeToLive: Duration.DurationInput
): <A, E, R>(
self: Effect<A, E, R>
) => Effect<[Effect<A, E>, Effect<void>], never, R>
<A, E, R>(
self: Effect<A, E, R>,
timeToLive: Duration.DurationInput
): Effect<[Effect<A, E>, Effect<void>], never, R>
(timeToLive: Duration.DurationInput): <A, E, R>(self: Effect<A, E, R>) => Effect<[Effect<A, E, R>, Effect<void>]>
<A, E, R>(self: Effect<A, E, R>, timeToLive: Duration.DurationInput): Effect<[Effect<A, E, R>, Effect<void>]>
} = internal.cachedInvalidateWithTTL
// -----------------------------------------------------------------------------
+14 -5
View File
@@ -76,10 +76,10 @@ import type { Effect } from "./Effect.js"
import type { Exit } from "./Exit.js"
import * as effect from "./internal/effect.js"
import { version } from "./internal/version.js"
import type { Option } from "./Option.js"
import type { Pipeable } from "./Pipeable.js"
import { hasProperty } from "./Predicate.js"
import type { Scheduler } from "./Scheduler.js"
import type { Scope } from "./Scope.js"
import type * as ServiceMap from "./ServiceMap.js"
import type { AnySpan, Span } from "./Tracer.js"
import type { Covariant } from "./Types.js"
@@ -452,7 +452,7 @@ export const isFiber = (
/**
* Returns the current fiber if called from within a fiber context,
* otherwise returns `None`.
* otherwise returns `undefined`.
*
* @example
* ```ts
@@ -460,8 +460,8 @@ export const isFiber = (
*
* const program = Effect.gen(function* () {
* const current = Fiber.getCurrent()
* if (Option.isSome(current)) {
* console.log(`Current fiber ID: ${current.value.id}`)
* if (current) {
* console.log(`Current fiber ID: ${current.id}`)
* }
* })
* ```
@@ -469,4 +469,13 @@ export const isFiber = (
* @since 2.0.0
* @category accessors
*/
export const getCurrent: () => Option<Fiber<any, any>> = effect.getCurrentFiber
export const getCurrent: () => Fiber<any, any> | undefined = effect.getCurrentFiber
/**
* @since 4.0.0
* @category Scope
*/
export const runIn: {
(scope: Scope): <A, E>(self: Fiber<A, E>) => Fiber<A, E>
<A, E>(self: Fiber<A, E>, scope: Scope): Fiber<A, E>
} = effect.fiberRunIn
+3 -3
View File
@@ -1063,9 +1063,9 @@ export interface SinkOptions extends OpenFileOptions {}
* @category options
*/
export interface StreamOptions {
readonly bytesToRead?: SizeInput
readonly chunkSize?: SizeInput
readonly offset?: SizeInput
readonly bytesToRead?: SizeInput | undefined
readonly chunkSize?: SizeInput | undefined
readonly offset?: SizeInput | undefined
}
/**
+249
View File
@@ -0,0 +1,249 @@
/**
* @since 2.0.0
*/
import * as Effect from "./Effect.js"
import * as Exit from "./Exit.js"
import * as Fiber from "./Fiber.js"
import * as Layer from "./Layer.js"
import { hasProperty } from "./Predicate.js"
import * as Scope from "./Scope.js"
import type * as ServiceMap from "./ServiceMap.js"
import type { Mutable } from "./Types.js"
/**
* @since 3.9.0
* @category symbol
*/
export const TypeId: TypeId = "~effect/ManagedRuntime"
/**
* @since 3.9.0
* @category symbol
*/
export type TypeId = "~effect/ManagedRuntime"
/**
* Checks if the provided argument is a `ManagedRuntime`.
*
* @since 3.9.0
* @category guards
*/
export const isManagedRuntime = (input: unknown): input is ManagedRuntime<unknown, unknown> =>
hasProperty(input, TypeId)
/**
* @since 3.4.0
*/
export declare namespace ManagedRuntime {
/**
* @category type-level
* @since 4.0.0
*/
export type Services<T extends ManagedRuntime<never, any>> = [T] extends [ManagedRuntime<infer R, infer _E>] ? R
: never
/**
* @category type-level
* @since 3.4.0
*/
export type Error<T extends ManagedRuntime<never, any>> = [T] extends [ManagedRuntime<infer _R, infer E>] ? E : never
}
/**
* @since 2.0.0
* @category models
*/
export interface ManagedRuntime<in R, out ER> {
readonly [TypeId]: TypeId
readonly memoMap: Layer.MemoMap
readonly servicesEffect: Effect.Effect<ServiceMap.ServiceMap<R>, ER>
readonly services: () => Promise<ServiceMap.ServiceMap<R>>
// internal
readonly scope: Scope.Scope.Closeable
// internal
cachedServices: ServiceMap.ServiceMap<R> | undefined
/**
* Executes the effect using the provided Scheduler or using the global
* Scheduler if not provided
*/
readonly runFork: <A, E>(
self: Effect.Effect<A, E, R>,
options?: Effect.RunOptions
) => Fiber.Fiber<A, E | ER>
/**
* Executes the effect synchronously returning the exit.
*
* This method is effectful and should only be invoked at the edges of your
* program.
*/
readonly runSyncExit: <A, E>(effect: Effect.Effect<A, E, R>) => Exit.Exit<A, ER | E>
/**
* Executes the effect synchronously throwing in case of errors or async boundaries.
*
* This method is effectful and should only be invoked at the edges of your
* program.
*/
readonly runSync: <A, E>(effect: Effect.Effect<A, E, R>) => A
// /**
// * Executes the effect asynchronously, eventually passing the exit value to
// * the specified callback.
// *
// * This method is effectful and should only be invoked at the edges of your
// * program.
// */
// readonly runCallback: <A, E>(
// effect: Effect.Effect<A, E, R>,
// options?: Runtime.RunCallbackOptions<A, E | ER> | undefined
// ) => Runtime.Cancel<A, E | ER>
/**
* Runs the `Effect`, returning a JavaScript `Promise` that will be resolved
* with the value of the effect once the effect has been executed, or will be
* rejected with the first error or exception throw by the effect.
*
* This method is effectful and should only be used at the edges of your
* program.
*/
readonly runPromise: <A, E>(effect: Effect.Effect<A, E, R>, options?: Effect.RunOptions) => Promise<A>
/**
* Runs the `Effect`, returning a JavaScript `Promise` that will be resolved
* with the `Exit` state of the effect once the effect has been executed.
*
* This method is effectful and should only be used at the edges of your
* program.
*/
readonly runPromiseExit: <A, E>(
effect: Effect.Effect<A, E, R>,
options?: Effect.RunOptions
) => Promise<Exit.Exit<A, ER | E>>
/**
* Dispose of the resources associated with the runtime.
*/
readonly dispose: () => Promise<void>
/**
* Dispose of the resources associated with the runtime.
*/
readonly disposeEffect: Effect.Effect<void, never, never>
}
/**
* Convert a Layer into an ManagedRuntime, that can be used to run Effect's using
* your services.
*
* @since 2.0.0
* @category runtime class
* @example
* ```ts
* import { Console, Effect, Layer, ManagedRuntime, ServiceMap } from "effect"
*
* class Notifications extends ServiceMap.Key<
* Notifications,
* { readonly notify: (message: string) => Effect.Effect<void> }
* >()("Notifications") {
* static layer = Layer.succeed(this, { notify: (message) => Console.log(message) })
* }
*
* async function main() {
* const runtime = ManagedRuntime.make(Notifications.layer)
* await runtime.runPromise(Effect.flatMap(
* Notifications.asEffect(),
* (_) => _.notify("Hello, world!")
* ))
* await runtime.dispose()
* }
*
* main()
* ```
*/
export const make = <R, ER>(
layer: Layer.Layer<R, ER, never>,
options?: {
readonly memoMap?: Layer.MemoMap | undefined
} | undefined
): ManagedRuntime<R, ER> => {
const memoMap = options?.memoMap ?? Layer.unsafeMakeMemoMap()
const scope = Scope.unsafeMake()
let buildFiber: Fiber.Fiber<ServiceMap.ServiceMap<R>, ER> | undefined
const servicesEffect = Effect.withFiber<ServiceMap.ServiceMap<R>, ER>((fiber) => {
if (!buildFiber) {
buildFiber = Fiber.runIn(
Effect.runFork(
Effect.tap(
Layer.buildWithMemoMap(layer, memoMap, scope),
(services) => {
self.cachedServices = services
}
),
{ scheduler: fiber.currentScheduler }
),
scope
)
}
return Effect.flatten(Fiber.await(buildFiber))
})
const self: ManagedRuntime<R, ER> = {
[TypeId]: TypeId,
memoMap,
scope,
servicesEffect,
cachedServices: undefined,
services() {
return self.cachedServices === undefined ?
Effect.runPromise(self.servicesEffect) :
Promise.resolve(self.cachedServices)
},
dispose(): Promise<void> {
return Effect.runPromise(self.disposeEffect)
},
disposeEffect: Effect.suspend(() => {
;(self as Mutable<ManagedRuntime<R, ER>>).servicesEffect = Effect.die("ManagedRuntime disposed")
self.cachedServices = undefined
return Scope.close(self.scope, Exit.void)
}),
runFork<A, E>(effect: Effect.Effect<A, E, R>, options?: Effect.RunOptions): Fiber.Fiber<A, E | ER> {
return self.cachedServices === undefined ?
Effect.runFork(provide(self, effect), options) :
Effect.runForkWith(self.cachedServices)(effect, options)
},
runSyncExit<A, E>(effect: Effect.Effect<A, E, R>): Exit.Exit<A, E | ER> {
return self.cachedServices === undefined ?
Effect.runSyncExit(provide(self, effect)) :
Effect.runSyncExitWith(self.cachedServices)(effect)
},
runSync<A, E>(effect: Effect.Effect<A, E, R>): A {
return self.cachedServices === undefined ?
Effect.runSync(provide(self, effect)) :
Effect.runSyncWith(self.cachedServices)(effect)
},
runPromiseExit<A, E>(effect: Effect.Effect<A, E, R>, options?: Effect.RunOptions): Promise<Exit.Exit<A, E | ER>> {
return self.cachedServices === undefined ?
Effect.runPromiseExit(provide(self, effect), options) :
Effect.runPromiseExitWith(self.cachedServices)(effect, options)
},
runPromise<A, E>(effect: Effect.Effect<A, E, R>, options?: {
readonly signal?: AbortSignal | undefined
}): Promise<A> {
return self.cachedServices === undefined ?
Effect.runPromise(provide(self, effect), options) :
Effect.runPromiseWith(self.cachedServices)(effect, options)
}
}
return self
}
function provide<R, ER, A, E>(
managed: ManagedRuntime<R, ER>,
effect: Effect.Effect<A, E, R>
): Effect.Effect<A, E | ER> {
return Effect.flatMap(
managed.servicesEffect,
(services) => Effect.provideServices(effect, services)
)
}
+604 -4
View File
@@ -1,8 +1,10 @@
/**
* @since 4.0.0
*/
import type { Effect } from "./Effect.js"
import type { BadArgument } from "./PlatformError.js"
import * as Effect from "./Effect.js"
import { identity } from "./Function.js"
import * as Layer from "./Layer.js"
import { BadArgument } from "./PlatformError.js"
import * as ServiceMap from "./ServiceMap.js"
/**
@@ -75,14 +77,14 @@ export interface Path {
readonly dirname: (path: string) => string
readonly extname: (path: string) => string
readonly format: (pathObject: Partial<Path.Parsed>) => string
readonly fromFileUrl: (url: URL) => Effect<string, BadArgument>
readonly fromFileUrl: (url: URL) => Effect.Effect<string, BadArgument>
readonly isAbsolute: (path: string) => boolean
readonly join: (...paths: ReadonlyArray<string>) => string
readonly normalize: (path: string) => string
readonly parse: (path: string) => Path.Parsed
readonly relative: (from: string, to: string) => string
readonly resolve: (...pathSegments: ReadonlyArray<string>) => string
readonly toFileUrl: (path: string) => Effect<URL, BadArgument>
readonly toFileUrl: (path: string) => Effect.Effect<URL, BadArgument>
readonly toNamespacedPath: (path: string) => string
}
@@ -211,3 +213,601 @@ export declare namespace Path {
* ```
*/
export const Path: ServiceMap.Key<Path, Path> = ServiceMap.Key("effect/Path")
/**
* The following functions are adapted from the Node.js source code:
* https://github.com/nodejs/node/blob/main/lib/internal/url.js
*
* The following license applies to these functions:
* - MIT
*/
// Resolves . and .. elements in a path with directory names
function normalizeStringPosix(path: string, allowAboveRoot: boolean) {
let res = ""
let lastSegmentLength = 0
let lastSlash = -1
let dots = 0
let code
for (let i = 0; i <= path.length; ++i) {
if (i < path.length) {
code = path.charCodeAt(i)
} else if (code === 47 /*/*/) {
break
} else {
code = 47 /*/*/
}
if (code === 47 /*/*/) {
if (lastSlash === i - 1 || dots === 1) {
// NOOP
} else if (lastSlash !== i - 1 && dots === 2) {
if (
res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 /*.*/ ||
res.charCodeAt(res.length - 2) !== 46 /*.*/
) {
if (res.length > 2) {
const lastSlashIndex = res.lastIndexOf("/")
if (lastSlashIndex !== res.length - 1) {
if (lastSlashIndex === -1) {
res = ""
lastSegmentLength = 0
} else {
res = res.slice(0, lastSlashIndex)
lastSegmentLength = res.length - 1 - res.lastIndexOf("/")
}
lastSlash = i
dots = 0
continue
}
} else if (res.length === 2 || res.length === 1) {
res = ""
lastSegmentLength = 0
lastSlash = i
dots = 0
continue
}
}
if (allowAboveRoot) {
if (res.length > 0) {
res += "/.."
} else {
res = ".."
}
lastSegmentLength = 2
}
} else {
if (res.length > 0) {
res += "/" + path.slice(lastSlash + 1, i)
} else {
res = path.slice(lastSlash + 1, i)
}
lastSegmentLength = i - lastSlash - 1
}
lastSlash = i
dots = 0
} else if (code === 46 /*.*/ && dots !== -1) {
++dots
} else {
dots = -1
}
}
return res
}
function _format(sep: string, pathObject: Partial<Path.Parsed>) {
const dir = pathObject.dir || pathObject.root
const base = pathObject.base || (pathObject.name || "") + (pathObject.ext || "")
if (!dir) {
return base
}
if (dir === pathObject.root) {
return dir + base
}
return dir + sep + base
}
function fromFileUrl(url: URL): Effect.Effect<string, BadArgument> {
if (url.protocol !== "file:") {
return Effect.fail(
new BadArgument({
module: "Path",
method: "fromFileUrl",
description: "URL must be of scheme file"
})
)
} else if (url.hostname !== "") {
return Effect.fail(
new BadArgument({
module: "Path",
method: "fromFileUrl",
description: "Invalid file URL host"
})
)
}
const pathname = url.pathname
for (let n = 0; n < pathname.length; n++) {
if (pathname[n] === "%") {
const third = pathname.codePointAt(n + 2)! | 0x20
if (pathname[n + 1] === "2" && third === 102) {
return Effect.fail(
new BadArgument({
module: "Path",
method: "fromFileUrl",
description: "must not include encoded / characters"
})
)
}
}
}
return Effect.succeed(decodeURIComponent(pathname))
}
const resolve: Path["resolve"] = function resolve() {
let resolvedPath = ""
let resolvedAbsolute = false
let cwd: string | undefined = undefined
for (let i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
let path: string
if (i >= 0) {
path = arguments[i]
} else {
const process = (globalThis as any).process
if (
cwd === undefined && "process" in globalThis &&
typeof process === "object" &&
process !== null &&
typeof process.cwd === "function"
) {
cwd = process.cwd()
}
path = cwd!
}
// Skip empty entries
if (path.length === 0) {
continue
}
resolvedPath = path + "/" + resolvedPath
resolvedAbsolute = path.charCodeAt(0) === 47 /*/*/
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute)
if (resolvedAbsolute) {
if (resolvedPath.length > 0) {
return "/" + resolvedPath
} else {
return "/"
}
} else if (resolvedPath.length > 0) {
return resolvedPath
} else {
return "."
}
}
const CHAR_FORWARD_SLASH = 47
function toFileUrl(filepath: string) {
const outURL = new URL("file://")
let resolved = resolve(filepath)
// path.resolve strips trailing slashes so we must add them back
const filePathLast = filepath.charCodeAt(filepath.length - 1)
if (
(filePathLast === CHAR_FORWARD_SLASH) &&
resolved[resolved.length - 1] !== "/"
) {
resolved += "/"
}
outURL.pathname = encodePathChars(resolved)
return Effect.succeed(outURL)
}
const percentRegEx = /%/g
const backslashRegEx = /\\/g
const newlineRegEx = /\n/g
const carriageReturnRegEx = /\r/g
const tabRegEx = /\t/g
function encodePathChars(filepath: string) {
if (filepath.includes("%")) {
filepath = filepath.replace(percentRegEx, "%25")
}
if (filepath.includes("\\")) {
filepath = filepath.replace(backslashRegEx, "%5C")
}
if (filepath.includes("\n")) {
filepath = filepath.replace(newlineRegEx, "%0A")
}
if (filepath.includes("\r")) {
filepath = filepath.replace(carriageReturnRegEx, "%0D")
}
if (filepath.includes("\t")) {
filepath = filepath.replace(tabRegEx, "%09")
}
return filepath
}
const posixImpl = Path.of({
[TypeId]: TypeId,
resolve,
normalize(path) {
if (path.length === 0) return "."
const isAbsolute = path.charCodeAt(0) === 47 /*/*/
const trailingSeparator = path.charCodeAt(path.length - 1) === 47 /*/*/
// Normalize the path
path = normalizeStringPosix(path, !isAbsolute)
if (path.length === 0 && !isAbsolute) path = "."
if (path.length > 0 && trailingSeparator) path += "/"
if (isAbsolute) return "/" + path
return path
},
isAbsolute(path) {
return path.length > 0 && path.charCodeAt(0) === 47 /*/*/
},
join() {
if (arguments.length === 0) {
return "."
}
let joined
for (let i = 0; i < arguments.length; ++i) {
const arg = arguments[i]
if (arg.length > 0) {
if (joined === undefined) {
joined = arg
} else {
joined += "/" + arg
}
}
}
if (joined === undefined) {
return "."
}
return posixImpl.normalize(joined)
},
relative(from, to) {
if (from === to) return ""
from = posixImpl.resolve(from)
to = posixImpl.resolve(to)
if (from === to) return ""
// Trim any leading backslashes
let fromStart = 1
for (; fromStart < from.length; ++fromStart) {
if (from.charCodeAt(fromStart) !== 47 /*/*/) {
break
}
}
const fromEnd = from.length
const fromLen = fromEnd - fromStart
// Trim any leading backslashes
let toStart = 1
for (; toStart < to.length; ++toStart) {
if (to.charCodeAt(toStart) !== 47 /*/*/) {
break
}
}
const toEnd = to.length
const toLen = toEnd - toStart
// Compare paths to find the longest common path from root
const length = fromLen < toLen ? fromLen : toLen
let lastCommonSep = -1
let i = 0
for (; i <= length; ++i) {
if (i === length) {
if (toLen > length) {
if (to.charCodeAt(toStart + i) === 47 /*/*/) {
// We get here if `from` is the exact base path for `to`.
// For example: from='/foo/bar'; to='/foo/bar/baz'
return to.slice(toStart + i + 1)
} else if (i === 0) {
// We get here if `from` is the root
// For example: from='/'; to='/foo'
return to.slice(toStart + i)
}
} else if (fromLen > length) {
if (from.charCodeAt(fromStart + i) === 47 /*/*/) {
// We get here if `to` is the exact base path for `from`.
// For example: from='/foo/bar/baz'; to='/foo/bar'
lastCommonSep = i
} else if (i === 0) {
// We get here if `to` is the root.
// For example: from='/foo'; to='/'
lastCommonSep = 0
}
}
break
}
const fromCode = from.charCodeAt(fromStart + i)
const toCode = to.charCodeAt(toStart + i)
if (fromCode !== toCode) {
break
} else if (fromCode === 47 /*/*/) {
lastCommonSep = i
}
}
let out = ""
// Generate the relative path based on the path difference between `to`
// and `from`
for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
if (i === fromEnd || from.charCodeAt(i) === 47 /*/*/) {
if (out.length === 0) {
out += ".."
} else {
out += "/.."
}
}
}
// Lastly, append the rest of the destination (`to`) path that comes after
// the common path parts
if (out.length > 0) {
return out + to.slice(toStart + lastCommonSep)
} else {
toStart += lastCommonSep
if (to.charCodeAt(toStart) === 47 /*/*/) {
++toStart
}
return to.slice(toStart)
}
},
dirname(path) {
if (path.length === 0) return "."
let code = path.charCodeAt(0)
const hasRoot = code === 47 /*/*/
let end = -1
let matchedSlash = true
for (let i = path.length - 1; i >= 1; --i) {
code = path.charCodeAt(i)
if (code === 47 /*/*/) {
if (!matchedSlash) {
end = i
break
}
} else {
// We saw the first non-path separator
matchedSlash = false
}
}
if (end === -1) return hasRoot ? "/" : "."
if (hasRoot && end === 1) return "//"
return path.slice(0, end)
},
basename(path, ext) {
let start = 0
let end = -1
let matchedSlash = true
let i
if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {
if (ext.length === path.length && ext === path) return ""
let extIdx = ext.length - 1
let firstNonSlashEnd = -1
for (i = path.length - 1; i >= 0; --i) {
const code = path.charCodeAt(i)
if (code === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
start = i + 1
break
}
} else {
if (firstNonSlashEnd === -1) {
// We saw the first non-path separator, remember this index in case
// we need it if the extension ends up not matching
matchedSlash = false
firstNonSlashEnd = i + 1
}
if (extIdx >= 0) {
// Try to match the explicit extension
if (code === ext.charCodeAt(extIdx)) {
if (--extIdx === -1) {
// We matched the extension, so mark this as the end of our path
// component
end = i
}
} else {
// Extension does not match, so our result is the entire path
// component
extIdx = -1
end = firstNonSlashEnd
}
}
}
}
if (start === end) end = firstNonSlashEnd
else if (end === -1) end = path.length
return path.slice(start, end)
} else {
for (i = path.length - 1; i >= 0; --i) {
if (path.charCodeAt(i) === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
start = i + 1
break
}
} else if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// path component
matchedSlash = false
end = i + 1
}
}
if (end === -1) return ""
return path.slice(start, end)
}
},
extname(path) {
let startDot = -1
let startPart = 0
let end = -1
let matchedSlash = true
// Track the state of characters (if any) we see before our first dot and
// after any path separator we find
let preDotState = 0
for (let i = path.length - 1; i >= 0; --i) {
const code = path.charCodeAt(i)
if (code === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
startPart = i + 1
break
}
continue
}
if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// extension
matchedSlash = false
end = i + 1
}
if (code === 46 /*.*/) {
// If this is our first dot, mark it as the start of our extension
if (startDot === -1) {
startDot = i
} else if (preDotState !== 1) {
preDotState = 1
}
} else if (startDot !== -1) {
// We saw a non-dot and non-path separator before our dot, so we should
// have a good chance at having a non-empty extension
preDotState = -1
}
}
if (
startDot === -1 || end === -1 ||
// We saw a non-dot character immediately before the dot
preDotState === 0 ||
// The (right-most) trimmed path component is exactly '..'
preDotState === 1 && startDot === end - 1 && startDot === startPart + 1
) {
return ""
}
return path.slice(startDot, end)
},
format: function format(pathObject) {
if (pathObject === null || typeof pathObject !== "object") {
throw new TypeError("The \"pathObject\" argument must be of type Object. Received type " + typeof pathObject)
}
return _format("/", pathObject)
},
parse(path) {
const ret = { root: "", dir: "", base: "", ext: "", name: "" }
if (path.length === 0) return ret
let code = path.charCodeAt(0)
const isAbsolute = code === 47 /*/*/
let start
if (isAbsolute) {
ret.root = "/"
start = 1
} else {
start = 0
}
let startDot = -1
let startPart = 0
let end = -1
let matchedSlash = true
let i = path.length - 1
// Track the state of characters (if any) we see before our first dot and
// after any path separator we find
let preDotState = 0
// Get non-dir info
for (; i >= start; --i) {
code = path.charCodeAt(i)
if (code === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
startPart = i + 1
break
}
continue
}
if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// extension
matchedSlash = false
end = i + 1
}
if (code === 46 /*.*/) {
// If this is our first dot, mark it as the start of our extension
if (startDot === -1) startDot = i
else if (preDotState !== 1) preDotState = 1
} else if (startDot !== -1) {
// We saw a non-dot and non-path separator before our dot, so we should
// have a good chance at having a non-empty extension
preDotState = -1
}
}
if (
startDot === -1 || end === -1 ||
// We saw a non-dot character immediately before the dot
preDotState === 0 ||
// The (right-most) trimmed path component is exactly '..'
preDotState === 1 && startDot === end - 1 && startDot === startPart + 1
) {
if (end !== -1) {
if (startPart === 0 && isAbsolute) ret.base = ret.name = path.slice(1, end)
else ret.base = ret.name = path.slice(startPart, end)
}
} else {
if (startPart === 0 && isAbsolute) {
ret.name = path.slice(1, startDot)
ret.base = path.slice(1, end)
} else {
ret.name = path.slice(startPart, startDot)
ret.base = path.slice(startPart, end)
}
ret.ext = path.slice(startDot, end)
}
if (startPart > 0) ret.dir = path.slice(0, startPart - 1)
else if (isAbsolute) ret.dir = "/"
return ret
},
sep: "/",
fromFileUrl,
toFileUrl,
toNamespacedPath: identity
})
/**
* @since 4.0.0
* @category Layers
*/
export const layer: Layer.Layer<Path> = Layer.succeed(Path, posixImpl)
+24 -1
View File
@@ -80,7 +80,7 @@ export type TypeId = "~effect/Scope"
export interface Scope {
readonly [TypeId]: TypeId
readonly strategy: "sequential" | "parallel"
state: Scope.State.Open | Scope.State.Closed
state: Scope.State.Open | Scope.State.Closed | Scope.State.Empty
}
/**
@@ -141,6 +141,29 @@ export declare namespace Scope {
* @category models
*/
export namespace State {
/**
* Represents an open scope state where finalizers can be added and
* the scope is still accepting new resources.
*
* @example
* ```ts
* import { Scope, Effect, Exit } from "effect"
*
* const scope = Scope.unsafeMake()
*
* // When scope is open, you can check its state
* if (scope.state._tag === "Open") {
* console.log("Scope is open and accepting finalizers")
* console.log(scope.state.finalizers.size) // Number of registered finalizers
* }
* ```
*
* @since 2.0.0
* @category models
*/
export type Empty = {
readonly _tag: "Empty"
}
/**
* Represents an open scope state where finalizers can be added and
* the scope is still accepting new resources.
+61 -9
View File
@@ -299,6 +299,16 @@ export const fromChannel = <Arr extends Arr.NonEmptyReadonlyArray<any>, E, R>(
return self
}
/**
* Either emits the success value of this effect or terminates the stream
* with the failure value of this effect.
*
* @since 2.0.0
* @category constructors
*/
export const fromEffect = <A, E, R>(effect: Effect.Effect<A, E, R>): Stream<A, E, R> =>
fromChannel(Channel.fromEffect(Effect.map(effect, Arr.of)))
/**
* Creates a stream from a pull effect.
*
@@ -1410,11 +1420,7 @@ const catch_: {
} = dual(2, <A, E, R, A2, E2, R2>(
self: Stream<A, E, R>,
f: (error: E) => Stream<A2, E2, R2>
): Stream<A | A2, E2, R | R2> =>
self.channel.pipe(
Channel.catch((error) => f(error).channel),
fromChannel
))
): Stream<A | A2, E2, R | R2> => fromChannel(Channel.catch(self.channel, (error) => f(error).channel)))
export {
/**
@@ -1424,6 +1430,20 @@ export {
catch_ as catch
}
/**
* Transforms the errors emitted by this stream using `f`.
*
* @since 2.0.0
* @category Error handling
*/
export const mapError: {
<E, E2>(f: (error: E) => E2): <A, R>(self: Stream<A, E, R>) => Stream<A, E2, R>
<A, E, R, E2>(self: Stream<A, E, R>, f: (error: E) => E2): Stream<A, E2, R>
} = dual(2, <A, E, R, E2>(
self: Stream<A, E, R>,
f: (error: E) => E2
): Stream<A, E2, R> => fromChannel(Channel.mapError(self.channel, f)))
/**
* Conditionally handles stream failures based on a predicate applied to the Cause.
*
@@ -1994,15 +2014,47 @@ export const encodeText = <E, R>(self: Stream<string, E, R>): Stream<Uint8Array,
* @since 4.0.0
* @category utils
*/
export const onExit = dual<
export const onExit: {
<E, R2>(
finalizer: (exit: Exit.Exit<unknown, E>) => Effect.Effect<unknown, never, R2>
) => <A, R>(self: Stream<A, E, R>) => Stream<A, E, R | R2>,
): <A, R>(self: Stream<A, E, R>) => Stream<A, E, R | R2>
<A, E, R, R2>(
self: Stream<A, E, R>,
finalizer: (exit: Exit.Exit<unknown, E>) => Effect.Effect<unknown, never, R2>
) => Stream<A, E, R | R2>
>(2, (self, finalizer) => fromChannel(Channel.onExit(self.channel, finalizer)))
): Stream<A, E, R | R2>
} = dual(2, <A, E, R, R2>(
self: Stream<A, E, R>,
finalizer: (exit: Exit.Exit<unknown, E>) => Effect.Effect<unknown, never, R2>
): Stream<A, E, R | R2> => fromChannel(Channel.onExit(self.channel, finalizer)))
/**
* @since 4.0.0
* @category utils
*/
export const ensuring: {
<R2>(finalizer: Effect.Effect<unknown, never, R2>): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E, R | R2>
<A, E, R, R2>(self: Stream<A, E, R>, finalizer: Effect.Effect<unknown, never, R2>): Stream<A, E, R | R2>
} = dual(
2,
<A, E, R, R2>(self: Stream<A, E, R>, finalizer: Effect.Effect<unknown, never, R2>): Stream<A, E, R | R2> =>
fromChannel(Channel.ensuring(self.channel, finalizer))
)
/**
* Provides the stream with some of its required services, which eliminates its
* dependency on `R`.
*
* @since 4.0.0
* @category context
*/
export const provideServices: {
<R2>(services: ServiceMap.ServiceMap<R2>): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E, Exclude<R, R2>>
<A, E, R, R2>(self: Stream<A, E, R>, services: ServiceMap.ServiceMap<R2>): Stream<A, E, Exclude<R, R2>>
} = dual(
2,
<A, E, R, R2>(self: Stream<A, E, R>, services: ServiceMap.ServiceMap<R2>): Stream<A, E, Exclude<R, R2>> =>
fromChannel(Channel.provideServices(self.channel, services))
)
/**
* Runs the sink on the stream to produce either the sink's result or an error.
+5
View File
@@ -1239,6 +1239,11 @@ export * as Logger from "./Logger.js"
*/
export * as LogLevel from "./LogLevel.js"
/**
* @since 2.0.0
*/
export * as ManagedRuntime from "./ManagedRuntime.js"
/**
* The `effect/match` module provides a type-safe pattern matching system for
* TypeScript. Inspired by functional programming, it simplifies conditional
+3
View File
@@ -267,6 +267,9 @@ export const causeFromFailures = <E>(
failures: ReadonlyArray<Cause.Failure<E>>
): Cause.Cause<E> => new CauseImpl(failures)
/** @internal */
export const causeEmpty: Cause.Cause<never> = new CauseImpl([])
/** @internal */
export const causeFail = <E>(error: E): Cause.Cause<E> => new CauseImpl([new Fail(error)])
+88 -38
View File
@@ -41,7 +41,7 @@ import type { Primitive } from "./core.js"
import {
args,
causeAnnotate,
causeDie,
causeEmpty,
causeFail,
causeFromFailures,
CauseImpl,
@@ -49,6 +49,7 @@ import {
contAll,
contE,
CurrentSpanKey,
Die,
evaluate,
exitDie,
exitFail,
@@ -416,11 +417,7 @@ const fiberIdStore = { id: 0 }
const currentFiberUri = "effect/Fiber/currentFiber"
/** @internal */
export const getCurrentFiberOrUndefined = (): Fiber.Fiber<any, any> | undefined => (globalThis as any)[currentFiberUri]
/** @internal */
export const getCurrentFiber = (): Option.Option<Fiber.Fiber<any, any>> =>
Option.fromNullable((globalThis as any)[currentFiberUri])
export const getCurrentFiber = (): Fiber.Fiber<any, any> | undefined => (globalThis as any)[currentFiberUri]
const keepAlive = (() => {
let count = 0
@@ -1081,7 +1078,10 @@ export const as: {
<A, E, R, B>(
self: Effect.Effect<A, E, R>,
value: B
): Effect.Effect<B, E, R> => map(self, (_) => value)
): Effect.Effect<B, E, R> => {
const b = succeed(value)
return flatMap(self, (_) => b)
}
)
/** @internal */
@@ -2098,7 +2098,7 @@ export const forever: {
): Effect.Effect<never, E, R> =>
whileLoop({
while: constTrue,
body: constant(options?.autoYield ? flatMap(self, () => yieldNow) : self),
body: constant(options?.autoYield ? flatMap(self, (_) => yieldNow) : self),
step: constVoid
}) as any)
@@ -2811,10 +2811,16 @@ export const scopeTag: ServiceMap.Key<Scope.Scope, Scope.Scope> = ServiceMap.Key
const ScopeProto = {
[ScopeTypeId]: ScopeTypeId,
state: { _tag: "Empty" },
close: fnUntraced(function*(this: Scope.Scope, exit_: Exit.Exit<any, any>) {
if (this.state._tag === "Closed") return
const closed: Scope.Scope.State.Closed = { _tag: "Closed", exit: exit_ }
if (this.state._tag === "Empty") {
this.state = closed
return
}
const { finalizers } = this.state
this.state = { _tag: "Closed", exit: exit_ }
this.state = closed
if (finalizers.size === 0) {
return
} else if (finalizers.size === 1) {
@@ -2827,7 +2833,7 @@ const ScopeProto = {
if (this.strategy === "sequential") {
exits.push(yield* exit(finalizer(exit_)))
} else {
fibers.push(unsafeFork(getCurrentFiberOrUndefined() as any, finalizer(exit_), true, true))
fibers.push(unsafeFork(getCurrentFiber() as any, finalizer(exit_), true, true))
}
}
if (fibers.length > 0) {
@@ -2849,7 +2855,7 @@ export const scopeUnsafeFork = (scope: Scope.Scope, finalizerStrategy?: "sequent
return newScope
}
const key = {}
scope.state.finalizers.set(key, (exit) => newScope.close(exit))
scopeUnsafeAddFinalizer(scope, key, (exit) => newScope.close(exit))
scopeUnsafeAddFinalizer(newScope, key, (_) => sync(() => scopeUnsafeRemoveFinalizer(scope, key)))
return newScope
}
@@ -2860,11 +2866,11 @@ export const scopeAddFinalizerExit = (
finalizer: (exit: Exit.Exit<any, any>) => Effect.Effect<unknown>
): Effect.Effect<void> => {
return suspend(() => {
if (scope.state._tag === "Open") {
scope.state.finalizers.set({}, finalizer)
return void_
if (scope.state._tag === "Closed") {
return finalizer(scope.state.exit)
}
return finalizer(scope.state.exit)
scopeUnsafeAddFinalizer(scope, {}, finalizer)
return void_
})
}
@@ -2880,7 +2886,9 @@ export const scopeUnsafeAddFinalizer = (
key: {},
finalizer: (exit: Exit.Exit<any, any>) => Effect.Effect<unknown>
): void => {
if (scope.state._tag === "Open") {
if (scope.state._tag === "Empty") {
scope.state = { _tag: "Open", finalizers: new Map([[key, finalizer]]) }
} else if (scope.state._tag === "Open") {
scope.state.finalizers.set(key, finalizer)
}
}
@@ -2899,7 +2907,6 @@ export const scopeUnsafeRemoveFinalizer = (
export const scopeUnsafeMake = (finalizerStrategy: "sequential" | "parallel" = "sequential"): Scope.Scope.Closeable => {
const self = Object.create(ScopeProto)
self.strategy = finalizerStrategy
self.state = { _tag: "Open", finalizers: new Map() }
return self
}
@@ -2960,18 +2967,39 @@ export const onExit: {
self: Effect.Effect<A, E, R>,
f: (exit: Exit.Exit<A, E>) => Effect.Effect<void, XE, XR>
): Effect.Effect<A, E | XE, R | XR>
} = dual(
2,
<A, E, R, XE, XR>(
self: Effect.Effect<A, E, R>,
f: (exit: Exit.Exit<A, E>) => Effect.Effect<void, XE, XR>
): Effect.Effect<A, E | XE, R | XR> => uninterruptibleMask((restore) => onExitInterruptible(restore(self), f))
)
/** @internal */
export const onExitInterruptible: {
<A, E, XE, XR>(
f: (exit: Exit.Exit<A, E>) => Effect.Effect<void, XE, XR>
): <R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E | XE, R | XR>
<A, E, R, XE, XR>(
self: Effect.Effect<A, E, R>,
f: (exit: Exit.Exit<A, E>) => Effect.Effect<void, XE, XR>
): Effect.Effect<A, E | XE, R | XR>
} = dual(
2,
<A, E, R, XE, XR>(
self: Effect.Effect<A, E, R>,
f: (exit: Exit.Exit<A, E>) => Effect.Effect<void, XE, XR>
): Effect.Effect<A, E | XE, R | XR> =>
uninterruptibleMask((restore) =>
matchCauseEffect(restore(self), {
onFailure: (cause) => flatMap(internalCall(() => f(exitFailCause(cause))), () => failCause(cause)),
onSuccess: (a) => flatMap(internalCall(() => f(exitSucceed(a))), () => succeed(a))
})
)
matchCauseEffect(self, {
onFailure(cause) {
const exit = exitFailCause(cause)
return flatMap(f(exit), (_) => exit)
},
onSuccess(a) {
const exit = exitSucceed(a)
return flatMap(f(exit), (_) => exit)
}
})
)
/** @internal */
@@ -3070,31 +3098,30 @@ export const acquireUseRelease = <Resource, E, R, A, E2, R2, E3, R3>(
export const cachedInvalidateWithTTL: {
(timeToLive: Duration.DurationInput): <A, E, R>(
self: Effect.Effect<A, E, R>
) => Effect.Effect<[Effect.Effect<A, E>, Effect.Effect<void>], never, R>
) => Effect.Effect<[Effect.Effect<A, E, R>, Effect.Effect<void>]>
<A, E, R>(
self: Effect.Effect<A, E, R>,
timeToLive: Duration.DurationInput
): Effect.Effect<[Effect.Effect<A, E>, Effect.Effect<void>], never, R>
): Effect.Effect<[Effect.Effect<A, E, R>, Effect.Effect<void>]>
} = dual(2, <A, E, R>(
self: Effect.Effect<A, E, R>,
ttl: Duration.DurationInput
): Effect.Effect<[Effect.Effect<A, E>, Effect.Effect<void>], never, R> =>
withFiber((fiber) => {
const services = fiber.services as ServiceMap.ServiceMap<R>
): Effect.Effect<[Effect.Effect<A, E, R>, Effect.Effect<void>]> =>
sync(() => {
const ttlMillis = Duration.toMillis(ttl)
const latch = unsafeMakeLatch(false)
let expiresAt = 0
let running = false
let exit: Exit.Exit<A, E> | undefined
const wait = flatMap(latch.await, () => exit!)
return succeed([
return [
withFiber((fiber) => {
const now = fiber.getRef(ClockRef).unsafeCurrentTimeMillis()
if (running || now < expiresAt) return exit ?? wait
running = true
latch.unsafeClose()
exit = undefined
return onExit(provideServices(self, services), (exit_) => {
return onExit(self, (exit_) => {
running = false
expiresAt = now + ttlMillis
exit = exit_
@@ -3106,28 +3133,28 @@ export const cachedInvalidateWithTTL: {
latch.unsafeClose()
exit = undefined
})
])
]
}))
/** @internal */
export const cachedWithTTL: {
(
timeToLive: Duration.DurationInput
): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<Effect.Effect<A, E>, never, R>
): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<Effect.Effect<A, E, R>>
<A, E, R>(
self: Effect.Effect<A, E, R>,
timeToLive: Duration.DurationInput
): Effect.Effect<Effect.Effect<A, E>, never, R>
): Effect.Effect<Effect.Effect<A, E, R>>
} = dual(
2,
<A, E, R>(
self: Effect.Effect<A, E, R>,
timeToLive: Duration.DurationInput
): Effect.Effect<Effect.Effect<A, E>, never, R> => map(cachedInvalidateWithTTL(self, timeToLive), (tuple) => tuple[0])
): Effect.Effect<Effect.Effect<A, E, R>> => map(cachedInvalidateWithTTL(self, timeToLive), (tuple) => tuple[0])
)
/** @internal */
export const cached = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<Effect.Effect<A, E>, never, R> =>
export const cached = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<Effect.Effect<A, E, R>> =>
cachedWithTTL(self, Duration.infinity)
// ----------------------------------------------------------------------------
@@ -3382,7 +3409,7 @@ export const forEach: {
} catch (err) {
failed = true
length = index
failures.push(causeDie(err).failures[0])
failures.push(new Die(err))
fibers.forEach((fiber) => fiber.unsafeInterrupt(parent.id, span))
}
}
@@ -3643,7 +3670,7 @@ export const forkIn: {
withFiber((parent) => {
const fiber = unsafeFork(parent, self, options?.startImmediately, true, options?.uninterruptible)
if (!(fiber as FiberImpl<any, any>)._exit) {
if (scope.state._tag === "Open") {
if (scope.state._tag !== "Closed") {
const key = {}
const finalizer = () => withFiberId((interruptor) => interruptor === fiber.id ? void_ : fiberInterrupt(fiber))
scopeUnsafeAddFinalizer(scope, key, finalizer)
@@ -3693,6 +3720,8 @@ export const runForkWith = <R>(services: ServiceMap.ServiceMap<R>) =>
serviceMap.set(Scheduler.Scheduler.key, options?.scheduler ?? new Scheduler.MixedScheduler())
const fiber = makeFiber<A, E>(ServiceMap.unsafeMake(serviceMap))
fiber.evaluate(effect as any)
if (fiber._exit) return fiber
if (options?.signal) {
if (options.signal.aborted) {
fiber.unsafeInterrupt()
@@ -3705,6 +3734,27 @@ export const runForkWith = <R>(services: ServiceMap.ServiceMap<R>) =>
return fiber
}
/** @internal */
export const fiberRunIn: {
(scope: Scope.Scope): <A, E>(self: Fiber.Fiber<A, E>) => Fiber.Fiber<A, E>
<A, E>(
self: Fiber.Fiber<A, E>,
scope: Scope.Scope
): Fiber.Fiber<A, E>
} = dual(2, <A, E>(
self: FiberImpl<A, E>,
scope: Scope.Scope
): Fiber.Fiber<A, E> => {
if (scope.state._tag === "Closed") {
self.unsafeInterrupt(self.id)
return self
}
const key = {}
scopeUnsafeAddFinalizer(scope, {}, () => fiberInterrupt(self))
self.addObserver(() => scopeUnsafeRemoveFinalizer(scope, key))
return self
})
/** @internal */
export const runFork: <A, E>(
effect: Effect.Effect<A, E, never>,
@@ -4500,7 +4550,7 @@ export const logWithLevel = (level?: LogLevel.LogLevel) =>
}
}
if (cause === undefined) {
cause = causeFromFailures([])
cause = causeEmpty
}
return withFiber((fiber) => {
const logLevel = level ?? fiber.getRef(CurrentLogLevel)
+1 -1
View File
@@ -41,7 +41,7 @@ export const request: {
Request.Error<A>,
Request.Services<A>
>((resume) => {
const entry = addEntry(resolver, self, resume, effect.getCurrentFiberOrUndefined()!)
const entry = addEntry(resolver, self, resume, effect.getCurrentFiber()!)
return maybeRemoveEntry(resolver, entry)
})
return isEffect(resolver) ? effect.flatMap(resolver, withResolver) : withResolver(resolver)
+97
View File
@@ -0,0 +1,97 @@
/**
* @since 4.0.0
*/
import * as Effect from "../../Effect.js"
import type * as FileSystem from "../../FileSystem.js"
import * as Layer from "../../Layer.js"
import * as ServiceMap from "../../ServiceMap.js"
import type * as Body from "./HttpBody.js"
/**
* @since 4.0.0
* @category models
*/
export type Etag = Weak | Strong
/**
* @since 4.0.0
* @category models
*/
export interface Weak {
readonly _tag: "Weak"
readonly value: string
}
/**
* @since 4.0.0
* @category models
*/
export interface Strong {
readonly _tag: "Strong"
readonly value: string
}
/**
* @since 4.0.0
* @category convertions
*/
export const toString = (self: Etag): string => {
switch (self._tag) {
case "Weak":
return `W/"${self.value}"`
case "Strong":
return `"${self.value}"`
}
}
/**
* @since 4.0.0
* @category models
*/
export class Generator extends ServiceMap.Key<Generator, {
readonly fromFileInfo: (info: FileSystem.File.Info) => Effect.Effect<Etag>
readonly fromFileWeb: (file: Body.HttpBody.FileLike) => Effect.Effect<Etag>
}>()("effect/http/Etag/Generator") {}
const fromFileInfo = (info: FileSystem.File.Info) => {
const mtime = info.mtime._tag === "Some"
? info.mtime.value.getTime().toString(16)
: "0"
return `${info.size.toString(16)}-${mtime}`
}
const fromFileWeb = (file: Body.HttpBody.FileLike) => {
return `${file.size.toString(16)}-${file.lastModified.toString(16)}`
}
/**
* @since 4.0.0
* @category Layers
*/
export const layer: Layer.Layer<Generator> = Layer.succeed(
Generator,
Generator.of({
fromFileInfo(info) {
return Effect.sync(() => ({ _tag: "Strong", value: fromFileInfo(info) }))
},
fromFileWeb(file) {
return Effect.sync(() => ({ _tag: "Strong", value: fromFileWeb(file) }))
}
})
)
/**
* @since 4.0.0
* @category Layers
*/
export const layerWeak: Layer.Layer<Generator> = Layer.succeed(
Generator,
Generator.of({
fromFileInfo(info) {
return Effect.sync(() => ({ _tag: "Weak", value: fromFileInfo(info) }))
},
fromFileWeb(file) {
return Effect.sync(() => ({ _tag: "Weak", value: fromFileWeb(file) }))
}
})
)
@@ -0,0 +1,9 @@
/**
* @since 4.0.0
*/
/**
* @since 4.0.0
* @category re-exports
*/
export * from "find-my-way-ts"
@@ -20,6 +20,7 @@ import type { Mutable } from "../../Types.js"
* @since 4.0.0
* @category type ids
*/
// note: this is a symbol to allow direct access of keys without conflicts
export const TypeId: unique symbol = Symbol.for("effect/http/Headers")
/**
@@ -0,0 +1,267 @@
/**
* @since 4.0.0
*/
import * as Effect from "../../Effect.js"
import * as Exit from "../../Exit.js"
import * as Fiber from "../../Fiber.js"
import { dual } from "../../Function.js"
import * as Layer from "../../Layer.js"
import * as Option from "../../Option.js"
import * as Scope from "../../Scope.js"
import * as ServiceMap from "../../ServiceMap.js"
import * as Stream from "../../Stream.js"
import * as HttpBody from "./HttpBody.js"
import { type HttpMiddleware, tracer } from "./HttpMiddleware.js"
import type { HttpServerError } from "./HttpServerError.js"
import { causeResponse, clientAbortFiberId } from "./HttpServerError.js"
import { HttpServerRequest } from "./HttpServerRequest.js"
import * as Request from "./HttpServerRequest.js"
import type { HttpServerResponse } from "./HttpServerResponse.js"
import * as Response from "./HttpServerResponse.js"
/**
* @since 4.0.0
* @category combinators
*/
export const toHandled = <E, R, EH, RH>(
self: Effect.Effect<HttpServerResponse, E, R>,
handleResponse: (
request: HttpServerRequest,
response: HttpServerResponse
) => Effect.Effect<unknown, EH, RH>,
middleware?: HttpMiddleware | undefined
): Effect.Effect<void, never, Exclude<R | RH | HttpServerRequest, Scope.Scope>> => {
const responded = Effect.flatMap(self, (response) => {
const fiber = Fiber.getCurrent()!
const request = ServiceMap.unsafeGet(fiber.services, HttpServerRequest)
const handler = fiber.getRef(PreResponseHandlers)
if (handler._tag === "None") {
;(request as any)[handledSymbol] = true
return Effect.as(handleResponse(request, response), response)
}
return Effect.tap(handler.value(request, response), (response) => {
;(request as any)[handledSymbol] = true
return handleResponse(request, response)
})
})
const withErrorHandling = Effect.catchCause(
responded,
(cause) =>
Effect.flatMap(causeResponse(cause), ([response, cause]) => {
const fiber = Fiber.getCurrent()!
const request = ServiceMap.unsafeGet(fiber.services, HttpServerRequest)
const handler = fiber.getRef(PreResponseHandlers)
if (handler._tag === "None") {
;(request as any)[handledSymbol] = true
return Effect.flatMap(handleResponse(request, response), () => Effect.failCause(cause))
}
return Effect.flatMap(
Effect.flatMap(handler.value(request, response), (response) => {
;(request as any)[handledSymbol] = true
return handleResponse(request, response)
}),
() => Effect.failCause(cause)
)
})
)
const withMiddleware: Effect.Effect<
unknown,
E | EH | HttpServerError,
HttpServerRequest | R | RH
> = middleware === undefined ?
tracer(withErrorHandling) :
Effect.matchCauseEffect(middleware(tracer(withErrorHandling)), {
onFailure: (cause): Effect.Effect<void, EH, RH> => {
const fiber = Fiber.getCurrent()!
const request = ServiceMap.unsafeGet(fiber.services, HttpServerRequest)
if (handledSymbol in request) {
return Effect.void
}
return Effect.matchCauseEffect(causeResponse(cause), {
onFailure: (_cause) => handleResponse(request, Response.empty({ status: 500 })),
onSuccess: ([response]) => handleResponse(request, response)
})
},
onSuccess: (response): Effect.Effect<void, EH, RH> => {
const fiber = Fiber.getCurrent()!
const request = ServiceMap.unsafeGet(fiber.services, Request.HttpServerRequest)
return handledSymbol in request ? Effect.void : handleResponse(request, response)
}
})
return Effect.uninterruptible(scoped(withMiddleware)) as any
}
const handledSymbol = Symbol.for("effect/http/HttpEffect/handled")
/**
* If you want to finalize the http request scope elsewhere, you can use this
* function to eject from the default scope closure.
*
* @since 4.0.0
* @category Scope
*/
export const scopeDisableClose = (scope: Scope.Scope): void => {
ejectedScopes.add(scope)
}
/**
* @since 4.0.0
* @category Scope
*/
export const scopeTransferToStream = (
response: HttpServerResponse
): HttpServerResponse => {
if (response.body._tag !== "Stream") {
return response
}
const fiber = Fiber.getCurrent()!
const scope = ServiceMap.unsafeGet(fiber.services, Scope.Scope) as Scope.Scope.Closeable
scopeDisableClose(scope)
return Response.setBody(
response,
HttpBody.stream(
Stream.onExit(response.body.stream, (exit) => Scope.close(scope, exit)),
response.body.contentType,
response.body.contentLength
)
)
}
const ejectedScopes = new WeakSet<Scope.Scope>()
const scoped = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
Effect.flatMap(Scope.make(), (scope) =>
Effect.onExitInterruptible(Scope.provide(effect, scope), (exit) => {
if (ejectedScopes.has(scope)) {
return Effect.void
}
return Scope.close(scope, exit)
}))
/**
* @since 4.0.0
* @category Pre-response handlers
*/
export type PreResponseHandler = (
request: HttpServerRequest,
response: HttpServerResponse
) => Effect.Effect<HttpServerResponse, HttpServerError>
/**
* @since 4.0.0
* @category Pre-response handlers
*/
export const PreResponseHandlers = ServiceMap.Reference<Option.Option<PreResponseHandler>>(
"effect/http/HttpEffect/PreResponseHandlers",
{ defaultValue: Option.none }
)
/**
* @since 4.0.0
* @category fiber refs
*/
export const appendPreResponseHandler = (handler: PreResponseHandler): Effect.Effect<void> =>
Effect.withFiber((fiber) => {
const o = Option.match(fiber.getRef(PreResponseHandlers), {
onNone: () => Option.some(handler),
onSome: (prev) =>
Option.some<PreResponseHandler>((request, response) =>
Effect.flatMap(prev(request, response), (response) => handler(request, response))
)
})
fiber.setServices(ServiceMap.add(fiber.services, PreResponseHandlers, o))
return Effect.void
})
/**
* @since 4.0.0
* @category fiber refs
*/
export const withPreResponseHandler: {
(handler: PreResponseHandler): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>
<A, E, R>(self: Effect.Effect<A, E, R>, handler: PreResponseHandler): Effect.Effect<A, E, R>
} = dual<
(handler: PreResponseHandler) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,
<A, E, R>(self: Effect.Effect<A, E, R>, handler: PreResponseHandler) => Effect.Effect<A, E, R>
>(2, (self, handler) =>
Effect.updateService(
self,
PreResponseHandlers,
Option.match({
onNone: () => Option.some(handler),
onSome: (prev) =>
Option.some((request, response) =>
Effect.flatMap(prev(request, response), (response) => handler(request, response))
)
})
))
/**
* @since 4.0.0
* @category conversions
*/
export const toWebHandlerWith = <R>(services: ServiceMap.ServiceMap<R>) => {
return <E>(
self: Effect.Effect<HttpServerResponse, E, R | HttpServerRequest | Scope.Scope>,
middleware?: HttpMiddleware | undefined
): (request: Request, services?: ServiceMap.ServiceMap<never> | undefined) => Promise<globalThis.Response> => {
const resolveSymbol = Symbol.for("@effect/platform/HttpApp/resolve")
const httpApp = toHandled(self, (request, response) => {
response = scopeTransferToStream(response)
;(request as any)[resolveSymbol](
Response.toWeb(response, { withoutBody: request.method === "HEAD", services })
)
return Effect.void
}, middleware)
return (request: Request, reqServices?: ServiceMap.ServiceMap<never> | undefined): Promise<globalThis.Response> =>
new Promise((resolve) => {
const contextMap = new Map<string, any>(services.unsafeMap)
if (ServiceMap.isServiceMap(reqServices)) {
for (const [key, value] of reqServices.unsafeMap) {
contextMap.set(key, value)
}
}
const httpServerRequest = Request.fromWeb(request)
contextMap.set(HttpServerRequest.key, httpServerRequest)
;(httpServerRequest as any)[resolveSymbol] = resolve
const fiber = Effect.runForkWith(ServiceMap.unsafeMake(contextMap))(httpApp as any)
request.signal?.addEventListener("abort", () => {
fiber.unsafeInterrupt(clientAbortFiberId)
}, { once: true })
})
}
}
/**
* @since 4.0.0
* @category conversions
*/
export const toWebHandler: <E>(
self: Effect.Effect<HttpServerResponse, E, HttpServerRequest | Scope.Scope>,
middleware?: HttpMiddleware | undefined
) => (request: Request, services?: ServiceMap.ServiceMap<never> | undefined) => Promise<globalThis.Response> =
toWebHandlerWith(ServiceMap.empty())
/**
* @since 4.0.0
* @category conversions
*/
export const toWebHandlerLayer = <E, R, RE>(
self: Effect.Effect<HttpServerResponse, E, R | HttpServerRequest | Scope.Scope>,
layer: Layer.Layer<R, RE>,
middleware?: HttpMiddleware | undefined
): {
readonly close: () => Promise<void>
readonly handler: (request: Request, context?: ServiceMap.ServiceMap<never> | undefined) => Promise<Response>
} => {
const scope = Effect.runSync(Scope.make())
const close = () => Effect.runPromise(Scope.close(scope, Exit.void))
const build = Effect.map(Layer.build(layer), (_) => toWebHandlerWith(_)(self, middleware))
const runner = Effect.runPromise(Scope.provide(build, scope))
const handler = (request: Request, context?: ServiceMap.ServiceMap<never> | undefined): Promise<Response> =>
runner.then((handler) => handler(request, context))
return { close, handler } as const
}
@@ -0,0 +1,360 @@
/**
* @since 4.0.0
*/
import * as Effect from "effect/Effect"
import { constFalse } from "../../Function.js"
import * as Layer from "../../Layer.js"
import * as Option from "../../Option.js"
import type { Predicate } from "../../Predicate.js"
import type { ReadonlyRecord } from "../../Record.js"
import * as ServiceMap from "../../ServiceMap.js"
import * as Headers from "./Headers.js"
import type { PreResponseHandler } from "./HttpEffect.js"
import { causeResponseStripped, exitResponse } from "./HttpServerError.js"
import { HttpServerRequest } from "./HttpServerRequest.js"
import * as Request from "./HttpServerRequest.js"
import * as Response from "./HttpServerResponse.js"
import type { HttpServerResponse } from "./HttpServerResponse.js"
import * as TraceContext from "./HttpTraceContext.js"
/**
* @since 4.0.0
* @category models
*/
export interface HttpMiddleware {
<E, R>(self: Effect.Effect<HttpServerResponse, E, R | HttpServerRequest>): Effect.Effect<HttpServerResponse, any, any>
}
/**
* @since 4.0.0
*/
export declare namespace HttpMiddleware {
/**
* @since 4.0.0
*/
export interface Applied<A extends Effect.Effect<HttpServerResponse, any, any>, E, R> {
(self: Effect.Effect<HttpServerResponse, E, R>): A
}
}
/**
* @since 4.0.0
* @category constructors
*/
export const make = <M extends HttpMiddleware>(middleware: M): M => middleware
/**
* @since 4.0.0
* @category Logger
*/
export const LoggerDisabled = ServiceMap.Reference<boolean>("effect/http/HttpMiddleware/LoggerDisabled", {
defaultValue: constFalse
})
/**
* @since 4.0.0
* @category Logger
*/
export const withLoggerDisabled = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
Effect.withFiber((fiber) => {
fiber.setServices(ServiceMap.add(fiber.services, LoggerDisabled, true))
return self
})
/**
* @since 4.0.0
* @category Tracer
*/
export const TracerDisabledWhen = ServiceMap.Reference<Predicate<HttpServerRequest>>(
"effect/http/HttpMiddleware/TracerDisabledWhen",
{ defaultValue: () => constFalse }
)
/**
* @since 4.0.0
* @category Tracer
*/
export const layerTracerDisabledForUrls = (
urls: ReadonlyArray<string>
): Layer.Layer<never> => Layer.succeed(TracerDisabledWhen, (req) => urls.includes(req.url))
/**
* @since 4.0.0
* @category Tracer
*/
export const SpanNameGenerator = ServiceMap.Reference<(request: HttpServerRequest) => string>(
"@effect/platform/HttpMiddleware/SpanNameGenerator",
{ defaultValue: () => (request) => `http.server ${request.method}` }
)
/**
* @since 4.0.0
* @category Logger
*/
export const logger: <E, R>(
httpApp: Effect.Effect<HttpServerResponse, E, HttpServerRequest | R>
) => Effect.Effect<HttpServerResponse, E, HttpServerRequest | R> = make((httpApp) => {
let counter = 0
return Effect.withFiber((fiber) => {
const request = ServiceMap.unsafeGet(fiber.services, HttpServerRequest)
return Effect.withLogSpan(
Effect.flatMap(Effect.exit(httpApp), (exit) => {
if (fiber.getRef(LoggerDisabled)) {
return exit
} else if (exit._tag === "Failure") {
const [response, cause] = causeResponseStripped(exit.cause)
return Effect.andThen(
Effect.annotateLogs(Effect.log(cause._tag === "Some" ? cause.value : "Sent HTTP Response"), {
"http.method": request.method,
"http.url": request.url,
"http.status": response.status
}),
exit
)
}
return Effect.andThen(
Effect.annotateLogs(Effect.log("Sent HTTP response"), {
"http.method": request.method,
"http.url": request.url,
"http.status": exit.value.status
}),
exit
)
}),
`http.span.${++counter}`
)
})
})
/**
* @since 4.0.0
* @category Tracer
*/
export const tracer: <E, R>(
httpApp: Effect.Effect<HttpServerResponse, E, HttpServerRequest | R>
) => Effect.Effect<HttpServerResponse, E, HttpServerRequest | R> = make((httpApp) =>
Effect.withFiber((fiber) => {
const request = ServiceMap.unsafeGet(fiber.services, HttpServerRequest)
const disabled = fiber.getRef(TracerDisabledWhen)(request)
if (disabled) {
return httpApp
}
const url = Option.getOrUndefined(Request.toURL(request))
if (url !== undefined && (url.username !== "" || url.password !== "")) {
url.username = "REDACTED"
url.password = "REDACTED"
}
const redactedHeaderNames = fiber.getRef(Headers.CurrentRedactedNames)
const redactedHeaders = Headers.redact(request.headers, redactedHeaderNames)
const nameGenerator = fiber.getRef(SpanNameGenerator)
return Effect.useSpan(
nameGenerator(request),
{
parent: Option.getOrUndefined(TraceContext.fromHeaders(request.headers)),
kind: "server",
captureStackTrace: false
},
(span) => {
span.attribute("http.request.method", request.method)
if (url !== undefined) {
span.attribute("url.full", url.toString())
span.attribute("url.path", url.pathname)
const query = url.search.slice(1)
if (query !== "") {
span.attribute("url.query", url.search.slice(1))
}
span.attribute("url.scheme", url.protocol.slice(0, -1))
}
if (request.headers["user-agent"] !== undefined) {
span.attribute("user_agent.original", request.headers["user-agent"])
}
for (const name in redactedHeaders) {
span.attribute(`http.request.header.${name}`, String(redactedHeaders[name]))
}
if (request.remoteAddress._tag === "Some") {
span.attribute("client.address", request.remoteAddress.value)
}
return Effect.onExitInterruptible(Effect.withParentSpan(httpApp, span), (exit) => {
const response = exitResponse(exit)
span.attribute("http.response.status_code", response.status)
const redactedHeaders = Headers.redact(response.headers, redactedHeaderNames)
for (const name in redactedHeaders) {
span.attribute(`http.response.header.${name}`, String(redactedHeaders[name]))
}
return Effect.void
})
}
)
})
)
/**
* @since 4.0.0
* @category Proxying
*/
export const xForwardedHeaders = make((httpApp) =>
Effect.updateService(httpApp, HttpServerRequest, (request) =>
request.headers["x-forwarded-host"]
? request.modify({
headers: Headers.set(
request.headers,
"host",
request.headers["x-forwarded-host"]
),
remoteAddress: request.headers["x-forwarded-for"]?.split(",")[0].trim()
})
: request)
)
/**
* @since 4.0.0
* @category Search params
*/
export const searchParamsParser = <E, R>(
httpApp: Effect.Effect<HttpServerResponse, E, R>
): Effect.Effect<Response.HttpServerResponse, E, HttpServerRequest | Exclude<R, Request.ParsedSearchParams>> =>
Effect.withFiber((fiber) => {
const services = fiber.services
const request = ServiceMap.unsafeGet(services, HttpServerRequest)
const params = Request.searchParamsFromURL(new URL(request.originalUrl))
return Effect.provideService(
httpApp,
Request.ParsedSearchParams,
params
) as any
})
/**
* @since 4.0.0
* @category CORS
*/
export const cors = (options?: {
readonly allowedOrigins?: ReadonlyArray<string> | undefined
readonly allowedMethods?: ReadonlyArray<string> | undefined
readonly allowedHeaders?: ReadonlyArray<string> | undefined
readonly exposedHeaders?: ReadonlyArray<string> | undefined
readonly maxAge?: number | undefined
readonly credentials?: boolean | undefined
}): <E, R>(
httpApp: Effect.Effect<HttpServerResponse, E, R>
) => Effect.Effect<HttpServerResponse, E, R | HttpServerRequest> => {
const opts = {
allowedOrigins: options?.allowedOrigins ?? ["*"],
allowedMethods: options?.allowedMethods ?? ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"],
allowedHeaders: options?.allowedHeaders ?? [],
exposedHeaders: options?.exposedHeaders ?? [],
credentials: options?.credentials ?? false,
maxAge: options?.maxAge
}
const isAllowedOrigin = (origin: string) => opts.allowedOrigins.includes(origin)
const allowOrigin = (originHeader: string): ReadonlyRecord<string, string> | undefined => {
if (opts.allowedOrigins.length === 0) {
return { "access-control-allow-origin": "*" }
}
if (opts.allowedOrigins.length === 1) {
return {
"access-control-allow-origin": opts.allowedOrigins[0],
vary: "Origin"
}
}
if (isAllowedOrigin(originHeader)) {
return {
"access-control-allow-origin": originHeader,
vary: "Origin"
}
}
return undefined
}
const allowMethods = opts.allowedMethods.length > 0
? { "access-control-allow-methods": opts.allowedMethods.join(", ") }
: undefined
const allowCredentials = opts.credentials
? { "access-control-allow-credentials": "true" }
: undefined
const allowHeaders = (
accessControlRequestHeaders: string | undefined
): ReadonlyRecord<string, string> | undefined => {
if (opts.allowedHeaders.length === 0 && accessControlRequestHeaders) {
return {
vary: "Access-Control-Request-Headers",
"access-control-allow-headers": accessControlRequestHeaders
}
}
if (opts.allowedHeaders) {
return {
"access-control-allow-headers": opts.allowedHeaders.join(",")
}
}
return undefined
}
const exposeHeaders = opts.exposedHeaders.length > 0
? { "access-control-expose-headers": opts.exposedHeaders.join(",") }
: undefined
const maxAge = opts.maxAge
? { "access-control-max-age": opts.maxAge.toString() }
: undefined
const headersFromRequest = (request: HttpServerRequest) => {
const origin = request.headers["origin"]
return Headers.unsafeFromRecord({
...allowOrigin(origin),
...allowCredentials,
...exposeHeaders
})
}
const headersFromRequestOptions = (request: HttpServerRequest) => {
const origin = request.headers["origin"]
const accessControlRequestHeaders = request.headers["access-control-request-headers"]
return Headers.unsafeFromRecord({
...allowOrigin(origin),
...allowCredentials,
...exposeHeaders,
...allowMethods,
...allowHeaders(accessControlRequestHeaders),
...maxAge
})
}
const preResponseHandler = (request: HttpServerRequest, response: HttpServerResponse) =>
Effect.succeed(Response.setHeaders(response, headersFromRequest(request)))
return <E, R>(
httpApp: Effect.Effect<HttpServerResponse, E, R>
): Effect.Effect<HttpServerResponse, E, R | HttpServerRequest> =>
Effect.withFiber((fiber) => {
const request = ServiceMap.unsafeGet(fiber.services, HttpServerRequest)
if (request.method === "OPTIONS") {
return Effect.succeed(Response.empty({
status: 204,
headers: headersFromRequestOptions(request)
}))
}
const o = Option.match(fiber.getRef(PreResponseHandlers), {
onNone: () => Option.some(preResponseHandler),
onSome: (prev) =>
Option.some<PreResponseHandler>((request, response) =>
Effect.flatMap(prev(request, response), (response) => preResponseHandler(request, response))
)
})
fiber.setServices(ServiceMap.add(fiber.services, PreResponseHandlers, o))
return httpApp
})
}
const PreResponseHandlers = ServiceMap.Reference<Option.Option<PreResponseHandler>>(
"effect/http/HttpEffect/PreResponseHandlers",
{ defaultValue: Option.none }
)
@@ -0,0 +1,145 @@
/**
* @since 4.0.0
*/
import * as Effect from "../../Effect.js"
import * as FileSystem from "../../FileSystem.js"
import { identity } from "../../Function.js"
import * as Layer from "../../Layer.js"
import type { PlatformError } from "../../PlatformError.js"
import * as ServiceMap from "../../ServiceMap.js"
import * as Stream from "../../Stream.js"
import * as Etag from "./Etag.js"
import * as Headers from "./Headers.js"
import type * as Body from "./HttpBody.js"
import * as Response from "./HttpServerResponse.js"
/**
* @since 4.0.0
* @category type ids
*/
export const TypeId: TypeId = "~effect/http/HttpPlatform"
/**
* @since 4.0.0
* @category type ids
*/
export type TypeId = "~effect/http/HttpPlatform"
/**
* @since 4.0.0
* @category tags
*/
export class HttpPlatform extends ServiceMap.Key<HttpPlatform, {
readonly fileResponse: (
path: string,
options?: Response.Options.WithContent & FileSystem.StreamOptions
) => Effect.Effect<Response.HttpServerResponse, PlatformError>
readonly fileWebResponse: (
file: Body.HttpBody.FileLike,
options?: Response.Options.WithContent & FileSystem.StreamOptions
) => Effect.Effect<Response.HttpServerResponse>
}>()("effect/http/HttpPlatform") {}
/**
* @since 4.0.0
* @category constructors
*/
export const make: (impl: {
readonly fileResponse: (
path: string,
status: number,
statusText: string | undefined,
headers: Headers.Headers,
start: number,
end: number | undefined,
contentLength: number
) => Response.HttpServerResponse
readonly fileWebResponse: (
file: Body.HttpBody.FileLike,
status: number,
statusText: string | undefined,
headers: Headers.Headers,
options?: FileSystem.StreamOptions
) => Response.HttpServerResponse
}) => Effect.Effect<
HttpPlatform["Service"],
never,
Etag.Generator | FileSystem.FileSystem
> = Effect.fnUntraced(function*(impl) {
const fs = yield* FileSystem.FileSystem
const etagGen = yield* Etag.Generator
return HttpPlatform.of({
fileResponse: Effect.fnUntraced(function*(path, options) {
const info = yield* fs.stat(path)
const etag = yield* etagGen.fromFileInfo(info)
const start = Number(options?.offset ?? 0)
const end = options?.bytesToRead !== undefined ? start + Number(options.bytesToRead) : undefined
const headers = Headers.set(
options?.headers ? Headers.fromInput(options.headers) : Headers.empty,
"etag",
Etag.toString(etag)
)
if (info.mtime._tag === "Some") {
;(headers as any)["last-modified"] = info.mtime.value.toUTCString()
}
const contentLength = end !== undefined ? end - start : Number(info.size) - start
return impl.fileResponse(
path,
options?.status ?? 200,
options?.statusText,
headers,
start,
end,
contentLength
)
}),
fileWebResponse(file, options) {
return Effect.map(etagGen.fromFileWeb(file), (etag) => {
const headers = Headers.merge(
options?.headers ? Headers.fromInput(options.headers) : Headers.empty,
Headers.unsafeFromRecord({
etag: Etag.toString(etag),
"last-modified": new Date(file.lastModified).toUTCString()
})
)
return impl.fileWebResponse(
file,
options?.status ?? 200,
options?.statusText,
headers,
options
)
})
}
})
})
/**
* @since 4.0.0
* @category layers
*/
export const layer = Layer.effect(
HttpPlatform,
Effect.flatMap(FileSystem.FileSystem.asEffect(), (fs) =>
make({
fileResponse(path, status, statusText, headers, start, end, contentLength) {
return Response.stream(
fs.stream(path, {
offset: start,
bytesToRead: end !== undefined ? end - start : undefined
}),
{ contentLength, headers, status, statusText }
)
},
fileWebResponse(file, status, statusText, headers, _options) {
return Response.stream(
Stream.fromReadableStream({
evaluate: () => file.stream() as ReadableStream<Uint8Array>,
onError: identity
}),
{ headers, status, statusText }
)
}
}))
).pipe(Layer.provide(Etag.layerWeak))
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,254 @@
/**
* @since 4.0.0
*/
import * as Effect from "../../Effect.js"
import * as FileSystem from "../../FileSystem.js"
import { dual } from "../../Function.js"
import * as Layer from "../../Layer.js"
import * as Path from "../../Path.js"
import type * as Scope from "../../Scope.js"
import * as ServiceMap from "../../ServiceMap.js"
import * as Etag from "./Etag.js"
import * as HttpClient from "./HttpClient.js"
import * as ClientRequest from "./HttpClientRequest.js"
import type * as Middleware from "./HttpMiddleware.js"
import * as HttpPlatform from "./HttpPlatform.js"
import type { HttpServerRequest } from "./HttpServerRequest.js"
import type { HttpServerResponse } from "./HttpServerResponse.js"
/**
* @since 4.0.0
* @category models
*/
export class HttpServer extends ServiceMap.Key<HttpServer, {
readonly serve: {
<E, R>(effect: Effect.Effect<HttpServerResponse, E, R>): Effect.Effect<
void,
never,
Exclude<R, HttpServerRequest> | Scope.Scope
>
<E, R, App extends Effect.Effect<HttpServerResponse, any, any>>(
effect: Effect.Effect<HttpServerResponse, E, R>,
middleware: Middleware.HttpMiddleware.Applied<App, E, R>
): Effect.Effect<
void,
never,
Exclude<R, HttpServerRequest> | Scope.Scope
>
}
readonly address: Address
}>()("effect/http/HttpServer") {}
/**
* @since 4.0.0
* @category address
*/
export type Address = UnixAddress | TcpAddress
/**
* @since 4.0.0
* @category address
*/
export interface TcpAddress {
readonly _tag: "TcpAddress"
readonly hostname: string
readonly port: number
}
/**
* @since 4.0.0
* @category address
*/
export interface UnixAddress {
readonly _tag: "UnixAddress"
readonly path: string
}
/**
* @since 4.0.0
* @category constructors
*/
export const make = (
options: {
readonly serve: (
httpApp: Effect.Effect<HttpServerResponse, unknown, HttpServerRequest | Scope.Scope>,
middleware?: Middleware.HttpMiddleware
) => Effect.Effect<void, never, Scope.Scope>
readonly address: Address
}
): HttpServer["Service"] => options
/**
* @since 4.0.0
* @category accessors
*/
export const serve: {
(): <E, R>(
effect: Effect.Effect<HttpServerResponse, E, R>
) => Layer.Layer<never, never, HttpServer | Exclude<R, HttpServerRequest | Scope.Scope>>
<E, R, App extends Effect.Effect<HttpServerResponse, any, any>>(
middleware: Middleware.HttpMiddleware.Applied<App, E, R>
): (
effect: Effect.Effect<HttpServerResponse, E, R>
) => Layer.Layer<
never,
never,
HttpServer | Exclude<Effect.Services<App>, HttpServerRequest | Scope.Scope>
>
<E, R>(
effect: Effect.Effect<HttpServerResponse, E, R>
): Layer.Layer<never, never, HttpServer | Exclude<R, HttpServerRequest | Scope.Scope>>
<E, R, App extends Effect.Effect<HttpServerResponse, any, any>>(
effect: Effect.Effect<HttpServerResponse, E, R>,
middleware: Middleware.HttpMiddleware.Applied<App, E, R>
): Layer.Layer<
never,
never,
HttpServer | Exclude<Effect.Services<App>, HttpServerRequest | Scope.Scope>
>
} = dual((args) => Effect.isEffect(args[0]), <E, R, App extends Effect.Effect<HttpServerResponse, any, any>>(
effect: Effect.Effect<HttpServerResponse, E, R>,
middleware?: Middleware.HttpMiddleware.Applied<App, E, R>
): Layer.Layer<
never,
never,
HttpServer | Exclude<Effect.Services<App>, HttpServerRequest | Scope.Scope>
> =>
Layer.effectDiscard(
Effect.flatMap(
HttpServer.asEffect(),
(server) => server.serve(effect, middleware!)
)
) as any)
/**
* @since 4.0.0
* @category accessors
*/
export const serveEffect: {
(): <E, R>(
effect: Effect.Effect<HttpServerResponse, E, R>
) => Effect.Effect<void, never, Scope.Scope | HttpServer | Exclude<R, HttpServerRequest>>
<E, R, App extends Effect.Effect<HttpServerResponse, any, any>>(
middleware: Middleware.HttpMiddleware.Applied<App, E, R>
): (
effect: Effect.Effect<HttpServerResponse, E, R>
) => Effect.Effect<
void,
never,
Scope.Scope | HttpServer | Exclude<Effect.Services<App>, HttpServerRequest>
>
<E, R>(
effect: Effect.Effect<HttpServerResponse, E, R>
): Effect.Effect<void, never, Scope.Scope | HttpServer | Exclude<R, HttpServerRequest>>
<E, R, App extends Effect.Effect<HttpServerResponse, any, any>>(
effect: Effect.Effect<HttpServerResponse, E, R>,
middleware: Middleware.HttpMiddleware.Applied<App, E, R>
): Effect.Effect<
void,
never,
Scope.Scope | HttpServer | Exclude<Effect.Services<App>, HttpServerRequest>
>
} = dual((args) => Effect.isEffect(args[0]), <E, R, App extends Effect.Effect<HttpServerResponse, any, any>>(
effect: Effect.Effect<HttpServerResponse, E, R>,
middleware?: Middleware.HttpMiddleware.Applied<App, E, R>
): Effect.Effect<
void,
never,
Scope.Scope | HttpServer | Exclude<Effect.Services<App>, HttpServerRequest>
> =>
Effect.flatMap(
HttpServer.asEffect(),
(server) => server.serve(effect, middleware!)
) as any)
/**
* @since 4.0.0
* @category address
*/
export const formatAddress = (address: Address): string => {
switch (address._tag) {
case "UnixAddress":
return `unix://${address.path}`
case "TcpAddress":
return `http://${address.hostname}:${address.port}`
}
}
/**
* @since 4.0.0
* @category address
*/
export const addressFormattedWith = <A, E, R>(
f: (address: string) => Effect.Effect<A, E, R>
): Effect.Effect<A, E, HttpServer | R> =>
Effect.flatMap(
HttpServer.asEffect(),
(server) => f(formatAddress(server.address))
)
/**
* @since 4.0.0
* @category address
*/
export const logAddress: Effect.Effect<void, never, HttpServer> = addressFormattedWith((_) =>
Effect.log(`Listening on ${_}`)
)
/**
* @since 4.0.0
* @category address
*/
export const withLogAddress = <A, E, R>(
layer: Layer.Layer<A, E, R>
): Layer.Layer<A, E, R | Exclude<HttpServer, A>> =>
Layer.effectDiscard(logAddress).pipe(
Layer.provideMerge(layer)
)
/**
* @since 4.0.0
* @category Testing
*/
export const makeTestClient: Effect.Effect<
HttpClient.HttpClient,
never,
HttpServer | HttpClient.HttpClient
> = Effect.gen(function*() {
const server = yield* HttpServer
const client = yield* HttpClient.HttpClient
const address = server.address
if (address._tag === "UnixAddress") {
return yield* Effect.die(new Error("HttpServer.layerTestClient: UnixAddress not supported"))
}
const host = address.hostname === "0.0.0.0" ? "127.0.0.1" : address.hostname
const url = `http://${host}:${address.port}`
return HttpClient.mapRequest(client, ClientRequest.prependUrl(url))
})
/**
* @since 4.0.0
* @category Testing
*/
export const layerTestClient: Layer.Layer<
HttpClient.HttpClient,
never,
HttpServer | HttpClient.HttpClient
> = Layer.effect(HttpClient.HttpClient, makeTestClient)
/**
* @since 4.0.0
* @category Testing
*/
export const layerServices: Layer.Layer<
| Path.Path
| HttpPlatform.HttpPlatform
| FileSystem.FileSystem
| Etag.Generator
> = Layer.mergeAll(
HttpPlatform.layer,
Path.layer,
Etag.layerWeak
).pipe(
Layer.provideMerge(FileSystem.layerNoop({}))
)
@@ -0,0 +1,203 @@
/**
* @since 4.0.0
*/
import * as Arr from "../../Array.js"
import * as Cause from "../../Cause.js"
import * as Data from "../../Data.js"
import * as Effect from "../../Effect.js"
import type * as Exit from "../../Exit.js"
import * as Option from "../../Option.js"
import { hasProperty } from "../../Predicate.js"
import type * as Request from "./HttpServerRequest.js"
import * as Respondable from "./HttpServerRespondable.js"
import * as Response from "./HttpServerResponse.js"
/**
* @since 4.0.0
* @category type id
*/
export const TypeId: TypeId = "~effect/http/HttpServerError"
/**
* @since 4.0.0
* @category type id
*/
export type TypeId = "~effect/http/HttpServerError"
/**
* @since 4.0.0
* @category error
*/
export type HttpServerError = RequestError | ResponseError
/**
* @since 4.0.0
* @category error
*/
export class RequestError extends Data.TaggedError("HttpServerError")<{
readonly reason: "RequestParseError" | "RouteNotFound"
readonly request: Request.HttpServerRequest
readonly description?: string
readonly cause?: unknown
}> implements Respondable.Respondable {
/**
* @since 4.0.0
*/
readonly [TypeId]: TypeId = TypeId
/**
* @since 4.0.0
*/
stack = `${this.name}: ${this.message}`;
/**
* @since 4.0.0
*/
[Respondable.symbol]() {
return Effect.succeed(Response.empty({ status: this.reason === "RouteNotFound" ? 404 : 400 }))
}
get methodAndUrl() {
return `${this.request.method} ${this.request.url}`
}
get message() {
const prefix = `${this.reason} (${this.methodAndUrl})`
return this.description ? `${prefix}: ${this.description}` : prefix
}
}
/**
* @since 4.0.0
* @category predicates
*/
export const isHttpServerError = (u: unknown): u is HttpServerError => hasProperty(u, TypeId)
/**
* @since 4.0.0
* @category error
*/
export class ResponseError extends Data.TaggedError("HttpServerError")<{
readonly request: Request.HttpServerRequest
readonly response: Response.HttpServerResponse
readonly description?: string
readonly cause?: unknown
}> implements Respondable.Respondable {
/**
* @since 4.0.0
*/
readonly [TypeId]: TypeId = TypeId
/**
* @since 4.0.0
*/
readonly reason = "ResponseError" as const
/**
* @since 4.0.0
*/
stack = `${this.name}: ${this.message}`;
/**
* @since 4.0.0
*/
[Respondable.symbol]() {
return Effect.succeed(Response.empty({ status: 500 }))
}
get methodAndUrl() {
return `${this.request.method} ${this.request.url}`
}
get message() {
const info = `${this.reason} (${this.response.status} ${this.methodAndUrl})`
return this.description ? `${info}: ${this.description}` : info
}
}
/**
* @since 4.0.0
* @category error
*/
export class ServeError extends Data.TaggedError("ServeError")<{
readonly cause: unknown
}> {
/**
* @since 4.0.0
*/
readonly [TypeId]: TypeId = TypeId
}
/**
* @since 4.0.0
*/
export const clientAbortFiberId = -499
/**
* @since 4.0.0
*/
export const causeResponse = <E>(
cause: Cause.Cause<E>
): Effect.Effect<readonly [Response.HttpServerResponse, Cause.Cause<E>]> => {
const [effect, failures] = Arr.reduce(
cause.failures,
[Effect.succeed(internalServerError), Arr.empty<Cause.Failure<E>>()] as const,
(acc, f) => {
switch (f._tag) {
case "Fail": {
return [Respondable.toResponseOrElse(f.error, internalServerError), [f]]
}
case "Die": {
return [Respondable.toResponseOrElseDefect(f.defect, internalServerError), [f]]
}
case "Interrupt": {
if (acc[1].length > 0) return acc
const response = f.fiberId._tag === "Some" && f.fiberId.value === clientAbortFiberId
? clientAbortError
: serverAbortError
return [Effect.succeed(response), [f]]
}
default: {
return acc
}
}
}
)
return Effect.map(effect, (response) => {
failures.push(Cause.failureDie(response))
return [response, Cause.fromFailures(failures)] as const
})
}
/**
* @since 4.0.0
*/
export const causeResponseStripped = <E>(
cause: Cause.Cause<E>
): readonly [response: Response.HttpServerResponse, cause: Option.Option<Cause.Cause<E>>] => {
let response: Response.HttpServerResponse | undefined
const failures = cause.failures.filter((f) => {
if (f._tag === "Die" && Response.isHttpServerResponse(f.defect)) {
response = f.defect
return false
}
return true
})
return [
response ?? internalServerError,
failures.length > 0 ? Option.some(Cause.fromFailures(failures)) : Option.none()
]
}
const internalServerError = Response.empty({ status: 500 })
const clientAbortError = Response.empty({ status: 499 })
const serverAbortError = Response.empty({ status: 503 })
/**
* @since 4.0.0
*/
export const exitResponse = <E>(exit: Exit.Exit<Response.HttpServerResponse, E>): Response.HttpServerResponse => {
if (exit._tag === "Success") {
return exit.value
}
return causeResponseStripped(exit.cause)[0]
}
@@ -0,0 +1,492 @@
/**
* @since 4.0.0
*/
import type * as Arr from "../../Array.js"
import * as Channel from "../../Channel.js"
import * as Effect from "../../Effect.js"
import type * as FileSystem from "../../FileSystem.js"
import * as Inspectable from "../../Inspectable.js"
import * as Option from "../../Option.js"
import type * as Path from "../../Path.js"
import type { ReadonlyRecord } from "../../Record.js"
import type { ParseOptions } from "../../schema/AST.js"
import * as Schema from "../../schema/Schema.js"
import type * as Scope from "../../Scope.js"
import * as ServiceMap from "../../ServiceMap.js"
import * as Stream from "../../Stream.js"
import * as Socket from "../socket/Socket.js"
import * as Cookies from "./Cookies.js"
import * as Headers from "./Headers.js"
import * as HttpIncomingMessage from "./HttpIncomingMessage.js"
import type { HttpMethod } from "./HttpMethod.js"
import { type HttpServerError, RequestError } from "./HttpServerError.js"
import * as Multipart from "./Multipart.js"
import * as UrlParams from "./UrlParams.js"
export {
/**
* @since 4.0.0
* @category fiber refs
*/
MaxBodySize
} from "./HttpIncomingMessage.js"
/**
* @since 4.0.0
* @category type ids
*/
export const TypeId: TypeId = "~effect/http/HttpServerRequest"
/**
* @since 4.0.0
* @category type ids
*/
export type TypeId = "~effect/http/HttpServerRequest"
/**
* @since 4.0.0
* @category models
*/
export interface HttpServerRequest extends HttpIncomingMessage.HttpIncomingMessage<HttpServerError> {
readonly [TypeId]: TypeId
readonly source: unknown
readonly url: string
readonly originalUrl: string
readonly method: HttpMethod
readonly cookies: ReadonlyRecord<string, string>
readonly multipart: Effect.Effect<
Multipart.Persisted,
Multipart.MultipartError,
Scope.Scope | FileSystem.FileSystem | Path.Path
>
readonly multipartStream: Stream.Stream<Multipart.Part, Multipart.MultipartError>
readonly upgrade: Effect.Effect<Socket.Socket, HttpServerError>
readonly modify: (
options: {
readonly url?: string
readonly headers?: Headers.Headers
readonly remoteAddress?: string
}
) => HttpServerRequest
}
/**
* @since 4.0.0
* @category context
*/
export const HttpServerRequest: ServiceMap.Key<HttpServerRequest, HttpServerRequest> = ServiceMap.Key(
"effect/http/HttpServerRequest"
)
/**
* @since 4.0.0
* @category search params
*/
export class ParsedSearchParams extends ServiceMap.Key<
ParsedSearchParams,
ReadonlyRecord<string, string | Array<string>>
>()("effect/http/ParsedSearchParams") {}
/**
* @since 4.0.0
* @category search params
*/
export const searchParamsFromURL = (url: URL): ReadonlyRecord<string, string | Array<string>> => {
const out: Record<string, string | Array<string>> = {}
for (const [key, value] of url.searchParams.entries()) {
const entry = out[key]
if (entry !== undefined) {
if (Array.isArray(entry)) {
entry.push(value)
} else {
out[key] = [entry, value]
}
} else {
out[key] = value
}
}
return out
}
/**
* @since 4.0.0
* @category accessors
*/
export const upgradeChannel = <IE = never>(): Channel.Channel<
Arr.NonEmptyReadonlyArray<Uint8Array>,
HttpServerError | IE | Socket.SocketError,
void,
Arr.NonEmptyReadonlyArray<string | Uint8Array | Socket.CloseEvent>,
IE,
unknown,
HttpServerRequest
> =>
HttpServerRequest.asEffect().pipe(
Effect.flatMap((_) => _.upgrade),
Effect.map(Socket.toChannelWith<IE>()),
Channel.unwrap
)
/**
* @since 4.0.0
* @category schema
*/
export const schemaCookies = <A, I extends Readonly<Record<string, string | undefined>>, RD, RE>(
schema: Schema.Codec<A, I, RD, RE>,
options?: ParseOptions | undefined
): Effect.Effect<A, Schema.SchemaError, RD | HttpServerRequest> => {
const parse = Schema.decodeUnknownEffect(schema)
return Effect.flatMap(HttpServerRequest.asEffect(), (req) => parse(req.cookies, options))
}
/**
* @since 4.0.0
* @category schema
*/
export const schemaHeaders = <A, I extends Readonly<Record<string, string | undefined>>, RD, RE>(
schema: Schema.Codec<A, I, RD, RE>,
options?: ParseOptions | undefined
): Effect.Effect<A, Schema.SchemaError, HttpServerRequest | RD> => {
const parse = Schema.decodeUnknownEffect(schema)
return Effect.flatMap(HttpServerRequest.asEffect(), (req) => parse(req.headers, options))
}
/**
* @since 4.0.0
* @category schema
*/
export const schemaSearchParams = <
A,
I extends Readonly<Record<string, string | ReadonlyArray<string> | undefined>>,
RD,
RE
>(
schema: Schema.Codec<A, I, RD, RE>,
options?: ParseOptions | undefined
): Effect.Effect<A, Schema.SchemaError, ParsedSearchParams | RD> => {
const parse = Schema.decodeUnknownEffect(schema)
return Effect.flatMap(ParsedSearchParams.asEffect(), (params) => parse(params, options))
}
/**
* @since 4.0.0
* @category schema
*/
export const schemaBodyJson = <A, I, RD, RE>(
schema: Schema.Codec<A, I, RD, RE>,
options?: ParseOptions | undefined
): Effect.Effect<A, HttpServerError | Schema.SchemaError, HttpServerRequest | RD> => {
const parse = HttpIncomingMessage.schemaBodyJson(schema, options)
return Effect.flatMap(HttpServerRequest.asEffect(), parse)
}
const isMultipart = (request: HttpServerRequest) =>
request.headers["content-type"]?.toLowerCase().includes("multipart/form-data")
/**
* @since 4.0.0
* @category schema
*/
/** @internal */
export const schemaBodyForm = <A, I extends Partial<Multipart.Persisted>, RD, RE>(
schema: Schema.Codec<A, I, RD, RE>,
options?: ParseOptions | undefined
) => {
const parseMultipart = Multipart.schemaPersisted(schema)
const parseUrlParams = HttpIncomingMessage.schemaBodyUrlParams(schema as Schema.Codec<A, any, RD, RE>, options)
return Effect.flatMap(HttpServerRequest.asEffect(), (request): Effect.Effect<
A,
Multipart.MultipartError | Schema.SchemaError | HttpServerError,
RD | HttpServerRequest | Scope.Scope | FileSystem.FileSystem | Path.Path
> => {
if (isMultipart(request)) {
return Effect.flatMap(request.multipart, (_) => parseMultipart(_, options))
}
return parseUrlParams(request)
})
}
/**
* @since 4.0.0
* @category schema
*/
export const schemaBodyUrlParams = <
A,
I extends Readonly<Record<string, string | ReadonlyArray<string> | undefined>>,
RD,
RE
>(
schema: Schema.Codec<A, I, RD, RE>,
options?: ParseOptions | undefined
): Effect.Effect<A, HttpServerError | Schema.SchemaError, HttpServerRequest | RD> => {
const parse = HttpIncomingMessage.schemaBodyJson(schema, options)
return Effect.flatMap(HttpServerRequest.asEffect(), parse)
}
/**
* @since 4.0.0
* @category schema
*/
export const schemaBodyMultipart = <A, I extends Partial<Multipart.Persisted>, RD, RE>(
schema: Schema.Codec<A, I, RD, RE>,
options?: ParseOptions | undefined
): Effect.Effect<
A,
Multipart.MultipartError | Schema.SchemaError,
HttpServerRequest | Scope.Scope | FileSystem.FileSystem | Path.Path | RD
> => {
const parse = Multipart.schemaPersisted(schema)
return HttpServerRequest.asEffect().pipe(
Effect.flatMap((_) => _.multipart),
Effect.flatMap((_) => parse(_, options))
)
}
/**
* @since 4.0.0
* @category schema
*/
export const schemaBodyFormJson = <A, I, RD, RE>(
schema: Schema.Codec<A, I, RD, RE>,
options?: ParseOptions | undefined
) => {
const parseMultipart = Multipart.schemaJson(schema, options)
return (field: string) => {
const parseUrlParams = UrlParams.schemaJsonField(field).pipe(
Schema.decodeTo(schema),
Schema.decodeEffect
)
return Effect.flatMap(
HttpServerRequest.asEffect(),
(request): Effect.Effect<
A,
Schema.SchemaError | HttpServerError,
RD | FileSystem.FileSystem | Path.Path | Scope.Scope | HttpServerRequest
> => {
if (isMultipart(request)) {
return Effect.flatMap(
Effect.mapError(request.multipart, (cause) =>
new RequestError({
request,
reason: "RequestParseError",
cause
})),
parseMultipart(field)
)
}
return Effect.flatMap(request.urlParamsBody, (_) => parseUrlParams(_, options))
}
)
}
}
/**
* @since 4.0.0
* @category conversions
*/
export const fromWeb = (request: globalThis.Request): HttpServerRequest =>
new ServerRequestImpl(request, removeHost(request.url))
const removeHost = (url: string) => {
if (url[0] === "/") {
return url
}
const index = url.indexOf("/", url.indexOf("//") + 2)
return index === -1 ? "/" : url.slice(index)
}
class ServerRequestImpl extends Inspectable.Class implements HttpServerRequest {
readonly [TypeId]: TypeId
readonly [HttpIncomingMessage.TypeId]: HttpIncomingMessage.TypeId
constructor(
readonly source: Request,
readonly url: string,
public headersOverride?: Headers.Headers,
private remoteAddressOverride?: string
) {
super()
this[TypeId] = TypeId
this[HttpIncomingMessage.TypeId] = HttpIncomingMessage.TypeId
}
toJSON(): unknown {
return HttpIncomingMessage.inspect(this, {
_id: "effect/http/HttpServerRequest",
method: this.method,
url: this.originalUrl
})
}
modify(
options: {
readonly url?: string | undefined
readonly headers?: Headers.Headers | undefined
readonly remoteAddress?: string | undefined
}
) {
return new ServerRequestImpl(
this.source,
options.url ?? this.url,
options.headers ?? this.headersOverride,
options.remoteAddress ?? this.remoteAddressOverride
)
}
get method(): HttpMethod {
return this.source.method.toUpperCase() as HttpMethod
}
get originalUrl() {
return this.source.url
}
get remoteAddress(): Option.Option<string> {
return this.remoteAddressOverride ? Option.some(this.remoteAddressOverride) : Option.none()
}
get headers(): Headers.Headers {
this.headersOverride ??= Headers.fromInput(this.source.headers as any)
return this.headersOverride
}
private cachedCookies: ReadonlyRecord<string, string> | undefined
get cookies() {
if (this.cachedCookies) {
return this.cachedCookies
}
return this.cachedCookies = Cookies.parseHeader(this.headers.cookie ?? "")
}
get stream(): Stream.Stream<Uint8Array, HttpServerError> {
return this.source.body
? Stream.fromReadableStream({
evaluate: () => this.source.body as any,
onError: (cause) =>
new RequestError({
request: this,
reason: "RequestParseError",
cause
})
})
: Stream.fail(
new RequestError({
request: this,
reason: "RequestParseError",
description: "can not create stream from empty body"
})
)
}
private textEffect: Effect.Effect<string, HttpServerError> | undefined
get text(): Effect.Effect<string, HttpServerError> {
if (this.textEffect) {
return this.textEffect
}
this.textEffect = Effect.runSync(Effect.cached(
Effect.tryPromise({
try: () => this.source.text(),
catch: (cause) =>
new RequestError({
request: this,
reason: "RequestParseError",
cause
})
})
))
return this.textEffect
}
get json(): Effect.Effect<unknown, HttpServerError> {
return Effect.flatMap(this.text, (text) =>
Effect.try({
try: () => JSON.parse(text) as unknown,
catch: (cause) =>
new RequestError({
request: this,
reason: "RequestParseError",
cause
})
}))
}
get urlParamsBody(): Effect.Effect<UrlParams.UrlParams, HttpServerError> {
return Effect.flatMap(this.text, (_) =>
Effect.try({
try: () => UrlParams.fromInput(new URLSearchParams(_)),
catch: (cause) =>
new RequestError({
request: this,
reason: "RequestParseError",
cause
})
}))
}
private multipartEffect:
| Effect.Effect<
Multipart.Persisted,
Multipart.MultipartError,
Scope.Scope | FileSystem.FileSystem | Path.Path
>
| undefined
get multipart(): Effect.Effect<
Multipart.Persisted,
Multipart.MultipartError,
Scope.Scope | FileSystem.FileSystem | Path.Path
> {
if (this.multipartEffect) {
return this.multipartEffect
}
this.multipartEffect = Effect.runSync(Effect.cached(
Multipart.toPersisted(this.multipartStream)
))
return this.multipartEffect
}
get multipartStream(): Stream.Stream<Multipart.Part, Multipart.MultipartError> {
return Stream.pipeThroughChannel(
Stream.mapError(this.stream, (cause) => new Multipart.MultipartError({ reason: "InternalError", cause })),
Multipart.makeChannel(this.headers)
)
}
private arrayBufferEffect: Effect.Effect<ArrayBuffer, HttpServerError> | undefined
get arrayBuffer(): Effect.Effect<ArrayBuffer, HttpServerError> {
if (this.arrayBufferEffect) {
return this.arrayBufferEffect
}
this.arrayBufferEffect = Effect.runSync(Effect.cached(
Effect.tryPromise({
try: () => this.source.arrayBuffer(),
catch: (cause) =>
new RequestError({
request: this,
reason: "RequestParseError",
cause
})
})
))
return this.arrayBufferEffect
}
get upgrade(): Effect.Effect<Socket.Socket, HttpServerError> {
return Effect.fail(
new RequestError({
request: this,
reason: "RequestParseError",
description: "Not an upgradeable ServerRequest"
})
)
}
}
/**
* @since 4.0.0
* @category conversions
*/
export const toURL = (self: HttpServerRequest): Option.Option<URL> => {
const host = self.headers.host ?? "localhost"
const protocol = self.headers["x-forwarded-proto"] === "https" ? "https" : "http"
try {
return Option.some(new URL(self.url, `${protocol}://${host}`))
} catch {
return Option.none()
}
}
@@ -0,0 +1,74 @@
/**
* @since 4.0.0
*/
import * as Cause from "../../Cause.js"
import * as Effect from "../../Effect.js"
import { hasProperty } from "../../Predicate.js"
import * as Schema from "../../schema/Schema.js"
import type { HttpServerResponse } from "./HttpServerResponse.js"
import * as Response from "./HttpServerResponse.js"
/**
* @since 4.0.0
* @category symbols
*/
export const symbol: "~effect/http/HttpServerRespondable" = "~effect/http/HttpServerRespondable" as const
/**
* @since 4.0.0
* @category models
*/
export interface Respondable {
readonly [symbol]: () => Effect.Effect<HttpServerResponse, unknown>
}
/**
* @since 4.0.0
* @category guards
*/
export const isRespondable = (u: unknown): u is Respondable => hasProperty(u, symbol)
const badRequest = Response.empty({ status: 400 })
const notFound = Response.empty({ status: 404 })
/**
* @since 4.0.0
* @category accessors
*/
export const toResponse = (self: Respondable): Effect.Effect<HttpServerResponse> => {
if (Response.isHttpServerResponse(self)) {
return Effect.succeed(self)
}
return Effect.orDie(self[symbol]())
}
/**
* @since 4.0.0
* @category accessors
*/
export const toResponseOrElse = (u: unknown, orElse: HttpServerResponse): Effect.Effect<HttpServerResponse> => {
if (Response.isHttpServerResponse(u)) {
return Effect.succeed(u)
} else if (isRespondable(u)) {
return Effect.catchCause(u[symbol](), () => Effect.succeed(orElse))
// add support for some commmon types
} else if (u instanceof Schema.SchemaError) {
return Effect.succeed(badRequest)
} else if (Cause.isNoSuchElementError(u)) {
return Effect.succeed(notFound)
}
return Effect.succeed(orElse)
}
/**
* @since 4.0.0
* @category accessors
*/
export const toResponseOrElseDefect = (u: unknown, orElse: HttpServerResponse): Effect.Effect<HttpServerResponse> => {
if (Response.isHttpServerResponse(u)) {
return Effect.succeed(u)
} else if (isRespondable(u)) {
return Effect.catchCause(u[symbol](), () => Effect.succeed(orElse))
}
return Effect.succeed(orElse)
}
@@ -0,0 +1,706 @@
/**
* @since 4.0.0
*/
import * as Effect from "../../Effect.js"
import type * as FileSystem from "../../FileSystem.js"
import { dual } from "../../Function.js"
import { ServiceMap } from "../../index.js"
import * as Inspectable from "../../Inspectable.js"
import { PipeInspectableProto } from "../../internal/core.js"
import type { Pipeable } from "../../Pipeable.js"
import type { PlatformError } from "../../PlatformError.js"
import { hasProperty } from "../../Predicate.js"
import type { ParseOptions } from "../../schema/AST.js"
import type * as Schema from "../../schema/Schema.js"
import * as Stream from "../../Stream.js"
import type { Mutable } from "../../Types.js"
import * as Cookies from "./Cookies.js"
import * as Headers from "./Headers.js"
import * as Body from "./HttpBody.js"
import { HttpPlatform } from "./HttpPlatform.js"
import * as Template from "./Template.js"
import * as UrlParams from "./UrlParams.js"
/**
* @since 4.0.0
* @category type ids
*/
export const TypeId: TypeId = "~effect/http/HttpServerResponse"
/**
* @since 4.0.0
* @category type ids
*/
export type TypeId = "~effect/http/HttpServerResponse"
/**
* @since 4.0.0
* @category models
*/
export interface HttpServerResponse extends Inspectable.Inspectable, Pipeable {
readonly [TypeId]: TypeId
readonly status: number
readonly statusText?: string | undefined
readonly headers: Headers.Headers
readonly cookies: Cookies.Cookies
readonly body: Body.HttpBody
}
/**
* @since 4.0.0
* @category models
*/
export interface Options {
readonly status?: number | undefined
readonly statusText?: string | undefined
readonly headers?: Headers.Input | undefined
readonly cookies?: Cookies.Cookies | undefined
readonly contentType?: string | undefined
readonly contentLength?: number | undefined
}
/**
* @since 4.0.0
*/
export declare namespace Options {
/**
* @since 4.0.0
* @category models
*/
export interface WithContent extends Omit<Options, "contentType" | "contentLength"> {}
/**
* @since 4.0.0
* @category models
*/
export interface WithContentType extends Omit<Options, "contentLength"> {}
}
/**
* @since 4.0.0
*/
export const isHttpServerResponse = (u: unknown): u is HttpServerResponse => hasProperty(u, TypeId)
/**
* @since 4.0.0
* @category constructors
*/
export const empty = (options?: Options.WithContent | undefined): HttpServerResponse =>
makeResponse({
status: options?.status ?? 204,
statusText: options?.statusText
})
/**
* @since 4.0.0
* @category constructors
*/
export const redirect = (location: string | URL, options?: Options.WithContentType | undefined): HttpServerResponse => {
const headers = Headers.unsafeFromRecord({ location: location.toString() })
return makeResponse({
status: options?.status ?? 302,
statusText: options?.statusText,
headers: options?.headers ?
Headers.merge(headers, Headers.fromInput(options.headers)) :
headers,
cookies: options?.cookies ?? Cookies.empty
})
}
/**
* @since 4.0.0
* @category constructors
*/
export const uint8Array = (
body: Uint8Array,
options?: Options.WithContentType
): HttpServerResponse => {
const headers = options?.headers ? Headers.fromInput(options.headers) : Headers.empty
return makeResponse({
status: options?.status ?? 200,
statusText: options?.statusText,
headers,
cookies: options?.cookies ?? Cookies.empty,
body: Body.uint8Array(body, getContentType(options, headers))
})
}
const getContentType = (
options: Options | undefined,
headers: Headers.Headers
): string | undefined => {
if (options?.contentType) {
return options.contentType
} else if (options?.headers) {
return headers["content-type"]
}
}
/**
* @since 4.0.0
* @category constructors
*/
export const text = (
body: string,
options?: Options.WithContentType
): HttpServerResponse => {
const headers = options?.headers ? Headers.fromInput(options.headers) : Headers.empty
return makeResponse({
status: options?.status ?? 200,
statusText: options?.statusText,
headers,
cookies: options?.cookies ?? Cookies.empty,
body: Body.text(body, getContentType(options, headers))
})
}
/**
* @since 4.0.0
* @category constructors
*/
export const html: {
<A extends ReadonlyArray<Template.Interpolated>>(
strings: TemplateStringsArray,
...args: A
): Effect.Effect<
HttpServerResponse,
Template.Interpolated.Error<A[number]>,
Template.Interpolated.Context<A[number]>
>
(html: string): HttpServerResponse
} = (
strings: TemplateStringsArray | string,
...args: ReadonlyArray<Template.Interpolated>
) => {
if (typeof strings === "string") {
return text(strings, { contentType: "text/html" })
}
return Effect.map(
Template.make(strings, ...args),
(_) => text(_, { contentType: "text/html" })
) as any
}
/**
* @since 4.0.0
* @category constructors
*/
export const htmlStream = <A extends ReadonlyArray<Template.InterpolatedWithStream>>(
strings: TemplateStringsArray,
...args: A
): Effect.Effect<
HttpServerResponse,
never,
Template.Interpolated.Context<A[number]>
> =>
Effect.map(
Effect.services<Template.Interpolated.Context<A[number]>>(),
(context) =>
stream(
Stream.provideServices(
Stream.encodeText(Template.stream(strings, ...args)),
context
),
{ contentType: "text/html" }
)
)
/**
* @since 4.0.0
* @category constructors
*/
export const json = (
body: unknown,
options?: Options.WithContent | undefined
): Effect.Effect<HttpServerResponse, Body.HttpBodyError> =>
Effect.map(Body.json(body), (body) =>
makeResponse({
status: options?.status ?? 200,
statusText: options?.statusText,
headers: options?.headers && Headers.fromInput(options.headers),
cookies: options?.cookies,
body
}))
/**
* @since 4.0.0
* @category constructors
*/
export const schemaJson = <A, I, RD, RE>(
schema: Schema.Codec<A, I, RD, RE>,
options?: ParseOptions | undefined
) => {
const encode = Body.jsonSchema(schema, options)
return (
body: A,
options?: Options.WithContent | undefined
): Effect.Effect<HttpServerResponse, Body.HttpBodyError, RE> =>
Effect.map(encode(body), (body) =>
makeResponse({
status: options?.status ?? 200,
statusText: options?.statusText,
headers: options?.headers && Headers.fromInput(options.headers),
cookies: options?.cookies,
body
}))
}
/**
* @since 4.0.0
* @category constructors
*/
export const unsafeJson = (
body: unknown,
options?: Options.WithContent | undefined
): HttpServerResponse =>
makeResponse({
status: options?.status ?? 200,
statusText: options?.statusText,
headers: options?.headers && Headers.fromInput(options.headers),
cookies: options?.cookies,
body: Body.unsafeJson(body)
})
/**
* @since 4.0.0
* @category constructors
*/
export const urlParams = (
body: UrlParams.Input,
options?: Options.WithContent | undefined
): HttpServerResponse =>
makeResponse({
status: options?.status ?? 200,
statusText: options?.statusText,
headers: options?.headers && Headers.fromInput(options.headers),
cookies: options?.cookies,
body: Body.text(UrlParams.toString(UrlParams.fromInput(body)), "application/x-www-form-urlencoded")
})
/**
* @since 4.0.0
* @category constructors
*/
export const raw = (body: unknown, options?: Options | undefined): HttpServerResponse =>
makeResponse({
status: options?.status ?? 200,
statusText: options?.statusText,
headers: options?.headers && Headers.fromInput(options.headers),
cookies: options?.cookies,
body: Body.raw(body, {
contentType: options?.contentType,
contentLength: options?.contentLength
})
})
/**
* @since 4.0.0
* @category constructors
*/
export const formData = (
body: FormData,
options?: Options.WithContent | undefined
): HttpServerResponse =>
makeResponse({
status: options?.status ?? 200,
statusText: options?.statusText,
headers: options?.headers && Headers.fromInput(options.headers),
cookies: options?.cookies,
body: Body.formData(body)
})
/**
* @since 4.0.0
* @category constructors
*/
export const stream = <E>(
body: Stream.Stream<Uint8Array, E>,
options?: Options | undefined
): HttpServerResponse => {
const headers = options?.headers ? Headers.fromInput(options.headers) : Headers.empty
return makeResponse({
status: options?.status ?? 200,
statusText: options?.statusText,
headers,
cookies: options?.cookies,
body: Body.stream(body, getContentType(options, headers), options?.contentLength)
})
}
/**
* @since 4.0.0
* @category constructors
*/
export const file = (
path: string,
options?: (Options & FileSystem.StreamOptions) | undefined
): Effect.Effect<HttpServerResponse, PlatformError, HttpPlatform> =>
Effect.flatMap(
HttpPlatform.asEffect(),
(platform) => platform.fileResponse(path, options)
)
/**
* @since 4.0.0
* @category constructors
*/
export const fileWeb = (
file: Body.HttpBody.FileLike,
options?: (Options.WithContent & FileSystem.StreamOptions) | undefined
): Effect.Effect<HttpServerResponse, never, HttpPlatform> =>
Effect.flatMap(
HttpPlatform.asEffect(),
(platform) => platform.fileWebResponse(file, options)
)
/**
* @since 4.0.0
* @category combinators
*/
export const setHeader: {
(key: string, value: string): (self: HttpServerResponse) => HttpServerResponse
(self: HttpServerResponse, key: string, value: string): HttpServerResponse
} = dual(3, (self: HttpServerResponse, key: string, value: string): HttpServerResponse =>
makeResponse({
...self,
headers: Headers.set(self.headers, key, value)
}))
/**
* @since 4.0.0
* @category combinators
*/
export const setHeaders: {
(input: Headers.Input): (self: HttpServerResponse) => HttpServerResponse
(self: HttpServerResponse, input: Headers.Input): HttpServerResponse
} = dual(2, (self: HttpServerResponse, input: Headers.Input): HttpServerResponse =>
makeResponse({
...self,
headers: Headers.setAll(self.headers, input)
}))
/**
* @since 4.0.0
* @category combinators
*/
export const removeCookie: {
(name: string): (self: HttpServerResponse) => HttpServerResponse
(self: HttpServerResponse, name: string): HttpServerResponse
} = dual(2, (self: HttpServerResponse, name: string): HttpServerResponse =>
makeResponse({
...self,
cookies: Cookies.remove(self.cookies, name)
}))
/**
* @since 4.0.0
* @category combinators
*/
export const replaceCookies: {
(cookies: Cookies.Cookies): (self: HttpServerResponse) => HttpServerResponse
(self: HttpServerResponse, cookies: Cookies.Cookies): HttpServerResponse
} = dual(
2,
(self: HttpServerResponse, cookies: Cookies.Cookies): HttpServerResponse => makeResponse({ ...self, cookies })
)
/**
* @since 4.0.0
* @category combinators
*/
export const setCookie: {
(
name: string,
value: string,
options?: Cookies.Cookie["options"]
): (
self: HttpServerResponse
) => Effect.Effect<
HttpServerResponse,
Cookies.CookiesError
>
(
self: HttpServerResponse,
name: string,
value: string,
options?: Cookies.Cookie["options"]
): Effect.Effect<
HttpServerResponse,
Cookies.CookiesError
>
} = dual(
(args) => isHttpServerResponse(args[0]),
(self: HttpServerResponse, name: string, value: string, options?: Cookies.Cookie["options"]): Effect.Effect<
HttpServerResponse,
Cookies.CookiesError
> =>
Effect.map(Cookies.set(self.cookies, name, value, options).asEffect(), (cookies) =>
makeResponse({
...self,
cookies
}))
)
/**
* @since 4.0.0
* @category combinators
*/
export const unsafeSetCookie: {
(
name: string,
value: string,
options?: Cookies.Cookie["options"]
): (self: HttpServerResponse) => HttpServerResponse
(
self: HttpServerResponse,
name: string,
value: string,
options?: Cookies.Cookie["options"]
): HttpServerResponse
} = dual(
(args) => isHttpServerResponse(args[0]),
(self: HttpServerResponse, name: string, value: string, options?: Cookies.Cookie["options"]): HttpServerResponse =>
makeResponse({
...self,
cookies: Cookies.unsafeSet(self.cookies, name, value, options)
})
)
/**
* @since 4.0.0
* @category combinators
*/
export const updateCookies: {
(f: (cookies: Cookies.Cookies) => Cookies.Cookies): (self: HttpServerResponse) => HttpServerResponse
(self: HttpServerResponse, f: (cookies: Cookies.Cookies) => Cookies.Cookies): HttpServerResponse
} = dual(
2,
(self: HttpServerResponse, f: (cookies: Cookies.Cookies) => Cookies.Cookies): HttpServerResponse =>
makeResponse({
...self,
cookies: f(self.cookies)
})
)
/**
* @since 4.0.0
* @category combinators
*/
export const mergeCookies: {
(cookies: Cookies.Cookies): (self: HttpServerResponse) => HttpServerResponse
(self: HttpServerResponse, cookies: Cookies.Cookies): HttpServerResponse
} = dual(
2,
(self: HttpServerResponse, cookies: Cookies.Cookies): HttpServerResponse =>
makeResponse({ ...self, cookies: Cookies.merge(self.cookies, cookies) })
)
/**
* @since 4.0.0
* @category combinators
*/
export const setCookies: {
(
cookies: Iterable<
readonly [
name: string,
value: string,
options?: Cookies.Cookie["options"]
]
>
): (self: HttpServerResponse) => Effect.Effect<HttpServerResponse, Cookies.CookiesError, never>
(
self: HttpServerResponse,
cookies: Iterable<
readonly [
name: string,
value: string,
options?: Cookies.Cookie["options"]
]
>
): Effect.Effect<HttpServerResponse, Cookies.CookiesError, never>
} = dual(2, (
self: HttpServerResponse,
cookies: Iterable<
readonly [
name: string,
value: string,
options?: Cookies.Cookie["options"]
]
>
): Effect.Effect<HttpServerResponse, Cookies.CookiesError> =>
Effect.map(Cookies.setAll(self.cookies, cookies).asEffect(), (cookies) =>
makeResponse({
...self,
cookies
})))
/**
* @since 4.0.0
* @category combinators
*/
export const unsafeSetCookies: {
(
cookies: Iterable<
readonly [
name: string,
value: string,
options?: Cookies.Cookie["options"]
]
>
): (self: HttpServerResponse) => HttpServerResponse
(
self: HttpServerResponse,
cookies: Iterable<
readonly [
name: string,
value: string,
options?: Cookies.Cookie["options"]
]
>
): HttpServerResponse
} = dual(2, (
self: HttpServerResponse,
cookies: Iterable<
readonly [
name: string,
value: string,
options?: Cookies.Cookie["options"]
]
>
): HttpServerResponse =>
makeResponse({
...self,
cookies: Cookies.unsafeSetAll(self.cookies, cookies)
}))
/**
* @since 4.0.0
* @category combinators
*/
export const setBody: {
(body: Body.HttpBody): (self: HttpServerResponse) => HttpServerResponse
(self: HttpServerResponse, body: Body.HttpBody): HttpServerResponse
} = dual(2, (self: HttpServerResponse, body: Body.HttpBody): HttpServerResponse => makeResponse({ ...self, body }))
/**
* @since 4.0.0
* @category combinators
*/
export const setStatus: {
(status: number, statusText?: string | undefined): (self: HttpServerResponse) => HttpServerResponse
(self: HttpServerResponse, status: number, statusText?: string | undefined): HttpServerResponse
} = dual(
(args) => isHttpServerResponse(args[0]),
(self: HttpServerResponse, status: number, statusText?: string | undefined): HttpServerResponse =>
makeResponse({
...self,
status,
statusText: statusText ?? self.statusText
})
)
/**
* @since 4.0.0
* @category conversions
*/
export const toWeb = (response: HttpServerResponse, options?: {
readonly withoutBody?: boolean | undefined
readonly services?: ServiceMap.ServiceMap<never> | undefined
}): Response => {
const headers = new globalThis.Headers(response.headers)
if (!Cookies.isEmpty(response.cookies)) {
const toAdd = Cookies.toSetCookieHeaders(response.cookies)
for (const header of toAdd) {
headers.append("set-cookie", header)
}
}
if (options?.withoutBody) {
return new Response(undefined, {
status: response.status,
statusText: response.statusText as string,
headers
})
}
const body = response.body
switch (body._tag) {
case "Empty": {
return new Response(undefined, {
status: response.status,
statusText: response.statusText as string,
headers
})
}
case "Uint8Array":
case "Raw": {
if (body.body instanceof Response) {
for (const [key, value] of headers as any) {
body.body.headers.set(key, value)
}
return body.body
}
return new Response(body.body as any, {
status: response.status,
statusText: response.statusText!,
headers
})
}
case "FormData": {
return new Response(body.formData as any, {
status: response.status,
statusText: response.statusText!,
headers
})
}
case "Stream": {
return new Response(Stream.toReadableStreamWith(body.stream, options?.services ?? ServiceMap.empty()), {
status: response.status,
statusText: response.statusText!,
headers
})
}
}
}
const Proto: Omit<HttpServerResponse, "status" | "statusText" | "headers" | "cookies" | "body"> = {
...PipeInspectableProto,
[TypeId]: TypeId,
toJSON(this: HttpServerResponse) {
return {
_id: "HttpServerResponse",
status: this.status,
statusText: this.statusText,
headers: Inspectable.redact(this.headers),
cookies: this.cookies.toJSON(),
body: this.body.toJSON()
}
}
}
const makeResponse = (options: {
readonly status: number
readonly statusText?: string | undefined
readonly headers?: Headers.Headers | undefined
readonly cookies?: Cookies.Cookies | undefined
readonly body?: Body.HttpBody | undefined
}) => {
const self = Object.create(Proto) as Mutable<HttpServerResponse>
self.status = options.status
self.statusText = options.statusText
self.cookies = options.cookies ?? Cookies.empty
self.body = options.body ?? Body.empty
if (self.body._tag !== "Empty" && (self.body.contentType || self.body.contentLength)) {
const newHeaders = Headers.unsafeFromRecord({ ...options.headers }) as any
if (self.body.contentType) {
newHeaders["content-type"] = self.body.contentType
}
if (self.body.contentLength) {
newHeaders["content-length"] = self.body.contentLength.toString()
}
self.headers = newHeaders
} else {
self.headers = options.headers ?? Headers.empty
}
return self
}
@@ -0,0 +1,617 @@
/**
* @since 4.0.0
*/
import * as Arr from "../../Array.js"
import * as Channel from "../../Channel.js"
import * as Effect from "../../Effect.js"
import * as Exit from "../../Exit.js"
import * as FileSystem from "../../FileSystem.js"
import { constant, dual } from "../../Function.js"
import * as Inspectable from "../../Inspectable.js"
import * as Option from "../../Option.js"
import * as Path from "../../Path.js"
import * as Predicate from "../../Predicate.js"
import * as Pull from "../../Pull.js"
import type { ParseOptions } from "../../schema/AST.js"
import * as Check from "../../schema/Check.js"
import * as Schema from "../../schema/Schema.js"
import * as Transformation from "../../schema/Transformation.js"
import type * as Scope from "../../Scope.js"
import * as ServiceMap from "../../ServiceMap.js"
import * as Stream from "../../Stream.js"
import * as IncomingMessage from "./HttpIncomingMessage.js"
import * as MP from "./Multipasta.js"
/**
* @since 4.0.0
* @category type ids
*/
export const TypeId: TypeId = "~effect/http/Multipart"
/**
* @since 4.0.0
* @category type ids
*/
export type TypeId = "~effect/http/Multipart"
/**
* @since 4.0.0
* @category models
*/
export type Part = Field | File
/**
* @since 4.0.0
*/
export declare namespace Part {
/**
* @since 4.0.0
* @category models
*/
export interface Proto extends Inspectable.Inspectable {
readonly [TypeId]: TypeId
readonly _tag: string
}
}
/**
* @since 4.0.0
* @category models
*/
export interface Field extends Part.Proto {
readonly _tag: "Field"
readonly key: string
readonly contentType: string
readonly value: string
}
/**
* @since 4.0.0
* @category Guards
*/
export const isPart = (u: unknown): u is Part => Predicate.hasProperty(u, TypeId)
/**
* @since 4.0.0
* @category Guards
*/
export const isField = (u: unknown): u is Field => isPart(u) && u._tag === "Field"
/**
* @since 4.0.0
* @category models
*/
export interface File extends Part.Proto {
readonly _tag: "File"
readonly key: string
readonly name: string
readonly contentType: string
readonly content: Stream.Stream<Uint8Array, MultipartError>
readonly contentEffect: Effect.Effect<Uint8Array, MultipartError>
}
/**
* @since 4.0.0
* @category Guards
*/
export const isFile = (u: unknown): u is File => isPart(u) && u._tag === "File"
/**
* @since 4.0.0
* @category models
*/
export interface PersistedFile extends Part.Proto {
readonly _tag: "PersistedFile"
readonly key: string
readonly name: string
readonly contentType: string
readonly path: string
}
/**
* @since 4.0.0
* @category Guards
*/
export const isPersistedFile = (u: unknown): u is PersistedFile =>
Predicate.hasProperty(u, TypeId) && Predicate.isTagged(u, "PersistedFile")
/**
* @since 4.0.0
* @category models
*/
export interface Persisted {
readonly [key: string]: ReadonlyArray<PersistedFile> | ReadonlyArray<string> | string
}
/**
* @since 4.0.0
* @category Errors
*/
export const ErrorTypeId: ErrorTypeId = "~effect/http/Multipart/MultipartError"
/**
* @since 4.0.0
* @category Errors
*/
export type ErrorTypeId = "~effect/http/Multipart/MultipartError"
/**
* @since 4.0.0
* @category Errors
*/
export class MultipartError extends Schema.ErrorClass<MultipartError>(ErrorTypeId)({
_tag: Schema.tag("MultipartError"),
reason: Schema.Literals(["FileTooLarge", "FieldTooLarge", "BodyTooLarge", "TooManyParts", "InternalError", "Parse"]),
cause: Schema.Unknown
}) {
/**
* @since 4.0.0
*/
readonly [ErrorTypeId]: ErrorTypeId = ErrorTypeId
/**
* @since 4.0.0
*/
get message(): string {
return this.reason
}
}
/**
* @since 4.0.0
* @category Schemas
*/
export interface FileSchema extends Schema.declareRefinement<PersistedFile> {}
/**
* @since 4.0.0
* @category Schemas
*/
export const FileSchema: FileSchema = Schema.declareRefinement({
is: isPersistedFile,
annotations: {
identifier: "PersistedFile",
jsonSchema: {
_tag: "override",
override: () => ({
type: "string",
format: "binary"
})
}
}
})
/**
* @since 4.0.0
* @category Schemas
*/
export const FilesSchema: Schema.Array$<FileSchema> = Schema.Array(FileSchema)
/**
* @since 4.0.0
* @category Schemas
*/
export const SingleFileSchema: Schema.decodeTo<
FileSchema,
Schema.Array$<FileSchema>,
never,
never
> = FilesSchema.check(Check.length(1)).pipe(
Schema.decodeTo(
FileSchema,
Transformation.transform({
decode: ([file]) => file,
encode: (file) => [file]
})
)
)
/**
* @since 4.0.0
* @category Schemas
*/
export const schemaPersisted = <A, I extends Partial<Persisted>, RD, RE>(
schema: Schema.Codec<A, I, RD, RE>
): (input: unknown, options?: ParseOptions) => Effect.Effect<A, Schema.SchemaError, RD> =>
Schema.decodeUnknownEffect(schema)
/**
* @since 4.0.0
* @category Schemas
*/
export const schemaJson = <A, I, RD, RE>(schema: Schema.Codec<A, I, RD, RE>, options?: ParseOptions | undefined): {
(
field: string
): (persisted: Persisted) => Effect.Effect<A, Schema.SchemaError, RD>
(
persisted: Persisted,
field: string
): Effect.Effect<A, Schema.SchemaError, RD>
} => {
const fromJson = Schema.fromJsonString(schema)
return dual(2, (persisted: Persisted, field: string): Effect.Effect<A, Schema.SchemaError, RD> =>
Effect.map(
Schema.decodeUnknownEffect(Schema.Struct({ [field]: fromJson }))(persisted, options),
(_) => _[field]
))
}
/**
* @since 4.0.0
* @category Config
*/
export const makeConfig = (
headers: Record<string, string>
): Effect.Effect<MP.BaseConfig> =>
Effect.withFiber((fiber) => {
const mimeTypes = ServiceMap.get(fiber.services, FieldMimeTypes)
return Effect.succeed<MP.BaseConfig>({
headers,
maxParts: Option.getOrUndefined(fiber.getRef(MaxParts)),
maxFieldSize: Number(fiber.getRef(MaxFieldSize)),
maxPartSize: fiber.getRef(MaxFileSize).pipe(Option.map(Number), Option.getOrUndefined),
maxTotalSize: fiber.getRef(IncomingMessage.MaxBodySize).pipe(
Option.map(Number),
Option.getOrUndefined
),
isFile: mimeTypes.length === 0 ? undefined : (info: MP.PartInfo): boolean =>
!mimeTypes.some(
(_) => info.contentType.includes(_)
) && MP.defaultIsFile(info)
})
})
/**
* @since 4.0.0
* @category Parsers
*/
export const makeChannel = <IE>(headers: Record<string, string>): Channel.Channel<
Arr.NonEmptyReadonlyArray<Part>,
MultipartError | IE,
void,
Arr.NonEmptyReadonlyArray<Uint8Array>,
IE,
unknown
> =>
Channel.fromTransform((upstream) =>
Effect.map(makeConfig(headers), (config) => {
let partsBuffer: Array<Part> = []
let exit = Option.none<Exit.Exit<never, IE | MultipartError | Pull.Halt<void>>>()
const parser = MP.make({
...config,
onField(info, value) {
partsBuffer.push(new FieldImpl(info.name, info.contentType, MP.decodeField(info, value)))
},
onFile(info) {
let chunks: Array<Uint8Array> = []
let finished = false
const pullChunks = Channel.fromPull(
Effect.succeed(Effect.suspend(function loop(): Pull.Pull<Arr.NonEmptyReadonlyArray<Uint8Array>> {
if (!Arr.isNonEmptyReadonlyArray(chunks)) {
return finished ? Pull.haltVoid : Effect.flatMap(pump, loop)
}
const chunk = chunks
chunks = []
return Effect.succeed(chunk)
}))
)
partsBuffer.push(new FileImpl(info, pullChunks))
return function(chunk) {
if (chunk === null) {
finished = true
} else {
chunks.push(chunk)
}
}
},
onError(error_) {
exit = Option.some(Exit.fail(convertError(error_)))
},
onDone() {
exit = Option.some(Exit.fail(new Pull.Halt(void 0)))
}
})
const pump = upstream.pipe(
Effect.flatMap((chunk) => {
for (let i = 0; i < chunk.length; i++) {
parser.write(chunk[i])
}
return Effect.void
}),
Effect.catchCause((cause) => {
if (Pull.isHaltCause(cause)) {
parser.end()
} else {
exit = Option.some(Exit.failCause(cause)) as any
}
return Effect.void
})
)
return pump.pipe(
Effect.flatMap(function loop(): Pull.Pull<Arr.NonEmptyReadonlyArray<Part>, IE | MultipartError> {
if (!Arr.isNonEmptyReadonlyArray(partsBuffer)) {
if (Option.isSome(exit)) {
return exit.value
}
return Effect.flatMap(pump, loop)
}
const parts = partsBuffer
partsBuffer = []
return Effect.succeed(parts)
})
)
})
)
function convertError(cause: MP.MultipartError): MultipartError {
switch (cause._tag) {
case "ReachedLimit": {
switch (cause.limit) {
case "MaxParts": {
return new MultipartError({ reason: "TooManyParts", cause })
}
case "MaxFieldSize": {
return new MultipartError({ reason: "FieldTooLarge", cause })
}
case "MaxPartSize": {
return new MultipartError({ reason: "FileTooLarge", cause })
}
case "MaxTotalSize": {
return new MultipartError({ reason: "BodyTooLarge", cause })
}
}
}
default: {
return new MultipartError({ reason: "Parse", cause })
}
}
}
abstract class PartBase extends Inspectable.Class {
readonly [TypeId]: TypeId
constructor() {
super()
this[TypeId] = TypeId
}
}
class FieldImpl extends PartBase implements Field {
readonly _tag = "Field"
constructor(
readonly key: string,
readonly contentType: string,
readonly value: string
) {
super()
}
toJSON(): unknown {
return {
_id: "@effect/platform/Multipart/Part",
_tag: "Field",
key: this.key,
contentType: this.contentType,
value: this.value
}
}
}
class FileImpl extends PartBase implements File {
readonly _tag = "File"
readonly key: string
readonly name: string
readonly contentType: string
readonly content: Stream.Stream<Uint8Array, MultipartError>
readonly contentEffect: Effect.Effect<Uint8Array, MultipartError>
constructor(
info: MP.PartInfo,
channel: Channel.Channel<Arr.NonEmptyReadonlyArray<Uint8Array>>
) {
super()
this.key = info.name
this.name = info.filename ?? info.name
this.contentType = info.contentType
this.content = Stream.fromChannel(channel)
this.contentEffect = channel.pipe(
collectUint8Array,
Effect.mapError((cause) => new MultipartError({ reason: "InternalError", cause }))
)
}
toJSON(): unknown {
return {
_id: "@effect/platform/Multipart/Part",
_tag: "File",
key: this.key,
name: this.name,
contentType: this.contentType
}
}
}
const defaultWriteFile = (path: string, file: File) =>
Effect.flatMap(
FileSystem.FileSystem.asEffect(),
(fs) =>
Effect.mapError(
Stream.run(file.content, fs.sink(path)),
(cause) => new MultipartError({ reason: "InternalError", cause })
)
)
/**
* @since 4.0.0
*/
export const collectUint8Array = <OE, OD, R>(
self: Channel.Channel<Arr.NonEmptyReadonlyArray<Uint8Array>, OE, OD, unknown, unknown, unknown, R>
): Effect.Effect<Uint8Array<ArrayBuffer>, OE, R> =>
Channel.runFold(self, constant(new Uint8Array(0)), (accumulator, chunk) => {
const totalLength = chunk.reduce((sum, element) => sum + element.length, accumulator.length)
const newAccumulator = new Uint8Array(totalLength)
newAccumulator.set(accumulator, 0)
let offset = accumulator.length
for (const element of chunk) {
newAccumulator.set(element, offset)
offset += element.length
}
return newAccumulator
})
/**
* @since 4.0.0
* @category Conversions
*/
export const toPersisted = (
stream: Stream.Stream<Part, MultipartError>,
writeFile = defaultWriteFile
): Effect.Effect<Persisted, MultipartError, FileSystem.FileSystem | Path.Path | Scope.Scope> =>
Effect.gen(function*() {
const fs = yield* FileSystem.FileSystem
const path_ = yield* Path.Path
const dir = yield* fs.makeTempDirectoryScoped()
const persisted: Record<string, Array<PersistedFile> | Array<string> | string> = Object.create(null)
yield* Stream.runForEach(stream, (part) => {
if (part._tag === "Field") {
if (!(part.key in persisted)) {
persisted[part.key] = part.value
} else if (typeof persisted[part.key] === "string") {
persisted[part.key] = [persisted[part.key] as string, part.value]
} else {
;(persisted[part.key] as Array<string>).push(part.value)
}
return Effect.void
} else if (part.name === "") {
return Effect.void
}
const file = part
const path = path_.join(dir, path_.basename(file.name).slice(-128))
const filePart = new PersistedFileImpl(
file.key,
file.name,
file.contentType,
path
)
if (Array.isArray(persisted[part.key])) {
;(persisted[part.key] as Array<PersistedFile>).push(filePart)
} else {
persisted[part.key] = [filePart]
}
return writeFile(path, file)
})
return persisted
}).pipe(
Effect.catchTags({
SystemError: (cause) => Effect.fail(new MultipartError({ reason: "InternalError", cause })),
BadArgument: (cause) => Effect.fail(new MultipartError({ reason: "InternalError", cause }))
})
)
class PersistedFileImpl extends PartBase implements PersistedFile {
readonly _tag = "PersistedFile"
constructor(
readonly key: string,
readonly name: string,
readonly contentType: string,
readonly path: string
) {
super()
}
toJSON(): unknown {
return {
_id: "@effect/platform/Multipart/Part",
_tag: "PersistedFile",
key: this.key,
name: this.name,
contentType: this.contentType,
path: this.path
}
}
}
/**
* @since 4.0.0
* @category References
*/
export const limitsServices = (options: {
readonly maxParts?: Option.Option<number> | undefined
readonly maxFieldSize?: FileSystem.SizeInput | undefined
readonly maxFileSize?: Option.Option<FileSystem.SizeInput> | undefined
readonly maxTotalSize?: Option.Option<FileSystem.SizeInput> | undefined
readonly fieldMimeTypes?: ReadonlyArray<string> | undefined
}): ServiceMap.ServiceMap<never> => {
const map = new Map<string, unknown>()
if (options.maxParts !== undefined) {
map.set(MaxParts.key, options.maxParts)
}
if (options.maxFieldSize !== undefined) {
map.set(MaxFieldSize.key, FileSystem.Size(options.maxFieldSize))
}
if (options.maxFileSize !== undefined) {
map.set(MaxFileSize.key, Option.map(options.maxFileSize, FileSystem.Size))
}
if (options.maxTotalSize !== undefined) {
map.set(IncomingMessage.MaxBodySize.key, Option.map(options.maxTotalSize, FileSystem.Size))
}
if (options.fieldMimeTypes !== undefined) {
map.set(FieldMimeTypes.key, options.fieldMimeTypes)
}
return ServiceMap.unsafeMake(map)
}
/**
* @since 4.0.0
* @category fiber refs
*/
export declare namespace withLimits {
/**
* @since 4.0.0
* @category fiber refs
*/
export type Options = {
readonly maxParts?: Option.Option<number> | undefined
readonly maxFieldSize?: FileSystem.SizeInput | undefined
readonly maxFileSize?: Option.Option<FileSystem.SizeInput> | undefined
readonly maxTotalSize?: Option.Option<FileSystem.SizeInput> | undefined
readonly fieldMimeTypes?: ReadonlyArray<string> | undefined
}
}
/**
* @since 4.0.0
* @category References
*/
export const MaxParts = ServiceMap.Reference<Option.Option<number>>("effect/http/Multipart/MaxParts", {
defaultValue: Option.none<number>
})
/**
* @since 4.0.0
* @category References
*/
export const MaxFieldSize = ServiceMap.Reference<FileSystem.SizeInput>("effect/http/Multipart/MaxFieldSize", {
defaultValue: constant(FileSystem.Size(10 * 1024 * 1024))
})
/**
* @since 4.0.0
* @category References
*/
export const MaxFileSize = ServiceMap.Reference<Option.Option<FileSystem.SizeInput>>(
"effect/http/Multipart/MaxFileSize",
{ defaultValue: Option.none<FileSystem.SizeInput> }
)
/**
* @since 4.0.0
* @category References
*/
export const FieldMimeTypes = ServiceMap.Reference<ReadonlyArray<string>>("effect/http/Multipart/FieldMimeTypes", {
defaultValue: constant(["application/json"])
})
@@ -0,0 +1,9 @@
/**
* @since 4.0.0
*/
/**
* @since 4.0.0
* @category re-exports
*/
export * from "multipasta"
@@ -0,0 +1,203 @@
/**
* @since 4.0.0
*/
import * as Effect from "../../Effect.js"
import * as Exit from "../../Exit.js"
import * as Option from "../../Option.js"
import * as Stream from "../../Stream.js"
/**
* @category models
* @since 4.0.0
*/
export type PrimitiveValue = string | number | bigint | boolean | null | undefined
/**
* @category models
* @since 4.0.0
*/
export type Primitive = PrimitiveValue | ReadonlyArray<PrimitiveValue>
/**
* @category models
* @since 4.0.0
*/
export type Interpolated =
| Primitive
| Option.Option<Primitive>
| Effect.Effect<Primitive, any, any>
/**
* @category models
* @since 4.0.0
*/
export type InterpolatedWithStream = Interpolated | Stream.Stream<Primitive, any, any>
/**
* @category models
* @since 4.0.0
*/
export declare namespace Interpolated {
/**
* @category models
* @since 4.0.0
*/
export type Context<A> = A extends infer T ? T extends Option.Option<infer _> ? never
: T extends Effect.Effect<infer _A, infer _E, infer R> ? R
: T extends Stream.Stream<infer _A, infer _E, infer R> ? R
: never
: never
/**
* @category models
* @since 4.0.0
*/
export type Error<A> = A extends infer T ? T extends Option.Option<infer _> ? never
: T extends Stream.Stream<infer _A, infer E, infer _R> ? E
: T extends Effect.Effect<infer _A, infer E, infer _R> ? E
: never
: never
}
/**
* @category constructors
* @since 4.0.0
*/
export function make<A extends ReadonlyArray<Interpolated>>(
strings: TemplateStringsArray,
...args: A
): Effect.Effect<
string,
Interpolated.Error<A[number]>,
Interpolated.Context<A[number]>
> {
const argsLength = args.length
const values = new Array<string>(argsLength)
const effects: Array<
[index: number, effect: Effect.Effect<Primitive, any, any>]
> = []
for (let i = 0; i < argsLength; i++) {
const arg = args[i]
if (Option.isOption(arg)) {
values[i] = arg._tag === "Some" ? primitiveToString(arg.value) : ""
} else if (isSuccess(arg)) {
values[i] = primitiveToString(arg.value)
} else if (Effect.isEffect(arg)) {
effects.push([i, arg])
} else {
values[i] = primitiveToString(arg)
}
}
if (effects.length === 0) {
return Effect.succeed(consolidate(strings, values))
}
return Effect.map(
Effect.forEach(
effects,
([index, effect]) =>
Effect.tap(effect, (value) => {
values[index] = primitiveToString(value)
}),
{
concurrency: "inherit",
discard: true
}
),
(_) => consolidate(strings, values)
)
}
/**
* @category constructors
* @since 4.0.0
*/
export function stream<A extends ReadonlyArray<InterpolatedWithStream>>(
strings: TemplateStringsArray,
...args: A
): Stream.Stream<
string,
Interpolated.Error<A[number]>,
Interpolated.Context<A[number]>
> {
const chunks: Array<string | Stream.Stream<string, any, any> | Effect.Effect<string, any, any>> = []
let buffer = ""
for (let i = 0, len = args.length; i < len; i++) {
buffer += strings[i]
const arg = args[i]
if (Option.isOption(arg)) {
buffer += arg._tag === "Some" ? primitiveToString(arg.value) : ""
} else if (isSuccess(arg)) {
buffer += primitiveToString(arg.value)
} else if (Effect.isEffect(arg)) {
if (buffer.length > 0) {
chunks.push(buffer)
buffer = ""
}
chunks.push(Effect.map(arg, primitiveToString))
} else if (Stream.isStream(arg)) {
if (buffer.length > 0) {
chunks.push(buffer)
buffer = ""
}
chunks.push(Stream.map(arg, primitiveToString))
} else {
buffer += primitiveToString(arg)
}
}
buffer += strings[strings.length - 1]
if (buffer.length > 0) {
chunks.push(buffer)
buffer = ""
}
return Stream.flatMap(
Stream.fromIterable(chunks),
(chunk) =>
typeof chunk === "string" ? Stream.succeed(chunk) : Effect.isEffect(chunk) ? Stream.fromEffect(chunk) : chunk,
{ concurrency: "unbounded" }
)
}
function primitiveToString(value: Primitive): string {
if (Array.isArray(value)) {
return value.map(primitiveToString).join("")
}
switch (typeof value) {
case "string": {
return value
}
case "number":
case "bigint": {
return value.toString()
}
case "boolean": {
return value ? "true" : "false"
}
default: {
return ""
}
}
}
function consolidate(
strings: ReadonlyArray<string>,
values: ReadonlyArray<string>
): string {
let out = ""
for (let i = 0, len = values.length; i < len; i++) {
out += strings[i]
out += values[i]
}
return out + strings[strings.length - 1]
}
function isSuccess(u: unknown): u is Exit.Success<Primitive, never> {
return Exit.isExit(u) && u._tag === "Success"
}
@@ -7,11 +7,21 @@
*/
export * as Cookies from "./Cookies.js"
/**
* @since 4.0.0
*/
export * as Etag from "./Etag.js"
/**
* @since 1.0.0
*/
export * as FetchHttpClient from "./FetchHttpClient.js"
/**
* @since 4.0.0
*/
export * as FindMyWay from "./FindMyWay.js"
/**
* @since 4.0.0
*/
@@ -42,6 +52,11 @@ export * as HttpClientRequest from "./HttpClientRequest.js"
*/
export * as HttpClientResponse from "./HttpClientResponse.js"
/**
* @since 4.0.0
*/
export * as HttpEffect from "./HttpEffect.js"
/**
* @since 4.0.0
*/
@@ -52,11 +67,66 @@ export * as HttpIncomingMessage from "./HttpIncomingMessage.js"
*/
export * as HttpMethod from "./HttpMethod.js"
/**
* @since 4.0.0
*/
export * as HttpMiddleware from "./HttpMiddleware.js"
/**
* @since 4.0.0
*/
export * as HttpPlatform from "./HttpPlatform.js"
/**
* @since 4.0.0
*/
export * as HttpRouter from "./HttpRouter.js"
/**
* @since 4.0.0
*/
export * as HttpServer from "./HttpServer.js"
/**
* @since 4.0.0
*/
export * as HttpServerError from "./HttpServerError.js"
/**
* @since 4.0.0
*/
export * as HttpServerRequest from "./HttpServerRequest.js"
/**
* @since 4.0.0
*/
export * as HttpServerRespondable from "./HttpServerRespondable.js"
/**
* @since 4.0.0
*/
export * as HttpServerResponse from "./HttpServerResponse.js"
/**
* @since 4.0.0
*/
export * as HttpTraceContext from "./HttpTraceContext.js"
/**
* @since 4.0.0
*/
export * as Multipart from "./Multipart.js"
/**
* @since 4.0.0
*/
export * as Multipasta from "./Multipasta.js"
/**
* @since 4.0.0
*/
export * as Template from "./Template.js"
/**
* @since 4.0.0
*/
@@ -0,0 +1,49 @@
import { describe, it, test } from "@effect/vitest"
import { strictEqual } from "@effect/vitest/utils"
import { Effect, Layer, ManagedRuntime, ServiceMap } from "effect"
describe("ManagedRuntime", () => {
test("memoizes the layer build", async () => {
let count = 0
const layer = Layer.effectDiscard(Effect.sync(() => {
count++
}))
const runtime = ManagedRuntime.make(layer)
await runtime.runPromise(Effect.void)
await runtime.runPromise(Effect.void)
await runtime.dispose()
strictEqual(count, 1)
})
test("provides context", async () => {
const tag = ServiceMap.Key<string>("string")
const layer = Layer.succeed(tag, "test")
const runtime = ManagedRuntime.make(layer)
const result = await runtime.runPromise(tag.asEffect())
await runtime.dispose()
strictEqual(result, "test")
})
test("allows sharing a MemoMap", async () => {
let count = 0
const layer = Layer.effectDiscard(Effect.sync(() => {
count++
}))
const runtimeA = ManagedRuntime.make(layer)
const runtimeB = ManagedRuntime.make(layer, { memoMap: runtimeA.memoMap })
await runtimeA.runPromise(Effect.void)
await runtimeB.runPromise(Effect.void)
await runtimeA.dispose()
await runtimeB.dispose()
strictEqual(count, 1)
})
it("can be built synchronously", () => {
const tag = ServiceMap.Key<string>("string")
const layer = Layer.succeed(tag, "test")
const managedRuntime = ManagedRuntime.make(layer)
const services = Effect.runSync(managedRuntime.servicesEffect)
const result = ServiceMap.get(services, tag)
strictEqual(result, "test")
})
})
+1 -1
View File
@@ -27,7 +27,7 @@ const assertConfigErrors = <A>(
) => {
const configProvider = ConfigProvider.fromEnv({ environment: env })
const result = Effect.runSyncExit(config.parse(configProvider.context()))
assertFailure(result, Cause.fromFailures(errors.flatMap((e) => Cause.fail(e).failures)))
assertFailure(result, Cause.fromFailures(errors.map(Cause.failureFail)))
}
const assertConfig = <A>(
@@ -0,0 +1,39 @@
import { describe, it } from "@effect/vitest"
import { deepStrictEqual } from "@effect/vitest/utils"
import { Effect, identity, Stream, Unify } from "effect"
import * as Multipart from "effect/unstable/http/Multipart"
describe("Multipart", () => {
it.effect("it parses", () =>
Effect.gen(function*() {
const data = new globalThis.FormData()
data.append("foo", "bar")
data.append("test", "ing")
data.append("file", new globalThis.File(["A".repeat(1024 * 1024)], "foo.txt", { type: "text/plain" }))
const response = new Response(data)
const parts = yield* Stream.fromReadableStream({
evaluate: () => response.body!,
onError: identity
}).pipe(
Stream.pipeThroughChannel(Multipart.makeChannel(Object.fromEntries(response.headers))),
Stream.mapEffect((part) => {
return Unify.unify(
part._tag === "File" ?
Effect.zip(
Effect.succeed(part.name),
Stream.mkString(Stream.decodeText(part.content))
) :
Effect.succeed([part.key, part.value] as const)
)
}),
Stream.runCollect
)
deepStrictEqual(parts, [
["foo", "bar"],
["test", "ing"],
["foo.txt", "A".repeat(1024 * 1024)]
])
}))
})
+16
View File
@@ -184,6 +184,12 @@ importers:
fast-check:
specifier: ^4.2.0
version: 4.2.0
find-my-way-ts:
specifier: ^0.1.6
version: 0.1.6
multipasta:
specifier: ^0.2.5
version: 0.2.5
devDependencies:
'@types/node':
specifier: ^24.0.12
@@ -2274,6 +2280,9 @@ packages:
resolution: {integrity: sha512-wXZV5emFEjrridIgED11OoUKLxiYjAcqot/NJdAkOhlJ+vGzwhOAfcG5OX1jP+S0PcjEn8bdMJv+g2jwQ3Onig==}
engines: {node: '>=8'}
find-my-way-ts@0.1.6:
resolution: {integrity: sha512-a85L9ZoXtNAey3Y6Z+eBWW658kO/MwR7zIafkIUPUMf3isZG0NCs2pjW2wtjxAKuJPxMAsHUIP4ZPGv0o5gyTA==}
find-up@3.0.0:
resolution: {integrity: sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==}
engines: {node: '>=6'}
@@ -2977,6 +2986,9 @@ packages:
ms@2.1.3:
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
multipasta@0.2.5:
resolution: {integrity: sha512-c8eMDb1WwZcE02WVjHoOmUVk7fnKU/RmUcosHACglrWAuPQsEJv+E8430sXj6jNc1jHw0zrS16aCjQh4BcEb4A==}
nanoid@3.3.11:
resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==}
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
@@ -6318,6 +6330,8 @@ snapshots:
make-dir: 3.1.0
pkg-dir: 4.2.0
find-my-way-ts@0.1.6: {}
find-up@3.0.0:
dependencies:
locate-path: 3.0.0
@@ -7052,6 +7066,8 @@ snapshots:
ms@2.1.3: {}
multipasta@0.2.5: {}
nanoid@3.3.11: {}
napi-postinstall@0.2.4: {}