Skip to main content

@flow-state-dev/core/helpers

Classes​

ScopeStateSchemaConflictError​

Two declarations of one scope-state field that disagree. Thrown by mergeScopeStateSchemas; the fields let a caller restate it in its own terms (the engine's cross-flow check does).

Extends​

  • Error

Constructors​

Constructor​
new ScopeStateSchemaConflictError(
owner,
conflict,
path,
why,
detail,
remedy,
first,
second
): ScopeStateSchemaConflictError;
Parameters​
owner​

string

conflict​

ScopeStateConflictKind

path​

string

why​

string

detail​

string

remedy​

string

first​

string

second​

string

Returns​

ScopeStateSchemaConflictError

Overrides​

Error.constructor

Properties​

cause?​
cause?: unknown;
Inherited from​

Error.cause

conflict​
readonly conflict: ScopeStateConflictKind;
detail​
readonly detail: string;

How they disagree, naming both: block "a" defaults it to "plan" and block "b" to "ask".

first​
readonly first: string;

The declarer met first.

message​
message: string;
Inherited from​

Error.message

name​
name: string;
Inherited from​

Error.name

path​
readonly path: string;

The field, from the scope: session.state.mode.

second​
readonly second: string;

The declarer that disagrees with it.

stack?​
stack?: string;
Inherited from​

Error.stack

Type Aliases​

ExpectedVersion​

type ExpectedVersion = number | "any" | "absent";

The version a write expects to find, on every versioned store.

  • A whole number n >= 1: the live row must be at exactly version n.
  • 0: no live row (never written, or deleted).
  • "absent": no row at all. On a resource store a tombstone is a row, so this is the stricter of the two create expectations.
  • "any": write unconditionally.

The engine re-exports this as ExpectedVersion and documents what each store family does with it.


ScopeStateConflictKind​

type ScopeStateConflictKind = "type" | "default";

What kind of disagreement refused a merge.


ScopeStateDeclaration​

type ScopeStateDeclaration = object;

One scope state schema, as one declarer stated it.

Properties​

schema​
readonly schema: ZodTypeAny;
source​
readonly source: string;

Who declared it, as a refusal names it: flow "x", block "y", capability "c" (used by block "y").


SegmentNameProblem​

type SegmentNameProblem = "too-long" | "reserved" | "pattern" | "windows-device";

Which part of the naming rule a segment breaks, checked in this order.

  • too-long: over MAX_SEGMENT_LENGTH characters.
  • reserved: a name the framework keeps for itself.
  • pattern: not lowercase letters, digits and single inner hyphens.
  • windows-device: a DOS device name Windows refuses with any extension (con, nul), which would make a repository holding it impossible to check out there.

UpdateOutcome​

type UpdateOutcome<TState, TResult> = object;

What an outcome-returning updater hands back: the next state, plus what it did.

Type Parameters​

TState​

TState

TResult​

TResult

Properties​

result​
result: TResult;

What this invocation did. Returned to the caller when this invocation is the one that commits.

state​
state: TState;

The state to commit — exactly what the underlying runner expects back.


UpdateStateRunner​

type UpdateStateRunner<TState> = object;

The subset of a resource handle these helpers need — ResourceRef, ResourceContext, and test doubles all satisfy it.

Type Parameters​

TState​

TState

Methods​

updateState()​
updateState(updater): Promise<unknown>;
Parameters​
updater​

(state) => TState | Promise<TState>

Returns​

Promise<unknown>


VersionConflict​

type VersionConflict<TState> = object;

The conflict half of a SetResult, which is all this rule can produce.

Type Parameters​

TState​

TState

Properties​

conflict​
conflict: object;
currentValue​
currentValue: TState | undefined;
currentVersion​
currentVersion: number;
ok​
ok: false;

VersionedRow​

type VersionedRow<TState> = object;

A stored row as every resource-state adapter models it internally, generic over the state it carries (JsonObject for ResourceStateStore).

Type Parameters​

TState​

TState

Properties​

lifecycle​
lifecycle: "live" | "deleted";
state​
state: TState;
version​
version: number;

ZodDeclaredDefault​

type ZodDeclaredDefault =
| {
factory: () => unknown;
kind: "static";
value: () => unknown;
}
| {
factory: () => unknown;
kind: "dynamic";
};

A .default()'s declared default, read without running an author's factory.

Union Members​

Type Literal​
{
factory: () => unknown;
kind: "static";
value: () => unknown;
}

.default(value): value() returns the declared value (zod's own thunk).


Type Literal​
{
factory: () => unknown;
kind: "dynamic";
}

.default(() => ...): an author's factory, compared by identity and never called here.


ZodSchemaCompareResult​

type ZodSchemaCompareResult =
| {
declaredKind: string | undefined;
inferredKind: string | undefined;
reason: string;
}
| null;

Variables​

MAX_SEGMENT_LENGTH​

const MAX_SEGMENT_LENGTH: 64 = 64;

Longest legal segment.


ONE_OFF_SESSION_PREFIX​

const ONE_OFF_SESSION_PREFIX: "ephemeral_" = "ephemeral_";

The prefix put on a one-off session's id. Stored ids carry it, so it never changes.

Functions​

assertDeleteExpectedVersion()​

function assertDeleteExpectedVersion(expectedVersion): asserts expectedVersion is number | "any";

Refuse an expectedVersion delete cannot act on.

Same numeric domain as assertSetExpectedVersion, and "absent" on top of it. "Delete only if the row does not exist" states no condition a delete could act on: 0 already covers "no live row, so the requested terminal state already holds," and there is nothing left for the stricter word to ask.

Call it before any early answer (a key that never existed, one already deleted). Those paths never consult the version, so a guard placed after them would leave them unguarded — and -1 could reach the SQL stores' sentinel (see assertVersionNumber).

Parameters​

expectedVersion​

ExpectedVersion

Returns​

asserts expectedVersion is number | "any"


assertSetExpectedVersion()​

function assertSetExpectedVersion(expectedVersion): asserts expectedVersion is number | "any" | "absent";

Refuse an expectedVersion set cannot act on, before any adapter does.

set honours all three members of the union, and the two non-numeric ones are not interchangeable:

  • 0 — "no live row." Create-if-absent, satisfied by a tombstone as well as a key that never existed. Recreating a deleted resource rides on this.
  • "absent" — "no row at all." A tombstone is a row, so it conflicts. This is what a read-modify-write that began from the absent-row seed writes at, so a delete cannot be undone by a mutation that never knew the resource was there.

delete refuses the word outright (assertDeleteExpectedVersion), so it never acquires a second, verb-dependent meaning.

The assertion signature carries the refusal into the type system, so every downstream body that does arithmetic on the value or binds it to a SQL parameter can narrow on it without restating the check. The narrowing is a promise the compiler takes on trust, which is why the check is an allowlist: Number.isInteger plus the two string early-returns refuse every other value, including members this union does not have yet.

Parameters​

expectedVersion​

ExpectedVersion

Returns​

asserts expectedVersion is number | "any" | "absent"


cloneValue()​

function cloneValue<TValue>(value): TValue;

Returns a structural deep copy of value. Uses the platform structuredClone when available and falls back to a JSON round-trip otherwise. The fallback only handles JSON-serializable shapes, matching the framework's state-tree contract (no Map, Set, functions, symbols).

Type Parameters​

TValue​

TValue

Parameters​

value​

TValue

Returns​

TValue


compareZodSchemasStructurally()​

function compareZodSchemasStructurally(declared, inferred): ZodSchemaCompareResult;

Conservative one-level structural comparison between two Zod schemas. Returns the first incompatibility, or null when structurally compatible.

Checks: top-level kind, object key sets, one level of object value kinds, and array element kind. Does NOT recurse into nested shapes, refinements, brands, or union variants.

Parameters​

declared​

ZodTypeAny

inferred​

ZodTypeAny

Returns​

ZodSchemaCompareResult


computeToolAliases()​

function computeToolAliases(names): Map<string, string>;

Computes the model-facing alias for each framework tool name, in order, using the exact sanitizeToolName + ensureUniqueAlias sequence the AI SDK adapter applies when compiling its tool dictionary. This is the alias seam between the framework-owned generator step loop and the adapter: the loop pre-renames the tools it passes to each step call with these aliases (so the adapter's own alias pass is a no-op and the dictionary is stable across steps), and builds inter-step tool-call / tool-result messages under the same aliases — bare re-sanitization would drop the ensureUniqueAlias suffix and mis-correlate colliding names.

Returns a map from framework tool name → disambiguated alias. Duplicate input names keep the first occurrence's alias (a tool list with duplicate names is invalid upstream).

Parameters​

names​

string[]

Returns​

Map<string, string>


containsZodLazy()​

function containsZodLazy(schema, seen?): boolean;

Whether schema holds a z.lazy anywhere: under its wrappers, in an object's fields, an array's or a set's items, a record's or a map's values, a tuple, a union, an intersection, a refinement, a pipe. A lazy is never expanded (a recursive one builds a fresh schema on each call), so what it holds can't be read: a schema holding one can't be shown to declare no default factory.

Parameters​

schema​

ZodTypeAny

seen?​

Set<ZodTypeAny>

Returns​

boolean


deepEqual()​

function deepEqual(a, b): boolean;

Parameters​

a​

unknown

b​

unknown

Returns​

boolean


deepMerge()​

function deepMerge<T>(base, override): T;

Recursively merges override into base. Returns a new object.

  • Scalar values in override replace base values.
  • Nested plain objects are merged recursively.
  • Arrays in override replace (not concat) arrays in base.
  • base is not mutated.

Type Parameters​

T​

T extends Record<string, unknown>

Parameters​

base​

T

override​

Record<string, unknown>

Returns​

T


dynamicDefaultFactories()​

function dynamicDefaultFactories(
schema,
out?,
seen?
): Set<() => unknown>;

Every author's default factory schema declares anywhere a read could fill from it: under its wrappers, in an object's fields, an array's or a set's items, a record's or a map's keys and values, a tuple, a union, an intersection. A lazy is never expanded (a recursive one builds a fresh schema on each call), so no factory is found inside one. Never calls a factory.

Parameters​

schema​

ZodTypeAny

out?​

Set<() => unknown>

seen?​

Set<ZodTypeAny>

Returns​

Set<() => unknown>


ensureUniqueAlias()​

function ensureUniqueAlias(candidate, taken): string;

Two distinct framework names can sanitize to the same alias (e.g. tf.memory/recall and tf-memory-recall both → tf_memory_recall). Disambiguate by appending the smallest numeric suffix that's unused in the dictionary built so far. taken is the set of aliases already assigned (the AI SDK adapter passes its compiled tool dictionary).

Parameters​

candidate​

string

taken​

Record<string, unknown>

Returns​

string


findBestOverlap()​

function findBestOverlap<T>(
content,
items,
threshold?
):
| {
fact: T;
minOverlap: number;
overlap: number;
}
| undefined;

Find the best-matching item from a list by bidirectional token overlap. Uses the max of overlap(a→b) and overlap(b→a) for match detection. Returns both the max overlap (for match threshold) and min overlap (for identity detection — both directions must be high for "same content").

Type Parameters​

T​

T extends object

Parameters​

content​

string

items​

T[]

threshold?​

number

Returns​

| { fact: T; minOverlap: number; overlap: number; } | undefined


getReadonlyStateKeys()​

function getReadonlyStateKeys(schema): string[];

The top-level keys of an object schema declared .readonly(): on a session stateSchema, the fields set when a session is created that never change.

The top is a z.object({...}), read through any .optional(), .nullable(), .default(), .readonly() or refinement wrapped around it: a scope record is always that object, so a wrapper there must not hide its readonly keys. Anything else (a union, an intersection, a lazy) has no readonly keys, rather than a guess. A key counts when a readonly wrapper sits anywhere in its own wrapper chain (.readonly().default(x) and .default(x).readonly() both count). .readonly() deeper inside a field's value doesn't make the field readonly. Reads zod 3 and zod 4 schemas alike.

Parameters​

schema​

ZodTypeAny | undefined

Returns​

string[]


getTransientKeys()​

function getTransientKeys(stateSchema): Set<string>;

Walk a z.object({...}) schema's top-level shape and collect the keys whose value schema was marked via transientSlot(). The object is found under any root wrapper (.default({}), effects). Non-object schemas (or undefined) yield an empty set.

Parameters​

stateSchema​

ZodTypeAny | undefined

Returns​

Set<string>


getZodArrayElement()​

function getZodArrayElement(schema): ZodTypeAny | undefined;

Returns the element schema of a z.array(), or undefined for non-arrays.

Parameters​

schema​

ZodTypeAny

Returns​

ZodTypeAny | undefined


getZodDeclaredDefault()​

function getZodDeclaredDefault(schema): ZodDeclaredDefault | undefined;

The default a .default() declares, or undefined for any other schema.

zod 3 keeps no raw value: .default(value) stores the thunk () => def, and .default(fn) stores fn. So a default is read as static only when both hold: its text is exactly zod's thunk, which is a read of one binding and so has no side effect to run; and two calls return the same value (Object.is), which a closure that recomputes (a getter behind the name, say) does not. That value is kept, so the thunk runs twice at most. Any other function is an author's factory: returned as is and never called.

Parameters​

schema​

ZodTypeAny

Returns​

ZodDeclaredDefault | undefined


getZodInnerType()​

function getZodInnerType(schema): ZodTypeAny | undefined;

Unwrap one layer of ZodOptional / ZodDefault / ZodNullable (_def.innerType) or ZodEffects (_def.schema). Returns undefined for non-wrapper types.

Parameters​

schema​

ZodTypeAny

Returns​

ZodTypeAny | undefined


getZodObjectShape()​

function getZodObjectShape(schema): Record<string, ZodTypeAny> | undefined;

Returns the top-level shape of a z.object(), or undefined for non-objects.

Parameters​

schema​

ZodTypeAny

Returns​

Record<string, ZodTypeAny> | undefined


getZodTypeName()​

function getZodTypeName(schema): string | undefined;

Read a Zod schema's discriminating _def.typeName (e.g. "ZodObject").

Parameters​

schema​

ZodTypeAny

Returns​

string | undefined


hasClientProjection()​

function hasClientProjection(client): boolean;

True when the client config declares an explicit projection (data / expose / exclude), as opposed to falling back to identity. Used by the debug snapshot and route snapshot builders to distinguish "developer-defined view" from "raw state passthrough".

Parameters​

client​

| ResourceClientConfig<JsonObject> | CollectionClientConfig<JsonObject> | undefined

Returns​

boolean


introspectStateKeys()​

function introspectStateKeys(stateSchema): Set<string> | undefined;

Best-effort Zod schema introspection. Returns the top-level keys of a ZodObject schema, or undefined when the schema is anything else (union, discriminated union, effects, primitives, null/undefined).

Used at build time to validate expose / exclude field lists against a state schema. Callers MUST treat undefined as "skip validation" rather than "no keys" — the silent-skip contract is what lets expose work against schemas that the framework can't reflect into.

NOTE: This uses a defensive schema.shape read for unknown input — it is intentionally distinct from getZodObjectShape which takes ZodTypeAny and reads _def.shape().

Parameters​

stateSchema​

unknown

Returns​

Set<string> | undefined


isMergeableScopeStateSchema()​

function isMergeableScopeStateSchema(schema): boolean;

true when schema is a state schema the merge can read: a z.object under the root wrappers. Anything else can only be declared once per scope.

Parameters​

schema​

ZodTypeAny

Returns​

boolean


isOneOffSessionId()​

function isOneOffSessionId(sessionId): boolean;

Whether sessionId has the one-off prefix.

Parameters​

sessionId​

string

Returns​

boolean


isTransientSlot()​

function isTransientSlot(schema): boolean;

Returns true when the schema instance has been stamped by transientSlot().

Parameters​

schema​

ZodTypeAny | undefined

Returns​

boolean


isWindowsReservedName()​

function isWindowsReservedName(name): boolean;

True when name is a name Windows reserves for a device, in any letter case.

Whole-name match only. Windows refuses these names with any extension — con.txt is as unopenable as con — so a caller checking a file passes its basename without the extension. A name authored on macOS or Linux that fails this check produces a repository or store that cannot be checked out or opened on Windows.

Parameters​

name​

string

Returns​

boolean


isZodObject()​

function isZodObject(schema): boolean;

Returns true when the schema is a z.object({...}).

Parameters​

schema​

ZodTypeAny

Returns​

boolean


keyPrefixSuccessor()​

function keyPrefixSuccessor(prefix): string | null;

The exclusive upper bound of the keys that start with prefix, in byte (code-point) order: the prefix with its last code point incremented, after dropping trailing code points that are already the highest.

Returns null when no upper bound exists: an empty prefix (every key matches), or one made only of U+10FFFF. The caller then reads key >= prefix alone.

Parameters​

prefix​

string

Returns​

string | null


looseDeepEqual()​

function looseDeepEqual(a, b): boolean;

Lenient structural equality for UI-side memoization (e.g. skipping a React re-render when projected data is unchanged).

Unlike deepEqual, this never throws: exotic shapes (Map, Set, Date, functions) compare by === / own-key recursion rather than failing fast. It is intentionally permissive because the data it compares is arbitrary client-projected state, not the framework's JSON-shaped persisted state. Use deepEqual for the state-write no-op guard; use this for "did this render input change?" checks where a false negative only costs a re-render.

Parameters​

a​

unknown

b​

unknown

Returns​

boolean


mergeScopeStateSchemas()​

function mergeScopeStateSchemas(
owner,
scope,
declarations
): ZodTypeAny | undefined;

Merge every declaration of one scope's state into one schema, or throw ScopeStateSchemaConflictError on the first two that disagree.

Returns undefined when nothing declares the scope, and the declared schema itself when one schema does, so a flow whose blocks add nothing reads exactly what it declared. Never calls an author's default factory.

Parameters​

owner​

string

Who the merge is for, as a refusal opens: Flow "my-app".

scope​

string

The scope, as a field path starts: session.

declarations​

readonly ScopeStateDeclaration[]

Every declaration, in the order a refusal names them.

Returns​

ZodTypeAny | undefined


omitSecretFields()​

function omitSecretFields<T>(config, state): JsonObject;

state without the fields config.secret names — what every read that leaves the server starts from. Returns state itself when nothing is secret, so the common path allocates nothing.

Type Parameters​

T​

T extends JsonObject

Parameters​

config​
secret?​

readonly string[]

state​

T

Returns​

JsonObject


oneOffSessionId()​

function oneOffSessionId(): string;

A fresh one-off session id: the only place such an id is made. Browser-safe. A caller sending a one-shot action passes it as the run's session id; the session is born on the run's first write, and the navigator folds it as a one-off.

Returns​

string


readCommitted()​

function readCommitted<TState, TResult>(ref, project): Promise<TResult | undefined>;

Read a resource's state as it is committed now, not as this request first read it.

A request's resource reads are the snapshot it took when it first touched each key, so a value another request wrote since is invisible to a plain read. A write that changes nothing is checked against the stored row before it reports "no change", and refreshes from it when the two differ, so running one and projecting what it saw reads the committed state, and writes nothing. For a waiter that polls a value another request will move.

Needs a writable resource or collection ref: it reads through updateState, so on a ref declared writable: false it is refused with resource_read_only and project never runs.

Returns undefined when the updater never ran (see withOutcome).

const status = await readCommitted(rowRef, (row) => row?.status);

Type Parameters​

TState​

TState

TResult​

TResult

Parameters​

ref​

UpdateStateRunner<TState>

project​

(state) => TResult

Returns​

Promise<TResult | undefined>


resolveClientData()​

function resolveClientData<TState>(config, state):
| JsonValue
| Promise<JsonValue>;

The client view of state: config.client's projection run on the full state, then any secret field dropped from the result's top level. A client.data function sees the whole state (its parameter type says so) and can derive from a secret, as in hasKey: s.value !== ""; it cannot pass one through under its own name. Every engine read that sends a projection to a client goes through here.

Type Parameters​

TState​

TState extends JsonObject

Parameters​

config​
client?​

| ResourceClientConfig<TState> | CollectionClientConfig<TState>

secret?​

readonly string[]

state​

TState

Returns​

| JsonValue | Promise<JsonValue>


resolveClientProjection()​

function resolveClientProjection<TState>(client, state):
| JsonValue
| Promise<JsonValue>;

Resolves the clientData payload for a resource or collection item.

  • client === undefined → identity (raw state). Server call sites are responsible for gating on client.state.read / clientData presence before calling.
  • client.data function → invoked with state. May return a Promise.
  • client.expose → pick the listed keys.
  • client.exclude → all keys except the listed ones.
  • otherwise → identity (raw state). This is the default and removes the historical silent-empty { topic } footgun.

Type Parameters​

TState​

TState extends JsonObject

Parameters​

client​

| ResourceClientConfig<TState> | CollectionClientConfig<TState> | undefined

state​

TState

Returns​

| JsonValue | Promise<JsonValue>


resourceStateConflict()​

function resourceStateConflict<TState>(row): VersionConflict<TState>;

Build the conflict a caller sees for row.

A conflict reports the current live value, or undefined when the row is a tombstone or absent — the distinction a caller needs in order to treat a deleted resource as terminal rather than refreshing from a stale cache. The version is the row's, or 0 when there is no row.

currentValue is deep-copied out of the row. A conflict exists to tell the losing writer what is actually stored, so handing it a live reference into the row would let the loser mutate the winner's value without touching the winner's version. The in-memory adapter is the caller that makes this load-bearing: it passes its retained row straight in. Adapters that pass a row parsed for that one query pay one small clone on an already-failed write.

Type Parameters​

TState​

TState

Parameters​

row​

VersionedRow<TState> | undefined

Returns​

VersionConflict<TState>


sanitizeToolName()​

function sanitizeToolName(name): string;

Tool-name sanitization for provider compatibility.

Framework tool blocks use a flexible naming convention that supports namespacing via . and / (e.g. tf.memory/recall). Most LLM providers — notably OpenAI — restrict tool names to ^[a-zA-Z0-9_-]+$. We rewrite any character outside that pattern to _ before submitting to the model and before listing the tool in any prompt context the model sees, so the name surfaced to the model matches the name it must call.

Sanitization is universal — applied regardless of provider — so flow authors don't have to reason about which provider their flow will run against. The framework retains the original name internally for observability, item provenance, and tool-block routing.

Parameters​

name​

string

Returns​

string


segmentNameProblem()​

function segmentNameProblem(segment): SegmentNameProblem | undefined;

The first part of the naming rule segment breaks, or undefined when the name is legal. The caller words the refusal, since what the name is (a kit, a team folder, a document file) belongs to the caller.

Parameters​

segment​

string

Returns​

SegmentNameProblem | undefined


shortId()​

function shortId(length?): string;

Generate a short random alphanumeric ID.

Parameters​

length?​

number

Returns​

string


stripAnsi()​

function stripAnsi(text): string;

text with its ANSI control sequences (ESC [ … final, the colour and style codes terminals interpret, colon-form SGR included) removed. Text without any comes back as is.

Parameters​

text​

string

Returns​

string


stripTransientKeys()​

function stripTransientKeys<T>(state, transientKeys): T;

Return a shallow copy of state with all keys in transientKeys removed. The input is not mutated. When transientKeys is empty, the original reference is returned (no allocation).

Type Parameters​

T​

T extends Record<string, unknown>

Parameters​

state​

T

transientKeys​

Set<string> | undefined

Returns​

T


toError()​

function toError(value, fallback?): Error;

Pass an Error through. A non-empty string becomes new Error(value). Anything else becomes new Error(fallback).

fallback defaults to "Unknown block execution error" so existing block-runtime callers keep their message. Hosts that normalize throws outside a block (the engine route layer, the SSE client) pass their own fallback.

Parameters​

value​

unknown

fallback?​

string

Returns​

Error


tokenize()​

function tokenize(text): string[];

Tokenize a string into lowercase word tokens, stripping punctuation.

Parameters​

text​

string

Returns​

string[]


tokenOverlap()​

function tokenOverlap(a, b): number;

Compute token overlap ratio between two strings. Returns a value [0, 1] representing the fraction of tokens in a that appear in b.

Parameters​

a​

string

b​

string

Returns​

number


updateStateWith()​

function updateStateWith<TState, TResult>(ref, updater): Promise<TResult | undefined>;

withOutcome bound to a resource's updateState, so the 20-odd resource-side call sites never see the runner argument.

return (await updateStateWith(ref, (s) => {
const idx = s.entries.findIndex((e) => e.id === id)
if (idx < 0) return { state: s, result: false }
return { state: { ...s, entries: withoutIndex(s.entries, idx) }, result: true }
})) ?? false

Type Parameters​

TState​

TState

TResult​

TResult

Parameters​

ref​

UpdateStateRunner<TState>

updater​

(state) => | UpdateOutcome<TState, TResult> | Promise<UpdateOutcome<TState, TResult>>

Returns​

Promise<TResult | undefined>


validateClientProjection()​

function validateClientProjection(args): void;

Throws at definition time when the client projection config is ambiguous (more than one of expose/exclude/data set), references a field name that isn't on the state schema, or sets live on a resource whose clientData isn't client-visible. definer is included verbatim in the error message so authors can grep for the location.

ref is the resource ref or collection pattern — surfaced in the error to disambiguate when many resources are defined in one file. kind selects the live visibility gate: a collection ships per-item clientData under state.read: true (or a projection); a single resource ships it only under a projection (no state.read gate exists for singles).

Parameters​

args​
client​

ProjectionClient

definer​

string

kind​

"collection" | "single"

ref​

string

secret?​

readonly string[]

stateSchema​

unknown

Returns​

void


withOutcome()​

function withOutcome<TState, TNext, TResult>(run, updater): Promise<TResult | undefined>;

Run a mutation through run, returning the updater's own outcome.

run is any function that applies a mutator — ref.updateState, a scope's atomicState, or a wrapper like the task collection's casWrite. Parameterising by the runner rather than by a resource is what lets one helper cover every replay entry point.

Returns undefined when the updater never completed an invocation — either the runner did not invoke it, or every invocation threw and the runner absorbed it. undefined means "nothing was reported", which is also the correct answer for "nothing was committed".

An async updater requires a runner that accepts one — see OutcomeUpdater. Without that constraint an async updater type-checks against a synchronous runner and hands it a Promise where it expects the next state, which the runner then persists.

Type Parameters​

TState​

TState

TNext​

TNext

TResult​

TResult

Parameters​

run​

(mutator) => Promise<unknown>

updater​

OutcomeUpdater<TState, TNext, TResult>

Returns​

Promise<TResult | undefined>


withTimeout()​

function withTimeout<TValue>(
promise,
timeoutMs,
label,
onTimeout?
): Promise<TValue>;

Resolve promise, or reject once timeoutMs elapses.

The bounded work is not cancelled — nothing here can cancel a promise somebody else handed us. What a timeout buys is that the caller stops waiting. Pair it with an AbortSignal when the work itself is cancellable.

Type Parameters​

TValue​

TValue

Parameters​

promise​

Promise<TValue>

The work to bound.

timeoutMs​

number | undefined

The deadline. undefined, Infinity or <= 0 means "no deadline" — promise is returned untouched and no timer is created.

label​

string

Names the bounded work in the rejection message.

onTimeout?​

(label, timeoutMs) => Error

Builds the rejection. Override it when a caller needs its own error type — a timeout that must be classified rather than just reported. Defaults to a plain Error.

Returns​

Promise<TValue>

References​

__resetDeprecationWarningsForTests​

Re-exports __resetDeprecationWarningsForTests


mapLimit​

Re-exports mapLimit


transientSlot​

Re-exports transientSlot