foldkit-remote 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["windowKey","DomainEntity"],"sources":["../src/requirement.ts","../src/store.ts","../src/mutation.ts","../src/query.ts","../src/wire.ts","../src/coalesce.ts","../src/client.ts","../src/connection.ts","../src/relation.ts","../src/selection.ts","../src/entity.ts","../src/inspect.ts","../src/optimistic.ts","../src/live.ts","../src/plan.ts","../src/retain.ts","../src/persistence.ts","../src/remoteData.ts","../src/model.ts","../src/policy.ts","../src/index.ts"],"sourcesContent":["/**\n * What a Remote Projection needs from the server: entity slices and query\n * connections. They ride on `Projection.metadata` under Remote's own keys, so\n * Surface composes them without knowing their shape.\n */\nimport { Metadata } from 'foldkit-surface'\nimport type { QueryWindow } from './query.js'\n\n/**\n * The slice required of an entity. `windows` carries a pagination window per\n * relation field, and `relations` the slice required of each relation's\n * target, so one requirement describes a whole selection graph.\n */\nexport interface RelationRequirement {\n readonly entity: string\n readonly fields: readonly string[]\n readonly windows?: Readonly<Record<string, QueryWindow>> | undefined\n readonly relations?: Readonly<Record<string, RelationRequirement>> | undefined\n}\n\nexport interface Requirement extends RelationRequirement {\n readonly id: string\n /** The projection also subscribes to changes of this entity (`Data.live`). */\n readonly live?: boolean | undefined\n}\n\n/**\n * A query connection a projection reads: the page it first asks for and the\n * slice it selects of each item. `identity` is the connection's (query plus\n * canonical input, excluding the window).\n */\nexport interface ConnectionRequirement {\n readonly identity: string\n readonly window: QueryWindow\n readonly select: RelationRequirement\n}\n\nconst windowKey = (window: QueryWindow): string =>\n JSON.stringify([\n window.first ?? null,\n window.last ?? null,\n window.after ?? null,\n window.before ?? null,\n ])\n\n/**\n * Merges connection requirements for the same connection and window into one,\n * unioning what they select of each item; the first keeps its other properties.\n */\nfunction mergeConnections(\n connections: readonly ConnectionRequirement[],\n): readonly ConnectionRequirement[] {\n const merged = new Map<string, ConnectionRequirement>()\n for (const connection of connections) {\n const key = `${connection.identity}\\u0000${windowKey(connection.window)}`\n const current = merged.get(key)\n merged.set(\n key,\n current === undefined\n ? connection\n : { ...current, select: mergeRelation(current.select, connection.select) },\n )\n }\n return [...merged.values()]\n}\n\n/** Unions two relation slices for the same target: fields, windows, and nested relations. */\nfunction mergeRelation(\n current: RelationRequirement,\n next: RelationRequirement,\n): RelationRequirement {\n const fields = [...current.fields]\n const seen = new Set(fields)\n for (const field of next.fields) {\n if (seen.has(field)) continue\n seen.add(field)\n fields.push(field)\n }\n const windows = { ...current.windows, ...next.windows }\n const relations = mergeRelations(current.relations, next.relations)\n return {\n entity: current.entity,\n fields,\n ...(Object.keys(windows).length === 0 ? {} : { windows }),\n ...(relations === undefined ? {} : { relations }),\n }\n}\n\n/** Unions two relation maps field by field; a field in both merges recursively. */\nfunction mergeRelations(\n current: Readonly<Record<string, RelationRequirement>> | undefined,\n next: Readonly<Record<string, RelationRequirement>> | undefined,\n): Readonly<Record<string, RelationRequirement>> | undefined {\n if (current === undefined) return next\n if (next === undefined) return current\n const merged: Record<string, RelationRequirement> = { ...current }\n for (const [field, relation] of Object.entries(next)) {\n const existing = merged[field]\n merged[field] = existing === undefined ? relation : mergeRelation(existing, relation)\n }\n return merged\n}\n\n/** Unions requirements for the same entity + id, dropping duplicate fields. */\nfunction mergeRequirements(requirements: readonly Requirement[]): readonly Requirement[] {\n const grouped = new Map<string, Requirement>()\n for (const requirement of requirements) {\n const key = `${requirement.entity}\\u0000${requirement.id}`\n // Later windows win; a duplicate is a caller bug, not a merge policy.\n const group = grouped.get(key)\n const live = group?.live === true || requirement.live === true\n grouped.set(key, {\n ...mergeRelation(group ?? { entity: requirement.entity, fields: [] }, requirement),\n id: requirement.id,\n ...(live ? { live } : {}),\n })\n }\n return [...grouped.values()]\n}\n\n/**\n * Requirement helpers, for the packages that plan and serve requirements.\n * `merge` unions same-entity+id requirements; `mergeRelation` unions two\n * slices of one target (fields, windows, nested relations).\n */\nexport const Requirement = {\n merge: mergeRequirements,\n mergeRelation,\n mergeConnections,\n}\n\n/** Remote's entity requirements on a Projection, unioned per entity and id as nodes compose. */\nexport const RemoteRequirements = Metadata.key<Requirement>('remote', {\n merge: mergeRequirements,\n summarize: requirement => `${requirement.entity}:${requirement.id}`,\n})\n\n/** Remote's query connections on a Projection, unioned per connection and window. */\nexport const RemoteConnections = Metadata.key<ConnectionRequirement>('remote.connection', {\n merge: mergeConnections,\n summarize: connection => connection.identity.split('\\u0000').join(' '),\n})\n\n/** The entity requirements a Projection carries. */\nexport const requirementsOf = (projection: {\n readonly metadata: Metadata\n}): ReadonlyArray<Requirement> => RemoteRequirements.get(projection.metadata)\n\n/** The query connections a Projection carries. */\nexport const connectionsOf = (projection: {\n readonly metadata: Metadata\n}): ReadonlyArray<ConnectionRequirement> => RemoteConnections.get(projection.metadata)\n","/**\n * The pure entity store: values, per-field presence, staleness, and tombstones.\n *\n * Presence is tracked **separately** from values, so `undefined`/`null`/absent/\n * stale/not-found are distinct states and a missing field is never inferred from\n * `value === undefined`. Nothing here performs I/O; every operation returns a\n * new store.\n */\nimport { Option } from 'effect'\n\nexport type EntityKey = string\n\nexport interface EntityEntry {\n readonly values: Readonly<Record<string, unknown>>\n readonly present: ReadonlySet<string>\n /** Present fields whose value may be outdated (revalidation needed). */\n readonly stale: ReadonlySet<string>\n /** The entity is known to be absent; a later write clears this. */\n readonly tombstone: boolean\n /** Injected clock reading of the last write; never read from ambient state. */\n readonly updatedAt: number\n /**\n * The canonical window each present field was fetched with (`\"\"` for none).\n * A later request with a *known, different* window is planned as missing.\n */\n readonly windows: Readonly<Record<string, string>>\n}\n\nexport type EntityStore = Readonly<Record<EntityKey, EntityEntry>>\n\n/** The separator keeps an untrusted id from colliding with a prototype key. */\nexport const entityKey = (entity: string, id: string): EntityKey => `${entity}:${id}`\n\nconst emptyEntry: EntityEntry = {\n values: {},\n present: new Set(),\n stale: new Set(),\n tombstone: false,\n updatedAt: 0,\n windows: {},\n}\n\nexport const emptyStore: EntityStore = {}\n\nconst replace = (store: EntityStore, key: EntityKey, entry: EntityEntry): EntityStore => ({\n ...store,\n [key]: entry,\n})\n\nconst written = (\n previous: EntityEntry,\n values: Readonly<Record<string, unknown>>,\n now: number,\n windows?: Readonly<Record<string, string>>,\n): EntityEntry => {\n const present = new Set(previous.present)\n const stale = new Set(previous.stale)\n const nextWindows: Record<string, string> = { ...previous.windows }\n for (const field of Object.keys(values)) {\n present.add(field)\n stale.delete(field)\n // A write without a window clears any remembered one: the value changed.\n const requested = windows?.[field]\n if (requested !== undefined && requested !== '') nextWindows[field] = requested\n else delete nextWindows[field]\n }\n return {\n values: { ...previous.values, ...values },\n present,\n stale,\n tombstone: false,\n updatedAt: now,\n windows: nextWindows,\n }\n}\n\nexport interface EntityWrite {\n readonly key: EntityKey\n readonly values: Readonly<Record<string, unknown>>\n /** The canonical window each written relation field was fetched with. */\n readonly windows?: Readonly<Record<string, string>> | undefined\n}\n\n/**\n * Merges known values into many entities, copying the store once. Every\n * written field becomes present and non-stale; a tombstone is cleared because\n * the entity is evidently not absent.\n */\nexport const writeEntities = (\n store: EntityStore,\n writes: ReadonlyArray<EntityWrite>,\n now = 0,\n): EntityStore => {\n if (writes.length === 0) return store\n const next: Record<EntityKey, EntityEntry> = { ...store }\n for (const write of writes) {\n next[write.key] = written(next[write.key] ?? emptyEntry, write.values, now, write.windows)\n }\n return next\n}\n\n/** `writeEntities` for one entity. */\nexport const writeEntity = (\n store: EntityStore,\n key: EntityKey,\n values: Readonly<Record<string, unknown>>,\n now = 0,\n windows?: Readonly<Record<string, string>>,\n): EntityStore => writeEntities(store, [{ key, values, windows }], now)\n\n/**\n * Marks present fields stale (`true`) or ends their staleness (`false`) across\n * many entities, copying the store once. A field never present stays missing;\n * an unknown entity is left alone.\n */\nexport const setStale = (\n store: EntityStore,\n marks: ReadonlyArray<readonly [key: EntityKey, fields: Iterable<string>]>,\n stale: boolean,\n): EntityStore => {\n let next: Record<EntityKey, EntityEntry> | undefined\n for (const [key, fields] of marks) {\n const previous = (next ?? store)[key]\n if (previous === undefined) continue\n const staleFields = new Set(previous.stale)\n for (const field of fields) {\n if (stale) {\n if (previous.present.has(field)) staleFields.add(field)\n } else staleFields.delete(field)\n }\n // Only ever added to or only ever removed from, so an equal size is the same set.\n if (staleFields.size === previous.stale.size) continue\n next ??= { ...store }\n next[key] = { ...previous, stale: staleFields }\n }\n return next ?? store\n}\n\n/** Marks present fields stale; fields that were never present stay missing. */\nexport const markStale = (\n store: EntityStore,\n key: EntityKey,\n fields: Iterable<string>,\n): EntityStore => setStale(store, [[key, fields]], true)\n\n/** Ends a refresh that did not land: the fields are present again as they were. */\nexport const clearStale = (\n store: EntityStore,\n key: EntityKey,\n fields: Iterable<string>,\n): EntityStore => setStale(store, [[key, fields]], false)\n\n/** Records that the entity is known to be absent, so it is not refetched. */\nexport const tombstone = (store: EntityStore, key: EntityKey): EntityStore =>\n replace(store, key, {\n values: {},\n present: new Set(),\n stale: new Set(),\n tombstone: true,\n updatedAt: 0,\n windows: {},\n })\n\n/** Forgets everything known about the entity, including a tombstone. */\nexport const remove = (store: EntityStore, key: EntityKey): EntityStore => {\n if (store[key] === undefined) return store\n const next = { ...store }\n delete next[key]\n return next\n}\n\nexport const entry = (store: EntityStore, key: EntityKey): Option.Option<EntityEntry> => {\n const value = store[key]\n return value === undefined ? Option.none() : Option.some(value)\n}\n\nexport const isTombstone = (store: EntityStore, key: EntityKey): boolean =>\n store[key]?.tombstone === true\n\n/** A field is known only if it is present and not stale. */\nexport const hasField = (store: EntityStore, key: EntityKey, field: string): boolean => {\n const value = store[key]\n return (\n value !== undefined && !value.tombstone && value.present.has(field) && !value.stale.has(field)\n )\n}\n\n/** A present field whose value may be outdated; absent fields are not stale. */\nexport const isFieldStale = (store: EntityStore, key: EntityKey, field: string): boolean => {\n const value = store[key]\n return value !== undefined && !value.tombstone && value.stale.has(field)\n}\n\n/**\n * Reads a present field, stale or not. Absence and a tombstone both yield\n * `Option.none()`; a present `undefined`/`null` yields `Option.some`.\n */\nexport const readField = (\n store: EntityStore,\n key: EntityKey,\n field: string,\n): Option.Option<unknown> => {\n const value = store[key]\n if (value === undefined || value.tombstone || !value.present.has(field)) return Option.none()\n return Option.some(value.values[field])\n}\n\n/**\n * The fields the planner must fetch. A tombstone makes every field known\n * (absent), so it returns an empty list and the entity is not refetched. A\n * requested window that differs from the one a field was fetched with also\n * marks it missing, but only when the stored window is known (never `\"\"`), so a\n * writer that does not record windows cannot cause a refetch loop.\n */\nexport const missingFields = (\n store: EntityStore,\n key: EntityKey,\n fields: Iterable<string>,\n windows?: Readonly<Record<string, string>>,\n): ReadonlyArray<string> => {\n const value = store[key]\n if (value !== undefined && value.tombstone) return []\n return [...fields].filter(field => {\n if (value === undefined || !value.present.has(field) || value.stale.has(field)) return true\n const requested = windows?.[field]\n const stored = value.windows[field]\n return requested !== undefined && stored !== undefined && stored !== '' && stored !== requested\n })\n}\n","/**\n * Mutation status and idempotent reconciliation.\n *\n * A mutation result is reconciled into the store **at most once per\n * `requestId`**, so a transport retry cannot apply the same change twice. An\n * unknown or already-applied result is a no-op.\n */\nimport { Schema } from 'effect'\nimport type { RemoteError } from './remoteData.js'\nimport { entityKey, tombstone, writeEntity, type EntityStore } from './store.js'\n\nexport interface NormalizedPatch {\n readonly entity: string\n readonly id: string\n readonly values: Readonly<Record<string, unknown>>\n}\n\nexport interface MutationState {\n readonly pending: ReadonlySet<string>\n readonly applied: ReadonlySet<string>\n readonly failed: ReadonlySet<string>\n /** Why each request in `failed` failed, kept exactly as long as `failed` keeps its id. */\n readonly errors: ReadonlyMap<string, RemoteError>\n /**\n * How many mutations this model has started. A bound domain takes its next\n * request id from here, so `update` stays pure and the id exists before the\n * Command runs.\n */\n readonly sequence: number\n}\n\nexport const emptyMutationState: MutationState = {\n pending: new Set(),\n applied: new Set(),\n failed: new Set(),\n errors: new Map(),\n sequence: 0,\n}\n\n/**\n * How many settled request ids a mutation state retains. A retry settles well\n * inside this window, so bounding the ledger stops a long-lived application\n * from growing it without limit; a retry older than the window would re-apply\n * its entities.\n */\nconst MUTATION_ID_WINDOW = 1024\n\n/** Records `id` as most recent, evicting the oldest once the window is full. */\nconst remember = (ids: ReadonlySet<string>, id: string): ReadonlySet<string> => {\n const next = new Set(ids)\n // Re-inserting an existing id moves it to the most-recent end.\n next.delete(id)\n next.add(id)\n if (next.size <= MUTATION_ID_WINDOW) return next\n return new Set([...next].slice(next.size - MUTATION_ID_WINDOW))\n}\n\nexport const beginMutation = (state: MutationState, requestId: string): MutationState => ({\n ...state,\n pending: new Set([...state.pending, requestId]),\n sequence: state.sequence + 1,\n})\n\nexport const failMutation = (\n state: MutationState,\n requestId: string,\n error: RemoteError,\n): MutationState => {\n const pending = new Set(state.pending)\n pending.delete(requestId)\n const failed = remember(state.failed, requestId)\n const errors = new Map([...state.errors, [requestId, error] as const])\n // `failed` is a bounded window; an error outlives its id by nothing.\n for (const id of errors.keys()) if (!failed.has(id)) errors.delete(id)\n return { ...state, pending, failed, errors }\n}\n\n/** What Remote knows of one mutation request, by the id `mutate` returned. */\nexport type MutationStatus =\n /** Never started here, or settled so long ago its id has left the window. */\n | { readonly _tag: 'Unknown' }\n | { readonly _tag: 'Pending' }\n | { readonly _tag: 'Applied' }\n | { readonly _tag: 'Failed'; readonly error: RemoteError }\n\nexport const mutationStatus = (state: MutationState, requestId: string): MutationStatus => {\n // A retry reuses its request id, so the latest outcome wins: in flight, then\n // applied (a request cannot fail once applied), then the failure it last had.\n if (state.pending.has(requestId)) return { _tag: 'Pending' }\n if (state.applied.has(requestId)) return { _tag: 'Applied' }\n const error = state.errors.get(requestId)\n return error === undefined ? { _tag: 'Unknown' } : { _tag: 'Failed', error }\n}\n\nexport interface Reconciled {\n readonly store: EntityStore\n readonly state: MutationState\n}\n\n/**\n * Applies a mutation result once and marks the request settled. A second call\n * with the same `requestId` (a retry, or a live event describing the same change)\n * does not re-apply the entities, but still clears `pending`.\n */\nexport const reconcileMutation = (\n store: EntityStore,\n state: MutationState,\n requestId: string,\n entities: ReadonlyArray<NormalizedPatch>,\n deleted: ReadonlyArray<{ readonly entity: string; readonly id: string }> = [],\n): Reconciled => {\n // Patches first, then deletions: a mutation that names an entity both ways has deleted it.\n const next = state.applied.has(requestId)\n ? store\n : deleted.reduce(\n (current, gone) => tombstone(current, entityKey(gone.entity, gone.id)),\n entities.reduce(\n (current, entity) =>\n writeEntity(current, entityKey(entity.entity, entity.id), entity.values),\n store,\n ),\n )\n const applied = remember(state.applied, requestId)\n const pending = new Set(state.pending)\n pending.delete(requestId)\n return { store: next, state: { ...state, applied, pending } }\n}\n\n/** A mutation an application declares: its name and input/output codecs. */\nexport interface MutationDescriptor<Name extends string, Input, Output> {\n readonly name: Name\n readonly Input: Schema.Codec<Input>\n readonly Output: Schema.Codec<Output>\n}\n\n/** A codec, or the fields of a `Schema.Struct` where one is expected. */\nexport type SchemaOrFields = Schema.Codec<any, any, any, any> | Schema.Struct.Fields\n\n/** The decoded type of a codec, or of the Struct the fields describe. */\nexport type TypeOf<S extends SchemaOrFields> =\n S extends Schema.Codec<infer T, any, any, any>\n ? T\n : S extends Schema.Struct.Fields\n ? Schema.Struct.Type<S>\n : never\n\n/** The codec itself, or a `Schema.Struct` over the fields. */\nexport const schemaOf = <S extends SchemaOrFields>(shape: S): Schema.Codec<TypeOf<S>> =>\n (Schema.isSchema(shape) ? shape : Schema.Struct(shape as Schema.Struct.Fields)) as Schema.Codec<\n TypeOf<S>\n >\n\nexport const Mutation = {\n /**\n * Declares a mutation. `Input` and `Output` are codecs, or the fields of the\n * `Schema.Struct` they would be (`{ id: ProjectId, name: Schema.String }`).\n */\n make: <const Name extends string, Input extends SchemaOrFields, Output extends SchemaOrFields>(\n name: Name,\n config: { readonly Input: Input; readonly Output: Output },\n ): MutationDescriptor<Name, TypeOf<Input>, TypeOf<Output>> => ({\n name,\n Input: schemaOf(config.Input),\n Output: schemaOf(config.Output),\n }),\n}\n","/**\n * Queries and connections. A connection's identity is its descriptor plus the\n * canonical encoded filter/sort input — **never** the pagination window, so\n * `first(25)` and `after(cursor).first(25)` address the same logical connection.\n */\nimport { Schema } from 'effect'\nimport type { Cursor } from './connection.js'\nimport { schemaOf, type SchemaOrFields, type TypeOf } from './mutation.js'\n\nexport type LiveInsertion = 'visible' | 'boundary' | 'invalidate' | 'ignore'\n\nexport interface LivePolicy {\n readonly prepend?: LiveInsertion\n readonly append?: LiveInsertion\n}\n\nexport interface ConnectionSpec<Entity extends string = string> {\n readonly entity: Entity\n readonly edgeKey?: Schema.Schema<unknown>\n readonly live?: LivePolicy\n}\n\nexport interface QueryWindow {\n readonly first?: number | undefined\n readonly last?: number | undefined\n readonly after?: Cursor | undefined\n readonly before?: Cursor | undefined\n}\n\nexport interface QueryRef<Name extends string, Input> {\n readonly query: Name\n readonly input: Input\n /** The input codec, so a `QueryRef` can encode itself without its descriptor. */\n readonly Input: Schema.Codec<Input>\n readonly window: QueryWindow\n /** Connection identity: descriptor + canonical input, excluding the window. */\n readonly identity: string\n}\n\nexport interface QueryDescriptor<Name extends string, Input, Result> {\n readonly name: Name\n readonly Input: Schema.Codec<Input>\n readonly Result: Result\n readonly ref: (input: Input) => QueryRef<Name, Input>\n}\n\n/** Stable stringify: object keys sorted, undefined-valued keys dropped, so equal inputs encode equally. */\nexport const stableStringify = (value: unknown): string => {\n if (value === undefined) return 'null'\n if (value === null || typeof value !== 'object') return JSON.stringify(value)\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`\n const record = value as Record<string, unknown>\n return `{${Object.keys(record)\n .filter(key => record[key] !== undefined)\n .sort()\n .map(key => `${JSON.stringify(key)}:${stableStringify(record[key])}`)\n .join(',')}}`\n}\n\n/**\n * `Result: Project` (or anything with the entity's `name`, as `Query.connection`\n * takes) means a connection over it; a `ConnectionSpec` names its `entity`\n * instead and is the result as given.\n */\nexport type ResultOf<Result> = Result extends { readonly name: infer Entity extends string }\n ? ConnectionSpec<Entity>\n : Result\n\nconst isEntityName = (result: unknown): result is { readonly name: string } =>\n typeof result === 'object' &&\n result !== null &&\n typeof (result as { readonly name?: unknown }).name === 'string'\n\nexport const Query = {\n /** Declares the entity and options a query's result is a connection over. */\n connection: <Entity extends string>(\n entity: { readonly name: Entity },\n options?: { readonly edgeKey?: Schema.Schema<unknown>; readonly live?: LivePolicy },\n ): ConnectionSpec<Entity> => ({\n entity: entity.name,\n ...(options?.edgeKey === undefined ? {} : { edgeKey: options.edgeKey }),\n ...(options?.live === undefined ? {} : { live: options.live }),\n }),\n\n /**\n * Declares a query. `Input` is a codec or the fields of the `Schema.Struct` it\n * would be; `Result` is a `Query.connection(...)`, or the entity the result is\n * a connection over.\n */\n make: <const Name extends string, Input extends SchemaOrFields, Result>(\n name: Name,\n config: { readonly Input: Input; readonly Result: Result },\n ): QueryDescriptor<Name, TypeOf<Input>, ResultOf<Result>> => {\n const Input = schemaOf(config.Input)\n const encode = Schema.encodeSync(Input)\n return {\n name,\n Input,\n Result: (isEntityName(config.Result)\n ? Query.connection(config.Result)\n : config.Result) as ResultOf<Result>,\n ref: input => ({\n query: name,\n input,\n Input,\n window: {},\n identity: `${name}\\u0000${stableStringify(encode(input))}`,\n }),\n }\n },\n\n first:\n (count: number) =>\n <R extends QueryRef<string, unknown>>(ref: R): R => ({\n ...ref,\n window: { ...ref.window, first: count },\n }),\n\n last:\n (count: number) =>\n <R extends QueryRef<string, unknown>>(ref: R): R => ({\n ...ref,\n window: { ...ref.window, last: count },\n }),\n\n after:\n (cursor: Cursor) =>\n <R extends QueryRef<string, unknown>>(ref: R): R => ({\n ...ref,\n window: { ...ref.window, after: cursor },\n }),\n\n before:\n (cursor: Cursor) =>\n <R extends QueryRef<string, unknown>>(ref: R): R => ({\n ...ref,\n window: { ...ref.window, before: cursor },\n }),\n}\n","/**\n * The Remote wire: Effect RPC semantics over `effect/unstable/rpc`. Remote owns\n * the message shapes; Effect owns the transport. `Make`ing reads batch, mutations\n * preserve order, and live data is a stream.\n */\nimport { Schema } from 'effect'\nimport { Rpc, RpcGroup } from 'effect/unstable/rpc'\nimport type { RelationRequirement, Requirement } from './requirement.js'\n\n/**\n * The read/live protocol version. A batch names the version it speaks and the\n * server refuses a mismatch with `RemoteProtocolError`, so a shape change never\n * drifts silently: bump it whenever `ReadRequest` or `LiveRequirement` change.\n */\nexport const REMOTE_PROTOCOL_VERSION = 3\n\nexport class RemoteReadError extends Schema.TaggedError<RemoteReadError>()('RemoteReadError', {\n message: Schema.String,\n}) {}\n\nexport class RemoteMutationError extends Schema.TaggedError<RemoteMutationError>()(\n 'RemoteMutationError',\n { message: Schema.String },\n) {}\n\nexport class RemoteLiveError extends Schema.TaggedError<RemoteLiveError>()('RemoteLiveError', {\n message: Schema.String,\n}) {}\n\n/** The peer speaks another protocol version; nothing was read. */\nexport class RemoteProtocolError extends Schema.TaggedError<RemoteProtocolError>()(\n 'RemoteProtocolError',\n { message: Schema.String, expected: Schema.Number, received: Schema.Number },\n) {}\n\n/** A page size: a non-negative integer, refused at decode otherwise rather than defaulted. */\nexport const PageSize = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))\n\nexport const WindowSchema = Schema.Struct({\n first: Schema.optional(PageSize),\n last: Schema.optional(PageSize),\n after: Schema.optional(Schema.String),\n before: Schema.optional(Schema.String),\n})\n\n/** A request may not name more fields of one entity than this; a selection never does. */\nexport const MAX_FIELDS_PER_REQUEST = 256\n/** A selection may not nest relations deeper than this; the wire refuses more. */\nexport const MAX_RELATION_DEPTH = 8\n\nconst Fields = Schema.Array(Schema.String).check(Schema.isMaxLength(MAX_FIELDS_PER_REQUEST))\n\n/**\n * The slice required of a relation's target; the ids come from the parent's\n * refs. Built as `MAX_RELATION_DEPTH` nested structs rather than a recursive\n * schema, so a deeper selection is refused at decode with a schema error.\n */\nconst relationLevel = (depth: number): Schema.Codec<RelationRequirement, RelationRequirement> => {\n const slice = {\n entity: Schema.String,\n fields: Fields,\n windows: Schema.optional(Schema.Record(Schema.String, WindowSchema)),\n }\n // A struct drops an unknown key silently; the last level refuses one instead.\n return (depth === 0\n ? Schema.Struct({ ...slice, relations: Schema.optionalKey(Schema.Never) })\n : Schema.Struct({\n ...slice,\n relations: Schema.optional(Schema.Record(Schema.String, relationLevel(depth - 1))),\n })) as unknown as Schema.Codec<RelationRequirement, RelationRequirement>\n}\n\nexport const RelationRequest = relationLevel(MAX_RELATION_DEPTH - 1)\n\nexport const ReadRequest: Schema.Codec<Requirement, Requirement> = Schema.Struct({\n entity: Schema.String,\n id: Schema.String,\n fields: Fields,\n /** Pagination window per relation field. */\n windows: Schema.optional(Schema.Record(Schema.String, WindowSchema)),\n /** The slice required of each relation field's target, resolved in the same read. */\n relations: Schema.optional(Schema.Record(Schema.String, RelationRequest)),\n}) as unknown as Schema.Codec<Requirement, Requirement>\n\nexport const ReadBatch = Schema.Struct({\n version: Schema.Number,\n requests: Schema.Array(ReadRequest),\n})\n\nexport const NormalizedEntity = Schema.Struct({\n entity: Schema.String,\n id: Schema.String,\n values: Schema.Record(Schema.String, Schema.Unknown),\n})\n\nexport const ReadBatchResult = Schema.Struct({ entities: Schema.Array(NormalizedEntity) })\n\nexport const MutationRequest = Schema.Struct({\n /** Stable across transport retries so a mutation is not applied twice. */\n requestId: Schema.String,\n mutation: Schema.String,\n input: Schema.Unknown,\n})\n\nexport const LiveEdge = Schema.Struct({\n entity: Schema.String,\n id: Schema.String,\n key: Schema.String,\n})\n\n/** A connection change a mutation confirms: the same facts a live event carries, without a cursor. */\nexport const ConnectionChangeSchema = Schema.Union([\n Schema.Struct({\n _tag: Schema.Literal('Insert'),\n connection: Schema.String,\n position: Schema.Union([Schema.Literal('prepend'), Schema.Literal('append')]),\n edge: LiveEdge,\n }),\n Schema.Struct({ _tag: Schema.Literal('Remove'), connection: Schema.String, edge: LiveEdge }),\n])\n\nexport const MutationResult = Schema.Struct({\n output: Schema.Unknown,\n entities: Schema.Array(NormalizedEntity),\n /** Connection changes the mutation made, applied alongside its entity patches. */\n connections: Schema.optional(Schema.Array(ConnectionChangeSchema)),\n /** Entities the mutation deleted; the client knows them absent from then on. */\n deleted: Schema.optional(\n Schema.Array(Schema.Struct({ entity: Schema.String, id: Schema.String })),\n ),\n})\n\nexport const LiveRequirement = Schema.Struct({\n version: Schema.Number,\n requirements: Schema.Array(ReadRequest),\n /** Resume cursor; events at or before it are duplicates. */\n after: Schema.Number,\n})\n\n/**\n * A live change. Entity changes update the store; connection changes alter\n * membership and ordering; both carry a per-stream cursor.\n */\nexport const LiveChange = Schema.Union([\n Schema.Struct({\n _tag: Schema.Literal('EntityPatched'),\n cursor: Schema.Number,\n entity: Schema.String,\n id: Schema.String,\n values: Schema.Record(Schema.String, Schema.Unknown),\n changed: Schema.Array(Schema.String),\n }),\n Schema.Struct({\n _tag: Schema.Literal('EntityDeleted'),\n cursor: Schema.Number,\n entity: Schema.String,\n id: Schema.String,\n }),\n Schema.Struct({\n _tag: Schema.Literal('ConnectionInsert'),\n cursor: Schema.Number,\n connection: Schema.String,\n position: Schema.Union([Schema.Literal('prepend'), Schema.Literal('append')]),\n edge: LiveEdge,\n }),\n Schema.Struct({\n _tag: Schema.Literal('ConnectionRemove'),\n cursor: Schema.Number,\n connection: Schema.String,\n edge: LiveEdge,\n }),\n Schema.Struct({\n _tag: Schema.Literal('ConnectionInvalidate'),\n cursor: Schema.Number,\n connection: Schema.String,\n }),\n])\n\nexport const Read = Rpc.make('FoldkitRemoteRead', {\n payload: ReadBatch,\n success: ReadBatchResult,\n error: Schema.Union([RemoteReadError, RemoteProtocolError]),\n})\n\nexport const Mutate = Rpc.make('FoldkitRemoteMutate', {\n payload: MutationRequest,\n success: MutationResult,\n error: RemoteMutationError,\n})\n\nexport const Live = Rpc.make('FoldkitRemoteLive', {\n payload: LiveRequirement,\n success: LiveChange,\n error: Schema.Union([RemoteLiveError, RemoteProtocolError]),\n stream: true,\n})\n\nexport class RemoteQueryError extends Schema.TaggedError<RemoteQueryError>()('RemoteQueryError', {\n message: Schema.String,\n}) {}\n\nexport const WireBoundary = Schema.Union([\n Schema.Struct({ _tag: Schema.Literal('Terminal') }),\n Schema.Struct({ _tag: Schema.Literal('Cursor'), cursor: Schema.String }),\n Schema.Struct({ _tag: Schema.Literal('Unknown') }),\n])\n\nexport const QueryRequest = Schema.Struct({\n query: Schema.String,\n input: Schema.Unknown,\n window: WindowSchema,\n})\n\nexport const QueryEdge = Schema.Struct({\n entity: Schema.String,\n id: Schema.String,\n key: Schema.String,\n})\n\nexport const QueryResult = Schema.Struct({\n edges: Schema.Array(QueryEdge),\n start: WireBoundary,\n end: WireBoundary,\n})\n\nexport const QueryRpc = Rpc.make('FoldkitRemoteQuery', {\n payload: QueryRequest,\n success: QueryResult,\n error: RemoteQueryError,\n})\n\nexport const RemoteRpc = RpcGroup.make(Read, Mutate, QueryRpc, Live)\n","/**\n * Read coalescing: every requirement a client asks for goes through one\n * `RequestResolver`, so requirements issued together become one `ReadBatch`\n * (ids batched, fields unioned) and a requirement already in flight is joined\n * rather than re-requested. The planner stays pure; this is the transport\n * seam's concern, and the store is still the only cache.\n */\nimport {\n Deferred,\n Duration,\n Effect,\n Request,\n RequestResolver,\n type Exit,\n type Schema,\n} from 'effect'\nimport { Requirement, type RelationRequirement } from './requirement.js'\nimport { stableStringify } from './query.js'\nimport {\n REMOTE_PROTOCOL_VERSION,\n type QueryRequest,\n type QueryResult,\n type ReadBatch,\n type ReadBatchResult,\n} from './wire.js'\nimport type { RemoteProtocolError, RemoteQueryError, RemoteReadError } from './wire.js'\n\ntype Batch = Schema.Schema.Type<typeof ReadBatch>\ntype BatchResult = Schema.Schema.Type<typeof ReadBatchResult>\ntype ReadError = RemoteReadError | RemoteProtocolError\nexport type BatchRead = (batch: Batch) => Effect.Effect<BatchResult, ReadError>\ntype QueryRequestValue = Schema.Schema.Type<typeof QueryRequest>\ntype QueryResultValue = Schema.Schema.Type<typeof QueryResult>\nexport type QueryRun = (\n request: QueryRequestValue,\n) => Effect.Effect<QueryResultValue, RemoteQueryError>\n\nexport interface CoalesceOptions {\n /**\n * How long a batch waits to collect more requirements before it runs.\n * Requirements issued concurrently coalesce even at the default of no wait.\n */\n readonly window?: Duration.Input | undefined\n}\n\n/** A stable key for a requirement, so an equal requirement in flight is joined. */\nexport const requirementKey = (requirement: Requirement): string =>\n stableStringify([\n requirement.entity,\n requirement.id,\n [...requirement.fields].sort(),\n requirement.windows ?? null,\n requirement.relations ?? null,\n ])\n\n/** Whether a requirement pages a relation anywhere in its graph. */\nconst hasWindows = (requirement: RelationRequirement): boolean =>\n requirement.windows !== undefined || Object.values(requirement.relations ?? {}).some(hasWindows)\n\n/**\n * The reads a batch runs. Requirements that page nothing union into one read\n * per entity and id, and every waiter may write its whole result, since\n * plain values are the same whoever asked. A requirement that pages a\n * relation reads alone: a page answers exactly one window, and a waiter\n * cannot tell which of two pages for the same entity was its own.\n */\nconst readsOf = (\n owned: ReadonlyMap<string, Requirement>,\n): ReadonlyArray<{\n readonly keys: ReadonlyArray<string>\n readonly requests: ReadonlyArray<Requirement>\n}> => {\n const plain = [...owned].filter(([, requirement]) => !hasWindows(requirement))\n const paged = [...owned].filter(([, requirement]) => hasWindows(requirement))\n return [\n ...(plain.length === 0\n ? []\n : [\n {\n keys: plain.map(([key]) => key),\n requests: Requirement.merge(plain.map(([, requirement]) => requirement)),\n },\n ]),\n ...paged.map(([key, requirement]) => ({ keys: [key], requests: [requirement] })),\n ]\n}\n\nclass QueryRead extends Request.Class<\n { readonly key: string; readonly request: QueryRequestValue },\n QueryResultValue,\n RemoteQueryError\n> {}\n\n/**\n * Wraps a raw query so that an identical query in flight (same query, input,\n * and window) is joined rather than run again; distinct queries run\n * concurrently. A page answers exactly one window, so nothing is batched.\n */\nexport const coalesceQueries = (\n query: QueryRun,\n options: CoalesceOptions = {},\n): Effect.Effect<QueryRun> =>\n Effect.gen(function* () {\n const runAll = (entries: ReadonlyArray<Request.Entry<QueryRead>>) =>\n Effect.gen(function* () {\n const distinct = new Map<string, QueryRequestValue>()\n for (const entry of entries) distinct.set(entry.request.key, entry.request.request)\n const results = new Map<string, Exit.Exit<QueryResultValue, RemoteQueryError>>()\n yield* Effect.forEach(\n distinct,\n ([key, request]) =>\n Effect.exit(query(request)).pipe(Effect.map(exit => void results.set(key, exit))),\n { concurrency: 'unbounded', discard: true },\n )\n for (const entry of entries) {\n yield* Request.completeEffect(entry, results.get(entry.request.key)!)\n }\n })\n let resolver = RequestResolver.make<QueryRead>(runAll)\n if (options.window !== undefined) {\n resolver = RequestResolver.setDelay(resolver, Duration.fromInputUnsafe(options.window))\n }\n return request =>\n Effect.request(\n new QueryRead({\n key: stableStringify([request.query, request.input, request.window]),\n request,\n }),\n resolver,\n )\n })\n\nclass ReadRequirement extends Request.Class<\n { readonly key: string; readonly requirement: Requirement },\n BatchResult,\n ReadError\n> {}\n\n/**\n * Wraps a raw batch read so that requirements are batched and deduplicated.\n * Every waiter receives the whole batch result; `Remote.writeRead` is\n * idempotent, so writing it more than once is harmless.\n */\nexport const coalesceReads = (\n read: BatchRead,\n options: CoalesceOptions = {},\n): Effect.Effect<BatchRead> =>\n Effect.gen(function* () {\n // Requirements a batch is currently reading; a later equal requirement\n // joins the deferred instead of starting another read.\n const inFlight = new Map<string, Deferred.Deferred<BatchResult, ReadError>>()\n\n // A batch runs to completion even when every requester is interrupted, so\n // an in-flight requirement is always settled and released by its read.\n const runAll = (entries: ReadonlyArray<Request.Entry<ReadRequirement>>) =>\n Effect.gen(function* () {\n // Per requirement key: the deferred this batch's entries wait on. One\n // already in flight from an earlier batch is joined; the rest are\n // owned here and settled by this batch's read.\n const joins = new Map<string, Deferred.Deferred<BatchResult, ReadError>>()\n const own = new Map<string, Deferred.Deferred<BatchResult, ReadError>>()\n for (const entry of entries) {\n const key = entry.request.key\n if (joins.has(key)) continue\n const existing = inFlight.get(key)\n if (existing !== undefined) {\n joins.set(key, existing)\n continue\n }\n const deferred = yield* Deferred.make<BatchResult, ReadError>()\n inFlight.set(key, deferred)\n own.set(key, deferred)\n joins.set(key, deferred)\n }\n if (own.size > 0) {\n const owned = new Map<string, Requirement>()\n for (const entry of entries) {\n if (own.has(entry.request.key)) owned.set(entry.request.key, entry.request.requirement)\n }\n yield* Effect.forEach(\n readsOf(owned),\n ({ keys, requests }) =>\n Effect.gen(function* () {\n const exit = yield* Effect.exit(\n read({ version: REMOTE_PROTOCOL_VERSION, requests }),\n )\n // Settle exactly the requirements this read answered.\n for (const key of keys) {\n inFlight.delete(key)\n yield* Deferred.done(own.get(key)!, exit)\n }\n }),\n { concurrency: 'unbounded', discard: true },\n )\n }\n for (const entry of entries) {\n yield* Request.completeEffect(entry, Deferred.await(joins.get(entry.request.key)!))\n }\n })\n\n let resolver = RequestResolver.make<ReadRequirement>(runAll)\n if (options.window !== undefined) {\n resolver = RequestResolver.setDelay(resolver, Duration.fromInputUnsafe(options.window))\n }\n\n return batch =>\n batch.requests.length === 0\n ? Effect.succeed({ entities: [] })\n : Effect.forEach(\n batch.requests,\n requirement =>\n Effect.request(\n new ReadRequirement({ key: requirementKey(requirement), requirement }),\n resolver,\n ),\n { concurrency: 'unbounded' },\n ).pipe(\n Effect.map(results => ({\n entities: [...new Set(results)].flatMap(result => result.entities),\n })),\n )\n })\n","/**\n * The transport seam: the `RemoteClient` Effect service, the RPC client it is\n * built from, the wire-to-client reconstructions, and the mutation call.\n */\nimport { Context, Effect, Layer, Schema, Stream } from 'effect'\nimport type { Requirement } from './requirement.js'\nimport { coalesceQueries, coalesceReads, type CoalesceOptions } from './coalesce.js'\nimport type { LiveCursor, LiveEvent } from './live.js'\nimport type { MutationDescriptor } from './mutation.js'\nimport type { ConnectionChange } from './optimistic.js'\nimport type { RemoteError } from './remoteData.js'\nimport {\n MutationRequest,\n MutationResult,\n QueryRequest,\n QueryResult,\n ReadBatch,\n ReadBatchResult,\n type ConnectionChangeSchema,\n RemoteLiveError,\n RemoteMutationError,\n RemoteProtocolError,\n RemoteQueryError,\n RemoteReadError,\n type LiveChange,\n type LiveRequirement,\n} from './wire.js'\n\n/**\n * The transport boundary. `foldkit-remote` never talks to a transport directly;\n * it depends on this Effect service, which a later phase wires to Effect RPC.\n */\nexport class RemoteClient extends Context.Service<\n RemoteClient,\n {\n readonly read: (\n batch: Schema.Schema.Type<typeof ReadBatch>,\n ) => Effect.Effect<\n Schema.Schema.Type<typeof ReadBatchResult>,\n RemoteReadError | RemoteProtocolError\n >\n readonly query: (\n request: Schema.Schema.Type<typeof QueryRequest>,\n ) => Effect.Effect<Schema.Schema.Type<typeof QueryResult>, RemoteQueryError>\n readonly mutate: (\n request: Schema.Schema.Type<typeof MutationRequest>,\n ) => Effect.Effect<Schema.Schema.Type<typeof MutationResult>, RemoteMutationError>\n readonly live: (request: {\n readonly requirements: ReadonlyArray<Requirement>\n readonly after: LiveCursor\n }) => Stream.Stream<LiveEvent, RemoteLiveError | RemoteProtocolError>\n }\n>()('foldkit-remote/RemoteClient') {}\n\n/**\n * The methods an Effect RPC client for `RemoteRpc` exposes. `R` is the\n * environment a handler needs; it defaults to `never`, which is what a real\n * transport client satisfies. `RemoteServer.handlers` returns this type with its\n * own `R`, so the two sides cannot drift apart.\n */\nexport interface RemoteRpcClient<R = never> {\n readonly FoldkitRemoteRead: (\n payload: Schema.Schema.Type<typeof ReadBatch>,\n ) => Effect.Effect<\n Schema.Schema.Type<typeof ReadBatchResult>,\n RemoteReadError | RemoteProtocolError,\n R\n >\n readonly FoldkitRemoteQuery: (\n payload: Schema.Schema.Type<typeof QueryRequest>,\n ) => Effect.Effect<Schema.Schema.Type<typeof QueryResult>, RemoteQueryError, R>\n readonly FoldkitRemoteMutate: (\n payload: Schema.Schema.Type<typeof MutationRequest>,\n ) => Effect.Effect<Schema.Schema.Type<typeof MutationResult>, RemoteMutationError, R>\n readonly FoldkitRemoteLive: (\n payload: Schema.Schema.Type<typeof LiveRequirement>,\n ) => Stream.Stream<\n Schema.Schema.Type<typeof LiveChange>,\n RemoteLiveError | RemoteProtocolError,\n R\n >\n}\n\n/** Reconstructs the client's `ConnectionChange` from the wire's flattened edge. */\nexport const connectionChangeOf = (\n change: Schema.Schema.Type<typeof ConnectionChangeSchema>,\n): ConnectionChange => {\n const edge = { key: change.edge.key, ref: { entity: change.edge.entity, id: change.edge.id } }\n return change._tag === 'Insert'\n ? { _tag: 'Insert', connection: change.connection, position: change.position, edge }\n : { _tag: 'Remove', connection: change.connection, edge }\n}\n\n/** Reconstructs the client's `LiveEvent` from the wire's flattened `LiveChange`. */\nexport const liveEventOf = (change: Schema.Schema.Type<typeof LiveChange>): LiveEvent => {\n switch (change._tag) {\n case 'EntityPatched':\n return {\n _tag: 'EntityPatched',\n ref: { entity: change.entity, id: change.id },\n values: change.values,\n changed: change.changed,\n cursor: change.cursor,\n }\n case 'EntityDeleted':\n return {\n _tag: 'EntityDeleted',\n ref: { entity: change.entity, id: change.id },\n cursor: change.cursor,\n }\n case 'ConnectionInsert':\n return {\n _tag: 'ConnectionInsert',\n connection: change.connection,\n position: change.position,\n edge: { key: change.edge.key, ref: { entity: change.edge.entity, id: change.edge.id } },\n cursor: change.cursor,\n }\n case 'ConnectionRemove':\n return {\n _tag: 'ConnectionRemove',\n connection: change.connection,\n edge: { key: change.edge.key, ref: { entity: change.edge.entity, id: change.edge.id } },\n cursor: change.cursor,\n }\n case 'ConnectionInvalidate':\n return { _tag: 'ConnectionInvalidate', connection: change.connection, cursor: change.cursor }\n }\n}\n\nexport const remoteError = (error: {\n readonly _tag: string\n readonly message: string\n}): RemoteError => ({\n _tag: error._tag,\n message: error.message,\n})\n\nexport const coalescedLayer = <E, R>(\n layer: Layer.Layer<RemoteClient, E, R>,\n options: CoalesceOptions = {},\n): Layer.Layer<RemoteClient, E, R> =>\n Layer.effect(\n RemoteClient,\n Effect.gen(function* () {\n const client = yield* RemoteClient\n const read = yield* coalesceReads(client.read, options)\n const query = yield* coalesceQueries(client.query, options)\n return { ...client, read, query }\n }),\n ).pipe(Layer.provide(layer))\n\n/**\n * `Remote.mutate` as a standalone effect, so `Remote.mutateInto` can reuse it\n * without the object literal referencing itself.\n */\nexport const mutateRemote = Effect.fn('Remote.mutate')(function* <\n Name extends string,\n Input,\n Output,\n>(mutation: MutationDescriptor<Name, Input, Output>, input: Input, requestId: string) {\n yield* Effect.annotateCurrentSpan({ mutation: mutation.name, requestId })\n const client = yield* RemoteClient\n const encoded = yield* Schema.encodeUnknownEffect(mutation.Input)(input).pipe(\n Effect.catchTag('SchemaError', error =>\n Effect.fail(new RemoteMutationError({ message: error.message })),\n ),\n )\n const result = yield* client.mutate({\n requestId,\n mutation: mutation.name,\n input: encoded,\n })\n const output = yield* Schema.decodeUnknownEffect(mutation.Output)(result.output).pipe(\n Effect.catchTag('SchemaError', error =>\n Effect.fail(new RemoteMutationError({ message: error.message })),\n ),\n )\n return {\n output,\n entities: result.entities,\n connections: (result.connections ?? []).map(connectionChangeOf),\n deleted: result.deleted ?? [],\n }\n})\n","/**\n * The pure connection model: an ordered normalized structure of edges with\n * explicit known boundaries. Pages, live events, and optimistic inserts are all\n * evidence about one connection; `merge` is the single deterministic reducer and\n * performs no I/O.\n *\n * Optimistic overlays and live state arrive in later phases.\n */\nimport { entityKey } from './store.js'\n\nexport interface EdgeRef {\n readonly entity: string\n readonly id: string\n}\n\n/** `key` is the edge identity used for de-duplication. */\nexport interface Edge {\n readonly key: string\n readonly ref: EdgeRef\n}\n\nexport const edge = (ref: EdgeRef, key: string = entityKey(ref.entity, ref.id)): Edge => ({\n key,\n ref,\n})\n\nexport type Cursor = string\n\nexport type Boundary =\n | { readonly _tag: 'Terminal' }\n | { readonly _tag: 'Cursor'; readonly cursor: Cursor }\n | { readonly _tag: 'Unknown' }\n\nexport const terminal: Boundary = { _tag: 'Terminal' }\nexport const unknown: Boundary = { _tag: 'Unknown' }\nexport const cursor = (value: Cursor): Boundary => ({ _tag: 'Cursor', cursor: value })\n\nexport interface Segment {\n readonly edges: readonly Edge[]\n readonly start: Boundary\n readonly end: Boundary\n}\n\nexport interface Connection {\n readonly segments: readonly Segment[]\n readonly stale: boolean\n}\n\nexport const emptyConnection: Connection = { segments: [], stale: false }\n\nexport const segment = (edges: readonly Edge[], start: Boundary, end: Boundary): Segment => ({\n edges,\n start,\n end,\n})\n\nconst dedupeEdges = (edges: readonly Edge[]): Edge[] => {\n const seen = new Set<string>()\n const out: Edge[] = []\n for (const value of edges) {\n if (seen.has(value.key)) continue\n seen.add(value.key)\n out.push(value)\n }\n return out\n}\n\nconst normalize = (segment: Segment): Segment => ({ ...segment, edges: dedupeEdges(segment.edges) })\n\n/** Longest suffix of `a` that is a prefix of `b`, matched by edge identity. */\nconst overlapLength = (a: readonly Edge[], b: readonly Edge[]): number => {\n const most = Math.min(a.length, b.length)\n for (let length = most; length > 0; length--) {\n let matches = true\n for (let i = 0; i < length; i++) {\n if (a[a.length - length + i]!.key !== b[i]!.key) {\n matches = false\n break\n }\n }\n if (matches) return length\n }\n return 0\n}\n\nconst cursorJoinable = (a: Boundary, b: Boundary): boolean =>\n a._tag === 'Cursor' && b._tag === 'Cursor' && a.cursor === b.cursor\n\n/** Joins `a` immediately before `b`, or returns `undefined` when they are not contiguous. */\nconst join = (a: Segment, b: Segment): Segment | undefined => {\n if (cursorJoinable(a.end, b.start)) {\n return { edges: dedupeEdges([...a.edges, ...b.edges]), start: a.start, end: b.end }\n }\n const overlap = overlapLength(a.edges, b.edges)\n if (overlap > 0) {\n return {\n edges: dedupeEdges([...a.edges, ...b.edges]),\n start: a.start,\n end: b.end,\n }\n }\n return undefined\n}\n\n/**\n * Global by edge identity: an edge appears once per connection. Dropping a\n * shared edge from the middle of a segment would otherwise imply that its\n * surviving neighbours are adjacent, so a segment with holes is split at each\n * hole and the new inner boundaries are `Unknown`.\n */\nconst dedupeConnection = (segments: readonly Segment[]): Segment[] => {\n const seen = new Set<string>()\n const out: Segment[] = []\n for (const segmentValue of segments) {\n const runs: Edge[][] = []\n let run: Edge[] = []\n for (const edgeValue of segmentValue.edges) {\n if (seen.has(edgeValue.key)) {\n if (run.length > 0) {\n runs.push(run)\n run = []\n }\n continue\n }\n seen.add(edgeValue.key)\n run.push(edgeValue)\n }\n if (run.length > 0) runs.push(run)\n if (runs.length === 0) continue\n if (runs.length === 1) {\n out.push({ ...segmentValue, edges: runs[0]! })\n continue\n }\n runs.forEach((edges, index) => {\n out.push({\n edges,\n start: index === 0 ? segmentValue.start : unknown,\n end: index === runs.length - 1 ? segmentValue.end : unknown,\n })\n })\n }\n return out\n}\n\n/** Adds a page to the connection, joining contiguous or overlapping segments. */\nexport const merge = (current: Connection, page: Segment): Connection => {\n // A zero-edge page carries no ordering evidence; joining it would let its\n // boundary overwrite a real segment's end. Ignore it.\n const incoming = normalize(page)\n if (incoming.edges.length === 0) return current\n\n const segments = [...current.segments.map(normalize), incoming]\n let joined = true\n while (joined) {\n joined = false\n outer: for (let i = 0; i < segments.length; i++) {\n for (let j = 0; j < segments.length; j++) {\n if (i === j) continue\n const result = join(segments[i]!, segments[j]!)\n if (result === undefined) continue\n segments[i] = result\n segments.splice(j, 1)\n joined = true\n break outer\n }\n }\n }\n return { ...current, segments: orderSegments(dedupeConnection(segments)) }\n}\n\n/**\n * Disjoint segments have no cursor linking them, so their relative order is\n * whatever it was; the two exceptions are known: a segment starting at the\n * terminal boundary is first, one ending at it is last.\n */\nconst orderSegments = (segments: readonly Segment[]): Segment[] => {\n const first = segments.filter(value => value.start._tag === 'Terminal')\n const last = segments.filter(value => value.end._tag === 'Terminal' && !first.includes(value))\n const middle = segments.filter(value => !first.includes(value) && !last.includes(value))\n return [...first, ...middle, ...last]\n}\n\n/** Visible edges, segment by segment. */\nexport const items = (connection: Connection): ReadonlyArray<Edge> =>\n connection.segments.flatMap(value => value.edges)\n\n/** There is more before the known region. Derived from boundaries, never row count. */\nexport const hasPrevious = (connection: Connection): boolean => {\n const first = connection.segments[0]\n return first !== undefined && first.start._tag !== 'Terminal'\n}\n\n/** There is more after the known region. Derived from boundaries, never row count. */\nexport const hasNext = (connection: Connection): boolean => {\n const last = connection.segments[connection.segments.length - 1]\n return last !== undefined && last.end._tag !== 'Terminal'\n}\n\n/** A connection with more than one segment has an explicit unknown gap. */\nexport const isGapped = (connection: Connection): boolean => connection.segments.length > 1\n","/**\n * Relation values on the wire and in the store: a ref key (`\"Entity:id\"`), a\n * nullable ref key, an array of ref keys, or a page of ref keys. The planner\n * follows them into the store; the server follows them into the next read.\n */\nimport type { Schema } from 'effect'\nimport type { RelationRequirement } from './requirement.js'\n\nexport interface RefParts {\n readonly entity: string\n readonly id: string\n}\n\n/** A page of refs as the wire and the store hold it. */\nexport interface RefPageValue {\n readonly refs: ReadonlyArray<string>\n readonly hasNext: boolean\n readonly hasPrevious: boolean\n}\n\n/** Marks the codec `Entity.ref`/`Entity.refPage` produce, so a Selection can tell the field's shape. */\nexport const RelationAnnotation = 'foldkitRemoteRelation'\n/** The target entity's name on the same codec, so a nested selection of another entity is refused. */\nexport const RelationEntityAnnotation = 'foldkitRemoteRelationEntity'\n\nexport type RelationKind = 'one' | 'many' | 'page'\n\nexport interface RelationShape {\n readonly kind: RelationKind\n readonly nullable: boolean\n readonly entity: string\n}\n\n/** Splits a ref key (`\"Entity:id\"`, the store key too) back into its parts. */\nexport const refParts = (encoded: string): RefParts => {\n const separator = encoded.indexOf(':')\n return separator === -1\n ? { entity: encoded, id: '' }\n : { entity: encoded.slice(0, separator), id: encoded.slice(separator + 1) }\n}\n\n/**\n * The refs a relation value carries, in order. Anything that is not a ref key,\n * an array of them, or a page of them contributes nothing.\n */\nexport const refsIn = (value: unknown): ReadonlyArray<RefParts> => {\n if (typeof value === 'string') return [refParts(value)]\n if (Array.isArray(value)) return value.filter(item => typeof item === 'string').map(refParts)\n if (value !== null && typeof value === 'object') {\n const refs = (value as { readonly refs?: unknown }).refs\n if (Array.isArray(refs)) return refs.filter(item => typeof item === 'string').map(refParts)\n }\n return []\n}\n\n/** The refs in a relation value that name the relation's target entity, and no other. */\nexport const targetsOf = (value: unknown, relation: RelationRequirement): ReadonlyArray<RefParts> =>\n refsIn(value).filter(ref => ref.entity === relation.entity)\n\nexport const isRefPage = (value: unknown): value is RefPageValue => {\n if (value === null || typeof value !== 'object') return false\n const page = value as Record<string, unknown>\n return (\n Array.isArray(page.refs) &&\n page.refs.every(ref => typeof ref === 'string') &&\n typeof page.hasNext === 'boolean' &&\n typeof page.hasPrevious === 'boolean'\n )\n}\n\ninterface AstLike {\n readonly _tag: string\n readonly annotations?: Readonly<Record<string, unknown>> | undefined\n readonly types?: ReadonlyArray<AstLike> | undefined\n readonly rest?: ReadonlyArray<AstLike> | undefined\n}\n\n/**\n * The relation shape an entity field schema declares: a ref (`one`), a nullable\n * ref, an array of refs (`many`), or a page of refs (`page`). `undefined` for a\n * scalar field, which cannot take a nested selection.\n */\nexport const relationShape = (schema: Schema.Top): RelationShape | undefined =>\n shapeOf(schema.ast as unknown as AstLike, false)\n\nconst shapeOf = (ast: AstLike, nullable: boolean): RelationShape | undefined => {\n const annotated = ast.annotations?.[RelationAnnotation]\n if (annotated === 'one' || annotated === 'page') {\n return {\n kind: annotated,\n nullable,\n entity: String(ast.annotations?.[RelationEntityAnnotation]),\n }\n }\n if (ast._tag === 'Arrays') {\n const item = ast.rest?.[0]\n const inner = item === undefined ? undefined : shapeOf(item, false)\n return inner?.kind === 'one' ? { kind: 'many', nullable, entity: inner.entity } : undefined\n }\n if (ast._tag === 'Union') {\n const members = ast.types ?? []\n const optional = members.some(member => member._tag === 'Null' || member._tag === 'Undefined')\n for (const member of members) {\n const shape = shapeOf(member, optional)\n if (shape !== undefined) return shape\n }\n }\n return undefined\n}\n","/**\n * Selections: the fields a Surface picks of an entity (nested through\n * relations, paged through connections), the requirement graph they imply,\n * and their assembly from the normalized store.\n */\nimport { Option, Schema } from 'effect'\nimport * as Domain from 'foldkit-entity'\nimport type { RelationRequirement } from './requirement.js'\nimport {\n Entity,\n type AnySchema,\n type EntityDescriptor,\n type EntityRef,\n type RefPage,\n} from './entity.js'\nimport type { QueryWindow } from './query.js'\nimport { isRefPage, relationShape, targetsOf } from './relation.js'\nimport { entityKey, isFieldStale, isTombstone, readField, type EntityStore } from './store.js'\n\n/** One page of a paginated relation with each target assembled through a nested selection. */\nexport interface Page<Item> {\n readonly items: ReadonlyArray<Item>\n readonly hasNext: boolean\n readonly hasPrevious: boolean\n}\n\n/**\n * The fields a projection reads of one entity, plus the slice it reads of each\n * relation's target. `Shape` tells a parent selection whether this one is a\n * paginated relation (`connection`) or a plain entity slice (`entity`).\n */\nexport interface Selection<\n Value,\n Name extends string = string,\n Shape extends 'entity' | 'connection' = 'entity' | 'connection',\n> {\n readonly entity: Name\n readonly fields: readonly string[]\n /** A pure codec: entity fields carry no decoding or encoding services. */\n readonly schema: Schema.Codec<Value, unknown, never, never>\n /** Pagination windows for nested relation fields, keyed by field name. */\n readonly connections?: Readonly<Record<string, QueryWindow>> | undefined\n /** The slice required of each nested relation's target, keyed by field name. */\n readonly relations?: Readonly<Record<string, RelationRequirement>> | undefined\n /** Present when this selection is itself a paginated relation. */\n readonly window?: QueryWindow | undefined\n /** Phantom: see `Shape`. */\n readonly shape?: Shape | undefined\n}\n\n/** Flattens a mapped type so hovers show the picked fields, not the machinery. */\ntype Simplify<T> = T extends infer O ? { readonly [K in keyof O]: O[K] } : never\n\n/** The value a Selection reads: `Selection.Value<typeof ProjectCard>`. */\nexport type SelectionValueOf<S> = S extends Selection<infer V, any, any> ? V : never\n\n/** The nested selections a relation field admits: of its target entity, in the shapes its value takes. */\ntype NestedFor<Field> =\n Exclude<Field, null | undefined> extends ReadonlyArray<EntityRef<infer Name, any>>\n ? Selection<unknown, Name, 'entity' | 'connection'>\n : Exclude<Field, null | undefined> extends RefPage<infer Name, any>\n ? Selection<unknown, Name, 'entity' | 'connection'>\n : Exclude<Field, null | undefined> extends EntityRef<infer Name, any>\n ? Selection<unknown, Name, 'entity'>\n : never\n\n/** What a selection of an entity with fields `F` may pick: `true` per scalar, a nested selection per relation. */\nexport type SelectionOf<F extends Schema.Struct.Fields> = {\n readonly [K in keyof F]?: true | NestedFor<Schema.Schema.Type<F[K]>>\n}\n\n/** `T | null` when the field admits `null` or `undefined` (both assemble to `null`). */\ntype Nullable<Field, T> = [Extract<Field, null | undefined>] extends [never] ? T : T | null\n\n/** A nested selection's value takes the shape of the field it selects through. */\ntype NestedValue<Field, Sel> =\n Sel extends Selection<infer V, string, 'connection'>\n ? Nullable<Field, V>\n : Sel extends Selection<infer V, string, 'entity'>\n ? Nullable<\n Field,\n Exclude<Field, null | undefined> extends ReadonlyArray<EntityRef<any, any>>\n ? ReadonlyArray<V>\n : Exclude<Field, null | undefined> extends RefPage<any, any>\n ? Page<V>\n : V\n >\n : never\n\n/** The value a selection `Sel` of fields `F` reads. */\nexport type SelectionValue<F extends Schema.Struct.Fields, Sel> = Simplify<{\n readonly [K in keyof Sel & keyof F]: Sel[K] extends true\n ? Schema.Schema.Type<F[K]>\n : NestedValue<Schema.Schema.Type<F[K]>, Sel[K]>\n}>\n\n// Built once per item schema, as `remoteDataSchema` is: a query projection is\n// rebuilt on every Model change.\nconst pageSchemas = new WeakMap<object, AnySchema>()\n\nexport const pageSchema = (item: AnySchema): AnySchema => {\n const cached = pageSchemas.get(item)\n if (cached !== undefined) return cached\n const built = Schema.Struct({\n items: Schema.Array(item),\n hasNext: Schema.Boolean,\n hasPrevious: Schema.Boolean,\n }) as unknown as AnySchema\n pageSchemas.set(item, built)\n return built\n}\n\n/** The requirement a nested selection contributes for its relation's target. */\nexport const relationOf = (selection: Selection<unknown>): RelationRequirement => ({\n entity: selection.entity,\n fields: selection.fields,\n ...(selection.connections === undefined ? {} : { windows: selection.connections }),\n ...(selection.relations === undefined ? {} : { relations: selection.relations }),\n})\n\nexport const Selection = {\n /**\n * The Remote Selection of a `foldkit-entity` Selection: the same members, read\n * from Remote's store. `true` on a relation reads its refs, as it does here.\n */\n from: <Name extends string, S extends Schema.Constraint>(\n selection: Domain.Selection<Name, unknown, S>,\n ): Selection<S['Type'], Name, 'entity'> => {\n const spec: Record<string, true | Selection<unknown>> = {}\n for (const [key, selected] of Object.entries(\n selection.members as Readonly<\n Record<\n string,\n | true\n | Domain.Selection<string, unknown, Schema.Constraint>\n | Domain.SelectionPage<string, Schema.Constraint>\n >\n >,\n ))\n spec[key] =\n selected === true\n ? true\n : Domain.SelectionPageTypeId in selected\n ? // A page of a `many` relation is Remote's relation connection.\n Selection.connection(\n Entity.from(selected.selection.entity as never),\n selected.window,\n Selection.from(selected.selection) as never,\n )\n : Selection.from(selected)\n return Selection.make(Entity.from(selection.entity as never), spec as never) as never\n },\n\n /**\n * The fields to read of `entity`. A nested `Selection` on a relation field\n * reads through the ref (or refs, or page of refs) the field holds into the\n * target's fields; a scalar field cannot take one.\n */\n make: <Name extends string, F extends Schema.Struct.Fields, const Sel extends SelectionOf<F>>(\n entity: EntityDescriptor<Name, F>,\n selection: Sel,\n ): Selection<SelectionValue<F, Sel>, Name, 'entity'> => {\n if (Object.keys(selection).length === 0) {\n throw new Error(`Selection.make: a selection of \"${entity.name}\" picks at least one field`)\n }\n const picked: Record<string, AnySchema> = {}\n const connections: Record<string, QueryWindow> = {}\n const relations: Record<string, RelationRequirement> = {}\n for (const key of Object.keys(selection)) {\n const choice = (selection as Record<string, unknown>)[key]\n if (choice === true) {\n picked[key] = entity.fields[key] as AnySchema\n continue\n }\n const nested = choice as Selection<unknown>\n const shape = relationShape(entity.fields[key] as Schema.Top)\n if (shape === undefined) {\n throw new Error(\n `Selection.make: \"${key}\" on \"${entity.name}\" is not a relation field, so it cannot take a nested selection`,\n )\n }\n if (nested.entity !== shape.entity) {\n throw new Error(\n `Selection.make: \"${key}\" on \"${entity.name}\" refers to \"${shape.entity}\", not \"${nested.entity}\"`,\n )\n }\n const nullable = (codec: AnySchema): AnySchema =>\n shape.nullable ? (Schema.NullOr(codec) as unknown as AnySchema) : codec\n if (nested.window !== undefined) {\n // A connection: the nested selection already carries its page codec.\n connections[key] = nested.window\n picked[key] = nullable(nested.schema as AnySchema)\n if (nested.fields.length > 0) relations[key] = relationOf(nested)\n continue\n }\n const item = nested.schema as AnySchema\n picked[key] = nullable(\n shape.kind === 'many'\n ? (Schema.Array(item) as unknown as AnySchema)\n : shape.kind === 'page'\n ? pageSchema(item)\n : item,\n )\n relations[key] = relationOf(nested)\n }\n return {\n entity: entity.name,\n fields: Object.keys(selection),\n schema: Schema.Struct(picked) as unknown as Schema.Codec<\n SelectionValue<F, Sel>,\n unknown,\n never,\n never\n >,\n ...(Object.keys(connections).length === 0 ? {} : { connections }),\n ...(Object.keys(relations).length === 0 ? {} : { relations }),\n }\n },\n\n /**\n * A paginated relation: one page of refs to `entity` with a window, or, with\n * a nested selection, one page of targets assembled through it.\n */\n connection: (<Name extends string, F extends Schema.Struct.Fields, Item = never>(\n entity: EntityDescriptor<Name, F>,\n window: QueryWindow,\n selection?: Selection<Item, Name, 'entity'>,\n ): Selection<RefPage<Name, F> | Page<Item>, Name, 'connection'> => {\n if (selection !== undefined && selection.entity !== entity.name) {\n throw new Error(\n `Selection.connection: a page of \"${entity.name}\" cannot select \"${selection.entity}\"`,\n )\n }\n return {\n entity: entity.name,\n fields: selection?.fields ?? [],\n schema: (selection === undefined\n ? Entity.refPage(entity)\n : pageSchema(selection.schema as AnySchema)) as unknown as Schema.Codec<\n RefPage<Name, F> | Page<Item>,\n unknown,\n never,\n never\n >,\n window,\n ...(selection?.connections === undefined ? {} : { connections: selection.connections }),\n ...(selection?.relations === undefined ? {} : { relations: selection.relations }),\n }\n }) as {\n <Name extends string, F extends Schema.Struct.Fields>(\n entity: EntityDescriptor<Name, F>,\n window: QueryWindow,\n ): Selection<RefPage<Name, F>, Name, 'connection'>\n <Name extends string, F extends Schema.Struct.Fields, Item>(\n entity: EntityDescriptor<Name, F>,\n window: QueryWindow,\n selection: Selection<Item, NoInfer<Name>, 'entity'>,\n ): Selection<Page<Item>, Name, 'connection'>\n },\n}\n\ninterface Assembled {\n readonly values: unknown\n readonly refreshing: boolean\n}\n\n/**\n * Reads an entity's selected fields out of the store, following each nested\n * relation into its targets. `undefined` means some field, at any depth, is\n * not present yet. A tombstoned target reads as `null` (or is dropped from a\n * list), so the Selection's codec decides whether that is a failure.\n */\nexport const assemble = (\n store: EntityStore,\n key: string,\n requirement: RelationRequirement,\n): Assembled | undefined => {\n const values: Record<string, unknown> = {}\n let refreshing = false\n for (const field of requirement.fields) {\n const value = readField(store, key, field)\n if (Option.isNone(value)) return undefined\n refreshing ||= isFieldStale(store, key, field)\n const relation = requirement.relations?.[field]\n if (relation === undefined) {\n values[field] = value.value\n continue\n }\n const nested = assembleRelation(store, value.value, relation)\n if (nested === undefined) return undefined\n values[field] = nested.values\n refreshing ||= nested.refreshing\n }\n return { values, refreshing }\n}\n\nconst assembleTarget = (\n store: EntityStore,\n ref: { readonly entity: string; readonly id: string },\n relation: RelationRequirement,\n): Assembled | 'absent' | undefined => {\n const key = entityKey(ref.entity, ref.id)\n return isTombstone(store, key) ? 'absent' : assemble(store, key, relation)\n}\n\n/** Assembles the targets a relation value refers to, in the value's own shape. */\nconst assembleRelation = (\n store: EntityStore,\n value: unknown,\n relation: RelationRequirement,\n): Assembled | undefined => {\n if (value === null || value === undefined) return { values: null, refreshing: false }\n const targets: unknown[] = []\n let refreshing = false\n for (const ref of targetsOf(value, relation)) {\n const target = assembleTarget(store, ref, relation)\n if (target === undefined) return undefined\n if (target === 'absent') continue\n targets.push(target.values)\n refreshing ||= target.refreshing\n }\n if (typeof value === 'string') {\n return { values: targets.length === 0 ? null : targets[0], refreshing }\n }\n if (isRefPage(value)) {\n return {\n values: { items: targets, hasNext: value.hasNext, hasPrevious: value.hasPrevious },\n refreshing,\n }\n }\n return { values: targets, refreshing }\n}\n","/**\n * Entities: the descriptor an application declares, refs, ref pages, and\n * patches, with the codecs that carry refs on the wire.\n */\nimport { Schema, SchemaGetter } from 'effect'\nimport type * as Domain from 'foldkit-entity'\nimport { RelationAnnotation, RelationEntityAnnotation, refParts } from './relation.js'\n// selection.ts imports this module too; both only use the other inside\n// function bodies, so the cycle is never observed at module evaluation.\nimport { Selection, type SelectionOf, type SelectionValue } from './selection.js'\nimport { entityKey } from './store.js'\n\nexport type AnySchema = Schema.Schema<unknown>\n\ndeclare const entityRefFields: unique symbol\n\n/**\n * A normalized reference to an entity. `F` is a phantom carrying the entity's\n * fields so `Entity.patch` can type its patch; it is absent at runtime.\n */\nexport interface EntityRef<\n Name extends string,\n F extends Schema.Struct.Fields = Schema.Struct.Fields,\n> {\n readonly entity: Name\n readonly id: string\n readonly [entityRefFields]?: F\n}\n\nexport interface EntityDescriptor<Name extends string, F extends Schema.Struct.Fields> {\n readonly name: Name\n readonly schema: Schema.Struct<F>\n readonly fields: F\n // Methods, not properties: method signatures are bivariant, so a concrete\n // descriptor stays assignable to `EntityDescriptor<any, any>` (which appears\n // in every heterogeneous collection, e.g. `Remote.make`'s entities).\n ref(id: Schema.Schema.Type<F['id']>): EntityRef<Name, F>\n /** The fields a Surface reads of this entity; `Selection.make(entity, …)` with the entity as receiver. */\n select<const Sel extends SelectionOf<F>>(\n selection: Sel,\n ): Selection<SelectionValue<F, Sel>, Name, 'entity'>\n /** A patch of this entity's wire-shaped values; `Entity.patch(entity.ref(id), values)`. */\n patch(\n id: Schema.Schema.Type<F['id']>,\n values: Partial<Schema.Struct.Encoded<F>>,\n ): EntityPatch<Name, F>\n}\n\n/**\n * Relations are **references**, never inline target schemas: a ref cannot\n * reconstruct a full entity, and dereferencing is a store concern. Because the\n * target schema is not inlined, recursive relations cannot arise through the\n * schema graph.\n */\nconst refCodec = <Name extends string, F extends Schema.Struct.Fields>(\n entity: Name,\n): Schema.Codec<EntityRef<Name, F>, string> =>\n Schema.Struct({ entity: Schema.String, id: Schema.String })\n .pipe(\n Schema.encodeTo(Schema.String, {\n decode: SchemaGetter.transform(refParts),\n encode: SchemaGetter.transform((ref: EntityRef<string>) => entityKey(ref.entity, ref.id)),\n }),\n )\n .annotate({\n [RelationAnnotation]: 'one',\n [RelationEntityAnnotation]: entity,\n }) as unknown as Schema.Codec<EntityRef<Name, F>, string>\n\n/**\n * A patch in wire shape: the values the store holds, so a relation is its ref\n * key (`Entity.refKey`), not an `EntityRef`.\n */\nexport interface EntityPatch<Name extends string, F extends Schema.Struct.Fields> {\n readonly entity: Name\n readonly id: string\n readonly values: Partial<Schema.Struct.Encoded<F>>\n}\n\n/**\n * One authoritative page of a paginated relation: refs (never inline entities)\n * plus whether more exist. The adapter does not hold segmentation state; the\n * client merges pages.\n */\nexport interface RefPage<\n Name extends string,\n F extends Schema.Struct.Fields = Schema.Struct.Fields,\n> {\n readonly refs: ReadonlyArray<EntityRef<Name, F>>\n readonly hasNext: boolean\n readonly hasPrevious: boolean\n}\n\nconst refPageCodec = <Name extends string, F extends Schema.Struct.Fields>(\n entity: Name,\n): Schema.Codec<\n RefPage<Name, F>,\n {\n readonly refs: ReadonlyArray<string>\n readonly hasNext: boolean\n readonly hasPrevious: boolean\n }\n> =>\n Schema.Struct({\n refs: Schema.Array(refCodec<Name, F>(entity)),\n hasNext: Schema.Boolean,\n hasPrevious: Schema.Boolean,\n }).annotate({\n [RelationAnnotation]: 'page',\n [RelationEntityAnnotation]: entity,\n }) as unknown as Schema.Codec<\n RefPage<Name, F>,\n {\n readonly refs: ReadonlyArray<string>\n readonly hasNext: boolean\n readonly hasPrevious: boolean\n }\n >\n\n/** The ref codec a `foldkit-entity` relation becomes: one ref, a nullable ref, or an array of refs. */\ntype RelationField<Spec> =\n Spec extends Domain.RelationSpec<infer Target, infer Cardinality, infer Optional>\n ? Cardinality extends 'many'\n ? Schema.$Array<Schema.Codec<EntityRef<Target['name']>, string>>\n : Optional extends true\n ? Schema.NullOr<Schema.Codec<EntityRef<Target['name']>, string>>\n : Schema.Codec<EntityRef<Target['name']>, string>\n : never\n\n/**\n * The fields Remote stores for a `foldkit-entity` Entity: its own fields, its\n * derived members (the server supplies them like any field), and each relation\n * as refs.\n */\nexport type FieldsFrom<E> =\n E extends Domain.Entity<any, infer Fields, infer Relations, infer Derived>\n ? Fields & { readonly [K in keyof Derived]: Derived[K]['schema'] } & {\n readonly [K in keyof Relations]: RelationField<Relations[K]>\n }\n : never\n\n// One descriptor per Entity version: `Selection.from` looks a Selection's Entity up again.\nconst descriptors = new WeakMap<Domain.AnyEntity, EntityDescriptor<any, any>>()\n\nconst relationField = (\n relation: Domain.EntityMember & { readonly _tag: 'Relation' },\n): AnySchema => {\n const ref = refCodec(relation.target().name) as unknown as AnySchema\n return (relation.cardinality === 'many'\n ? Schema.Array(ref)\n : relation.optional\n ? Schema.NullOr(ref)\n : ref) as unknown as AnySchema\n}\n\nexport const Entity = {\n /**\n * The Remote descriptor of a `foldkit-entity` Entity. Relations declared with\n * `Entity.relate` become ref fields, so the store, the planner, and the server\n * treat it as they treat an `Entity.make` descriptor.\n */\n from: <E extends Domain.AnyEntity>(\n entity: E & { readonly fields: { readonly id: unknown } },\n ): EntityDescriptor<E['name'], FieldsFrom<E>> => {\n const cached = descriptors.get(entity)\n if (cached !== undefined) return cached\n const members: Readonly<Record<string, Domain.EntityMember>> = entity.members\n if (members.id?._tag !== 'Field')\n throw new Error(`Entity.from: \"${entity.name}\" needs an \"id\" field for Remote to key it by`)\n const fields: Record<string, AnySchema> = {}\n for (const [key, member] of Object.entries(members))\n fields[key] =\n member._tag === 'Relation' ? relationField(member) : (member.schema as AnySchema)\n const descriptor = Entity.make(entity.name, Schema.Struct(fields) as never)\n descriptors.set(entity, descriptor)\n return descriptor as never\n },\n\n make: <\n const Name extends string,\n const F extends Schema.Struct.Fields & { readonly id: Schema.Schema<unknown> },\n >(\n name: Name,\n schema: Schema.Struct<F>,\n ): EntityDescriptor<Name, F> => {\n const descriptor: EntityDescriptor<Name, F> = {\n name,\n schema,\n fields: schema.fields,\n ref: id => ({ entity: name, id: String(id) }) as EntityRef<Name, F>,\n select: selection => Selection.make(descriptor, selection),\n patch: (id, values) => ({ entity: name, id: String(id), values }),\n }\n return descriptor\n },\n\n /** A relation to a known entity, decoded as a reference. */\n ref: <Name extends string, F extends Schema.Struct.Fields>(\n entity: EntityDescriptor<Name, F>,\n ): Schema.Codec<EntityRef<Name, F>, string> => refCodec<Name, F>(entity.name),\n\n /** A relation by name, for recursive or forward references. */\n refTo: <Name extends string>(name: Name): Schema.Codec<EntityRef<Name>, string> =>\n refCodec<Name, Schema.Struct.Fields>(name),\n\n /**\n * The wire key a relation field carries (`\"Entity:id\"`). Adapters that read a\n * foreign key emit this so the ref codec can decode it on the client.\n */\n refKey: (ref: { readonly entity: string; readonly id: string }): string =>\n entityKey(ref.entity, ref.id),\n\n /** Splits a ref key back into its entity and id. */\n refParts,\n\n /** A relation value of one authoritative page of refs. */\n refPage: <Name extends string, F extends Schema.Struct.Fields>(\n entity: EntityDescriptor<Name, F>,\n ): Schema.Codec<\n RefPage<Name, F>,\n {\n readonly refs: ReadonlyArray<string>\n readonly hasNext: boolean\n readonly hasPrevious: boolean\n }\n > => refPageCodec<Name, F>(entity.name),\n\n /**\n * A normalized patch for an entity, typed against its fields' wire shape:\n * write a relation as its ref key (`Entity.refKey`), as the server does.\n */\n patch: <Name extends string, F extends Schema.Struct.Fields>(\n ref: EntityRef<Name, F>,\n patch: Partial<Schema.Struct.Encoded<F>>,\n ): EntityPatch<Name, F> => ({ entity: ref.entity, id: ref.id, values: patch }),\n}\n","/** A serializable summary of a RemoteModel for DevTools and diagnostics. */\nimport type { RemoteModel } from './model.js'\nimport type { EntityEntry } from './store.js'\n\n/** A serializable summary of a RemoteModel for DevTools and diagnostics. */\nexport interface RemoteInspection {\n readonly entities: ReadonlyArray<{\n readonly key: string\n readonly present: ReadonlyArray<string>\n readonly stale: ReadonlyArray<string>\n readonly tombstone: boolean\n readonly updatedAt: number\n readonly windows: Readonly<Record<string, string>>\n }>\n readonly connections: ReadonlyArray<string>\n readonly live: ReadonlyArray<string>\n readonly gaps: ReadonlyArray<string>\n readonly mutations: {\n readonly pending: ReadonlyArray<string>\n readonly failed: ReadonlyArray<string>\n readonly applied: number\n }\n}\n\nconst inspectEntry = (key: string, entry: EntityEntry): RemoteInspection['entities'][number] => ({\n key,\n present: [...entry.present],\n stale: [...entry.stale],\n tombstone: entry.tombstone,\n updatedAt: entry.updatedAt,\n windows: { ...entry.windows },\n})\n\n/** A pure, serializable view of the whole cache. */\nexport const inspectRemote = (model: RemoteModel): RemoteInspection => ({\n entities: Object.entries(model.entities).map(([key, entry]) => inspectEntry(key, entry)),\n connections: Object.keys(model.connections),\n live: Object.keys(model.live),\n gaps: [...model.gaps],\n mutations: {\n pending: [...model.mutations.pending],\n failed: [...model.mutations.failed],\n applied: model.mutations.applied.size,\n },\n})\n\n/** A pure, serializable view of one entity, or `undefined` if unknown. */\nexport const inspectEntity = (\n model: RemoteModel,\n key: string,\n): RemoteInspection['entities'][number] | undefined => {\n const entry = model.entities[key]\n return entry === undefined ? undefined : inspectEntry(key, entry)\n}\n","/**\n * Optimistic layers. Pending changes are held as ordered layers over a base\n * store and as overlays over a connection; the visible value is recomputed, never\n * patched with inverses. Settling is remove-the-layer, so overlapping layers\n * rebase for free.\n */\nimport { type Connection, type Edge, edge, items } from './connection.js'\nimport { reconcileMutation, type MutationState, type NormalizedPatch } from './mutation.js'\nimport { entityKey, isTombstone, writeEntity, type EntityStore } from './store.js'\n\nexport interface EntityLayer {\n readonly id: string\n readonly patches: ReadonlyArray<NormalizedPatch>\n}\n\n/**\n * Edges placed outside a connection's server-known region (`prepend`,\n * `append`) or hidden from it (`remove`), owned by the request or live event\n * that produced them.\n */\nexport interface ConnectionOverlay {\n readonly id: string\n readonly connection: string\n readonly edges: ReadonlyArray<Edge>\n readonly position: 'prepend' | 'append' | 'remove'\n}\n\n/** A connection change a request makes optimistically or a mutation result confirms. */\nexport type ConnectionChange =\n | {\n readonly _tag: 'Insert'\n readonly connection: string\n readonly position: 'prepend' | 'append'\n readonly edge: Edge\n }\n | { readonly _tag: 'Remove'; readonly connection: string; readonly edge: Edge }\n\n/** What a request changes before the server answers: entity patches and connection changes. */\nexport type OptimisticOperation = NormalizedPatch | ConnectionChange\n\nconst isConnectionChange = (operation: OptimisticOperation): operation is ConnectionChange =>\n '_tag' in operation\n\nconst toOverlays = (id: string, changes: ReadonlyArray<ConnectionChange>): ConnectionOverlay[] =>\n changes.map(change => ({\n id,\n connection: change.connection,\n edges: [change.edge],\n position: change._tag === 'Insert' ? change.position : 'remove',\n }))\n\n/** A connection, by identity string or by anything that carries one (a `QueryRef`). */\nexport type ConnectionIdentity = string | { readonly identity: string }\n\nexport const connectionIdentity = (connection: ConnectionIdentity): string =>\n typeof connection === 'string' ? connection : connection.identity\n\nconst change = (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n position: 'prepend' | 'append' | 'remove',\n): ConnectionChange =>\n position === 'remove'\n ? { _tag: 'Remove', connection: connectionIdentity(connection), edge: edge(ref) }\n : { _tag: 'Insert', connection: connectionIdentity(connection), position, edge: edge(ref) }\n\n/**\n * Constructors for connection changes: what a request shows optimistically\n * (`MutateOptions.optimistic`) and what a mutation source reports it made\n * (`MutationOutcome.connections`).\n */\nexport const ConnectionChange = {\n /** Show `ref` at the front of the connection until the request settles. */\n prepend: (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n ): ConnectionChange => change(connection, ref, 'prepend'),\n\n /** Show `ref` at the end of the connection until the request settles. */\n append: (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n ): ConnectionChange => change(connection, ref, 'append'),\n\n /** Hide `ref` from the connection until the request settles. */\n remove: (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n ): ConnectionChange => change(connection, ref, 'remove'),\n}\n\n/**\n * Applies a request's operations: its patches become one layer and its\n * connection changes become overlays, all owned by `requestId` so settling\n * removes every one of them together.\n */\nexport const beginOptimistic = (\n optimistic: OptimisticState,\n requestId: string,\n operations: ReadonlyArray<OptimisticOperation>,\n): OptimisticState => {\n const patches = operations.filter(\n (operation): operation is NormalizedPatch => !isConnectionChange(operation),\n )\n const changes = operations.filter(isConnectionChange)\n return {\n layers:\n patches.length === 0 ? optimistic.layers : [...optimistic.layers, { id: requestId, patches }],\n overlays: [...optimistic.overlays, ...toOverlays(requestId, changes)],\n }\n}\n\n/**\n * Replaces a request's overlays with the server-confirmed changes, owned by\n * `id`, in the position the request's overlays held, so a confirmed edge keeps\n * its place among other pending inserts.\n */\nconst confirm = (\n optimistic: OptimisticState,\n requestId: string,\n id: string,\n changes: ReadonlyArray<ConnectionChange>,\n): OptimisticState => {\n const confirmed = toOverlays(id, changes)\n const at = optimistic.overlays.findIndex(overlay => overlay.id === requestId)\n const others = optimistic.overlays.filter(overlay => overlay.id !== requestId)\n return {\n ...optimistic,\n overlays:\n at === -1\n ? [...others, ...confirmed]\n : [...others.slice(0, at), ...confirmed, ...others.slice(at)],\n }\n}\n\n/** Pending entity layers and connection overlays over the base store. */\nexport interface OptimisticState {\n readonly layers: ReadonlyArray<EntityLayer>\n readonly overlays: ReadonlyArray<ConnectionOverlay>\n}\n\nexport const emptyOptimistic: OptimisticState = { layers: [], overlays: [] }\n\nexport const addLayer = (optimistic: OptimisticState, layer: EntityLayer): OptimisticState => ({\n ...optimistic,\n layers: [...optimistic.layers, layer],\n})\n\nexport const removeLayer = (optimistic: OptimisticState, id: string): OptimisticState => ({\n ...optimistic,\n layers: optimistic.layers.filter(layer => layer.id !== id),\n})\n\nexport const addOverlay = (\n optimistic: OptimisticState,\n overlay: ConnectionOverlay,\n): OptimisticState => ({\n ...optimistic,\n overlays: [...optimistic.overlays, overlay],\n})\n\nexport const removeOverlay = (optimistic: OptimisticState, id: string): OptimisticState => ({\n ...optimistic,\n overlays: optimistic.overlays.filter(overlay => overlay.id !== id),\n})\n\n/** Base store with every layer applied in order. Later layers win. */\nexport const visibleStore = (base: EntityStore, optimistic: OptimisticState): EntityStore =>\n optimistic.layers.reduce(\n (store, layer) =>\n layer.patches.reduce(\n (current, patch) => writeEntity(current, entityKey(patch.entity, patch.id), patch.values),\n store,\n ),\n base,\n )\n\n/**\n * A fresh page is newer than any settled overlay it covers: an edge the page\n * carries no longer needs an insert overlay, and a `remove` overlay hiding it\n * is stale (the server says it is back). A pending request's overlays are\n * left alone; they settle with the request.\n */\nexport const pruneOverlays = (\n optimistic: OptimisticState,\n connection: string,\n covered: ReadonlySet<string>,\n pending: ReadonlySet<string>,\n): OptimisticState => ({\n ...optimistic,\n overlays: optimistic.overlays.flatMap(overlay => {\n if (overlay.connection !== connection || pending.has(overlay.id)) return [overlay]\n const edges = overlay.edges.filter(edge => !covered.has(edge.key))\n return edges.length === 0 ? [] : [{ ...overlay, edges }]\n }),\n})\n\n/** Everything a request owns: its layer and its overlays. */\nconst release = (optimistic: OptimisticState, requestId: string): OptimisticState =>\n removeOverlay(removeLayer(optimistic, requestId), requestId)\n\n/**\n * Applies a result idempotently and releases the request's layer and overlays:\n * a later layer re-wins on rebase. Confirmed connection changes are recorded\n * once per request, as overlays the request no longer owns.\n */\nexport const settleSuccess = (\n base: EntityStore,\n optimistic: OptimisticState,\n state: MutationState,\n requestId: string,\n entities: ReadonlyArray<NormalizedPatch>,\n connections: ReadonlyArray<ConnectionChange> = [],\n deleted: ReadonlyArray<{ readonly entity: string; readonly id: string }> = [],\n): {\n readonly store: EntityStore\n readonly state: MutationState\n readonly optimistic: OptimisticState\n} => {\n const reconciled = reconcileMutation(base, state, requestId, entities, deleted)\n return {\n store: reconciled.store,\n state: reconciled.state,\n optimistic: state.applied.has(requestId)\n ? release(optimistic, requestId)\n : confirm(\n removeLayer(optimistic, requestId),\n requestId,\n `confirmed:${requestId}`,\n connections,\n ),\n }\n}\n\n/** A failed request's layer and overlays are dropped; the base was never mutated. */\nexport const settleFailure = (optimistic: OptimisticState, requestId: string): OptimisticState =>\n release(optimistic, requestId)\n\n/**\n * Visible edges for one connection: applicable overlays are placed outside the\n * server-known segments and de-duplicated by edge identity (across overlays too),\n * so a pending insert never corrupts server-known ordering; a `remove` overlay\n * hides its edges wherever they are, and so does a tombstone on the edge's\n * target when `store` is given. A later prepend lands before an earlier one, a\n * later append after, so pending inserts read in the order they were made.\n * Boundaries still come from the connection's segments.\n */\nexport const visibleItems = (\n connection: Connection,\n connectionId: string,\n overlays: ReadonlyArray<ConnectionOverlay>,\n store?: EntityStore,\n): ReadonlyArray<Edge> => {\n const applicable = overlays.filter(overlay => overlay.connection === connectionId)\n // Overlays are ordered evidence: the last word on an edge wins, so a remove\n // hides it only until a later insert brings it back.\n const hidden = new Set<string>()\n for (const overlay of applicable) {\n for (const edge of overlay.edges) {\n if (overlay.position === 'remove') hidden.add(edge.key)\n else hidden.delete(edge.key)\n }\n }\n const gone = (edge: Edge): boolean =>\n hidden.has(edge.key) ||\n (store !== undefined && isTombstone(store, entityKey(edge.ref.entity, edge.ref.id)))\n const known = items(connection).filter(edge => !gone(edge))\n const seen = new Set(known.map(edge => edge.key))\n\n const take = (position: 'prepend' | 'append'): ReadonlyArray<Edge> => {\n const edges: Edge[] = []\n const ordered = applicable.filter(value => value.position === position)\n for (const overlay of position === 'prepend' ? [...ordered].reverse() : ordered) {\n for (const edge of overlay.edges) {\n if (seen.has(edge.key) || gone(edge)) continue\n seen.add(edge.key)\n edges.push(edge)\n }\n }\n return edges\n }\n\n return [...take('prepend'), ...known, ...take('append')]\n}\n","/**\n * Live data. Entity facts update the store; connection facts change ordering and\n * membership. Events carry a monotonic cursor ordered **per stream**: duplicates\n * are ignored, and a gap is surfaced so the caller can resume or invalidate.\n * Subscriptions are selection-aware and driven by active Surfaces.\n */\nimport type { EdgeRef } from './connection.js'\nimport { type Connection, type Edge, hasNext, hasPrevious } from './connection.js'\nimport { addOverlay, type OptimisticState } from './optimistic.js'\nimport type { LiveInsertion, LivePolicy } from './query.js'\nimport { entityKey, tombstone, writeEntity, type EntityStore } from './store.js'\n\nexport type LiveCursor = number\n\nexport type LiveEvent =\n | {\n readonly _tag: 'EntityPatched'\n readonly ref: EdgeRef\n readonly values: Readonly<Record<string, unknown>>\n readonly changed: ReadonlyArray<string>\n readonly cursor: LiveCursor\n }\n | { readonly _tag: 'EntityDeleted'; readonly ref: EdgeRef; readonly cursor: LiveCursor }\n | {\n readonly _tag: 'ConnectionInsert'\n readonly connection: string\n readonly position: 'prepend' | 'append'\n readonly edge: Edge\n readonly cursor: LiveCursor\n }\n | {\n readonly _tag: 'ConnectionRemove'\n readonly connection: string\n readonly edge: Edge\n readonly cursor: LiveCursor\n }\n | {\n readonly _tag: 'ConnectionInvalidate'\n readonly connection: string\n readonly cursor: LiveCursor\n }\n\nexport interface BoundaryCounts {\n readonly before: number\n readonly after: number\n}\n\nexport interface LiveState {\n /** Last applied cursor for this stream. */\n readonly cursor: LiveCursor\n /** Connections marked stale by an invalidating event. */\n readonly stale: ReadonlySet<string>\n /** Edges recorded outside the loaded boundary, not visible in `items`. */\n readonly boundary: Readonly<Record<string, BoundaryCounts>>\n}\n\nexport const emptyLiveState: LiveState = { cursor: 0, stale: new Set(), boundary: {} }\n\nexport type LiveOutcome = 'applied' | 'duplicate' | 'gap'\n\n/**\n * Ordering per stream: at most the next cursor; ahead is a gap. Cursor `0` means\n * \"no baseline yet\" (cursors are 1-based), so the first event of a stream is\n * accepted whatever its cursor — otherwise a stream not starting at 1 would be a\n * spurious gap.\n */\nexport const classifyLive = (state: LiveState, cursor: LiveCursor): LiveOutcome =>\n cursor <= state.cursor\n ? 'duplicate'\n : state.cursor === 0 || cursor === state.cursor + 1\n ? 'applied'\n : 'gap'\n\nconst advance = (state: LiveState, cursor: LiveCursor): LiveState => ({ ...state, cursor })\n\nconst recordBoundary = (\n state: LiveState,\n connection: string,\n position: 'prepend' | 'append',\n): LiveState => {\n const current = state.boundary[connection] ?? { before: 0, after: 0 }\n const next =\n position === 'prepend'\n ? { ...current, before: current.before + 1 }\n : { ...current, after: current.after + 1 }\n return { ...state, boundary: { ...state.boundary, [connection]: next } }\n}\n\nexport const invalidateConnection = (state: LiveState, connection: string): LiveState => ({\n ...state,\n stale: new Set([...state.stale, connection]),\n})\n\n/**\n * A subscriber is woken only if the event changed a field it selects. A\n * change to an unselected field is skipped entirely.\n */\nexport const shouldWake = (\n changed: ReadonlyArray<string>,\n selected: ReadonlyArray<string>,\n): boolean => changed.some(field => selected.includes(field))\n\nexport interface EntityApplied {\n readonly state: LiveState\n readonly store: EntityStore\n readonly outcome: LiveOutcome\n}\n\nexport const applyEntityEvent = (\n state: LiveState,\n store: EntityStore,\n event: Extract<LiveEvent, { _tag: 'EntityPatched' | 'EntityDeleted' }>,\n now = 0,\n): EntityApplied => {\n const outcome = classifyLive(state, event.cursor)\n if (outcome !== 'applied') return { state, store, outcome }\n const key = entityKey(event.ref.entity, event.ref.id)\n const next =\n event._tag === 'EntityPatched'\n ? writeEntity(store, key, event.values, now)\n : tombstone(store, key)\n return { state: advance(state, event.cursor), store: next, outcome }\n}\n\nexport interface ConnectionApplied {\n readonly state: LiveState\n readonly optimistic: OptimisticState\n readonly outcome: LiveOutcome\n}\n\nconst removeEdgeOverlays = (\n optimistic: OptimisticState,\n connection: string,\n key: string,\n): OptimisticState => ({\n ...optimistic,\n overlays: optimistic.overlays.map(overlay =>\n overlay.connection !== connection || overlay.position === 'remove'\n ? overlay\n : { ...overlay, edges: overlay.edges.filter(edge => edge.key !== key) },\n ),\n})\n\nexport const applyConnectionEvent = (\n state: LiveState,\n optimistic: OptimisticState,\n event: Extract<\n LiveEvent,\n { _tag: 'ConnectionInsert' | 'ConnectionRemove' | 'ConnectionInvalidate' }\n >,\n policy: LivePolicy = {},\n): ConnectionApplied => {\n const outcome = classifyLive(state, event.cursor)\n if (outcome !== 'applied') return { state, optimistic, outcome }\n\n switch (event._tag) {\n case 'ConnectionInsert': {\n const selection: LiveInsertion =\n (event.position === 'prepend' ? policy.prepend : policy.append) ?? 'visible'\n switch (selection) {\n case 'visible':\n return {\n state: advance(state, event.cursor),\n optimistic: addOverlay(optimistic, {\n id: `live:${event.cursor}`,\n connection: event.connection,\n edges: [event.edge],\n position: event.position,\n }),\n outcome,\n }\n case 'boundary':\n return {\n state: recordBoundary(advance(state, event.cursor), event.connection, event.position),\n optimistic,\n outcome,\n }\n case 'invalidate':\n return {\n state: invalidateConnection(advance(state, event.cursor), event.connection),\n optimistic,\n outcome,\n }\n case 'ignore':\n return { state: advance(state, event.cursor), optimistic, outcome }\n }\n }\n case 'ConnectionRemove':\n // Strip the edge from pending inserts and hide it wherever else it is\n // (a server-known segment included) until a fresh page says otherwise.\n return {\n state: advance(state, event.cursor),\n optimistic: addOverlay(removeEdgeOverlays(optimistic, event.connection, event.edge.key), {\n id: `live:${event.cursor}`,\n connection: event.connection,\n edges: [event.edge],\n position: 'remove',\n }),\n outcome,\n }\n case 'ConnectionInvalidate':\n return {\n state: invalidateConnection(advance(state, event.cursor), event.connection),\n optimistic,\n outcome,\n }\n }\n}\n\nexport const isStale = (state: LiveState, connection: string): boolean =>\n state.stale.has(connection)\n\n/**\n * Clears a connection's stale mark once a fresh page has been adopted. An\n * invalidating event only records that a refetch is due; whoever merges the\n * refetched page calls this so `isStale` stops reporting.\n */\nexport const refreshConnection = (state: LiveState, connection: string): LiveState => {\n if (!state.stale.has(connection)) return state\n const stale = new Set(state.stale)\n stale.delete(connection)\n return { ...state, stale }\n}\n\n/** `hasPrevious` accounting for edges recorded outside the loaded boundary. */\nexport const liveHasPrevious = (\n connection: Connection,\n state: LiveState,\n connectionId: string,\n): boolean => hasPrevious(connection) || (state.boundary[connectionId]?.before ?? 0) > 0\n\n/** `hasNext` accounting for edges recorded outside the loaded boundary. */\nexport const liveHasNext = (\n connection: Connection,\n state: LiveState,\n connectionId: string,\n): boolean => hasNext(connection) || (state.boundary[connectionId]?.after ?? 0) > 0\n","/**\n * The pure requirement planner.\n *\n * A `Requirement` is plain data: which entity fields a Remote projection needs,\n * and through `relations`, which fields of each relation's target. `plan` diffs\n * requirements against the store and returns only the missing fields, grouped\n * and deterministically ordered. A relation whose field is being fetched keeps\n * its nested requirement on the request, so the server resolves the graph in\n * one read; a relation whose refs the store already holds is followed into\n * concrete requirements for the targets. Time enters through `PlanFreshness`,\n * never from ambient state; `force` plans every field.\n */\nimport { stableStringify } from './query.js'\nimport { targetsOf } from './relation.js'\nimport { Requirement, type RelationRequirement } from './requirement.js'\nimport { entityKey, missingFields, readField, type EntityStore } from './store.js'\n\ntype Window = NonNullable<Requirement['windows']>[string]\n\n/** A stable key for a window, so two equal windows compare equal. */\nexport const windowKey = (window: Window): string => stableStringify(window)\n\nexport interface PlanFreshness {\n readonly now: number\n /** A present entry older than this many milliseconds is refreshed whole. */\n readonly freshness: number\n}\n\nexport interface PlanOptions {\n readonly freshness?: PlanFreshness | undefined\n /** Plan every requested field, present or not, tombstoned or not. */\n readonly force?: boolean | undefined\n}\n\nconst pickFields = <T>(\n record: Readonly<Record<string, T>> | undefined,\n fields: ReadonlySet<string>,\n): Readonly<Record<string, T>> | undefined => {\n if (record === undefined) return undefined\n const picked = Object.fromEntries(Object.entries(record).filter(([field]) => fields.has(field)))\n return Object.keys(picked).length === 0 ? undefined : picked\n}\n\n/** The concrete requirements a known relation value contributes for its targets. */\nconst followRelation = (\n value: unknown,\n relation: RelationRequirement,\n): ReadonlyArray<Requirement> =>\n targetsOf(value, relation).map(ref => ({ ...relation, id: ref.id }))\n\nexport const plan = (\n store: EntityStore,\n requirements: readonly Requirement[],\n options: PlanOptions = {},\n): ReadonlyArray<Requirement> => {\n const { freshness, force = false } = options\n const planned: Requirement[] = []\n const followed: Requirement[] = []\n\n for (const group of Requirement.merge(requirements)) {\n const key = entityKey(group.entity, group.id)\n const entry = store[key]\n const expired =\n freshness !== undefined &&\n entry !== undefined &&\n !entry.tombstone &&\n freshness.now - entry.updatedAt > freshness.freshness\n const windowKeys = Object.fromEntries(\n Object.entries(group.windows ?? {}).map(([field, window]) => [field, windowKey(window)]),\n )\n const missing =\n force || expired ? group.fields : missingFields(store, key, group.fields, windowKeys)\n const missingSet = new Set(missing)\n\n // A relation the store already holds is followed into its targets; one\n // being fetched rides on the request instead.\n for (const [field, relation] of Object.entries(group.relations ?? {})) {\n if (missingSet.has(field)) continue\n const value = readField(store, key, field)\n if (value._tag === 'Some') followed.push(...followRelation(value.value, relation))\n }\n\n if (missing.length === 0) continue\n // Only a field being fetched carries its window and its relation.\n const windows = pickFields(group.windows, missingSet)\n const relations = pickFields(group.relations, missingSet)\n planned.push({\n entity: group.entity,\n id: group.id,\n fields: missing,\n ...(windows === undefined ? {} : { windows }),\n ...(relations === undefined ? {} : { relations }),\n })\n }\n\n const nested = followed.length === 0 ? [] : plan(store, followed, options)\n return [...Requirement.merge([...planned, ...nested])].sort((a, b) =>\n entityKey(a.entity, a.id) < entityKey(b.entity, b.id) ? -1 : 1,\n )\n}\n","/**\n * Cache lifetime. Retention roots are the requirements (and connections) the\n * application's active Surfaces observe; `gc` keeps what they reach through\n * the store's refs plus every pending optimistic change, and drops the rest.\n * Roots live outside the Model, so GC arrives as a Message.\n */\nimport type { RelationRequirement, Requirement } from './requirement.js'\nimport { refsIn } from './relation.js'\nimport { entityKey, readField, type EntityKey, type EntityStore } from './store.js'\nimport type { Connection } from './connection.js'\nimport type { OptimisticState } from './optimistic.js'\nimport type { MutationState } from './mutation.js'\n\n/** A connection to keep: its identity, and what a page of it selects of each item, if a projection reads it. */\nexport interface ConnectionRoot {\n readonly identity: string\n readonly select?: RelationRequirement | undefined\n}\n\nexport interface RetentionRoots {\n readonly requirements: ReadonlyArray<Requirement>\n /** Connections (`QueryRef.identity`) to keep, with their edges' targets and what `select` reaches through them. */\n readonly connections: ReadonlyArray<ConnectionRoot>\n}\n\nexport interface Retained {\n readonly entities: EntityStore\n readonly connections: Readonly<Record<string, Connection>>\n readonly optimistic: OptimisticState\n}\n\n/**\n * The entity keys the roots reach: each root entity, the targets its retained\n * fields refer to, and recursively the targets a nested relation selects.\n */\nexport const reachable = (\n store: EntityStore,\n roots: RetentionRoots,\n connections: Readonly<Record<string, Connection>>,\n optimistic: OptimisticState,\n pending: ReadonlySet<string>,\n): ReadonlySet<EntityKey> => {\n const kept = new Set<EntityKey>()\n const rootConnections = new Set(roots.connections.map(root => root.identity))\n // A target is walked once per relation spec that reaches it: two specs may\n // select different nested relations of the same entity, and a spec tree is\n // finite, so this terminates on cyclic data too.\n const walked = new Map<EntityKey, Set<Omit<Requirement, 'id'>>>()\n const visit = (key: EntityKey, requirement: Omit<Requirement, 'id'>): void => {\n kept.add(key)\n const seen = walked.get(key) ?? new Set()\n if (seen.has(requirement)) return\n seen.add(requirement)\n walked.set(key, seen)\n for (const field of requirement.fields) {\n const value = readField(store, key, field)\n if (value._tag === 'None') continue\n const relation = requirement.relations?.[field]\n for (const ref of refsIn(value.value)) {\n const target = entityKey(ref.entity, ref.id)\n if (relation === undefined || ref.entity !== relation.entity) {\n kept.add(target)\n continue\n }\n visit(target, relation)\n }\n }\n }\n for (const root of roots.requirements) visit(entityKey(root.entity, root.id), root)\n // A connection root keeps its edges' targets, and what a page's `select`\n // reaches through them (an item's owner, say), so the page stays readable.\n for (const { identity, select } of roots.connections) {\n for (const segment of connections[identity]?.segments ?? []) {\n for (const edge of segment.edges) {\n const target = entityKey(edge.ref.entity, edge.ref.id)\n if (select === undefined || edge.ref.entity !== select.entity) kept.add(target)\n else visit(target, select)\n }\n }\n }\n // A pending request's changes are kept whole; a settled overlay (a live or\n // confirmed insert) is kept only with a retained connection, below.\n for (const layer of optimistic.layers) {\n if (!pending.has(layer.id)) continue\n for (const patch of layer.patches) kept.add(entityKey(patch.entity, patch.id))\n }\n for (const overlay of optimistic.overlays) {\n if (!pending.has(overlay.id) && !rootConnections.has(overlay.connection)) continue\n for (const edge of overlay.edges) kept.add(entityKey(edge.ref.entity, edge.ref.id))\n }\n return kept\n}\n\n/**\n * Drops every entity the roots do not reach, every connection they do not\n * name, and every settled overlay on a dropped connection, keeping whatever a\n * pending request's layer or overlays touch. Pure.\n */\nexport const gc = (\n state: Retained & { readonly mutations: MutationState },\n roots: RetentionRoots,\n): Retained => {\n const pending = state.mutations.pending\n const kept = reachable(state.entities, roots, state.connections, state.optimistic, pending)\n const entities = Object.fromEntries(\n Object.entries(state.entities).filter(([key]) => kept.has(key)),\n )\n const keptConnections = new Set([\n ...roots.connections.map(root => root.identity),\n ...state.optimistic.overlays\n .filter(overlay => pending.has(overlay.id))\n .map(overlay => overlay.connection),\n ])\n const connections = Object.fromEntries(\n Object.entries(state.connections).filter(([identity]) => keptConnections.has(identity)),\n )\n const optimistic: OptimisticState = {\n layers: state.optimistic.layers,\n overlays: state.optimistic.overlays.filter(\n overlay => pending.has(overlay.id) || keptConnections.has(overlay.connection),\n ),\n }\n return { entities, connections, optimistic }\n}\n","/**\n * Remote cache persistence: a snapshot of the entity store and nothing else.\n * Runtime state (connections' live cursors, optimistic layers, the mutation\n * ledger, gaps, retention roots) is never in a snapshot; it belongs to the\n * session that produced it.\n *\n * The cache is server-derived and disposable: an incompatible, oversized, or\n * corrupt snapshot is discarded (and removed from a `KeyValueStore`) so the\n * planner refetches. `dehydrate`/`hydrate` are the string forms, for SSR and\n * any other transport; `save`/`restore` put them behind Effect's\n * `KeyValueStore`, so the backend (memory, filesystem, SQL, Web Storage) is the\n * application's choice.\n */\nimport { Effect } from 'effect'\nimport { KeyValueStore } from 'effect/unstable/persistence'\nimport { stableStringify } from './query.js'\nimport { emptyStore, type EntityEntry, type EntityStore } from './store.js'\n\n/** Bump when the serialized shape changes; a mismatch discards the cache. */\nexport const REMOTE_CACHE_VERSION = 3\n\nexport interface SnapshotOptions {\n /**\n * Who or what the snapshot is for (a user id, a tenant, a build). A snapshot\n * taken under another scope is discarded rather than shown to the wrong\n * reader. Default: unscoped, which only matches unscoped.\n */\n readonly scope?: string | undefined\n /** Snapshots larger than this many bytes are not written and not read. */\n readonly maxBytes?: number | undefined\n}\n\n/** How a snapshot meets a store that already has entries. */\nexport type MergePolicy = 'replace' | 'preserve-existing'\n\ninterface SerializedEntry {\n readonly values: Readonly<Record<string, unknown>>\n readonly present: ReadonlyArray<string>\n readonly stale: ReadonlyArray<string>\n readonly tombstone: boolean\n readonly updatedAt: number\n readonly windows: Readonly<Record<string, string>>\n}\n\ninterface SerializedStore {\n readonly version: number\n readonly scope: string | null\n readonly entities: Readonly<Record<string, SerializedEntry>>\n}\n\nconst sorted = <T>(values: Iterable<T>): T[] => [...values].sort()\n\n/**\n * The snapshot's data shape. `stableStringify` sorts object keys, and the\n * field sets are sorted here, so equal stores give byte-equal snapshots\n * whatever order they were built in.\n */\nconst serializeStore = (store: EntityStore, scope?: string): SerializedStore => ({\n version: REMOTE_CACHE_VERSION,\n scope: scope ?? null,\n entities: Object.fromEntries(\n Object.entries(store).map(([key, entry]) => [\n key,\n {\n values: entry.values,\n present: sorted(entry.present),\n stale: sorted(entry.stale),\n tombstone: entry.tombstone,\n updatedAt: entry.updatedAt,\n windows: entry.windows,\n },\n ]),\n ),\n})\n\nconst isStringArray = (value: unknown): value is ReadonlyArray<string> =>\n Array.isArray(value) && value.every(item => typeof item === 'string')\n\nconst isStringRecord = (value: unknown): value is Readonly<Record<string, string>> =>\n value !== null &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n Object.values(value as Record<string, unknown>).every(item => typeof item === 'string')\n\n/** Throws on a malformed entry so the whole snapshot is discarded. */\nconst parseEntry = (value: unknown): EntityEntry => {\n if (value === null || typeof value !== 'object') throw new Error('entry is not an object')\n const entry = value as Record<string, unknown>\n if (entry.values === null || typeof entry.values !== 'object' || Array.isArray(entry.values)) {\n throw new Error('entry.values is not a record')\n }\n if (!isStringArray(entry.present)) throw new Error('entry.present is not a string array')\n if (!isStringArray(entry.stale)) throw new Error('entry.stale is not a string array')\n if (typeof entry.tombstone !== 'boolean') throw new Error('entry.tombstone is not a boolean')\n if (typeof entry.updatedAt !== 'number') throw new Error('entry.updatedAt is not a number')\n if (!isStringRecord(entry.windows)) throw new Error('entry.windows is not a string record')\n return {\n values: entry.values as Readonly<Record<string, unknown>>,\n present: new Set(entry.present),\n stale: new Set(entry.stale),\n tombstone: entry.tombstone,\n updatedAt: entry.updatedAt,\n windows: entry.windows,\n }\n}\n\nconst deserializeStore = (serialized: SerializedStore): EntityStore =>\n Object.fromEntries(\n Object.entries(serialized.entities).map(([key, entry]) => [key, parseEntry(entry)]),\n )\n\n/**\n * The snapshot text, or `undefined` when it would exceed `maxBytes`. Only the\n * entity store goes in; pass `model.entities`, never the whole `RemoteModel`.\n */\nfunction dehydrate(\n store: EntityStore,\n options?: SnapshotOptions & { readonly maxBytes?: undefined },\n): string\nfunction dehydrate(store: EntityStore, options?: SnapshotOptions): string | undefined\nfunction dehydrate(store: EntityStore, options: SnapshotOptions = {}): string | undefined {\n const text = stableStringify(serializeStore(store, options.scope))\n return exceeds(text, options.maxBytes) ? undefined : text\n}\n\n/**\n * Whether the UTF-8 size of `text` exceeds `maxBytes`. A character is one to\n * three bytes, so most texts are decided from their length alone; only the\n * rest are measured.\n */\nconst exceeds = (text: string, maxBytes: number | undefined): boolean => {\n if (maxBytes === undefined) return false\n if (text.length > maxBytes) return true\n if (text.length * 3 <= maxBytes) return false\n return new TextEncoder().encode(text).length > maxBytes\n}\n\n/**\n * The store a snapshot text holds, or `undefined` when the text is missing,\n * oversized, not this version, for another scope, or malformed. Hydrating the\n * same text twice yields equal stores.\n */\nconst hydrate = (\n raw: string | undefined | null,\n options: SnapshotOptions = {},\n): EntityStore | undefined => {\n if (raw === undefined || raw === null) return undefined\n if (exceeds(raw, options.maxBytes)) return undefined\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n return undefined\n }\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return undefined\n const candidate = parsed as {\n readonly version?: unknown\n readonly scope?: unknown\n readonly entities?: unknown\n }\n if (candidate.version !== REMOTE_CACHE_VERSION) return undefined\n if ((candidate.scope ?? null) !== (options.scope ?? null)) return undefined\n if (candidate.entities === null || typeof candidate.entities !== 'object') return undefined\n if (Array.isArray(candidate.entities)) return undefined\n try {\n return deserializeStore(candidate as SerializedStore)\n } catch {\n return undefined\n }\n}\n\n/**\n * Brings a snapshot into a store that may already hold entries. `replace`\n * takes the snapshot's entry for every key it has; `preserve-existing` keeps\n * an entry the current store already has (it is at least as fresh as a\n * snapshot taken earlier). Either way, keys only the current store has stay.\n */\nconst mergeStores = (\n current: EntityStore,\n snapshot: EntityStore,\n policy: MergePolicy,\n): EntityStore => (policy === 'replace' ? { ...current, ...snapshot } : { ...snapshot, ...current })\n\nexport const RemotePersistence = {\n /** The snapshot text, or `undefined` when it would exceed `maxBytes`. */\n dehydrate,\n /** The store a snapshot text holds, or `undefined` when it is refused. */\n hydrate,\n /** A snapshot brought into a store by policy. */\n mergeStores,\n\n /**\n * Writes the snapshot under `key`, or removes the key when the store would\n * exceed `maxBytes`, so a stale smaller snapshot cannot outlive a larger\n * store it no longer describes.\n */\n save: (store: EntityStore, options: { readonly key: string } & SnapshotOptions) =>\n Effect.gen(function* () {\n const kv = yield* KeyValueStore.KeyValueStore\n const text = dehydrate(store, options)\n if (text === undefined) yield* kv.remove(options.key)\n else yield* kv.set(options.key, text)\n }),\n\n /**\n * Reads the cache. A missing key yields `emptyStore`; anything `hydrate`\n * refuses yields `emptyStore` and removes the key, so the next `restore` is\n * clean and the planner refetches.\n */\n restore: (options: { readonly key: string } & SnapshotOptions) =>\n Effect.gen(function* () {\n const kv = yield* KeyValueStore.KeyValueStore\n const raw = yield* kv.get(options.key)\n if (raw === undefined) return emptyStore\n const restored = hydrate(raw, options)\n if (restored === undefined) {\n yield* kv.remove(options.key)\n return emptyStore\n }\n return restored\n }),\n}\n","/** `RemoteData`: the state of a value the store may not hold yet. */\nimport { Option, Schema } from 'effect'\n\nexport interface RemoteError {\n readonly _tag: string\n readonly message: string\n}\n\nexport type RemoteData<A> =\n | { readonly _tag: 'Initial' }\n | { readonly _tag: 'Loading' }\n | { readonly _tag: 'Ready'; readonly value: A }\n | { readonly _tag: 'Refreshing'; readonly value: A }\n | { readonly _tag: 'Failed'; readonly error: RemoteError; readonly previous?: A }\n | { readonly _tag: 'NotFound' }\n\nexport const remoteErrorSchema = Schema.Struct({ _tag: Schema.String, message: Schema.String })\n\n/** A `RemoteData` schema, so a projection that reads remote state is typed. */\n// A projection is rebuilt on every Model change (a Surface's `model` callback\n// runs per dependency computation), so the schema for a value schema is built\n// once and shared: the value schema is a module-level constant in practice.\nconst remoteDataSchemas = new WeakMap<object, Schema.Schema<unknown>>()\n\nexport const remoteDataSchema = <A>(\n value: Schema.Schema<A>,\n): Schema.Codec<RemoteData<A>, unknown> => {\n const cached = remoteDataSchemas.get(value)\n if (cached !== undefined) return cached as Schema.Codec<RemoteData<A>, unknown>\n const built = Schema.Union([\n Schema.Struct({ _tag: Schema.Literal('Initial') }),\n Schema.Struct({ _tag: Schema.Literal('Loading') }),\n Schema.Struct({ _tag: Schema.Literal('Ready'), value }),\n Schema.Struct({ _tag: Schema.Literal('Refreshing'), value }),\n Schema.Struct({\n _tag: Schema.Literal('Failed'),\n error: remoteErrorSchema,\n previous: Schema.optional(value),\n }),\n Schema.Struct({ _tag: Schema.Literal('NotFound') }),\n ]) as unknown as Schema.Codec<RemoteData<A>, unknown>\n remoteDataSchemas.set(value, built as Schema.Schema<unknown>)\n return built\n}\n\nexport const RemoteData = {\n /**\n * The `RemoteData` schema for a value schema. Exposed so a `RemoteData` can\n * be embedded in a hand-written Model schema, not only through `Remote.select`.\n */\n schema: <A>(value: Schema.Schema<A>): Schema.Schema<RemoteData<A>> => remoteDataSchema(value),\n\n /** Exhaustive: omitting a state is a compile error. */\n match: <A, R>(\n data: RemoteData<A>,\n cases: {\n readonly Initial: () => R\n readonly Loading: () => R\n readonly Ready: (value: A) => R\n readonly Refreshing: (value: A) => R\n readonly Failed: (error: RemoteError, previous: Option.Option<A>) => R\n readonly NotFound: () => R\n },\n ): R => {\n switch (data._tag) {\n case 'Initial':\n return cases.Initial()\n case 'Loading':\n return cases.Loading()\n case 'Ready':\n return cases.Ready(data.value)\n case 'Refreshing':\n return cases.Refreshing(data.value)\n case 'Failed':\n return cases.Failed(\n data.error,\n data.previous === undefined ? Option.none() : Option.some(data.previous),\n )\n case 'NotFound':\n return cases.NotFound()\n }\n },\n\n map: <A, B>(data: RemoteData<A>, f: (value: A) => B): RemoteData<B> => {\n switch (data._tag) {\n case 'Ready':\n return { _tag: 'Ready', value: f(data.value) }\n case 'Refreshing':\n return { _tag: 'Refreshing', value: f(data.value) }\n case 'Failed':\n return data.previous === undefined\n ? { _tag: 'Failed', error: data.error }\n : { _tag: 'Failed', error: data.error, previous: f(data.previous) }\n default:\n return data\n }\n },\n}\n","/**\n * The Remote submodel: the store, connections, mutations, live state, and\n * optimistic layers an application keeps in its Model, the Messages that\n * change it, and the pure reducer over them.\n */\nimport { Schema } from 'effect'\nimport type { Requirement } from './requirement.js'\nimport { emptyConnection, merge, type Connection, type Segment } from './connection.js'\nimport {\n beginOptimistic,\n emptyOptimistic,\n pruneOverlays,\n settleFailure,\n settleSuccess,\n type ConnectionChange,\n type OptimisticState,\n type OptimisticOperation,\n} from './optimistic.js'\nimport {\n applyConnectionEvent,\n applyEntityEvent,\n emptyLiveState,\n type LiveEvent,\n type LiveState,\n} from './live.js'\nimport {\n beginMutation,\n emptyMutationState,\n failMutation,\n type MutationState,\n type NormalizedPatch,\n} from './mutation.js'\nimport {\n entityKey,\n emptyStore,\n setStale,\n tombstone,\n writeEntities,\n type EntityStore,\n type EntityWrite,\n} from './store.js'\nimport { windowKey } from './plan.js'\nimport { isRefPage, targetsOf, type RefPageValue } from './relation.js'\nimport { gc, type RetentionRoots } from './retain.js'\nimport { RemotePersistence, type MergePolicy } from './persistence.js'\nimport { NormalizedEntity, ReadBatchResult, ReadRequest, RelationRequest } from './wire.js'\nimport { remoteErrorSchema, type RemoteError } from './remoteData.js'\nimport type { LivePolicy } from './query.js'\n\n/**\n * The normalized cache as a Foldkit Submodel. `Remote.define` returns a schema\n * and an `update` for this shape; `updateRemote` reconciles every producer.\n */\nexport interface RemoteModel {\n /** Entity values, presence, staleness, tombstones, and applied windows. */\n readonly entities: EntityStore\n /** Normalized ordered connections, keyed by connection identity. */\n readonly connections: Readonly<Record<string, Connection>>\n /** Optimistic entity layers and connection overlays over the base store. */\n readonly optimistic: OptimisticState\n /** Live cursor and boundary state, keyed by the subscription's stream key. */\n readonly live: Readonly<Record<string, LiveState>>\n /** Mutation pending/applied/failed ledger. */\n readonly mutations: MutationState\n /** Streams whose live cursor fell behind; the caller should resync or refetch. */\n readonly gaps: ReadonlySet<string>\n /**\n * The `entity\\0id\\0field` marks a read is currently fetching. A field absent\n * from the store reads as `Loading` while its mark is here and `Initial`\n * otherwise, which is what separates \"being fetched\" from \"nothing is\n * fetching this\".\n */\n readonly loading: ReadonlySet<string>\n /**\n * `Remote.refresh` generations. The read entries restart when `requested`\n * moves, so a read sent before a refresh cannot land after it; `started` is\n * the latest generation a read began under.\n */\n readonly refresh: { readonly requested: number; readonly started: number }\n}\n\nexport const initialRemoteModel: RemoteModel = {\n entities: emptyStore,\n connections: {},\n optimistic: emptyOptimistic,\n live: {},\n mutations: emptyMutationState,\n gaps: new Set(),\n loading: new Set(),\n refresh: { requested: 0, started: 0 },\n}\n\n/** The entity store and the mutation ledger are runtime values, not wire shapes. */\nconst runtimeSchema = Schema.Unknown\n\nexport const remoteModelSchema = (): Schema.Codec<RemoteModel, unknown> =>\n // The runtime fields decode as `unknown`; their types come from `RemoteModel`.\n Schema.Struct({\n entities: runtimeSchema,\n connections: Schema.Record(Schema.String, runtimeSchema),\n optimistic: runtimeSchema,\n live: Schema.Record(Schema.String, runtimeSchema),\n mutations: runtimeSchema,\n gaps: runtimeSchema,\n loading: runtimeSchema,\n refresh: Schema.Struct({ requested: Schema.Number, started: Schema.Number }),\n }) as unknown as Schema.Codec<RemoteModel, unknown>\n\n/** The submodel's Messages; each reduces to `RemoteModel` through `updateRemote`. */\nexport type RemoteMessage =\n | {\n readonly _tag: 'ReadReceived'\n readonly requests: readonly Requirement[]\n readonly result: Schema.Schema.Type<typeof ReadBatchResult>\n readonly now: number\n }\n | {\n readonly _tag: 'ReadFailed'\n readonly requests: readonly Requirement[]\n readonly error: RemoteError\n }\n /** A refetch of present fields began; they read as `Refreshing` until it lands. */\n | { readonly _tag: 'RefreshStarted'; readonly requests: readonly Requirement[] }\n /** A read began; the fields it asks for that the store lacks read as `Loading`. */\n | {\n readonly _tag: 'ReadStarted'\n readonly requests: readonly Requirement[]\n /** The refresh generation the read was planned under. */\n readonly refresh?: number | undefined\n }\n /** The active Surfaces' roots changed; everything they do not reach is collected. */\n | { readonly _tag: 'RetentionChanged'; readonly roots: RetentionRoots }\n /** A restored snapshot meets the store; runtime state is untouched. */\n | { readonly _tag: 'Hydrated'; readonly entities: EntityStore; readonly merge: MergePolicy }\n /** A mutation began; its optimistic operations show until it settles. */\n | {\n readonly _tag: 'MutationStarted'\n readonly requestId: string\n readonly optimistic?: ReadonlyArray<OptimisticOperation> | undefined\n }\n | {\n readonly _tag: 'MutationSucceeded'\n readonly requestId: string\n readonly entities: readonly NormalizedPatch[]\n /** Connection changes the server confirmed; they replace the request's own. */\n readonly connections?: ReadonlyArray<ConnectionChange> | undefined\n /** Entities the mutation deleted: tombstoned, which hides them from every connection. */\n readonly deleted?: ReadonlyArray<{ readonly entity: string; readonly id: string }> | undefined\n }\n | { readonly _tag: 'MutationFailed'; readonly requestId: string; readonly error: RemoteError }\n | {\n readonly _tag: 'LiveReceived'\n readonly stream: string\n readonly event: LiveEvent\n readonly policy?: LivePolicy\n readonly now: number\n }\n | { readonly _tag: 'GapCleared'; readonly stream: string }\n | {\n readonly _tag: 'ConnectionMerged'\n readonly connection: string\n readonly page: Segment\n /** The page answers the connection's refresh, so the merge also clears `stale`. */\n readonly refreshes?: boolean | undefined\n }\n | { readonly _tag: 'ConnectionInvalidated'; readonly connection: string }\n | { readonly _tag: 'ConnectionRefreshed'; readonly connection: string }\n /** A query for the connection failed; it reads as it did before the request. */\n | { readonly _tag: 'QueryFailed'; readonly connection: string; readonly error: RemoteError }\n\nexport const retentionRootsSchema = Schema.Struct({\n requirements: Schema.Array(ReadRequest),\n connections: Schema.Array(\n Schema.Struct({ identity: Schema.String, select: Schema.optional(RelationRequest) }),\n ),\n})\n\n/**\n * The Messages' fields by tag, without `_tag`: what `defineMessageUnion` takes,\n * so an application spreads them into its own union (`Remote.messages`).\n */\nexport const remoteMessageCases = {\n ReadReceived: {\n requests: Schema.Array(ReadRequest),\n result: ReadBatchResult,\n now: Schema.Number,\n },\n ReadFailed: { requests: Schema.Array(ReadRequest), error: remoteErrorSchema },\n RefreshStarted: { requests: Schema.Array(ReadRequest) },\n ReadStarted: { requests: Schema.Array(ReadRequest), refresh: Schema.optional(Schema.Number) },\n RetentionChanged: { roots: retentionRootsSchema },\n Hydrated: {\n entities: runtimeSchema,\n merge: Schema.Union([Schema.Literal('replace'), Schema.Literal('preserve-existing')]),\n },\n MutationStarted: {\n requestId: Schema.String,\n optimistic: Schema.optional(Schema.Array(Schema.Unknown)),\n },\n MutationSucceeded: {\n requestId: Schema.String,\n entities: Schema.Array(NormalizedEntity),\n connections: Schema.optional(Schema.Array(Schema.Unknown)),\n deleted: Schema.optional(\n Schema.Array(Schema.Struct({ entity: Schema.String, id: Schema.String })),\n ),\n },\n MutationFailed: { requestId: Schema.String, error: remoteErrorSchema },\n LiveReceived: {\n stream: Schema.String,\n event: Schema.Unknown,\n policy: Schema.optional(Schema.Unknown),\n now: Schema.Number,\n },\n GapCleared: { stream: Schema.String },\n ConnectionMerged: {\n connection: Schema.String,\n page: Schema.Unknown,\n refreshes: Schema.optional(Schema.Boolean),\n },\n ConnectionInvalidated: { connection: Schema.String },\n ConnectionRefreshed: { connection: Schema.String },\n QueryFailed: { connection: Schema.String, error: remoteErrorSchema },\n} satisfies Record<RemoteMessage['_tag'], Schema.Struct.Fields>\n\nexport type RemoteMessageTag = RemoteMessage['_tag']\n\n/**\n * A Remote Message as an application's union constructs it from\n * `remoteMessageCases`: the same shape `RemoteMessage` names, with the runtime\n * slots (`entities`, `event`, `page`) typed `unknown` by their schemas.\n */\nexport type RemoteMessageInput = {\n [Tag in RemoteMessageTag]: { readonly _tag: Tag } & Schema.Struct.Type<\n (typeof remoteMessageCases)[Tag]\n >\n}[RemoteMessageTag]\n\n/**\n * Whether a Message is one of Remote's, by tag. Narrows an application's union\n * to its Remote cases, and its complement to the application's own.\n */\nexport const isRemoteMessage = <M extends { readonly _tag: string }>(\n message: M,\n): message is Extract<M, { readonly _tag: RemoteMessageTag }> =>\n Object.hasOwn(remoteMessageCases, message._tag)\n\nexport const remoteMessageSchema = Schema.Union(\n Object.entries(remoteMessageCases).map(([tag, fields]) =>\n Schema.Struct({ _tag: Schema.Literal(tag), ...fields }),\n ),\n) as unknown as Schema.Schema<RemoteMessage>\n\nconst marksOf = (\n requests: ReadonlyArray<Requirement>,\n): ReadonlyArray<readonly [string, ReadonlyArray<string>]> =>\n requests.map(request => [entityKey(request.entity, request.id), request.fields] as const)\n\n/**\n * One mark per requested field. A read is identified by what it asks for, not by\n * a request id: two reads asking for one field share its mark, so the first\n * answer clears it. Over-clearing shows `Initial` rather than a spinner, which\n * is the safer way to be wrong.\n */\nconst loadingMarks = function* (requests: ReadonlyArray<Requirement>): Generator<string> {\n for (const request of requests) {\n const key = entityKey(request.entity, request.id)\n for (const field of request.fields) yield `${key}\\u0000${field}`\n }\n}\n\nconst withLoading = (\n loading: ReadonlySet<string>,\n requests: ReadonlyArray<Requirement>,\n): ReadonlySet<string> => {\n const next = new Set(loading)\n for (const mark of loadingMarks(requests)) next.add(mark)\n return next\n}\n\nconst withoutLoading = (\n loading: ReadonlySet<string>,\n requests: ReadonlyArray<Requirement>,\n): ReadonlySet<string> => {\n if (loading.size === 0) return loading\n const next = new Set(loading)\n for (const mark of loadingMarks(requests)) next.delete(mark)\n return next\n}\n\n/**\n * Whether a read is fetching any of `fields` for this entity. Consulted only\n * when the store lacks the value, which is what separates `Loading` from\n * `Initial`.\n */\nexport const isLoading = (\n model: RemoteModel,\n entity: string,\n id: string,\n fields: ReadonlyArray<string>,\n): boolean => {\n if (model.loading.size === 0) return false\n const key = entityKey(entity, id)\n return fields.some(field => model.loading.has(`${key}\\u0000${field}`))\n}\n\nconst setConnectionStale = (\n connections: Readonly<Record<string, Connection>>,\n connection: string,\n stale: boolean,\n): Readonly<Record<string, Connection>> => {\n const current = connections[connection] ?? emptyConnection\n return { ...connections, [connection]: { ...current, stale } }\n}\n\nconst markGap = (model: RemoteModel, stream: string): RemoteModel =>\n model.gaps.has(stream) ? model : { ...model, gaps: new Set([...model.gaps, stream]) }\n\nconst clearGap = (model: RemoteModel, stream: string): RemoteModel =>\n model.gaps.has(stream)\n ? { ...model, gaps: new Set([...model.gaps].filter(entry => entry !== stream)) }\n : model\n\n/**\n * The pure reducer all four producers share. A live event that arrives ahead of\n * its cursor is a gap: it is not applied, and the stream is recorded so the host\n * can resubscribe rather than silently miss facts.\n */\nexport const updateRemote = (model: RemoteModel, message: RemoteMessage): RemoteModel => {\n switch (message._tag) {\n case 'ReadReceived':\n return {\n ...model,\n entities: writeRead(model.entities, message.requests, message.result, message.now),\n loading: withoutLoading(model.loading, message.requests),\n }\n case 'ReadFailed':\n // The read is over; the fields read as they did before it started. A field\n // it never delivered goes back to `Initial`, not a spinner that never ends.\n return {\n ...model,\n entities: setStale(model.entities, marksOf(message.requests), false),\n loading: withoutLoading(model.loading, message.requests),\n }\n case 'RetentionChanged':\n return { ...model, ...gc(model, message.roots) }\n case 'Hydrated':\n return {\n ...model,\n entities: RemotePersistence.mergeStores(model.entities, message.entities, message.merge),\n }\n case 'RefreshStarted': {\n const entities = setStale(model.entities, marksOf(message.requests), true)\n return entities === model.entities ? model : { ...model, entities }\n }\n case 'ReadStarted': {\n const started = Math.max(model.refresh.started, message.refresh ?? 0)\n return {\n ...model,\n loading: withLoading(model.loading, message.requests),\n refresh: started === model.refresh.started ? model.refresh : { ...model.refresh, started },\n }\n }\n case 'MutationStarted':\n return {\n ...model,\n mutations: beginMutation(model.mutations, message.requestId),\n optimistic: beginOptimistic(model.optimistic, message.requestId, message.optimistic ?? []),\n }\n case 'MutationSucceeded': {\n // Settling is release-the-layer-and-overlays, so overlapping optimistic\n // layers rebase instead of needing inverse patches.\n const settled = settleSuccess(\n model.entities,\n model.optimistic,\n model.mutations,\n message.requestId,\n message.entities,\n message.connections ?? [],\n message.deleted ?? [],\n )\n return {\n ...model,\n entities: settled.store,\n mutations: settled.state,\n optimistic: settled.optimistic,\n }\n }\n case 'MutationFailed':\n return {\n ...model,\n mutations: failMutation(model.mutations, message.requestId, message.error),\n optimistic: settleFailure(model.optimistic, message.requestId),\n }\n case 'LiveReceived': {\n const state = model.live[message.stream] ?? emptyLiveState\n if (message.event._tag === 'EntityPatched' || message.event._tag === 'EntityDeleted') {\n const applied = applyEntityEvent(state, model.entities, message.event, message.now)\n return applied.outcome === 'gap'\n ? markGap(model, message.stream)\n : clearGap(\n {\n ...model,\n entities: applied.store,\n live: { ...model.live, [message.stream]: applied.state },\n },\n message.stream,\n )\n }\n const applied = applyConnectionEvent(state, model.optimistic, message.event, message.policy)\n return applied.outcome === 'gap'\n ? markGap(model, message.stream)\n : clearGap(\n {\n ...model,\n optimistic: applied.optimistic,\n live: { ...model.live, [message.stream]: applied.state },\n },\n message.stream,\n )\n }\n case 'GapCleared':\n return clearGap(model, message.stream)\n case 'ConnectionMerged': {\n const current = model.connections[message.connection] ?? emptyConnection\n // The page answering an invalidation is the server's list as it now is, so it\n // replaces the pages: removed and reordered items go, and later pages are paged\n // again. A re-run of a connection that was not invalidated still merges.\n const replaces = message.refreshes === true && current.stale\n const merged = merge(replaces ? emptyConnection : current, message.page)\n return {\n ...model,\n connections: {\n ...model.connections,\n [message.connection]: message.refreshes === true ? { ...merged, stale: false } : merged,\n },\n optimistic: pruneOverlays(\n model.optimistic,\n message.connection,\n new Set(message.page.edges.map(edge => edge.key)),\n model.mutations.pending,\n ),\n }\n }\n case 'ConnectionInvalidated':\n if (model.connections[message.connection]?.stale === true) return model\n return {\n ...model,\n connections: setConnectionStale(model.connections, message.connection, true),\n }\n case 'QueryFailed':\n // The refresh is over; the connection reads as it did before it started,\n // and one the Model never held stays absent.\n return message.connection in model.connections\n ? {\n ...model,\n connections: setConnectionStale(model.connections, message.connection, false),\n }\n : model\n case 'ConnectionRefreshed':\n return {\n ...model,\n connections: setConnectionStale(model.connections, message.connection, false),\n }\n }\n}\n\n/** Appends (after) or prepends (before) an incoming page onto the stored one. */\nconst mergeWireRefPages = (\n current: RefPageValue,\n next: RefPageValue,\n direction: 'after' | 'before',\n): RefPageValue => {\n const refs =\n direction === 'after'\n ? [...new Set([...current.refs, ...next.refs])]\n : [...new Set([...next.refs, ...current.refs])]\n // The far boundary is the incoming page's; the near one is still the stored page's.\n return direction === 'after'\n ? { refs, hasNext: next.hasNext, hasPrevious: current.hasPrevious }\n : { refs, hasNext: current.hasNext, hasPrevious: next.hasPrevious }\n}\n\n/**\n * Writes a read result into the store, recording each field's applied window so\n * a later request with a different window refetches. A relation page requested\n * with a cursor is merged onto the page already stored, so \"load more\"\n * accumulates rather than replaces. Every read path should use this rather than\n * reducing `writeEntity` by hand.\n */\nexport const writeRead = (\n store: EntityStore,\n requests: ReadonlyArray<Requirement>,\n result: Schema.Schema.Type<typeof ReadBatchResult>,\n now = 0,\n): EntityStore => {\n const returned = new Map<string, Record<string, unknown>>()\n for (const entity of result.entities) {\n const key = entityKey(entity.entity, entity.id)\n returned.set(key, { ...returned.get(key), ...entity.values })\n }\n const byEntity = new Map<\n string,\n { windows: Record<string, string>; merge: Map<string, 'after' | 'before'> }\n >()\n // A request's windows apply to its entity; a relation's windows apply to\n // each target the returned refs name, and so on down the graph.\n const record = (\n key: string,\n windows: Requirement['windows'],\n relations: Requirement['relations'],\n ): void => {\n let entry = byEntity.get(key)\n if (entry === undefined) {\n entry = { windows: {}, merge: new Map() }\n byEntity.set(key, entry)\n }\n for (const [field, window] of Object.entries(windows ?? {})) {\n entry.windows[field] = windowKey(window)\n const direction =\n window.after !== undefined ? 'after' : window.before !== undefined ? 'before' : undefined\n if (direction !== undefined) entry.merge.set(field, direction)\n }\n const values = returned.get(key)\n if (values === undefined) return\n for (const [field, relation] of Object.entries(relations ?? {})) {\n for (const ref of targetsOf(values[field], relation)) {\n record(entityKey(ref.entity, ref.id), relation.windows, relation.relations)\n }\n }\n }\n for (const request of requests) {\n record(entityKey(request.entity, request.id), request.windows, request.relations)\n }\n\n const writes: EntityWrite[] = []\n const pending = new Map<string, Record<string, unknown>>()\n for (const entity of result.entities) {\n const key = entityKey(entity.entity, entity.id)\n const entry = byEntity.get(key)\n let values = entity.values\n if (entry !== undefined && entry.merge.size > 0) {\n // A cursor page merges onto the page stored (or written earlier in this result).\n const previous = pending.get(key) ?? store[key]?.values\n if (previous !== undefined) {\n const merged: Record<string, unknown> = { ...values }\n for (const [field, direction] of entry.merge) {\n const incoming = values[field]\n const existing = previous[field]\n if (isRefPage(incoming) && isRefPage(existing)) {\n merged[field] = mergeWireRefPages(existing, incoming, direction)\n }\n }\n values = merged\n }\n }\n pending.set(key, { ...pending.get(key), ...values })\n writes.push({ key, values, windows: entry?.windows })\n }\n // The server was asked for these ids by name and answered without them.\n // Whether the entity never existed, is gone, or is not this principal's to\n // see, the client knows the same thing: it is not there. Without this the read\n // would stay `Loading` for good. A forced plan (`refresh`) asks again, and any\n // later write clears the tombstone.\n //\n // Only ids asked for directly: the target of a returned ref is left alone. A\n // server need not expand a relation that rides on a request; the planner\n // follows a relation the store holds and asks for its targets by id next, and\n // a tombstone here would stop it.\n let answered = store\n for (const request of requests) {\n const key = entityKey(request.entity, request.id)\n if (!returned.has(key)) answered = tombstone(answered, key)\n }\n return writeEntities(answered, writes, now)\n}\n","/**\n * Request policies: how a read treats fields the store already holds. A policy\n * compiles to planner options; it is not a second cache. `Remote.observe` and\n * `Remote.prefetch` take one, and the planner itself stays pure and\n * time-injected.\n */\nimport type { PlanOptions } from './plan.js'\n\nexport type RemotePolicy =\n /** Fetch only fields the store lacks (missing, stale, or re-windowed). */\n | { readonly _tag: 'CacheFirst' }\n /**\n * Keep present values visible, read them as `Refreshing`, and refetch an\n * entry older than `maxAge` milliseconds.\n */\n | { readonly _tag: 'StaleWhileRevalidate'; readonly maxAge: number }\n /** Fetch every selected field regardless of coverage; cached values stay visible meanwhile. */\n | { readonly _tag: 'NetworkOnly' }\n\nexport const RemotePolicy = {\n /** Fetch only what the store lacks. */\n cacheFirst: { _tag: 'CacheFirst' } as const satisfies RemotePolicy,\n\n /** Keep present values visible, read as `Refreshing`, and refetch an entry older than `maxAge` ms. */\n staleWhileRevalidate: (options: { readonly maxAge: number }): RemotePolicy => ({\n _tag: 'StaleWhileRevalidate',\n maxAge: options.maxAge,\n }),\n\n /** Fetch every selected field regardless of coverage; cached values stay visible meanwhile. */\n networkOnly: { _tag: 'NetworkOnly' } as const satisfies RemotePolicy,\n\n /** The planner options a policy compiles to at `now`. */\n toPlan: (policy: RemotePolicy, now: number): PlanOptions => {\n switch (policy._tag) {\n case 'CacheFirst':\n return {}\n case 'StaleWhileRevalidate':\n return { freshness: { now, freshness: policy.maxAge } }\n case 'NetworkOnly':\n return { force: true }\n }\n },\n\n /**\n * Whether a read under this policy may refetch fields the store already\n * holds, so an observer marks them stale (read as `Refreshing`) while the\n * request is pending.\n */\n refreshes: (policy: RemotePolicy): boolean => policy._tag !== 'CacheFirst',\n}\n","/**\n * `foldkit-remote` — normalized application-facing server state.\n *\n * The pure core (entities, selections, the store, the planner, connections,\n * live classification, optimistic layers) performs no I/O. The `Remote.*`\n * helpers that read or mutate go through the `RemoteClient` Effect service.\n */\nimport { Effect, Layer, Option, Result, Schema, Stream } from 'effect'\nimport { Entity as DomainEntity, SelectionTypeId } from 'foldkit-entity'\nimport type * as Domain from 'foldkit-entity'\nimport type { Duration } from 'effect'\nimport type { Command } from 'foldkit/command'\nimport * as Subscription from 'foldkit/subscription'\nimport type { EntryWithoutKeepAlive } from 'foldkit/subscription'\nimport {\n type ActiveSurface,\n type Contract,\n type Invalid,\n type ModelRef,\n type Projection,\n type Surface,\n type Wiring,\n} from 'foldkit-surface'\nimport {\n RemoteClient,\n coalescedLayer,\n liveEventOf,\n mutateRemote,\n remoteError,\n type RemoteRpcClient,\n} from './client.js'\nimport { emptyConnection, hasNext, hasPrevious, type Edge } from './connection.js'\nimport { Entity, type EntityDescriptor } from './entity.js'\nimport { inspectEntity, inspectRemote, type RemoteInspection } from './inspect.js'\nimport type { LiveCursor } from './live.js'\nimport {\n initialRemoteModel,\n isLoading,\n isRemoteMessage,\n remoteMessageCases,\n remoteMessageSchema,\n remoteModelSchema,\n retentionRootsSchema,\n updateRemote,\n writeRead,\n type RemoteMessage,\n type RemoteMessageInput,\n type RemoteModel,\n} from './model.js'\nimport { mutationStatus, type MutationDescriptor, type MutationStatus } from './mutation.js'\nimport {\n connectionIdentity,\n visibleItems,\n visibleStore,\n type ConnectionIdentity,\n type OptimisticState,\n type OptimisticOperation,\n} from './optimistic.js'\nimport { plan, type PlanOptions } from './plan.js'\nimport { RemotePolicy } from './policy.js'\nimport { stableStringify } from './query.js'\nimport type { ConnectionSpec, QueryDescriptor, QueryRef, QueryWindow } from './query.js'\nimport { remoteDataSchema, type RemoteData } from './remoteData.js'\nimport type { ConnectionRoot, RetentionRoots } from './retain.js'\nimport { Selection, assemble, pageSchema, relationOf, type Page } from './selection.js'\nimport { entityKey, isTombstone, type EntityStore } from './store.js'\nimport {\n QueryRequest,\n QueryResult,\n ReadRequest,\n RelationRequest,\n REMOTE_PROTOCOL_VERSION,\n WindowSchema,\n RemoteLiveError,\n RemoteProtocolError,\n RemoteQueryError,\n RemoteReadError,\n RemoteRpc,\n} from './wire.js'\nimport type { CoalesceOptions } from './coalesce.js'\nimport {\n Requirement,\n RemoteConnections,\n RemoteRequirements,\n connectionsOf,\n requirementsOf,\n type ConnectionRequirement,\n type RelationRequirement,\n} from './requirement.js'\n\nexport * from './client.js'\nexport * from './coalesce.js'\nexport * from './connection.js'\nexport * from './entity.js'\nexport * from './inspect.js'\nexport * from './live.js'\nexport * from './model.js'\nexport * from './mutation.js'\nexport * from './optimistic.js'\nexport * from './persistence.js'\nexport * from './plan.js'\nexport * from './policy.js'\nexport * from './query.js'\nexport * from './relation.js'\nexport * from './remoteData.js'\nexport * from './requirement.js'\nexport * from './retain.js'\nexport * from './selection.js'\nexport * from './store.js'\nexport * from './wire.js'\n\n/** What a domain registers: a Remote descriptor, or a `foldkit-entity` Entity (read through `Entity.from`). */\nexport type EntityLike = EntityDescriptor<any, any> | Domain.AnyEntity\n\n/**\n * What a read selects: a Remote Selection, or a `foldkit-entity` Selection\n * (read through `Selection.from`).\n */\nexport type EntitySelection<Value, Name extends string> =\n | Selection<Value, Name, 'entity'>\n | Domain.Selection<Name, unknown, Schema.Constraint & { readonly Type: Value }>\n\nconst descriptorOf = (entity: EntityLike): EntityDescriptor<any, any> =>\n DomainEntity.is(entity) ? Entity.from(entity as never) : entity\n\nconst selectionOf = <Value, Name extends string>(\n selection: EntitySelection<Value, Name>,\n): Selection<Value, Name, 'entity'> =>\n SelectionTypeId in selection ? (Selection.from(selection) as never) : selection\n\ntype EntityName<D> = D extends { readonly name: infer Name extends string } ? Name : never\ntype QueryName<D> = D extends QueryDescriptor<infer Name, any, any> ? Name : never\ntype MutationName<D> = D extends MutationDescriptor<infer Name, any, any> ? Name : never\n\n/**\n * Nothing when `Name` is one of the domain's registered `Names`; otherwise a\n * branded failure naming the descriptor, so `Data.get(Team.select(…))` for an\n * unregistered `Team` errors at the selection in one line.\n */\nexport type Registered<Name extends string, Names extends string, Kind extends string> = [\n Name,\n] extends [Names]\n ? unknown\n : Invalid<`${Kind} \"${Name}\" is not registered with this Remote domain`>\n\n/** Nothing when a selection is of the query's entity; otherwise a branded failure naming both. */\nexport type SelectsEntity<Entity extends string, Of extends string> = [Entity] extends [Of]\n ? unknown\n : Invalid<`the selection is of \"${Entity}\", but the query lists \"${Of}\"`>\n\nexport interface RemoteDescriptor<\n Entities extends readonly EntityLike[] = readonly EntityLike[],\n Queries extends readonly QueryDescriptor<any, any, any>[] = readonly QueryDescriptor<\n any,\n any,\n any\n >[],\n Mutations extends readonly MutationDescriptor<any, any, any>[] = readonly MutationDescriptor<\n any,\n any,\n any\n >[],\n> {\n readonly entities: Entities\n readonly queries: Queries\n readonly mutations: Mutations\n readonly Model: Schema.Codec<RemoteModel, unknown>\n readonly initial: RemoteModel\n readonly Message: Schema.Schema<RemoteMessage>\n readonly update: (model: RemoteModel, message: RemoteMessage) => RemoteModel\n readonly rpc: typeof RemoteRpc\n /** Name-keyed lookups built from the declared entities, queries, and mutations. */\n readonly registry: {\n readonly entities: ReadonlyMap<string, EntityDescriptor<any, any>>\n readonly queries: ReadonlyMap<string, QueryDescriptor<any, any, any>>\n readonly mutations: ReadonlyMap<string, MutationDescriptor<any, any, any>>\n }\n}\n\ndeclare const boundRemoteNames: unique symbol\n\nexport interface BoundRemote<AppModel, Store extends RemoteModel, Names extends string = string> {\n readonly definition: RemoteDescriptor\n readonly store: ModelRef<AppModel, Store>\n /** For `Module`: owns the store's Model path. */\n readonly contract: Contract\n /** Phantom: the entity names this Remote definition registers. */\n readonly [boundRemoteNames]?: Names\n}\n\ntype MutationInput<M> = M extends MutationDescriptor<any, infer Input, any> ? Input : never\n\nexport interface DomainMutateOptions {\n /** Overrides the generated id, for a retry, a durable bridge, or a test. */\n readonly requestId?: string | undefined\n /**\n * What the request changes before the server answers, released when it\n * settles. A function receives the generated ids, so a created entity can\n * carry `tempId` until the result names the real one.\n */\n readonly optimistic?:\n | ReadonlyArray<OptimisticOperation>\n | ((ids: {\n readonly requestId: string\n readonly tempId: string\n }) => ReadonlyArray<OptimisticOperation>)\n | undefined\n}\n\n/** A Foldkit Subscription entry of the Remote domain, emitting its Messages through `RemoteClient`. */\nexport type RemoteEntry<AppModel, Dependencies> = EntryWithoutKeepAlive<\n AppModel,\n RemoteMessage,\n Dependencies,\n RemoteClient\n>\n\n/**\n * The entries `RemoteDomain.subscriptions` returns for an active record: a read\n * and a live entry per key (the live one idles when nothing is read live), and\n * `retain`.\n */\nexport type SubscriptionEntries<AppModel, Active> = {\n // `Object.entries` turns a numeric key into a string, so numeric keys have entries too.\n readonly [K in keyof Active & (string | number) as `${K}.read` | `${K}.live`]: RemoteEntry<\n AppModel,\n any\n >\n} & { readonly retain: RemoteEntry<AppModel, any> }\n\nexport interface SubscriptionsOptions extends ObserveOptions, LiveOptions, RetainOptions {}\n\n/** A Remote domain's wiring for an assembly: it routes Remote's Messages into `reduce`, brings its Subscriptions and contract, and requires `RemoteClient` from the runtime's resources Layer. */\nexport type RemoteWiring<AppModel> = Wiring<\n AppModel,\n RemoteMessage | RemoteMessageInput,\n RemoteClient\n>\n\n/** What `RemoteDomain.mutate` hands `update`: the Model with the request started, and the Command that settles it. */\nexport interface MutationStarted<AppModel> {\n readonly model: AppModel\n readonly requestId: string\n readonly tempId: string\n /** Yields `MutationSucceeded` or `MutationFailed`; never fails. */\n readonly command: Command<RemoteMessage, never, RemoteClient>\n}\n\n/**\n * A Remote domain bound to its place in the application Model: the descriptor\n * (`Remote.define`), the binding (`Remote.at`), and the application-facing\n * operations over them. Every method compiles to the `Remote.*` function of the\n * same name, which stays exported for tooling, SSR, and tests.\n */\nexport interface RemoteDomain<\n AppModel,\n Store extends RemoteModel,\n Entities extends readonly EntityLike[],\n Queries extends readonly QueryDescriptor<any, any, any>[],\n Mutations extends readonly MutationDescriptor<any, any, any>[],\n>\n extends\n BoundRemote<AppModel, Store, EntityName<Entities[number]>>,\n RemoteDescriptor<Entities, Queries, Mutations> {\n /** `Remote.select`: a Projection reading one entity through a selection of a registered entity. */\n get<Value, Name extends string>(\n selection: EntitySelection<Value, Name> &\n Registered<Name, EntityName<Entities[number]>, 'Entity'>,\n id: string,\n ): Projection<AppModel, RemoteData<Value>>\n /**\n * `get`, and the projection also subscribes to the entity's changes: its\n * requirements are marked `live`, so `subscriptions` derives a live entry for\n * the Surfaces that read it.\n */\n live<Value, Name extends string>(\n selection: EntitySelection<Value, Name> &\n Registered<Name, EntityName<Entities[number]>, 'Entity'>,\n id: string,\n ): Projection<AppModel, RemoteData<Value>>\n /**\n * A query connection read as a `Page` of items selected of the query's\n * entity: `Initial` until the page and every item's selected fields are\n * present, `Refreshing` while any of them is being refetched. The window is\n * the page first asked for; the pages `next`, `previous` and `fetch` merge\n * onto the connection read through the same projection.\n */\n query<Q extends QueryDescriptor<any, any, any>, Value, Entity extends string>(\n query: Q & Registered<Q['name'], QueryName<Queries[number]>, 'Query'>,\n input: QueryInput<Q>,\n options: QueryOptions<Value, Entity, QueryEntity<Q>>,\n ): QueryProjection<AppModel, Value, Q['name'], QueryInput<Q>>\n /** The `QueryRef` for the page after the loaded end (same page size), or `undefined` when there is none or its cursor is unknown. */\n next<Name extends string, Input>(\n model: AppModel,\n projection: QueryProjection<AppModel, any, Name, Input>,\n ): QueryRef<Name, Input> | undefined\n /** The `QueryRef` for the page before the loaded start, or `undefined`. */\n previous<Name extends string, Input>(\n model: AppModel,\n projection: QueryProjection<AppModel, any, Name, Input>,\n ): QueryRef<Name, Input> | undefined\n /** A Command that runs the query and yields the `ConnectionMerged` (or `QueryFailed`) that reduces it: \"load more\". */\n fetch(ref: QueryRef<string, unknown>): Command<RemoteMessage, never, RemoteClient>\n /** `Remote.refresh`: marks what a projection or a Surface requires as due, for its read entry to refetch. */\n refresh(\n model: AppModel,\n target: Projection<AppModel, unknown> | Surface<AppModel, any, any, void>,\n ): AppModel\n /**\n * The Foldkit Subscription entries for the active Surfaces, keyed for\n * `Subscription.make`: a read entry per Surface (`Remote.observe`), a live\n * entry per Surface that reads through `live` (`Remote.live`), and one\n * retain entry with every active Surface as a root (`Remote.retain`). A\n * Surface's params are a function of the Model (`Surface.at`), so what is\n * fetched, subscribed, and retained follows the Model.\n */\n subscriptions<\n const Active extends Readonly<\n Record<string, ActiveSurface<AppModel> | Surface<AppModel, any, any, void>>\n >,\n >(\n active: Active,\n options?: SubscriptionsOptions,\n ): SubscriptionEntries<AppModel, Active>\n /** `Remote.plan`: the requirements the store does not satisfy. */\n plan<Value>(\n model: AppModel,\n projection: Projection<AppModel, Value>,\n options?: PlanOptions,\n ): ReadonlyArray<Requirement>\n /** `Remote.storeOf`: the visible store, base under the pending optimistic layers. */\n storeOf(model: AppModel): EntityStore\n /**\n * The plan run through `RemoteClient` and reduced into the Model: the\n * projection's pending queries first, then the fields it lacks (the pages'\n * items included). For SSR, route or hover prefetch, and tests.\n */\n prefetch<Value>(\n model: AppModel,\n projection: Projection<AppModel, Value>,\n options?: ObserveOptions,\n ): Effect.Effect<AppModel, RemoteReadError | RemoteProtocolError | RemoteQueryError, RemoteClient>\n /**\n * Starts a registered mutation from `update`: applies `MutationStarted` (with\n * the optimistic operations) to the Model and returns the Command that runs\n * it and yields the settling Message. The request id comes from the model's\n * mutation sequence unless `options.requestId` is given.\n */\n mutate<M extends MutationDescriptor<any, any, any>>(\n model: AppModel,\n mutation: M & Registered<M['name'], MutationName<Mutations[number]>, 'Mutation'>,\n input: MutationInput<M>,\n options?: DomainMutateOptions,\n ): MutationStarted<AppModel>\n /**\n * What Remote knows of a mutation `mutate` started, by its request id:\n * pending, applied, or failed with the error the server or transport gave.\n */\n mutation(model: AppModel, requestId: string): MutationStatus\n /** `updateRemote` on the bound slice: reduces one of Remote's Messages, as `RemoteMessage` or as the application's union constructs it. */\n reduce(model: AppModel, message: RemoteMessage | RemoteMessageInput): AppModel\n /**\n * How this domain joins an assembly: it routes Remote's Messages into\n * `reduce`, brings its Subscriptions and contract, and requires\n * `RemoteClient` from the runtime's resources Layer. One assembly holds at\n * most one Remote wiring: every domain claims the same tags, and routing\n * takes the first claimant.\n */\n wiring: <\n const Active extends Readonly<\n Record<string, ActiveSurface<AppModel> | Surface<AppModel, any, any, void>>\n >,\n >(\n active: Active,\n options?: SubscriptionsOptions,\n ) => RemoteWiring<AppModel>\n /** `Remote.inspect` of the bound slice. */\n inspect(model: AppModel): RemoteInspection\n}\n\n/** A projection's connection requirement with the `QueryRef` that runs it. */\nexport interface QueryRequirement extends ConnectionRequirement {\n readonly ref: QueryRef<string, unknown>\n}\n\n/** A page forward (`first`, `after`) or back (`last`, `before`); mixing the two is a type error. */\nexport type QueryWindowOptions =\n | {\n readonly first?: number | undefined\n readonly after?: string | undefined\n readonly last?: undefined\n readonly before?: undefined\n }\n | {\n readonly last: number\n readonly before?: string | undefined\n readonly first?: undefined\n readonly after?: undefined\n }\n\nexport type QueryOptions<Value, Entity extends string, Of extends string = Entity> = {\n /** What to read of each item: a selection of the query's entity (`Of`). */\n readonly select: EntitySelection<Value, Entity> & SelectsEntity<Entity, Of>\n} & QueryWindowOptions\n\n/** A query connection read as a `Page` of selected items; `ref` is the connection with its first window. */\nexport interface QueryProjection<AppModel, Value, Name extends string, Input> extends Projection<\n AppModel,\n RemoteData<Page<Value>>\n> {\n readonly ref: QueryRef<Name, Input>\n}\n\n/** The input of a query descriptor. */\nexport type QueryInput<Q> = Q extends QueryDescriptor<any, infer Input, any> ? Input : never\n/** The entity a query's connection is over. */\nexport type QueryEntity<Q> =\n Q extends QueryDescriptor<any, any, ConnectionSpec<infer Entity>> ? Entity : string\n\n/**\n * The store a read or plan sees: the base with every pending optimistic layer\n * applied, so a request's patches show until it settles and a temporary id is\n * not planned as a fetch.\n */\nconst storeOf = <AppModel, Store extends RemoteModel, Names extends string>(\n bound: BoundRemote<AppModel, Store, Names>,\n model: AppModel,\n): EntityStore => {\n const remote = bound.store.get(model)\n return visibleStoreOf(remote.entities, remote.optimistic)\n}\n\n// The visible store is recomputed only when the base store or the layers\n// change, so reads and plans across renders of one Model share it.\nconst visibleStores = new WeakMap<OptimisticState, WeakMap<EntityStore, EntityStore>>()\n\nconst visibleStoreOf = (entities: EntityStore, optimistic: OptimisticState): EntityStore => {\n let byStore = visibleStores.get(optimistic)\n if (byStore === undefined) {\n byStore = new WeakMap()\n visibleStores.set(optimistic, byStore)\n }\n let visible = byStore.get(entities)\n if (visible === undefined) {\n visible = visibleStore(entities, optimistic)\n byStore.set(entities, visible)\n }\n return visible\n}\n\n// A read's result per store snapshot. `Remote.storeOf` is shared across every\n// read of one Model state, so equal reads of one render assemble and decode\n// once and return one value (a view may compare by identity). A query read\n// also depends on its connection, which changes independently of the store,\n// so it keys on that object too. Weak on both, bounded by what is read.\nconst readResults = new WeakMap<object, WeakMap<object, Map<string, unknown>>>()\n\nconst memoRead = <T>(snapshot: object, by: object, key: string, compute: () => T): T => {\n let byScope = readResults.get(snapshot)\n if (byScope === undefined) {\n byScope = new WeakMap()\n readResults.set(snapshot, byScope)\n }\n let results = byScope.get(by)\n if (results === undefined) {\n results = new Map()\n byScope.set(by, results)\n }\n if (results.has(key)) return results.get(key) as T\n const value = compute()\n results.set(key, value)\n return value\n}\n\nexport interface MutateOptions {\n /** What the request changes before the server answers; released when it settles. */\n readonly optimistic?: ReadonlyArray<OptimisticOperation> | undefined\n}\n\n/** The default `toMessage`: the application reduces `RemoteMessage` itself. */\nconst identityMessage = (message: RemoteMessage): RemoteMessage => message\n\nexport interface RetainOptions {\n /** The query connections the application shows, by `QueryRef` or identity. */\n readonly connections?: ReadonlyArray<ConnectionIdentity> | undefined\n /** How long the roots must be stable before collecting; default none. */\n readonly grace?: Duration.Input | undefined\n}\n\n/** How `Remote.observe` and `Remote.prefetch` treat fields the store already holds. */\nexport interface ObserveOptions {\n /** Default `RemotePolicy.cacheFirst`. */\n readonly policy?: RemotePolicy | undefined\n /** The clock a refreshing policy reads; default `Date.now`. */\n readonly now?: (() => number) | undefined\n}\n\nexport interface LiveOptions {\n /** The clock `LiveReceived` stamps events with; default `Date.now`. */\n readonly now?: (() => number) | undefined\n}\n\n/** A stable key for a live subscription's requirement set. */\nconst liveStreamKey = (requirements: readonly Requirement[]): string =>\n requirements\n .map(\n requirement =>\n `${entityKey(requirement.entity, requirement.id)}:${[...requirement.fields].sort().join(',')}`,\n )\n .sort()\n .join('|')\n\n/** Declares a Remote domain: its entities, queries, and mutations, plus the submodel. */\nconst defineRemote = <\n const Entities extends readonly EntityLike[],\n const Queries extends readonly QueryDescriptor<any, any, any>[] = readonly QueryDescriptor<\n any,\n any,\n any\n >[],\n const Mutations extends readonly MutationDescriptor<any, any, any>[] =\n readonly MutationDescriptor<any, any, any>[],\n>(config: {\n readonly entities: Entities\n readonly queries?: Queries\n readonly mutations?: Mutations\n}): RemoteDescriptor<Entities, Queries, Mutations> => {\n const entities = config.entities.map(descriptorOf)\n return {\n entities: entities as unknown as Entities,\n queries: (config.queries ?? []) as unknown as Queries,\n mutations: (config.mutations ?? []) as unknown as Mutations,\n Model: remoteModelSchema(),\n initial: initialRemoteModel,\n Message: remoteMessageSchema,\n update: updateRemote,\n rpc: RemoteRpc,\n registry: {\n entities: new Map(entities.map(entity => [entity.name, entity])),\n queries: new Map((config.queries ?? []).map(query => [query.name, query])),\n mutations: new Map((config.mutations ?? []).map(mutation => [mutation.name, mutation])),\n },\n }\n}\n\n/** Binds a Remote domain to its store's location in the application Model. */\nconst bindRemote = <\n AppModel,\n Store extends RemoteModel,\n Entities extends readonly EntityLike[],\n Queries extends readonly QueryDescriptor<any, any, any>[],\n Mutations extends readonly MutationDescriptor<any, any, any>[],\n>(\n definition: RemoteDescriptor<Entities, Queries, Mutations>,\n store: ModelRef<AppModel, Store>,\n): BoundRemote<AppModel, Store, EntityName<Entities[number]>> => ({\n definition,\n store,\n contract: {\n kind: 'remote',\n name: store.dependency.join('.') || 'remote',\n // A generated field reference knows its application and its path; a raw\n // optic (`ModelRef.fromOptic`) knows neither, so it claims nothing.\n owner: (store as { readonly owner?: object }).owner,\n owns: store.dependency.length === 0 ? [] : [store.dependency],\n observes: store.dependency.length === 0 ? [] : [store.dependency],\n messages: [],\n metadata: [],\n },\n})\n\n/** The runtime half of `Registered`: a descriptor the domain never declared is an error naming both. */\nconst assertRegistered = (\n bound: BoundRemote<any, any>,\n kind: 'Entity' | 'Query' | 'Mutation',\n registered: ReadonlyMap<string, unknown>,\n name: string,\n): void => {\n if (!registered.has(name)) {\n throw new Error(\n `Remote: ${kind} \"${name}\" is not registered with domain \"${bound.contract.name}\"`,\n )\n }\n}\n\n/** What a projection asks of the remote: entity requirements and query connections. */\ninterface Asked {\n readonly requirements: ReadonlyArray<Requirement>\n readonly connections: ReadonlyArray<ConnectionRequirement>\n}\n\nconst nothingAsked: Asked = { requirements: [], connections: [] }\n\nconst askedOf = (projection: Projection<any, unknown> | undefined): Asked =>\n projection === undefined\n ? nothingAsked\n : { requirements: requirementsOf(projection), connections: connectionsOf(projection) }\n\n/** The plan for what a projection asks: the entity fields to read, and the queries to run. */\ninterface Planned {\n readonly requirements: ReadonlyArray<Requirement>\n readonly queries: ReadonlyArray<QueryRequirement>\n}\n\n/**\n * Plans what a projection asks against the Model. A connection the Model holds\n * fresh contributes its visible items' selected fields to the entity plan; one\n * it does not hold, or holds stale, is a query to run (its items are planned\n * once the page arrives).\n */\nconst planAsked = (remote: RemoteModel, asked: Asked, options: PlanOptions): Planned => {\n const queries: QueryRequirement[] = []\n const items: Requirement[] = []\n const connections = Requirement.mergeConnections(\n asked.connections,\n ) as ReadonlyArray<QueryRequirement>\n for (const connection of connections) {\n const known = remote.connections[connection.identity]\n if (known === undefined || known.stale || options.force === true) {\n queries.push(connection)\n continue\n }\n const edges = visibleItems(\n known,\n connection.identity,\n remote.optimistic.overlays,\n remote.entities,\n )\n items.push(\n ...itemsOf(\n edges.map(edge => edge.ref),\n connection.select,\n ),\n )\n }\n return {\n requirements: plan(\n visibleStoreOf(remote.entities, remote.optimistic),\n [...asked.requirements, ...items],\n options,\n ),\n queries,\n }\n}\n\n/** The entity requirements a page's edges add under a selection. */\nconst itemsOf = (\n edges: ReadonlyArray<{ readonly entity: string; readonly id: string }>,\n select: RelationRequirement,\n): ReadonlyArray<Requirement> =>\n edges.filter(edge => edge.entity === select.entity).map(edge => ({ ...select, id: edge.id }))\n\n/**\n * The wire request of a planned query; a `QueryRef` identity carries the query\n * name and the canonical encoded input. A connection requirement built by hand\n * with another identity cannot be run, and fails as a query would.\n */\nconst queryRequestOf = (query: {\n readonly identity: string\n readonly window: QueryWindow\n}): Effect.Effect<Schema.Schema.Type<typeof QueryRequest>, RemoteQueryError> => {\n const separator = query.identity.indexOf('\\u0000')\n if (separator < 0) {\n return Effect.fail(\n new RemoteQueryError({\n message: `connection \"${query.identity}\" is not a query's: only a QueryRef identity can be run`,\n }),\n )\n }\n return Effect.try({\n try: () => ({\n query: query.identity.slice(0, separator),\n input: JSON.parse(query.identity.slice(separator + 1)) as unknown,\n window: query.window,\n }),\n catch: () =>\n new RemoteQueryError({ message: `connection \"${query.identity}\" carries no encoded input` }),\n })\n}\n\n/**\n * The `ConnectionMerged` for a query result, in the client's edge shape.\n * `refreshes` marks the page as answering the connection's refresh, so one\n * Message both merges it and clears `stale`.\n */\nconst pageMessage = (\n connection: string,\n result: Schema.Schema.Type<typeof QueryResult>,\n refreshes = false,\n): RemoteMessage => ({\n _tag: 'ConnectionMerged',\n connection,\n page: {\n edges: result.edges.map(edge => ({ key: edge.key, ref: { entity: edge.entity, id: edge.id } })),\n start: result.start,\n end: result.end,\n },\n ...(refreshes ? { refreshes } : {}),\n})\n\n/**\n * The retention roots of some projections: their requirements, their\n * connections (each with the union of what the projections select of its\n * items), and the connections listed by identity alone.\n */\nconst rootsOf = (\n projections: ReadonlyArray<Projection<any, unknown>>,\n options: RetainOptions,\n): RetentionRoots => {\n const connections = new Map<string, ConnectionRoot>()\n for (const identity of (options.connections ?? []).map(connectionIdentity)) {\n connections.set(identity, { identity })\n }\n for (const { identity, select } of projections.flatMap(connectionsOf)) {\n const current = connections.get(identity)?.select\n connections.set(identity, {\n identity,\n select: current === undefined ? select : Requirement.mergeRelation(current, select),\n })\n }\n return {\n requirements: Requirement.merge(projections.flatMap(requirementsOf)),\n connections: [...connections.values()].sort((a, b) => (a.identity < b.identity ? -1 : 1)),\n }\n}\n\n/** Reads requirements and reports the Message that settles them. Never fails. */\nconst readMessage = (\n requirements: ReadonlyArray<Requirement>,\n now: () => number,\n): Effect.Effect<RemoteMessage, never, RemoteClient> =>\n Effect.gen(function* () {\n const client = yield* RemoteClient\n const at = now()\n const result = yield* Effect.result(\n client.read({ version: REMOTE_PROTOCOL_VERSION, requests: requirements }),\n )\n return Result.isFailure(result)\n ? { _tag: 'ReadFailed', requests: requirements, error: remoteError(result.failure) }\n : { _tag: 'ReadReceived', requests: requirements, result: result.success, now: at }\n })\n\n/** Runs a query and reports the page that refreshes its connection, or the failure. Never fails. */\nconst queryMessage = (query: {\n readonly identity: string\n readonly window: QueryWindow\n}): Effect.Effect<RemoteMessage, never, RemoteClient> =>\n Effect.gen(function* () {\n const client = yield* RemoteClient\n const result = yield* Effect.result(\n queryRequestOf(query).pipe(Effect.flatMap(request => client.query(request))),\n )\n return Result.isFailure(result)\n ? { _tag: 'QueryFailed', connection: query.identity, error: remoteError(result.failure) }\n : pageMessage(query.identity, result.success, true)\n })\n\n/** A query the read entry runs, as its dependencies carry it: plain data Foldkit compares. */\nconst PlannedQuery = Schema.Struct({\n identity: Schema.String,\n window: WindowSchema,\n select: RelationRequest,\n})\n\n/** The dependencies of the read entry: the entity fields to read and the queries to run. */\nexport interface ReadDependencies {\n readonly requirements: ReadonlyArray<Requirement>\n readonly queries: ReadonlyArray<Schema.Schema.Type<typeof PlannedQuery>>\n /** The Model's requested refresh generation: a refresh restarts the entry. */\n readonly refresh: number\n}\n\n/**\n * The read entry: plans what `askedOf(model)` asks against the Model and runs\n * the entity read and the queries concurrently. Each Message it emits changes\n * the Model, so Foldkit recomputes the dependencies and restarts the stream\n * (`switchMap`): a merged page's items are planned by that next computation,\n * against the store as it then is, rather than read here unplanned. Nothing\n * the entry needs is spread over two Messages, since the second could be lost\n * to the restart; a page and its refresh are one `ConnectionMerged`.\n */\nconst observeEntry = <AppModel, Store extends RemoteModel, Message>(\n bound: BoundRemote<AppModel, Store>,\n askedOf: (model: AppModel) => Asked,\n toMessage: (message: RemoteMessage) => Message,\n options: ObserveOptions,\n): EntryWithoutKeepAlive<AppModel, Message, ReadDependencies, RemoteClient> => {\n const { policy = RemotePolicy.cacheFirst, now = Date.now } = options\n const read = (requirements: ReadonlyArray<Requirement>) =>\n Effect.map(readMessage(requirements, now), toMessage)\n const run = (query: ReadDependencies['queries'][number]) =>\n Effect.map(queryMessage(query), toMessage)\n return {\n dependenciesSchema: Schema.Struct({\n requirements: Schema.Array(ReadRequest),\n queries: Schema.Array(PlannedQuery),\n refresh: Schema.Number,\n }),\n modelToDependencies: model => {\n const remote = bound.store.get(model)\n const planned = planAsked(remote, askedOf(model), RemotePolicy.toPlan(policy, now()))\n return {\n refresh: remote.refresh.requested,\n requirements: planned.requirements,\n queries: planned.queries.map(({ identity, window, select }) => ({\n identity,\n window,\n select,\n })),\n }\n },\n dependenciesToStream: ({ requirements, queries, refresh }) =>\n Stream.concat(\n requirements.length === 0\n ? Stream.empty\n : Stream.fromIterable([\n // Absent fields read as `Loading` until the read lands.\n toMessage({ _tag: 'ReadStarted', requests: requirements, refresh }),\n // A refreshing policy also marks the present ones stale.\n ...(RemotePolicy.refreshes(policy)\n ? [toMessage({ _tag: 'RefreshStarted', requests: requirements })]\n : []),\n ]),\n Stream.mergeAll(\n [\n ...(requirements.length === 0 ? [] : [Stream.fromEffect(read(requirements))]),\n ...queries.map(query => Stream.fromEffect(run(query))),\n ],\n { concurrency: 'unbounded' },\n ),\n ),\n }\n}\n\n/** The live entry: subscribes to `requirementsOf(model)` from the Model's resume cursor. */\nconst liveEntry = <AppModel, Store extends RemoteModel, Message>(\n bound: BoundRemote<AppModel, Store>,\n requirementsOf: (model: AppModel) => ReadonlyArray<Requirement>,\n toMessage: (message: RemoteMessage) => Message,\n options: LiveOptions,\n): EntryWithoutKeepAlive<\n AppModel,\n Message,\n { readonly requirements: ReadonlyArray<Requirement>; readonly cursor: LiveCursor },\n RemoteClient\n> => ({\n dependenciesSchema: Schema.Struct({\n requirements: Schema.Array(ReadRequest),\n cursor: Schema.Number,\n }),\n modelToDependencies: model => {\n const requirements = requirementsOf(model)\n const stream = liveStreamKey(requirements)\n return {\n requirements,\n cursor: bound.store.get(model).live[stream]?.cursor ?? 0,\n }\n },\n dependenciesToStream: ({ requirements, cursor }) =>\n requirements.length === 0\n ? Stream.empty\n : Stream.unwrap(\n Effect.gen(function* () {\n const client = yield* RemoteClient\n return client.live({ requirements, after: cursor })\n }),\n ).pipe(\n Stream.map(event =>\n toMessage({\n _tag: 'LiveReceived',\n stream: liveStreamKey(requirements),\n event,\n now: (options.now ?? Date.now)(),\n }),\n ),\n Stream.catchIf(\n (_error): _error is RemoteLiveError | RemoteProtocolError => true,\n error =>\n Stream.succeed(\n toMessage({\n _tag: 'ReadFailed',\n requests: requirements,\n error: remoteError(error),\n }),\n ),\n ),\n ),\n})\n\n/** The projection an active Surface has for this Model, if it is active. */\nconst projectionOf = <AppModel>(\n entry: ActiveSurface<AppModel> | Surface<AppModel, any, any, void>,\n model: AppModel,\n): Projection<AppModel, unknown> | undefined =>\n 'projectionOf' in entry ? entry.projectionOf(model) : entry.projection()\n\n/**\n * `projectionOf` computed once per Model: the read, live, and retain entries\n * all derive their dependencies from the same projection on the same Model\n * change, and a Surface's `model` callback (which lifts and builds schemas)\n * need not run three times for it. Models are objects, so the memo is weak.\n */\nconst memoizedProjectionOf = <AppModel>(\n entry: ActiveSurface<AppModel> | Surface<AppModel, any, any, void>,\n): ((model: AppModel) => Projection<AppModel, unknown> | undefined) => {\n const cache = new WeakMap<object, Projection<AppModel, unknown> | undefined>()\n return model => {\n const key: unknown = model\n if (typeof key !== 'object' || key === null) return projectionOf(entry, model)\n if (cache.has(key)) return cache.get(key)\n const projection = projectionOf(entry, model)\n cache.set(key, projection)\n return projection\n }\n}\n\nexport const Remote = {\n /** The submodel's schema, the same for every domain; embed it in the application Model. */\n Model: remoteModelSchema(),\n /** The submodel's initial value. */\n initial: initialRemoteModel,\n /**\n * Remote's Message cases for `defineMessageUnion`: spread them into the\n * application's union, and reduce the ones `Remote.reduces` recognizes with\n * `RemoteDomain.reduce`.\n */\n messages: remoteMessageCases,\n /** Whether a Message is one of Remote's, by tag. */\n reduces: isRemoteMessage,\n\n /**\n * Declares a Remote domain and binds it to its place in the application Model\n * in one step; the result carries the application-facing operations. The\n * descriptor alone is `Remote.define`, the binding alone `Remote.at`.\n */\n make: <\n AppModel,\n Store extends RemoteModel,\n const Entities extends readonly EntityLike[],\n const Queries extends readonly QueryDescriptor<any, any, any>[] = readonly [],\n const Mutations extends readonly MutationDescriptor<any, any, any>[] = readonly [],\n >(config: {\n readonly model: ModelRef<AppModel, Store>\n readonly entities: Entities\n readonly queries?: Queries\n readonly mutations?: Mutations\n }): RemoteDomain<AppModel, Store, Entities, Queries, Mutations> =>\n bindDomain(defineRemote(config), config.model),\n\n /**\n * Declares a Remote domain without binding it: its entities, queries, and\n * mutations, plus the submodel. For a domain reused across applications or\n * bound in a test; `Remote.make` is the one-step form.\n */\n define: defineRemote,\n\n /**\n * Binds a Remote domain to its store's location in the application Model. The\n * registered entity names are carried on the returned value, so `Remote.select`\n * rejects a selection for an entity this domain never declared.\n */\n at: bindRemote,\n\n /**\n * A Projection node that reads a `RemoteData` value out of the store. The id\n * is supplied by the caller, usually from a Surface's params. The assembled\n * value is decoded against the Selection, so malformed server data surfaces\n * as `Failed` instead of being asserted into `Value`. A present value with a\n * stale field reads as `Refreshing`: an observer is refetching it.\n */\n select: <AppModel, Store extends RemoteModel, Names extends string, Value, Name extends string>(\n bound: BoundRemote<AppModel, Store, Names>,\n given: EntitySelection<Value, Name> & Registered<Name, Names, 'Entity'>,\n ) => {\n const selection = selectionOf<Value, Name>(given)\n assertRegistered(bound, 'Entity', bound.definition.registry.entities, selection.entity)\n const relation = relationOf(selection)\n return (id: string): Projection<AppModel, RemoteData<Value>> => ({\n Model: remoteDataSchema(selection.schema),\n dependencies: [],\n metadata: RemoteRequirements.of({ ...relation, id }),\n read: (root: AppModel): RemoteData<Value> => {\n const store = storeOf(bound, root)\n const key = entityKey(selection.entity, id)\n // The store-dependent half is memoized per store snapshot; `undefined`\n // means the store lacks the value. Whether that reads as `Loading` or\n // `Initial` depends on the in-flight marks, which change independently\n // of the store, so it is decided outside the memo.\n const present = memoRead<RemoteData<Value> | undefined>(\n store,\n store,\n `${key}\\u0000${stableStringify(relation)}`,\n () => {\n if (isTombstone(store, key)) return { _tag: 'NotFound' }\n const assembled = assemble(store, key, relation)\n if (assembled === undefined) return undefined\n const decoded = Schema.decodeUnknownResult(selection.schema)(assembled.values)\n return Result.isFailure(decoded)\n ? { _tag: 'Failed', error: { _tag: 'DecodeError', message: decoded.failure.message } }\n : assembled.refreshing\n ? { _tag: 'Refreshing', value: decoded.success }\n : { _tag: 'Ready', value: decoded.success }\n },\n )\n if (present !== undefined) return present\n // Nothing is fetching this: usually a projection no active Surface\n // observes, rather than a slow network.\n return isLoading(bound.store.get(root), selection.entity, id, relation.fields)\n ? { _tag: 'Loading' }\n : { _tag: 'Initial' }\n },\n })\n },\n\n /**\n * The pure plan for a projection against a Model: the requirements its\n * remote store does not satisfy, under `options` (freshness, force). A\n * Surface's projection is `surface.projection(params)`.\n */\n plan: <AppModel, Store extends RemoteModel, Value>(\n bound: BoundRemote<AppModel, Store>,\n model: AppModel,\n projection: Projection<AppModel, Value>,\n options?: PlanOptions,\n ): ReadonlyArray<Requirement> =>\n planAsked(bound.store.get(model), askedOf(projection), options ?? {}).requirements,\n\n /**\n * The queries a projection needs run before its connections read: those the\n * Model does not hold, or holds stale (every one under `force`).\n */\n planQueries: <AppModel, Store extends RemoteModel, Value>(\n bound: BoundRemote<AppModel, Store>,\n model: AppModel,\n projection: Projection<AppModel, Value>,\n options?: PlanOptions,\n ): ReadonlyArray<QueryRef<string, unknown>> =>\n planAsked(bound.store.get(model), askedOf(projection), options ?? {}).queries.flatMap(query =>\n query.ref === undefined ? [] : [query.ref],\n ),\n\n /**\n * The store reads see: the base store under the pending optimistic layers.\n * One store is shared by every read and plan of a Model whose remote state\n * has not changed.\n */\n storeOf: <AppModel, Store extends RemoteModel>(\n bound: BoundRemote<AppModel, Store>,\n model: AppModel,\n ): EntityStore => storeOf(bound, model),\n\n /**\n * Executes the plan against the `RemoteClient` and returns a new store. Used\n * for SSR route prefetch, hover prefetch, and tests. Never called during render.\n * `policy` decides what a present field means (default cache-first); `now`\n * is the clock it reads, so the planner itself stays pure and time-injected.\n */\n prefetch: Effect.fn('Remote.prefetch')(function* <AppModel, Store extends RemoteModel, Value>(\n bound: BoundRemote<AppModel, Store>,\n model: AppModel,\n projection: Projection<AppModel, Value>,\n options: ObserveOptions = {},\n ) {\n const store = storeOf(bound, model)\n const { policy = RemotePolicy.cacheFirst, now = Date.now } = options\n const at = now()\n const missing = plan(store, requirementsOf(projection), RemotePolicy.toPlan(policy, at))\n if (missing.length === 0) return store\n yield* Effect.annotateCurrentSpan('requirementCount', missing.length)\n const client = yield* RemoteClient\n const result = yield* client.read({ version: REMOTE_PROTOCOL_VERSION, requests: missing })\n return writeRead(store, missing, result, at)\n }),\n\n /**\n * Marks what a projection, or a Surface without params, requires as due again.\n * Called from `update`: every selected field the store holds reads `Refreshing`,\n * and every loaded query connection is invalidated. Nothing is fetched here.\n * The read entries `Data.subscriptions` derives refetch it, because a stale\n * field or connection is planned again under every policy, so a refresh never\n * sends a request beside the entry already observing the same data.\n *\n * A refreshed connection's page replaces its pages, so items the server removed\n * or reordered follow it; pages loaded past the first are dropped and paged\n * again with `next`/`previous`. The read entries restart, so a read or query\n * sent before the refresh is not applied after it.\n *\n * The projection must be observed, which it is while it is on screen. Live\n * subscriptions are left as they are. For data nothing observes (SSR, tests),\n * use `Remote.prefetch` with `RemotePolicy.networkOnly`. Refreshing what is\n * already being refreshed returns the same Model.\n */\n refresh: <AppModel, Store extends RemoteModel>(\n bound: BoundRemote<AppModel, Store>,\n model: AppModel,\n target: Projection<AppModel, unknown> | Surface<AppModel, any, any, void>,\n ): AppModel => {\n const projection = 'read' in target ? target : target.projection(undefined)\n const remote = bound.store.get(model)\n const asked = askedOf(projection)\n const connections = Requirement.mergeConnections(\n asked.connections,\n ) as ReadonlyArray<QueryRequirement>\n // A loaded connection's current items are marked with the entities; its page\n // is re-run by the read entry, and new items are planned when it lands.\n const items = connections.flatMap(connection => {\n const known = remote.connections[connection.identity]\n return known === undefined\n ? []\n : itemsOf(\n visibleItems(\n known,\n connection.identity,\n remote.optimistic.overlays,\n remote.entities,\n ).map(edge => edge.ref),\n connection.select,\n )\n })\n const requirements = plan(\n visibleStoreOf(remote.entities, remote.optimistic),\n [...asked.requirements, ...items],\n { force: true },\n )\n\n const marks: RemoteMessage[] = [\n ...(requirements.length === 0\n ? []\n : [{ _tag: 'RefreshStarted' as const, requests: requirements }]),\n // A connection the Model never loaded is already a query to run.\n ...connections\n .filter(connection => remote.connections[connection.identity] !== undefined)\n .map(connection => ({\n _tag: 'ConnectionInvalidated' as const,\n connection: connection.identity,\n })),\n ]\n const marked = marks.reduce(updateRemote, remote)\n // Fields already stale may be in a read that began before this refresh (a\n // refreshing policy marks what it refetches); unless no read has begun since\n // the last refresh, that read is restarted too.\n const inFlight =\n remote.refresh.started === remote.refresh.requested &&\n requirements.some(requirement =>\n requirement.fields.some(\n field =>\n remote.entities[entityKey(requirement.entity, requirement.id)]?.stale.has(field) ===\n true,\n ),\n )\n // Marking what is already marked changes nothing, so the Model keeps its identity.\n if (marked === remote && !inFlight) return model\n const refresh = { ...marked.refresh, requested: marked.refresh.requested + 1 }\n return bound.store.set(model, { ...marked, refresh } as Store)\n },\n\n /**\n * Writes a read result into the store, recording each field's applied window.\n * `requests` are the planned requirements the result answers.\n */\n writeRead,\n\n /**\n * Adapts an Effect RPC client for `RemoteRpc` to `RemoteClient`, so an\n * application provides the transport's RPC layer instead of writing the\n * `LiveChange`-to-`LiveEvent` mapping by hand.\n */\n clientLayer: <R = never>(\n client: RemoteRpcClient<R>,\n options: CoalesceOptions = {},\n ): Layer.Layer<RemoteClient, never, R> =>\n coalescedLayer(\n Layer.effect(\n RemoteClient,\n Effect.gen(function* () {\n // What the RPC client needs (a database under in-process handlers,\n // nothing under a transport) is supplied once, when the layer is built.\n const context = yield* Effect.context<R>()\n return {\n read: batch => client.FoldkitRemoteRead(batch).pipe(Effect.provideContext(context)),\n query: request =>\n client.FoldkitRemoteQuery(request).pipe(Effect.provideContext(context)),\n mutate: request =>\n client.FoldkitRemoteMutate(request).pipe(Effect.provideContext(context)),\n live: ({ requirements, after }) =>\n client\n .FoldkitRemoteLive({ version: REMOTE_PROTOCOL_VERSION, requirements, after })\n .pipe(Stream.map(liveEventOf), Stream.provideContext(context)),\n }\n }),\n ),\n options,\n ),\n\n /**\n * Wraps a `RemoteClient` layer so its reads coalesce: requirements issued\n * together become one batch, and a requirement already in flight is joined.\n * `Remote.clientLayer` applies this; use it on a hand-written client.\n */\n coalesced: coalescedLayer,\n\n /**\n * A Foldkit Subscription entry that keeps the cache to what the active\n * Surfaces reach. `projections` are the ones the application observes (the\n * same it passes to `Remote.observe`), `connections` the query connections\n * it shows; anything else is collected once the roots have been stable for\n * `grace`, so a route transition that comes straight back does not thrash.\n */\n retain: <AppModel, Message = RemoteMessage>(\n projections: ReadonlyArray<Projection<AppModel, unknown>>,\n toMessage: (message: RemoteMessage) => Message = identityMessage as never,\n options: RetainOptions = {},\n ): EntryWithoutKeepAlive<AppModel, Message, RetentionRoots, never> => {\n const roots = rootsOf(projections, options)\n return {\n dependenciesSchema: retentionRootsSchema,\n modelToDependencies: () => roots,\n dependenciesToStream: current =>\n Stream.fromEffect(\n Effect.succeed(toMessage({ _tag: 'RetentionChanged', roots: current })).pipe(\n Effect.delay(options.grace ?? 0),\n ),\n ),\n }\n },\n\n /**\n * Runs a `Query` through `RemoteClient`, encoding its input from the ref.\n * Pair the result with `Remote.queryMessage` to merge the page into the Model.\n */\n query: Effect.fn('Remote.query')(function* <Name extends string, Input>(\n ref: QueryRef<Name, Input>,\n ) {\n const client = yield* RemoteClient\n const input = yield* Schema.encodeUnknownEffect(ref.Input)(ref.input).pipe(\n Effect.catchTag('SchemaError', error =>\n Effect.fail(new RemoteQueryError({ message: error.message })),\n ),\n )\n return yield* client.query({ query: ref.query, input, window: ref.window })\n }),\n\n /** The `RemoteMessage` that merges a query page into its connection. */\n queryMessage: <Name extends string, Input>(\n ref: QueryRef<Name, Input>,\n result: Schema.Schema.Type<typeof QueryResult>,\n ): RemoteMessage => pageMessage(ref.identity, result),\n\n /**\n * The edges a connection shows: its server-known region with pending and\n * confirmed overlays placed around it, minus removed edges and edges whose\n * target is a tombstone.\n */\n visibleItems: (model: RemoteModel, connection: ConnectionIdentity): ReadonlyArray<Edge> => {\n const identity = connectionIdentity(connection)\n return visibleItems(\n model.connections[identity] ?? emptyConnection,\n identity,\n model.optimistic.overlays,\n model.entities,\n )\n },\n\n /** A pure, serializable view of the whole cache. */\n inspect: inspectRemote,\n\n /** A pure, serializable view of one entity, or `undefined` if unknown. */\n inspectEntity,\n\n /**\n * Runs a mutation through `RemoteClient`, decoding its typed Output and\n * returning the result's normalized patches so the caller can reconcile them\n * through `updateRemote`'s `MutationSucceeded` (or `Remote.mutateInto`).\n */\n mutate: mutateRemote,\n\n /**\n * Runs a mutation and reconciles its patches into a `RemoteModel` in one step,\n * returning the new model alongside the typed Output. The model-level form of\n * `MutationStarted` → `RemoteClient.mutate` → `MutationSucceeded`; in an\n * application the three are `update` (with `optimistic`), a Command, and the\n * Message the Command returns, so the optimistic operations show meanwhile.\n */\n mutateInto: Effect.fn('Remote.mutateInto')(function* <\n Name extends string,\n Input,\n Output,\n AppModel,\n Store extends RemoteModel,\n >(\n bound: BoundRemote<AppModel, Store>,\n model: AppModel,\n mutation: MutationDescriptor<Name, Input, Output>,\n input: Input,\n requestId: string,\n options: MutateOptions = {},\n ) {\n const started = updateRemote(bound.store.get(model), {\n _tag: 'MutationStarted',\n requestId,\n ...(options.optimistic === undefined ? {} : { optimistic: options.optimistic }),\n })\n const outcome = yield* mutateRemote(mutation, input, requestId)\n const settled = updateRemote(started, {\n _tag: 'MutationSucceeded',\n requestId,\n entities: outcome.entities,\n connections: outcome.connections,\n deleted: outcome.deleted,\n })\n return {\n output: outcome.output,\n model: bound.store.set(model, settled as Store),\n }\n }),\n\n /**\n * A Foldkit Subscription entry that plans a Surface's missing fields from the\n * Model and fetches them through `RemoteClient`, emitting a `RemoteMessage`\n * per outcome. Wrap it in an application Message (`toMessage`) and reduce it\n * with the domain's `update`. Under a refreshing `policy` the entry first\n * emits `RefreshStarted`, so the fields being refetched read as `Refreshing`\n * while the request is pending.\n */\n observe: <\n AppModel,\n Store extends RemoteModel,\n Names extends string,\n Model,\n SurfaceMessage,\n Params,\n Message = RemoteMessage,\n >(\n bound: BoundRemote<AppModel, Store, Names>,\n surface: Surface<AppModel, Model, SurfaceMessage, Params>,\n params: Params,\n toMessage: (message: RemoteMessage) => Message = identityMessage as never,\n options: ObserveOptions = {},\n ): EntryWithoutKeepAlive<AppModel, Message, ReadDependencies, RemoteClient> =>\n observeEntry(bound, () => askedOf(surface.projection(params)), toMessage, options),\n\n /**\n * A Foldkit Subscription entry that consumes the live stream for a Surface's\n * requirements, emitting a `LiveReceived` per event and a `ReadFailed` when\n * the stream breaks (including `ResumeUnavailable`). The resume cursor is read\n * from `RemoteModel.live`, so the application tracks no cursor of its own.\n */\n live: <\n AppModel,\n Store extends RemoteModel,\n Names extends string,\n Model,\n SurfaceMessage,\n Params,\n Message = RemoteMessage,\n >(\n bound: BoundRemote<AppModel, Store, Names>,\n surface: Surface<AppModel, Model, SurfaceMessage, Params>,\n params: Params,\n toMessage: (message: RemoteMessage) => Message = identityMessage as never,\n options: LiveOptions = {},\n ): EntryWithoutKeepAlive<\n AppModel,\n Message,\n { readonly requirements: ReadonlyArray<Requirement>; readonly cursor: LiveCursor },\n RemoteClient\n > => liveEntry(bound, () => requirementsOf(surface.projection(params)), toMessage, options),\n}\n\n// A domain's Subscription entries are unbranded so an application can spread\n// them into its own `Subscription.make`; wiring hands them over as a branded record.\nconst brandEntries = <AppModel>(\n entries: Readonly<Record<string, RemoteEntry<AppModel, any>>>,\n): Subscription.Subscriptions<AppModel, RemoteMessage, RemoteClient> =>\n Subscription.make<AppModel, RemoteMessage, RemoteClient>()(() => entries)\n\n/** The bound domain: the descriptor, the binding, and the operations over them. */\nconst bindDomain = <\n AppModel,\n Store extends RemoteModel,\n Entities extends readonly EntityLike[],\n Queries extends readonly QueryDescriptor<any, any, any>[],\n Mutations extends readonly MutationDescriptor<any, any, any>[],\n>(\n definition: RemoteDescriptor<Entities, Queries, Mutations>,\n store: ModelRef<AppModel, Store>,\n): RemoteDomain<AppModel, Store, Entities, Queries, Mutations> => {\n const bound = bindRemote(definition, store)\n // An application-union case has the runtime shape of the `RemoteMessage` it names.\n const reduce = (model: AppModel, message: RemoteMessage | RemoteMessageInput): AppModel =>\n store.set(model, updateRemote(store.get(model), message as RemoteMessage) as Store)\n const domain: RemoteDomain<AppModel, Store, Entities, Queries, Mutations> = {\n ...definition,\n ...bound,\n get: (selection, id) => Remote.select(bound, selection)(id),\n live: (selection, id) => {\n const projection = Remote.select(bound, selection)(id)\n return {\n ...projection,\n metadata: RemoteRequirements.of(\n ...requirementsOf(projection).map(requirement => ({ ...requirement, live: true })),\n ),\n }\n },\n subscriptions: (active, options = {}) => {\n // Dependencies differ per entry, as in Foldkit's own `Subscriptions` record.\n const entries: Record<string, RemoteEntry<AppModel, any>> = {}\n const projections: Array<(model: AppModel) => Projection<AppModel, unknown> | undefined> = []\n for (const [key, entry] of Object.entries(active)) {\n // Two applications can have the same Model type; the owner token tells them apart.\n if (bound.contract.owner !== undefined && entry.owner !== bound.contract.owner) {\n throw new Error(\n `Remote: Surface \"${entry.name}\" belongs to another application than domain \"${bound.contract.name}\"`,\n )\n }\n const projectionAt = memoizedProjectionOf(entry)\n projections.push(projectionAt)\n const asked = (model: AppModel) => askedOf(projectionAt(model))\n entries[`${key}.read`] = observeEntry(bound, asked, identityMessage, options)\n entries[`${key}.live`] = liveEntry(\n bound,\n model => asked(model).requirements.filter(requirement => requirement.live === true),\n identityMessage,\n options,\n )\n }\n entries.retain = {\n dependenciesSchema: retentionRootsSchema,\n modelToDependencies: model =>\n rootsOf(\n projections.flatMap(projectionAt => {\n const projection = projectionAt(model)\n return projection === undefined ? [] : [projection]\n }),\n options,\n ),\n dependenciesToStream: (current: RetentionRoots) =>\n Stream.fromEffect(\n Effect.succeed<RemoteMessage>({ _tag: 'RetentionChanged', roots: current }).pipe(\n Effect.delay(options.grace ?? 0),\n ),\n ),\n }\n // The loop above wrote exactly the keys the mapped type names.\n return entries as SubscriptionEntries<AppModel, typeof active>\n },\n plan: (model, projection, options) => Remote.plan(bound, model, projection, options),\n storeOf: model => storeOf(bound, model),\n prefetch: (model, projection, options = {}) =>\n Effect.gen(function* () {\n const { policy = RemotePolicy.cacheFirst, now = Date.now } = options\n const client = yield* RemoteClient\n const planOptions = RemotePolicy.toPlan(policy, now())\n let current = model\n // The pages first, so their items join the one entity read below.\n for (const query of planAsked(store.get(current), askedOf(projection), planOptions)\n .queries) {\n const page = yield* queryRequestOf(query).pipe(\n Effect.flatMap(request => client.query(request)),\n )\n current = reduce(current, pageMessage(query.identity, page, true))\n }\n const requirements = planAsked(\n store.get(current),\n askedOf(projection),\n planOptions,\n ).requirements\n if (requirements.length === 0) return current\n const at = now()\n const result = yield* client.read({\n version: REMOTE_PROTOCOL_VERSION,\n requests: requirements,\n })\n return reduce(current, { _tag: 'ReadReceived', requests: requirements, result, now: at })\n }),\n query: <Q extends QueryDescriptor<any, any, any>, Value, Entity extends string>(\n query: Q,\n input: QueryInput<Q>,\n options: QueryOptions<Value, Entity, QueryEntity<Q>>,\n ): QueryProjection<AppModel, Value, Q['name'], QueryInput<Q>> => {\n assertRegistered(bound, 'Query', definition.registry.queries, query.name)\n const { select: given, ...window } = options\n const select = selectionOf<Value, Entity>(given)\n for (const [side, size] of [\n ['first', window.first],\n ['last', window.last],\n ] as const) {\n if (size !== undefined && !(Number.isInteger(size) && size >= 0)) {\n throw new Error(\n `Remote: query \"${query.name}\" asks for ${side}: ${String(size)}; a page size is a non-negative integer`,\n )\n }\n }\n const listed = (query.Result as Partial<ConnectionSpec>).entity\n if (listed === undefined) {\n throw new Error(\n `Remote: query \"${query.name}\" is not a connection over an entity, so it has no page to select`,\n )\n }\n if (select.entity !== listed) {\n throw new Error(\n `Remote: the selection is of \"${select.entity}\", but query \"${query.name}\" lists \"${listed}\"`,\n )\n }\n const ref: QueryRef<Q['name'], QueryInput<Q>> = {\n ...query.ref(input),\n window: pickWindow(window),\n }\n const relation = relationOf(select)\n const relationKey = stableStringify(relation)\n const requirement: QueryRequirement = {\n identity: ref.identity,\n window: ref.window,\n select: relation,\n ref,\n }\n return {\n Model: remoteDataSchema(pageSchema(select.schema)) as Schema.Codec<\n RemoteData<Page<Value>>,\n unknown\n >,\n dependencies: [],\n metadata: RemoteConnections.of(requirement),\n ref,\n read: (root: AppModel): RemoteData<Page<Value>> => {\n const remote = store.get(root)\n const connection = remote.connections[ref.identity]\n // Invalidating a connection the Model never loaded records it stale with no\n // segments: still nothing to show. (A loaded empty page is not stale.)\n if (connection === undefined || (connection.stale && connection.segments.length === 0)) {\n return { _tag: 'Initial' }\n }\n const visible = visibleStoreOf(remote.entities, remote.optimistic)\n return memoRead(visible, connection, `${ref.identity}\\u0000${relationKey}`, () => {\n const items: Value[] = []\n let refreshing = connection.stale\n const edges = visibleItems(\n connection,\n ref.identity,\n remote.optimistic.overlays,\n remote.entities,\n )\n for (const edge of edges) {\n const assembled = assemble(visible, entityKey(edge.ref.entity, edge.ref.id), relation)\n if (assembled === undefined) return { _tag: 'Initial' }\n const decoded = Schema.decodeUnknownResult(select.schema)(assembled.values)\n if (Result.isFailure(decoded)) {\n return {\n _tag: 'Failed',\n error: { _tag: 'DecodeError', message: decoded.failure.message },\n }\n }\n refreshing ||= assembled.refreshing\n items.push(decoded.success)\n }\n const page = {\n items,\n hasNext: hasNext(connection),\n hasPrevious: hasPrevious(connection),\n }\n return refreshing ? { _tag: 'Refreshing', value: page } : { _tag: 'Ready', value: page }\n })\n },\n }\n },\n next: (model, projection) => {\n const segments = store.get(model).connections[projection.ref.identity]?.segments ?? []\n const end = segments[segments.length - 1]?.end\n return end?._tag === 'Cursor'\n ? {\n ...projection.ref,\n window: { ...pageSize(projection.ref.window, 'first'), after: end.cursor },\n }\n : undefined\n },\n previous: (model, projection) => {\n const start = store.get(model).connections[projection.ref.identity]?.segments[0]?.start\n return start?._tag === 'Cursor'\n ? {\n ...projection.ref,\n window: { ...pageSize(projection.ref.window, 'last'), before: start.cursor },\n }\n : undefined\n },\n refresh: (model, target) => Remote.refresh(bound, model, target),\n fetch: ref => ({\n name: `Remote.query(${ref.query})`,\n args: { connection: ref.identity, window: ref.window },\n effect: Remote.query(ref).pipe(\n Effect.match({\n onFailure: (error): RemoteMessage => ({\n _tag: 'QueryFailed',\n connection: ref.identity,\n error: remoteError(error),\n }),\n onSuccess: (page): RemoteMessage => pageMessage(ref.identity, page),\n }),\n ),\n }),\n mutate: (model, mutation, input, options = {}) => {\n assertRegistered(bound, 'Mutation', definition.registry.mutations, mutation.name)\n const remote = store.get(model)\n const requestId =\n options.requestId ?? `${bound.contract.name}-${remote.mutations.sequence + 1}`\n const tempId = `${requestId}.tmp`\n const optimistic =\n typeof options.optimistic === 'function'\n ? options.optimistic({ requestId, tempId })\n : options.optimistic\n const started = updateRemote(remote, {\n _tag: 'MutationStarted',\n requestId,\n ...(optimistic === undefined ? {} : { optimistic }),\n })\n return {\n model: store.set(model, started as Store),\n requestId,\n tempId,\n command: {\n name: `Remote.mutate(${mutation.name})`,\n args: { requestId },\n effect: mutateRemote(mutation, input, requestId).pipe(\n Effect.match({\n onFailure: (error): RemoteMessage => ({\n _tag: 'MutationFailed',\n requestId,\n error: remoteError(error),\n }),\n onSuccess: (outcome): RemoteMessage => ({\n _tag: 'MutationSucceeded',\n requestId,\n entities: outcome.entities,\n connections: outcome.connections,\n deleted: outcome.deleted,\n }),\n }),\n ),\n },\n }\n },\n mutation: (model, requestId) => mutationStatus(store.get(model).mutations, requestId),\n reduce,\n inspect: model => inspectRemote(store.get(model)),\n wiring: (active, options): RemoteWiring<AppModel> => ({\n key: `remote:${bound.contract.name}`,\n // Every domain claims the same tags with no per-domain discriminator, so\n // the assembly's claimant check keeps one assembly to one domain.\n handles: Object.keys(remoteMessageCases),\n route: (model, message) =>\n isRemoteMessage(message) ? Option.some({ model: reduce(model, message) }) : Option.none(),\n subscriptions: brandEntries(domain.subscriptions(active, options)),\n contract: bound.contract,\n }),\n }\n return domain\n}\n\n/** The window keys of a `QueryOptions`, and only those, without the undefined ones. */\nconst pickWindow = (window: QueryWindowOptions): QueryWindow => ({\n ...(window.first === undefined ? {} : { first: window.first }),\n ...(window.last === undefined ? {} : { last: window.last }),\n ...(window.after === undefined ? {} : { after: window.after }),\n ...(window.before === undefined ? {} : { before: window.before }),\n})\n\n/** The page size of a window, carried onto the next or previous page's window under `key`. */\nconst pageSize = (window: QueryWindow, key: 'first' | 'last'): QueryWindow => {\n const size = window.first ?? window.last\n return size === undefined ? {} : { [key]: size }\n}\n"],"mappings":";;;;;;;;;;;;;AAqCA,MAAMA,eAAa,WACjB,KAAK,UAAU;CACb,OAAO,SAAS;CAChB,OAAO,QAAQ;CACf,OAAO,SAAS;CAChB,OAAO,UAAU;AACnB,CAAC;;;;;AAMH,SAAS,iBACP,aACkC;CAClC,MAAM,yBAAS,IAAI,IAAmC;CACtD,KAAK,MAAM,cAAc,aAAa;EACpC,MAAM,MAAM,GAAG,WAAW,SAAS,QAAQA,YAAU,WAAW,MAAM;EACtE,MAAM,UAAU,OAAO,IAAI,GAAG;EAC9B,OAAO,IACL,KACA,YAAY,KAAA,IACR,aACA;GAAE,GAAG;GAAS,QAAQ,cAAc,QAAQ,QAAQ,WAAW,MAAM;EAAE,CAC7E;CACF;CACA,OAAO,CAAC,GAAG,OAAO,OAAO,CAAC;AAC5B;;AAGA,SAAS,cACP,SACA,MACqB;CACrB,MAAM,SAAS,CAAC,GAAG,QAAQ,MAAM;CACjC,MAAM,OAAO,IAAI,IAAI,MAAM;CAC3B,KAAK,MAAM,SAAS,KAAK,QAAQ;EAC/B,IAAI,KAAK,IAAI,KAAK,GAAG;EACrB,KAAK,IAAI,KAAK;EACd,OAAO,KAAK,KAAK;CACnB;CACA,MAAM,UAAU;EAAE,GAAG,QAAQ;EAAS,GAAG,KAAK;CAAQ;CACtD,MAAM,YAAY,eAAe,QAAQ,WAAW,KAAK,SAAS;CAClE,OAAO;EACL,QAAQ,QAAQ;EAChB;EACA,GAAI,OAAO,KAAK,OAAO,CAAC,CAAC,WAAW,IAAI,CAAC,IAAI,EAAE,QAAQ;E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EAAE,QAAQ,OAAO,OAAO;AACjE;;AAGA,MAAM,YAAY,QAAqB,QAAuC;CAC5E,MAAM,OAAO,OAAO,SAAS,OAAO;CACpC,OAAO,SAAS,KAAA,IAAY,CAAC,IAAI,GAAG,MAAM,KAAK;AACjD"}
1
+ {"version":3,"file":"index.mjs","names":["windowKey","RelationalQuery","Relational","unknownBoundary","DomainEntity","Relational"],"sources":["../src/requirement.ts","../src/relation.ts","../src/store.ts","../src/mutation.ts","../src/query.ts","../src/wire.ts","../src/coalesce.ts","../src/client.ts","../src/connection.ts","../src/selection.ts","../src/entity.ts","../src/matching.ts","../src/inspect.ts","../src/optimistic.ts","../src/live.ts","../src/plan.ts","../src/retain.ts","../src/persistence.ts","../src/remoteData.ts","../src/model.ts","../src/policy.ts","../src/index.ts"],"sourcesContent":["/**\n * What a Remote Projection needs from the server: entity slices and query\n * connections. They ride on `Projection.metadata` under Remote's own keys, so\n * Surface composes them without knowing their shape.\n */\nimport { Metadata } from 'foldkit-surface'\nimport type { QueryWindow } from './query.js'\n\n/**\n * The slice required of an entity. `windows` carries a pagination window per\n * relation field, and `relations` the slice required of each relation's\n * target, so one requirement describes a whole selection graph.\n */\nexport interface RelationRequirement {\n readonly entity: string\n readonly fields: readonly string[]\n readonly windows?: Readonly<Record<string, QueryWindow>> | undefined\n readonly relations?: Readonly<Record<string, RelationRequirement>> | undefined\n}\n\nexport interface Requirement extends RelationRequirement {\n readonly id: string\n /** The projection also subscribes to changes of this entity (`Data.live`). */\n readonly live?: boolean | undefined\n}\n\n/**\n * A query connection a projection reads: the page it first asks for and the\n * slice it selects of each item. `identity` is the connection's (query plus\n * canonical input, excluding the window).\n */\nexport interface ConnectionRequirement {\n readonly identity: string\n readonly window: QueryWindow\n readonly select: RelationRequirement\n}\n\nconst windowKey = (window: QueryWindow): string =>\n JSON.stringify([\n window.first ?? null,\n window.last ?? null,\n window.after ?? null,\n window.before ?? null,\n ])\n\n/**\n * Merges connection requirements for the same connection and window into one,\n * unioning what they select of each item; the first keeps its other properties.\n */\nfunction mergeConnections(\n connections: readonly ConnectionRequirement[],\n): readonly ConnectionRequirement[] {\n const merged = new Map<string, ConnectionRequirement>()\n for (const connection of connections) {\n const key = `${connection.identity}\\u0000${windowKey(connection.window)}`\n const current = merged.get(key)\n merged.set(\n key,\n current === undefined\n ? connection\n : { ...current, select: mergeRelation(current.select, connection.select) },\n )\n }\n return [...merged.values()]\n}\n\n/** Unions two relation slices for the same target: fields, windows, and nested relations. */\nfunction mergeRelation(\n current: RelationRequirement,\n next: RelationRequirement,\n): RelationRequirement {\n const fields = [...current.fields]\n const seen = new Set(fields)\n for (const field of next.fields) {\n if (seen.has(field)) continue\n seen.add(field)\n fields.push(field)\n }\n const windows = { ...current.windows, ...next.windows }\n const relations = mergeRelations(current.relations, next.relations)\n return {\n entity: current.entity,\n fields,\n ...(Object.keys(windows).length === 0 ? {} : { windows }),\n ...(relations === undefined ? {} : { relations }),\n }\n}\n\n/** Unions two relation maps field by field; a field in both merges recursively. */\nfunction mergeRelations(\n current: Readonly<Record<string, RelationRequirement>> | undefined,\n next: Readonly<Record<string, RelationRequirement>> | undefined,\n): Readonly<Record<string, RelationRequirement>> | undefined {\n if (current === undefined) return next\n if (next === undefined) return current\n const merged: Record<string, RelationRequirement> = { ...current }\n for (const [field, relation] of Object.entries(next)) {\n const existing = merged[field]\n merged[field] = existing === undefined ? relation : mergeRelation(existing, relation)\n }\n return merged\n}\n\n/** Unions requirements for the same entity + id, dropping duplicate fields. */\nfunction mergeRequirements(requirements: readonly Requirement[]): readonly Requirement[] {\n const grouped = new Map<string, Requirement>()\n for (const requirement of requirements) {\n const key = `${requirement.entity}\\u0000${requirement.id}`\n // Later windows win; a duplicate is a caller bug, not a merge policy.\n const group = grouped.get(key)\n const live = group?.live === true || requirement.live === true\n grouped.set(key, {\n ...mergeRelation(group ?? { entity: requirement.entity, fields: [] }, requirement),\n id: requirement.id,\n ...(live ? { live } : {}),\n })\n }\n return [...grouped.values()]\n}\n\n/**\n * Requirement helpers, for the packages that plan and serve requirements.\n * `merge` unions same-entity+id requirements; `mergeRelation` unions two\n * slices of one target (fields, windows, nested relations).\n */\nexport const Requirement = {\n merge: mergeRequirements,\n mergeRelation,\n mergeConnections,\n}\n\n/** Remote's entity requirements on a Projection, unioned per entity and id as nodes compose. */\nexport const RemoteRequirements = Metadata.key<Requirement>('remote', {\n merge: mergeRequirements,\n summarize: requirement => `${requirement.entity}:${requirement.id}`,\n})\n\n/** Remote's query connections on a Projection, unioned per connection and window. */\nexport const RemoteConnections = Metadata.key<ConnectionRequirement>('remote.connection', {\n merge: mergeConnections,\n summarize: connection => connection.identity.split('\\u0000').join(' '),\n})\n\n/** The entity requirements a Projection carries. */\nexport const requirementsOf = (projection: {\n readonly metadata: Metadata\n}): ReadonlyArray<Requirement> => RemoteRequirements.get(projection.metadata)\n\n/** The query connections a Projection carries. */\nexport const connectionsOf = (projection: {\n readonly metadata: Metadata\n}): ReadonlyArray<ConnectionRequirement> => RemoteConnections.get(projection.metadata)\n","/**\n * Relation values on the wire and in the store: a ref key (`\"Entity:id\"`), a\n * nullable ref key, an array of ref keys, or a page of ref keys. The planner\n * follows them into the store; the server follows them into the next read.\n */\nimport type { Schema } from 'effect'\nimport type { RelationRequirement } from './requirement.js'\n\nexport interface RefParts {\n readonly entity: string\n readonly id: string\n}\n\n/** A page of refs as the wire and the store hold it. */\nexport interface RefPageValue {\n readonly refs: ReadonlyArray<string>\n readonly hasNext: boolean\n readonly hasPrevious: boolean\n}\n\n/** Marks the codec `Entity.ref`/`Entity.refPage` produce, so a Selection can tell the field's shape. */\nexport const RelationAnnotation = 'foldkitRemoteRelation'\n/** The target entity's name on the same codec, so a nested selection of another entity is refused. */\nexport const RelationEntityAnnotation = 'foldkitRemoteRelationEntity'\n\nexport type RelationKind = 'one' | 'many' | 'page'\n\nexport interface RelationShape {\n readonly kind: RelationKind\n readonly nullable: boolean\n readonly entity: string\n}\n\n/**\n * A page of a relation that is a whole list is read under a name of its own, the\n * field's name and the page's size: `comments@first=10`. It is a field like any\n * other to the store, the planner, and the wire, so the whole list and a page of\n * it are held side by side, merged, marked stale, and persisted each on its own.\n * The server reads the name apart, reads the relation with the window, and\n * answers under the alias. A cursor is not part of the name: a page read from a\n * cursor merges onto the page it continues.\n */\nexport const RELATION_ALIAS = '@'\n\n/** The alias a relation field is read under, for a window of this size. */\nexport const relationAlias = (\n field: string,\n window: {\n readonly first?: number | undefined\n readonly last?: number | undefined\n // A cursor is no part of the name: a page read from one merges onto the page it continues.\n readonly after?: string | undefined\n readonly before?: string | undefined\n },\n): string =>\n `${field}${RELATION_ALIAS}${window.last !== undefined ? `last=${window.last}` : `first=${window.first ?? ''}`}`\n\n/** The field an alias reads; a name that is no alias is its own field. */\nexport const aliasedField = (name: string): string => {\n const at = name.indexOf(RELATION_ALIAS)\n return at === -1 ? name : name.slice(0, at)\n}\n\n/** Splits a ref key (`\"Entity:id\"`, the store key too) back into its parts. */\nexport const refParts = (encoded: string): RefParts => {\n const separator = encoded.indexOf(':')\n return separator === -1\n ? { entity: encoded, id: '' }\n : { entity: encoded.slice(0, separator), id: encoded.slice(separator + 1) }\n}\n\n/**\n * The refs a relation value carries, in order. Anything that is not a ref key,\n * an array of them, or a page of them contributes nothing.\n */\nexport const refsIn = (value: unknown): ReadonlyArray<RefParts> => {\n if (typeof value === 'string') return [refParts(value)]\n if (Array.isArray(value)) return value.filter(item => typeof item === 'string').map(refParts)\n if (value !== null && typeof value === 'object') {\n const refs = (value as { readonly refs?: unknown }).refs\n if (Array.isArray(refs)) return refs.filter(item => typeof item === 'string').map(refParts)\n }\n return []\n}\n\n/** The refs in a relation value that name the relation's target entity, and no other. */\nexport const targetsOf = (value: unknown, relation: RelationRequirement): ReadonlyArray<RefParts> =>\n refsIn(value).filter(ref => ref.entity === relation.entity)\n\nexport const isRefPage = (value: unknown): value is RefPageValue => {\n if (value === null || typeof value !== 'object') return false\n const page = value as Record<string, unknown>\n return (\n Array.isArray(page.refs) &&\n page.refs.every(ref => typeof ref === 'string') &&\n typeof page.hasNext === 'boolean' &&\n typeof page.hasPrevious === 'boolean'\n )\n}\n\ninterface AstLike {\n readonly _tag: string\n readonly annotations?: Readonly<Record<string, unknown>> | undefined\n readonly types?: ReadonlyArray<AstLike> | undefined\n readonly rest?: ReadonlyArray<AstLike> | undefined\n}\n\n/**\n * The relation shape an entity field schema declares: a ref (`one`), a nullable\n * ref, an array of refs (`many`), or a page of refs (`page`). `undefined` for a\n * scalar field, which cannot take a nested selection.\n */\nexport const relationShape = (schema: Schema.Top): RelationShape | undefined =>\n shapeOf(schema.ast as unknown as AstLike, false)\n\nconst shapeOf = (ast: AstLike, nullable: boolean): RelationShape | undefined => {\n const annotated = ast.annotations?.[RelationAnnotation]\n if (annotated === 'one' || annotated === 'page') {\n return {\n kind: annotated,\n nullable,\n entity: String(ast.annotations?.[RelationEntityAnnotation]),\n }\n }\n if (ast._tag === 'Arrays') {\n const item = ast.rest?.[0]\n const inner = item === undefined ? undefined : shapeOf(item, false)\n return inner?.kind === 'one' ? { kind: 'many', nullable, entity: inner.entity } : undefined\n }\n if (ast._tag === 'Union') {\n const members = ast.types ?? []\n const optional = members.some(member => member._tag === 'Null' || member._tag === 'Undefined')\n for (const member of members) {\n const shape = shapeOf(member, optional)\n if (shape !== undefined) return shape\n }\n }\n return undefined\n}\n","/**\n * The pure entity store: values, per-field presence, staleness, and tombstones.\n *\n * Presence is tracked **separately** from values, so `undefined`/`null`/absent/\n * stale/not-found are distinct states and a missing field is never inferred from\n * `value === undefined`. Nothing here performs I/O; every operation returns a\n * new store.\n */\nimport { Option } from 'effect'\nimport { RELATION_ALIAS } from './relation.js'\n\nexport type EntityKey = string\n\nexport interface EntityEntry {\n readonly values: Readonly<Record<string, unknown>>\n readonly present: ReadonlySet<string>\n /** Present fields whose value may be outdated (revalidation needed). */\n readonly stale: ReadonlySet<string>\n /** The entity is known to be absent; a later write clears this. */\n readonly tombstone: boolean\n /** Injected clock reading of the last write; never read from ambient state. */\n readonly updatedAt: number\n /**\n * The canonical window each present field was fetched with (`\"\"` for none).\n * A later request with a *known, different* window is planned as missing.\n */\n readonly windows: Readonly<Record<string, string>>\n}\n\nexport type EntityStore = Readonly<Record<EntityKey, EntityEntry>>\n\n/** The separator keeps an untrusted id from colliding with a prototype key. */\nexport const entityKey = (entity: string, id: string): EntityKey => `${entity}:${id}`\n\nconst emptyEntry: EntityEntry = {\n values: {},\n present: new Set(),\n stale: new Set(),\n tombstone: false,\n updatedAt: 0,\n windows: {},\n}\n\nexport const emptyStore: EntityStore = {}\n\nconst replace = (store: EntityStore, key: EntityKey, entry: EntityEntry): EntityStore => ({\n ...store,\n [key]: entry,\n})\n\nconst written = (\n previous: EntityEntry,\n values: Readonly<Record<string, unknown>>,\n now: number,\n windows?: Readonly<Record<string, string>>,\n): EntityEntry => {\n const present = new Set(previous.present)\n const stale = new Set(previous.stale)\n const nextWindows: Record<string, string> = { ...previous.windows }\n for (const field of Object.keys(values)) {\n present.add(field)\n stale.delete(field)\n // A write without a window clears any remembered one: the value changed.\n const requested = windows?.[field]\n if (requested !== undefined && requested !== '') nextWindows[field] = requested\n else delete nextWindows[field]\n // The whole list changed, so a page of it read under an alias may have too.\n if (!field.includes(RELATION_ALIAS))\n for (const held of present)\n if (held.startsWith(`${field}${RELATION_ALIAS}`) && !(held in values)) stale.add(held)\n }\n return {\n values: { ...previous.values, ...values },\n present,\n stale,\n tombstone: false,\n updatedAt: now,\n windows: nextWindows,\n }\n}\n\nexport interface EntityWrite {\n readonly key: EntityKey\n readonly values: Readonly<Record<string, unknown>>\n /** The canonical window each written relation field was fetched with. */\n readonly windows?: Readonly<Record<string, string>> | undefined\n}\n\n/**\n * Merges known values into many entities, copying the store once. Every\n * written field becomes present and non-stale; a tombstone is cleared because\n * the entity is evidently not absent.\n */\nexport const writeEntities = (\n store: EntityStore,\n writes: ReadonlyArray<EntityWrite>,\n now = 0,\n): EntityStore => {\n if (writes.length === 0) return store\n const next: Record<EntityKey, EntityEntry> = { ...store }\n for (const write of writes) {\n next[write.key] = written(next[write.key] ?? emptyEntry, write.values, now, write.windows)\n }\n return next\n}\n\n/** `writeEntities` for one entity. */\nexport const writeEntity = (\n store: EntityStore,\n key: EntityKey,\n values: Readonly<Record<string, unknown>>,\n now = 0,\n windows?: Readonly<Record<string, string>>,\n): EntityStore => writeEntities(store, [{ key, values, windows }], now)\n\n/**\n * Marks present fields stale (`true`) or ends their staleness (`false`) across\n * many entities, copying the store once. A field never present stays missing;\n * an unknown entity is left alone.\n */\nexport const setStale = (\n store: EntityStore,\n marks: ReadonlyArray<readonly [key: EntityKey, fields: Iterable<string>]>,\n stale: boolean,\n): EntityStore => {\n let next: Record<EntityKey, EntityEntry> | undefined\n for (const [key, fields] of marks) {\n const previous = (next ?? store)[key]\n if (previous === undefined) continue\n const staleFields = new Set(previous.stale)\n for (const field of fields) {\n if (stale) {\n if (previous.present.has(field)) staleFields.add(field)\n } else staleFields.delete(field)\n }\n // Only ever added to or only ever removed from, so an equal size is the same set.\n if (staleFields.size === previous.stale.size) continue\n next ??= { ...store }\n next[key] = { ...previous, stale: staleFields }\n }\n return next ?? store\n}\n\n/** Marks present fields stale; fields that were never present stay missing. */\nexport const markStale = (\n store: EntityStore,\n key: EntityKey,\n fields: Iterable<string>,\n): EntityStore => setStale(store, [[key, fields]], true)\n\n/** Ends a refresh that did not land: the fields are present again as they were. */\nexport const clearStale = (\n store: EntityStore,\n key: EntityKey,\n fields: Iterable<string>,\n): EntityStore => setStale(store, [[key, fields]], false)\n\n/** Records that the entity is known to be absent, so it is not refetched. */\nexport const tombstone = (store: EntityStore, key: EntityKey): EntityStore =>\n replace(store, key, {\n values: {},\n present: new Set(),\n stale: new Set(),\n tombstone: true,\n updatedAt: 0,\n windows: {},\n })\n\n/** Forgets everything known about the entity, including a tombstone. */\nexport const remove = (store: EntityStore, key: EntityKey): EntityStore => {\n if (store[key] === undefined) return store\n const next = { ...store }\n delete next[key]\n return next\n}\n\nexport const entry = (store: EntityStore, key: EntityKey): Option.Option<EntityEntry> => {\n const value = store[key]\n return value === undefined ? Option.none() : Option.some(value)\n}\n\nexport const isTombstone = (store: EntityStore, key: EntityKey): boolean =>\n store[key]?.tombstone === true\n\n/** A field is known only if it is present and not stale. */\nexport const hasField = (store: EntityStore, key: EntityKey, field: string): boolean => {\n const value = store[key]\n return (\n value !== undefined && !value.tombstone && value.present.has(field) && !value.stale.has(field)\n )\n}\n\n/** A present field whose value may be outdated; absent fields are not stale. */\nexport const isFieldStale = (store: EntityStore, key: EntityKey, field: string): boolean => {\n const value = store[key]\n return value !== undefined && !value.tombstone && value.stale.has(field)\n}\n\n/**\n * Reads a present field, stale or not. Absence and a tombstone both yield\n * `Option.none()`; a present `undefined`/`null` yields `Option.some`.\n */\nexport const readField = (\n store: EntityStore,\n key: EntityKey,\n field: string,\n): Option.Option<unknown> => {\n const value = store[key]\n if (value === undefined || value.tombstone || !value.present.has(field)) return Option.none()\n return Option.some(value.values[field])\n}\n\n/**\n * The fields the planner must fetch. A tombstone makes every field known\n * (absent), so it returns an empty list and the entity is not refetched. A\n * requested window that differs from the one a field was fetched with also\n * marks it missing, but only when the stored window is known (never `\"\"`), so a\n * writer that does not record windows cannot cause a refetch loop.\n */\nexport const missingFields = (\n store: EntityStore,\n key: EntityKey,\n fields: Iterable<string>,\n windows?: Readonly<Record<string, string>>,\n): ReadonlyArray<string> => {\n const value = store[key]\n if (value !== undefined && value.tombstone) return []\n return [...fields].filter(field => {\n if (value === undefined || !value.present.has(field) || value.stale.has(field)) return true\n const requested = windows?.[field]\n const stored = value.windows[field]\n return requested !== undefined && stored !== undefined && stored !== '' && stored !== requested\n })\n}\n","/**\n * Mutation status and idempotent reconciliation.\n *\n * A mutation result is reconciled into the store **at most once per\n * `requestId`**, so a transport retry cannot apply the same change twice. An\n * unknown or already-applied result is a no-op.\n */\nimport { Schema } from 'effect'\nimport type { RemoteError } from './remoteData.js'\nimport { entityKey, tombstone, writeEntity, type EntityStore } from './store.js'\n\nexport interface NormalizedPatch {\n readonly entity: string\n readonly id: string\n readonly values: Readonly<Record<string, unknown>>\n}\n\nexport interface MutationState {\n readonly pending: ReadonlySet<string>\n readonly applied: ReadonlySet<string>\n readonly failed: ReadonlySet<string>\n /** Why each request in `failed` failed, kept exactly as long as `failed` keeps its id. */\n readonly errors: ReadonlyMap<string, RemoteError>\n /**\n * How many mutations this model has started. A bound domain takes its next\n * request id from here, so `update` stays pure and the id exists before the\n * Command runs.\n */\n readonly sequence: number\n}\n\nexport const emptyMutationState: MutationState = {\n pending: new Set(),\n applied: new Set(),\n failed: new Set(),\n errors: new Map(),\n sequence: 0,\n}\n\n/**\n * How many settled request ids a mutation state retains. A retry settles well\n * inside this window, so bounding the ledger stops a long-lived application\n * from growing it without limit; a retry older than the window would re-apply\n * its entities.\n */\nconst MUTATION_ID_WINDOW = 1024\n\n/** Records `id` as most recent, evicting the oldest once the window is full. */\nconst remember = (ids: ReadonlySet<string>, id: string): ReadonlySet<string> => {\n const next = new Set(ids)\n // Re-inserting an existing id moves it to the most-recent end.\n next.delete(id)\n next.add(id)\n if (next.size <= MUTATION_ID_WINDOW) return next\n return new Set([...next].slice(next.size - MUTATION_ID_WINDOW))\n}\n\nexport const beginMutation = (state: MutationState, requestId: string): MutationState => ({\n ...state,\n pending: new Set([...state.pending, requestId]),\n sequence: state.sequence + 1,\n})\n\nexport const failMutation = (\n state: MutationState,\n requestId: string,\n error: RemoteError,\n): MutationState => {\n const pending = new Set(state.pending)\n pending.delete(requestId)\n const failed = remember(state.failed, requestId)\n const errors = new Map([...state.errors, [requestId, error] as const])\n // `failed` is a bounded window; an error outlives its id by nothing.\n for (const id of errors.keys()) if (!failed.has(id)) errors.delete(id)\n return { ...state, pending, failed, errors }\n}\n\n/** What Remote knows of one mutation request, by the id `mutate` returned. */\nexport type MutationStatus =\n /** Never started here, or settled so long ago its id has left the window. */\n | { readonly _tag: 'Unknown' }\n | { readonly _tag: 'Pending' }\n | { readonly _tag: 'Applied' }\n | { readonly _tag: 'Failed'; readonly error: RemoteError }\n\nexport const mutationStatus = (state: MutationState, requestId: string): MutationStatus => {\n // A retry reuses its request id, so the latest outcome wins: in flight, then\n // applied (a request cannot fail once applied), then the failure it last had.\n if (state.pending.has(requestId)) return { _tag: 'Pending' }\n if (state.applied.has(requestId)) return { _tag: 'Applied' }\n const error = state.errors.get(requestId)\n return error === undefined ? { _tag: 'Unknown' } : { _tag: 'Failed', error }\n}\n\nexport interface Reconciled {\n readonly store: EntityStore\n readonly state: MutationState\n}\n\n/**\n * Applies a mutation result once and marks the request settled. A second call\n * with the same `requestId` (a retry, or a live event describing the same change)\n * does not re-apply the entities, but still clears `pending`.\n */\nexport const reconcileMutation = (\n store: EntityStore,\n state: MutationState,\n requestId: string,\n entities: ReadonlyArray<NormalizedPatch>,\n deleted: ReadonlyArray<{ readonly entity: string; readonly id: string }> = [],\n): Reconciled => {\n // Patches first, then deletions: a mutation that names an entity both ways has deleted it.\n const next = state.applied.has(requestId)\n ? store\n : deleted.reduce(\n (current, gone) => tombstone(current, entityKey(gone.entity, gone.id)),\n entities.reduce(\n (current, entity) =>\n writeEntity(current, entityKey(entity.entity, entity.id), entity.values),\n store,\n ),\n )\n const applied = remember(state.applied, requestId)\n const pending = new Set(state.pending)\n pending.delete(requestId)\n return { store: next, state: { ...state, applied, pending } }\n}\n\n/** A mutation an application declares: its name and input/output codecs. */\nexport interface MutationDescriptor<Name extends string, Input, Output> {\n readonly name: Name\n readonly Input: Schema.Codec<Input>\n readonly Output: Schema.Codec<Output>\n}\n\n/** A codec, or the fields of a `Schema.Struct` where one is expected. */\nexport type SchemaOrFields = Schema.Codec<any, any, any, any> | Schema.Struct.Fields\n\n/** The decoded type of a codec, or of the Struct the fields describe. */\nexport type TypeOf<S extends SchemaOrFields> =\n S extends Schema.Codec<infer T, any, any, any>\n ? T\n : S extends Schema.Struct.Fields\n ? Schema.Struct.Type<S>\n : never\n\n/** The codec itself, or a `Schema.Struct` over the fields. */\nexport const schemaOf = <S extends SchemaOrFields>(shape: S): Schema.Codec<TypeOf<S>> =>\n (Schema.isSchema(shape) ? shape : Schema.Struct(shape as Schema.Struct.Fields)) as Schema.Codec<\n TypeOf<S>\n >\n\nexport const Mutation = {\n /**\n * Declares a mutation. `Input` and `Output` are codecs, or the fields of the\n * `Schema.Struct` they would be (`{ id: ProjectId, name: Schema.String }`).\n */\n make: <const Name extends string, Input extends SchemaOrFields, Output extends SchemaOrFields>(\n name: Name,\n config: { readonly Input: Input; readonly Output: Output },\n ): MutationDescriptor<Name, TypeOf<Input>, TypeOf<Output>> => ({\n name,\n Input: schemaOf(config.Input),\n Output: schemaOf(config.Output),\n }),\n}\n","/**\n * Queries and connections. A connection's identity is its descriptor plus the\n * canonical encoded filter/sort input — **never** the pagination window, so\n * `first(25)` and `after(cursor).first(25)` address the same logical connection.\n */\nimport { Schema } from 'effect'\nimport {\n Expr,\n Query as RelationalQuery,\n type AnyEntity,\n type AnyQuery,\n type InputExpr,\n} from 'foldkit-entity'\nimport type { Cursor } from './connection.js'\nimport { schemaOf, type SchemaOrFields, type TypeOf } from './mutation.js'\n\nexport type LiveInsertion = 'visible' | 'boundary' | 'invalidate' | 'ignore'\n\nexport interface LivePolicy {\n readonly prepend?: LiveInsertion\n readonly append?: LiveInsertion\n}\n\nexport interface ConnectionSpec<Entity extends string = string> {\n readonly entity: Entity\n readonly edgeKey?: Schema.Schema<unknown>\n readonly live?: LivePolicy\n}\n\nexport interface QueryWindow {\n readonly first?: number | undefined\n readonly last?: number | undefined\n readonly after?: Cursor | undefined\n readonly before?: Cursor | undefined\n}\n\nexport interface QueryRef<Name extends string, Input> {\n readonly query: Name\n readonly input: Input\n /** The input codec, so a `QueryRef` can encode itself without its descriptor. */\n readonly Input: Schema.Codec<Input>\n readonly window: QueryWindow\n /** Connection identity: descriptor + canonical input, excluding the window. */\n readonly identity: string\n}\n\nexport interface QueryDescriptor<Name extends string, Input, Result> {\n readonly name: Name\n readonly Input: Schema.Codec<Input>\n readonly Result: Result\n readonly ref: (input: Input) => QueryRef<Name, Input>\n /**\n * What the query means, when it was declared with `Query.define`: the rows it\n * is about, as a value an interpreter can compile. A descriptor from\n * `Query.make` has none — its meaning lives in whatever the server registered\n * to answer it — and a source is free to answer either.\n */\n readonly body?: AnyQuery | undefined\n}\n\n/**\n * The inputs of a definition's body: one placeholder per key of `Input`, typed\n * as that key's value. A body is built once, so these stand for what the query\n * will be given rather than being it.\n */\nexport type QueryInputs<Input> = {\n readonly [K in keyof Input & string]: InputExpr<Input[K]>\n}\n\n/**\n * What separates a query's name from its canonical encoded input in a\n * connection identity.\n *\n * NUL, because `JSON.stringify` escapes it inside a string (`\\u0000`) and a\n * query name is a TypeScript identifier — so the first occurrence is always the\n * boundary, and a name or an input value cannot forge one. Anything recovering\n * the query from an identity splits here.\n */\nexport const IDENTITY_SEPARATOR = '\\u0000'\n\n/** Stable stringify: object keys sorted, undefined-valued keys dropped, so equal inputs encode equally. */\nexport const stableStringify = (value: unknown): string => {\n if (value === undefined) return 'null'\n if (value === null || typeof value !== 'object') return JSON.stringify(value)\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`\n const record = value as Record<string, unknown>\n return `{${Object.keys(record)\n .filter(key => record[key] !== undefined)\n .sort()\n .map(key => `${JSON.stringify(key)}:${stableStringify(record[key])}`)\n .join(',')}}`\n}\n\n/**\n * `Result: Project` (or anything with the entity's `name`, as `Query.connection`\n * takes) means a connection over it; a `ConnectionSpec` names its `entity`\n * instead and is the result as given.\n */\nexport type ResultOf<Result> = Result extends { readonly name: infer Entity extends string }\n ? ConnectionSpec<Entity>\n : Result\n\nconst isEntityName = (result: unknown): result is { readonly name: string } =>\n typeof result === 'object' &&\n result !== null &&\n typeof (result as { readonly name?: unknown }).name === 'string'\n\n/**\n * The relational half comes from `foldkit-entity`, so one `Query` namespace\n * holds both what a query means (`from`, `where`, `orderBy`) and how this\n * client addresses it (`make`, `connection`, the window steps). They are one\n * vocabulary in use — a definition's body is composed and then named — and two\n * namespaces of the same name in one file would be a trap.\n */\n/**\n * One placeholder per key of the input's schema, each carrying that key's own\n * codec so a comparison against it is checked.\n *\n * A codec that is not a `Schema.Struct` exposes no keys to stand for, while its\n * *type* may well have them — so the body would be handed an empty object,\n * `input.slug` would be `undefined`, and the comparison would silently be\n * against nothing while the types all agreed. That is a wrong query rather than\n * a missing one, so it is refused where the query is declared.\n */\nconst inputsOf = (\n name: string,\n schema: Schema.Codec<unknown>,\n): Record<string, InputExpr<unknown>> => {\n const fields = (schema as { readonly fields?: Schema.Struct.Fields }).fields\n if (fields === undefined) {\n throw new Error(\n `[foldkit-remote] Query.define: the Input of \"${name}\" is not a Schema.Struct, so its body has no inputs to read. Declare it as fields (\\`{ slug: Schema.String }\\`) or a plain \\`Schema.Struct\\`.`,\n )\n }\n const inputs: Record<string, InputExpr<unknown>> = {}\n for (const key of Object.keys(fields)) {\n inputs[key] = Expr.input(key, fields[key] as unknown as Schema.Codec<unknown, unknown>)\n }\n return Object.freeze(inputs)\n}\n\n/** A relational `Query` over one Entity, as `Query.define`'s body returns. */\ntype RelationalQueryOf<E extends AnyEntity> = ReturnType<typeof RelationalQuery.from<E>>\n\nexport const Query = {\n ...RelationalQuery,\n\n /** Declares the entity and options a query's result is a connection over. */\n connection: <Entity extends string>(\n entity: { readonly name: Entity },\n options?: { readonly edgeKey?: Schema.Schema<unknown>; readonly live?: LivePolicy },\n ): ConnectionSpec<Entity> => ({\n entity: entity.name,\n ...(options?.edgeKey === undefined ? {} : { edgeKey: options.edgeKey }),\n ...(options?.live === undefined ? {} : { live: options.live }),\n }),\n\n /**\n * Declares a query. `Input` is a codec or the fields of the `Schema.Struct` it\n * would be; `Result` is a `Query.connection(...)`, or the entity the result is\n * a connection over.\n */\n make: <const Name extends string, Input extends SchemaOrFields, Result>(\n name: Name,\n config: { readonly Input: Input; readonly Result: Result },\n ): QueryDescriptor<Name, TypeOf<Input>, ResultOf<Result>> => {\n const Input = schemaOf(config.Input)\n const encode = Schema.encodeSync(Input)\n return {\n name,\n Input,\n Result: (isEntityName(config.Result)\n ? Query.connection(config.Result)\n : config.Result) as ResultOf<Result>,\n ref: input => ({\n query: name,\n input,\n Input,\n window: {},\n identity: `${name}${IDENTITY_SEPARATOR}${stableStringify(encode(input))}`,\n }),\n }\n },\n\n /**\n * Declares a query by what it means. The body is built once, here, and the\n * `input` it is given holds placeholders rather than values — there is\n * nothing yet to branch on, so a condition that depends on what was passed is\n * a comparison over the placeholder:\n *\n * ```ts\n * const PostsBySlug = Query.define('PostsBySlug', { slug: Schema.String }, ({ input }) =>\n * Query.from(Post).pipe(\n * Query.where(Expr.eq(Post.fields.slug, input.slug)),\n * Query.orderBy(Order.asc(Post.fields.id)),\n * ),\n * )\n * ```\n *\n * What comes back is an ordinary `QueryDescriptor` — the same name, `Input`,\n * `ref` and connection identity `Query.make` gives — carrying its `body`\n * besides. A server can compile that body instead of being told the same\n * thing again in its own dialect, and one that would rather answer the query\n * its own way still can.\n *\n * The result is a connection over the Entity the body reads, so it is not\n * named twice.\n */\n define: <const Name extends string, Input extends SchemaOrFields, E extends AnyEntity>(\n name: Name,\n Input: Input,\n body: (context: { readonly input: QueryInputs<TypeOf<Input>> }) => RelationalQueryOf<E>,\n options?: { readonly edgeKey?: Schema.Schema<unknown>; readonly live?: LivePolicy },\n ): QueryDescriptor<Name, TypeOf<Input>, ConnectionSpec<E['name']>> => {\n const schema = schemaOf(Input)\n const built = body({ input: inputsOf(name, schema) as QueryInputs<TypeOf<Input>> })\n const descriptor = Query.make(name, {\n Input,\n Result: Query.connection(built.entity, options) as ConnectionSpec<E['name']>,\n })\n return { ...descriptor, body: built }\n },\n\n first:\n (count: number) =>\n <R extends QueryRef<string, unknown>>(ref: R): R => ({\n ...ref,\n window: { ...ref.window, first: count },\n }),\n\n last:\n (count: number) =>\n <R extends QueryRef<string, unknown>>(ref: R): R => ({\n ...ref,\n window: { ...ref.window, last: count },\n }),\n\n after:\n (cursor: Cursor) =>\n <R extends QueryRef<string, unknown>>(ref: R): R => ({\n ...ref,\n window: { ...ref.window, after: cursor },\n }),\n\n before:\n (cursor: Cursor) =>\n <R extends QueryRef<string, unknown>>(ref: R): R => ({\n ...ref,\n window: { ...ref.window, before: cursor },\n }),\n}\n","/**\n * The Remote wire: Effect RPC semantics over `effect/unstable/rpc`. Remote owns\n * the message shapes; Effect owns the transport. `Make`ing reads batch, mutations\n * preserve order, and live data is a stream.\n */\nimport { Schema } from 'effect'\nimport { Rpc, RpcGroup } from 'effect/unstable/rpc'\nimport type { RelationRequirement, Requirement } from './requirement.js'\n\n/**\n * The read/live protocol version. A batch names the version it speaks and the\n * server refuses a mismatch with `RemoteProtocolError`, so a shape change never\n * drifts silently: bump it whenever `ReadRequest` or `LiveRequirement` change.\n */\nexport const REMOTE_PROTOCOL_VERSION = 3\n\nexport class RemoteReadError extends Schema.TaggedError<RemoteReadError>()('RemoteReadError', {\n message: Schema.String,\n}) {}\n\nexport class RemoteMutationError extends Schema.TaggedError<RemoteMutationError>()(\n 'RemoteMutationError',\n { message: Schema.String },\n) {}\n\nexport class RemoteLiveError extends Schema.TaggedError<RemoteLiveError>()('RemoteLiveError', {\n message: Schema.String,\n}) {}\n\n/** The peer speaks another protocol version; nothing was read. */\nexport class RemoteProtocolError extends Schema.TaggedError<RemoteProtocolError>()(\n 'RemoteProtocolError',\n { message: Schema.String, expected: Schema.Number, received: Schema.Number },\n) {}\n\n/** A page size: a non-negative integer, refused at decode otherwise rather than defaulted. */\nexport const PageSize = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))\n\nexport const WindowSchema = Schema.Struct({\n first: Schema.optional(PageSize),\n last: Schema.optional(PageSize),\n after: Schema.optional(Schema.String),\n before: Schema.optional(Schema.String),\n})\n\n/** A request may not name more fields of one entity than this; a selection never does. */\nexport const MAX_FIELDS_PER_REQUEST = 256\n/** A selection may not nest relations deeper than this; the wire refuses more. */\nexport const MAX_RELATION_DEPTH = 8\n\nconst Fields = Schema.Array(Schema.String).check(Schema.isMaxLength(MAX_FIELDS_PER_REQUEST))\n\n/**\n * The slice required of a relation's target; the ids come from the parent's\n * refs. Built as `MAX_RELATION_DEPTH` nested structs rather than a recursive\n * schema, so a deeper selection is refused at decode with a schema error.\n */\nconst relationLevel = (depth: number): Schema.Codec<RelationRequirement, RelationRequirement> => {\n const slice = {\n entity: Schema.String,\n fields: Fields,\n windows: Schema.optional(Schema.Record(Schema.String, WindowSchema)),\n }\n // A struct drops an unknown key silently; the last level refuses one instead.\n return (depth === 0\n ? Schema.Struct({ ...slice, relations: Schema.optionalKey(Schema.Never) })\n : Schema.Struct({\n ...slice,\n relations: Schema.optional(Schema.Record(Schema.String, relationLevel(depth - 1))),\n })) as unknown as Schema.Codec<RelationRequirement, RelationRequirement>\n}\n\nexport const RelationRequest = relationLevel(MAX_RELATION_DEPTH - 1)\n\nexport const ReadRequest: Schema.Codec<Requirement, Requirement> = Schema.Struct({\n entity: Schema.String,\n id: Schema.String,\n fields: Fields,\n /** Pagination window per relation field. */\n windows: Schema.optional(Schema.Record(Schema.String, WindowSchema)),\n /** The slice required of each relation field's target, resolved in the same read. */\n relations: Schema.optional(Schema.Record(Schema.String, RelationRequest)),\n}) as unknown as Schema.Codec<Requirement, Requirement>\n\nexport const ReadBatch = Schema.Struct({\n version: Schema.Number,\n requests: Schema.Array(ReadRequest),\n})\n\nexport const NormalizedEntity = Schema.Struct({\n entity: Schema.String,\n id: Schema.String,\n values: Schema.Record(Schema.String, Schema.Unknown),\n})\n\nexport const ReadBatchResult = Schema.Struct({ entities: Schema.Array(NormalizedEntity) })\n\nexport const MutationRequest = Schema.Struct({\n /** Stable across transport retries so a mutation is not applied twice. */\n requestId: Schema.String,\n mutation: Schema.String,\n input: Schema.Unknown,\n})\n\nexport const LiveEdge = Schema.Struct({\n entity: Schema.String,\n id: Schema.String,\n key: Schema.String,\n})\n\n/** A connection change a mutation confirms: the same facts a live event carries, without a cursor. */\nexport const ConnectionChangeSchema = Schema.Union([\n Schema.Struct({\n _tag: Schema.Literal('Insert'),\n connection: Schema.String,\n position: Schema.Union([Schema.Literal('prepend'), Schema.Literal('append')]),\n edge: LiveEdge,\n }),\n Schema.Struct({ _tag: Schema.Literal('Remove'), connection: Schema.String, edge: LiveEdge }),\n])\n\nexport const MutationResult = Schema.Struct({\n output: Schema.Unknown,\n entities: Schema.Array(NormalizedEntity),\n /** Connection changes the mutation made, applied alongside its entity patches. */\n connections: Schema.optional(Schema.Array(ConnectionChangeSchema)),\n /** Entities the mutation deleted; the client knows them absent from then on. */\n deleted: Schema.optional(\n Schema.Array(Schema.Struct({ entity: Schema.String, id: Schema.String })),\n ),\n})\n\nexport const LiveRequirement = Schema.Struct({\n version: Schema.Number,\n requirements: Schema.Array(ReadRequest),\n /** Resume cursor; events at or before it are duplicates. */\n after: Schema.Number,\n})\n\n/**\n * A live change. Entity changes update the store; connection changes alter\n * membership and ordering; both carry a per-stream cursor.\n */\nexport const LiveChange = Schema.Union([\n Schema.Struct({\n _tag: Schema.Literal('EntityPatched'),\n cursor: Schema.Number,\n entity: Schema.String,\n id: Schema.String,\n values: Schema.Record(Schema.String, Schema.Unknown),\n changed: Schema.Array(Schema.String),\n }),\n Schema.Struct({\n _tag: Schema.Literal('EntityDeleted'),\n cursor: Schema.Number,\n entity: Schema.String,\n id: Schema.String,\n }),\n Schema.Struct({\n _tag: Schema.Literal('ConnectionInsert'),\n cursor: Schema.Number,\n connection: Schema.String,\n position: Schema.Union([Schema.Literal('prepend'), Schema.Literal('append')]),\n edge: LiveEdge,\n }),\n Schema.Struct({\n _tag: Schema.Literal('ConnectionRemove'),\n cursor: Schema.Number,\n connection: Schema.String,\n edge: LiveEdge,\n }),\n Schema.Struct({\n _tag: Schema.Literal('ConnectionInvalidate'),\n cursor: Schema.Number,\n connection: Schema.String,\n }),\n])\n\nexport const Read = Rpc.make('FoldkitRemoteRead', {\n payload: ReadBatch,\n success: ReadBatchResult,\n error: Schema.Union([RemoteReadError, RemoteProtocolError]),\n})\n\nexport const Mutate = Rpc.make('FoldkitRemoteMutate', {\n payload: MutationRequest,\n success: MutationResult,\n error: RemoteMutationError,\n})\n\nexport const Live = Rpc.make('FoldkitRemoteLive', {\n payload: LiveRequirement,\n success: LiveChange,\n error: Schema.Union([RemoteLiveError, RemoteProtocolError]),\n stream: true,\n})\n\nexport class RemoteQueryError extends Schema.TaggedError<RemoteQueryError>()('RemoteQueryError', {\n message: Schema.String,\n}) {}\n\nexport const WireBoundary = Schema.Union([\n Schema.Struct({ _tag: Schema.Literal('Terminal') }),\n Schema.Struct({ _tag: Schema.Literal('Cursor'), cursor: Schema.String }),\n Schema.Struct({ _tag: Schema.Literal('Unknown') }),\n])\n\nexport const QueryRequest = Schema.Struct({\n query: Schema.String,\n input: Schema.Unknown,\n window: WindowSchema,\n})\n\nexport const QueryEdge = Schema.Struct({\n entity: Schema.String,\n id: Schema.String,\n key: Schema.String,\n})\n\nexport const QueryResult = Schema.Struct({\n edges: Schema.Array(QueryEdge),\n start: WireBoundary,\n end: WireBoundary,\n})\n\nexport const QueryRpc = Rpc.make('FoldkitRemoteQuery', {\n payload: QueryRequest,\n success: QueryResult,\n error: RemoteQueryError,\n})\n\nexport const RemoteRpc = RpcGroup.make(Read, Mutate, QueryRpc, Live)\n","/**\n * Read coalescing: every requirement a client asks for goes through one\n * `RequestResolver`, so requirements issued together become one `ReadBatch`\n * (ids batched, fields unioned) and a requirement already in flight is joined\n * rather than re-requested. The planner stays pure; this is the transport\n * seam's concern, and the store is still the only cache.\n */\nimport {\n Deferred,\n Duration,\n Effect,\n Request,\n RequestResolver,\n type Exit,\n type Schema,\n} from 'effect'\nimport { Requirement, type RelationRequirement } from './requirement.js'\nimport { stableStringify } from './query.js'\nimport {\n REMOTE_PROTOCOL_VERSION,\n type QueryRequest,\n type QueryResult,\n type ReadBatch,\n type ReadBatchResult,\n} from './wire.js'\nimport type { RemoteProtocolError, RemoteQueryError, RemoteReadError } from './wire.js'\n\ntype Batch = Schema.Schema.Type<typeof ReadBatch>\ntype BatchResult = Schema.Schema.Type<typeof ReadBatchResult>\ntype ReadError = RemoteReadError | RemoteProtocolError\nexport type BatchRead = (batch: Batch) => Effect.Effect<BatchResult, ReadError>\ntype QueryRequestValue = Schema.Schema.Type<typeof QueryRequest>\ntype QueryResultValue = Schema.Schema.Type<typeof QueryResult>\nexport type QueryRun = (\n request: QueryRequestValue,\n) => Effect.Effect<QueryResultValue, RemoteQueryError>\n\nexport interface CoalesceOptions {\n /**\n * How long a batch waits to collect more requirements before it runs.\n * Requirements issued concurrently coalesce even at the default of no wait.\n */\n readonly window?: Duration.Input | undefined\n}\n\n/** A stable key for a requirement, so an equal requirement in flight is joined. */\nexport const requirementKey = (requirement: Requirement): string =>\n stableStringify([\n requirement.entity,\n requirement.id,\n [...requirement.fields].sort(),\n requirement.windows ?? null,\n requirement.relations ?? null,\n ])\n\n/** Whether a requirement pages a relation anywhere in its graph. */\nconst hasWindows = (requirement: RelationRequirement): boolean =>\n requirement.windows !== undefined || Object.values(requirement.relations ?? {}).some(hasWindows)\n\n/**\n * The reads a batch runs. Requirements that page nothing union into one read\n * per entity and id, and every waiter may write its whole result, since\n * plain values are the same whoever asked. A requirement that pages a\n * relation reads alone: a page answers exactly one window, and a waiter\n * cannot tell which of two pages for the same entity was its own.\n */\nconst readsOf = (\n owned: ReadonlyMap<string, Requirement>,\n): ReadonlyArray<{\n readonly keys: ReadonlyArray<string>\n readonly requests: ReadonlyArray<Requirement>\n}> => {\n const plain = [...owned].filter(([, requirement]) => !hasWindows(requirement))\n const paged = [...owned].filter(([, requirement]) => hasWindows(requirement))\n return [\n ...(plain.length === 0\n ? []\n : [\n {\n keys: plain.map(([key]) => key),\n requests: Requirement.merge(plain.map(([, requirement]) => requirement)),\n },\n ]),\n ...paged.map(([key, requirement]) => ({ keys: [key], requests: [requirement] })),\n ]\n}\n\nclass QueryRead extends Request.Class<\n { readonly key: string; readonly request: QueryRequestValue },\n QueryResultValue,\n RemoteQueryError\n> {}\n\n/**\n * Wraps a raw query so that an identical query in flight (same query, input,\n * and window) is joined rather than run again; distinct queries run\n * concurrently. A page answers exactly one window, so nothing is batched.\n */\nexport const coalesceQueries = (\n query: QueryRun,\n options: CoalesceOptions = {},\n): Effect.Effect<QueryRun> =>\n Effect.gen(function* () {\n const runAll = (entries: ReadonlyArray<Request.Entry<QueryRead>>) =>\n Effect.gen(function* () {\n const distinct = new Map<string, QueryRequestValue>()\n for (const entry of entries) distinct.set(entry.request.key, entry.request.request)\n const results = new Map<string, Exit.Exit<QueryResultValue, RemoteQueryError>>()\n yield* Effect.forEach(\n distinct,\n ([key, request]) =>\n Effect.exit(query(request)).pipe(Effect.map(exit => void results.set(key, exit))),\n { concurrency: 'unbounded', discard: true },\n )\n for (const entry of entries) {\n yield* Request.completeEffect(entry, results.get(entry.request.key)!)\n }\n })\n let resolver = RequestResolver.make<QueryRead>(runAll)\n if (options.window !== undefined) {\n resolver = RequestResolver.setDelay(resolver, Duration.fromInputUnsafe(options.window))\n }\n return request =>\n Effect.request(\n new QueryRead({\n key: stableStringify([request.query, request.input, request.window]),\n request,\n }),\n resolver,\n )\n })\n\nclass ReadRequirement extends Request.Class<\n { readonly key: string; readonly requirement: Requirement },\n BatchResult,\n ReadError\n> {}\n\n/**\n * Wraps a raw batch read so that requirements are batched and deduplicated.\n * Every waiter receives the whole batch result; `Remote.writeRead` is\n * idempotent, so writing it more than once is harmless.\n */\nexport const coalesceReads = (\n read: BatchRead,\n options: CoalesceOptions = {},\n): Effect.Effect<BatchRead> =>\n Effect.gen(function* () {\n // Requirements a batch is currently reading; a later equal requirement\n // joins the deferred instead of starting another read.\n const inFlight = new Map<string, Deferred.Deferred<BatchResult, ReadError>>()\n\n // A batch runs to completion even when every requester is interrupted, so\n // an in-flight requirement is always settled and released by its read.\n const runAll = (entries: ReadonlyArray<Request.Entry<ReadRequirement>>) =>\n Effect.gen(function* () {\n // Per requirement key: the deferred this batch's entries wait on. One\n // already in flight from an earlier batch is joined; the rest are\n // owned here and settled by this batch's read.\n const joins = new Map<string, Deferred.Deferred<BatchResult, ReadError>>()\n const own = new Map<string, Deferred.Deferred<BatchResult, ReadError>>()\n for (const entry of entries) {\n const key = entry.request.key\n if (joins.has(key)) continue\n const existing = inFlight.get(key)\n if (existing !== undefined) {\n joins.set(key, existing)\n continue\n }\n const deferred = yield* Deferred.make<BatchResult, ReadError>()\n inFlight.set(key, deferred)\n own.set(key, deferred)\n joins.set(key, deferred)\n }\n if (own.size > 0) {\n const owned = new Map<string, Requirement>()\n for (const entry of entries) {\n if (own.has(entry.request.key)) owned.set(entry.request.key, entry.request.requirement)\n }\n yield* Effect.forEach(\n readsOf(owned),\n ({ keys, requests }) =>\n Effect.gen(function* () {\n const exit = yield* Effect.exit(\n read({ version: REMOTE_PROTOCOL_VERSION, requests }),\n )\n // Settle exactly the requirements this read answered.\n for (const key of keys) {\n inFlight.delete(key)\n yield* Deferred.done(own.get(key)!, exit)\n }\n }),\n { concurrency: 'unbounded', discard: true },\n )\n }\n for (const entry of entries) {\n yield* Request.completeEffect(entry, Deferred.await(joins.get(entry.request.key)!))\n }\n })\n\n let resolver = RequestResolver.make<ReadRequirement>(runAll)\n if (options.window !== undefined) {\n resolver = RequestResolver.setDelay(resolver, Duration.fromInputUnsafe(options.window))\n }\n\n return batch =>\n batch.requests.length === 0\n ? Effect.succeed({ entities: [] })\n : Effect.forEach(\n batch.requests,\n requirement =>\n Effect.request(\n new ReadRequirement({ key: requirementKey(requirement), requirement }),\n resolver,\n ),\n { concurrency: 'unbounded' },\n ).pipe(\n Effect.map(results => ({\n entities: [...new Set(results)].flatMap(result => result.entities),\n })),\n )\n })\n","/**\n * The transport seam: the `RemoteClient` Effect service, the RPC client it is\n * built from, the wire-to-client reconstructions, and the mutation call.\n */\nimport { Context, Effect, Layer, Schema, Stream } from 'effect'\nimport type { Requirement } from './requirement.js'\nimport { coalesceQueries, coalesceReads, type CoalesceOptions } from './coalesce.js'\nimport type { LiveCursor, LiveEvent } from './live.js'\nimport type { MutationDescriptor } from './mutation.js'\nimport type { ConnectionChange } from './optimistic.js'\nimport type { RemoteError } from './remoteData.js'\nimport {\n MutationRequest,\n MutationResult,\n QueryRequest,\n QueryResult,\n ReadBatch,\n ReadBatchResult,\n type ConnectionChangeSchema,\n RemoteLiveError,\n RemoteMutationError,\n RemoteProtocolError,\n RemoteQueryError,\n RemoteReadError,\n type LiveChange,\n type LiveRequirement,\n} from './wire.js'\n\n/**\n * The transport boundary. `foldkit-remote` never talks to a transport directly;\n * it depends on this Effect service, which a later phase wires to Effect RPC.\n */\nexport class RemoteClient extends Context.Service<\n RemoteClient,\n {\n readonly read: (\n batch: Schema.Schema.Type<typeof ReadBatch>,\n ) => Effect.Effect<\n Schema.Schema.Type<typeof ReadBatchResult>,\n RemoteReadError | RemoteProtocolError\n >\n readonly query: (\n request: Schema.Schema.Type<typeof QueryRequest>,\n ) => Effect.Effect<Schema.Schema.Type<typeof QueryResult>, RemoteQueryError>\n readonly mutate: (\n request: Schema.Schema.Type<typeof MutationRequest>,\n ) => Effect.Effect<Schema.Schema.Type<typeof MutationResult>, RemoteMutationError>\n readonly live: (request: {\n readonly requirements: ReadonlyArray<Requirement>\n readonly after: LiveCursor\n }) => Stream.Stream<LiveEvent, RemoteLiveError | RemoteProtocolError>\n }\n>()('foldkit-remote/RemoteClient') {}\n\n/**\n * The methods an Effect RPC client for `RemoteRpc` exposes. `R` is the\n * environment a handler needs; it defaults to `never`, which is what a real\n * transport client satisfies. `RemoteServer.handlers` returns this type with its\n * own `R`, so the two sides cannot drift apart.\n */\nexport interface RemoteRpcClient<R = never> {\n readonly FoldkitRemoteRead: (\n payload: Schema.Schema.Type<typeof ReadBatch>,\n ) => Effect.Effect<\n Schema.Schema.Type<typeof ReadBatchResult>,\n RemoteReadError | RemoteProtocolError,\n R\n >\n readonly FoldkitRemoteQuery: (\n payload: Schema.Schema.Type<typeof QueryRequest>,\n ) => Effect.Effect<Schema.Schema.Type<typeof QueryResult>, RemoteQueryError, R>\n readonly FoldkitRemoteMutate: (\n payload: Schema.Schema.Type<typeof MutationRequest>,\n ) => Effect.Effect<Schema.Schema.Type<typeof MutationResult>, RemoteMutationError, R>\n readonly FoldkitRemoteLive: (\n payload: Schema.Schema.Type<typeof LiveRequirement>,\n ) => Stream.Stream<\n Schema.Schema.Type<typeof LiveChange>,\n RemoteLiveError | RemoteProtocolError,\n R\n >\n}\n\n/** Reconstructs the client's `ConnectionChange` from the wire's flattened edge. */\nexport const connectionChangeOf = (\n change: Schema.Schema.Type<typeof ConnectionChangeSchema>,\n): ConnectionChange => {\n const edge = { key: change.edge.key, ref: { entity: change.edge.entity, id: change.edge.id } }\n return change._tag === 'Insert'\n ? { _tag: 'Insert', connection: change.connection, position: change.position, edge }\n : { _tag: 'Remove', connection: change.connection, edge }\n}\n\n/** Reconstructs the client's `LiveEvent` from the wire's flattened `LiveChange`. */\nexport const liveEventOf = (change: Schema.Schema.Type<typeof LiveChange>): LiveEvent => {\n switch (change._tag) {\n case 'EntityPatched':\n return {\n _tag: 'EntityPatched',\n ref: { entity: change.entity, id: change.id },\n values: change.values,\n changed: change.changed,\n cursor: change.cursor,\n }\n case 'EntityDeleted':\n return {\n _tag: 'EntityDeleted',\n ref: { entity: change.entity, id: change.id },\n cursor: change.cursor,\n }\n case 'ConnectionInsert':\n return {\n _tag: 'ConnectionInsert',\n connection: change.connection,\n position: change.position,\n edge: { key: change.edge.key, ref: { entity: change.edge.entity, id: change.edge.id } },\n cursor: change.cursor,\n }\n case 'ConnectionRemove':\n return {\n _tag: 'ConnectionRemove',\n connection: change.connection,\n edge: { key: change.edge.key, ref: { entity: change.edge.entity, id: change.edge.id } },\n cursor: change.cursor,\n }\n case 'ConnectionInvalidate':\n return { _tag: 'ConnectionInvalidate', connection: change.connection, cursor: change.cursor }\n }\n}\n\nexport const remoteError = (error: {\n readonly _tag: string\n readonly message: string\n}): RemoteError => ({\n _tag: error._tag,\n message: error.message,\n})\n\nexport const coalescedLayer = <E, R>(\n layer: Layer.Layer<RemoteClient, E, R>,\n options: CoalesceOptions = {},\n): Layer.Layer<RemoteClient, E, R> =>\n Layer.effect(\n RemoteClient,\n Effect.gen(function* () {\n const client = yield* RemoteClient\n const read = yield* coalesceReads(client.read, options)\n const query = yield* coalesceQueries(client.query, options)\n return { ...client, read, query }\n }),\n ).pipe(Layer.provide(layer))\n\n/**\n * `Remote.mutate` as a standalone effect, so `Remote.mutateInto` can reuse it\n * without the object literal referencing itself.\n */\nexport const mutateRemote = Effect.fn('Remote.mutate')(function* <\n Name extends string,\n Input,\n Output,\n>(mutation: MutationDescriptor<Name, Input, Output>, input: Input, requestId: string) {\n yield* Effect.annotateCurrentSpan({ mutation: mutation.name, requestId })\n const client = yield* RemoteClient\n const encoded = yield* Schema.encodeUnknownEffect(mutation.Input)(input).pipe(\n Effect.catchTag('SchemaError', error =>\n Effect.fail(new RemoteMutationError({ message: error.message })),\n ),\n )\n const result = yield* client.mutate({\n requestId,\n mutation: mutation.name,\n input: encoded,\n })\n const output = yield* Schema.decodeUnknownEffect(mutation.Output)(result.output).pipe(\n Effect.catchTag('SchemaError', error =>\n Effect.fail(new RemoteMutationError({ message: error.message })),\n ),\n )\n return {\n output,\n entities: result.entities,\n connections: (result.connections ?? []).map(connectionChangeOf),\n deleted: result.deleted ?? [],\n }\n})\n","/**\n * The pure connection model: an ordered normalized structure of edges with\n * explicit known boundaries. Pages, live events, and optimistic inserts are all\n * evidence about one connection; `merge` is the single deterministic reducer and\n * performs no I/O.\n *\n * Optimistic overlays and live state arrive in later phases.\n */\nimport { entityKey } from './store.js'\n\nexport interface EdgeRef {\n readonly entity: string\n readonly id: string\n}\n\n/** `key` is the edge identity used for de-duplication. */\nexport interface Edge {\n readonly key: string\n readonly ref: EdgeRef\n}\n\nexport const edge = (ref: EdgeRef, key: string = entityKey(ref.entity, ref.id)): Edge => ({\n key,\n ref,\n})\n\nexport type Cursor = string\n\nexport type Boundary =\n | { readonly _tag: 'Terminal' }\n | { readonly _tag: 'Cursor'; readonly cursor: Cursor }\n | { readonly _tag: 'Unknown' }\n\nexport const terminal: Boundary = { _tag: 'Terminal' }\nexport const unknown: Boundary = { _tag: 'Unknown' }\nexport const cursor = (value: Cursor): Boundary => ({ _tag: 'Cursor', cursor: value })\n\nexport interface Segment {\n readonly edges: readonly Edge[]\n readonly start: Boundary\n readonly end: Boundary\n}\n\nexport interface Connection {\n readonly segments: readonly Segment[]\n readonly stale: boolean\n}\n\nexport const emptyConnection: Connection = { segments: [], stale: false }\n\nexport const segment = (edges: readonly Edge[], start: Boundary, end: Boundary): Segment => ({\n edges,\n start,\n end,\n})\n\nconst dedupeEdges = (edges: readonly Edge[]): Edge[] => {\n const seen = new Set<string>()\n const out: Edge[] = []\n for (const value of edges) {\n if (seen.has(value.key)) continue\n seen.add(value.key)\n out.push(value)\n }\n return out\n}\n\nconst normalize = (segment: Segment): Segment => ({ ...segment, edges: dedupeEdges(segment.edges) })\n\n/** Longest suffix of `a` that is a prefix of `b`, matched by edge identity. */\nconst overlapLength = (a: readonly Edge[], b: readonly Edge[]): number => {\n const most = Math.min(a.length, b.length)\n for (let length = most; length > 0; length--) {\n let matches = true\n for (let i = 0; i < length; i++) {\n if (a[a.length - length + i]!.key !== b[i]!.key) {\n matches = false\n break\n }\n }\n if (matches) return length\n }\n return 0\n}\n\nconst cursorJoinable = (a: Boundary, b: Boundary): boolean =>\n a._tag === 'Cursor' && b._tag === 'Cursor' && a.cursor === b.cursor\n\n/** Joins `a` immediately before `b`, or returns `undefined` when they are not contiguous. */\nconst join = (a: Segment, b: Segment): Segment | undefined => {\n if (cursorJoinable(a.end, b.start)) {\n return { edges: dedupeEdges([...a.edges, ...b.edges]), start: a.start, end: b.end }\n }\n const overlap = overlapLength(a.edges, b.edges)\n if (overlap > 0) {\n return {\n edges: dedupeEdges([...a.edges, ...b.edges]),\n start: a.start,\n end: b.end,\n }\n }\n return undefined\n}\n\n/**\n * Global by edge identity: an edge appears once per connection. Dropping a\n * shared edge from the middle of a segment would otherwise imply that its\n * surviving neighbours are adjacent, so a segment with holes is split at each\n * hole and the new inner boundaries are `Unknown`.\n */\nconst dedupeConnection = (segments: readonly Segment[]): Segment[] => {\n const seen = new Set<string>()\n const out: Segment[] = []\n for (const segmentValue of segments) {\n const runs: Edge[][] = []\n let run: Edge[] = []\n for (const edgeValue of segmentValue.edges) {\n if (seen.has(edgeValue.key)) {\n if (run.length > 0) {\n runs.push(run)\n run = []\n }\n continue\n }\n seen.add(edgeValue.key)\n run.push(edgeValue)\n }\n if (run.length > 0) runs.push(run)\n if (runs.length === 0) continue\n if (runs.length === 1) {\n out.push({ ...segmentValue, edges: runs[0]! })\n continue\n }\n runs.forEach((edges, index) => {\n out.push({\n edges,\n start: index === 0 ? segmentValue.start : unknown,\n end: index === runs.length - 1 ? segmentValue.end : unknown,\n })\n })\n }\n return out\n}\n\n/** Adds a page to the connection, joining contiguous or overlapping segments. */\nexport const merge = (current: Connection, page: Segment): Connection => {\n // A zero-edge page carries no ordering evidence; joining it would let its\n // boundary overwrite a real segment's end. Ignore it.\n const incoming = normalize(page)\n if (incoming.edges.length === 0) return current\n\n const segments = [...current.segments.map(normalize), incoming]\n let joined = true\n while (joined) {\n joined = false\n outer: for (let i = 0; i < segments.length; i++) {\n for (let j = 0; j < segments.length; j++) {\n if (i === j) continue\n const result = join(segments[i]!, segments[j]!)\n if (result === undefined) continue\n segments[i] = result\n segments.splice(j, 1)\n joined = true\n break outer\n }\n }\n }\n return { ...current, segments: orderSegments(dedupeConnection(segments)) }\n}\n\n/**\n * Disjoint segments have no cursor linking them, so their relative order is\n * whatever it was; the two exceptions are known: a segment starting at the\n * terminal boundary is first, one ending at it is last.\n */\nconst orderSegments = (segments: readonly Segment[]): Segment[] => {\n const first = segments.filter(value => value.start._tag === 'Terminal')\n const last = segments.filter(value => value.end._tag === 'Terminal' && !first.includes(value))\n const middle = segments.filter(value => !first.includes(value) && !last.includes(value))\n return [...first, ...middle, ...last]\n}\n\n/** Visible edges, segment by segment. */\nexport const items = (connection: Connection): ReadonlyArray<Edge> =>\n connection.segments.flatMap(value => value.edges)\n\n/** There is more before the known region. Derived from boundaries, never row count. */\nexport const hasPrevious = (connection: Connection): boolean => {\n const first = connection.segments[0]\n return first !== undefined && first.start._tag !== 'Terminal'\n}\n\n/** There is more after the known region. Derived from boundaries, never row count. */\nexport const hasNext = (connection: Connection): boolean => {\n const last = connection.segments[connection.segments.length - 1]\n return last !== undefined && last.end._tag !== 'Terminal'\n}\n\n/** A connection with more than one segment has an explicit unknown gap. */\nexport const isGapped = (connection: Connection): boolean => connection.segments.length > 1\n","/**\n * Selections: the fields a Surface picks of an entity (nested through\n * relations, paged through connections), the requirement graph they imply,\n * and their assembly from the normalized store.\n */\nimport { Option, Schema } from 'effect'\nimport * as Domain from 'foldkit-entity'\nimport type { RelationRequirement } from './requirement.js'\nimport {\n Entity,\n type AnySchema,\n type EntityDescriptor,\n type EntityRef,\n type RefPage,\n} from './entity.js'\nimport type { QueryWindow } from './query.js'\nimport { aliasedField, isRefPage, relationAlias, relationShape, targetsOf } from './relation.js'\nimport { entityKey, isFieldStale, isTombstone, readField, type EntityStore } from './store.js'\n\n/** One page of a paginated relation with each target assembled through a nested selection. */\nexport interface Page<Item> {\n readonly items: ReadonlyArray<Item>\n readonly hasNext: boolean\n readonly hasPrevious: boolean\n}\n\n/**\n * The fields a projection reads of one entity, plus the slice it reads of each\n * relation's target. `Shape` tells a parent selection whether this one is a\n * paginated relation (`connection`) or a plain entity slice (`entity`).\n */\nexport interface Selection<\n Value,\n Name extends string = string,\n Shape extends 'entity' | 'connection' = 'entity' | 'connection',\n> {\n readonly entity: Name\n readonly fields: readonly string[]\n /** A pure codec: entity fields carry no decoding or encoding services. */\n readonly schema: Schema.Codec<Value, unknown, never, never>\n /** Pagination windows for nested relation fields, keyed by field name. */\n readonly connections?: Readonly<Record<string, QueryWindow>> | undefined\n /** The slice required of each nested relation's target, keyed by field name. */\n readonly relations?: Readonly<Record<string, RelationRequirement>> | undefined\n /** Present when this selection is itself a paginated relation. */\n readonly window?: QueryWindow | undefined\n /** Phantom: see `Shape`. */\n readonly shape?: Shape | undefined\n}\n\n/** Flattens a mapped type so hovers show the picked fields, not the machinery. */\ntype Simplify<T> = T extends infer O ? { readonly [K in keyof O]: O[K] } : never\n\n/** The value a Selection reads: `Selection.Value<typeof ProjectCard>`. */\nexport type SelectionValueOf<S> = S extends Selection<infer V, any, any> ? V : never\n\n/** The nested selections a relation field admits: of its target entity, in the shapes its value takes. */\ntype NestedFor<Field> =\n Exclude<Field, null | undefined> extends ReadonlyArray<EntityRef<infer Name, any>>\n ? Selection<unknown, Name, 'entity' | 'connection'>\n : Exclude<Field, null | undefined> extends RefPage<infer Name, any>\n ? Selection<unknown, Name, 'entity' | 'connection'>\n : Exclude<Field, null | undefined> extends EntityRef<infer Name, any>\n ? Selection<unknown, Name, 'entity'>\n : never\n\n/** What a selection of an entity with fields `F` may pick: `true` per scalar, a nested selection per relation. */\nexport type SelectionOf<F extends Schema.Struct.Fields> = {\n readonly [K in keyof F]?: true | NestedFor<Schema.Schema.Type<F[K]>>\n}\n\n/** `T | null` when the field admits `null` or `undefined` (both assemble to `null`). */\ntype Nullable<Field, T> = [Extract<Field, null | undefined>] extends [never] ? T : T | null\n\n/** A nested selection's value takes the shape of the field it selects through. */\ntype NestedValue<Field, Sel> =\n Sel extends Selection<infer V, string, 'connection'>\n ? Nullable<Field, V>\n : Sel extends Selection<infer V, string, 'entity'>\n ? Nullable<\n Field,\n Exclude<Field, null | undefined> extends ReadonlyArray<EntityRef<any, any>>\n ? ReadonlyArray<V>\n : Exclude<Field, null | undefined> extends RefPage<any, any>\n ? Page<V>\n : V\n >\n : never\n\n/** The value a selection `Sel` of fields `F` reads. */\nexport type SelectionValue<F extends Schema.Struct.Fields, Sel> = Simplify<{\n readonly [K in keyof Sel & keyof F]: Sel[K] extends true\n ? Schema.Schema.Type<F[K]>\n : NestedValue<Schema.Schema.Type<F[K]>, Sel[K]>\n}>\n\n// Built once per item schema, as `remoteDataSchema` is: a query projection is\n// rebuilt on every Model change.\nconst pageSchemas = new WeakMap<object, AnySchema>()\n\nexport const pageSchema = (item: AnySchema): AnySchema => {\n const cached = pageSchemas.get(item)\n if (cached !== undefined) return cached\n const built = Schema.Struct({\n items: Schema.Array(item),\n hasNext: Schema.Boolean,\n hasPrevious: Schema.Boolean,\n }) as unknown as AnySchema\n pageSchemas.set(item, built)\n return built\n}\n\n/** The requirement a nested selection contributes for its relation's target. */\nexport const relationOf = (selection: Selection<unknown>): RelationRequirement => ({\n entity: selection.entity,\n fields: selection.fields,\n ...(selection.connections === undefined ? {} : { windows: selection.connections }),\n ...(selection.relations === undefined ? {} : { relations: selection.relations }),\n})\n\nconst fromEntitySelections = new WeakMap<object, Selection<unknown>>()\n\nexport const Selection = {\n /**\n * The Remote Selection of a `foldkit-entity` Selection: the same members, read\n * from Remote's store. `true` on a relation reads its refs, as it does here.\n */\n from: <Name extends string, S extends Schema.Constraint>(\n selection: Domain.Selection<Name, unknown, S>,\n ): Selection<S['Type'], Name, 'entity'> => {\n // Compiled once per Entity Selection: `Data.get` and `Data.query` are called\n // with one on every render, and Remote caches its reads by the Selection's identity.\n const compiled = fromEntitySelections.get(selection)\n if (compiled !== undefined) return compiled as never\n const spec: Record<string, true | Selection<unknown>> = {}\n for (const [key, selected] of Object.entries(\n selection.members as Readonly<\n Record<\n string,\n | true\n | Domain.Selection<string, unknown, Schema.Constraint>\n | Domain.SelectionPage<string, Schema.Constraint>\n >\n >,\n ))\n spec[key] =\n selected === true\n ? true\n : Domain.SelectionPageTypeId in selected\n ? // A page of a `many` relation is Remote's relation connection.\n Selection.connection(\n Entity.from(selected.selection.entity as never),\n selected.window,\n Selection.from(selected.selection) as never,\n )\n : Selection.from(selected)\n const made = Selection.make(Entity.from(selection.entity as never), spec as never)\n fromEntitySelections.set(selection, made as Selection<unknown>)\n return made as never\n },\n\n /**\n * The fields to read of `entity`. A nested `Selection` on a relation field\n * reads through the ref (or refs, or page of refs) the field holds into the\n * target's fields; a scalar field cannot take one.\n */\n make: <Name extends string, F extends Schema.Struct.Fields, const Sel extends SelectionOf<F>>(\n entity: EntityDescriptor<Name, F>,\n selection: Sel,\n ): Selection<SelectionValue<F, Sel>, Name, 'entity'> => {\n if (Object.keys(selection).length === 0) {\n throw new Error(`Selection.make: a selection of \"${entity.name}\" picks at least one field`)\n }\n const picked: Record<string, AnySchema> = {}\n // The names read: a field's own, or the alias a page of a list is read under.\n const names: string[] = []\n const connections: Record<string, QueryWindow> = {}\n const relations: Record<string, RelationRequirement> = {}\n for (const key of Object.keys(selection)) {\n const choice = (selection as Record<string, unknown>)[key]\n if (choice === true) {\n picked[key] = entity.fields[key] as AnySchema\n names.push(key)\n continue\n }\n const nested = choice as Selection<unknown>\n const shape = relationShape(entity.fields[key] as Schema.Top)\n if (shape === undefined) {\n throw new Error(\n `Selection.make: \"${key}\" on \"${entity.name}\" is not a relation field, so it cannot take a nested selection`,\n )\n }\n if (nested.entity !== shape.entity) {\n throw new Error(\n `Selection.make: \"${key}\" on \"${entity.name}\" refers to \"${shape.entity}\", not \"${nested.entity}\"`,\n )\n }\n const nullable = (codec: AnySchema): AnySchema =>\n shape.nullable ? (Schema.NullOr(codec) as unknown as AnySchema) : codec\n if (nested.window !== undefined) {\n // A connection: the nested selection already carries its page codec. A page\n // of a whole list is read under its alias, so the list can be read beside it;\n // a field that is always a page has nothing to be beside.\n const name = shape.kind === 'many' ? relationAlias(key, nested.window) : key\n names.push(name)\n connections[name] = nested.window\n picked[key] = nullable(nested.schema as AnySchema)\n if (nested.fields.length > 0) relations[name] = relationOf(nested)\n continue\n }\n names.push(key)\n const item = nested.schema as AnySchema\n picked[key] = nullable(\n shape.kind === 'many'\n ? (Schema.Array(item) as unknown as AnySchema)\n : shape.kind === 'page'\n ? pageSchema(item)\n : item,\n )\n relations[key] = relationOf(nested)\n }\n return {\n entity: entity.name,\n fields: names,\n schema: Schema.Struct(picked) as unknown as Schema.Codec<\n SelectionValue<F, Sel>,\n unknown,\n never,\n never\n >,\n ...(Object.keys(connections).length === 0 ? {} : { connections }),\n ...(Object.keys(relations).length === 0 ? {} : { relations }),\n }\n },\n\n /**\n * A paginated relation: one page of refs to `entity` with a window, or, with\n * a nested selection, one page of targets assembled through it.\n */\n connection: (<Name extends string, F extends Schema.Struct.Fields, Item = never>(\n entity: EntityDescriptor<Name, F>,\n window: QueryWindow,\n selection?: Selection<Item, Name, 'entity'>,\n ): Selection<RefPage<Name, F> | Page<Item>, Name, 'connection'> => {\n if (selection !== undefined && selection.entity !== entity.name) {\n throw new Error(\n `Selection.connection: a page of \"${entity.name}\" cannot select \"${selection.entity}\"`,\n )\n }\n return {\n entity: entity.name,\n fields: selection?.fields ?? [],\n schema: (selection === undefined\n ? Entity.refPage(entity)\n : pageSchema(selection.schema as AnySchema)) as unknown as Schema.Codec<\n RefPage<Name, F> | Page<Item>,\n unknown,\n never,\n never\n >,\n window,\n ...(selection?.connections === undefined ? {} : { connections: selection.connections }),\n ...(selection?.relations === undefined ? {} : { relations: selection.relations }),\n }\n }) as {\n <Name extends string, F extends Schema.Struct.Fields>(\n entity: EntityDescriptor<Name, F>,\n window: QueryWindow,\n ): Selection<RefPage<Name, F>, Name, 'connection'>\n <Name extends string, F extends Schema.Struct.Fields, Item>(\n entity: EntityDescriptor<Name, F>,\n window: QueryWindow,\n selection: Selection<Item, NoInfer<Name>, 'entity'>,\n ): Selection<Page<Item>, Name, 'connection'>\n },\n}\n\ninterface Assembled {\n readonly values: unknown\n readonly refreshing: boolean\n}\n\n/**\n * Reads an entity's selected fields out of the store, following each nested\n * relation into its targets. `undefined` means some field, at any depth, is\n * not present yet. A tombstoned target reads as `null` (or is dropped from a\n * list), so the Selection's codec decides whether that is a failure.\n */\nexport const assemble = (\n store: EntityStore,\n key: string,\n requirement: RelationRequirement,\n): Assembled | undefined => {\n const values: Record<string, unknown> = {}\n let refreshing = false\n for (const field of requirement.fields) {\n const value = readField(store, key, field)\n if (Option.isNone(value)) return undefined\n refreshing ||= isFieldStale(store, key, field)\n // A page read under an alias is the value of the field the alias reads.\n const relation = requirement.relations?.[field]\n if (relation === undefined) {\n values[aliasedField(field)] = value.value\n continue\n }\n const nested = assembleRelation(store, value.value, relation)\n if (nested === undefined) return undefined\n values[aliasedField(field)] = nested.values\n refreshing ||= nested.refreshing\n }\n return { values, refreshing }\n}\n\nconst assembleTarget = (\n store: EntityStore,\n ref: { readonly entity: string; readonly id: string },\n relation: RelationRequirement,\n): Assembled | 'absent' | undefined => {\n const key = entityKey(ref.entity, ref.id)\n return isTombstone(store, key) ? 'absent' : assemble(store, key, relation)\n}\n\n/** Assembles the targets a relation value refers to, in the value's own shape. */\nconst assembleRelation = (\n store: EntityStore,\n value: unknown,\n relation: RelationRequirement,\n): Assembled | undefined => {\n if (value === null || value === undefined) return { values: null, refreshing: false }\n const targets: unknown[] = []\n let refreshing = false\n for (const ref of targetsOf(value, relation)) {\n const target = assembleTarget(store, ref, relation)\n if (target === undefined) return undefined\n if (target === 'absent') continue\n targets.push(target.values)\n refreshing ||= target.refreshing\n }\n if (typeof value === 'string') {\n return { values: targets.length === 0 ? null : targets[0], refreshing }\n }\n if (isRefPage(value)) {\n return {\n values: { items: targets, hasNext: value.hasNext, hasPrevious: value.hasPrevious },\n refreshing,\n }\n }\n return { values: targets, refreshing }\n}\n","/**\n * Entities: the descriptor an application declares, refs, ref pages, and\n * patches, with the codecs that carry refs on the wire.\n */\nimport { Schema, SchemaGetter } from 'effect'\nimport type * as Domain from 'foldkit-entity'\nimport {\n RelationAnnotation,\n RelationEntityAnnotation,\n refParts,\n RELATION_ALIAS,\n} from './relation.js'\n// selection.ts imports this module too; both only use the other inside\n// function bodies, so the cycle is never observed at module evaluation.\nimport { Selection, type SelectionOf, type SelectionValue } from './selection.js'\nimport { entityKey } from './store.js'\n\nexport type AnySchema = Schema.Schema<unknown>\n\ndeclare const entityRefFields: unique symbol\n\n/**\n * A normalized reference to an entity. `F` is a phantom carrying the entity's\n * fields so `Entity.patch` can type its patch; it is absent at runtime.\n */\nexport interface EntityRef<\n Name extends string,\n F extends Schema.Struct.Fields = Schema.Struct.Fields,\n> {\n readonly entity: Name\n readonly id: string\n readonly [entityRefFields]?: F\n}\n\nexport interface EntityDescriptor<Name extends string, F extends Schema.Struct.Fields> {\n readonly name: Name\n readonly schema: Schema.Struct<F>\n readonly fields: F\n // Methods, not properties: method signatures are bivariant, so a concrete\n // descriptor stays assignable to `EntityDescriptor<any, any>` (which appears\n // in every heterogeneous collection, e.g. `Remote.make`'s entities).\n ref(id: Schema.Schema.Type<F['id']>): EntityRef<Name, F>\n /** The fields a Surface reads of this entity; `Selection.make(entity, …)` with the entity as receiver. */\n select<const Sel extends SelectionOf<F>>(\n selection: Sel,\n ): Selection<SelectionValue<F, Sel>, Name, 'entity'>\n /** A patch of this entity's wire-shaped values; `Entity.patch(entity.ref(id), values)`. */\n patch(\n id: Schema.Schema.Type<F['id']>,\n values: Partial<Schema.Struct.Encoded<F>>,\n ): EntityPatch<Name, F>\n}\n\n/**\n * Relations are **references**, never inline target schemas: a ref cannot\n * reconstruct a full entity, and dereferencing is a store concern. Because the\n * target schema is not inlined, recursive relations cannot arise through the\n * schema graph.\n */\nconst refCodec = <Name extends string, F extends Schema.Struct.Fields>(\n entity: Name,\n): Schema.Codec<EntityRef<Name, F>, string> =>\n Schema.Struct({ entity: Schema.String, id: Schema.String })\n .pipe(\n Schema.encodeTo(Schema.String, {\n decode: SchemaGetter.transform(refParts),\n encode: SchemaGetter.transform((ref: EntityRef<string>) => entityKey(ref.entity, ref.id)),\n }),\n )\n .annotate({\n [RelationAnnotation]: 'one',\n [RelationEntityAnnotation]: entity,\n }) as unknown as Schema.Codec<EntityRef<Name, F>, string>\n\n/**\n * A patch in wire shape: the values the store holds, so a relation is its ref\n * key (`Entity.refKey`), not an `EntityRef`.\n */\nexport interface EntityPatch<Name extends string, F extends Schema.Struct.Fields> {\n readonly entity: Name\n readonly id: string\n readonly values: Partial<Schema.Struct.Encoded<F>>\n}\n\n/**\n * One authoritative page of a paginated relation: refs (never inline entities)\n * plus whether more exist. The adapter does not hold segmentation state; the\n * client merges pages.\n */\nexport interface RefPage<\n Name extends string,\n F extends Schema.Struct.Fields = Schema.Struct.Fields,\n> {\n readonly refs: ReadonlyArray<EntityRef<Name, F>>\n readonly hasNext: boolean\n readonly hasPrevious: boolean\n}\n\nconst refPageCodec = <Name extends string, F extends Schema.Struct.Fields>(\n entity: Name,\n): Schema.Codec<\n RefPage<Name, F>,\n {\n readonly refs: ReadonlyArray<string>\n readonly hasNext: boolean\n readonly hasPrevious: boolean\n }\n> =>\n Schema.Struct({\n refs: Schema.Array(refCodec<Name, F>(entity)),\n hasNext: Schema.Boolean,\n hasPrevious: Schema.Boolean,\n }).annotate({\n [RelationAnnotation]: 'page',\n [RelationEntityAnnotation]: entity,\n }) as unknown as Schema.Codec<\n RefPage<Name, F>,\n {\n readonly refs: ReadonlyArray<string>\n readonly hasNext: boolean\n readonly hasPrevious: boolean\n }\n >\n\n/** The ref codec a `foldkit-entity` relation becomes: one ref, a nullable ref, or an array of refs. */\ntype RelationField<Spec> =\n Spec extends Domain.RelationSpec<infer Target, infer Cardinality, infer Optional>\n ? Cardinality extends 'many'\n ? Schema.$Array<Schema.Codec<EntityRef<Target['name']>, string>>\n : Optional extends true\n ? Schema.NullOr<Schema.Codec<EntityRef<Target['name']>, string>>\n : Schema.Codec<EntityRef<Target['name']>, string>\n : never\n\n/**\n * The fields Remote stores for a `foldkit-entity` Entity: its own fields, its\n * derived members (the server supplies them like any field), and each relation\n * as refs.\n */\nexport type FieldsFrom<E> =\n E extends Domain.Entity<any, infer Fields, infer Relations, infer Derived>\n ? Fields & { readonly [K in keyof Derived]: Derived[K]['schema'] } & {\n readonly [K in keyof Relations]: RelationField<Relations[K]>\n }\n : never\n\n// One descriptor per Entity version: `Selection.from` looks a Selection's Entity up again.\nconst descriptors = new WeakMap<Domain.AnyEntity, EntityDescriptor<any, any>>()\n\nconst relationField = (\n relation: Domain.EntityMember & { readonly _tag: 'Relation' },\n): AnySchema => {\n const ref = refCodec(relation.target().name) as unknown as AnySchema\n return (relation.cardinality === 'many'\n ? Schema.Array(ref)\n : relation.optional\n ? Schema.NullOr(ref)\n : ref) as unknown as AnySchema\n}\n\nexport const Entity = {\n /**\n * The Remote descriptor of a `foldkit-entity` Entity. Relations declared with\n * `Entity.relate` become ref fields, so the store, the planner, and the server\n * treat it as they treat an `Entity.make` descriptor.\n */\n from: <E extends Domain.AnyEntity>(\n entity: E & { readonly fields: { readonly id: unknown } },\n ): EntityDescriptor<E['name'], FieldsFrom<E>> => {\n const cached = descriptors.get(entity)\n if (cached !== undefined) return cached\n const members: Readonly<Record<string, Domain.EntityMember>> = entity.members\n if (members.id?._tag !== 'Field')\n throw new Error(`Entity.from: \"${entity.name}\" needs an \"id\" field for Remote to key it by`)\n const fields: Record<string, AnySchema> = {}\n for (const [key, member] of Object.entries(members))\n fields[key] =\n member._tag === 'Relation' ? relationField(member) : (member.schema as AnySchema)\n const descriptor = Entity.make(entity.name, Schema.Struct(fields) as never)\n descriptors.set(entity, descriptor)\n return descriptor as never\n },\n\n make: <\n const Name extends string,\n const F extends Schema.Struct.Fields & { readonly id: Schema.Schema<unknown> },\n >(\n name: Name,\n schema: Schema.Struct<F>,\n ): EntityDescriptor<Name, F> => {\n // A page of a relation is read as `field@size`, so a field may not look like one.\n const reserved = Object.keys(schema.fields).find(field => field.includes(RELATION_ALIAS))\n if (reserved !== undefined) {\n throw new Error(\n `Entity.make: field \"${reserved}\" of \"${name}\" contains \"${RELATION_ALIAS}\", which names a page of a relation`,\n )\n }\n const descriptor: EntityDescriptor<Name, F> = {\n name,\n schema,\n fields: schema.fields,\n ref: id => ({ entity: name, id: String(id) }) as EntityRef<Name, F>,\n select: selection => Selection.make(descriptor, selection),\n patch: (id, values) => ({ entity: name, id: String(id), values }),\n }\n return descriptor\n },\n\n /** A relation to a known entity, decoded as a reference. */\n ref: <Name extends string, F extends Schema.Struct.Fields>(\n entity: EntityDescriptor<Name, F>,\n ): Schema.Codec<EntityRef<Name, F>, string> => refCodec<Name, F>(entity.name),\n\n /** A relation by name, for recursive or forward references. */\n refTo: <Name extends string>(name: Name): Schema.Codec<EntityRef<Name>, string> =>\n refCodec<Name, Schema.Struct.Fields>(name),\n\n /**\n * The wire key a relation field carries (`\"Entity:id\"`). Adapters that read a\n * foreign key emit this so the ref codec can decode it on the client.\n */\n refKey: (ref: { readonly entity: string; readonly id: string }): string =>\n entityKey(ref.entity, ref.id),\n\n /** Splits a ref key back into its entity and id. */\n refParts,\n\n /** A relation value of one authoritative page of refs. */\n refPage: <Name extends string, F extends Schema.Struct.Fields>(\n entity: EntityDescriptor<Name, F>,\n ): Schema.Codec<\n RefPage<Name, F>,\n {\n readonly refs: ReadonlyArray<string>\n readonly hasNext: boolean\n readonly hasPrevious: boolean\n }\n > => refPageCodec<Name, F>(entity.name),\n\n /**\n * A normalized patch for an entity, typed against its fields' wire shape:\n * write a relation as its ref key (`Entity.refKey`), as the server does.\n */\n patch: <Name extends string, F extends Schema.Struct.Fields>(\n ref: EntityRef<Name, F>,\n patch: Partial<Schema.Struct.Encoded<F>>,\n ): EntityPatch<Name, F> => ({ entity: ref.entity, id: ref.id, values: patch }),\n}\n","/**\n * Running a query body against the rows the client already holds.\n *\n * local-execution-DESIGN phase 3. A connection's rows are edges the server\n * delivered, and until now nothing on the client ever evaluated a body — which\n * is why an optimistic insert has to guess between `prepend` and `append`, and\n * why `LivePolicy` exists to be told in advance what to do with a row nobody\n * could judge.\n *\n * This judges them. It is pure, it performs no I/O, and it reuses the reference\n * interpreter in `foldkit-entity` rather than reimplementing the semantics —\n * so a body means here exactly what it means on the server, checked by the same\n * conformance suite.\n *\n * **It answers \"which of the rows I hold match\", never \"which rows match\".**\n * Those are different questions and the difference is not recoverable from the\n * result, so it is in the shape: `matched` is what satisfied the body, and\n * `skipped` is what was held but could not be judged. A caller that knows it\n * holds the whole population — a connection terminal at both ends — is the one\n * that can turn this into a complete answer. Nothing here can.\n *\n * **It is not authorization.** On the server a compiled `where` is conjoined\n * with the binding's `visible` rule. There is no `visible` here, and this is\n * safe only because the client holds only rows the server already released to\n * it. A local filter is not an access decision.\n */\nimport { Schema } from 'effect'\nimport { Query as Relational } from 'foldkit-entity'\nimport { evaluate, type Row } from 'foldkit-entity'\nimport type { QueryDescriptor } from './query.js'\nimport type { EntityKey, EntityStore } from './store.js'\n\n/**\n * An answer over the rows the client holds — never over the rows that exist.\n *\n * `complete` is the whole reason this is its own type rather than a `Page`. A\n * `Page` carries `hasNext`/`hasPrevious`, which are facts the *server* stated\n * about rows beyond the ones it delivered; a local answer has no such facts and\n * cannot invent them. What it can say is whether the population it judged was\n * all of it, which is decidable: a connection terminal at both ends is wholly\n * held, and nothing was skipped for a missing field.\n *\n * An incomplete answer is not wrong — it is an answer about less than the\n * caller may have meant, and the flag is what lets a view say \"3 so far\" rather\n * than \"3\", or a caller decide to ask the server.\n */\nexport interface Matched<A> {\n readonly items: ReadonlyArray<A>\n /** Whether every row the answer is about was judged. */\n readonly complete: boolean\n}\n\n/**\n * What the rows the client holds had to say about a body.\n *\n * `skipped` is the honest half. A row missing a field the body reads cannot be\n * judged — it is neither a match nor a non-match — and dropping it silently\n * would turn \"I could not tell\" into \"no\". Naming it lets a caller decide:\n * fetch the field, ask the server, or say the answer is partial.\n */\nexport interface Judged {\n /** Keys of the rows that satisfy the body, in the order the body asks for. */\n readonly matched: ReadonlyArray<EntityKey>\n /** Keys of rows held but missing a field the body reads, so not judged either way. */\n readonly skipped: ReadonlyArray<EntityKey>\n}\n\n/**\n * The fields of the body's own Entity that a row must have for the body to be\n * decidable about it — its predicates and its ordering terms.\n *\n * `id` is never among them: it is the key, so it is known for every row in the\n * store whether or not anything fetched it as a field.\n */\nconst decidableOn = (body: Parameters<typeof Relational.dependencies>[0]): ReadonlyArray<string> =>\n Relational.dependencies(body)\n .fields.filter(field => field.entity === body.entity.name && field.key !== 'id')\n .map(field => field.key)\n\nexport interface MatchingOptions {\n /**\n * Judge only these keys. Without it every row of the body's Entity in the\n * store is a candidate, which is what a filter over a loaded list wants; with\n * it, a caller narrows to a connection's own edges.\n */\n readonly among?: ReadonlyArray<EntityKey> | undefined\n}\n\n/**\n * The rows of `descriptor`'s Entity that the store holds and the body matches.\n *\n * The input is given **decoded**, as an application writes it, and encoded here\n * through the descriptor's own `Input` codec. That is deliberate and is the\n * whole reason this takes a descriptor rather than a bare body: a store holds\n * wire values, so an input has to be in that space to be compared against them,\n * and handing an interpreter a decoded value is a mistake **no runtime error\n * catches** — the reference interpreter answers \"no rows\", which reads exactly\n * like a correct answer. Doing it here means a caller cannot get it wrong.\n *\n * Literals in the body are deliberately *not* encoded. A literal written in\n * domain terms is already broken against the server, which binds it to a column\n * the same way; accepting it here would make the client quietly more permissive\n * than the thing it has to agree with.\n */\nexport const matching = <Name extends string, Input>(\n store: EntityStore,\n descriptor: QueryDescriptor<Name, Input, unknown>,\n input: Input,\n options: MatchingOptions = {},\n): Judged =>\n matchingEncoded(\n store,\n descriptor,\n Schema.encodeSync(descriptor.Input)(input) as Readonly<Record<string, unknown>>,\n options,\n )\n\n/**\n * As `matching`, for the callers in this module that already hold the input\n * **encoded**. Not exported: `matching` is the way in, and it cannot be given\n * the wrong space.\n */\nconst matchingEncoded = <Name extends string, Input>(\n store: EntityStore,\n descriptor: QueryDescriptor<Name, Input, unknown>,\n encoded: Readonly<Record<string, unknown>>,\n options: MatchingOptions = {},\n): Judged => {\n const body = descriptor.body\n if (body === undefined) {\n throw new Error(\n `[foldkit-remote] Remote.matching: query \"${descriptor.name}\" carries no body, so there is nothing to judge rows against. Declare it with Query.define.`,\n )\n }\n\n const entity = body.entity.name\n const prefix = `${entity}:`\n const needed = decidableOn(body)\n\n const candidates = options.among ?? Object.keys(store).filter(key => key.startsWith(prefix))\n\n const rows: Array<Row & { readonly __key: EntityKey }> = []\n const skipped: EntityKey[] = []\n\n for (const key of candidates) {\n if (!key.startsWith(prefix)) continue\n const entry = store[key]\n // Not held at all: nothing to judge. Reachable only through `among`, where\n // a caller named a key the store does not have — and a key nobody could\n // judge belongs in `skipped`, not in silence, or an answer built from it\n // would claim to have considered it.\n if (entry === undefined) {\n skipped.push(key)\n continue\n }\n // A tombstone is not a row. Known absent is an answer, not an absence of\n // one, so it is neither matched nor skipped.\n if (entry.tombstone) continue\n if (needed.some(field => !entry.present.has(field))) {\n skipped.push(key)\n continue\n }\n // The key's id is a **fallback**, not the truth: `Entity.ref` stringifies\n // ids, so a numeric id is `7` in the store and `\"7\"` in the key. Overwriting\n // the encoded value with the key's makes `eq(id, 7)` false and sorts ids\n // lexicographically — both silently.\n rows.push(\n 'id' in entry.values\n ? { ...entry.values, __key: key }\n : { ...entry.values, id: key.slice(prefix.length), __key: key },\n )\n }\n\n const matched = evaluate(body, encoded, rows).map(\n row => (row as { readonly __key: EntityKey }).__key,\n )\n\n return { matched, skipped }\n}\n\n/**\n * Whether one row belongs to a query, as far as the client can tell.\n *\n * Three answers, and the third is the one that makes this usable. `'unknown'`\n * is a row the store never fetched, or holds without a field the body reads —\n * a caller that collapses it into `'no'` has turned \"I could not tell\" into an\n * answer, which is the mistake this whole module is shaped against.\n *\n * **Membership is decidable where position is not.** Whether a row satisfies\n * `eq`, `isNull` or `contains` needs no collation: equality on text is exact\n * and `contains` folds ASCII, both stated in §6.0.1. *Where* a row sorts needs\n * text collation, which is the backend's and deliberately outside the\n * conformant subset — so this answers the half that is always answerable, and\n * ordering stays the server's until a query can declare its collation.\n */\nexport type Belongs = 'yes' | 'no' | 'unknown'\n\n/**\n * Takes the input **encoded**, because its one caller holds it that way: a\n * connection identity carries the canonical encoded input, and making it decode\n * only for this to encode again would be a round trip that can fail.\n *\n * A decoded-input sibling was written first and deleted: nothing called it. The\n * asymmetry with `matching`, which takes a decoded input, is the shape of the\n * two real callers rather than an oversight.\n */\nexport const belongsEncoded = <Name extends string, Input>(\n store: EntityStore,\n descriptor: QueryDescriptor<Name, Input, unknown>,\n encoded: Readonly<Record<string, unknown>>,\n key: EntityKey,\n): Belongs => {\n const entry = store[key]\n // Never fetched: nothing to judge, and silence is the honest answer.\n if (entry === undefined) return 'unknown'\n // Known absent. Not \"does not match\" — but it definitely does not belong in\n // a list, which is what a caller is asking.\n if (entry.tombstone) return 'no'\n\n // A value the store itself calls outdated cannot settle a question about new\n // information. `matching` still judges on a stale value — that is what is on\n // screen — but this is used to *decide*, and deciding \"does not belong\" from\n // a field the store says may be behind would suppress a live insert on the\n // strength of the very fact the insert contradicts.\n const body = descriptor.body\n if (body !== undefined && decidableOn(body).some(field => entry.stale.has(field))) {\n return 'unknown'\n }\n\n const judged = matchingEncoded(store, descriptor, encoded, { among: [key] })\n if (judged.matched.includes(key)) return 'yes'\n // Held, but missing a field the body reads.\n if (judged.skipped.includes(key)) return 'unknown'\n // Judged and did not match — or is a row of another Entity entirely, which\n // cannot belong to a connection over this one.\n return 'no'\n}\n","/** A serializable summary of a RemoteModel for DevTools and diagnostics. */\nimport type { Dependencies } from 'foldkit-entity'\nimport type { Failures, RemoteModel } from './model.js'\nimport type { QueryWindow } from './query.js'\nimport type { RemoteData } from './remoteData.js'\nimport type { RelationRequirement } from './requirement.js'\nimport type { EntityEntry } from './store.js'\n\n/** A serializable summary of a RemoteModel for DevTools and diagnostics. */\nexport interface RemoteInspection {\n readonly entities: ReadonlyArray<{\n readonly key: string\n readonly present: ReadonlyArray<string>\n readonly stale: ReadonlyArray<string>\n readonly tombstone: boolean\n readonly updatedAt: number\n readonly windows: Readonly<Record<string, string>>\n }>\n readonly connections: ReadonlyArray<string>\n readonly live: ReadonlyArray<string>\n readonly gaps: ReadonlyArray<string>\n /**\n * The `entity\\0id\\0field` marks of reads in flight, and a\n * `\\0connection\\0identity` mark for each query in flight. This is what \"Remote is\n * working\" means here, and it is read from the Model rather than from the\n * fibers doing the work: a tool that shows it shows something the Model can\n * be replayed to, and nothing that needs the runtime to be asked.\n */\n readonly loading: ReadonlyArray<string>\n /**\n * The reads that failed and are not yet settled: queries by connection\n * identity, entity fields by `entity\\0id\\0field` mark, each with its error.\n */\n readonly failures: Failures\n readonly mutations: {\n readonly pending: ReadonlyArray<string>\n readonly failed: ReadonlyArray<string>\n readonly applied: number\n }\n}\n\nconst inspectEntry = (key: string, entry: EntityEntry): RemoteInspection['entities'][number] => ({\n key,\n present: [...entry.present],\n stale: [...entry.stale],\n tombstone: entry.tombstone,\n updatedAt: entry.updatedAt,\n windows: { ...entry.windows },\n})\n\n/** A pure, serializable view of the whole cache. */\nexport const inspectRemote = (model: RemoteModel): RemoteInspection => ({\n entities: Object.entries(model.entities).map(([key, entry]) => inspectEntry(key, entry)),\n connections: Object.keys(model.connections),\n live: Object.keys(model.live),\n gaps: [...model.gaps],\n loading: [...model.loading],\n failures: model.failures,\n mutations: {\n pending: [...model.mutations.pending],\n failed: [...model.mutations.failed],\n applied: model.mutations.applied.size,\n },\n})\n\n/** A pure, serializable view of one entity, or `undefined` if unknown. */\nexport const inspectEntity = (\n model: RemoteModel,\n key: string,\n): RemoteInspection['entities'][number] | undefined => {\n const entry = model.entities[key]\n return entry === undefined ? undefined : inspectEntry(key, entry)\n}\n\n/**\n * What one query read is, and what it currently is — data-query-DESIGN §29.1.\n *\n * Every member is gathered from something that already existed: the read was\n * always this many pieces, and nothing had ever been asked to put them in one\n * place. It is plain serializable data, so a DevTools panel, a log line and a\n * test assert on the same value.\n *\n * Two members of §29.1's sketch are **not** here, and their absence is the\n * finding rather than an omission:\n *\n * - **Surface.** A Projection does not know which Surface reads it, and often\n * several do — so it is not a property of the read, and `explain` cannot\n * recover it alone. Given the active Surfaces (the same record\n * `subscriptions` takes), it reports **every** Surface reading the connection\n * rather than guessing one, and omits the member entirely when it was not\n * given them.\n * - **Executor.** The thing that answers a query is a `RemoteClient` Layer in\n * the runtime, not a value in the Model, and a pure read of the Model cannot\n * see it. That is the same boundary that makes this function pure and\n * replayable, so it is worth more than the line of text.\n *\n * And one that the design proposed and this does not want: *expectation*\n * (required versus optional). §11 left it unbuilt for want of a consumer, and\n * the explanation was the likeliest consumer. It turns out not to need it — a\n * query's result is a connection, so the shape is a `Page`, decided by the\n * definition rather than by the read. Nothing here has an opinion about whether\n * an empty one is an error, because nothing here has to have one.\n */\nexport interface QueryExplanation {\n /** The bound Remote domain that answers it. */\n readonly domain: string\n /** The definition's name. */\n readonly query: string\n /** The input as encoded, which is what the identity is built from. */\n readonly input: unknown\n /** The connection identity: definition plus canonical input, excluding the window. */\n readonly identity: string\n /** How much of the connection this read asks for. */\n readonly window: QueryWindow\n /** What it reads of each item, as the slice asked of the server. */\n readonly select: RelationRequirement\n /**\n * What the query means, as readable text — `Query.show`, and so neither SQL\n * nor whatever the backend compiled. Absent for a definition made with\n * `Query.make`, whose meaning lives on the server that answers it.\n */\n readonly body?: string | undefined\n /** The fields, inputs and operations the body reads; absent with the body. */\n readonly dependencies?: Dependencies | undefined\n /** What the read answers from this Model right now. */\n readonly state: RemoteData<unknown>['_tag']\n /**\n * The active Surfaces reading this connection at this Model, if the active\n * record was supplied. Plural because several may, which is why a Projection\n * cannot carry the answer itself.\n */\n readonly surfaces?: ReadonlyArray<string> | undefined\n /**\n * Why each of those Surfaces is active, where it was placed with\n * `Surface.when` — the Model path and the tag, without running anything. A\n * Surface placed with `Surface.at` has no entry: a callback cannot be read.\n */\n readonly activation?:\n | ReadonlyArray<{\n readonly surface: string\n readonly path: readonly string[]\n readonly tag: string\n }>\n | undefined\n}\n","/**\n * Optimistic layers. Pending changes are held as ordered layers over a base\n * store and as overlays over a connection; the visible value is recomputed, never\n * patched with inverses. Settling is remove-the-layer, so overlapping layers\n * rebase for free.\n */\nimport { type Connection, type Edge, edge, items } from './connection.js'\nimport { reconcileMutation, type MutationState, type NormalizedPatch } from './mutation.js'\nimport { entityKey, isTombstone, writeEntity, type EntityStore } from './store.js'\n\nexport interface EntityLayer {\n readonly id: string\n readonly patches: ReadonlyArray<NormalizedPatch>\n}\n\n/**\n * Edges placed outside a connection's server-known region (`prepend`,\n * `append`) or hidden from it (`remove`), owned by the request or live event\n * that produced them.\n */\nexport interface ConnectionOverlay {\n readonly id: string\n readonly connection: string\n readonly edges: ReadonlyArray<Edge>\n readonly position: 'prepend' | 'append' | 'remove'\n}\n\n/** A connection change a request makes optimistically or a mutation result confirms. */\nexport type ConnectionChange =\n | {\n readonly _tag: 'Insert'\n readonly connection: string\n readonly position: 'prepend' | 'append'\n readonly edge: Edge\n }\n | { readonly _tag: 'Remove'; readonly connection: string; readonly edge: Edge }\n\n/** What a request changes before the server answers: entity patches and connection changes. */\nexport type OptimisticOperation = NormalizedPatch | ConnectionChange\n\nconst isConnectionChange = (operation: OptimisticOperation): operation is ConnectionChange =>\n '_tag' in operation\n\nconst toOverlays = (id: string, changes: ReadonlyArray<ConnectionChange>): ConnectionOverlay[] =>\n changes.map(change => ({\n id,\n connection: change.connection,\n edges: [change.edge],\n position: change._tag === 'Insert' ? change.position : 'remove',\n }))\n\n/** A connection, by identity string or by anything that carries one (a `QueryRef`). */\nexport type ConnectionIdentity = string | { readonly identity: string }\n\nexport const connectionIdentity = (connection: ConnectionIdentity): string =>\n typeof connection === 'string' ? connection : connection.identity\n\nconst change = (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n position: 'prepend' | 'append' | 'remove',\n): ConnectionChange =>\n position === 'remove'\n ? { _tag: 'Remove', connection: connectionIdentity(connection), edge: edge(ref) }\n : { _tag: 'Insert', connection: connectionIdentity(connection), position, edge: edge(ref) }\n\n/**\n * Constructors for connection changes: what a request shows optimistically\n * (`MutateOptions.optimistic`) and what a mutation source reports it made\n * (`MutationOutcome.connections`).\n */\nexport const ConnectionChange = {\n /** Show `ref` at the front of the connection until the request settles. */\n prepend: (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n ): ConnectionChange => change(connection, ref, 'prepend'),\n\n /** Show `ref` at the end of the connection until the request settles. */\n append: (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n ): ConnectionChange => change(connection, ref, 'append'),\n\n /** Hide `ref` from the connection until the request settles. */\n remove: (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n ): ConnectionChange => change(connection, ref, 'remove'),\n}\n\n/**\n * Applies a request's operations: its patches become one layer and its\n * connection changes become overlays, all owned by `requestId` so settling\n * removes every one of them together.\n */\nexport const beginOptimistic = (\n optimistic: OptimisticState,\n requestId: string,\n operations: ReadonlyArray<OptimisticOperation>,\n): OptimisticState => {\n const patches = operations.filter(\n (operation): operation is NormalizedPatch => !isConnectionChange(operation),\n )\n const changes = operations.filter(isConnectionChange)\n return {\n layers:\n patches.length === 0 ? optimistic.layers : [...optimistic.layers, { id: requestId, patches }],\n overlays: [...optimistic.overlays, ...toOverlays(requestId, changes)],\n }\n}\n\n/**\n * Replaces a request's overlays with the server-confirmed changes, owned by\n * `id`, in the position the request's overlays held, so a confirmed edge keeps\n * its place among other pending inserts.\n */\nconst confirm = (\n optimistic: OptimisticState,\n requestId: string,\n id: string,\n changes: ReadonlyArray<ConnectionChange>,\n): OptimisticState => {\n const confirmed = toOverlays(id, changes)\n const at = optimistic.overlays.findIndex(overlay => overlay.id === requestId)\n const others = optimistic.overlays.filter(overlay => overlay.id !== requestId)\n return {\n ...optimistic,\n overlays:\n at === -1\n ? [...others, ...confirmed]\n : [...others.slice(0, at), ...confirmed, ...others.slice(at)],\n }\n}\n\n/** Pending entity layers and connection overlays over the base store. */\nexport interface OptimisticState {\n readonly layers: ReadonlyArray<EntityLayer>\n readonly overlays: ReadonlyArray<ConnectionOverlay>\n}\n\nexport const emptyOptimistic: OptimisticState = { layers: [], overlays: [] }\n\nexport const addLayer = (optimistic: OptimisticState, layer: EntityLayer): OptimisticState => ({\n ...optimistic,\n layers: [...optimistic.layers, layer],\n})\n\nexport const removeLayer = (optimistic: OptimisticState, id: string): OptimisticState => ({\n ...optimistic,\n layers: optimistic.layers.filter(layer => layer.id !== id),\n})\n\nexport const addOverlay = (\n optimistic: OptimisticState,\n overlay: ConnectionOverlay,\n): OptimisticState => ({\n ...optimistic,\n overlays: [...optimistic.overlays, overlay],\n})\n\nexport const removeOverlay = (optimistic: OptimisticState, id: string): OptimisticState => ({\n ...optimistic,\n overlays: optimistic.overlays.filter(overlay => overlay.id !== id),\n})\n\n/** Base store with every layer applied in order. Later layers win. */\nexport const visibleStore = (base: EntityStore, optimistic: OptimisticState): EntityStore =>\n optimistic.layers.reduce(\n (store, layer) =>\n layer.patches.reduce(\n (current, patch) => writeEntity(current, entityKey(patch.entity, patch.id), patch.values),\n store,\n ),\n base,\n )\n\n/**\n * A fresh page is newer than any settled overlay it covers: an edge the page\n * carries no longer needs an insert overlay, and a `remove` overlay hiding it\n * is stale (the server says it is back). A pending request's overlays are\n * left alone; they settle with the request.\n */\nexport const pruneOverlays = (\n optimistic: OptimisticState,\n connection: string,\n covered: ReadonlySet<string>,\n pending: ReadonlySet<string>,\n): OptimisticState => ({\n ...optimistic,\n overlays: optimistic.overlays.flatMap(overlay => {\n if (overlay.connection !== connection || pending.has(overlay.id)) return [overlay]\n const edges = overlay.edges.filter(edge => !covered.has(edge.key))\n return edges.length === 0 ? [] : [{ ...overlay, edges }]\n }),\n})\n\n/** Everything a request owns: its layer and its overlays. */\nconst release = (optimistic: OptimisticState, requestId: string): OptimisticState =>\n removeOverlay(removeLayer(optimistic, requestId), requestId)\n\n/**\n * Applies a result idempotently and releases the request's layer and overlays:\n * a later layer re-wins on rebase. Confirmed connection changes are recorded\n * once per request, as overlays the request no longer owns.\n */\nexport const settleSuccess = (\n base: EntityStore,\n optimistic: OptimisticState,\n state: MutationState,\n requestId: string,\n entities: ReadonlyArray<NormalizedPatch>,\n connections: ReadonlyArray<ConnectionChange> = [],\n deleted: ReadonlyArray<{ readonly entity: string; readonly id: string }> = [],\n): {\n readonly store: EntityStore\n readonly state: MutationState\n readonly optimistic: OptimisticState\n} => {\n const reconciled = reconcileMutation(base, state, requestId, entities, deleted)\n return {\n store: reconciled.store,\n state: reconciled.state,\n optimistic: state.applied.has(requestId)\n ? release(optimistic, requestId)\n : confirm(\n removeLayer(optimistic, requestId),\n requestId,\n `confirmed:${requestId}`,\n connections,\n ),\n }\n}\n\n/** A failed request's layer and overlays are dropped; the base was never mutated. */\nexport const settleFailure = (optimistic: OptimisticState, requestId: string): OptimisticState =>\n release(optimistic, requestId)\n\n/**\n * Visible edges for one connection: applicable overlays are placed outside the\n * server-known segments and de-duplicated by edge identity (across overlays too),\n * so a pending insert never corrupts server-known ordering; a `remove` overlay\n * hides its edges wherever they are, and so does a tombstone on the edge's\n * target when `store` is given. A later prepend lands before an earlier one, a\n * later append after, so pending inserts read in the order they were made.\n * Boundaries still come from the connection's segments.\n */\nexport const visibleItems = (\n connection: Connection,\n connectionId: string,\n overlays: ReadonlyArray<ConnectionOverlay>,\n store?: EntityStore,\n): ReadonlyArray<Edge> => {\n const applicable = overlays.filter(overlay => overlay.connection === connectionId)\n // Overlays are ordered evidence: the last word on an edge wins, so a remove\n // hides it only until a later insert brings it back.\n const hidden = new Set<string>()\n for (const overlay of applicable) {\n for (const edge of overlay.edges) {\n if (overlay.position === 'remove') hidden.add(edge.key)\n else hidden.delete(edge.key)\n }\n }\n const gone = (edge: Edge): boolean =>\n hidden.has(edge.key) ||\n (store !== undefined && isTombstone(store, entityKey(edge.ref.entity, edge.ref.id)))\n const known = items(connection).filter(edge => !gone(edge))\n const seen = new Set(known.map(edge => edge.key))\n\n const take = (position: 'prepend' | 'append'): ReadonlyArray<Edge> => {\n const edges: Edge[] = []\n const ordered = applicable.filter(value => value.position === position)\n for (const overlay of position === 'prepend' ? [...ordered].reverse() : ordered) {\n for (const edge of overlay.edges) {\n if (seen.has(edge.key) || gone(edge)) continue\n seen.add(edge.key)\n edges.push(edge)\n }\n }\n return edges\n }\n\n return [...take('prepend'), ...known, ...take('append')]\n}\n","/**\n * Live data. Entity facts update the store; connection facts change ordering and\n * membership. Events carry a monotonic cursor ordered **per stream**: duplicates\n * are ignored, and a gap is surfaced so the caller can resume or invalidate.\n * Subscriptions are selection-aware and driven by active Surfaces.\n */\nimport type { EdgeRef } from './connection.js'\nimport { type Connection, type Edge, hasNext, hasPrevious } from './connection.js'\nimport { addOverlay, type OptimisticState } from './optimistic.js'\nimport type { LiveInsertion, LivePolicy } from './query.js'\nimport { entityKey, tombstone, writeEntity, type EntityStore } from './store.js'\n\nexport type LiveCursor = number\n\nexport type LiveEvent =\n | {\n readonly _tag: 'EntityPatched'\n readonly ref: EdgeRef\n readonly values: Readonly<Record<string, unknown>>\n readonly changed: ReadonlyArray<string>\n readonly cursor: LiveCursor\n }\n | { readonly _tag: 'EntityDeleted'; readonly ref: EdgeRef; readonly cursor: LiveCursor }\n | {\n readonly _tag: 'ConnectionInsert'\n readonly connection: string\n readonly position: 'prepend' | 'append'\n readonly edge: Edge\n readonly cursor: LiveCursor\n }\n | {\n readonly _tag: 'ConnectionRemove'\n readonly connection: string\n readonly edge: Edge\n readonly cursor: LiveCursor\n }\n | {\n readonly _tag: 'ConnectionInvalidate'\n readonly connection: string\n readonly cursor: LiveCursor\n }\n\nexport interface BoundaryCounts {\n readonly before: number\n readonly after: number\n}\n\nexport interface LiveState {\n /** Last applied cursor for this stream. */\n readonly cursor: LiveCursor\n /** Edges recorded outside the loaded boundary, not visible in `items`. */\n readonly boundary: Readonly<Record<string, BoundaryCounts>>\n}\n\nexport const emptyLiveState: LiveState = { cursor: 0, boundary: {} }\n\nexport type LiveOutcome = 'applied' | 'duplicate' | 'gap'\n\n/**\n * Ordering per stream: at most the next cursor; ahead is a gap. Cursor `0` means\n * \"no baseline yet\" (cursors are 1-based), so the first event of a stream is\n * accepted whatever its cursor — otherwise a stream not starting at 1 would be a\n * spurious gap.\n */\nexport const classifyLive = (state: LiveState, cursor: LiveCursor): LiveOutcome =>\n cursor <= state.cursor\n ? 'duplicate'\n : state.cursor === 0 || cursor === state.cursor + 1\n ? 'applied'\n : 'gap'\n\nconst advance = (state: LiveState, cursor: LiveCursor): LiveState => ({ ...state, cursor })\n\nconst recordBoundary = (\n state: LiveState,\n connection: string,\n position: 'prepend' | 'append',\n): LiveState => {\n const current = state.boundary[connection] ?? { before: 0, after: 0 }\n const next =\n position === 'prepend'\n ? { ...current, before: current.before + 1 }\n : { ...current, after: current.after + 1 }\n return { ...state, boundary: { ...state.boundary, [connection]: next } }\n}\n\n/**\n * A subscriber is woken only if the event changed a field it selects. A\n * change to an unselected field is skipped entirely.\n */\nexport const shouldWake = (\n changed: ReadonlyArray<string>,\n selected: ReadonlyArray<string>,\n): boolean => changed.some(field => selected.includes(field))\n\nexport interface EntityApplied {\n readonly state: LiveState\n readonly store: EntityStore\n readonly outcome: LiveOutcome\n}\n\nexport const applyEntityEvent = (\n state: LiveState,\n store: EntityStore,\n event: Extract<LiveEvent, { _tag: 'EntityPatched' | 'EntityDeleted' }>,\n now = 0,\n): EntityApplied => {\n const outcome = classifyLive(state, event.cursor)\n if (outcome !== 'applied') return { state, store, outcome }\n const key = entityKey(event.ref.entity, event.ref.id)\n const next =\n event._tag === 'EntityPatched'\n ? writeEntity(store, key, event.values, now)\n : tombstone(store, key)\n return { state: advance(state, event.cursor), store: next, outcome }\n}\n\nexport interface ConnectionApplied {\n readonly state: LiveState\n readonly optimistic: OptimisticState\n readonly outcome: LiveOutcome\n /**\n * A connection the event says to refetch. Reported rather than recorded here,\n * because staleness lives on the connection in the Model — which is what the\n * planner and every read consult. It used to be written into a set on this\n * live state that nothing read, so an invalidating event did nothing at all.\n */\n readonly invalidated?: string | undefined\n}\n\nconst removeEdgeOverlays = (\n optimistic: OptimisticState,\n connection: string,\n key: string,\n): OptimisticState => ({\n ...optimistic,\n overlays: optimistic.overlays.map(overlay =>\n overlay.connection !== connection || overlay.position === 'remove'\n ? overlay\n : { ...overlay, edges: overlay.edges.filter(edge => edge.key !== key) },\n ),\n})\n\nexport const applyConnectionEvent = (\n state: LiveState,\n optimistic: OptimisticState,\n event: Extract<\n LiveEvent,\n { _tag: 'ConnectionInsert' | 'ConnectionRemove' | 'ConnectionInvalidate' }\n >,\n policy: LivePolicy = {},\n): ConnectionApplied => {\n const outcome = classifyLive(state, event.cursor)\n if (outcome !== 'applied') return { state, optimistic, outcome }\n\n switch (event._tag) {\n case 'ConnectionInsert': {\n const selection: LiveInsertion =\n (event.position === 'prepend' ? policy.prepend : policy.append) ?? 'visible'\n switch (selection) {\n case 'visible':\n return {\n state: advance(state, event.cursor),\n optimistic: addOverlay(optimistic, {\n id: `live:${event.cursor}`,\n connection: event.connection,\n edges: [event.edge],\n position: event.position,\n }),\n outcome,\n }\n case 'boundary':\n return {\n state: recordBoundary(advance(state, event.cursor), event.connection, event.position),\n optimistic,\n outcome,\n }\n case 'invalidate':\n return {\n state: advance(state, event.cursor),\n optimistic,\n outcome,\n invalidated: event.connection,\n }\n case 'ignore':\n return { state: advance(state, event.cursor), optimistic, outcome }\n }\n }\n case 'ConnectionRemove':\n // Strip the edge from pending inserts and hide it wherever else it is\n // (a server-known segment included) until a fresh page says otherwise.\n return {\n state: advance(state, event.cursor),\n optimistic: addOverlay(removeEdgeOverlays(optimistic, event.connection, event.edge.key), {\n id: `live:${event.cursor}`,\n connection: event.connection,\n edges: [event.edge],\n position: 'remove',\n }),\n outcome,\n }\n case 'ConnectionInvalidate':\n return {\n state: advance(state, event.cursor),\n invalidated: event.connection,\n optimistic,\n outcome,\n }\n }\n}\n\n/** `hasPrevious` accounting for edges recorded outside the loaded boundary. */\nexport const liveHasPrevious = (\n connection: Connection,\n state: LiveState,\n connectionId: string,\n): boolean => hasPrevious(connection) || (state.boundary[connectionId]?.before ?? 0) > 0\n\n/** `hasNext` accounting for edges recorded outside the loaded boundary. */\nexport const liveHasNext = (\n connection: Connection,\n state: LiveState,\n connectionId: string,\n): boolean => hasNext(connection) || (state.boundary[connectionId]?.after ?? 0) > 0\n","/**\n * The pure requirement planner.\n *\n * A `Requirement` is plain data: which entity fields a Remote projection needs,\n * and through `relations`, which fields of each relation's target. `plan` diffs\n * requirements against the store and returns only the missing fields, grouped\n * and deterministically ordered. A relation whose field is being fetched keeps\n * its nested requirement on the request, so the server resolves the graph in\n * one read; a relation whose refs the store already holds is followed into\n * concrete requirements for the targets. Time enters through `PlanFreshness`,\n * never from ambient state; `force` plans every field.\n */\nimport { stableStringify } from './query.js'\nimport { targetsOf } from './relation.js'\nimport { Requirement, type RelationRequirement } from './requirement.js'\nimport { entityKey, missingFields, readField, type EntityStore } from './store.js'\n\ntype Window = NonNullable<Requirement['windows']>[string]\n\n/** A stable key for a window, so two equal windows compare equal. */\nexport const windowKey = (window: Window): string => stableStringify(window)\n\nexport interface PlanFreshness {\n readonly now: number\n /** A present entry older than this many milliseconds is refreshed whole. */\n readonly freshness: number\n}\n\nexport interface PlanOptions {\n readonly freshness?: PlanFreshness | undefined\n /** Plan every requested field, present or not, tombstoned or not. */\n readonly force?: boolean | undefined\n}\n\nconst pickFields = <T>(\n record: Readonly<Record<string, T>> | undefined,\n fields: ReadonlySet<string>,\n): Readonly<Record<string, T>> | undefined => {\n if (record === undefined) return undefined\n const picked = Object.fromEntries(Object.entries(record).filter(([field]) => fields.has(field)))\n return Object.keys(picked).length === 0 ? undefined : picked\n}\n\n/** The concrete requirements a known relation value contributes for its targets. */\nconst followRelation = (\n value: unknown,\n relation: RelationRequirement,\n): ReadonlyArray<Requirement> =>\n targetsOf(value, relation).map(ref => ({ ...relation, id: ref.id }))\n\nexport const plan = (\n store: EntityStore,\n requirements: readonly Requirement[],\n options: PlanOptions = {},\n): ReadonlyArray<Requirement> => {\n const { freshness, force = false } = options\n const planned: Requirement[] = []\n const followed: Requirement[] = []\n\n for (const group of Requirement.merge(requirements)) {\n const key = entityKey(group.entity, group.id)\n const entry = store[key]\n const expired =\n freshness !== undefined &&\n entry !== undefined &&\n !entry.tombstone &&\n freshness.now - entry.updatedAt > freshness.freshness\n const windowKeys = Object.fromEntries(\n Object.entries(group.windows ?? {}).map(([field, window]) => [field, windowKey(window)]),\n )\n const missing =\n force || expired ? group.fields : missingFields(store, key, group.fields, windowKeys)\n const missingSet = new Set(missing)\n\n // A relation the store already holds is followed into its targets; one\n // being fetched rides on the request instead.\n for (const [field, relation] of Object.entries(group.relations ?? {})) {\n if (missingSet.has(field)) continue\n const value = readField(store, key, field)\n if (value._tag === 'Some') followed.push(...followRelation(value.value, relation))\n }\n\n if (missing.length === 0) continue\n // Only a field being fetched carries its window and its relation.\n const windows = pickFields(group.windows, missingSet)\n const relations = pickFields(group.relations, missingSet)\n planned.push({\n entity: group.entity,\n id: group.id,\n fields: missing,\n ...(windows === undefined ? {} : { windows }),\n ...(relations === undefined ? {} : { relations }),\n })\n }\n\n const nested = followed.length === 0 ? [] : plan(store, followed, options)\n return [...Requirement.merge([...planned, ...nested])].sort((a, b) =>\n entityKey(a.entity, a.id) < entityKey(b.entity, b.id) ? -1 : 1,\n )\n}\n","/**\n * Cache lifetime. Retention roots are the requirements (and connections) the\n * application's active Surfaces observe; `gc` keeps what they reach through\n * the store's refs plus every pending optimistic change, and drops the rest.\n * Roots live outside the Model, so GC arrives as a Message.\n */\nimport type { RelationRequirement, Requirement } from './requirement.js'\nimport { refsIn } from './relation.js'\nimport { entityKey, readField, type EntityKey, type EntityStore } from './store.js'\nimport type { Connection } from './connection.js'\nimport type { OptimisticState } from './optimistic.js'\nimport type { MutationState } from './mutation.js'\n\n/** A connection to keep: its identity, and what a page of it selects of each item, if a projection reads it. */\nexport interface ConnectionRoot {\n readonly identity: string\n readonly select?: RelationRequirement | undefined\n}\n\nexport interface RetentionRoots {\n readonly requirements: ReadonlyArray<Requirement>\n /** Connections (`QueryRef.identity`) to keep, with their edges' targets and what `select` reaches through them. */\n readonly connections: ReadonlyArray<ConnectionRoot>\n}\n\nexport interface Retained {\n readonly entities: EntityStore\n readonly connections: Readonly<Record<string, Connection>>\n readonly optimistic: OptimisticState\n}\n\n/**\n * The entity keys the roots reach: each root entity, the targets its retained\n * fields refer to, and recursively the targets a nested relation selects.\n */\nexport const reachable = (\n store: EntityStore,\n roots: RetentionRoots,\n connections: Readonly<Record<string, Connection>>,\n optimistic: OptimisticState,\n pending: ReadonlySet<string>,\n): ReadonlySet<EntityKey> => {\n const kept = new Set<EntityKey>()\n const rootConnections = new Set(roots.connections.map(root => root.identity))\n // A target is walked once per relation spec that reaches it: two specs may\n // select different nested relations of the same entity, and a spec tree is\n // finite, so this terminates on cyclic data too.\n const walked = new Map<EntityKey, Set<Omit<Requirement, 'id'>>>()\n const visit = (key: EntityKey, requirement: Omit<Requirement, 'id'>): void => {\n kept.add(key)\n const seen = walked.get(key) ?? new Set()\n if (seen.has(requirement)) return\n seen.add(requirement)\n walked.set(key, seen)\n for (const field of requirement.fields) {\n const value = readField(store, key, field)\n if (value._tag === 'None') continue\n const relation = requirement.relations?.[field]\n for (const ref of refsIn(value.value)) {\n const target = entityKey(ref.entity, ref.id)\n if (relation === undefined || ref.entity !== relation.entity) {\n kept.add(target)\n continue\n }\n visit(target, relation)\n }\n }\n }\n for (const root of roots.requirements) visit(entityKey(root.entity, root.id), root)\n // A connection root keeps its edges' targets, and what a page's `select`\n // reaches through them (an item's owner, say), so the page stays readable.\n for (const { identity, select } of roots.connections) {\n for (const segment of connections[identity]?.segments ?? []) {\n for (const edge of segment.edges) {\n const target = entityKey(edge.ref.entity, edge.ref.id)\n if (select === undefined || edge.ref.entity !== select.entity) kept.add(target)\n else visit(target, select)\n }\n }\n }\n // A pending request's changes are kept whole; a settled overlay (a live or\n // confirmed insert) is kept only with a retained connection, below.\n for (const layer of optimistic.layers) {\n if (!pending.has(layer.id)) continue\n for (const patch of layer.patches) kept.add(entityKey(patch.entity, patch.id))\n }\n for (const overlay of optimistic.overlays) {\n if (!pending.has(overlay.id) && !rootConnections.has(overlay.connection)) continue\n for (const edge of overlay.edges) kept.add(entityKey(edge.ref.entity, edge.ref.id))\n }\n return kept\n}\n\n/**\n * Drops every entity the roots do not reach, every connection they do not\n * name, and every settled overlay on a dropped connection, keeping whatever a\n * pending request's layer or overlays touch. Pure.\n */\nexport const gc = (\n state: Retained & { readonly mutations: MutationState },\n roots: RetentionRoots,\n): Retained => {\n const pending = state.mutations.pending\n const kept = reachable(state.entities, roots, state.connections, state.optimistic, pending)\n const entities = Object.fromEntries(\n Object.entries(state.entities).filter(([key]) => kept.has(key)),\n )\n const keptConnections = new Set([\n ...roots.connections.map(root => root.identity),\n ...state.optimistic.overlays\n .filter(overlay => pending.has(overlay.id))\n .map(overlay => overlay.connection),\n ])\n const connections = Object.fromEntries(\n Object.entries(state.connections).filter(([identity]) => keptConnections.has(identity)),\n )\n const optimistic: OptimisticState = {\n layers: state.optimistic.layers,\n overlays: state.optimistic.overlays.filter(\n overlay => pending.has(overlay.id) || keptConnections.has(overlay.connection),\n ),\n }\n return { entities, connections, optimistic }\n}\n","/**\n * Remote cache persistence: a snapshot of the entity store and nothing else.\n * Runtime state (connections' live cursors, optimistic layers, the mutation\n * ledger, gaps, retention roots) is never in a snapshot; it belongs to the\n * session that produced it.\n *\n * The cache is server-derived and disposable: an incompatible, oversized, or\n * corrupt snapshot is discarded (and removed from a `KeyValueStore`) so the\n * planner refetches. `dehydrate`/`hydrate` are the string forms, for SSR and\n * any other transport; `save`/`restore` put them behind Effect's\n * `KeyValueStore`, so the backend (memory, filesystem, SQL, Web Storage) is the\n * application's choice.\n */\nimport { Effect } from 'effect'\nimport { KeyValueStore } from 'effect/unstable/persistence'\nimport { items, type Connection, type Edge } from './connection.js'\nimport { connectionIdentity, type ConnectionIdentity } from './optimistic.js'\nimport { stableStringify } from './query.js'\nimport { emptyStore, type EntityEntry, type EntityStore } from './store.js'\n\n/** Bump when the serialized shape changes; a mismatch discards the cache. */\nexport const REMOTE_CACHE_VERSION = 4\n\n/**\n * What survives a reload: the entity cache, and the connections an application\n * **declared** should come back.\n *\n * Connections are session state by default and stay that way — `snapshotOf`\n * takes none unless asked. What a declared one keeps is its **edges and\n * nothing else**, which is not a simplification but the rule: a connection's\n * boundaries are cursors the server minted, and a cursor may name server state\n * that no longer exists. Restoring one would be claiming to know where the\n * page ends. The shape has nowhere to put a cursor, so that cannot be got\n * wrong later.\n */\nexport interface Snapshot {\n readonly entities: EntityStore\n /**\n * By connection identity: its **segments**, each a run of edges. No\n * boundaries.\n *\n * Segments rather than one flat list, because the gaps between them are\n * knowledge too. A connection paged from both ends holds a head and a tail\n * with an unfetched middle; flattening those into one run would claim the\n * tail's first row follows the head's last, which is a thing the client was\n * never told.\n */\n readonly connections: Readonly<Record<string, ReadonlyArray<ReadonlyArray<Edge>>>>\n}\n\n/**\n * A snapshot of a Model, keeping the entity cache and only the connections\n * named.\n *\n * Naming none — the default — is exactly what Remote did before connections\n * could be kept at all: a disposable, server-derived cache.\n */\nconst snapshotOf = (\n model: {\n readonly entities: EntityStore\n readonly connections: Readonly<Record<string, Connection>>\n },\n options: { readonly connections?: ReadonlyArray<ConnectionIdentity> | undefined } = {},\n): Snapshot => ({\n entities: model.entities,\n connections: Object.fromEntries(\n (options.connections ?? []).flatMap(connection => {\n const identity = connectionIdentity(connection)\n const held = model.connections[identity]\n return held === undefined\n ? []\n : [[identity, held.segments.map(segment => segment.edges)] as const]\n }),\n ),\n})\n\nexport interface SnapshotOptions {\n /**\n * Who or what the snapshot is for (a user id, a tenant, a build). A snapshot\n * taken under another scope is discarded rather than shown to the wrong\n * reader. Default: unscoped, which only matches unscoped.\n */\n readonly scope?: string | undefined\n /** Snapshots larger than this many bytes are not written and not read. */\n readonly maxBytes?: number | undefined\n}\n\n/** How a snapshot meets a store that already has entries. */\nexport type MergePolicy = 'replace' | 'preserve-existing'\n\ninterface SerializedEntry {\n readonly values: Readonly<Record<string, unknown>>\n readonly present: ReadonlyArray<string>\n readonly stale: ReadonlyArray<string>\n readonly tombstone: boolean\n readonly updatedAt: number\n readonly windows: Readonly<Record<string, string>>\n}\n\ninterface SerializedStore {\n readonly version: number\n readonly scope: string | null\n readonly entities: Readonly<Record<string, SerializedEntry>>\n readonly connections: Readonly<Record<string, ReadonlyArray<ReadonlyArray<Edge>>>>\n}\n\nconst sorted = <T>(values: Iterable<T>): T[] => [...values].sort()\n\n/**\n * The snapshot's data shape. `stableStringify` sorts object keys, and the\n * field sets are sorted here, so equal stores give byte-equal snapshots\n * whatever order they were built in.\n */\nconst serializeStore = (snapshot: Snapshot, scope?: string): SerializedStore => ({\n version: REMOTE_CACHE_VERSION,\n scope: scope ?? null,\n connections: snapshot.connections,\n entities: Object.fromEntries(\n Object.entries(snapshot.entities).map(([key, entry]) => [\n key,\n {\n values: entry.values,\n present: sorted(entry.present),\n stale: sorted(entry.stale),\n tombstone: entry.tombstone,\n updatedAt: entry.updatedAt,\n windows: entry.windows,\n },\n ]),\n ),\n})\n\nconst isStringArray = (value: unknown): value is ReadonlyArray<string> =>\n Array.isArray(value) && value.every(item => typeof item === 'string')\n\nconst isStringRecord = (value: unknown): value is Readonly<Record<string, string>> =>\n value !== null &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n Object.values(value as Record<string, unknown>).every(item => typeof item === 'string')\n\n/** Throws on a malformed entry so the whole snapshot is discarded. */\nconst parseEntry = (value: unknown): EntityEntry => {\n if (value === null || typeof value !== 'object') throw new Error('entry is not an object')\n const entry = value as Record<string, unknown>\n if (entry.values === null || typeof entry.values !== 'object' || Array.isArray(entry.values)) {\n throw new Error('entry.values is not a record')\n }\n if (!isStringArray(entry.present)) throw new Error('entry.present is not a string array')\n if (!isStringArray(entry.stale)) throw new Error('entry.stale is not a string array')\n if (typeof entry.tombstone !== 'boolean') throw new Error('entry.tombstone is not a boolean')\n if (typeof entry.updatedAt !== 'number') throw new Error('entry.updatedAt is not a number')\n if (!isStringRecord(entry.windows)) throw new Error('entry.windows is not a string record')\n return {\n values: entry.values as Readonly<Record<string, unknown>>,\n present: new Set(entry.present),\n stale: new Set(entry.stale),\n tombstone: entry.tombstone,\n updatedAt: entry.updatedAt,\n windows: entry.windows,\n }\n}\n\n/** Throws on a malformed edge so the whole snapshot is discarded. */\nconst parseEdges = (value: unknown): ReadonlyArray<Edge> => {\n if (!Array.isArray(value)) throw new Error('segment is not an array of edges')\n return value.map(edge => {\n const candidate = edge as { key?: unknown; ref?: { entity?: unknown; id?: unknown } }\n if (\n typeof candidate.key !== 'string' ||\n typeof candidate.ref?.entity !== 'string' ||\n typeof candidate.ref?.id !== 'string'\n ) {\n throw new Error('edge is not { key, ref: { entity, id } }')\n }\n return { key: candidate.key, ref: { entity: candidate.ref.entity, id: candidate.ref.id } }\n })\n}\n\nconst deserializeStore = (serialized: SerializedStore): Snapshot => ({\n entities: Object.fromEntries(\n Object.entries(serialized.entities).map(([key, entry]) => [key, parseEntry(entry)]),\n ),\n connections: Object.fromEntries(\n Object.entries(serialized.connections ?? {}).map(([key, segments]) => {\n if (!Array.isArray(segments)) throw new Error('connection is not an array of segments')\n return [key, segments.map(parseEdges)]\n }),\n ),\n})\n\n/**\n * The snapshot text, or `undefined` when it would exceed `maxBytes`. Build the\n * snapshot with `snapshotOf`, which is where the connections that survive are\n * named; runtime state — optimistic layers, live cursors, gaps, the mutation\n * ledger — is never in one.\n */\nfunction dehydrate(\n snapshot: Snapshot,\n options?: SnapshotOptions & { readonly maxBytes?: undefined },\n): string\nfunction dehydrate(snapshot: Snapshot, options?: SnapshotOptions): string | undefined\nfunction dehydrate(snapshot: Snapshot, options: SnapshotOptions = {}): string | undefined {\n const text = stableStringify(serializeStore(snapshot, options.scope))\n return exceeds(text, options.maxBytes) ? undefined : text\n}\n\n/**\n * Whether the UTF-8 size of `text` exceeds `maxBytes`. A character is one to\n * three bytes, so most texts are decided from their length alone; only the\n * rest are measured.\n */\nconst exceeds = (text: string, maxBytes: number | undefined): boolean => {\n if (maxBytes === undefined) return false\n if (text.length > maxBytes) return true\n if (text.length * 3 <= maxBytes) return false\n return new TextEncoder().encode(text).length > maxBytes\n}\n\n/**\n * The store a snapshot text holds, or `undefined` when the text is missing,\n * oversized, not this version, for another scope, or malformed. Hydrating the\n * same text twice yields equal stores.\n */\nconst hydrate = (\n raw: string | undefined | null,\n options: SnapshotOptions = {},\n): Snapshot | undefined => {\n if (raw === undefined || raw === null) return undefined\n if (exceeds(raw, options.maxBytes)) return undefined\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n return undefined\n }\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return undefined\n const candidate = parsed as {\n readonly version?: unknown\n readonly scope?: unknown\n readonly entities?: unknown\n }\n if (candidate.version !== REMOTE_CACHE_VERSION) return undefined\n if ((candidate.scope ?? null) !== (options.scope ?? null)) return undefined\n if (candidate.entities === null || typeof candidate.entities !== 'object') return undefined\n if (Array.isArray(candidate.entities)) return undefined\n try {\n return deserializeStore(candidate as SerializedStore)\n } catch {\n return undefined\n }\n}\n\n/**\n * Brings a snapshot into a store that may already hold entries. `replace`\n * takes the snapshot's entry for every key it has; `preserve-existing` keeps\n * an entry the current store already has (it is at least as fresh as a\n * snapshot taken earlier). Either way, keys only the current store has stay.\n */\nconst mergeStores = (\n current: EntityStore,\n snapshot: EntityStore,\n policy: MergePolicy,\n): EntityStore => (policy === 'replace' ? { ...current, ...snapshot } : { ...snapshot, ...current })\n\n/** An empty snapshot: the cache as a fresh session has it. */\nconst emptySnapshot: Snapshot = { entities: emptyStore, connections: {} }\n\nexport const RemotePersistence = {\n /** The snapshot text, or `undefined` when it would exceed `maxBytes`. */\n dehydrate,\n /** What a snapshot text holds, or `undefined` when it is refused. */\n hydrate,\n /**\n * What to keep of a Model, naming the connections that should survive a\n * reload. Naming none is the default and is what Remote always did.\n */\n snapshotOf,\n /** A snapshot's entities brought into a store by policy. */\n mergeStores,\n /** The cache as a fresh session has it; what a refused `restore` yields. */\n emptySnapshot,\n\n /**\n * Writes the snapshot under `key`, or removes the key when the store would\n * exceed `maxBytes`, so a stale smaller snapshot cannot outlive a larger\n * store it no longer describes.\n */\n save: (snapshot: Snapshot, options: { readonly key: string } & SnapshotOptions) =>\n Effect.gen(function* () {\n const kv = yield* KeyValueStore.KeyValueStore\n const text = dehydrate(snapshot, options)\n if (text === undefined) yield* kv.remove(options.key)\n else yield* kv.set(options.key, text)\n }),\n\n /**\n * Reads the cache. A missing key yields `emptySnapshot`; anything `hydrate`\n * refuses yields `emptySnapshot` and removes the key, so the next `restore`\n * is clean and the planner refetches.\n */\n restore: (options: { readonly key: string } & SnapshotOptions) =>\n Effect.gen(function* () {\n const kv = yield* KeyValueStore.KeyValueStore\n const raw = yield* kv.get(options.key)\n if (raw === undefined) return emptySnapshot\n const restored = hydrate(raw, options)\n if (restored === undefined) {\n yield* kv.remove(options.key)\n return emptySnapshot\n }\n return restored\n }),\n}\n","/** `RemoteData`: the state of a value the store may not hold yet. */\nimport { Option, Schema } from 'effect'\n\nexport interface RemoteError {\n readonly _tag: string\n readonly message: string\n}\n\nexport type RemoteData<A> =\n | { readonly _tag: 'Initial' }\n | { readonly _tag: 'Loading' }\n | { readonly _tag: 'Ready'; readonly value: A }\n | { readonly _tag: 'Refreshing'; readonly value: A }\n | { readonly _tag: 'Failed'; readonly error: RemoteError; readonly previous?: A }\n | { readonly _tag: 'NotFound' }\n\n/**\n * What `RemoteData.render` tells the `data` branch about the value it is\n * given: whether a newer answer is on its way, and whether this one is what\n * was last known good before a read failed. It is one tag rather than two\n * booleans because a value cannot be both at once, and a type that can say so\n * invites a view to handle a state that never arrives.\n */\nexport type Freshness =\n | { readonly _tag: 'Fresh' }\n | { readonly _tag: 'Refreshing' }\n | { readonly _tag: 'Stale'; readonly error: RemoteError }\n\nconst fresh: Freshness = { _tag: 'Fresh' }\nconst refreshing: Freshness = { _tag: 'Refreshing' }\n\nexport const remoteErrorSchema = Schema.Struct({ _tag: Schema.String, message: Schema.String })\n\n/** A `RemoteData` schema, so a projection that reads remote state is typed. */\n// A projection is rebuilt on every Model change (a Surface's `model` callback\n// runs per dependency computation), so the schema for a value schema is built\n// once and shared: the value schema is a module-level constant in practice.\nconst remoteDataSchemas = new WeakMap<object, Schema.Schema<unknown>>()\n\nexport const remoteDataSchema = <A>(\n value: Schema.Schema<A>,\n): Schema.Codec<RemoteData<A>, unknown> => {\n const cached = remoteDataSchemas.get(value)\n if (cached !== undefined) return cached as Schema.Codec<RemoteData<A>, unknown>\n const built = Schema.Union([\n Schema.Struct({ _tag: Schema.Literal('Initial') }),\n Schema.Struct({ _tag: Schema.Literal('Loading') }),\n Schema.Struct({ _tag: Schema.Literal('Ready'), value }),\n Schema.Struct({ _tag: Schema.Literal('Refreshing'), value }),\n Schema.Struct({\n _tag: Schema.Literal('Failed'),\n error: remoteErrorSchema,\n previous: Schema.optional(value),\n }),\n Schema.Struct({ _tag: Schema.Literal('NotFound') }),\n ]) as unknown as Schema.Codec<RemoteData<A>, unknown>\n remoteDataSchemas.set(value, built as Schema.Schema<unknown>)\n return built\n}\n\nexport const RemoteData = {\n /**\n * The `RemoteData` schema for a value schema. Exposed so a `RemoteData` can\n * be embedded in a hand-written Model schema, not only through `Remote.select`.\n */\n schema: <A>(value: Schema.Schema<A>): Schema.Schema<RemoteData<A>> => remoteDataSchema(value),\n\n /** Exhaustive: omitting a state is a compile error. */\n match: <A, R>(\n data: RemoteData<A>,\n cases: {\n readonly Initial: () => R\n readonly Loading: () => R\n readonly Ready: (value: A) => R\n readonly Refreshing: (value: A) => R\n readonly Failed: (error: RemoteError, previous: Option.Option<A>) => R\n readonly NotFound: () => R\n },\n ): R => {\n switch (data._tag) {\n case 'Initial':\n return cases.Initial()\n case 'Loading':\n return cases.Loading()\n case 'Ready':\n return cases.Ready(data.value)\n case 'Refreshing':\n return cases.Refreshing(data.value)\n case 'Failed':\n return cases.Failed(\n data.error,\n data.previous === undefined ? Option.none() : Option.some(data.previous),\n )\n case 'NotFound':\n return cases.NotFound()\n }\n },\n\n /**\n * The view-oriented fold: the six states as the three things a view actually\n * draws, under the policy that useful data stays on screen. A value that is\n * being refetched, or that a later read failed to replace, still reaches\n * `data` — with `freshness` saying which — instead of being replaced by a\n * spinner or an error the reader cannot act on.\n *\n * ```ts\n * RemoteData.render(model.user, {\n * loading: () => UserSkeleton(),\n * notFound: () => NoSuchUser(),\n * failed: error => ErrorView(error),\n * data: (user, freshness) => UserView({ user, dimmed: freshness._tag !== 'Fresh' }),\n * })\n * ```\n *\n * `notFound` is its own branch and not optional: a row the server answered\n * for and does not have is neither loading nor a failure, and drawing it as\n * either is a spinner that never ends or an error nobody can fix.\n *\n * This does not replace `match`, which is the exhaustive fold over the states\n * themselves. Reach for `match` when the six states really do draw\n * differently, and for this when they draw the usual three ways.\n */\n render: <A, R>(\n data: RemoteData<A>,\n cases: {\n readonly loading: () => R\n readonly notFound: () => R\n readonly failed: (error: RemoteError) => R\n readonly data: (value: A, freshness: Freshness) => R\n },\n ): R => {\n switch (data._tag) {\n case 'Initial':\n case 'Loading':\n return cases.loading()\n case 'NotFound':\n return cases.notFound()\n case 'Ready':\n return cases.data(data.value, fresh)\n case 'Refreshing':\n return cases.data(data.value, refreshing)\n case 'Failed':\n return data.previous === undefined\n ? cases.failed(data.error)\n : cases.data(data.previous, { _tag: 'Stale', error: data.error })\n }\n },\n\n map: <A, B>(data: RemoteData<A>, f: (value: A) => B): RemoteData<B> => {\n switch (data._tag) {\n case 'Ready':\n return { _tag: 'Ready', value: f(data.value) }\n case 'Refreshing':\n return { _tag: 'Refreshing', value: f(data.value) }\n case 'Failed':\n return data.previous === undefined\n ? { _tag: 'Failed', error: data.error }\n : { _tag: 'Failed', error: data.error, previous: f(data.previous) }\n default:\n return data\n }\n },\n}\n","/**\n * The Remote submodel: the store, connections, mutations, live state, and\n * optimistic layers an application keeps in its Model, the Messages that\n * change it, and the pure reducer over them.\n */\nimport { Schema } from 'effect'\nimport type { RelationRequirement, Requirement } from './requirement.js'\nimport {\n emptyConnection,\n merge,\n unknown as unknownBoundary,\n type Connection,\n type Edge,\n type Segment,\n} from './connection.js'\nimport {\n beginOptimistic,\n emptyOptimistic,\n pruneOverlays,\n settleFailure,\n settleSuccess,\n type ConnectionChange,\n type OptimisticState,\n type OptimisticOperation,\n} from './optimistic.js'\nimport {\n applyConnectionEvent,\n applyEntityEvent,\n emptyLiveState,\n type LiveEvent,\n type LiveState,\n} from './live.js'\nimport {\n beginMutation,\n emptyMutationState,\n failMutation,\n type MutationState,\n type NormalizedPatch,\n} from './mutation.js'\nimport {\n entityKey,\n emptyStore,\n isTombstone,\n readField,\n remove,\n setStale,\n tombstone,\n writeEntities,\n type EntityStore,\n type EntityWrite,\n} from './store.js'\nimport { windowKey } from './plan.js'\nimport { isRefPage, targetsOf, type RefPageValue } from './relation.js'\nimport { gc, reachable, type Retained, type RetentionRoots } from './retain.js'\nimport { RemotePersistence, type MergePolicy } from './persistence.js'\nimport { NormalizedEntity, ReadBatchResult, ReadRequest, RelationRequest } from './wire.js'\nimport { remoteErrorSchema, type RemoteError } from './remoteData.js'\nimport type { LivePolicy } from './query.js'\n\n/**\n * The normalized cache as a Foldkit Submodel. `Remote.define` returns a schema\n * and an `update` for this shape; `updateRemote` reconciles every producer.\n */\nexport interface RemoteModel {\n /** Entity values, presence, staleness, tombstones, and applied windows. */\n readonly entities: EntityStore\n /** Normalized ordered connections, keyed by connection identity. */\n readonly connections: Readonly<Record<string, Connection>>\n /** Optimistic entity layers and connection overlays over the base store. */\n readonly optimistic: OptimisticState\n /** Live cursor and boundary state, keyed by the subscription's stream key. */\n readonly live: Readonly<Record<string, LiveState>>\n /** Mutation pending/applied/failed ledger. */\n readonly mutations: MutationState\n /** Streams whose live cursor fell behind; the caller should resync or refetch. */\n readonly gaps: ReadonlySet<string>\n /**\n * The `entity\\0id\\0field` marks a read is currently fetching. A field absent\n * from the store reads as `Loading` while its mark is here and `Initial`\n * otherwise, which is what separates \"being fetched\" from \"nothing is\n * fetching this\".\n */\n readonly loading: ReadonlySet<string>\n /**\n * `Remote.refresh` generations, held per field rather than for the store as a\n * whole. A read entry restarts when the generation over the fields it plans\n * moves, so a read sent before a refresh of its own fields cannot land after\n * it, and a refresh of one field leaves every other entry's read alone.\n */\n readonly refresh: RefreshState\n /**\n * The reads that failed and have not been settled since, so a read can say\n * `Failed` rather than `Initial`.\n *\n * Without them a read that failed before anything loaded read exactly like\n * one nobody had asked for, and nothing asked again: a read entry restarts\n * only when what it plans changes, and a failure changed nothing. What failed\n * is not planned again on its own either, so a persistent error is not\n * retried every time an unrelated read restarts the entry. `Remote.refresh`\n * is how a view retries.\n */\n readonly failures: Failures\n}\n\n/**\n * Failed reads, as the errors they failed with.\n *\n * `connections` is by connection identity, and is settled by a page arriving,\n * an invalidation, or retention dropping the connection. `fields` is by field\n * mark (`entity\\0id\\0field`, the marks `loading` uses), and is settled by the\n * field being written again, a refresh asking for it, or retention dropping the\n * entity. A read of it in flight reads `Loading` over the failure without\n * settling it: if that read fails too, the failure is simply recorded again.\n */\nexport interface Failures {\n readonly connections: Readonly<Record<string, RemoteError>>\n readonly fields: Readonly<Record<string, RemoteError>>\n}\n\nexport const noFailures: Failures = { connections: {}, fields: {} }\n\n/**\n * `Remote.refresh` generations, per field mark. `generation` is the last one\n * handed out; `requested` is when each field was last refreshed, and `started`\n * is the generation each field's read last began under. Holding them per field\n * is what keeps one Projection's refresh from restarting every read entry.\n */\nexport interface RefreshState {\n readonly generation: number\n readonly requested: ReadonlyMap<string, number>\n readonly started: ReadonlyMap<string, number>\n}\n\nexport const emptyRefresh: RefreshState = {\n generation: 0,\n requested: new Map(),\n started: new Map(),\n}\n\nexport const initialRemoteModel: RemoteModel = {\n entities: emptyStore,\n connections: {},\n optimistic: emptyOptimistic,\n live: {},\n mutations: emptyMutationState,\n gaps: new Set(),\n loading: new Set(),\n refresh: emptyRefresh,\n failures: noFailures,\n}\n\n/** The entity store and the mutation ledger are runtime values, not wire shapes. */\nconst runtimeSchema = Schema.Unknown\n\nexport const remoteModelSchema = (): Schema.Codec<RemoteModel, unknown> =>\n // The runtime fields decode as `unknown`; their types come from `RemoteModel`.\n Schema.Struct({\n entities: runtimeSchema,\n connections: Schema.Record(Schema.String, runtimeSchema),\n optimistic: runtimeSchema,\n live: Schema.Record(Schema.String, runtimeSchema),\n mutations: runtimeSchema,\n gaps: runtimeSchema,\n loading: runtimeSchema,\n refresh: runtimeSchema,\n failures: Schema.Struct({\n connections: Schema.Record(Schema.String, remoteErrorSchema),\n fields: Schema.Record(Schema.String, remoteErrorSchema),\n }),\n }) as unknown as Schema.Codec<RemoteModel, unknown>\n\n/** The submodel's Messages; each reduces to `RemoteModel` through `updateRemote`. */\nexport type RemoteMessage =\n | {\n readonly _tag: 'ReadReceived'\n readonly requests: readonly Requirement[]\n readonly result: Schema.Schema.Type<typeof ReadBatchResult>\n readonly now: number\n }\n | {\n readonly _tag: 'ReadFailed'\n readonly requests: readonly Requirement[]\n readonly error: RemoteError\n /**\n * The live stream whose subscription broke, when this is that rather\n * than a read. Nothing was being read, so no field failed: the stream is\n * recorded as a gap, since changes after it are missed until the host\n * resubscribes.\n */\n readonly stream?: string | undefined\n }\n /** A refetch of present fields began; they read as `Refreshing` until it lands. */\n | { readonly _tag: 'RefreshStarted'; readonly requests: readonly Requirement[] }\n /** A read began; the fields it asks for that the store lacks read as `Loading`. */\n | {\n readonly _tag: 'ReadStarted'\n readonly requests: readonly Requirement[]\n /** The refresh generation the read was planned under. */\n readonly refresh?: number | undefined\n }\n /**\n * Queries for these connections were sent. One with nothing to show reads\n * `Loading` until its page or its failure arrives, which is what separates\n * \"being fetched\" from `Initial`, \"nothing is fetching this\".\n */\n | { readonly _tag: 'QueryStarted'; readonly connections: readonly string[] }\n /** The active Surfaces' roots changed; everything they do not reach is collected. */\n | { readonly _tag: 'RetentionChanged'; readonly roots: RetentionRoots }\n /** A restored snapshot meets the store; runtime state is untouched. */\n | {\n readonly _tag: 'Hydrated'\n readonly entities: EntityStore\n /**\n * The connections a snapshot declared should survive, as their edges.\n * Restored with **unknown** boundaries and marked stale: the rows show\n * at once and the connection is refetched, because a persisted cursor\n * may name server state that is gone.\n */\n readonly connections?:\n Readonly<Record<string, ReadonlyArray<ReadonlyArray<Edge>>>> | undefined\n readonly merge: MergePolicy\n }\n /** A mutation began; its optimistic operations show until it settles. */\n | {\n readonly _tag: 'MutationStarted'\n readonly requestId: string\n readonly optimistic?: ReadonlyArray<OptimisticOperation> | undefined\n }\n | {\n readonly _tag: 'MutationSucceeded'\n readonly requestId: string\n readonly entities: readonly NormalizedPatch[]\n /** Connection changes the server confirmed; they replace the request's own. */\n readonly connections?: ReadonlyArray<ConnectionChange> | undefined\n /** Entities the mutation deleted: tombstoned, which hides them from every connection. */\n readonly deleted?: ReadonlyArray<{ readonly entity: string; readonly id: string }> | undefined\n }\n | { readonly _tag: 'MutationFailed'; readonly requestId: string; readonly error: RemoteError }\n /**\n * Operations shown over the store with no request behind them, until they are\n * lifted: a preview of a change nobody has made. Showing an id again replaces\n * what it showed.\n */\n | {\n readonly _tag: 'OverlayShown'\n readonly id: string\n readonly optimistic: ReadonlyArray<OptimisticOperation>\n }\n | { readonly _tag: 'OverlayLifted'; readonly id: string }\n | {\n readonly _tag: 'LiveReceived'\n readonly stream: string\n readonly event: LiveEvent\n readonly policy?: LivePolicy\n readonly now: number\n }\n | { readonly _tag: 'GapCleared'; readonly stream: string }\n | {\n readonly _tag: 'ConnectionMerged'\n readonly connection: string\n readonly page: Segment\n /** The page answers the connection's refresh, so the merge also clears `stale`. */\n readonly refreshes?: boolean | undefined\n }\n | { readonly _tag: 'ConnectionInvalidated'; readonly connection: string }\n | { readonly _tag: 'ConnectionRefreshed'; readonly connection: string }\n /**\n * A query for the connection failed. Its pages stay as they were, and it\n * reads `Failed` — with them as `previous`, when it has any — until a page\n * arrives, it is invalidated, or retention drops it.\n */\n | { readonly _tag: 'QueryFailed'; readonly connection: string; readonly error: RemoteError }\n\nexport const retentionRootsSchema = Schema.Struct({\n requirements: Schema.Array(ReadRequest),\n connections: Schema.Array(\n Schema.Struct({ identity: Schema.String, select: Schema.optional(RelationRequest) }),\n ),\n})\n\n/**\n * The Messages' fields by tag, without `_tag`: what `defineMessageUnion` takes,\n * so an application spreads them into its own union (`Remote.messages`).\n */\nexport const remoteMessageCases = {\n ReadReceived: {\n requests: Schema.Array(ReadRequest),\n result: ReadBatchResult,\n now: Schema.Number,\n },\n ReadFailed: {\n requests: Schema.Array(ReadRequest),\n error: remoteErrorSchema,\n stream: Schema.optional(Schema.String),\n },\n RefreshStarted: { requests: Schema.Array(ReadRequest) },\n ReadStarted: { requests: Schema.Array(ReadRequest), refresh: Schema.optional(Schema.Number) },\n QueryStarted: { connections: Schema.Array(Schema.String) },\n RetentionChanged: { roots: retentionRootsSchema },\n Hydrated: {\n connections: Schema.optional(Schema.Unknown),\n entities: runtimeSchema,\n merge: Schema.Union([Schema.Literal('replace'), Schema.Literal('preserve-existing')]),\n },\n MutationStarted: {\n requestId: Schema.String,\n optimistic: Schema.optional(Schema.Array(Schema.Unknown)),\n },\n MutationSucceeded: {\n requestId: Schema.String,\n entities: Schema.Array(NormalizedEntity),\n connections: Schema.optional(Schema.Array(Schema.Unknown)),\n deleted: Schema.optional(\n Schema.Array(Schema.Struct({ entity: Schema.String, id: Schema.String })),\n ),\n },\n MutationFailed: { requestId: Schema.String, error: remoteErrorSchema },\n OverlayShown: { id: Schema.String, optimistic: Schema.Array(Schema.Unknown) },\n OverlayLifted: { id: Schema.String },\n LiveReceived: {\n stream: Schema.String,\n event: Schema.Unknown,\n policy: Schema.optional(Schema.Unknown),\n now: Schema.Number,\n },\n GapCleared: { stream: Schema.String },\n ConnectionMerged: {\n connection: Schema.String,\n page: Schema.Unknown,\n refreshes: Schema.optional(Schema.Boolean),\n },\n ConnectionInvalidated: { connection: Schema.String },\n ConnectionRefreshed: { connection: Schema.String },\n QueryFailed: { connection: Schema.String, error: remoteErrorSchema },\n} satisfies Record<RemoteMessage['_tag'], Schema.Struct.Fields>\n\nexport type RemoteMessageTag = RemoteMessage['_tag']\n\n/**\n * A Remote Message as an application's union constructs it from\n * `remoteMessageCases`: the same shape `RemoteMessage` names, with the runtime\n * slots (`entities`, `event`, `page`) typed `unknown` by their schemas.\n */\nexport type RemoteMessageInput = {\n [Tag in RemoteMessageTag]: { readonly _tag: Tag } & Schema.Struct.Type<\n (typeof remoteMessageCases)[Tag]\n >\n}[RemoteMessageTag]\n\n/**\n * Whether a Message is one of Remote's, by tag. Narrows an application's union\n * to its Remote cases, and its complement to the application's own.\n */\nexport const isRemoteMessage = <M extends { readonly _tag: string }>(\n message: M,\n): message is Extract<M, { readonly _tag: RemoteMessageTag }> =>\n Object.hasOwn(remoteMessageCases, message._tag)\n\nexport const remoteMessageSchema = Schema.Union(\n Object.entries(remoteMessageCases).map(([tag, fields]) =>\n Schema.Struct({ _tag: Schema.Literal(tag), ...fields }),\n ),\n) as unknown as Schema.Schema<RemoteMessage>\n\n/** An overlay's layer, named apart from every request's: a request id is the application's to choose too. */\nconst overlayLayer = (id: string): string => `overlay:${id}`\n\nconst marksOf = (\n requests: ReadonlyArray<Requirement>,\n): ReadonlyArray<readonly [string, ReadonlyArray<string>]> =>\n requests.map(request => [entityKey(request.entity, request.id), request.fields] as const)\n\n/**\n * One mark per requested field, `entity\\0id\\0field`. A read is identified by\n * what it asks for, not by a request id: two reads asking for one field share\n * its mark, so the first answer clears it. Over-clearing shows `Initial` rather\n * than a spinner, which is the safer way to be wrong. The refresh generations\n * below key off the same marks, so \"what a read asks for\" means one thing.\n */\nconst fieldMark = (entity: string, id: string, field: string): string =>\n `${entityKey(entity, id)}\\u0000${field}`\n\nconst fieldMarks = function* (requests: ReadonlyArray<Requirement>): Generator<string> {\n for (const request of requests) {\n for (const field of request.fields) yield fieldMark(request.entity, request.id, field)\n }\n}\n\nconst withLoading = (\n loading: ReadonlySet<string>,\n requests: ReadonlyArray<Requirement>,\n): ReadonlySet<string> => {\n const next = new Set(loading)\n for (const mark of fieldMarks(requests)) next.add(mark)\n return next\n}\n\nconst withoutLoading = (\n loading: ReadonlySet<string>,\n requests: ReadonlyArray<Requirement>,\n): ReadonlySet<string> => {\n if (loading.size === 0) return loading\n const next = new Set(loading)\n for (const mark of fieldMarks(requests)) next.delete(mark)\n return next\n}\n\n/**\n * A connection's mark. The leading separator keeps it out of the field marks'\n * space, whatever a connection identity happens to spell.\n */\nconst connectionPrefix = '\\u0000connection\\u0000'\nconst connectionMark = (identity: string): string => `${connectionPrefix}${identity}`\n\n/** Whether a query for this connection is in flight. */\nexport const isQueryLoading = (model: RemoteModel, identity: string): boolean =>\n model.loading.size !== 0 && model.loading.has(connectionMark(identity))\n\nconst withoutQueryLoading = (loading: ReadonlySet<string>, identity: string) => {\n if (!loading.has(connectionMark(identity))) return loading\n const next = new Set(loading)\n next.delete(connectionMark(identity))\n return next\n}\n\n/**\n * The in-flight marks of connections the roots still name. A query the entry\n * stopped waiting for — it was restarted or deactivated before an answer came —\n * leaves its mark behind, and a connection released with that mark would read\n * `Loading` forever the next time something asked for it before sending.\n */\nconst prunedQueryLoading = (\n loading: ReadonlySet<string>,\n roots: RetentionRoots,\n): ReadonlySet<string> => {\n const named = new Set(roots.connections.map(root => connectionMark(root.identity)))\n const kept = [...loading].filter(mark => !mark.startsWith(connectionPrefix) || named.has(mark))\n return kept.length === loading.size ? loading : new Set(kept)\n}\n\n/**\n * Drops the refresh marks of entities and connections that were collected.\n * Nothing observes a collected entity — the retention roots are the active\n * Surfaces — so no read entry's generation can fall back when its mark goes.\n * Without this the generations would be bounded by how many things the\n * application has ever refreshed rather than by what it currently holds, which\n * for a list refreshed on a timer is the same as not bounded at all.\n */\nconst prunedRefresh = (refresh: RefreshState, retained: Retained): RefreshState => {\n const live = (mark: string): boolean =>\n mark.startsWith(connectionPrefix)\n ? retained.connections[mark.slice(connectionPrefix.length)] !== undefined\n : retained.entities[mark.slice(0, mark.indexOf('\\u0000'))] !== undefined\n const keep = (marks: ReadonlyMap<string, number>): ReadonlyMap<string, number> => {\n const next = new Map<string, number>()\n for (const [mark, generation] of marks) if (live(mark)) next.set(mark, generation)\n return next.size === marks.size ? marks : next\n }\n const requested = keep(refresh.requested)\n const started = keep(refresh.started)\n return requested === refresh.requested && started === refresh.started\n ? refresh\n : { ...refresh, requested, started }\n}\n\n/**\n * The generation a read is planned under: the highest any of the fields it\n * reads or connections it runs was refreshed at. A read entry carries this as a\n * dependency, so it restarts when what it observes is refreshed and not when\n * anything else is.\n */\nexport const refreshedAt = (\n refresh: RefreshState,\n requests: ReadonlyArray<Requirement>,\n connections: ReadonlyArray<string> = [],\n): number => {\n let at = 0\n for (const mark of fieldMarks(requests)) at = Math.max(at, refresh.requested.get(mark) ?? 0)\n for (const identity of connections) {\n at = Math.max(at, refresh.requested.get(connectionMark(identity)) ?? 0)\n }\n return at\n}\n\n/**\n * Marks every field of `requests` and every connection in `connections`\n * refreshed at the next generation.\n */\nexport const withRefreshRequested = (\n refresh: RefreshState,\n requests: ReadonlyArray<Requirement>,\n connections: ReadonlyArray<string> = [],\n): RefreshState => {\n const generation = refresh.generation + 1\n const requested = new Map(refresh.requested)\n for (const mark of fieldMarks(requests)) requested.set(mark, generation)\n for (const identity of connections) requested.set(connectionMark(identity), generation)\n return { ...refresh, generation, requested }\n}\n\n/**\n * Records that a read of `requests` began under `generation`. A read that\n * carries no generation began under none, and leaves the marks as they are.\n */\nconst withRefreshStarted = (\n refresh: RefreshState,\n requests: ReadonlyArray<Requirement>,\n generation: number | undefined,\n): RefreshState => {\n if (generation === undefined || generation === 0) return refresh\n let started: Map<string, number> | undefined\n for (const mark of fieldMarks(requests)) {\n if ((refresh.started.get(mark) ?? 0) >= generation) continue\n started ??= new Map(refresh.started)\n started.set(mark, generation)\n }\n return started === undefined ? refresh : { ...refresh, started }\n}\n\n/**\n * Whether one field's read already began under the generation that field was\n * last refreshed at. Such a read is in flight and would otherwise outlive the\n * refresh, so the refresh takes a new generation to restart it even though the\n * field is already stale.\n */\nexport const refreshIsInFlight = (\n refresh: RefreshState,\n request: Requirement,\n field: string,\n): boolean => {\n const mark = fieldMark(request.entity, request.id, field)\n return (refresh.started.get(mark) ?? 0) === (refresh.requested.get(mark) ?? 0)\n}\n\n/**\n * Whether a read is fetching any of `fields` for this entity. Consulted only\n * when the store lacks the value, which is what separates `Loading` from\n * `Initial`.\n */\nexport const isLoading = (\n model: RemoteModel,\n entity: string,\n id: string,\n fields: ReadonlyArray<string>,\n): boolean => {\n if (model.loading.size === 0) return false\n return fields.some(field => model.loading.has(fieldMark(entity, id, field)))\n}\n\nconst setConnectionStale = (\n connections: Readonly<Record<string, Connection>>,\n connection: string,\n stale: boolean,\n): Readonly<Record<string, Connection>> => {\n const current = connections[connection] ?? emptyConnection\n return { ...connections, [connection]: { ...current, stale } }\n}\n\nconst markGap = (model: RemoteModel, stream: string): RemoteModel =>\n model.gaps.has(stream) ? model : { ...model, gaps: new Set([...model.gaps, stream]) }\n\nconst clearGap = (model: RemoteModel, stream: string): RemoteModel =>\n model.gaps.has(stream)\n ? { ...model, gaps: new Set([...model.gaps].filter(entry => entry !== stream)) }\n : model\n\n/**\n * The pure reducer all four producers share. A live event that arrives ahead of\n * its cursor is a gap: it is not applied, and the stream is recorded so the host\n * can resubscribe rather than silently miss facts.\n */\nexport const updateRemote = (model: RemoteModel, message: RemoteMessage): RemoteModel => {\n switch (message._tag) {\n case 'ReadReceived':\n return {\n ...model,\n entities: writeRead(model.entities, message.requests, message.result, message.now),\n loading: withoutLoading(model.loading, message.requests),\n // What was asked, and what came back: a relation riding on the request\n // writes its targets too, and a target's old failure must not outlive\n // the value that answers it.\n failures: withoutFieldFailures(model.failures, [\n ...fieldMarks(message.requests),\n ...patchedMarks(message.result.entities),\n ]),\n }\n case 'ReadFailed':\n // A broken live stream is not a failed read. Marking its fields failed\n // would take them out of the read entry's plan, and restart it, which is\n // the opposite of what missing changes calls for.\n if (message.stream !== undefined) return markGap(model, message.stream)\n // The read is over. Fields it refreshed read as they did, and every field\n // it asked for carries the error until something settles it.\n return {\n ...model,\n entities: setStale(model.entities, marksOf(message.requests), false),\n loading: withoutLoading(model.loading, message.requests),\n failures: withFieldFailures(model.failures, message.requests, message.error),\n }\n case 'RetentionChanged': {\n const retained = gc(model, message.roots)\n return {\n ...model,\n ...retained,\n refresh: prunedRefresh(model.refresh, retained),\n failures: prunedFailures(model, message.roots),\n loading: prunedQueryLoading(model.loading, message.roots),\n }\n }\n case 'Hydrated': {\n // A restored connection is evidence about its rows and about nothing\n // else. Its boundaries are `Unknown` — not `Terminal`, which would claim\n // there is no more, and not the cursors it had, which the server may no\n // longer honour — and it is stale, so the planner refetches it while the\n // rows it held are already on screen.\n const restored = Object.entries(message.connections ?? {}).map(\n ([identity, segments]) =>\n [\n identity,\n {\n // One segment per saved segment: the gaps between them are what\n // says \"these rows do not adjoin\", and merging them into one run\n // would invent an adjacency nobody established.\n segments: segments.map(edges => ({\n edges: [...edges],\n start: unknownBoundary,\n end: unknownBoundary,\n })),\n stale: true,\n },\n ] as const,\n )\n return {\n ...model,\n entities: RemotePersistence.mergeStores(model.entities, message.entities, message.merge),\n connections:\n message.merge === 'replace'\n ? { ...model.connections, ...Object.fromEntries(restored) }\n : { ...Object.fromEntries(restored), ...model.connections },\n }\n }\n case 'RefreshStarted': {\n // An entity known to be absent has no field to mark, and nothing plans a\n // read of it again. Asked about again, it is forgotten, so it is.\n const asked = message.requests.reduce(\n (store, request) =>\n isTombstone(store, entityKey(request.entity, request.id))\n ? remove(store, entityKey(request.entity, request.id))\n : store,\n model.entities,\n )\n const entities = setStale(asked, marksOf(message.requests), true)\n // Asking again is also how a failed field is retried, including one that\n // never loaded and so has nothing to mark stale.\n const failures = withoutFieldFailures(model.failures, fieldMarks(message.requests))\n return entities === model.entities && failures === model.failures\n ? model\n : { ...model, entities, failures }\n }\n case 'QueryStarted': {\n const loading = new Set(model.loading)\n for (const identity of message.connections) loading.add(connectionMark(identity))\n return loading.size === model.loading.size ? model : { ...model, loading }\n }\n case 'ReadStarted':\n return {\n ...model,\n loading: withLoading(model.loading, message.requests),\n refresh: withRefreshStarted(model.refresh, message.requests, message.refresh),\n }\n case 'MutationStarted':\n return {\n ...model,\n mutations: beginMutation(model.mutations, message.requestId),\n optimistic: beginOptimistic(model.optimistic, message.requestId, message.optimistic ?? []),\n }\n case 'MutationSucceeded': {\n // Settling is release-the-layer-and-overlays, so overlapping optimistic\n // layers rebase instead of needing inverse patches.\n const settled = settleSuccess(\n model.entities,\n model.optimistic,\n model.mutations,\n message.requestId,\n message.entities,\n message.connections ?? [],\n message.deleted ?? [],\n )\n return {\n ...model,\n entities: settled.store,\n mutations: settled.state,\n optimistic: settled.optimistic,\n failures: withoutFieldFailures(model.failures, [\n ...patchedMarks(message.entities),\n ...(message.deleted ?? []).flatMap(ref =>\n entityFailureMarks(model.failures, entityKey(ref.entity, ref.id)),\n ),\n ]),\n }\n }\n case 'OverlayShown':\n return {\n ...model,\n optimistic: beginOptimistic(\n settleFailure(model.optimistic, overlayLayer(message.id)),\n overlayLayer(message.id),\n message.optimistic,\n ),\n }\n case 'OverlayLifted': {\n const optimistic = settleFailure(model.optimistic, overlayLayer(message.id))\n return optimistic.layers.length === model.optimistic.layers.length &&\n optimistic.overlays.length === model.optimistic.overlays.length\n ? model\n : { ...model, optimistic }\n }\n case 'MutationFailed':\n return {\n ...model,\n mutations: failMutation(model.mutations, message.requestId, message.error),\n optimistic: settleFailure(model.optimistic, message.requestId),\n }\n case 'LiveReceived': {\n const state = model.live[message.stream] ?? emptyLiveState\n if (message.event._tag === 'EntityPatched' || message.event._tag === 'EntityDeleted') {\n const event = message.event\n const applied = applyEntityEvent(state, model.entities, event, message.now)\n if (applied.outcome === 'gap') return markGap(model, message.stream)\n // A value the server sent is newer than any failure to fetch it.\n const settled =\n applied.outcome !== 'applied'\n ? []\n : event._tag === 'EntityPatched'\n ? [...patchedMarks([{ ...event.ref, values: event.values }])]\n : entityFailureMarks(model.failures, entityKey(event.ref.entity, event.ref.id))\n return clearGap(\n {\n ...model,\n entities: applied.store,\n live: { ...model.live, [message.stream]: applied.state },\n failures: withoutFieldFailures(model.failures, settled),\n },\n message.stream,\n )\n }\n const applied = applyConnectionEvent(state, model.optimistic, message.event, message.policy)\n if (applied.outcome === 'gap') return markGap(model, message.stream)\n const next = clearGap(\n {\n ...model,\n optimistic: applied.optimistic,\n live: { ...model.live, [message.stream]: applied.state },\n },\n message.stream,\n )\n // An invalidating event means exactly what `ConnectionInvalidated` means,\n // so it goes through the same reduction rather than a parallel one.\n return applied.invalidated === undefined\n ? next\n : updateRemote(next, { _tag: 'ConnectionInvalidated', connection: applied.invalidated })\n }\n case 'GapCleared':\n return clearGap(model, message.stream)\n case 'ConnectionMerged': {\n const current = model.connections[message.connection] ?? emptyConnection\n const failures = withoutConnectionFailure(model.failures, message.connection)\n const loading = withoutQueryLoading(model.loading, message.connection)\n // The page answering an invalidation is the server's list as it now is, so it\n // replaces the pages: removed and reordered items go, and later pages are paged\n // again. A re-run of a connection that was not invalidated still merges.\n const replaces = message.refreshes === true && current.stale\n const merged = merge(replaces ? emptyConnection : current, message.page)\n return {\n ...model,\n connections: {\n ...model.connections,\n [message.connection]: message.refreshes === true ? { ...merged, stale: false } : merged,\n },\n optimistic: pruneOverlays(\n model.optimistic,\n message.connection,\n new Set(message.page.edges.map(edge => edge.key)),\n model.mutations.pending,\n ),\n failures,\n loading,\n }\n }\n case 'ConnectionInvalidated':\n // Asking again is also how a failed query is retried, so the failure goes\n // with the mark: a connection is never both due and failed.\n // A connection can be both, though: `Hydrated` restores one stale, and a\n // failure recorded before it arrived must still go when asked again.\n if (\n model.connections[message.connection]?.stale === true &&\n !(message.connection in model.failures.connections)\n ) {\n return model\n }\n return {\n ...model,\n connections: setConnectionStale(model.connections, message.connection, true),\n failures: withoutConnectionFailure(model.failures, message.connection),\n }\n case 'QueryFailed':\n // The refresh is over and the pages stay as they were. One the Model never\n // held stays absent from `connections`; the failure is what it now knows.\n return {\n ...model,\n connections:\n message.connection in model.connections\n ? setConnectionStale(model.connections, message.connection, false)\n : model.connections,\n failures: {\n ...model.failures,\n connections: { ...model.failures.connections, [message.connection]: message.error },\n },\n loading: withoutQueryLoading(model.loading, message.connection),\n }\n case 'ConnectionRefreshed':\n return {\n ...model,\n connections: setConnectionStale(model.connections, message.connection, false),\n }\n }\n}\n\n/** The failures without one connection's, keeping identity when it had none. */\nconst withoutConnectionFailure = (failures: Failures, connection: string): Failures => {\n if (!(connection in failures.connections)) return failures\n const { [connection]: _settled, ...connections } = failures.connections\n return { ...failures, connections }\n}\n\n/** The failures with every field a read asked for failed with `error`. */\nconst withFieldFailures = (\n failures: Failures,\n requests: ReadonlyArray<Requirement>,\n error: RemoteError,\n): Failures => {\n const fields = { ...failures.fields }\n for (const mark of fieldMarks(requests)) fields[mark] = error\n return { ...failures, fields }\n}\n\n/**\n * The failures without the fields `settled` names, keeping identity when none\n * of them had failed, which is nearly always: this runs on every write.\n */\nconst withoutFieldFailures = (failures: Failures, settled: Iterable<string>): Failures => {\n if (Object.keys(failures.fields).length === 0) return failures\n const marks = [...settled].filter(mark => mark in failures.fields)\n if (marks.length === 0) return failures\n const fields = { ...failures.fields }\n for (const mark of marks) delete fields[mark]\n return { ...failures, fields }\n}\n\n/** Every failed field of one entity: what deleting the entity settles. */\nconst entityFailureMarks = (failures: Failures, key: string): ReadonlyArray<string> =>\n Object.keys(failures.fields).filter(mark => mark.startsWith(`${key}\\u0000`))\n\n/** The field marks of written values: each patch settles the fields it carries. */\nconst patchedMarks = function* (\n patches: ReadonlyArray<{ readonly entity: string; readonly id: string; readonly values: object }>,\n): Generator<string> {\n for (const patch of patches) {\n for (const field of Object.keys(patch.values)) yield fieldMark(patch.entity, patch.id, field)\n }\n}\n\n/**\n * The failures of what the roots still reach. A released connection's or\n * entity's failure goes with it, so asking for it again later asks the server\n * again rather than repeating an error that may no longer hold.\n *\n * Reached is retention's own walk, taken over the Model before collection. It\n * counts a relation's target and a list's row that the store does not hold,\n * which is exactly a value whose first read failed: it is still on screen,\n * behind the parent that refers to it.\n */\nconst prunedFailures = (model: RemoteModel, roots: RetentionRoots): Failures => {\n const { failures } = model\n const named = new Set(roots.connections.map(root => root.identity))\n const connections = Object.entries(failures.connections).filter(([identity]) =>\n named.has(identity),\n )\n const kept =\n Object.keys(failures.fields).length === 0\n ? new Set<string>()\n : reachable(\n model.entities,\n roots,\n model.connections,\n model.optimistic,\n model.mutations.pending,\n )\n const fields = Object.entries(failures.fields).filter(([mark]) =>\n kept.has(mark.slice(0, mark.indexOf('\\u0000'))),\n )\n return connections.length === Object.keys(failures.connections).length &&\n fields.length === Object.keys(failures.fields).length\n ? failures\n : { connections: Object.fromEntries(connections), fields: Object.fromEntries(fields) }\n}\n\n/** Whether this field's last read failed and nothing has settled it since. */\nexport const isFieldFailed = (\n model: RemoteModel,\n entity: string,\n id: string,\n field: string,\n): boolean => fieldMark(entity, id, field) in model.failures.fields\n\n/**\n * The first failure among the fields `relation` reads of an entity, following\n * each relation the store holds into its targets, as `assemble` does. A read\n * that consults it shows `Failed` for a related entity's failure too, rather\n * than waiting on a field nothing will fetch.\n */\nexport const failureOf = (\n model: RemoteModel,\n entity: string,\n id: string,\n relation: RelationRequirement,\n): RemoteError | undefined => {\n const failed = model.failures.fields\n if (Object.keys(failed).length === 0) return undefined\n // Once per entity and requirement, as retention walks: two relations can\n // reach one entity for different fields, and skipping the second would hide\n // its failure. A requirement tree is finite, so cyclic data still ends.\n const walked = new Map<string, Set<RelationRequirement>>()\n const walk = (\n target: string,\n targetId: string,\n requirement: RelationRequirement,\n ): RemoteError | undefined => {\n const key = entityKey(target, targetId)\n const seen = walked.get(key) ?? new Set()\n if (seen.has(requirement)) return undefined\n seen.add(requirement)\n walked.set(key, seen)\n for (const field of requirement.fields) {\n const error = failed[fieldMark(target, targetId, field)]\n if (error !== undefined) return error\n const nested = requirement.relations?.[field]\n if (nested === undefined) continue\n const value = readField(model.entities, key, field)\n if (value._tag === 'None') continue\n for (const ref of targetsOf(value.value, nested)) {\n const found = walk(ref.entity, ref.id, nested)\n if (found !== undefined) return found\n }\n }\n return undefined\n }\n return walk(entity, id, relation)\n}\n\n/** Appends (after) or prepends (before) an incoming page onto the stored one. */\nconst mergeWireRefPages = (\n current: RefPageValue,\n next: RefPageValue,\n direction: 'after' | 'before',\n): RefPageValue => {\n const refs =\n direction === 'after'\n ? [...new Set([...current.refs, ...next.refs])]\n : [...new Set([...next.refs, ...current.refs])]\n // The far boundary is the incoming page's; the near one is still the stored page's.\n return direction === 'after'\n ? { refs, hasNext: next.hasNext, hasPrevious: current.hasPrevious }\n : { refs, hasNext: current.hasNext, hasPrevious: next.hasPrevious }\n}\n\n/**\n * Writes a read result into the store, recording each field's applied window so\n * a later request with a different window refetches. A relation page requested\n * with a cursor is merged onto the page already stored, so \"load more\"\n * accumulates rather than replaces. Every read path should use this rather than\n * reducing `writeEntity` by hand.\n */\nexport const writeRead = (\n store: EntityStore,\n requests: ReadonlyArray<Requirement>,\n result: Schema.Schema.Type<typeof ReadBatchResult>,\n now = 0,\n): EntityStore => {\n const returned = new Map<string, Record<string, unknown>>()\n for (const entity of result.entities) {\n const key = entityKey(entity.entity, entity.id)\n returned.set(key, { ...returned.get(key), ...entity.values })\n }\n const byEntity = new Map<\n string,\n { windows: Record<string, string>; merge: Map<string, 'after' | 'before'> }\n >()\n // A request's windows apply to its entity; a relation's windows apply to\n // each target the returned refs name, and so on down the graph.\n const record = (\n key: string,\n windows: Requirement['windows'],\n relations: Requirement['relations'],\n ): void => {\n let entry = byEntity.get(key)\n if (entry === undefined) {\n entry = { windows: {}, merge: new Map() }\n byEntity.set(key, entry)\n }\n for (const [field, window] of Object.entries(windows ?? {})) {\n entry.windows[field] = windowKey(window)\n const direction =\n window.after !== undefined ? 'after' : window.before !== undefined ? 'before' : undefined\n if (direction !== undefined) entry.merge.set(field, direction)\n }\n const values = returned.get(key)\n if (values === undefined) return\n for (const [field, relation] of Object.entries(relations ?? {})) {\n for (const ref of targetsOf(values[field], relation)) {\n record(entityKey(ref.entity, ref.id), relation.windows, relation.relations)\n }\n }\n }\n for (const request of requests) {\n record(entityKey(request.entity, request.id), request.windows, request.relations)\n }\n\n const writes: EntityWrite[] = []\n const pending = new Map<string, Record<string, unknown>>()\n for (const entity of result.entities) {\n const key = entityKey(entity.entity, entity.id)\n const entry = byEntity.get(key)\n let values = entity.values\n if (entry !== undefined && entry.merge.size > 0) {\n // A cursor page merges onto the page stored (or written earlier in this result).\n const previous = pending.get(key) ?? store[key]?.values\n if (previous !== undefined) {\n const merged: Record<string, unknown> = { ...values }\n for (const [field, direction] of entry.merge) {\n const incoming = values[field]\n const existing = previous[field]\n if (isRefPage(incoming) && isRefPage(existing)) {\n merged[field] = mergeWireRefPages(existing, incoming, direction)\n }\n }\n values = merged\n }\n }\n pending.set(key, { ...pending.get(key), ...values })\n writes.push({ key, values, windows: entry?.windows })\n }\n // The server was asked for these ids by name and answered without them.\n // Whether the entity never existed, is gone, or is not this principal's to\n // see, the client knows the same thing: it is not there. Without this the read\n // would stay `Loading` for good. A forced plan (`refresh`) asks again, and any\n // later write clears the tombstone.\n //\n // Only ids asked for directly: the target of a returned ref is left alone. A\n // server need not expand a relation that rides on a request; the planner\n // follows a relation the store holds and asks for its targets by id next, and\n // a tombstone here would stop it.\n let answered = store\n for (const request of requests) {\n const key = entityKey(request.entity, request.id)\n if (!returned.has(key)) answered = tombstone(answered, key)\n }\n return writeEntities(answered, writes, now)\n}\n","/**\n * Request policies: how a read treats fields the store already holds. A policy\n * compiles to planner options; it is not a second cache. `Remote.observe` and\n * `Remote.prefetch` take one, and the planner itself stays pure and\n * time-injected.\n */\nimport type { PlanOptions } from './plan.js'\n\nexport type RemotePolicy =\n /** Fetch only fields the store lacks (missing, stale, or re-windowed). */\n | { readonly _tag: 'CacheFirst' }\n /**\n * Keep present values visible, read them as `Refreshing`, and refetch an\n * entry older than `maxAge` milliseconds.\n */\n | { readonly _tag: 'StaleWhileRevalidate'; readonly maxAge: number }\n /** Fetch every selected field regardless of coverage; cached values stay visible meanwhile. */\n | { readonly _tag: 'NetworkOnly' }\n\nexport const RemotePolicy = {\n /** Fetch only what the store lacks. */\n cacheFirst: { _tag: 'CacheFirst' } as const satisfies RemotePolicy,\n\n /** Keep present values visible, read as `Refreshing`, and refetch an entry older than `maxAge` ms. */\n staleWhileRevalidate: (options: { readonly maxAge: number }): RemotePolicy => ({\n _tag: 'StaleWhileRevalidate',\n maxAge: options.maxAge,\n }),\n\n /** Fetch every selected field regardless of coverage; cached values stay visible meanwhile. */\n networkOnly: { _tag: 'NetworkOnly' } as const satisfies RemotePolicy,\n\n /** The planner options a policy compiles to at `now`. */\n toPlan: (policy: RemotePolicy, now: number): PlanOptions => {\n switch (policy._tag) {\n case 'CacheFirst':\n return {}\n case 'StaleWhileRevalidate':\n return { freshness: { now, freshness: policy.maxAge } }\n case 'NetworkOnly':\n return { force: true }\n }\n },\n\n /**\n * Whether a read under this policy may refetch fields the store already\n * holds, so an observer marks them stale (read as `Refreshing`) while the\n * request is pending.\n */\n refreshes: (policy: RemotePolicy): boolean => policy._tag !== 'CacheFirst',\n}\n","/**\n * `foldkit-remote` — normalized application-facing server state.\n *\n * The pure core (entities, selections, the store, the planner, connections,\n * live classification, optimistic layers) performs no I/O. The `Remote.*`\n * helpers that read or mutate go through the `RemoteClient` Effect service.\n */\nimport { Effect, Layer, Option, Result, Schema, Stream } from 'effect'\nimport { Entity as DomainEntity, Query as Relational, SelectionTypeId } from 'foldkit-entity'\nimport type * as Domain from 'foldkit-entity'\nimport type { Duration } from 'effect'\nimport type { Command } from 'foldkit/command'\nimport * as Subscription from 'foldkit/subscription'\nimport type { EntryWithoutKeepAlive } from 'foldkit/subscription'\nimport {\n type ActiveSurface,\n type Contract,\n type Invalid,\n type ModelRef,\n type Projection,\n type Surface,\n type Wiring,\n} from 'foldkit-surface'\nimport {\n RemoteClient,\n coalescedLayer,\n liveEventOf,\n mutateRemote,\n remoteError,\n type RemoteRpcClient,\n} from './client.js'\nimport {\n emptyConnection,\n hasNext,\n hasPrevious,\n isGapped,\n type Connection,\n type Edge,\n} from './connection.js'\nimport { Entity, type EntityDescriptor } from './entity.js'\nimport { belongsEncoded, matching, type Matched } from './matching.js'\nimport {\n inspectEntity,\n inspectRemote,\n type QueryExplanation,\n type RemoteInspection,\n} from './inspect.js'\nimport type { LiveCursor, LiveEvent } from './live.js'\nimport {\n failureOf,\n initialRemoteModel,\n isFieldFailed,\n isLoading,\n isQueryLoading,\n isRemoteMessage,\n refreshIsInFlight,\n refreshedAt,\n remoteMessageCases,\n remoteMessageSchema,\n remoteModelSchema,\n retentionRootsSchema,\n updateRemote,\n withRefreshRequested,\n writeRead,\n type RemoteMessage,\n type RemoteMessageInput,\n type RemoteModel,\n} from './model.js'\nimport { mutationStatus, type MutationDescriptor, type MutationStatus } from './mutation.js'\nimport {\n connectionIdentity,\n emptyOptimistic,\n visibleItems,\n visibleStore,\n type ConnectionIdentity,\n type OptimisticState,\n type OptimisticOperation,\n} from './optimistic.js'\nimport { plan, type PlanOptions } from './plan.js'\nimport { RemotePolicy } from './policy.js'\nimport { IDENTITY_SEPARATOR, stableStringify } from './query.js'\nimport type { ConnectionSpec, LivePolicy, QueryDescriptor, QueryRef, QueryWindow } from './query.js'\nimport { remoteDataSchema, type RemoteData, type RemoteError } from './remoteData.js'\nimport type { ConnectionRoot, RetentionRoots } from './retain.js'\nimport { Selection, assemble, pageSchema, relationOf, type Page } from './selection.js'\nimport { entityKey, isTombstone, type EntityStore } from './store.js'\nimport {\n QueryRequest,\n QueryResult,\n ReadRequest,\n RelationRequest,\n REMOTE_PROTOCOL_VERSION,\n WindowSchema,\n RemoteLiveError,\n RemoteProtocolError,\n RemoteQueryError,\n RemoteReadError,\n RemoteRpc,\n} from './wire.js'\nimport type { CoalesceOptions } from './coalesce.js'\nimport {\n Requirement,\n RemoteConnections,\n RemoteRequirements,\n connectionsOf,\n requirementsOf,\n type ConnectionRequirement,\n type RelationRequirement,\n} from './requirement.js'\n\nexport * from './client.js'\nexport * from './coalesce.js'\nexport * from './connection.js'\nexport * from './entity.js'\nexport * from './inspect.js'\nexport * from './live.js'\nexport * from './matching.js'\nexport * from './model.js'\nexport * from './mutation.js'\nexport * from './optimistic.js'\nexport * from './persistence.js'\nexport * from './plan.js'\nexport * from './policy.js'\nexport * from './query.js'\nexport * from './relation.js'\nexport * from './remoteData.js'\nexport * from './requirement.js'\nexport * from './retain.js'\nexport * from './selection.js'\nexport * from './store.js'\nexport * from './wire.js'\n\n/** What a domain registers: a Remote descriptor, or a `foldkit-entity` Entity (read through `Entity.from`). */\nexport type EntityLike = EntityDescriptor<any, any> | Domain.AnyEntity\n\n/**\n * What a read selects: a Remote Selection, or a `foldkit-entity` Selection\n * (read through `Selection.from`).\n */\nexport type EntitySelection<Value, Name extends string, Id extends string = string> =\n | Selection<Value, Name, 'entity'>\n | Domain.Selection<Name, unknown, Schema.Constraint & { readonly Type: Value }, Id>\n\nconst descriptorOf = (entity: EntityLike): EntityDescriptor<any, any> =>\n DomainEntity.is(entity) ? Entity.from(entity as never) : entity\n\nconst selectionOf = <Value, Name extends string>(\n selection: EntitySelection<Value, Name>,\n): Selection<Value, Name, 'entity'> =>\n SelectionTypeId in selection ? (Selection.from(selection) as never) : selection\n\ntype EntityName<D> = D extends { readonly name: infer Name extends string } ? Name : never\ntype QueryName<D> = D extends QueryDescriptor<infer Name, any, any> ? Name : never\ntype MutationName<D> = D extends MutationDescriptor<infer Name, any, any> ? Name : never\n\n/**\n * Nothing when `Name` is one of the domain's registered `Names`; otherwise a\n * branded failure naming the descriptor, so `Data.get(Team.select(…))` for an\n * unregistered `Team` errors at the selection in one line.\n */\nexport type Registered<Name extends string, Names extends string, Kind extends string> = [\n Name,\n] extends [Names]\n ? unknown\n : Invalid<`${Kind} \"${Name}\" is not registered with this Remote domain`>\n\n/** Nothing when a selection is of the query's entity; otherwise a branded failure naming both. */\nexport type SelectsEntity<Entity extends string, Of extends string> = [Entity] extends [Of]\n ? unknown\n : Invalid<`the selection is of \"${Entity}\", but the query lists \"${Of}\"`>\n\nexport interface RemoteDescriptor<\n Entities extends readonly EntityLike[] = readonly EntityLike[],\n Queries extends readonly QueryDescriptor<any, any, any>[] = readonly QueryDescriptor<\n any,\n any,\n any\n >[],\n Mutations extends readonly MutationDescriptor<any, any, any>[] = readonly MutationDescriptor<\n any,\n any,\n any\n >[],\n> {\n readonly entities: Entities\n readonly queries: Queries\n readonly mutations: Mutations\n readonly Model: Schema.Codec<RemoteModel, unknown>\n readonly initial: RemoteModel\n readonly Message: Schema.Schema<RemoteMessage>\n readonly update: (model: RemoteModel, message: RemoteMessage) => RemoteModel\n readonly rpc: typeof RemoteRpc\n /** Name-keyed lookups built from the declared entities, queries, and mutations. */\n readonly registry: {\n readonly entities: ReadonlyMap<string, EntityDescriptor<any, any>>\n readonly queries: ReadonlyMap<string, QueryDescriptor<any, any, any>>\n readonly mutations: ReadonlyMap<string, MutationDescriptor<any, any, any>>\n }\n}\n\ndeclare const boundRemoteNames: unique symbol\n\nexport interface BoundRemote<AppModel, Store extends RemoteModel, Names extends string = string> {\n readonly definition: RemoteDescriptor\n readonly store: ModelRef<AppModel, Store>\n /** For `Module`: owns the store's Model path. */\n readonly contract: Contract\n /** Phantom: the entity names this Remote definition registers. */\n readonly [boundRemoteNames]?: Names\n}\n\ntype MutationInput<M> = M extends MutationDescriptor<any, infer Input, any> ? Input : never\n\nexport interface DomainMutateOptions {\n /** Overrides the generated id, for a retry, a durable bridge, or a test. */\n readonly requestId?: string | undefined\n /**\n * What the request changes before the server answers, released when it\n * settles. A function receives the generated ids, so a created entity can\n * carry `tempId` until the result names the real one.\n */\n readonly optimistic?:\n | ReadonlyArray<OptimisticOperation>\n | ((ids: {\n readonly requestId: string\n readonly tempId: string\n }) => ReadonlyArray<OptimisticOperation>)\n | undefined\n}\n\n/** A Foldkit Subscription entry of the Remote domain, emitting its Messages through `RemoteClient`. */\nexport type RemoteEntry<AppModel, Dependencies> = EntryWithoutKeepAlive<\n AppModel,\n RemoteMessage,\n Dependencies,\n RemoteClient\n>\n\n/**\n * The entries `RemoteDomain.subscriptions` returns for an active record: a read\n * and a live entry per key (the live one idles when nothing is read live), and\n * `retain`.\n */\nexport type SubscriptionEntries<AppModel, Active> = {\n // `Object.entries` turns a numeric key into a string, so numeric keys have entries too.\n readonly [K in keyof Active & (string | number) as `${K}.read` | `${K}.live`]: RemoteEntry<\n AppModel,\n any\n >\n} & { readonly retain: RemoteEntry<AppModel, any> }\n\nexport interface SubscriptionsOptions extends ObserveOptions, LiveOptions, RetainOptions {}\n\n/** A Remote domain's wiring for an assembly: it routes Remote's Messages into `reduce`, brings its Subscriptions and contract, and requires `RemoteClient` from the runtime's resources Layer. */\nexport type RemoteWiring<AppModel> = Wiring<\n AppModel,\n RemoteMessage | RemoteMessageInput,\n RemoteClient\n>\n\n/** What `RemoteDomain.mutate` hands `update`: the Model with the request started, and the Command that settles it. */\nexport interface MutationStarted<AppModel> {\n readonly model: AppModel\n readonly requestId: string\n readonly tempId: string\n /** Yields `MutationSucceeded` or `MutationFailed`; never fails. */\n readonly command: Command<RemoteMessage, never, RemoteClient>\n}\n\n/**\n * A Remote domain bound to its place in the application Model: the descriptor\n * (`Remote.define`), the binding (`Remote.at`), and the application-facing\n * operations over them. Every method compiles to the `Remote.*` function of the\n * same name, which stays exported for tooling, SSR, and tests.\n */\nexport interface RemoteDomain<\n AppModel,\n Store extends RemoteModel,\n Entities extends readonly EntityLike[],\n Queries extends readonly QueryDescriptor<any, any, any>[],\n Mutations extends readonly MutationDescriptor<any, any, any>[],\n>\n extends\n BoundRemote<AppModel, Store, EntityName<Entities[number]>>,\n RemoteDescriptor<Entities, Queries, Mutations> {\n /** `Remote.select`: a Projection reading one entity through a selection of a registered entity. */\n get<Value, Name extends string, Id extends string = string>(\n selection: EntitySelection<Value, Name, Id> &\n Registered<Name, EntityName<Entities[number]>, 'Entity'>,\n // The id type of the Entity selected: another Entity's branded id does not fit.\n id: NoInfer<Id>,\n ): Projection<AppModel, RemoteData<Value>>\n /**\n * `get`, and the projection also subscribes to the entity's changes: its\n * requirements are marked `live`, so `subscriptions` derives a live entry for\n * the Surfaces that read it.\n */\n live<Value, Name extends string, Id extends string = string>(\n selection: EntitySelection<Value, Name, Id> &\n Registered<Name, EntityName<Entities[number]>, 'Entity'>,\n // The id type of the Entity selected: another Entity's branded id does not fit.\n id: NoInfer<Id>,\n ): Projection<AppModel, RemoteData<Value>>\n /**\n * A query connection read as a `Page` of items selected of the query's\n * entity: `Initial` until the page and every item's selected fields are\n * present, `Refreshing` while any of them is being refetched. The window is\n * the page first asked for; the pages `next`, `previous` and `fetch` merge\n * onto the connection read through the same projection.\n */\n query<Q extends QueryDescriptor<any, any, any>, Value, Entity extends string>(\n query: Q & Registered<Q['name'], QueryName<Queries[number]>, 'Query'>,\n input: QueryInput<Q>,\n options: QueryOptions<Value, Entity, QueryEntity<Q>>,\n ): QueryProjection<AppModel, Value, Q['name'], QueryInput<Q>>\n /** The `QueryRef` for the page after the loaded end (same page size), or `undefined` when there is none or its cursor is unknown. */\n next<Name extends string, Input>(\n model: AppModel,\n projection: QueryProjection<AppModel, any, Name, Input>,\n ): QueryRef<Name, Input> | undefined\n /** The `QueryRef` for the page before the loaded start, or `undefined`. */\n previous<Name extends string, Input>(\n model: AppModel,\n projection: QueryProjection<AppModel, any, Name, Input>,\n ): QueryRef<Name, Input> | undefined\n /**\n * What a query read is and what it currently is, as one serializable value —\n * data-query-DESIGN §29.1: the domain, the definition and its input, the\n * connection identity, the window, the Selection, the body as readable text\n * with what it depends on, and what the read answers from this Model.\n *\n * Pure, so a DevTools panel showing it shows something the Model can be\n * replayed to.\n *\n * Given `surfaces` — the same active record `subscriptions` takes — it also\n * reports which of them read this connection, and why each is active where\n * that is a readable fact (`Surface.when`) rather than a callback\n * (`Surface.at`). A Projection cannot carry this itself: several Surfaces may\n * read one connection, so it is not a property of the read.\n */\n explain<Name extends string, Input>(\n model: AppModel,\n projection: QueryProjection<AppModel, any, Name, Input>,\n options?: {\n readonly surfaces?: Readonly<Record<string, ActiveSurface<AppModel>>> | undefined\n },\n ): QueryExplanation\n /**\n * The rows of a loaded list that a body matches, decoded as the list decodes\n * them — a filter that asks the server nothing.\n *\n * **It filters a list; it does not run a query.** That distinction is what\n * keeps it honest. \"Which rows match\" would need to know that the list holds\n * every row the body could match, which is predicate containment and is\n * deliberately not built. \"Which rows *of this list* match\" is decidable from\n * what is already here, and is what a search box over a loaded page actually\n * wants.\n *\n * `complete` says whether the answer is about the whole list: every edge\n * judged, and the connection terminal at both ends. An incomplete answer is\n * not wrong — it is about less than the caller may have meant, which is why\n * it is said rather than left for a view to assume.\n *\n * Creates no connection, so there is nothing new to retain and nothing new to\n * fetch. The server stays authoritative for which rows exist.\n */\n filtered<Value, Name extends string, Input, Q extends QueryDescriptor<any, any, any>>(\n model: AppModel,\n over: QueryProjection<AppModel, Value, Name, Input>,\n by: Q & Registered<Q['name'], QueryName<Queries[number]>, 'Query'>,\n input: QueryInput<Q>,\n ): Matched<Value>\n /** A Command that runs the query and yields the `ConnectionMerged` (or `QueryFailed`) that reduces it: \"load more\". */\n fetch(ref: QueryRef<string, unknown>): Command<RemoteMessage, never, RemoteClient>\n /**\n * Shows operations over the store with no request behind them, as a mutation's\n * `optimistic` ones show while it is in flight: every Selection and view draws\n * them. For a preview of a change nobody has made. They stay until `lift`;\n * showing an id again replaces what it showed. Called from `update`.\n */\n overlay(model: AppModel, id: string, optimistic: ReadonlyArray<OptimisticOperation>): AppModel\n /** Lifts what `overlay` showed under this id. Lifting nothing returns the same Model. */\n lift(model: AppModel, id: string): AppModel\n /** `Remote.refresh`: marks what a projection or a Surface requires as due, for its read entry to refetch. */\n refresh(\n model: AppModel,\n target: Projection<AppModel, unknown> | Surface<AppModel, any, any, void>,\n ): AppModel\n /**\n * The Foldkit Subscription entries for the active Surfaces, keyed for\n * `Subscription.make`: a read entry per Surface (`Remote.observe`), a live\n * entry per Surface that reads through `live` (`Remote.live`), and one\n * retain entry with every active Surface as a root (`Remote.retain`). A\n * Surface's params are a function of the Model (`Surface.at`), so what is\n * fetched, subscribed, and retained follows the Model.\n */\n subscriptions<\n const Active extends Readonly<\n Record<string, ActiveSurface<AppModel> | Surface<AppModel, any, any, void>>\n >,\n >(\n active: Active,\n options?: SubscriptionsOptions,\n ): SubscriptionEntries<AppModel, Active>\n /** `Remote.plan`: the requirements the store does not satisfy. */\n plan<Value>(\n model: AppModel,\n projection: Projection<AppModel, Value>,\n options?: PlanOptions,\n ): ReadonlyArray<Requirement>\n /** `Remote.storeOf`: the visible store, base under the pending optimistic layers. */\n storeOf(model: AppModel): EntityStore\n /**\n * `Remote.confirmed`: the same projection read against the server-derived\n * store alone, with every pending optimistic layer and connection overlay\n * left off. What it plans is unchanged — the requirements are the\n * projection's own — so observing it reads exactly what observing the\n * projection reads; only what it *shows* differs.\n *\n * A view usually wants the projection itself, which is the visible read:\n * the optimistic layers are there so a change shows before the server has\n * agreed to it. This is for the reader that must not believe a change until\n * the server has confirmed it, which in practice is an Agent capability\n * reporting that what it was asked to do is done:\n *\n * ```ts\n * Agent.when({\n * projection: Data.confirmed(ProjectPage.model.project),\n * predicate: (project, request) => project.name === request.name,\n * })\n * ```\n *\n * There is deliberately no `visible`: a projection is already the visible\n * read, and a wrapper that only forwards would be a second name for it.\n */\n confirmed<P extends Projection<AppModel, any>>(projection: P): P\n /**\n * The plan run through `RemoteClient` and reduced into the Model: the\n * projection's pending queries first, then the fields it lacks (the pages'\n * items included). For SSR, route or hover prefetch, and tests.\n */\n prefetch<Value>(\n model: AppModel,\n projection: Projection<AppModel, Value>,\n options?: ObserveOptions,\n ): Effect.Effect<AppModel, RemoteReadError | RemoteProtocolError | RemoteQueryError, RemoteClient>\n /**\n * Starts a registered mutation from `update`: applies `MutationStarted` (with\n * the optimistic operations) to the Model and returns the Command that runs\n * it and yields the settling Message. The request id comes from the model's\n * mutation sequence unless `options.requestId` is given.\n */\n mutate<M extends MutationDescriptor<any, any, any>>(\n model: AppModel,\n mutation: M & Registered<M['name'], MutationName<Mutations[number]>, 'Mutation'>,\n input: MutationInput<M>,\n options?: DomainMutateOptions,\n ): MutationStarted<AppModel>\n /**\n * What Remote knows of a mutation `mutate` started, by its request id:\n * pending, applied, or failed with the error the server or transport gave.\n */\n mutation(model: AppModel, requestId: string): MutationStatus\n /** `updateRemote` on the bound slice: reduces one of Remote's Messages, as `RemoteMessage` or as the application's union constructs it. */\n reduce(model: AppModel, message: RemoteMessage | RemoteMessageInput): AppModel\n /**\n * How this domain joins an assembly: it routes Remote's Messages into\n * `reduce`, brings its Subscriptions and contract, and requires\n * `RemoteClient` from the runtime's resources Layer. One assembly holds at\n * most one Remote wiring: every domain claims the same tags, and routing\n * takes the first claimant.\n */\n wiring: <\n const Active extends Readonly<\n Record<string, ActiveSurface<AppModel> | Surface<AppModel, any, any, void>>\n >,\n >(\n active: Active,\n options?: SubscriptionsOptions,\n ) => RemoteWiring<AppModel>\n /** `Remote.inspect` of the bound slice. */\n inspect(model: AppModel): RemoteInspection\n}\n\n/** A projection's connection requirement with the `QueryRef` that runs it. */\nexport interface QueryRequirement extends ConnectionRequirement {\n readonly ref: QueryRef<string, unknown>\n}\n\n/** A page forward (`first`, `after`) or back (`last`, `before`); mixing the two is a type error. */\nexport type QueryWindowOptions =\n | {\n readonly first?: number | undefined\n readonly after?: string | undefined\n readonly last?: undefined\n readonly before?: undefined\n }\n | {\n readonly last: number\n readonly before?: string | undefined\n readonly first?: undefined\n readonly after?: undefined\n }\n\nexport type QueryOptions<Value, Entity extends string, Of extends string = Entity> = {\n /** What to read of each item: a selection of the query's entity (`Of`). */\n readonly select: EntitySelection<Value, Entity> & SelectsEntity<Entity, Of>\n} & QueryWindowOptions\n\n/** A query connection read as a `Page` of selected items; `ref` is the connection with its first window. */\nexport interface QueryProjection<AppModel, Value, Name extends string, Input> extends Projection<\n AppModel,\n RemoteData<Page<Value>>\n> {\n readonly ref: QueryRef<Name, Input>\n /** What it reads of each item, so a filter over the same list decodes identically. */\n readonly selection: Selection<Value, string>\n}\n\n/** The input of a query descriptor. */\nexport type QueryInput<Q> = Q extends QueryDescriptor<any, infer Input, any> ? Input : never\n/** The entity a query's connection is over. */\nexport type QueryEntity<Q> =\n Q extends QueryDescriptor<any, any, ConnectionSpec<infer Entity>> ? Entity : string\n\n/**\n * What one consumer asks of one connection, as the pieces it is actually made\n * of — data-query-DESIGN §11's read contract, with only the parts that exist\n * here:\n *\n * - **source** — the `QueryRef`: the query and its input, whose `identity`\n * names the connection and deliberately excludes the window.\n * - **window** — how much of it this consumer wants.\n * - **shape** — the Selection, as the relation slice a read asks the server for.\n *\n * The design's other two are absent on purpose. *Expectation* (required versus\n * optional) has no consumer yet, so there is nothing to carry. *Observation* is\n * a policy of the subscription that runs the read, not of the read itself: one\n * policy covers every connection an active Surface asks for.\n *\n * This is a shaping step, not a public type. The design asked for the\n * separation, not for a new API to compose it with.\n *\n * Note what is *not* here: a read identity keyed on the shape. Two consumers\n * asking one connection and window for different Selections merge into one\n * requirement whose fields are the union, so one read serves both — see\n * `Requirement.mergeConnections`. An identity that included the Selection would\n * split them and fetch twice.\n */\ninterface ReadContract<Name extends string, Input> {\n readonly ref: QueryRef<Name, Input>\n readonly relation: RelationRequirement\n readonly requirement: QueryRequirement\n}\n\nconst readContract = <Name extends string, Input, Value, Entity extends string>(\n source: QueryRef<Name, Input>,\n shape: Selection<Value, Entity>,\n window: QueryWindowOptions,\n): ReadContract<Name, Input> => {\n const ref: QueryRef<Name, Input> = { ...source, window: pickWindow(window) }\n const relation = relationOf(shape)\n return {\n ref,\n relation,\n requirement: { identity: ref.identity, window: ref.window, select: relation, ref },\n }\n}\n\n/**\n * The store a read or plan sees: the base with every pending optimistic layer\n * applied, so a request's patches show until it settles and a temporary id is\n * not planned as a fetch.\n */\nconst storeOf = <AppModel, Store extends RemoteModel, Names extends string>(\n bound: BoundRemote<AppModel, Store, Names>,\n model: AppModel,\n): EntityStore => {\n const remote = bound.store.get(model)\n return visibleStoreOf(remote.entities, remote.optimistic)\n}\n\n/**\n * The Model as it would be with nothing optimistic pending. Every read reaches\n * the layers through the Model it is given, so dropping them here is what makes\n * a read confirmed — no read has to know it is being read confirmed.\n */\nconst withoutOptimistic = <AppModel, Store extends RemoteModel, Names extends string>(\n bound: BoundRemote<AppModel, Store, Names>,\n model: AppModel,\n): AppModel => {\n const remote = bound.store.get(model)\n return remote.optimistic.layers.length === 0 && remote.optimistic.overlays.length === 0\n ? model\n : bound.store.set(model, { ...remote, optimistic: emptyOptimistic } as Store)\n}\n\nconst confirmed = <AppModel, Store extends RemoteModel, P extends Projection<AppModel, any>>(\n bound: BoundRemote<AppModel, Store>,\n projection: P,\n): P => ({\n ...projection,\n read: (root: AppModel) => projection.read(withoutOptimistic(bound, root)),\n})\n\n// The visible store is recomputed only when the base store or the layers\n// change, so reads and plans across renders of one Model share it.\nconst visibleStores = new WeakMap<OptimisticState, WeakMap<EntityStore, EntityStore>>()\n\nconst visibleStoreOf = (entities: EntityStore, optimistic: OptimisticState): EntityStore => {\n let byStore = visibleStores.get(optimistic)\n if (byStore === undefined) {\n byStore = new WeakMap()\n visibleStores.set(optimistic, byStore)\n }\n let visible = byStore.get(entities)\n if (visible === undefined) {\n visible = visibleStore(entities, optimistic)\n byStore.set(entities, visible)\n }\n return visible\n}\n\n// A read's result per store snapshot. `Remote.storeOf` is shared across every\n// read of one Model state, so equal reads of one render assemble and decode\n// once and return one value (a view may compare by identity). A query read\n// also depends on its connection, which changes independently of the store,\n// so it keys on that object too. Weak on both, bounded by what is read.\nconst readResults = new WeakMap<object, WeakMap<object, Map<string, unknown>>>()\n\nconst memoRead = <T>(snapshot: object, by: object, key: string, compute: () => T): T => {\n let byScope = readResults.get(snapshot)\n if (byScope === undefined) {\n byScope = new WeakMap()\n readResults.set(snapshot, byScope)\n }\n let results = byScope.get(by)\n if (results === undefined) {\n results = new Map()\n byScope.set(by, results)\n }\n if (results.has(key)) return results.get(key) as T\n const value = compute()\n results.set(key, value)\n return value\n}\n\nexport interface MutateOptions {\n /** What the request changes before the server answers; released when it settles. */\n readonly optimistic?: ReadonlyArray<OptimisticOperation> | undefined\n}\n\n/** The default `toMessage`: the application reduces `RemoteMessage` itself. */\nconst identityMessage = (message: RemoteMessage): RemoteMessage => message\n\nexport interface RetainOptions {\n /** The query connections the application shows, by `QueryRef` or identity. */\n readonly connections?: ReadonlyArray<ConnectionIdentity> | undefined\n /** How long the roots must be stable before collecting; default none. */\n readonly grace?: Duration.Input | undefined\n}\n\n/** How `Remote.observe` and `Remote.prefetch` treat fields the store already holds. */\nexport interface ObserveOptions {\n /** Default `RemotePolicy.cacheFirst`. */\n readonly policy?: RemotePolicy | undefined\n /** The clock a refreshing policy reads; default `Date.now`. */\n readonly now?: (() => number) | undefined\n}\n\nexport interface LiveOptions {\n /** The clock `LiveReceived` stamps events with; default `Date.now`. */\n readonly now?: (() => number) | undefined\n}\n\n/** A stable key for a live subscription's requirement set. */\nconst liveStreamKey = (requirements: readonly Requirement[]): string =>\n requirements\n .map(\n requirement =>\n `${entityKey(requirement.entity, requirement.id)}:${[...requirement.fields].sort().join(',')}`,\n )\n .sort()\n .join('|')\n\n/** Declares a Remote domain: its entities, queries, and mutations, plus the submodel. */\nconst defineRemote = <\n const Entities extends readonly EntityLike[],\n const Queries extends readonly QueryDescriptor<any, any, any>[] = readonly QueryDescriptor<\n any,\n any,\n any\n >[],\n const Mutations extends readonly MutationDescriptor<any, any, any>[] =\n readonly MutationDescriptor<any, any, any>[],\n>(config: {\n readonly entities: Entities\n readonly queries?: Queries\n readonly mutations?: Mutations\n}): RemoteDescriptor<Entities, Queries, Mutations> => {\n const entities = config.entities.map(descriptorOf)\n return {\n entities: entities as unknown as Entities,\n queries: (config.queries ?? []) as unknown as Queries,\n mutations: (config.mutations ?? []) as unknown as Mutations,\n Model: remoteModelSchema(),\n initial: initialRemoteModel,\n Message: remoteMessageSchema,\n update: updateRemote,\n rpc: RemoteRpc,\n registry: {\n entities: new Map(entities.map(entity => [entity.name, entity])),\n queries: new Map((config.queries ?? []).map(query => [query.name, query])),\n mutations: new Map((config.mutations ?? []).map(mutation => [mutation.name, mutation])),\n },\n }\n}\n\n/** Binds a Remote domain to its store's location in the application Model. */\nconst bindRemote = <\n AppModel,\n Store extends RemoteModel,\n Entities extends readonly EntityLike[],\n Queries extends readonly QueryDescriptor<any, any, any>[],\n Mutations extends readonly MutationDescriptor<any, any, any>[],\n>(\n definition: RemoteDescriptor<Entities, Queries, Mutations>,\n store: ModelRef<AppModel, Store>,\n): BoundRemote<AppModel, Store, EntityName<Entities[number]>> => ({\n definition,\n store,\n contract: {\n kind: 'remote',\n name: store.dependency.join('.') || 'remote',\n // A generated field reference knows its application and its path; a raw\n // optic (`ModelRef.fromOptic`) knows neither, so it claims nothing.\n owner: (store as { readonly owner?: object }).owner,\n owns: store.dependency.length === 0 ? [] : [store.dependency],\n observes: store.dependency.length === 0 ? [] : [store.dependency],\n messages: [],\n metadata: [],\n },\n})\n\n/** The runtime half of `Registered`: a descriptor the domain never declared is an error naming both. */\nconst assertRegistered = (\n bound: BoundRemote<any, any>,\n kind: 'Entity' | 'Query' | 'Mutation',\n registered: ReadonlyMap<string, unknown>,\n name: string,\n): void => {\n if (!registered.has(name)) {\n throw new Error(\n `Remote: ${kind} \"${name}\" is not registered with domain \"${bound.contract.name}\"`,\n )\n }\n}\n\n/** What a projection asks of the remote: entity requirements and query connections. */\ninterface Asked {\n readonly requirements: ReadonlyArray<Requirement>\n readonly connections: ReadonlyArray<ConnectionRequirement>\n}\n\nconst nothingAsked: Asked = { requirements: [], connections: [] }\n\nconst askedOf = (projection: Projection<any, unknown> | undefined): Asked =>\n projection === undefined\n ? nothingAsked\n : { requirements: requirementsOf(projection), connections: connectionsOf(projection) }\n\n/** The plan for what a projection asks: the entity fields to read, and the queries to run. */\ninterface Planned {\n readonly requirements: ReadonlyArray<Requirement>\n readonly queries: ReadonlyArray<QueryRequirement>\n}\n\n/**\n * Plans what a projection asks against the Model. A connection the Model holds\n * fresh contributes its visible items' selected fields to the entity plan; one\n * it does not hold, or holds stale, is a query to run (its items are planned\n * once the page arrives).\n *\n * A connection whose query failed is not run again here, short of `force`: the\n * failure is what its read shows, and retrying is `Remote.refresh`'s to ask\n * for. The rows it already holds are still planned, since they are on screen.\n */\nconst planAsked = (remote: RemoteModel, asked: Asked, options: PlanOptions): Planned => {\n const queries: QueryRequirement[] = []\n const items: Requirement[] = []\n const connections = Requirement.mergeConnections(\n asked.connections,\n ) as ReadonlyArray<QueryRequirement>\n for (const connection of connections) {\n const known = remote.connections[connection.identity]\n const failed = options.force !== true && connection.identity in remote.failures.connections\n if (!failed && (known === undefined || known.stale || options.force === true)) {\n queries.push(connection)\n continue\n }\n if (known === undefined) continue\n const edges = visibleItems(\n known,\n connection.identity,\n remote.optimistic.overlays,\n remote.entities,\n )\n items.push(\n ...itemsOf(\n edges.map(edge => edge.ref),\n connection.select,\n ),\n )\n }\n const planned = plan(\n visibleStoreOf(remote.entities, remote.optimistic),\n [...asked.requirements, ...items],\n options,\n )\n return {\n requirements: options.force === true ? planned : withoutFailedFields(remote, planned),\n queries,\n }\n}\n\n/**\n * The plan without the fields whose last read failed. Like a failed query,\n * a failed field is shown rather than retried on its own, so a persistent\n * error is not asked again on every unrelated restart of the read entry. A\n * field leaving the request takes its window and its relation with it.\n */\nconst withoutFailedFields = (\n remote: RemoteModel,\n planned: ReadonlyArray<Requirement>,\n): ReadonlyArray<Requirement> => {\n if (Object.keys(remote.failures.fields).length === 0) return planned\n return planned.flatMap(requirement => {\n const fields = requirement.fields.filter(\n field => !isFieldFailed(remote, requirement.entity, requirement.id, field),\n )\n if (fields.length === requirement.fields.length) return [requirement]\n if (fields.length === 0) return []\n const kept = new Set(fields)\n const only = <T>(record: Readonly<Record<string, T>> | undefined) =>\n record === undefined\n ? undefined\n : Object.fromEntries(Object.entries(record).filter(([field]) => kept.has(field)))\n const windows = only(requirement.windows)\n const relations = only(requirement.relations)\n return [\n {\n entity: requirement.entity,\n id: requirement.id,\n fields,\n ...(windows === undefined || Object.keys(windows).length === 0 ? {} : { windows }),\n ...(relations === undefined || Object.keys(relations).length === 0 ? {} : { relations }),\n ...(requirement.live === undefined ? {} : { live: requirement.live }),\n },\n ]\n })\n}\n\n/** The entity requirements a page's edges add under a selection. */\nconst itemsOf = (\n edges: ReadonlyArray<{ readonly entity: string; readonly id: string }>,\n select: RelationRequirement,\n): ReadonlyArray<Requirement> =>\n edges.filter(edge => edge.entity === select.entity).map(edge => ({ ...select, id: edge.id }))\n\n/**\n * The wire request of a planned query; a `QueryRef` identity carries the query\n * name and the canonical encoded input. A connection requirement built by hand\n * with another identity cannot be run, and fails as a query would.\n */\nconst queryRequestOf = (query: {\n readonly identity: string\n readonly window: QueryWindow\n}): Effect.Effect<Schema.Schema.Type<typeof QueryRequest>, RemoteQueryError> => {\n const separator = query.identity.indexOf('\\u0000')\n if (separator < 0) {\n return Effect.fail(\n new RemoteQueryError({\n message: `connection \"${query.identity}\" is not a query's: only a QueryRef identity can be run`,\n }),\n )\n }\n return Effect.try({\n try: () => ({\n query: query.identity.slice(0, separator),\n input: JSON.parse(query.identity.slice(separator + 1)) as unknown,\n window: query.window,\n }),\n catch: () =>\n new RemoteQueryError({ message: `connection \"${query.identity}\" carries no encoded input` }),\n })\n}\n\n/**\n * The `ConnectionMerged` for a query result, in the client's edge shape.\n * `refreshes` marks the page as answering the connection's refresh, so one\n * Message both merges it and clears `stale`.\n */\n/**\n * The page a window asked for, or the number of edges that came back instead.\n *\n * A window is a request the client made and the server answered, so more edges\n * than were asked for is a protocol disagreement rather than a windfall: the\n * client cannot tell which of them the window meant, the connection's\n * boundaries stop describing what it holds, and a `first: 25` that quietly\n * becomes a thousand is a memory event with no error attached to it.\n *\n * `undefined` when the page is within its window, or when no size was asked\n * for — `after`/`before` with no `first`/`last` bounds nothing.\n */\nconst overrun = (\n window: QueryWindow,\n edges: ReadonlyArray<unknown>,\n): { readonly asked: number; readonly got: number } | undefined => {\n const asked = window.first ?? window.last\n return asked !== undefined && edges.length > asked ? { asked, got: edges.length } : undefined\n}\n\nconst pageMessage = (\n connection: string,\n result: Schema.Schema.Type<typeof QueryResult>,\n refreshes = false,\n window: QueryWindow = {},\n): RemoteMessage => {\n // Failed the way any query fails, with a named protocol error, rather than\n // the page being silently accepted or an exception escaping a subscription.\n const over = overrun(window, result.edges)\n if (over !== undefined) {\n return {\n _tag: 'QueryFailed',\n connection,\n error: {\n _tag: 'RemoteProtocolError',\n message: `the server returned ${over.got} edges for a window of ${over.asked}`,\n },\n }\n }\n return {\n _tag: 'ConnectionMerged',\n connection,\n page: {\n edges: result.edges.map(edge => ({\n key: edge.key,\n ref: { entity: edge.entity, id: edge.id },\n })),\n start: result.start,\n end: result.end,\n },\n ...(refreshes ? { refreshes } : {}),\n }\n}\n\n/**\n * The retention roots of some projections: their requirements, their\n * connections (each with the union of what the projections select of its\n * items), and the connections listed by identity alone.\n */\nconst rootsOf = (\n projections: ReadonlyArray<Projection<any, unknown>>,\n options: RetainOptions,\n): RetentionRoots => {\n const connections = new Map<string, ConnectionRoot>()\n for (const identity of (options.connections ?? []).map(connectionIdentity)) {\n connections.set(identity, { identity })\n }\n for (const { identity, select } of projections.flatMap(connectionsOf)) {\n const current = connections.get(identity)?.select\n connections.set(identity, {\n identity,\n select: current === undefined ? select : Requirement.mergeRelation(current, select),\n })\n }\n return {\n requirements: Requirement.merge(projections.flatMap(requirementsOf)),\n connections: [...connections.values()].sort((a, b) => (a.identity < b.identity ? -1 : 1)),\n }\n}\n\n/** Reads requirements and reports the Message that settles them. Never fails. */\nconst readMessage = (\n requirements: ReadonlyArray<Requirement>,\n now: () => number,\n): Effect.Effect<RemoteMessage, never, RemoteClient> =>\n Effect.gen(function* () {\n const client = yield* RemoteClient\n const at = now()\n const result = yield* Effect.result(\n client.read({ version: REMOTE_PROTOCOL_VERSION, requests: requirements }),\n )\n return Result.isFailure(result)\n ? { _tag: 'ReadFailed', requests: requirements, error: remoteError(result.failure) }\n : { _tag: 'ReadReceived', requests: requirements, result: result.success, now: at }\n })\n\n/** Runs a query and reports the page that refreshes its connection, or the failure. Never fails. */\nconst queryMessage = (query: {\n readonly identity: string\n readonly window: QueryWindow\n}): Effect.Effect<RemoteMessage, never, RemoteClient> =>\n Effect.gen(function* () {\n const client = yield* RemoteClient\n const result = yield* Effect.result(\n queryRequestOf(query).pipe(Effect.flatMap(request => client.query(request))),\n )\n return Result.isFailure(result)\n ? { _tag: 'QueryFailed', connection: query.identity, error: remoteError(result.failure) }\n : pageMessage(query.identity, result.success, true, query.window)\n })\n\n/** A query the read entry runs, as its dependencies carry it: plain data Foldkit compares. */\nconst PlannedQuery = Schema.Struct({\n identity: Schema.String,\n window: WindowSchema,\n select: RelationRequest,\n})\n\n/** The dependencies of the read entry: the entity fields to read and the queries to run. */\nexport interface ReadDependencies {\n readonly requirements: ReadonlyArray<Requirement>\n readonly queries: ReadonlyArray<Schema.Schema.Type<typeof PlannedQuery>>\n /**\n * The highest generation the fields this entry reads were refreshed at: a\n * refresh of any of them restarts the entry, and a refresh of anything else\n * leaves it running.\n */\n readonly refresh: number\n}\n\n/**\n * The read entry: plans what `askedOf(model)` asks against the Model and runs\n * the entity read and the queries concurrently. Each Message it emits changes\n * the Model, so Foldkit recomputes the dependencies and restarts the stream\n * (`switchMap`): a merged page's items are planned by that next computation,\n * against the store as it then is, rather than read here unplanned. Nothing\n * the entry needs is spread over two Messages, since the second could be lost\n * to the restart; a page and its refresh are one `ConnectionMerged`.\n */\nconst observeEntry = <AppModel, Store extends RemoteModel, Message>(\n bound: BoundRemote<AppModel, Store>,\n askedOf: (model: AppModel) => Asked,\n toMessage: (message: RemoteMessage) => Message,\n options: ObserveOptions,\n): EntryWithoutKeepAlive<AppModel, Message, ReadDependencies, RemoteClient> => {\n const { policy = RemotePolicy.cacheFirst, now = Date.now } = options\n const read = (requirements: ReadonlyArray<Requirement>) =>\n Effect.map(readMessage(requirements, now), toMessage)\n const run = (query: ReadDependencies['queries'][number]) =>\n Effect.map(queryMessage(query), toMessage)\n return {\n dependenciesSchema: Schema.Struct({\n requirements: Schema.Array(ReadRequest),\n queries: Schema.Array(PlannedQuery),\n refresh: Schema.Number,\n }),\n modelToDependencies: model => {\n const remote = bound.store.get(model)\n const planned = planAsked(remote, askedOf(model), RemotePolicy.toPlan(policy, now()))\n return {\n refresh: refreshedAt(\n remote.refresh,\n planned.requirements,\n planned.queries.map(query => query.identity),\n ),\n requirements: planned.requirements,\n queries: planned.queries.map(({ identity, window, select }) => ({\n identity,\n window,\n select,\n })),\n }\n },\n dependenciesToStream: ({ requirements, queries, refresh }) =>\n Stream.concat(\n Stream.fromIterable([\n ...(requirements.length === 0\n ? []\n : [\n // Absent fields read as `Loading` until the read lands.\n toMessage({ _tag: 'ReadStarted', requests: requirements, refresh }),\n // A refreshing policy also marks the present ones stale.\n ...(RemotePolicy.refreshes(policy)\n ? [toMessage({ _tag: 'RefreshStarted', requests: requirements })]\n : []),\n ]),\n // A list with nothing to show reads `Loading` until its page lands.\n ...(queries.length === 0\n ? []\n : [\n toMessage({\n _tag: 'QueryStarted',\n connections: queries.map(query => query.identity),\n }),\n ]),\n ]),\n Stream.mergeAll(\n [\n ...(requirements.length === 0 ? [] : [Stream.fromEffect(read(requirements))]),\n ...queries.map(query => Stream.fromEffect(run(query))),\n ],\n { concurrency: 'unbounded' },\n ),\n ),\n }\n}\n\n/** The live entry: subscribes to `requirementsOf(model)` from the Model's resume cursor. */\nconst liveEntry = <AppModel, Store extends RemoteModel, Message>(\n bound: BoundRemote<AppModel, Store>,\n requirementsOf: (model: AppModel) => ReadonlyArray<Requirement>,\n toMessage: (message: RemoteMessage) => Message,\n options: LiveOptions,\n): EntryWithoutKeepAlive<\n AppModel,\n Message,\n { readonly requirements: ReadonlyArray<Requirement>; readonly cursor: LiveCursor },\n RemoteClient\n> => ({\n dependenciesSchema: Schema.Struct({\n requirements: Schema.Array(ReadRequest),\n cursor: Schema.Number,\n }),\n modelToDependencies: model => {\n const requirements = requirementsOf(model)\n const stream = liveStreamKey(requirements)\n return {\n requirements,\n cursor: bound.store.get(model).live[stream]?.cursor ?? 0,\n }\n },\n dependenciesToStream: ({ requirements, cursor }) =>\n requirements.length === 0\n ? Stream.empty\n : Stream.unwrap(\n Effect.gen(function* () {\n const client = yield* RemoteClient\n return client.live({ requirements, after: cursor })\n }),\n ).pipe(\n Stream.map(event =>\n toMessage({\n _tag: 'LiveReceived',\n stream: liveStreamKey(requirements),\n event,\n now: (options.now ?? Date.now)(),\n }),\n ),\n Stream.catchIf(\n (_error): _error is RemoteLiveError | RemoteProtocolError => true,\n error =>\n Stream.succeed(\n toMessage({\n _tag: 'ReadFailed',\n requests: requirements,\n error: remoteError(error),\n stream: liveStreamKey(requirements),\n }),\n ),\n ),\n ),\n})\n\n/** The projection an active Surface has for this Model, if it is active. */\nconst projectionOf = <AppModel>(\n entry: ActiveSurface<AppModel> | Surface<AppModel, any, any, void>,\n model: AppModel,\n): Projection<AppModel, unknown> | undefined =>\n 'projectionOf' in entry ? entry.projectionOf(model) : entry.projection()\n\n/**\n * `projectionOf` computed once per Model: the read, live, and retain entries\n * all derive their dependencies from the same projection on the same Model\n * change, and a Surface's `model` callback (which lifts and builds schemas)\n * need not run three times for it. Models are objects, so the memo is weak.\n */\nconst memoizedProjectionOf = <AppModel>(\n entry: ActiveSurface<AppModel> | Surface<AppModel, any, any, void>,\n): ((model: AppModel) => Projection<AppModel, unknown> | undefined) => {\n const cache = new WeakMap<object, Projection<AppModel, unknown> | undefined>()\n return model => {\n const key: unknown = model\n if (typeof key !== 'object' || key === null) return projectionOf(entry, model)\n if (cache.has(key)) return cache.get(key)\n const projection = projectionOf(entry, model)\n cache.set(key, projection)\n return projection\n }\n}\n\nexport const Remote = {\n /** The submodel's schema, the same for every domain; embed it in the application Model. */\n Model: remoteModelSchema(),\n /** The submodel's initial value. */\n initial: initialRemoteModel,\n /**\n * Remote's Message cases for `defineMessageUnion`: spread them into the\n * application's union, and reduce the ones `Remote.reduces` recognizes with\n * `RemoteDomain.reduce`.\n */\n messages: remoteMessageCases,\n /** Whether a Message is one of Remote's, by tag. */\n reduces: isRemoteMessage,\n\n /**\n * Declares a Remote domain and binds it to its place in the application Model\n * in one step; the result carries the application-facing operations. The\n * descriptor alone is `Remote.define`, the binding alone `Remote.at`.\n */\n make: <\n AppModel,\n Store extends RemoteModel,\n const Entities extends readonly EntityLike[],\n const Queries extends readonly QueryDescriptor<any, any, any>[] = readonly [],\n const Mutations extends readonly MutationDescriptor<any, any, any>[] = readonly [],\n >(config: {\n readonly model: ModelRef<AppModel, Store>\n readonly entities: Entities\n readonly queries?: Queries\n readonly mutations?: Mutations\n }): RemoteDomain<AppModel, Store, Entities, Queries, Mutations> =>\n bindDomain(defineRemote(config), config.model),\n\n /**\n * Declares a Remote domain without binding it: its entities, queries, and\n * mutations, plus the submodel. For a domain reused across applications or\n * bound in a test; `Remote.make` is the one-step form.\n */\n define: defineRemote,\n\n /**\n * Binds a Remote domain to its store's location in the application Model. The\n * registered entity names are carried on the returned value, so `Remote.select`\n * rejects a selection for an entity this domain never declared.\n */\n at: bindRemote,\n\n /**\n * A Projection node that reads a `RemoteData` value out of the store. The id\n * is supplied by the caller, usually from a Surface's params. The assembled\n * value is decoded against the Selection, so malformed server data surfaces\n * as `Failed` instead of being asserted into `Value`. A present value with a\n * stale field reads as `Refreshing`: an observer is refetching it.\n */\n select: <AppModel, Store extends RemoteModel, Names extends string, Value, Name extends string>(\n bound: BoundRemote<AppModel, Store, Names>,\n given: EntitySelection<Value, Name> & Registered<Name, Names, 'Entity'>,\n ) => {\n const selection = selectionOf<Value, Name>(given)\n assertRegistered(bound, 'Entity', bound.definition.registry.entities, selection.entity)\n const relation = relationOf(selection)\n return (id: string): Projection<AppModel, RemoteData<Value>> => ({\n Model: remoteDataSchema(selection.schema),\n dependencies: [],\n metadata: RemoteRequirements.of({ ...relation, id }),\n read: (root: AppModel): RemoteData<Value> => {\n const store = storeOf(bound, root)\n const key = entityKey(selection.entity, id)\n // The store-dependent half is memoized per store snapshot; `undefined`\n // means the store lacks the value. Whether that reads as `Loading` or\n // `Initial` depends on the in-flight marks, which change independently\n // of the store, so it is decided outside the memo.\n const present = memoRead<RemoteData<Value> | undefined>(\n store,\n store,\n `${key}\\u0000${stableStringify(relation)}`,\n () => {\n if (isTombstone(store, key)) return { _tag: 'NotFound' }\n const assembled = assemble(store, key, relation)\n if (assembled === undefined) return undefined\n const decoded = Schema.decodeUnknownResult(selection.schema)(assembled.values)\n return Result.isFailure(decoded)\n ? { _tag: 'Failed', error: { _tag: 'DecodeError', message: decoded.failure.message } }\n : assembled.refreshing\n ? { _tag: 'Refreshing', value: decoded.success }\n : { _tag: 'Ready', value: decoded.success }\n },\n )\n // Decided outside the memo, as loading is: a failure can arrive\n // without the store changing.\n const remote = bound.store.get(root)\n const failure = failureOf(remote, selection.entity, id, relation)\n if (present !== undefined) {\n // A value on screen whose refresh failed stays on screen, with the\n // error, which `RemoteData.render` draws as stale.\n return failure !== undefined &&\n (present._tag === 'Ready' || present._tag === 'Refreshing')\n ? { _tag: 'Failed', error: failure, previous: present.value }\n : present\n }\n if (isLoading(remote, selection.entity, id, relation.fields)) return { _tag: 'Loading' }\n // Nothing is fetching this. Either its read failed, which is said, or no\n // active Surface observes it, which is usually a wiring mistake.\n return failure === undefined ? { _tag: 'Initial' } : { _tag: 'Failed', error: failure }\n },\n })\n },\n\n /**\n * The pure plan for a projection against a Model: the requirements its\n * remote store does not satisfy, under `options` (freshness, force). A\n * Surface's projection is `surface.projection(params)`.\n */\n plan: <AppModel, Store extends RemoteModel, Value>(\n bound: BoundRemote<AppModel, Store>,\n model: AppModel,\n projection: Projection<AppModel, Value>,\n options?: PlanOptions,\n ): ReadonlyArray<Requirement> =>\n planAsked(bound.store.get(model), askedOf(projection), options ?? {}).requirements,\n\n /**\n * The queries a projection needs run before its connections read: those the\n * Model does not hold, or holds stale (every one under `force`).\n */\n planQueries: <AppModel, Store extends RemoteModel, Value>(\n bound: BoundRemote<AppModel, Store>,\n model: AppModel,\n projection: Projection<AppModel, Value>,\n options?: PlanOptions,\n ): ReadonlyArray<QueryRef<string, unknown>> =>\n planAsked(bound.store.get(model), askedOf(projection), options ?? {}).queries.flatMap(query =>\n query.ref === undefined ? [] : [query.ref],\n ),\n\n /**\n * The store reads see: the base store under the pending optimistic layers.\n * One store is shared by every read and plan of a Model whose remote state\n * has not changed.\n */\n storeOf: <AppModel, Store extends RemoteModel>(\n bound: BoundRemote<AppModel, Store>,\n model: AppModel,\n ): EntityStore => storeOf(bound, model),\n\n /**\n * The projection read against the server-derived store alone: the same\n * requirements, planned the same way, with the pending optimistic layers and\n * connection overlays left off. See the bound `Remote.confirmed`.\n */\n confirmed: <AppModel, Store extends RemoteModel, P extends Projection<AppModel, any>>(\n bound: BoundRemote<AppModel, Store>,\n projection: P,\n ): P => confirmed(bound, projection),\n\n /**\n * Executes the plan against the `RemoteClient` and returns a new store. Used\n * for SSR route prefetch, hover prefetch, and tests. Never called during render.\n * `policy` decides what a present field means (default cache-first); `now`\n * is the clock it reads, so the planner itself stays pure and time-injected.\n */\n prefetch: Effect.fn('Remote.prefetch')(function* <AppModel, Store extends RemoteModel, Value>(\n bound: BoundRemote<AppModel, Store>,\n model: AppModel,\n projection: Projection<AppModel, Value>,\n options: ObserveOptions = {},\n ) {\n const store = storeOf(bound, model)\n const { policy = RemotePolicy.cacheFirst, now = Date.now } = options\n const at = now()\n const missing = plan(store, requirementsOf(projection), RemotePolicy.toPlan(policy, at))\n if (missing.length === 0) return store\n yield* Effect.annotateCurrentSpan('requirementCount', missing.length)\n const client = yield* RemoteClient\n const result = yield* client.read({ version: REMOTE_PROTOCOL_VERSION, requests: missing })\n return writeRead(store, missing, result, at)\n }),\n\n /**\n * Marks what a projection, or a Surface without params, requires as due again.\n * Called from `update`: every selected field the store holds reads `Refreshing`,\n * and every loaded query connection is invalidated. Nothing is fetched here.\n * The read entries `Data.subscriptions` derives refetch it, because a stale\n * field or connection is planned again under every policy, so a refresh never\n * sends a request beside the entry already observing the same data.\n *\n * A refreshed connection's page replaces its pages, so items the server removed\n * or reordered follow it; pages loaded past the first are dropped and paged\n * again with `next`/`previous`. The read entries restart, so a read or query\n * sent before the refresh is not applied after it.\n *\n * It is also how a failed query is retried: a connection whose query failed\n * is not run again on its own, so its read stays `Failed` until this asks.\n *\n * The projection must be observed, which it is while it is on screen. Live\n * subscriptions are left as they are. For data nothing observes (SSR, tests),\n * use `Remote.prefetch` with `RemotePolicy.networkOnly`. Refreshing what is\n * already being refreshed returns the same Model.\n */\n refresh: <AppModel, Store extends RemoteModel>(\n bound: BoundRemote<AppModel, Store>,\n model: AppModel,\n target: Projection<AppModel, unknown> | Surface<AppModel, any, any, void>,\n ): AppModel => {\n const projection = 'read' in target ? target : target.projection(undefined)\n const remote = bound.store.get(model)\n const asked = askedOf(projection)\n const connections = Requirement.mergeConnections(\n asked.connections,\n ) as ReadonlyArray<QueryRequirement>\n // A loaded connection's current items are marked with the entities; its page\n // is re-run by the read entry, and new items are planned when it lands.\n const items = connections.flatMap(connection => {\n const known = remote.connections[connection.identity]\n return known === undefined\n ? []\n : itemsOf(\n visibleItems(\n known,\n connection.identity,\n remote.optimistic.overlays,\n remote.entities,\n ).map(edge => edge.ref),\n connection.select,\n )\n })\n const requirements = plan(\n visibleStoreOf(remote.entities, remote.optimistic),\n [...asked.requirements, ...items],\n { force: true },\n )\n\n // A connection the Model never loaded is already a query to run: there is\n // nothing to invalidate and nothing to restart, so it takes no generation\n // either — unless its query failed, which is exactly what a refresh retries.\n const invalidated = connections\n .filter(\n connection =>\n remote.connections[connection.identity] !== undefined ||\n connection.identity in remote.failures.connections,\n )\n .map(connection => connection.identity)\n const marks: RemoteMessage[] = [\n ...(requirements.length === 0\n ? []\n : [{ _tag: 'RefreshStarted' as const, requests: requirements }]),\n ...invalidated.map(connection => ({\n _tag: 'ConnectionInvalidated' as const,\n connection,\n })),\n ]\n const marked = marks.reduce(updateRemote, remote)\n // Fields already stale may be in a read that began before this refresh (a\n // refreshing policy marks what it refetches); unless no read has begun since\n // the last refresh, that read is restarted too.\n const inFlight = requirements.some(requirement =>\n requirement.fields.some(\n field =>\n remote.entities[entityKey(requirement.entity, requirement.id)]?.stale.has(field) ===\n true && refreshIsInFlight(remote.refresh, requirement, field),\n ),\n )\n // Marking what is already marked changes nothing, so the Model keeps its identity.\n if (marked === remote && !inFlight) return model\n const refresh = withRefreshRequested(marked.refresh, requirements, invalidated)\n return bound.store.set(model, { ...marked, refresh } as Store)\n },\n\n /**\n * Writes a read result into the store, recording each field's applied window.\n * `requests` are the planned requirements the result answers.\n */\n writeRead,\n\n /**\n * Adapts an Effect RPC client for `RemoteRpc` to `RemoteClient`, so an\n * application provides the transport's RPC layer instead of writing the\n * `LiveChange`-to-`LiveEvent` mapping by hand.\n */\n clientLayer: <R = never>(\n client: RemoteRpcClient<R>,\n options: CoalesceOptions = {},\n ): Layer.Layer<RemoteClient, never, R> =>\n coalescedLayer(\n Layer.effect(\n RemoteClient,\n Effect.gen(function* () {\n // What the RPC client needs (a database under in-process handlers,\n // nothing under a transport) is supplied once, when the layer is built.\n const context = yield* Effect.context<R>()\n return {\n read: batch => client.FoldkitRemoteRead(batch).pipe(Effect.provideContext(context)),\n query: request =>\n client.FoldkitRemoteQuery(request).pipe(Effect.provideContext(context)),\n mutate: request =>\n client.FoldkitRemoteMutate(request).pipe(Effect.provideContext(context)),\n live: ({ requirements, after }) =>\n client\n .FoldkitRemoteLive({ version: REMOTE_PROTOCOL_VERSION, requirements, after })\n .pipe(Stream.map(liveEventOf), Stream.provideContext(context)),\n }\n }),\n ),\n options,\n ),\n\n /**\n * Wraps a `RemoteClient` layer so its reads coalesce: requirements issued\n * together become one batch, and a requirement already in flight is joined.\n * `Remote.clientLayer` applies this; use it on a hand-written client.\n */\n coalesced: coalescedLayer,\n\n /**\n * A Foldkit Subscription entry that keeps the cache to what the active\n * Surfaces reach. `projections` are the ones the application observes (the\n * same it passes to `Remote.observe`), `connections` the query connections\n * it shows; anything else is collected once the roots have been stable for\n * `grace`, so a route transition that comes straight back does not thrash.\n */\n retain: <AppModel, Message = RemoteMessage>(\n projections: ReadonlyArray<Projection<AppModel, unknown>>,\n toMessage: (message: RemoteMessage) => Message = identityMessage as never,\n options: RetainOptions = {},\n ): EntryWithoutKeepAlive<AppModel, Message, RetentionRoots, never> => {\n const roots = rootsOf(projections, options)\n return {\n dependenciesSchema: retentionRootsSchema,\n modelToDependencies: () => roots,\n dependenciesToStream: current =>\n Stream.fromEffect(\n Effect.succeed(toMessage({ _tag: 'RetentionChanged', roots: current })).pipe(\n Effect.delay(options.grace ?? 0),\n ),\n ),\n }\n },\n\n /**\n * Runs a `Query` through `RemoteClient`, encoding its input from the ref.\n * Pair the result with `Remote.queryMessage` to merge the page into the Model.\n */\n query: Effect.fn('Remote.query')(function* <Name extends string, Input>(\n ref: QueryRef<Name, Input>,\n ) {\n const client = yield* RemoteClient\n const input = yield* Schema.encodeUnknownEffect(ref.Input)(ref.input).pipe(\n Effect.catchTag('SchemaError', error =>\n Effect.fail(new RemoteQueryError({ message: error.message })),\n ),\n )\n return yield* client.query({ query: ref.query, input, window: ref.window })\n }),\n\n /** The `RemoteMessage` that merges a query page into its connection. */\n queryMessage: <Name extends string, Input>(\n ref: QueryRef<Name, Input>,\n result: Schema.Schema.Type<typeof QueryResult>,\n ): RemoteMessage => pageMessage(ref.identity, result, false, ref.window),\n\n /**\n * The edges a connection shows: its server-known region with pending and\n * confirmed overlays placed around it, minus removed edges and edges whose\n * target is a tombstone.\n */\n visibleItems: (model: RemoteModel, connection: ConnectionIdentity): ReadonlyArray<Edge> => {\n const identity = connectionIdentity(connection)\n return visibleItems(\n model.connections[identity] ?? emptyConnection,\n identity,\n model.optimistic.overlays,\n model.entities,\n )\n },\n\n /** A pure, serializable view of the whole cache. */\n inspect: inspectRemote,\n\n /** A pure, serializable view of one entity, or `undefined` if unknown. */\n inspectEntity,\n\n /**\n * Runs a mutation through `RemoteClient`, decoding its typed Output and\n * returning the result's normalized patches so the caller can reconcile them\n * through `updateRemote`'s `MutationSucceeded` (or `Remote.mutateInto`).\n */\n mutate: mutateRemote,\n\n /**\n * Runs a mutation and reconciles its patches into a `RemoteModel` in one step,\n * returning the new model alongside the typed Output. The model-level form of\n * `MutationStarted` → `RemoteClient.mutate` → `MutationSucceeded`; in an\n * application the three are `update` (with `optimistic`), a Command, and the\n * Message the Command returns, so the optimistic operations show meanwhile.\n */\n mutateInto: Effect.fn('Remote.mutateInto')(function* <\n Name extends string,\n Input,\n Output,\n AppModel,\n Store extends RemoteModel,\n >(\n bound: BoundRemote<AppModel, Store>,\n model: AppModel,\n mutation: MutationDescriptor<Name, Input, Output>,\n input: Input,\n requestId: string,\n options: MutateOptions = {},\n ) {\n const started = updateRemote(bound.store.get(model), {\n _tag: 'MutationStarted',\n requestId,\n ...(options.optimistic === undefined ? {} : { optimistic: options.optimistic }),\n })\n const outcome = yield* mutateRemote(mutation, input, requestId)\n const settled = updateRemote(started, {\n _tag: 'MutationSucceeded',\n requestId,\n entities: outcome.entities,\n connections: outcome.connections,\n deleted: outcome.deleted,\n })\n return {\n output: outcome.output,\n model: bound.store.set(model, settled as Store),\n }\n }),\n\n /**\n * A Foldkit Subscription entry that plans a Surface's missing fields from the\n * Model and fetches them through `RemoteClient`, emitting a `RemoteMessage`\n * per outcome. Wrap it in an application Message (`toMessage`) and reduce it\n * with the domain's `update`. Under a refreshing `policy` the entry first\n * emits `RefreshStarted`, so the fields being refetched read as `Refreshing`\n * while the request is pending.\n */\n observe: <\n AppModel,\n Store extends RemoteModel,\n Names extends string,\n Model,\n SurfaceMessage,\n Params,\n Message = RemoteMessage,\n >(\n bound: BoundRemote<AppModel, Store, Names>,\n surface: Surface<AppModel, Model, SurfaceMessage, Params>,\n params: Params,\n toMessage: (message: RemoteMessage) => Message = identityMessage as never,\n options: ObserveOptions = {},\n ): EntryWithoutKeepAlive<AppModel, Message, ReadDependencies, RemoteClient> =>\n observeEntry(bound, () => askedOf(surface.projection(params)), toMessage, options),\n\n /**\n * A Foldkit Subscription entry that consumes the live stream for a Surface's\n * requirements, emitting a `LiveReceived` per event and a `ReadFailed`\n * carrying its `stream` when the stream breaks (including\n * `ResumeUnavailable`). That records a gap on the stream rather than a failed\n * read, since nothing was being read. The resume cursor is read\n * from `RemoteModel.live`, so the application tracks no cursor of its own.\n */\n live: <\n AppModel,\n Store extends RemoteModel,\n Names extends string,\n Model,\n SurfaceMessage,\n Params,\n Message = RemoteMessage,\n >(\n bound: BoundRemote<AppModel, Store, Names>,\n surface: Surface<AppModel, Model, SurfaceMessage, Params>,\n params: Params,\n toMessage: (message: RemoteMessage) => Message = identityMessage as never,\n options: LiveOptions = {},\n ): EntryWithoutKeepAlive<\n AppModel,\n Message,\n { readonly requirements: ReadonlyArray<Requirement>; readonly cursor: LiveCursor },\n RemoteClient\n > => liveEntry(bound, () => requirementsOf(surface.projection(params)), toMessage, options),\n}\n\n// A domain's Subscription entries are unbranded so an application can spread\n// them into its own `Subscription.make`; wiring hands them over as a branded record.\nconst brandEntries = <AppModel>(\n entries: Readonly<Record<string, RemoteEntry<AppModel, any>>>,\n): Subscription.Subscriptions<AppModel, RemoteMessage, RemoteClient> =>\n Subscription.make<AppModel, RemoteMessage, RemoteClient>()(() => entries)\n\n/** The bound domain: the descriptor, the binding, and the operations over them. */\nconst bindDomain = <\n AppModel,\n Store extends RemoteModel,\n Entities extends readonly EntityLike[],\n Queries extends readonly QueryDescriptor<any, any, any>[],\n Mutations extends readonly MutationDescriptor<any, any, any>[],\n>(\n definition: RemoteDescriptor<Entities, Queries, Mutations>,\n store: ModelRef<AppModel, Store>,\n): RemoteDomain<AppModel, Store, Entities, Queries, Mutations> => {\n const bound = bindRemote(definition, store)\n /**\n * What to do with a row a live event says was inserted into a connection.\n *\n * Resolved here rather than in the pure reducer because this is the only\n * place with both the Model and the registry, and two separate things needed\n * one or the other.\n *\n * **The declared policy reaches the decision.** `Query.connection(E, { live })`\n * has always been typed, documented, carried on the descriptor and encoded in\n * the Message schema — and nothing ever put it on a Message, so every live\n * insert took the default whatever an application asked for. It does now.\n *\n * **A row the client can judge does not need a policy.** The policy exists\n * because nothing could tell whether an inserted row belonged to the query.\n * Where the body says it does not, `ignore` is not a guess. Where the body\n * says it does, or the client cannot tell — a row it never fetched, or holds\n * without a field the body reads — the declared policy is the answer, exactly\n * as it was meant to be.\n *\n * Only membership is decided here. *Where* a row sorts needs text collation,\n * which is the backend's, so the position the event carries stands.\n */\n const livePolicyFor = (model: AppModel, event: LiveEvent): LivePolicy | undefined => {\n if (event._tag !== 'ConnectionInsert') return undefined\n // An identity is always `name`, the separator, and the encoded input — it\n // is minted in exactly one place — so the separator is always present.\n const identity = event.connection\n const descriptor = definition.registry.queries.get(\n identity.slice(0, identity.indexOf(IDENTITY_SEPARATOR)),\n )\n const declared = (descriptor?.Result as Partial<ConnectionSpec> | undefined)?.live\n if (descriptor?.body === undefined) return declared\n const encoded = JSON.parse(identity.slice(identity.indexOf(IDENTITY_SEPARATOR) + 1)) as Record<\n string,\n unknown\n >\n const decided = belongsEncoded(\n storeOf(bound, model),\n descriptor,\n encoded,\n entityKey(event.edge.ref.entity, event.edge.ref.id),\n )\n return decided === 'no' ? { prepend: 'ignore', append: 'ignore' } : declared\n }\n\n // An application-union case has the runtime shape of the `RemoteMessage` it names.\n const reduce = (model: AppModel, message: RemoteMessage | RemoteMessageInput): AppModel => {\n const live =\n (message as RemoteMessage)._tag === 'LiveReceived'\n ? (message as Extract<RemoteMessage, { _tag: 'LiveReceived' }>)\n : undefined\n // A caller that said what it wanted keeps it; `updateRemote` on its own is\n // unchanged, so the pure reducer stays testable without a registry.\n const resolved =\n live === undefined || live.policy !== undefined\n ? message\n : { ...live, policy: livePolicyFor(model, live.event) }\n return store.set(model, updateRemote(store.get(model), resolved as RemoteMessage) as Store)\n }\n const domain: RemoteDomain<AppModel, Store, Entities, Queries, Mutations> = {\n ...definition,\n ...bound,\n get: (selection, id) => Remote.select(bound, selection)(id),\n live: (selection, id) => {\n const projection = Remote.select(bound, selection)(id)\n return {\n ...projection,\n metadata: RemoteRequirements.of(\n ...requirementsOf(projection).map(requirement => ({ ...requirement, live: true })),\n ),\n }\n },\n subscriptions: (active, options = {}) => {\n // Dependencies differ per entry, as in Foldkit's own `Subscriptions` record.\n const entries: Record<string, RemoteEntry<AppModel, any>> = {}\n const projections: Array<(model: AppModel) => Projection<AppModel, unknown> | undefined> = []\n for (const [key, entry] of Object.entries(active)) {\n // Two applications can have the same Model type; the owner token tells them apart.\n if (bound.contract.owner !== undefined && entry.owner !== bound.contract.owner) {\n throw new Error(\n `Remote: Surface \"${entry.name}\" belongs to another application than domain \"${bound.contract.name}\"`,\n )\n }\n const projectionAt = memoizedProjectionOf(entry)\n projections.push(projectionAt)\n const asked = (model: AppModel) => askedOf(projectionAt(model))\n entries[`${key}.read`] = observeEntry(bound, asked, identityMessage, options)\n entries[`${key}.live`] = liveEntry(\n bound,\n model => asked(model).requirements.filter(requirement => requirement.live === true),\n identityMessage,\n options,\n )\n }\n entries.retain = {\n dependenciesSchema: retentionRootsSchema,\n modelToDependencies: model =>\n rootsOf(\n projections.flatMap(projectionAt => {\n const projection = projectionAt(model)\n return projection === undefined ? [] : [projection]\n }),\n options,\n ),\n dependenciesToStream: (current: RetentionRoots) =>\n Stream.fromEffect(\n Effect.succeed<RemoteMessage>({ _tag: 'RetentionChanged', roots: current }).pipe(\n Effect.delay(options.grace ?? 0),\n ),\n ),\n }\n // The loop above wrote exactly the keys the mapped type names.\n return entries as SubscriptionEntries<AppModel, typeof active>\n },\n plan: (model, projection, options) => Remote.plan(bound, model, projection, options),\n storeOf: model => storeOf(bound, model),\n confirmed: projection => confirmed(bound, projection),\n prefetch: (model, projection, options = {}) =>\n Effect.gen(function* () {\n const { policy = RemotePolicy.cacheFirst, now = Date.now } = options\n const client = yield* RemoteClient\n const planOptions = RemotePolicy.toPlan(policy, now())\n let current = model\n // The pages first, so their items join the one entity read below.\n for (const query of planAsked(store.get(current), askedOf(projection), planOptions)\n .queries) {\n const page = yield* queryRequestOf(query).pipe(\n Effect.flatMap(request => client.query(request)),\n )\n current = reduce(current, pageMessage(query.identity, page, true, query.window))\n }\n const requirements = planAsked(\n store.get(current),\n askedOf(projection),\n planOptions,\n ).requirements\n if (requirements.length === 0) return current\n const at = now()\n const result = yield* client.read({\n version: REMOTE_PROTOCOL_VERSION,\n requests: requirements,\n })\n return reduce(current, { _tag: 'ReadReceived', requests: requirements, result, now: at })\n }),\n query: <Q extends QueryDescriptor<any, any, any>, Value, Entity extends string>(\n query: Q,\n input: QueryInput<Q>,\n options: QueryOptions<Value, Entity, QueryEntity<Q>>,\n ): QueryProjection<AppModel, Value, Q['name'], QueryInput<Q>> => {\n assertRegistered(bound, 'Query', definition.registry.queries, query.name)\n const { select: given, ...window } = options\n const select = selectionOf<Value, Entity>(given)\n for (const [side, size] of [\n ['first', window.first],\n ['last', window.last],\n ] as const) {\n if (size !== undefined && !(Number.isInteger(size) && size >= 0)) {\n throw new Error(\n `Remote: query \"${query.name}\" asks for ${side}: ${String(size)}; a page size is a non-negative integer`,\n )\n }\n }\n const listed = (query.Result as Partial<ConnectionSpec>).entity\n if (listed === undefined) {\n throw new Error(\n `Remote: query \"${query.name}\" is not a connection over an entity, so it has no page to select`,\n )\n }\n if (select.entity !== listed) {\n throw new Error(\n `Remote: the selection is of \"${select.entity}\", but query \"${query.name}\" lists \"${listed}\"`,\n )\n }\n const ref: QueryRef<Q['name'], QueryInput<Q>> = {\n ...query.ref(input),\n window: pickWindow(window),\n }\n const relation = relationOf(select)\n const relationKey = stableStringify(relation)\n // The first failed field among the rows a list shows, if any. Decided\n // outside the memo, which is keyed on the store and the connection: a\n // failure can arrive without either changing.\n const failedItem = (\n remote: RemoteModel,\n connection: Connection,\n ): { readonly _tag: 'Failed'; readonly error: RemoteError } | undefined => {\n if (Object.keys(remote.failures.fields).length === 0) return undefined\n for (const edge of visibleItems(\n connection,\n ref.identity,\n remote.optimistic.overlays,\n remote.entities,\n )) {\n if (edge.ref.entity !== relation.entity) continue\n const error = failureOf(remote, edge.ref.entity, edge.ref.id, relation)\n if (error !== undefined) return { _tag: 'Failed', error }\n }\n return undefined\n }\n // A page carries refs; its rows' fields are read after it lands. While\n // that read is in flight the list is loading, not `Initial`.\n const loadingItem = (\n remote: RemoteModel,\n connection: Connection,\n ): { readonly _tag: 'Loading' } | undefined => {\n if (remote.loading.size === 0) return undefined\n for (const edge of visibleItems(\n connection,\n ref.identity,\n remote.optimistic.overlays,\n remote.entities,\n )) {\n if (edge.ref.entity !== relation.entity) continue\n if (isLoading(remote, edge.ref.entity, edge.ref.id, relation.fields)) {\n return { _tag: 'Loading' }\n }\n }\n return undefined\n }\n // The page as the rows held make it, before any failure is laid over it;\n // `undefined` when a row is missing a field.\n const readPage = (\n remote: RemoteModel,\n connection: Connection,\n ): RemoteData<Page<Value>> | undefined => {\n const visible = visibleStoreOf(remote.entities, remote.optimistic)\n return memoRead<RemoteData<Page<Value>> | undefined>(\n visible,\n connection,\n `${ref.identity}\\u0000${relationKey}`,\n () => {\n const items: Value[] = []\n let refreshing = connection.stale\n const edges = visibleItems(\n connection,\n ref.identity,\n remote.optimistic.overlays,\n remote.entities,\n )\n for (const edge of edges) {\n const assembled = assemble(visible, entityKey(edge.ref.entity, edge.ref.id), relation)\n if (assembled === undefined) return undefined\n const decoded = Schema.decodeUnknownResult(select.schema)(assembled.values)\n if (Result.isFailure(decoded)) {\n return {\n _tag: 'Failed',\n error: { _tag: 'DecodeError', message: decoded.failure.message },\n }\n }\n refreshing ||= assembled.refreshing\n items.push(decoded.success)\n }\n const page = {\n items,\n hasNext: hasNext(connection),\n hasPrevious: hasPrevious(connection),\n }\n return refreshing ? { _tag: 'Refreshing', value: page } : { _tag: 'Ready', value: page }\n },\n )\n }\n const requirement: QueryRequirement = {\n identity: ref.identity,\n window: ref.window,\n select: relation,\n ref,\n }\n return {\n Model: remoteDataSchema(pageSchema(select.schema)) as Schema.Codec<\n RemoteData<Page<Value>>,\n unknown\n >,\n dependencies: [],\n metadata: RemoteConnections.of(requirement),\n ref,\n selection: select as Selection<Value, string>,\n read: (root: AppModel): RemoteData<Page<Value>> => {\n const remote = store.get(root)\n const connection = remote.connections[ref.identity]\n const failure = remote.failures.connections[ref.identity]\n // Invalidating a connection the Model never loaded records it stale with no\n // segments: still nothing to show. (A loaded empty page is not stale.)\n if (connection === undefined || (connection.stale && connection.segments.length === 0)) {\n if (isQueryLoading(remote, ref.identity)) return { _tag: 'Loading' }\n return failure === undefined ? { _tag: 'Initial' } : { _tag: 'Failed', error: failure }\n }\n // A query that answered is not the whole of a list: its rows' fields\n // are read separately, and one of those failing is the list's failure.\n const read = readPage(remote, connection) ??\n failedItem(remote, connection) ??\n loadingItem(remote, connection) ?? { _tag: 'Initial' }\n if (failure === undefined) {\n if (read._tag !== 'Ready' && read._tag !== 'Refreshing') return read\n const item = failedItem(remote, connection)\n return item === undefined\n ? read\n : { _tag: 'Failed', error: item.error, previous: read.value }\n }\n // The rows held before the failure are still the best there is, so they\n // go with it as `previous`, which `RemoteData.render` shows as stale.\n switch (read._tag) {\n case 'Ready':\n case 'Refreshing':\n return { _tag: 'Failed', error: failure, previous: read.value }\n case 'Failed':\n return read\n default:\n return { _tag: 'Failed', error: failure }\n }\n },\n }\n },\n next: (model, projection) => {\n const segments = store.get(model).connections[projection.ref.identity]?.segments ?? []\n const end = segments[segments.length - 1]?.end\n return end?._tag === 'Cursor'\n ? {\n ...projection.ref,\n window: { ...pageSize(projection.ref.window, 'first'), after: end.cursor },\n }\n : undefined\n },\n previous: (model, projection) => {\n const start = store.get(model).connections[projection.ref.identity]?.segments[0]?.start\n return start?._tag === 'Cursor'\n ? {\n ...projection.ref,\n window: { ...pageSize(projection.ref.window, 'last'), before: start.cursor },\n }\n : undefined\n },\n explain: (model, projection, options) => {\n const { ref } = projection\n // Which active Surfaces read this connection, asked of the Model rather\n // than of the projection: a Surface's projection is rebuilt per Model, so\n // the only honest comparison is by connection identity.\n const reading = Object.values(options?.surfaces ?? {}).filter(active => {\n const active_ = active.projectionOf(model)\n // An inactive Surface reads nothing, which is not the same as reading\n // something else.\n return (\n active_ !== undefined &&\n connectionsOf(active_).some(connection => connection.identity === ref.identity)\n )\n })\n // The body lives on the descriptor, and a projection keeps only its\n // `QueryRef` — so the explanation looks the definition back up by name.\n // Which it can, because `Data` is bound to the domain that registered it.\n const body = definition.registry.queries.get(ref.query)?.body\n const [connection] = RemoteConnections.get(projection.metadata)\n return {\n domain: bound.contract.name,\n query: ref.query,\n input: Schema.encodeSync(ref.Input)(ref.input),\n identity: ref.identity,\n window: ref.window,\n select: connection!.select,\n ...(body === undefined\n ? {}\n : { body: Relational.show(body), dependencies: Relational.dependencies(body) }),\n state: projection.read(model)._tag,\n ...(options?.surfaces === undefined\n ? {}\n : {\n surfaces: reading.map(active => active.name),\n activation: reading.flatMap(active =>\n active.activation === undefined\n ? []\n : [{ surface: active.name, ...active.activation }],\n ),\n }),\n }\n },\n filtered: (model, over, by, input) => {\n assertRegistered(bound, 'Query', definition.registry.queries, by.name)\n // A filter over a different Entity can never match anything, and would\n // otherwise answer \"I checked the whole list and found nothing\" — a\n // confident wrong answer rather than a refusal.\n const filters = by.body?.entity.name\n if (filters !== undefined && filters !== over.selection.entity) {\n throw new Error(\n `Remote: query \"${by.name}\" is over \"${filters}\", but the list is of \"${over.selection.entity}\", so it cannot filter it`,\n )\n }\n const remote = store.get(model)\n const connection = remote.connections[over.ref.identity]\n const visible = visibleStoreOf(remote.entities, remote.optimistic)\n const edges =\n connection === undefined\n ? []\n : visibleItems(connection, over.ref.identity, remote.optimistic.overlays, remote.entities)\n const among = edges.map(edge => entityKey(edge.ref.entity, edge.ref.id))\n const judged = matching(visible, by, input, { among })\n const relation = relationOf(over.selection)\n\n const items: unknown[] = []\n let assembledAll = true\n for (const key of judged.matched) {\n const assembled = assemble(visible, key, relation)\n // A matching row whose selected fields are not all here cannot be shown.\n // It is not dropped from the truth, only from the list: `complete` says\n // the answer is about less than the whole.\n if (assembled === undefined) {\n assembledAll = false\n continue\n }\n const decoded = Schema.decodeUnknownResult(over.selection.schema)(assembled.values)\n if (Result.isFailure(decoded)) {\n assembledAll = false\n continue\n }\n items.push(decoded.success)\n }\n\n return {\n items: items as never,\n // Whole only if every edge was judged, every match could be shown, and\n // the list itself is all there — a connection terminal at both ends.\n // Whole only if every edge was judged, every match could be shown, and\n // the list itself is all there. `hasNext`/`hasPrevious` read the outer\n // boundaries alone, so `isGapped` is the third question: a connection\n // paged from both ends is `Terminal` at both and still missing its\n // middle.\n complete:\n judged.skipped.length === 0 &&\n assembledAll &&\n connection !== undefined &&\n !isGapped(connection) &&\n !hasNext(connection) &&\n !hasPrevious(connection),\n }\n },\n refresh: (model, target) => Remote.refresh(bound, model, target),\n overlay: (model, id, optimistic) =>\n bound.store.set(\n model,\n updateRemote(bound.store.get(model), { _tag: 'OverlayShown', id, optimistic }) as Store,\n ),\n lift: (model, id) => {\n const remote = bound.store.get(model)\n const lifted = updateRemote(remote, { _tag: 'OverlayLifted', id })\n return lifted === remote ? model : bound.store.set(model, lifted as Store)\n },\n fetch: ref => ({\n name: `Remote.query(${ref.query})`,\n args: { connection: ref.identity, window: ref.window },\n effect: Remote.query(ref).pipe(\n Effect.match({\n onFailure: (error): RemoteMessage => ({\n _tag: 'QueryFailed',\n connection: ref.identity,\n error: remoteError(error),\n }),\n onSuccess: (page): RemoteMessage => pageMessage(ref.identity, page, false, ref.window),\n }),\n ),\n }),\n mutate: (model, mutation, input, options = {}) => {\n assertRegistered(bound, 'Mutation', definition.registry.mutations, mutation.name)\n const remote = store.get(model)\n const requestId =\n options.requestId ?? `${bound.contract.name}-${remote.mutations.sequence + 1}`\n const tempId = `${requestId}.tmp`\n const optimistic =\n typeof options.optimistic === 'function'\n ? options.optimistic({ requestId, tempId })\n : options.optimistic\n const started = updateRemote(remote, {\n _tag: 'MutationStarted',\n requestId,\n ...(optimistic === undefined ? {} : { optimistic }),\n })\n return {\n model: store.set(model, started as Store),\n requestId,\n tempId,\n command: {\n name: `Remote.mutate(${mutation.name})`,\n args: { requestId },\n effect: mutateRemote(mutation, input, requestId).pipe(\n Effect.match({\n onFailure: (error): RemoteMessage => ({\n _tag: 'MutationFailed',\n requestId,\n error: remoteError(error),\n }),\n onSuccess: (outcome): RemoteMessage => ({\n _tag: 'MutationSucceeded',\n requestId,\n entities: outcome.entities,\n connections: outcome.connections,\n deleted: outcome.deleted,\n }),\n }),\n ),\n },\n }\n },\n mutation: (model, requestId) => mutationStatus(store.get(model).mutations, requestId),\n reduce,\n inspect: model => inspectRemote(store.get(model)),\n wiring: (active, options): RemoteWiring<AppModel> => ({\n key: `remote:${bound.contract.name}`,\n // Every domain claims the same tags with no per-domain discriminator, so\n // the assembly's claimant check keeps one assembly to one domain.\n handles: Object.keys(remoteMessageCases),\n route: (model, message) =>\n isRemoteMessage(message) ? Option.some({ model: reduce(model, message) }) : Option.none(),\n subscriptions: brandEntries(domain.subscriptions(active, options)),\n contract: bound.contract,\n }),\n }\n return domain\n}\n\n/** The window keys of a `QueryOptions`, and only those, without the undefined ones. */\nconst pickWindow = (window: QueryWindowOptions): QueryWindow => ({\n ...(window.first === undefined ? {} : { first: window.first }),\n ...(window.last === undefined ? {} : { last: window.last }),\n ...(window.after === undefined ? {} : { after: window.after }),\n ...(window.before === undefined ? {} : { before: window.before }),\n})\n\n/** The page size of a window, carried onto the next or previous page's window under `key`. */\nconst pageSize = (window: QueryWindow, key: 'first' | 'last'): QueryWindow => {\n const size = window.first ?? window.last\n return size === undefined ? {} : { [key]: size }\n}\n"],"mappings":";;;;;;;;;;;;;AAqCA,MAAMA,eAAa,WACjB,KAAK,UAAU;CACb,OAAO,SAAS;CAChB,OAAO,QAAQ;CACf,OAAO,SAAS;CAChB,OAAO,UAAU;AACnB,CAAC;;;;;AAMH,SAAS,iBACP,aACkC;CAClC,MAAM,yBAAS,IAAI,IAAmC;CACtD,KAAK,MAAM,cAAc,aAAa;EACpC,MAAM,MAAM,GAAG,WAAW,SAAS,QAAQA,YAAU,WAAW,MAAM;EACtE,MAAM,UAAU,OAAO,IAAI,GAAG;EAC9B,OAAO,IACL,KACA,YAAY,KAAA,IACR,aACA;GAAE,GAAG;GAAS,QAAQ,cAAc,QAAQ,QAAQ,WAAW,MAAM;EAAE,CAC7E;CACF;CACA,OAAO,CAAC,GAAG,OAAO,OAAO,CAAC;AAC5B;;AAGA,SAAS,cACP,SACA,MACqB;CACrB,MAAM,SAAS,CAAC,GAAG,QAAQ,MAAM;CACjC,MAAM,OAAO,IAAI,IAAI,MAAM;CAC3B,KAAK,MAAM,SAAS,KAAK,QAAQ;EAC/B,IAAI,KAAK,IAAI,KAAK,GAAG;EACrB,KAAK,I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