Cheat sheet
Every VibeLang change beside the Effect code it replaces: VibeLang and Effect 4 TypeScript in labeled tabs. The specification states the rules behind each. In a .vibe file, the Effect tab's error classes, services, schemas, Effect types, Effect.succeed and Effect.fail, catch combinators, and withSpan and provide calls draw warnings that suggest the VibeLang tab where it keeps the program's meaning (TypeScript-style Effect code). Complete Effect tabs import their dependencies and are typechecked. Tabs marked // fragment use the declarations below or a surrounding Effect.gen body. The VibeLang examples share these declarations:
error NotFound { id: string }
interface User { id: string; name: string }
effect function getUser(id: string): User!NotFound!never {
try sleep("5 millis")
if (id === "missing") throw new NotFound({ id })
return { id, name: "Ada" }
}
effect function getOrders(id: string): number!! {
return id.length
}
service Approval { approve(request: string): boolean!! }
effect function release(version: string) {
const approval = try Approval
return (try approval.approve(`deploy ${version}`)) ? `released ${version}` : "declined"
}
// Run in an effect function: provide Approval = { approve: (_request) => succeed(true) } { { const jsonValue = [try getUser("1"), try getOrders("1"), try release("v1")]; try Console.log(try Effect.try(() => JSON.stringify(jsonValue))) } }
// Output: [{"id":"1","name":"Ada"},1,"released v1"]Types
Effect types. A!E!R means exactly Effect.Effect<A, E, R>. Empty and omitted slots are never. Leave out the whole annotation to infer a function's type. A line break ends the type: each ! and its slot stay on one line, A!! may end a line, and a slot in parentheses may span lines; a ! with no slot on its line is TS17019. Both slots can be object types: number!{ reason: string }!{ service: number }. After !!, parenthesize an object requirement as number!!({ service: number }) so { can still begin a function body. In an expression, write (value as number!!)! to apply a non-null assertion to the asserted value. Store or return an asserted Effect; discarding it in an expression statement is EK4801.
An Effect type such as A!!B!C needs explicit grouping (EK0302). Choose (A!!B)!C to nest the first Effect or A!(B!C) to nest the error channel. An asserted Effect used to test a line boundary still needs a binding or a return; discarding it reports EK4801.
type Find = (id: string) => User!NotFound
type Release = (version: string) => string!!Approval
type Load = () => string!!
effect function hello(id: string): string!NotFound!never {
return `Hello, ${(try getUser(id)).name}`
}
// Run in an effect function: try Console.log(try hello("1"))
// Output: Hello, Ada// fragment
type Find = (id: string) => Effect.Effect<User, NotFound>
type Release = (version: string) => Effect.Effect<string, never, Approval>
type Load = () => Effect.Effect<string>
const hello = (id: string): Effect.Effect<string, NotFound> =>
Effect.map(getUser(id), (user) => `Hello, ${user.name}`)Declarations
Errors.
error Missing { id: string }
error Timeoutimport { Data } from "effect"
class Missing extends Data.TaggedError("Missing")<{ readonly id: string }> {}
class Timeout extends Data.TaggedError("Timeout") {}Errors are classes. An error declaration supports fields, methods, and getters. Use an ordinary Data.TaggedError class when you need a constructor, inheritance, or a custom tag.
// expect-warning: EK4830
class Invalid extends Data.TaggedError("Invalid")<{ readonly code: string }> {
constructor(input: string) {
super({ code: input.trim() })
}
get label(): string {
return `invalid ${this.code}`
}
}
class Failure extends Data.TaggedError("Failure" as string)<{ readonly code: string }> {}
class Refused extends Failure {
override readonly _tag = "Refused"
}
// Run in an effect function: try Console.log(try Effect.try(() => JSON.stringify([new Invalid(" x ").label, new Refused({ code: "r" })._tag])))
// Output: ["invalid x","Refused"]import { Data } from "effect"
class Invalid extends Data.TaggedError("Invalid")<{ readonly code: string }> {
constructor(input: string) {
super({ code: input.trim() })
}
get label(): string {
return `invalid ${this.code}`
}
}
class Failure extends Data.TaggedError("Failure" as string)<{ readonly code: string }> {}
class Refused extends Failure {
override readonly _tag = "Refused"
}Errors that encode. Fields map to schemas as a schema declaration's do.
schema error Stored { key: string; attempts?: number }import { Schema } from "effect"
class Stored extends Schema.TaggedError<Stored>()("Stored", { key: Schema.String, attempts: Schema.optional(Schema.Number) }) {}Services. Members have no bodies. Write their contracts explicitly. readonly has its TypeScript meaning.
service Users {
static readonly key = "app/Users"
find(id: string): User!NotFound
readonly region: string
}// fragment
class Users extends Context.Service<Users, {
find(id: string): Effect.Effect<User, NotFound>
readonly region: string
}>()("app/Users") {}Services of any shape. service Name: Type { … } uses the whole written type, including a primitive or an existing interface. The required body admits only key and defaultValue. Within the declaration's own body, Name.Shape denotes Type; elsewhere use Type or Context.Service.Shape<typeof Name>.
interface SearchApi {
find(query: string): string!!
}
service Search: SearchApi { static readonly key = "app/Search" }
service Prefix: string { static readonly key = "app/Prefix" }import { Context, Effect } from "effect"
interface SearchApi {
find(query: string): Effect.Effect<string>
}
class Search extends Context.Service<Search, SearchApi>()("app/Search") {}
class Prefix extends Context.Service<Prefix, string>()("app/Prefix") {}Layers. A layer is Effect's own call: effect { ... } is the second argument to Layer.effect(Users, effect { ... }) and is its Effect, runs once when the layer builds, and returns members typed by the service. Without setup, write Layer.succeed(Users, { ... }).
const UsersLive = Layer.effect(Users, effect {
const seen = new Set<string>()
return Users.of({
find: (id) => getUser(id),
region: "eu"
})
})
// Run in an effect function:
// provide UsersLive {
// const users = try Users
// {
// const jsonValue = try users.find("1")
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// try Console.log(users.region)
// }
// Output: {"id":"1","name":"Ada"}
// Output: eu// fragment
const UsersLive = Layer.effect(Users, Effect.gen(function* () {
const seen = new Set<string>()
return Users.of({ find: (id) => getUser(id), region: "eu" })
}))Schemas. One declaration gives the schema and its type.
schema Account {
readonly id: string
readonly nickname?: string
readonly role: "admin" | "member"
}
// Run in an effect function:
// {
// const jsonValue = try Schema.decodeUnknownEffect(Account)({ id: "1", role: "admin" })
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: {"id":"1","role":"admin"}import { Schema } from "effect"
const Account = Schema.Struct({
id: Schema.String,
nickname: Schema.optional(Schema.String),
role: Schema.Literals(["admin", "member"])
})
type Account = typeof Account.TypeSchema aliases. A schema of any type the struct form maps, and the type, under one name.
schema Role = "admin" | "member"
// Run in an effect function:
// try Console.log(Schema.is(Role)("admin"))
// try Console.log(Schema.is(Role)("owner"))
// Output: true
// Output: falseimport { Schema } from "effect"
const Role = Schema.Literals(["admin", "member"])
type Role = typeof Role.TypeData types. A tagged union: Effect's Data.TaggedEnum type and its Data.taggedEnum constructors under one name. A variant without fields is a bare name.
data Delivery {
Waiting
Sent { tracking: string }
}
// Run in an effect function: try Console.log(try Effect.try(() => JSON.stringify([Delivery.Waiting(), Delivery.Sent({ tracking: "parcel-8" })])))
// Output: [{"_tag":"Waiting"},{"tracking":"parcel-8","_tag":"Sent"}]import { Data } from "effect"
type Delivery = Data.TaggedEnum<{
Waiting: {}
Sent: { readonly tracking: string }
}>
const Delivery = Data.taggedEnum<Delivery>()Readonly members. Use TypeScript's readonly modifier for a member that cannot be assigned.
interface Cart { readonly id: string; items: Array<string> }interface Cart { readonly id: string; items: Array<string> }Programs
Statements instead of generators. Declare an effect function. Run each Effect with try.
effect function greetUser(id: string) {
return try withSpan(effect {
const user = try getUser(id)
try Console.log(`Hello, ${user.name}`)
return user.name
}, "greetUser")
}
// Run in an effect function:
// const output = try Console.Console
// try Console.log(try Effect.provide(greetUser("1"), Logger.layer([Logger.make(({ message }) => output.log(...(message as unknown[])))])))
// Output: Hello, Ada
// Output: Ada// fragment
const greetUser = Effect.fn("greetUser")(function* (id: string) {
const user = yield* getUser(id)
yield* Console.log(`Hello, ${user.name}`)
return user.name
})Effect.fn("name")(body) adds a named tracing span. Preserve it with try withSpan(effect { ... }, "name") inside an effect function. The block's result, failures, and requirements flow through.
Programs as Effect values. Calling an effect function returns an Effect. Pass it directly to combinators, then use try to run the combined Effect.
effect function fastest() {
const user = try getUser("1")
return try race(getUser("1"), getUser("2"))
}
// Run in an effect function: try Console.log((try fastest()).name)
// Output: Ada// fragment
const user = yield* getUser("1")
const first = yield* Effect.race(getUser("1"), getUser("2"))Providing layers. return inside the block returns from the function.
effect function program() {
provide UsersLive {
const users = try Users
return try users.find("1")
}
}
// Run in an effect function:
// {
// const jsonValue = try program()
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: {"id":"1","name":"Ada"}// fragment
const program = Effect.gen(function* () {
const users = yield* Users
return yield* users.find("1")
}).pipe(Effect.provide(UsersLive))Providing one service. provide Key = value supplies an implementation. Mix layers and service bindings in one list. Use the service key, such as Random.Random.
const seeded = { nextIntUnsafe: (): number => 4, nextDoubleUnsafe: (): number => 0.5 }
effect function roll(): number!! {
provide Logger.layer([]), Random.Random = seeded {
return try Random.nextInt
}
}
// Run in an effect function: try Console.log(try roll())
// Output: 4import { Effect, Logger, Random } from "effect"
const seeded = { nextIntUnsafe: () => 4, nextDoubleUnsafe: () => 0.5 }
const roll = Random.nextInt.pipe(
Effect.provideService(Random.Random, seeded),
Effect.provide(Logger.layer([]))
)Catching by tag. Catch the failure and match on it. A match naming every failure needs no rethrow; default: throw e passes on the rest.
effect function describe(id: string) {
return effect {
return (try getUser(id)).name
} catch (e) => match (e) {
when NotFound: `no user ${e.id}`;
}
}
// Run in an effect function:
// {
// const jsonValue = [try describe("1"), try describe("missing")]
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: ["Ada","no user missing"]// fragment
const describe = (id: string) =>
Effect.map(getUser(id), (user) => user.name).pipe(
Effect.catchTag("NotFound", (e) => Effect.succeed(`no user ${e.id}`))
)Falling back in an expression. x catch () => fallback runs the Effect and gives the fallback after a typed failure. Defects and interruption propagate.
effect function nameOrGuest(id: string) {
return effect { return (try getUser(id)).name } catch () => "guest"
}
// Run in an effect function:
// {
// const jsonValue = [try nameOrGuest("1"), try nameOrGuest("missing")]
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: ["Ada","guest"]// fragment
const nameOrGuest = (id: string) =>
Effect.map(getUser(id), (user) => user.name).pipe(
Effect.orElseSucceed(() => "guest")
)Catching in an expression. x catch (e) => … passes the failure to a handler, which can match on it; a match naming every failure removes them all.
effect function nameOrReason(id: string) {
return effect { return (try getUser(id)).name } catch (e) => match (e) {
when NotFound: `no user ${e.id}`;
}
}
// Run in an effect function:
// {
// const jsonValue = [try nameOrReason("1"), try nameOrReason("missing")]
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: ["Ada","no user missing"]// fragment
const nameOrReason = (id: string) =>
Effect.map(getUser(id), (user) => user.name).pipe(
Effect.catch((e) => Effect.succeed(`no user ${e.id}`))
)Entry point. Call a runner explicitly at the module top level. await runPromise(main()) waits for the returned Promise. A Node application can use NodeRuntime.runMain(main()).
// main.vibe
export effect function main() {
try log("Hello")
}
// Run in an effect function:
// const output = try Console.Console
// try Effect.provide(main(), Logger.layer([Logger.make(({ message }) => output.log(...(message as unknown[])))]))
// Output: Hello// fragment
// main.ts
export const main = Effect.log("Hello")
// run.ts
NodeRuntime.runMain(main)// run.vibe
import { main } from "./main.vibe"
await runPromise(main())Causes, exits, and interruption
Catch every cause. match on exit(…): a Failure exit's cause also holds defects and interrupts.
effect function safe(id: string) {
return match (try exit(getUser(id))) {
when Exit.Success(let user): user.name;
when Exit.Failure(let cause): `failed: ${Cause.pretty(cause)}`;
}
}
// Run in an effect function:
// try Console.log(try safe("1"))
// try Console.log((try safe("missing")).includes("NotFound"))
// Output: Ada
// Output: true// fragment
const safe = (id: string) =>
Effect.map(getUser(id), (user) => user.name).pipe(
Effect.catchCause((cause) => Effect.succeed(`failed: ${Cause.pretty(cause)}`))
)Rethrow a cause. Use try failCause(cause) to fail with the whole cause. throw cause would make the Cause object a typed failure.
effect function logged() {
const outcome = try exit(getUser("1"))
if (outcome is Exit.Failure(let cause)) {
try logError(cause)
return try failCause(cause)
}
return outcome.value
}
// Run in an effect function:
// {
// const jsonValue = try logged()
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: {"id":"1","name":"Ada"}// fragment
const logged = getUser("1").pipe(
Effect.catchCause((cause) => Effect.andThen(Effect.logError(cause), Effect.failCause(cause)))
)Run on every exit. onExit runs its callback without interruption and passes the complete Exit, including the success value.
effect function tracked() {
return try onExit(getUser("1"), (outcome) => log(`lookup ${outcome._tag}`))
}
// Run in an effect function:
// const output = try Console.Console
// const user = try Effect.provide(tracked(), Logger.layer([Logger.make(({ message }) => output.log(...(message as unknown[])))]))
// try Console.log(user.name)
// Output: lookup Success
// Output: Ada// fragment
const tracked = getUser("1").pipe(
Effect.onExit((exit) => Effect.log(`lookup ${exit._tag}`))
)Exit, yield, and interrupt. Pass the Effect directly to exit. yieldNow and interrupt are Effect values. Run them with try.
effect function outcome() {
const result = try exit(getUser("1"))
try yieldNow
if (result is Exit.Failure) try interrupt
return result
}
// Run in an effect function: try Console.log((try outcome())._tag)
// Output: Success// fragment
const result = yield* Effect.exit(getUser("1"))
yield* Effect.yieldNow
if (result._tag === "Failure") yield* Effect.interruptInterruption. Store or pass the native functions as Effect.interruptible and Effect.uninterruptible. These statements require effect code; plain and async functions, class field and enum member initializers, static blocks and parameter defaults report EK2201. uninterruptible { … } masks interruption for its statements, and restore { … } inside it restores the interruptibility from before the innermost mask, which may itself be uninterruptible. interruptible { … } allows interruption inside masked code. They are ordinary blocks, so return inside one returns from the effect function. A returned anonymous function or class keeps its empty .name, including the name observed by class static initializers. A nested effect callable or effect block must introduce its own mask; it cannot capture an outer block's restore. This remains EK2202 when a for concurrent item stands between the nested activation and the outer mask; the nested activation can use its own uninterruptible block.
Computed object and class method names, and a class's extends expression, evaluate in the enclosing activation and keep its mask. A restore inside a do in one of those expressions uses that mask; a method body still starts a separate activation.
The opening { follows the keyword on the same line; across a line break the word is an ordinary identifier before a separate block.
effect function guarded() {
uninterruptible {
const user = try getUser("1")
restore {
const orders = try getOrders(user.id)
return { user, orders }
}
}
}
effect function cancellable() {
interruptible {
return try getOrders("1")
}
}
// Run in an effect function:
// {
// const jsonValue = [try guarded(), try cancellable()]
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: [{"user":{"id":"1","name":"Ada"},"orders":1},1]// fragment
const guarded = Effect.uninterruptibleMask((restore) =>
Effect.gen(function* () {
const user = yield* getUser("1")
const orders = yield* restore(getOrders(user.id))
return { user, orders }
})
)
const cancellable = Effect.interruptible(getOrders("1"))Calls
A tagged template is a call of its tag. If sql returns an Effect, the statement try sql`CREATE TABLE example (id TEXT)` runs it, and const rows = try sql`SELECT * FROM example` gets its success value. Plain tags keep JavaScript behavior. To pass one as a program, write sql`...` , as for an Effect-returning call.
No imports from effect or its subpath packages.
effect function ready() {
try Console.log(Hex.encode("ready"))
}
// Run in an effect function: try ready()
// Output: 7265616479import { Console } from "effect"
import { Hex } from "effect/encoding"
const ready = Console.log(Hex.encode("ready"))Look up platform services. Get the implementation with try FileSystem.FileSystem, then run its Effect members with try.
effect function size(path: string) {
const fs = try FileSystem.FileSystem
return (try fs.readFileString(path)).length
}
// Run in an effect function: provide FileSystem.layerNoop({ readFileString: () => succeed("hello") }) { try Console.log(try size("notes.txt")) }
// Output: 5import { Effect } from "effect"
import { FileSystem } from "effect/FileSystem"
const size = (path: string) =>
Effect.gen(function* () {
const fs = yield* FileSystem
const text = yield* fs.readFileString(path)
return text.length
})Effect's functions without the Effect. prefix: every export of the Effect module, such as sleep, log, retry, timeout, race, all, tryPromise, and map, except a name that clashes, such as Effect.try and Effect.match. "vibe": { "effectGlobals": false } turns them off.
effect function patient() {
try sleep("10 millis")
return try timeout(retry(getUser("1"), Schedule.recurs(2)), "1 second")
}
// Run in an effect function:
// {
// const jsonValue = try patient()
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: {"id":"1","name":"Ada"}// fragment
const patient = Effect.gen(function* () {
yield* Effect.sleep("10 millis")
return yield* Effect.timeout(Effect.retry(getUser("1"), Schedule.recurs(2)), "1 second")
})Operators on Effect's data types. Use the module's functions, directly or through .pipe.
function hot() {
return Stream.make(18, 25, 30).pipe(
Stream.filter((c) => c >= 25),
Stream.map((c) => `${c} C`),
Stream.take(2)
)
}
// Run in an effect function:
// {
// const jsonValue = try Stream.runCollect(hot())
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: ["25 C","30 C"]import { Stream } from "effect"
const hot = Stream.take(
Stream.map(Stream.filter(Stream.make(18, 25, 30), (c) => c >= 25), (c) => `${c} C`),
2
)Stream transformations construct a Stream. Run it with a Stream consumer such as Stream.runCollect, or iterate it with for try.
The pipe operator. % is the value on the left, evaluated once. An anonymous function or class used as a topic keeps its empty .name, including inside class static initializers. Effects remain values in a pipe: try (getUser("1") |> retry(%, policy) |> timeout(%, "1 second")).
effect function shout() {
return (try getUser("1")).name |> %.toUpperCase() |> `${%}!`
}
// Run in an effect function: try Console.log(try shout())
// Output: ADA!// fragment
const user = yield* getUser("1")
const shout = pipe(user.name, (name) => name.toUpperCase(), (name) => `${name}!`)TC39 forms
Fail on a missing value.
effect function findUser(users: Map<string, User>, id: string) {
const user = users.get(id)
if (user === undefined) throw new NotFound({ id })
return user
}
// Run in an effect function:
// try Console.log((try findUser(new Map([["1", { id: "1", name: "Ada" }]]), "1")).name)
// try Console.log((try result(findUser(new Map<string, User>(), "missing")))._tag)
// Output: Ada
// Output: Failure// fragment
const findUser = (users: Map<string, User>, id: string) =>
Effect.fromNullishOr(users.get(id)).pipe(Effect.mapError(() => new NotFound({ id })))throw is a statement. In an effect function, it fails the Effect with a typed error. In a plain function it is EK0401: make the function effect, or keep JavaScript's throw in a module block with @throws {T} on each function that throws. In an async function it rejects the Promise.
Blocks as values (do expressions). The value is the block's normal completion value: an empty last statement keeps the earlier value, so do { 7; {} } is 7. A block with no normal completion has type never, including do { stop(); 1 } when stop(): never. With strict checking, [].concat(do { [] }) keeps the empty array's never[] type. Unreachable surrounding code does not erase the type of a do block’s local normal completions. Paths that leave by return, break, continue or throw contribute no result type; a do with no normal completion has type never. If old code relied on the leaked any to call or read properties of such a result, make that any explicit with an erased assertion. Native protocol checks still apply to this never result: iteration, destructuring, yield* and function-call spreads report TypeScript's errors. Array literal spreads retain TypeScript's accepted behavior.
effect function label(id: string) {
const name = do {
const user = try getUser(id)
if (user.name.length > 3) user.name
else "short"
}
return name
}
// Run in an effect function: try Console.log(try label("1"))
// Output: short// fragment
const label = (id: string) =>
Effect.map(getUser(id), (user) => (user.name.length > 3 ? user.name : "short"))A do expression is TC39's: return, break and continue inside it mean what they mean around it. Its block cannot end with a declaration, a loop (including for concurrent and for try) or an if without else (EK0201); an unlabeled jump or one targeting any label directly chained around the same loop cannot leave a do expression in that loop's head (EK0205), nor a var stand in one in a parameter list (EK0203), including inside nested do expressions; and where VibeLang still writes a function around it, such as a class field initializer, a constructor or native generator parameter default, a default that itself uses try, await or yield, or a parameter list with a binding pattern after a returning default or combined with a rest parameter, none of them can leave it (EK0204). A return in a do in a parameter default of a plain, async or effect function, arrow or method returns from that function before later defaults and the body run: a plain function returns the value, an async function fulfills with it, an effect function's call gives an Effect that succeeds with it, built at the call without starting the body, and a producer's call gives an empty Stream. The defaults keep their order, a later parameter stays in its temporal dead zone, the function's length and declaration output do not change, and a parameter without a type takes its default's type. In a producer body, yield in a retained do emits from the enclosing producer, including binding defaults and definition-time expressions. The pattern’s order and iterator closing stay native; parameter initialization and written nested activations keep their own rules.
Source var declarations are EK0107 everywhere in a .vibe file, including do expressions and plain functions. The one exception is an ambient var directly in declare global { }, such as declare global { var __LIMIT__: number | undefined }: it emits no code and is how TypeScript adds a typed property to globalThis. Use const or let and preserve the original scope when rewriting.
A final for concurrent discards its item results. To keep the formerly accepted spelling, wrap that loop in a block ending with void 0 as void, making its undefined result explicit while retaining its void type. A later value, as in do { for concurrent (const n of xs) { use(n) }; 7 }, is already valid.
An anonymous function or class used as a do completion, conditional value, method receiver, computed key, match subject or array value keeps its empty .name. An object property before a later do keeps its property name; class static initializers observe that source name during creation.
A do in the right-hand operand of a for…in or for…of lexical head keeps that head's scope. Its closures capture the uninitialized let or const head bindings, separately from the initialized bindings of each iteration. TypeScript reports an unknown or possibly missing do operand of for…of as Object (TS2571, TS2532), as it does for a call.
A do in a short-circuit operand keeps the selected branch’s TypeScript narrowing: x !== undefined && do { x.length } is valid for x: string | undefined. The same rule applies to || and ??; the left operand runs once, and assignments inside the body invalidate narrowing normally.
Erased TypeScript callee wrappers (!, as, satisfies and type assertions) keep a method’s receiver when a later argument contains do. The receiver and method are captured once before the argument runs, and the asserted function type still checks the call.
Logical assignments with a do right operand (&&=, ||=, ??=) read the target once. A skipped assignment returns that read; a taken assignment returns the right operand's value, even when a global accessor's setter stores a different value. Testing the result preserves TypeScript's narrowing of the target.
When a returning do appears in a parameter default, earlier defaults in the same group of simple parameters keep sharing the body's parameter bindings. A callback created by an earlier default sees assignments in the body, and a callback called while a later parameter is still initializing gets JavaScript's temporal-dead-zone error. Function and class defaults keep their inferred names before class static initializers run, and callback defaults keep TypeScript's contextual parameter types. A trailing rest parameter is supported when every parameter binds an identifier. Its array is available to the body and closures after initialization, and a reused Effect or Stream keeps the same array for that call. A declaration directly in the body cannot reuse a parameter name; TypeScript's original declaration diagnostics still apply. Declarations in nested blocks keep their native shadowing rules.
Directly evaluated await in an Effect callable's parameter default reports EK0102. This includes a class's extends expression in that default, including after an earlier returning do. Move Promise work into an appropriate callable body; a nested async callable keeps its own native rules.
Directly evaluated await in an Effect callable's parameter default reports EK0102, including computed class element names and object method or getter names. This also applies after an earlier returning do; a nested async callable keeps its own native rules.
A producer parameter default reports EK2104 for yield in class definition expressions and computed object member names, including after an earlier returning do; a nested native generator keeps its own rules.
An enum member initializer uses native TypeScript await placement rules. Nest an async or effect callable to give its body that callable’s own context.
A class field initializer cannot itself use await. A nested async callable keeps native Promise waiting, and a nested effect callable runs Effects with try.
A break or continue whose target is outside an effect { } block is EK0202; the block runs as its own Effect. Class decorators, computed member names and extends expressions keep that enclosing block context. A do in those positions reports EK0202 when its jump would leave the block; written method bodies keep their own targets.
Effect blocks as arguments. Pass effect { ... } as an ordinary argument. A test API takes a callback that returns the Effect, such as it.live("name", () => effect { ... }).
effect function loaded() {
return try withSpan(effect {
const user = try getUser("1")
return user.name
}, "load")
}
// Run in an effect function: try Console.log(try loaded())
// Output: Ada// fragment
const loaded = Effect.withSpan(
Effect.gen(function* () {
const user = yield* getUser("1")
return user.name
}),
"load"
)
it.live("finds a user", () =>
Effect.gen(function* () {
const user = yield* getUser("1")
assert.strictEqual(user.name, "Ada")
}))import { assert, it } from "@effect/vitest"
it.live("finds a user", () => effect {
const user = try getUser("1")
try Effect.try(() => assert.strictEqual(user.name, "Ada"))
})it.live uses the live clock, because this page's getUser sleeps. Under it.effect's test clock, a sleeping test must advance it with TestClock.adjust.
Pattern matching
From the TC39 pattern matching proposal (stage 1). See Pattern matching with match and is.
Match a value. match is exhaustive: without default, a match that misses a case of a finite union is EK4701, as with Match.exhaustive. Leave out the second arm below and the compiler reports This match does not handle every case of "draft" | "published": "published" is left.
function phaseLabel(phase: "draft" | "published") {
return match (phase) {
when "draft": "Draft";
when "published": "Published";
}
}
// Run in an effect function: try Console.log(try Effect.try(() => JSON.stringify([phaseLabel("draft"), phaseLabel("published")])))
// Output: ["Draft","Published"]import { Match } from "effect"
const phaseLabel = (phase: "draft" | "published") =>
Match.value(phase).pipe(
Match.when("draft", () => "Draft"),
Match.when("published", () => "Published"),
Match.exhaustive
)Match errors by class. An error class matches its _tag. and { let id } binds a property.
function describeFailure(failure: NotFound | Timeout) {
return match (failure) {
when NotFound(let e): `no user ${e.id}`;
when Timeout: "retry";
}
}
// Run in an effect function: try Console.log(try Effect.try(() => JSON.stringify([describeFailure(new NotFound({ id: "7" })), describeFailure(new Timeout())])))
// Output: ["no user 7","retry"]// fragment
const describeFailure = (failure: NotFound | Timeout) =>
Match.value(failure).pipe(
Match.tag("NotFound", (e) => `no user ${e.id}`),
Match.tag("Timeout", () => "retry"),
Match.exhaustive
)Match a data type's variants. Use an object pattern on _tag and bind the fields you need.
function deliveryLabel(delivery: Delivery) {
return match (delivery) {
when { _tag: "Waiting" }: "waiting";
when { _tag: "Sent", let tracking }: `sent ${tracking}`;
default: "unknown";
}
}
// Run in an effect function: try Console.log(try Effect.try(() => JSON.stringify([deliveryLabel(Delivery.Waiting()), deliveryLabel(Delivery.Sent({ tracking: "parcel-8" }))])))
// Output: ["waiting","sent parcel-8"]// fragment
const deliveryLabel = Delivery.$match({
Waiting: () => "waiting",
Sent: ({ tracking }) => `sent ${tracking}`
})Option, Exit, and Result. Arms can run Effect functions.
function greet(name: Option.Option<string>) {
return match (name) {
when Option.Some(let n): `Hello, ${n}`;
when Option.None: "Hello";
}
}
function failed(outcome: Exit.Exit<User, NotFound>) {
return outcome is Exit.Failure
}
// Run in an effect function:
// try Console.log(greet(Option.some("Ada")))
// try Console.log(greet(Option.none()))
// try Console.log(failed(Exit.fail(new NotFound({ id: "7" }))))
// try Console.log(failed(Exit.succeed({ id: "1", name: "Ada" })))
// Output: Hello, Ada
// Output: Hello
// Output: true
// Output: false// fragment
const greet = (name: Option.Option<string>) =>
Option.match(name, { onNone: () => "Hello", onSome: (n) => `Hello, ${n}` })
const failed = (outcome: Exit.Exit<User, NotFound>) => Exit.isFailure(outcome)Test and bind. Bindings in an is work in an if or while condition.
function firstFailure(outcome: Exit.Exit<User, NotFound>) {
if (outcome is Exit.Failure(let cause) && Cause.hasFails(cause)) return Cause.pretty(cause)
return "ok"
}
// Run in an effect function:
// try Console.log(firstFailure(Exit.succeed({ id: "1", name: "Ada" })))
// try Console.log(firstFailure(Exit.fail(new NotFound({ id: "7" }))).includes("NotFound"))
// Output: ok
// Output: true// fragment
const firstFailure = (outcome: Exit.Exit<User, NotFound>) =>
Exit.isFailure(outcome) && Cause.hasFails(outcome.cause) ? Cause.pretty(outcome.cause) : "ok"Wrap TypeScript calls
Native await. A class static block rejects await with TS18037, including an Effect-valued operand. A nested async callback keeps its own await rules; running an Effect there requires await runPromise(program).
Wrap TypeScript calls. Call a known nonthrowing function directly. Wrap a potentially throwing function with Effect.try. Use sync for a function that can't throw; when a function may throw and its failure should be a defect, use orDie(Effect.try(() => …)). Always wrap Promises: tryPromise for a function that may throw, promise for one that can't. Callback arrows capture locals normally.
Built-in exceptions. VibeLang ships @throws annotations for JavaScript's globals: JSON.parse throws SyntaxError, and decodeURI and decodeURIComponent throw URIError. decode on a TextDecoder throws TypeError only when the decoder was made with fatal: true, so new TextDecoder().decode(bytes), or decode on a const made that way without fatal: true, needs no wrapper. Wrap these calls with Effect.try before running them with try in an effect function. Use its catch option to map the error. Inside TypeScript's Effect.gen, a plain JSON.parse throw is a defect.
Use injected services for platform APIs that Effect covers. Keep node:* value imports and Node.js globals in a .ts companion file. The following companions supply the foreign APIs for this comparison:
// node-apis.ts
// types: node
export { uptime } from "node:os"
export { statfs } from "node:fs/promises"
import { EventEmitter } from "node:events"
/** @throws {never} */
export function makeTicker() {
const ticker = new EventEmitter()
ticker.on("newListener", () => queueMicrotask(() => ticker.emit("tick", 7)))
return ticker
}
/** @throws {never} */
export function onceTick(ticker: EventEmitter, listener: (n: number) => void): void {
ticker.once("tick", listener)
}
/** @throws {never} */
export function offTick(ticker: EventEmitter, listener: (n: number) => void): void {
ticker.off("tick", listener)
}// web-apis.ts
export function generateKey() {
return crypto.subtle.generateKey({ name: "HMAC", hash: "SHA-256" }, false, ["sign"])
}import { makeTicker, offTick, onceTick, statfs, uptime } from "./node-apis.ts"
import type { EventEmitter } from "node:events"
import { generateKey } from "./web-apis.ts"
error BadJson { error: unknown }
error NoDisk { error: unknown }
effect function wrappedCalls(text: string, path: string, ticker: EventEmitter) {
const up = try Effect.try(() => uptime())
const parsed = try Effect.try({ try: () => JSON.parse(text), catch: (error) => new BadJson({ error }) })
const key = try tryPromise(() => generateKey())
const free = try tryPromise({ try: async () => (await statfs(path)).bavail, catch: (error) => new NoDisk({ error }) })
const tick = try callback<number>((resume) => {
const listener = (n: number) => resume(succeed(n))
onceTick(ticker, listener)
return sync(() => offTick(ticker, listener))
})
const name = try tryPromise(() => greetFromTypeScript())
return { up, parsed, key, free, tick, name }
}
async function greetFromTypeScript() {
return await runPromise(greetUser("1"))
}
// Run in an effect function:
// const output = try Console.Console
// provide Logger.layer([Logger.make(({ message }) => output.log(...(message as unknown[])))]) {
// const ticker = try sync(() => makeTicker())
// const value = try wrappedCalls('{"ok":true}', ".", ticker)
// try Console.log(try Effect.try(() => JSON.stringify({ ...value, up: typeof value.up, key: value.key.type, free: typeof value.free })))
// }
// Output: Hello, Ada
// Output: {"up":"number","parsed":{"ok":true},"key":"secret","free":"number","tick":7,"name":"Ada"}// fragment
import { uptime } from "node:os"
import { statfs } from "node:fs/promises"
const up = Effect.try(() => uptime())
const parsed = Effect.try({ try: () => JSON.parse(text), catch: (error) => new BadJson({ error }) })
const key = Effect.tryPromise(() => crypto.subtle.generateKey({ name: "HMAC", hash: "SHA-256" }, false, ["sign"]))
const free = Effect.tryPromise({ try: async () => (await statfs(path)).bavail, catch: (error) => new NoDisk({ error }) })
const tick = Effect.callback<number>((resume) => {
const listener = (n: number) => resume(Effect.succeed(n))
ticker.once("tick", listener)
return Effect.sync(() => ticker.off("tick", listener))
})
const name = await Effect.runPromise(greetUser("1"))TypeScript companion files. Import a .ts file normally. Plain functions and async functions keep their TypeScript behavior. This helper matches the Effect comparison:
// links.ts
// types: node
import { lstatSync } from "node:fs"
/** @throws {never} */
export function isSymbolicLink(path: string): boolean {
try {
return lstatSync(path).isSymbolicLink()
} catch {
return false
}
}import { isSymbolicLink } from "./links.ts"
const linked = (path: string) => sync(() => isSymbolicLink(path))
// Run in an effect function: try Console.log(try linked("."))
// Output: false// fragment
// links.ts
import { lstatSync } from "node:fs"
export function isSymbolicLink(path: string): boolean {
try {
return lstatSync(path).isSymbolicLink()
} catch {
return false
}
}
// main.ts
import { isSymbolicLink } from "./links.ts"
const linked = (path: string) => Effect.sync(() => isSymbolicLink(path))Fibers
Fork and join. fork creates a child owned by the current fiber. The child is interrupted when its parent ends. Join each fiber with join.
effect function both() {
const user = fork getUser("1")
const orders = fork getOrders("1")
return [join user, join orders]
}
// Run in an effect function:
// {
// const jsonValue = try both()
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: [{"id":"1","name":"Ada"},1]// fragment
const user = yield* Effect.forkChild(getUser("1"))
const orders = yield* Effect.forkChild(getOrders("1"))
return [yield* Fiber.join(user), yield* Fiber.join(orders)]Wait for several. try.all behaves like Promise.all: it keeps the array's shape, and a failure interrupts the rest. Its operands start in order, and one that fails before it suspends stops later ones from starting. Use try all(record, { concurrency: "unbounded" }) to keep object keys.
effect function many() {
const [user, orders] = try.all [getUser("1"), getOrders("1")]
const pair = try all({ user: getUser("1"), orders: getOrders("1") }, { concurrency: "unbounded" })
return { user, orders, pair }
}
// Run in an effect function:
// {
// const jsonValue = try many()
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: {"user":{"id":"1","name":"Ada"},"orders":1,"pair":{"user":{"id":"1","name":"Ada"},"orders":1}}// fragment
const [user, orders] = yield* Effect.all([getUser("1"), getOrders("1")], { concurrency: "unbounded" })
const pair = yield* Effect.all({ user: getUser("1"), orders: getOrders("1") }, { concurrency: "unbounded" })First success, all outcomes. try.any waits for the first success. try.allSettled returns each element's full outcome as an Exit: success, typed failure, defect, or interruption. The whole never fails, as Promise.allSettled never rejects. The explicit equivalent is try.all [exit(a()), exit(b())].
effect function outcomes() {
const fastest = try.any [getUser("1"), getUser("2")]
const results = try.allSettled [getUser("1"), getOrders("1")]
return { fastest, results }
}
// Run in an effect function:
// const value = try outcomes()
// try Console.log(value.fastest.name)
// try Console.log(try Effect.try(() => JSON.stringify(value.results.map((result) => result._tag))))
// {
// const jsonValue = (try.allSettled [getUser("missing"), getOrders("1")]).map((result) => result._tag)
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// {
// const jsonValue = (try.all [exit(die("defect")), exit(getOrders("1"))]).map((e) => e._tag)
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: Ada
// Output: ["Success","Success"]
// Output: ["Failure","Success"]
// Output: ["Failure","Success"]// fragment
const fastest = yield* Effect.raceAll([getUser("1"), getUser("2")])
const outcomes = yield* Effect.all([Effect.exit(getUser("1")), Effect.exit(getOrders("1"))], { concurrency: "unbounded" })Fork scoped work. fork.scoped attaches a fiber to the current Scope. scoped closes that scope and interrupts the worker when the operation ends.
effect function withHeartbeat() {
return try scoped(effect {
fork.scoped forever(andThen(log("tick"), sleep("1 second")))
return try getUser("1")
})
}
// Run in an effect function: provide Logger.layer([]) { try Console.log((try withHeartbeat()).name) }
// Output: Ada// fragment
const withHeartbeat = Effect.scoped(Effect.gen(function* () {
yield* Effect.forkScoped(Effect.forever(Effect.andThen(Effect.log("tick"), Effect.sleep("1 second"))))
return yield* getUser("1")
}))Detached and scoped fibers.
effect function background() {
fork.detached getUser("1")
const scope = try Scope.make()
const fiber = fork.in(scope) getUser("2")
try Scope.close(scope, Exit.void)
return fiber
}
// Run in an effect function: try Console.log(Exit.isFailure(try Fiber.await(try background())))
// Output: true// fragment
yield* Effect.forkDetach(getUser("1"))
const scope = yield* Scope.make()
const fiber = yield* Effect.forkIn(getUser("2"), scope)Wait for a Deferred. Run the Effect returned by Deferred.await with try.
effect function signal() {
const ready = try Deferred.make<string>()
try Deferred.succeed(ready, "go")
return try Deferred.await(ready)
}
// Run in an effect function: try Console.log(try signal())
// Output: go// fragment
const ready = yield* Deferred.make<string>()
yield* Deferred.succeed(ready, "go")
const value = yield* Deferred.await(ready)Race. try.race behaves like Promise.race: the first to finish wins, success or failure, and the rest are interrupted. Use Effect blocks when a branch needs several statements; poll with Queue.poll and an if.
effect function next() {
const jobs = try Queue.unbounded<string>()
try Queue.offer(jobs, "build")
return try.race [
effect { return `ran ${try Queue.take(jobs)}` },
effect {
try sleep("1 second")
return "timeout"
}
]
}
// Run in an effect function: try Console.log(try next())
// Output: ran build// fragment
const next = yield* Effect.raceFirst(
Effect.map(Queue.take(jobs), (job) => `ran ${job}`),
Effect.as(Effect.sleep("1 second"), "timeout")
)A concurrent loop. At most n items run at once, and all finish before the loop ends.
effect function logAll(ids: string[]) {
for concurrent(8) (const id of ids) {
try log((try getUser(id)).name)
}
}
// Run in an effect function:
// const output = try Console.Console
// try Effect.provide(logAll(["1", "2"]), Logger.layer([Logger.make(({ message }) => output.log(...(message as unknown[])))]))
// Output: Ada
// Output: Ada// fragment
yield* Effect.forEach(ids, (id) => Effect.flatMap(getUser(id), (user) => Effect.log(user.name)), {
concurrency: 8,
discard: true
})The schema and schema-error examples use TypeScript's default optional-property setting. With exactOptionalPropertyTypes: true, name?: T uses Schema.optionalKey; write name?: T | undefined for Schema.optional. Optional tuple elements follow the same setting.
Callbacks in static blocks. await in a plain function or callback nested in a class static block keeps TypeScript's native diagnostic: TS1308, or TS2311 for a parenthesized call. Make that callback async to await a Promise; the surrounding block does not give it permission to wait.
Async parameters. An async function's parameter defaults keep TypeScript's TS2524 error for await, including an Effect-valued operand. A nested async callback has its own body and can await a Promise; awaiting an Effect in that callback still requires await runPromise(program).
Await in match arms. await in a match arm follows its written context. A class static block rejects it with TS18037; a nested async callback can await a Promise.
Directly evaluated await in an Effect callable's parameter default reports EK0102, including class and member decorator expressions. This also applies after an earlier returning do; a nested async callable keeps its own native rules.