/**
* @since 1.0.0
*/
/* eslint-disable @typescript-eslint/no-empty-object-type */
import * as Reactivity from "@effect/experimental/Reactivity"
import * as KeyValueStore from "@effect/platform/KeyValueStore"
import * as Arr from "effect/Array"
import { NoSuchElementException } from "effect/Cause"
import * as Cause from "effect/Cause"
import * as Channel from "effect/Channel"
import * as Chunk from "effect/Chunk"
import * as EffectContext from "effect/Context"
import * as Duration from "effect/Duration"
import * as Effect from "effect/Effect"
import * as Either from "effect/Either"
import * as Exit from "effect/Exit"
import * as Fiber from "effect/Fiber"
import * as FiberId from "effect/FiberId"
import * as FiberRef from "effect/FiberRef"
import type { LazyArg } from "effect/Function"
import { constant, constVoid, dual, pipe } from "effect/Function"
import { globalValue } from "effect/GlobalValue"
import * as Inspectable from "effect/Inspectable"
import * as Layer from "effect/Layer"
import * as MutableHashMap from "effect/MutableHashMap"
import * as Option from "effect/Option"
import { type Pipeable, pipeArguments } from "effect/Pipeable"
import { hasProperty, isObject } from "effect/Predicate"
import type { ReadonlyRecord } from "effect/Record"
import * as Runtime from "effect/Runtime"
import * as Schema from "effect/Schema"
import * as Scope from "effect/Scope"
import * as Stream from "effect/Stream"
import * as Subscribable from "effect/Subscribable"
import * as SubscriptionRef from "effect/SubscriptionRef"
import type { NoInfer } from "effect/Types"
import * as internalRegistry from "./internal/registry.js"
import { runCallbackSync } from "./internal/runtime.js"
import * as Registry from "./Registry.js"
import { AtomRegistry as AtomRegistry } from "./Registry.js"
import * as Result from "./Result.js"
const TypeId: TypeId = "~effect-atom/atom/Atom"
type TypeId = "~effect-atom/atom/Atom"
/**
* @since 1.0.0
* @category models
*/
export interface Atom extends Pipeable, Inspectable.Inspectable {
readonly [TypeId]: TypeId
readonly keepAlive: boolean
readonly lazy: boolean
readonly read: (get: Context) => A
readonly refresh?: (f: (atom: Atom) => void) => void
readonly label?: readonly [name: string, stack: string]
readonly idleTTL?: number
}
/**
* @since 1.0.0
* @category Guards
*/
export const isAtom = (u: unknown): u is Atom => hasProperty(u, TypeId)
/**
* @since 1.0.0
*/
export type Type> = T extends Atom ? A : never
/**
* @since 1.0.0
*/
export type Success> = T extends Atom> ? A : never
/**
* @since 1.0.0
*/
export type PullSuccess> = T extends Atom> ? A : never
/**
* @since 1.0.0
*/
export type Failure> = T extends Atom> ? E : never
/**
* @since 1.0.0
*/
export type WithoutSerializable> = T extends Writable ? Writable
: Atom>
type WritableTypeId = "~effect-atom/atom/Atom/Writable"
const WritableTypeId: WritableTypeId = "~effect-atom/atom/Atom/Writable"
/**
* @since 1.0.0
* @category models
*/
export interface Writable extends Atom {
readonly [WritableTypeId]: WritableTypeId
readonly write: (ctx: WriteContext, value: W) => void
}
/**
* @since 1.0.0
* @category context
*/
export interface Context {
(atom: Atom): A
get(this: Context, atom: Atom): A
result(this: Context, atom: Atom>, options?: {
readonly suspendOnWaiting?: boolean | undefined
}): Effect.Effect
resultOnce(this: Context, atom: Atom>, options?: {
readonly suspendOnWaiting?: boolean | undefined
}): Effect.Effect
once(this: Context, atom: Atom): A
addFinalizer(this: Context, f: () => void): void
mount(this: Context, atom: Atom): void
refresh(this: Context, atom: Atom): void
refreshSelf(this: Context): void
self(this: Context): Option.Option
setSelf(this: Context, a: A): void
set(this: Context, atom: Writable, value: W): void
setResult(this: Context, atom: Writable, W>, value: W): Effect.Effect
some(this: Context, atom: Atom>): Effect.Effect
someOnce(this: Context, atom: Atom>): Effect.Effect
stream(this: Context, atom: Atom, options?: {
readonly withoutInitialValue?: boolean
readonly bufferSize?: number
}): Stream.Stream
streamResult(this: Context, atom: Atom>, options?: {
readonly withoutInitialValue?: boolean
readonly bufferSize?: number
}): Stream.Stream
subscribe(this: Context, atom: Atom, f: (_: A) => void, options?: {
readonly immediate?: boolean
}): void
readonly registry: Registry.Registry
}
/**
* @since 1.0.0
* @category context
*/
export interface WriteContext {
get(this: WriteContext, atom: Atom): T
refreshSelf(this: WriteContext): void
setSelf(this: WriteContext, a: A): void
set(this: WriteContext, atom: Writable, value: W): void
}
/**
* @since 1.0.0
* @category combinators
*/
export const setIdleTTL: {
(duration: Duration.DurationInput): >(self: A) => A
>(self: A, duration: Duration.DurationInput): A
} = dual<
(duration: Duration.DurationInput) => >(self: A) => A,
>(self: A, duration: Duration.DurationInput) => A
>(2, (self, durationInput) => {
const duration = Duration.decode(durationInput)
const isFinite = Duration.isFinite(duration)
return Object.assign(Object.create(Object.getPrototypeOf(self)), {
...self,
keepAlive: !isFinite,
idleTTL: isFinite ? Duration.toMillis(duration) : undefined
})
})
const removeTtl = setIdleTTL(0)
const AtomProto = {
[TypeId]: TypeId,
pipe() {
return pipeArguments(this, arguments)
},
toJSON(this: Atom) {
return {
_id: "Atom",
keepAlive: this.keepAlive,
lazy: this.lazy,
label: this.label
}
},
toString() {
return Inspectable.format(this)
},
[Inspectable.NodeInspectSymbol](this: Atom) {
return this.toJSON()
}
} as const
const RuntimeProto = {
...AtomProto,
atom(this: AtomRuntime, arg: any, options?: { readonly initialValue?: unknown }) {
const read = makeRead(arg, options)
return readable((get) => {
const previous = get.self>()
const runtimeResult = get(this)
if (runtimeResult._tag !== "Success") {
return Result.replacePrevious(runtimeResult, previous)
}
return read(get, runtimeResult.value)
})
},
fn(this: AtomRuntime, arg: any, options?: {
readonly initialValue?: unknown
readonly reactivityKeys?: ReadonlyArray | ReadonlyRecord> | undefined
readonly concurrent?: boolean | undefined
}) {
if (arguments.length === 0) {
return (arg: any, options?: {}) => makeFnRuntime(this, arg, options)
}
return makeFnRuntime(this, arg, options)
},
pull(this: AtomRuntime, arg: any, options?: {
readonly disableAccumulation?: boolean
readonly initialValue?: ReadonlyArray
}) {
const pullSignal = removeTtl(state(0))
const pullAtom = readable((get) => {
const previous = get.self>()
const runtimeResult = get(this)
if (runtimeResult._tag !== "Success") {
return Result.replacePrevious(runtimeResult, previous)
}
return makeEffect(
get,
makeStreamPullEffect(get, pullSignal, arg, options),
Result.initial(true),
runtimeResult.value
)
})
return makeStreamPull(pullSignal, pullAtom)
},
subscriptionRef(this: AtomRuntime, ref: any) {
return makeSubRef(
removeTtl(readable((get) => {
const previous = get.self>()
const runtimeResult = get(this)
if (runtimeResult._tag !== "Success") {
return Result.replacePrevious(runtimeResult, previous)
}
const value = typeof ref === "function" ? ref(get) : ref
return SubscriptionRef.SubscriptionRefTypeId in value
? value
: makeEffect(get, value, Result.initial(true), runtimeResult.value)
})),
(get, ref) => {
const runtime = Result.getOrThrow(get(this))
return readSubscribable(get, ref, runtime)
}
)
},
subscribable(this: AtomRuntime, arg: any) {
return makeSubscribable(
readable((get) => {
const previous = get.self>()
const runtimeResult = get(this)
if (runtimeResult._tag !== "Success") {
return Result.replacePrevious(runtimeResult, previous)
}
const value = typeof arg === "function" ? arg(get) : arg
return Subscribable.isSubscribable(value) ?
value as Subscribable.Subscribable
: makeEffect(get, value, Result.initial(true), runtimeResult.value)
}),
(get, ref) => {
const runtime = Result.getOrThrow(get(this))
return readSubscribable(get, ref, runtime)
}
)
}
}
const makeFnRuntime = (
self: AtomRuntime,
arg: (
arg: any,
get: FnContext
) =>
| Effect.Effect
| Stream.Stream,
options?: {
readonly initialValue?: unknown
readonly reactivityKeys?: ReadonlyArray | ReadonlyRecord> | undefined
}
) => {
const [read, write, argAtom] = makeResultFn(
options?.reactivityKeys ?
((a: any, get: FnContext) => {
const effect = arg(a, get)
return Effect.isEffect(effect)
? Reactivity.mutation(effect, options.reactivityKeys!)
: Stream.ensuring(effect, Reactivity.invalidate(options.reactivityKeys!))
}) as any :
arg,
options
)
return writable((get) => {
get.get(argAtom)
const previous = get.self>()
const runtimeResult = get.get(self)
if (runtimeResult._tag !== "Success") {
return Result.replacePrevious(runtimeResult, previous)
}
return read(get, runtimeResult.value)
}, write)
}
const WritableProto = {
...AtomProto,
[WritableTypeId]: WritableTypeId
} as const
/**
* @since 1.0.0
* @category refinements
*/
export const isWritable = (atom: Atom): atom is Writable => WritableTypeId in atom
/**
* @since 1.0.0
* @category constructors
*/
export const readable = (
read: (get: Context) => A,
refresh?: (f: (atom: Atom) => void) => void
): Atom => {
const self = Object.create(AtomProto)
self.keepAlive = false
self.lazy = true
self.read = read
self.refresh = refresh
return self
}
/**
* @since 1.0.0
* @category constructors
*/
export const writable = (
read: (get: Context) => R,
write: (ctx: WriteContext, value: W) => void,
refresh?: (f: (atom: Atom) => void) => void
): Writable => {
const self = Object.create(WritableProto)
self.keepAlive = false
self.lazy = true
self.read = read
self.write = write
self.refresh = refresh
return self
}
function constSetSelf(ctx: WriteContext, value: A) {
ctx.setSelf(value)
}
// -----------------------------------------------------------------------------
// constructors
// -----------------------------------------------------------------------------
/**
* @since 1.0.0
* @category constructors
*/
export const make: {
(create: (get: Context) => Effect.Effect, options?: {
readonly initialValue?: A
}): Atom>
(effect: Effect.Effect, options?: {
readonly initialValue?: A
}): Atom>
(create: (get: Context) => Stream.Stream, options?: {
readonly initialValue?: A
}): Atom>
(stream: Stream.Stream, options?: {
readonly initialValue?: A
}): Atom>
(create: (get: Context) => A): Atom
(initialValue: A): Writable
} = (arg: any, options?: { readonly initialValue?: unknown }) => {
const readOrAtom = makeRead(arg, options)
if (TypeId in readOrAtom) {
return readOrAtom as any
}
return readable(readOrAtom)
}
// -----------------------------------------------------------------------------
// constructors - effect
// -----------------------------------------------------------------------------
const isDataType = (u: object): u is Option.Option | Either.Either =>
Option.TypeId in u ||
Either.TypeId in u
const makeRead: {
(effect: Effect.Effect, options?: {
readonly initialValue?: A
}): (get: Context, runtime?: Runtime.Runtime) => Result.Result
(create: (get: Context) => Effect.Effect, options?: {
readonly initialValue?: A
}): (get: Context, runtime?: Runtime.Runtime) => Result.Result
(stream: Stream.Stream, options?: {
readonly initialValue?: A
}): (get: Context, runtime?: Runtime.Runtime) => Result.Result
(create: (get: Context) => Stream.Stream, options?: {
readonly initialValue?: A
}): (get: Context, runtime?: Runtime.Runtime) => Result.Result
(create: (get: Context) => A): (get: Context, runtime?: Runtime.Runtime) => A
(initialValue: A): Writable
} = (
arg:
| Effect.Effect
| ((get: Context) => Effect.Effect)
| Stream.Stream
| ((get: Context) => Stream.Stream)
| ((get: Context) => A)
| A,
options?: { readonly initialValue?: unknown }
) => {
if (typeof arg === "function" && !Effect.isEffect(arg) && !(Stream.StreamTypeId in arg)) {
const create = arg as (get: Context) => any
return function(get: Context, providedRuntime?: Runtime.Runtime) {
const value = create(get)
if (isObject(value)) {
if (isDataType(value)) {
return value
} else if (Effect.EffectTypeId in value) {
return effect(get, value as any, options, providedRuntime)
} else if (Stream.StreamTypeId in value) {
return stream(get, value as any, options, providedRuntime)
}
}
return value
}
} else if (isObject(arg)) {
if (isDataType(arg)) {
return state(arg)
} else if (Effect.EffectTypeId in arg) {
return function(get: Context, providedRuntime?: Runtime.Runtime) {
return effect(get, arg as any, options, providedRuntime)
}
} else if (Stream.StreamTypeId in arg) {
return function(get: Context, providedRuntime?: Runtime.Runtime) {
return stream(get, arg as any, options, providedRuntime)
}
}
}
return state(arg) as any
}
const state = (
initialValue: A
): Writable =>
writable(function(_get) {
return initialValue
}, constSetSelf)
const effect = (
get: Context,
effect: Effect.Effect,
options?: { readonly initialValue?: A; readonly uninterruptible?: boolean },
runtime?: Runtime.Runtime
): Result.Result => {
const initialValue = options?.initialValue !== undefined
? Result.success(options.initialValue)
: Result.initial()
return makeEffect(get, effect, initialValue, runtime, options?.uninterruptible)
}
function makeEffect(
ctx: Context,
effect: Effect.Effect,
initialValue: Result.Result,
runtime = Runtime.defaultRuntime,
uninterruptible = false
): Result.Result {
const previous = ctx.self>()
const scope = Effect.runSync(Scope.make())
ctx.addFinalizer(() => {
Effect.runFork(Scope.close(scope, Exit.void))
})
const contextMap = new Map(runtime.context.unsafeMap)
contextMap.set(Scope.Scope.key, scope)
contextMap.set(AtomRegistry.key, ctx.registry)
const scopedRuntime = Runtime.make({
context: EffectContext.unsafeMake(contextMap),
fiberRefs: runtime.fiberRefs,
runtimeFlags: runtime.runtimeFlags
})
let syncResult: Result.Result | undefined
let isAsync = false
const cancel = runCallbackSync(scopedRuntime)(
effect,
function(exit) {
syncResult = Result.fromExitWithPrevious(exit, previous)
if (isAsync) {
ctx.setSelf(syncResult)
}
},
uninterruptible
)
isAsync = true
if (cancel !== undefined) {
ctx.addFinalizer(cancel)
}
if (syncResult !== undefined) {
return syncResult
} else if (previous._tag === "Some") {
return Result.waitingFrom(previous)
}
return Result.waiting(initialValue)
}
// -----------------------------------------------------------------------------
// context
// -----------------------------------------------------------------------------
/**
* @since 1.0.0
* @category models
*/
export interface AtomRuntime extends Atom, ER>> {
readonly factory: RuntimeFactory
readonly layer: Atom>
readonly atom: {
(
create: (get: Context) => Effect.Effect,
options?: {
readonly initialValue?: A
}
): Atom>
(effect: Effect.Effect, options?: {
readonly initialValue?: A
}): Atom>
(create: (get: Context) => Stream.Stream, options?: {
readonly initialValue?: A
}): Atom>
(stream: Stream.Stream, options?: {
readonly initialValue?: A
}): Atom>
}
readonly fn: {
(): {
(
fn: (arg: Arg, get: FnContext) => Effect.Effect,
options?: {
readonly initialValue?: A | undefined
readonly reactivityKeys?: ReadonlyArray | ReadonlyRecord> | undefined
readonly concurrent?: boolean | undefined
}
): AtomResultFn
(
fn: (arg: Arg, get: FnContext) => Stream.Stream,
options?: {
readonly initialValue?: A | undefined
readonly reactivityKeys?: ReadonlyArray | ReadonlyRecord> | undefined
readonly concurrent?: boolean | undefined
}
): AtomResultFn
}
(
fn: (arg: Arg, get: FnContext) => Effect.Effect,
options?: {
readonly initialValue?: A | undefined
readonly reactivityKeys?: ReadonlyArray | ReadonlyRecord> | undefined
readonly concurrent?: boolean | undefined
}
): AtomResultFn
(
fn: (arg: Arg, get: FnContext) => Stream.Stream,
options?: {
readonly initialValue?: A | undefined
readonly reactivityKeys?: ReadonlyArray | ReadonlyRecord> | undefined
readonly concurrent?: boolean | undefined
}
): AtomResultFn
}
readonly pull: (
create:
| ((get: Context) => Stream.Stream)
| Stream.Stream,
options?: {
readonly disableAccumulation?: boolean
readonly initialValue?: ReadonlyArray
}
) => Writable, void>
readonly subscriptionRef: (
create:
| Effect.Effect, E, Scope.Scope | R | AtomRegistry | Reactivity.Reactivity>
| ((
get: Context
) => Effect.Effect, E, Scope.Scope | R | AtomRegistry | Reactivity.Reactivity>)
) => Writable, A>
readonly subscribable: (
create:
| Effect.Effect, E1, Scope.Scope | R | AtomRegistry | Reactivity.Reactivity>
| ((
get: Context
) => Effect.Effect<
Subscribable.Subscribable,
E1,
Scope.Scope | R | AtomRegistry | Reactivity.Reactivity
>)
) => Atom>
}
/**
* @since 1.0.0
* @category models
*/
export interface RuntimeFactory {
(
create:
| Layer.Layer
| ((get: Context) => Layer.Layer)
): AtomRuntime
readonly memoMap: Layer.MemoMap
readonly addGlobalLayer: (layer: Layer.Layer) => void
/**
* Uses the `Reactivity` service from the runtime to refresh the atom whenever
* the keys change.
*/
readonly withReactivity: (
keys: ReadonlyArray | ReadonlyRecord>
) => >(atom: A) => A
}
/**
* @since 1.0.0
* @category constructors
*/
export const context: (options: {
readonly memoMap: Layer.MemoMap
}) => RuntimeFactory = (options) => {
let globalLayer: Layer.Layer = Reactivity.layer
function factory(
create:
| Layer.Layer
| ((get: Context) => Layer.Layer)
): AtomRuntime {
const self = Object.create(RuntimeProto)
self.keepAlive = false
self.lazy = true
self.refresh = undefined
self.factory = factory
const layerAtom = keepAlive(
typeof create === "function"
? readable((get) => Layer.provideMerge(create(get), globalLayer))
: readable(() => Layer.provideMerge(create, globalLayer))
)
self.layer = layerAtom
self.read = function read(get: Context) {
const layer = get(layerAtom)
const build = Effect.flatMap(
Effect.flatMap(Effect.scope, (scope) => Layer.buildWithMemoMap(layer, options.memoMap, scope)),
(context) => Effect.provide(Effect.runtime(), context)
)
return effect(get, build, { uninterruptible: true })
}
return self
}
factory.memoMap = options.memoMap
factory.addGlobalLayer = (layer: Layer.Layer) => {
globalLayer = Layer.provideMerge(globalLayer, Layer.provide(layer, Reactivity.layer))
}
const reactivityAtom = removeTtl(make(
Effect.scopeWith((scope) => Layer.buildWithMemoMap(Reactivity.layer, options.memoMap, scope)).pipe(
Effect.map(EffectContext.get(Reactivity.Reactivity))
)
))
factory.withReactivity =
(keys: ReadonlyArray | ReadonlyRecord>) =>
>(atom: A): A =>
transform(atom, (get) => {
const reactivity = Result.getOrThrow(get(reactivityAtom))
get.addFinalizer(reactivity.unsafeRegister(keys, () => {
get.refresh(atom)
}))
get.subscribe(atom, (value) => get.setSelf(value))
return get.once(atom)
}) as any as A
return factory
}
/**
* @since 1.0.0
* @category context
*/
export const defaultMemoMap: Layer.MemoMap = globalValue(
"@effect-atom/atom/Atom/defaultMemoMap",
() => Effect.runSync(Layer.makeMemoMap)
)
/**
* @since 1.0.0
* @category context
*/
export const runtime: RuntimeFactory = globalValue(
"@effect-atom/atom/Atom/defaultContext",
() => context({ memoMap: defaultMemoMap })
)
/**
* An alias to `Rx.runtime.withReactivity`, for refreshing an atom whenever the
* keys change in the `Reactivity` service.
*
* @since 1.0.0
* @category Reactivity
*/
export const withReactivity: (
keys: ReadonlyArray | ReadonlyRecord>
) => >(atom: A) => A = runtime.withReactivity
// -----------------------------------------------------------------------------
// constructors - stream
// -----------------------------------------------------------------------------
const stream = (
get: Context,
stream: Stream.Stream,
options?: { readonly initialValue?: A },
runtime?: Runtime.Runtime
): Result.Result => {
const initialValue = options?.initialValue !== undefined
? Result.success(options.initialValue)
: Result.initial()
return makeStream(get, stream, initialValue, runtime)
}
function makeStream(
ctx: Context,
stream: Stream.Stream,
initialValue: Result.Result,
runtime = Runtime.defaultRuntime
): Result.Result {
const previous = ctx.self>()
const writer: Channel.Channel, never, E> = Channel.readWithCause({
onInput(input: Chunk.Chunk) {
return Channel.suspend(() => {
const last = Chunk.last(input)
if (last._tag === "Some") {
ctx.setSelf(Result.success(last.value, {
waiting: true
}))
}
return writer
})
},
onFailure(cause: Cause.Cause) {
return Channel.sync(() => {
ctx.setSelf(Result.failureWithPrevious(cause, {
previous: ctx.self>()
}))
})
},
onDone(_done: unknown) {
return Channel.sync(() => {
pipe(
ctx.self>(),
Option.flatMap(Result.value),
Option.match({
onNone: () =>
ctx.setSelf(
Result.failWithPrevious(new NoSuchElementException(), {
previous: ctx.self>()
})
),
onSome: (a) => ctx.setSelf(Result.success(a))
})
)
})
}
})
const registryRuntime = Runtime.make({
context: EffectContext.add(runtime.context, AtomRegistry, ctx.registry),
fiberRefs: runtime.fiberRefs,
runtimeFlags: runtime.runtimeFlags
})
const cancel = runCallbackSync(registryRuntime)(
Channel.runDrain(Channel.pipeTo(Stream.toChannel(stream), writer)),
constVoid,
false
)
if (cancel !== undefined) {
ctx.addFinalizer(cancel)
}
if (previous._tag === "Some") {
return Result.waitingFrom(previous)
}
return Result.waiting(initialValue)
}
// -----------------------------------------------------------------------------
// constructors - subscription ref
// -----------------------------------------------------------------------------
/** @internal */
const readSubscribable = (
get: Context,
sub:
| Subscribable.Subscribable
| Result.Result, any>,
runtime = Runtime.defaultRuntime
) => {
if (Subscribable.TypeId in sub) {
get.addFinalizer(
sub.changes.pipe(
Stream.runForEach((value) => {
get.setSelf(value)
return Effect.void
}),
Runtime.runCallback(runtime)
)
)
return Runtime.runSync(runtime)(sub.get)
} else if (sub._tag !== "Success") {
return sub
}
return makeStream(get, sub.value.changes, Result.initial(true), runtime)
}
const makeSubRef = (
refAtom: Atom | Result.Result, any>>,
read: (
get: Context,
ref: SubscriptionRef.SubscriptionRef | Result.Success, any>
) => any
) => {
function write(ctx: WriteContext>, value: any) {
const ref = ctx.get(refAtom)
if (SubscriptionRef.SubscriptionRefTypeId in ref) {
Effect.runSync(SubscriptionRef.set(ref, value))
} else if (Result.isSuccess(ref)) {
Effect.runSync(SubscriptionRef.set(ref.value, value))
}
}
return writable((get) => {
const ref = get(refAtom)
if (SubscriptionRef.SubscriptionRefTypeId in ref) {
return read(get, ref)
} else if (Result.isSuccess(ref)) {
return read(get, ref)
}
return ref
}, write)
}
/**
* @since 1.0.0
* @category constructors
*/
export const subscriptionRef: {
(ref: SubscriptionRef.SubscriptionRef | ((get: Context) => SubscriptionRef.SubscriptionRef)): Writable
(
effect:
| Effect.Effect, E, Scope.Scope | AtomRegistry>
| ((get: Context) => Effect.Effect, E, Scope.Scope | AtomRegistry>)
): Writable, A>
} = (
ref:
| SubscriptionRef.SubscriptionRef
| ((get: Context) => SubscriptionRef.SubscriptionRef)
| Effect.Effect, any, Scope.Scope | AtomRegistry>
| ((get: Context) => Effect.Effect, any, Scope.Scope | AtomRegistry>)
) =>
makeSubRef(
readable((get) => {
const value = typeof ref === "function" ? ref(get) : ref
return SubscriptionRef.SubscriptionRefTypeId in value
? value
: makeEffect(get, value, Result.initial(true))
}),
readSubscribable
) as any
// -----------------------------------------------------------------------------
// constructors - subscribable
// -----------------------------------------------------------------------------
/**
* @since 1.0.0
* @category constructors
*/
export const subscribable: {
(
ref: Subscribable.Subscribable | ((get: Context) => Subscribable.Subscribable)
): Atom
(
effect:
| Effect.Effect, E, Scope.Scope | AtomRegistry>
| ((get: Context) => Effect.Effect, E, Scope.Scope | AtomRegistry>)
): Atom>
} = (
ref:
| Subscribable.Subscribable
| ((get: Context) => Subscribable.Subscribable)
| Effect.Effect, any, Scope.Scope | AtomRegistry>
| ((get: Context) => Effect.Effect, any, Scope.Scope | AtomRegistry>)
) =>
makeSubscribable(
readable((get) => {
const value = typeof ref === "function" ? ref(get) : ref
return Subscribable.isSubscribable(value)
? value
: makeEffect(get, value, Result.initial(true))
}),
readSubscribable
)
const makeSubscribable = (
subAtom: Atom | Result.Result, any>>,
read: (
get: Context,
sub: Subscribable.Subscribable | Result.Success, any>
) => any
) =>
readable((get) => {
const sub = get(subAtom)
if (Subscribable.isSubscribable(sub)) {
return read(get, sub)
} else if (Result.isSuccess(sub)) {
return read(get, sub)
}
return sub
})
// -----------------------------------------------------------------------------
// constructors - functions
// -----------------------------------------------------------------------------
/**
* @since 1.0.0
* @category models
*/
export interface FnContext {
(atom: Atom): A
result(this: FnContext, atom: Atom>, options?: {
readonly suspendOnWaiting?: boolean | undefined
}): Effect.Effect
addFinalizer(this: FnContext, f: () => void): void
mount(this: FnContext, atom: Atom): void
refresh(this: FnContext, atom: Atom): void
self(this: FnContext): Option.Option
setSelf(this: FnContext, a: A): void
set(this: FnContext, atom: Writable, value: W): void
setResult(this: FnContext, atom: Writable, W>, value: W): Effect.Effect
some(this: FnContext, atom: Atom>): Effect.Effect
stream(this: FnContext, atom: Atom, options?: {
readonly withoutInitialValue?: boolean
readonly bufferSize?: number
}): Stream.Stream
streamResult(this: FnContext, atom: Atom>, options?: {
readonly withoutInitialValue?: boolean
readonly bufferSize?: number
}): Stream.Stream
subscribe(this: FnContext, atom: Atom, f: (_: A) => void, options?: {
readonly immediate?: boolean
}): void
readonly registry: Registry.Registry
}
/**
* @since 1.0.0
* @category constructors
*/
export const fnSync: {
(): {
(
f: (arg: Arg, get: FnContext) => A
): Writable, Arg>
(
f: (arg: Arg, get: FnContext) => A,
options: { readonly initialValue: A }
): Writable
}
(
f: (arg: Arg, get: FnContext) => A
): Writable, Arg>
(
f: (arg: Arg, get: FnContext) => A,
options: { readonly initialValue: A }
): Writable
} = function(...args: ReadonlyArray) {
if (args.length === 0) {
return makeFnSync
}
return makeFnSync(...args as [any, any]) as any
}
const makeFnSync = (f: (arg: Arg, get: FnContext) => A, options?: {
readonly initialValue?: A
}): Writable | A, Arg> => {
const argAtom = removeTtl(state<[number, Arg]>([0, undefined as any]))
const hasInitialValue = options?.initialValue !== undefined
return writable(function(get) {
;(get as any).isFn = true
const [counter, arg] = get.get(argAtom)
if (counter === 0) {
return hasInitialValue ? options.initialValue : Option.none()
}
return hasInitialValue ? f(arg, get) : Option.some(f(arg, get))
}, function(ctx, arg) {
batch(() => {
ctx.set(argAtom, [ctx.get(argAtom)[0] + 1, arg as Arg])
ctx.refreshSelf()
})
})
}
/**
* @since 1.0.0
* @category models
*/
export interface AtomResultFn extends Writable, Arg | Reset | Interrupt> {}
/**
* @since 1.0.0
* @category symbols
*/
export const Reset = Symbol.for("@effect-atom/atom/Atom/Reset")
/**
* @since 1.0.0
* @category symbols
*/
export type Reset = typeof Reset
/**
* @since 1.0.0
* @category symbols
*/
export const Interrupt = Symbol.for("@effect-atom/atom/Atom/Interrupt")
/**
* @since 1.0.0
* @category symbols
*/
export type Interrupt = typeof Interrupt
/**
* @since 1.0.0
* @category constructors
*/
export const fn: {
(): (fn: (arg: Arg, get: FnContext) => Effect.Effect, options?: {
readonly initialValue?: A | undefined
readonly concurrent?: boolean | undefined
}) => AtomResultFn
(fn: (arg: Arg, get: FnContext) => Effect.Effect, options?: {
readonly initialValue?: A | undefined
readonly concurrent?: boolean | undefined
}): AtomResultFn
(): (fn: (arg: Arg, get: FnContext) => Stream.Stream, options?: {
readonly initialValue?: A | undefined
readonly concurrent?: boolean | undefined
}) => AtomResultFn
(fn: (arg: Arg, get: FnContext) => Stream.Stream, options?: {
readonly initialValue?: A | undefined
readonly concurrent?: boolean | undefined
}): AtomResultFn
} = function(...args: ReadonlyArray) {
if (args.length === 0) {
return makeFn
}
return makeFn(...args as [any, any]) as any
}
const makeFn = (
f: (arg: Arg, get: FnContext) => Stream.Stream | Effect.Effect,
options?: {
readonly initialValue?: A | undefined
readonly concurrent?: boolean | undefined
}
): AtomResultFn => {
const [read, write] = makeResultFn(f, options)
return writable(read, write) as any
}
function makeResultFn(
f: (arg: Arg, get: FnContext) => Effect.Effect | Stream.Stream,
options?: {
readonly initialValue?: A
readonly concurrent?: boolean | undefined
}
) {
const argAtom = removeTtl(state<[number, Arg | Interrupt]>([0, undefined as any]))
const initialValue = options?.initialValue !== undefined
? Result.success(options.initialValue)
: Result.initial()
const fibersAtom = options?.concurrent
? removeTtl(readable((get) => {
const fibers = new Set>()
get.addFinalizer(() => fibers.forEach((f) => f.unsafeInterruptAsFork(FiberId.none)))
return fibers
}))
: undefined
function read(get: Context, runtime?: Runtime.Runtime): Result.Result {
const fibers = fibersAtom ? get(fibersAtom) : undefined
;(get as any).isFn = true
const [counter, arg] = get.get(argAtom)
if (counter === 0) {
return initialValue
} else if (arg === Interrupt) {
return Result.failureWithPrevious(Cause.interrupt(FiberId.none), { previous: get.self() })
}
let value = f(arg, get)
if (Effect.EffectTypeId in value) {
if (fibers) {
const eff = value
value = Effect.flatMap(Effect.runtime(), (r) => {
const fiber = Runtime.runFork(r, eff)
fibers.add(fiber)
const arr = Array.from(fibers)
fiber.addObserver(() => fibers.delete(fiber))
return joinAll(arr)
})
}
return makeEffect(get, value as any, initialValue, runtime, false)
}
return makeStream(get, value, initialValue, runtime)
}
function write(ctx: WriteContext>, arg: Arg | Reset | Interrupt) {
batch(() => {
if (arg === Reset) {
ctx.set(argAtom, [0, undefined as any])
} else if (arg === Interrupt) {
ctx.set(argAtom, [ctx.get(argAtom)[0] + 1, Interrupt])
} else {
ctx.set(argAtom, [ctx.get(argAtom)[0] + 1, arg])
}
ctx.refreshSelf()
})
}
return [read, write, argAtom] as const
}
const joinAll = (fibers: ReadonlyArray>) =>
Effect.async((resume) => {
let i = 0
let cause: Cause.Cause | undefined
let exit: Exit.Exit | undefined
function onExit(exit_: Exit.Exit, inLoop = false) {
if (exit_._tag === "Failure") {
cause = cause ? Cause.parallel(exit_.cause, cause) : exit_.cause
} else if (!cause) {
exit = exit_
}
i++
if (!inLoop) loop()
}
function loop() {
while (i < fibers.length) {
const fiber = fibers[i]
const exit = fiber.unsafePoll()
if (!exit) return fiber.addObserver(onExit)
onExit(exit, true)
}
resume(cause ? Exit.failCause(cause) : exit ? exit : Exit.failCause(Cause.empty))
}
loop()
return Effect.sync(() => {
if (i < fibers.length) {
fibers[i].removeObserver(onExit)
}
})
})
/**
* @since 1.0.0
* @category models
*/
export type PullResult = Result.Result<{
readonly done: boolean
readonly items: Arr.NonEmptyArray
}, E | Cause.NoSuchElementException>
/**
* @since 1.0.0
* @category constructors
*/
export const pull = (
create: ((get: Context) => Stream.Stream) | Stream.Stream,
options?: {
readonly disableAccumulation?: boolean | undefined
}
): Writable, void> => {
const pullSignal = removeTtl(state(0))
const pullAtom = readable(makeRead(function(get) {
return makeStreamPullEffect(get, pullSignal, create, options)
}))
return makeStreamPull(pullSignal, pullAtom)
}
const makeStreamPullEffect = (
get: Context,
pullSignal: Atom