foldkit-remote 0.17.0 → 0.18.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.
- package/README.md +12 -4
- package/dist/{index-BgUaBYoa.d.mts → index-86gaaCWm.d.mts} +83 -33
- package/dist/index-86gaaCWm.d.mts.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/port.d.mts +1 -1
- package/dist/port.mjs +1 -1
- package/dist/{src-CibwNXeG.mjs → src-Cp71fJac.mjs} +121 -23
- package/dist/src-Cp71fJac.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/index-BgUaBYoa.d.mts.map +0 -1
- package/dist/src-CibwNXeG.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-Cp71fJac.mjs","names":["windowKey","Rec","DomainWrite","Query","RelationalQuery","Entity","Entity","Relational","Relational","Relational","unknownBoundary","askedOf","DomainEntity","Entity","Relational","jsonClient","httpClient","httpWithLiveClient"],"sources":["../src/requirement.ts","../src/data.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/placement.ts","../src/matching.ts","../src/impact.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/resume.ts","../src/json.ts","../src/sse.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 * Whether two values the server sent are the same data: equal primitives, or\n * arrays and plain objects whose entries are. Anything else is compared by\n * identity.\n */\nexport const sameData = (left: unknown, right: unknown): boolean => {\n if (Object.is(left, right)) return true\n if (typeof left !== 'object' || typeof right !== 'object' || left === null || right === null) {\n return false\n }\n if (Array.isArray(left)) {\n return (\n Array.isArray(right) &&\n left.length === right.length &&\n left.every((item, index) => sameData(item, right[index]))\n )\n }\n if (!isPlain(left) || !isPlain(right)) return false\n const keys = Object.keys(left)\n return (\n keys.length === Object.keys(right).length &&\n keys.every(\n key =>\n Object.hasOwn(right, key) &&\n sameData((left as Record<string, unknown>)[key], (right as Record<string, unknown>)[key]),\n )\n )\n}\n\nconst isPlain = (value: object): boolean => {\n const prototype = Object.getPrototypeOf(value)\n return prototype === Object.prototype || prototype === null\n}\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 { SchemaAST, type Schema } from 'effect'\nimport { SchemaShape } from 'foldkit-entity'\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\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, false)\n\nconst shapeOf = (ast: SchemaAST.AST, 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 (SchemaAST.isArrays(ast)) {\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 (SchemaAST.isUnion(ast)) {\n const optional = ast.types.some(SchemaShape.isNullish)\n for (const member of ast.types) {\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 or mutates its input; an\n * operation that changes nothing returns the store it was given.\n */\nimport { Option } from 'effect'\nimport { sameData } from './data.js'\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 /**\n * Fields the server settled without a value: asked for, and answered without\n * them, whatever the reason. Not planned again until a refresh asks; a later\n * write of the field clears it.\n */\n readonly unavailable: 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 unavailable: 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 unavailable = new Set(previous.unavailable)\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 unavailable.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 // Equal data keeps the object it was, so what is derived from it by\n // identity (a read's decoded row) survives a refetch that changed nothing.\n // Comparing costs the size of the written data, less than decoding it again.\n values: Object.keys(values).every(\n field =>\n Object.hasOwn(previous.values, field) && sameData(previous.values[field], values[field]),\n )\n ? previous.values\n : { ...previous.values, ...values },\n present,\n stale,\n unavailable,\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 /** When this write dates the entity, instead of the batch's `now`. */\n readonly updatedAt?: number | 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(\n next[write.key] ?? emptyEntry,\n write.values,\n write.updatedAt ?? now,\n write.windows,\n )\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/**\n * Records fields the server settled without a value. A present field is left\n * as it is: the answer that settled it was not about the value it holds.\n * `false` forgets the marks, which is how a refresh asks again.\n */\nexport const setUnavailable = (\n store: EntityStore,\n marks: ReadonlyArray<readonly [key: EntityKey, fields: Iterable<string>]>,\n unavailable: boolean,\n): EntityStore => {\n let next: Record<EntityKey, EntityEntry> | undefined\n for (const [key, fields] of marks) {\n const previous = (next ?? store)[key] ?? emptyEntry\n if (previous.tombstone) continue\n const marked = new Set(previous.unavailable)\n for (const field of fields) {\n if (unavailable) {\n if (!previous.present.has(field)) marked.add(field)\n } else marked.delete(field)\n }\n if (marked.size === previous.unavailable.size) continue\n next ??= { ...store }\n next[key] = { ...previous, unavailable: marked }\n }\n return next ?? store\n}\n\n/** Whether the server settled this field without a value, and nothing has written it since. */\nexport const isFieldUnavailable = (store: EntityStore, key: EntityKey, field: string): boolean => {\n const value = store[key]\n return value !== undefined && !value.tombstone && value.unavailable.has(field)\n}\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 isTombstone(store, key)\n ? store\n : replace(store, key, {\n values: {},\n present: new Set(),\n stale: new Set(),\n unavailable: 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, and a\n * field the server settled without a value is known the same way. 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) return true\n if (!value.present.has(field)) return !value.unavailable.has(field)\n if (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 { Match, Option, Record as Rec, Schema } from 'effect'\nimport { Write as DomainWrite, type AnyWrite, type BoundWrite, type Write } from 'foldkit-entity'\nimport type { RemoteError } from './remoteData.js'\nimport { entityKey, tombstone, writeEntities, 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/** What a settled mutation wrote, as `MutationSucceeded` carries it. */\nexport interface MutationAnswer {\n readonly entities: ReadonlyArray<NormalizedPatch>\n /** Entities the mutation deleted; each is tombstoned. */\n readonly deleted?: ReadonlyArray<{ readonly entity: string; readonly id: string }> | undefined\n /** Injected clock reading of the answer, which dates what it writes. */\n readonly now: number\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 answer: MutationAnswer,\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 : (answer.deleted ?? []).reduce(\n (current, gone) => tombstone(current, entityKey(gone.entity, gone.id)),\n writeEntities(\n store,\n answer.entities.map(entity => ({\n key: entityKey(entity.entity, entity.id),\n values: entity.values,\n })),\n answer.now,\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, Refused = unknown> {\n readonly name: Name\n readonly Input: Schema.Codec<Input>\n readonly Output: Schema.Codec<Output>\n /**\n * What the server may refuse the mutation with, as a value a client can\n * match on rather than a message to parse: `Schema.Never` when it declares\n * none.\n */\n readonly Refusal: Schema.Codec<Refused, unknown>\n /**\n * What the mutation writes, when it was declared as a `Write`: the optimistic\n * patch a client shows, and what a server can run without a handler.\n */\n readonly write?: AnyWrite | undefined\n}\n\nconst conflict = Schema.TaggedStruct('Conflict', {})\nconst anyField = Schema.TaggedStruct('Field', { key: Schema.String, reason: Schema.Unknown })\n\n/** Refusals a form or an editor knows how to show. */\nexport const Refusal = {\n /** One input key was refused, for `reason`, which a form shows beside that key. */\n field: <const Key extends string, Reason extends Schema.Top>(key: Key, reason: Reason) =>\n Schema.TaggedStruct('Field', { key: Schema.Literal(key), reason }),\n /** The row moved on since the client read it; the author decides what wins. */\n conflict,\n /** Whether a refusal, of whatever mutation, is a `Refusal.field`. */\n isField: Schema.is(anyField),\n /** Whether a refusal, of whatever mutation, is `Refusal.conflict`. */\n isConflict: Schema.is(conflict),\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\n/**\n * A bound write as the store patches it: its fields as they are, and each\n * relation it points as the ref key the store holds (`'User:u1'`), or null.\n */\nexport const patchOfWrite = (bound: BoundWrite): NormalizedPatch => ({\n entity: bound.entity,\n id: bound.id,\n values: {\n ...bound.values,\n ...Rec.map(bound.links, link =>\n Option.match(link, { onNone: () => null, onSome: ref => entityKey(ref.entity, ref.id) }),\n ),\n },\n})\n\n/**\n * What a declared write shows before the server answers: an update's or an\n * insert's row as a patch (an update's only for the keys named, when some\n * are). A delete shows nothing, since no operation removes a row from every\n * list it is in; its answer does.\n */\nexport const optimisticOfWrite = (\n write: AnyWrite,\n input: unknown,\n keys: ReadonlyArray<string> | undefined,\n): ReadonlyArray<NormalizedPatch> =>\n Match.value(write).pipe(\n Match.tagsExhaustive({\n Update: () => [patchOfWrite(DomainWrite.bind(write, input as never, keys))],\n // A new row is read like any other, so it carries its own id.\n Insert: () => {\n const patch = patchOfWrite(DomainWrite.bind(write, input as never))\n return [{ ...patch, values: { id: patch.id, ...patch.values } }]\n },\n Delete: () => [],\n }),\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 * `Refusal`, when given, is what the server may refuse with: a codec, usually\n * a union of `Refusal.field(...)` and `Refusal.conflict`.\n */\n /**\n * A mutation that is a declared `Write` (`update`, `insert` or `delete`): its\n * input is the write's, and it answers nothing but the row it changed, as a\n * patch, or its deletion. It may be refused as a conflict, for a write that\n * `expect`s a revision the row has moved past.\n */\n write: <const Name extends string, Fields extends Schema.Struct.Fields>(\n name: Name,\n write: Write<any, Fields>,\n ): MutationDescriptor<Name, Schema.Struct.Type<Fields>, {}, typeof Refusal.conflict.Type> & {\n readonly write: Write<any, Fields>\n } => ({\n name,\n Input: write.input.schema as unknown as Schema.Codec<Schema.Struct.Type<Fields>>,\n Output: Schema.Struct({}),\n Refusal: Refusal.conflict,\n write,\n }),\n\n make: <\n const Name extends string,\n Input extends SchemaOrFields,\n Output extends SchemaOrFields,\n Refused = never,\n >(\n name: Name,\n config: {\n readonly Input: Input\n readonly Output: Output\n readonly Refusal?: Schema.Codec<Refused, any>\n },\n ): MutationDescriptor<Name, TypeOf<Input>, TypeOf<Output>, Refused> => ({\n name,\n Input: schemaOf(config.Input),\n Output: schemaOf(config.Output),\n Refusal: config.Refusal ?? Schema.Never,\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/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/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 = 4\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 {\n message: Schema.String,\n /** The mutation's own `Refusal`, encoded, when the server refused it as one. */\n refusal: Schema.optional(Schema.Unknown),\n },\n) {}\n\n/**\n * The server refused who is asking: they may not do this, and asking again\n * as the same principal is refused again. `reason` is the application's own\n * words for the person who asked; without it the refusal says nothing of why.\n */\nexport class RemoteForbidden extends Schema.TaggedError<RemoteForbidden>()('Forbidden', {\n message: Schema.String,\n reason: Schema.optional(Schema.String),\n}) {}\n\n/**\n * The server could not tell who is asking: a credential was sent and no\n * longer holds, or none was sent where one is needed. Asking again as the\n * same caller is refused again; signing in again is the remedy. `reason` is\n * words for the person who asked; without it the refusal says nothing of why.\n */\nexport class RemoteUnauthenticated extends Schema.TaggedError<RemoteUnauthenticated>()(\n 'Unauthenticated',\n {\n message: Schema.String,\n reason: Schema.optional(Schema.String),\n },\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\n/**\n * Fields a read asked for that the server answered without, and will not\n * answer with: the client stops asking. It says nothing about why, so a rule\n * that withholds a field is not itself on the wire.\n */\nexport const SettledFields = Schema.Struct({\n entity: Schema.String,\n id: Schema.String,\n fields: Schema.Array(Schema.String),\n})\n\nexport const ReadBatchResult = Schema.Struct({\n entities: Schema.Array(NormalizedEntity),\n settled: Schema.Array(SettledFields),\n})\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 /** For a mutation that is a `Write`: the input keys to write, when not all of them. */\n keys: Schema.optional(Schema.Array(Schema.String)),\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, RemoteUnauthenticated]),\n})\n\nexport const Mutate = Rpc.make('FoldkitRemoteMutate', {\n payload: MutationRequest,\n success: MutationResult,\n error: Schema.Union([RemoteMutationError, RemoteForbidden, RemoteUnauthenticated]),\n})\n\nexport const Live = Rpc.make('FoldkitRemoteLive', {\n payload: LiveRequirement,\n success: LiveChange,\n error: Schema.Union([RemoteLiveError, RemoteProtocolError, RemoteUnauthenticated]),\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 * What to read of each item, as the relation slice a read asks the server\n * for. Absent for a query run without one: the response carries only edges,\n * and the client's read entry fetches fields in a second round trip.\n */\n select: Schema.optional(RelationRequest),\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 * The selected fields of the page's items, in the same shape a read batch\n * returns. Absent from a server that predates payload planning: the client\n * reads it as empty and fetches fields as before.\n */\n entities: Schema.optional(Schema.Array(NormalizedEntity)),\n settled: Schema.optional(Schema.Array(SettledFields)),\n})\n\nexport const QueryRpc = Rpc.make('FoldkitRemoteQuery', {\n payload: QueryRequest,\n success: QueryResult,\n error: Schema.Union([RemoteQueryError, RemoteUnauthenticated]),\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 {\n RemoteProtocolError,\n RemoteQueryError,\n RemoteReadError,\n RemoteUnauthenticated,\n} from './wire.js'\n\ntype Batch = Schema.Schema.Type<typeof ReadBatch>\ntype BatchResult = Schema.Schema.Type<typeof ReadBatchResult>\ntype ReadError = RemoteReadError | RemoteProtocolError | RemoteUnauthenticated\ntype QueryError = RemoteQueryError | RemoteUnauthenticated\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 = (request: QueryRequestValue) => Effect.Effect<QueryResultValue, QueryError>\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 QueryError\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, QueryError>>()\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([\n request.query,\n request.input,\n request.window,\n request.select ?? null,\n ]),\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: [], settled: [] })\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 const distinct = [...new Set(results)]\n return {\n entities: distinct.flatMap(result => result.entities),\n settled: distinct.flatMap(result => result.settled),\n }\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 RemoteForbidden,\n RemoteUnauthenticated,\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 | RemoteUnauthenticated\n >\n readonly query: (\n request: Schema.Schema.Type<typeof QueryRequest>,\n ) => Effect.Effect<\n Schema.Schema.Type<typeof QueryResult>,\n RemoteQueryError | RemoteUnauthenticated\n >\n readonly mutate: (\n request: Schema.Schema.Type<typeof MutationRequest>,\n ) => Effect.Effect<\n Schema.Schema.Type<typeof MutationResult>,\n RemoteMutationError | RemoteForbidden | RemoteUnauthenticated\n >\n readonly live: (request: {\n readonly requirements: ReadonlyArray<Requirement>\n readonly after: LiveCursor\n }) => Stream.Stream<LiveEvent, RemoteLiveError | RemoteProtocolError | RemoteUnauthenticated>\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 *\n * `TransportError` is what the transport itself may fail with on top of the\n * declared errors: `RpcClientError` for the client `RpcClient.make` builds,\n * `never` for in-process handlers.\n */\nexport interface RemoteRpcClient<R = never, TransportError = never> {\n readonly FoldkitRemoteRead: (\n payload: Schema.Schema.Type<typeof ReadBatch>,\n ) => Effect.Effect<\n Schema.Schema.Type<typeof ReadBatchResult>,\n RemoteReadError | RemoteProtocolError | RemoteUnauthenticated | TransportError,\n R\n >\n readonly FoldkitRemoteQuery: (\n payload: Schema.Schema.Type<typeof QueryRequest>,\n ) => Effect.Effect<\n Schema.Schema.Type<typeof QueryResult>,\n RemoteQueryError | RemoteUnauthenticated | TransportError,\n R\n >\n readonly FoldkitRemoteMutate: (\n payload: Schema.Schema.Type<typeof MutationRequest>,\n ) => Effect.Effect<\n Schema.Schema.Type<typeof MutationResult>,\n RemoteMutationError | RemoteForbidden | RemoteUnauthenticated | TransportError,\n R\n >\n readonly FoldkitRemoteLive: (\n payload: Schema.Schema.Type<typeof LiveRequirement>,\n ) => Stream.Stream<\n Schema.Schema.Type<typeof LiveChange>,\n RemoteLiveError | RemoteProtocolError | RemoteUnauthenticated | TransportError,\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 readonly refusal?: unknown\n readonly reason?: string | undefined\n}): RemoteError => ({\n _tag: error._tag,\n message: error.message,\n ...(error.refusal === undefined ? {} : { refusal: error.refusal }),\n ...(error.reason === undefined ? {} : { reason: error.reason }),\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>(\n mutation: MutationDescriptor<Name, Input, Output>,\n input: Input,\n requestId: string,\n keys?: ReadonlyArray<string>,\n) {\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 ...(keys === undefined ? {} : { keys }),\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 {\n entityKey,\n isFieldStale,\n isFieldUnavailable,\n isTombstone,\n readField,\n type EntityStore,\n} 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\n/**\n * The first field `requirement` reads, at any depth, that the server settled\n * without a value, as `Entity:id.field`. A read that consults it says why it\n * cannot assemble rather than waiting on a field nothing will fetch.\n */\nexport const unavailableOf = (\n store: EntityStore,\n key: string,\n requirement: RelationRequirement,\n): string | undefined => {\n for (const field of requirement.fields) {\n if (isFieldUnavailable(store, key, field)) return `${key}.${field}`\n const relation = requirement.relations?.[field]\n if (relation === undefined) continue\n const value = readField(store, key, field)\n if (Option.isNone(value) || value.value === null || value.value === undefined) continue\n for (const ref of targetsOf(value.value, relation)) {\n const found = unavailableOf(store, entityKey(ref.entity, ref.id), relation)\n if (found !== undefined) return found\n }\n }\n return undefined\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 */\n/**\n * A ref as the wire carries it: the target's name, a colon, and its id. Typed\n * with the name, so a relation to `User` takes `'User:u1'` and not a ref to\n * some other entity, which would read as a row that does not exist.\n */\nexport type RefKey<Name extends string> = `${Name}:${string}`\n\nconst refCodec = <Name extends string, F extends Schema.Struct.Fields>(\n entity: Name,\n): Schema.Codec<EntityRef<Name, F>, RefKey<Name>> =>\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>, RefKey<Name>>\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']>, RefKey<Target['name']>>>\n : Optional extends true\n ? Schema.NullOr<Schema.Codec<EntityRef<Target['name']>, RefKey<Target['name']>>>\n : Schema.Codec<EntityRef<Target['name']>, RefKey<Target['name']>>\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>, RefKey<Name>> => 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>, RefKey<Name>> =>\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 * Where one row falls in a loaded list, by the list's own declared order:\n * the decidable half of placing a row instead of fetching the list again.\n *\n * A list is segments of edges between boundaries, and only a `Terminal`\n * boundary says nothing lies beyond it. So a row is placed between two loaded\n * edges, or before a segment's first edge when that segment starts the list,\n * or at its end when it ends it; a row that sorts past a `Cursor` or into a\n * gap belongs to rows the client has not read, and is `Outside`. Anything the\n * client cannot judge exactly (a body it cannot place, a field a row lacks,\n * keys it cannot compare) is `Unknown`, with why, never a guess.\n *\n * Pure: it reads the store and the list it is given.\n */\nimport { Data, Match, Option, Schema, SchemaAST } from 'effect'\nimport { Query as Relational, compareRows, type AnyQuery, type OrderTerm } from 'foldkit-entity'\nimport type { Connection, Edge } from './connection.js'\nimport { entityKey, readField, type EntityStore } from './store.js'\n\n/** Where a row falls in a loaded list. */\nexport type RowPlace = Data.TaggedEnum<{\n /** Just before this edge, in this segment. */\n Before: { readonly segment: number; readonly edge: string }\n /** After every edge of this segment, which ends the list. */\n End: { readonly segment: number }\n /** In rows the list has not loaded: past a `Cursor` boundary, or in a gap. */\n Outside: {}\n /** Not judged exactly, and why. */\n Unknown: { readonly reason: string }\n}>\nexport const RowPlace = Data.taggedEnum<RowPlace>()\n\n/**\n * The values a row holds of the fields an order reads, or none when it lacks\n * one. An `id` no Selection stored is its key's, when the id is stored as\n * text as a key holds it, so the id tie-break every order ends on does not\n * make such a row unplaceable; a number id is never compared as text.\n */\nconst keysOf = (\n store: EntityStore,\n key: string,\n id: Option.Option<string>,\n idIsText: boolean,\n terms: ReadonlyArray<OrderTerm>,\n): Option.Option<Readonly<Record<string, unknown>>> => {\n const values: Record<string, unknown> = Object.create(null)\n for (const term of terms) {\n if (term.expr._tag !== 'Field') return Option.none()\n const field = term.expr.key\n const stored = readField(store, key, field)\n const value = field === 'id' && Option.isNone(stored) && idIsText ? id : stored\n if (Option.isNone(value)) return Option.none()\n values[field] = value.value\n }\n return Option.some(values)\n}\n\n/**\n * Where the row stored under `key` falls in `connection`, by `body`'s order\n * for `input` (encoded, as a connection's identity carries it). The row's own\n * edge, if the list holds it, is left out: placing a row that moved asks\n * where it goes now.\n */\nexport const placeIn = (\n store: EntityStore,\n connection: Connection,\n body: AnyQuery,\n input: Readonly<Record<string, unknown>>,\n key: string,\n): RowPlace => {\n const placement = Relational.placement(body, input)\n if (placement._tag === 'NotPlaceable') return RowPlace.Unknown({ reason: placement.reason })\n const terms = Relational.orderFor(body, input)\n // The row is of the body's Entity, so its key is that name, a colon, its id.\n const prefix = `${body.entity.name}:`\n const id = key.startsWith(prefix) ? Option.some(key.slice(prefix.length)) : Option.none()\n const idField = (body.entity.fields as Readonly<Record<string, { readonly schema: Schema.Top }>>)\n .id\n const idIsText = idField !== undefined && SchemaAST.isString(Schema.toEncoded(idField.schema).ast)\n const row = keysOf(store, key, id, idIsText, terms)\n if (Option.isNone(row)) {\n return RowPlace.Unknown({ reason: `${key} lacks a field the order reads` })\n }\n /** Negative when the row sorts before the edge; none when the edge cannot be compared. */\n const against = (edge: Edge): Option.Option<number> =>\n Option.flatMap(\n keysOf(\n store,\n entityKey(edge.ref.entity, edge.ref.id),\n Option.some(edge.ref.id),\n idIsText,\n terms,\n ),\n values => {\n try {\n return Option.some(compareRows(terms, row.value, values, body.entity.name))\n } catch {\n return Option.none()\n }\n },\n )\n\n // A row that was a segment's first or last edge beside a `Cursor` was\n // itself where its page began or ended: its old keys are gone from the\n // store, so whether it moved past that boundary cannot be told.\n const boundary = RowPlace.Unknown({ reason: `${key} was where its page met rows not loaded` })\n const { segments } = connection\n for (let index = 0; index < segments.length; index++) {\n const segment = segments[index]!\n const held = segment.edges.findIndex(edge => edge.key === key)\n const edges = segment.edges.filter(edge => edge.key !== key)\n for (let position = 0; position < edges.length; position++) {\n const edge = edges[position]!\n const sign = against(edge)\n if (Option.isNone(sign)) {\n return RowPlace.Unknown({ reason: `${edge.key} lacks a field the order reads` })\n }\n if (sign.value < 0) {\n const before = RowPlace.Before({ segment: index, edge: edge.key })\n if (position > 0) return before\n // Before this segment's first edge is loaded only when nothing precedes it.\n return Match.value(segment.start).pipe(\n Match.tag('Terminal', () => before),\n Match.orElse(() => (held === 0 ? boundary : RowPlace.Outside())),\n )\n }\n }\n // After every edge of this segment: its end, if nothing follows; else the\n // next segment, or rows not loaded.\n const ends = Match.value(segment.end).pipe(\n Match.tag('Terminal', () => true),\n Match.orElse(() => false),\n )\n if (ends) return RowPlace.End({ segment: index })\n if (held >= 0 && held === segment.edges.length - 1) return boundary\n }\n return RowPlace.Outside()\n}\n\n/** The connection without the edge of `key`, or the connection itself when it holds none. */\nexport const withoutEdge = (connection: Connection, key: string): Connection =>\n connection.segments.some(segment => segment.edges.some(edge => edge.key === key))\n ? {\n ...connection,\n segments: connection.segments.map(segment => ({\n ...segment,\n edges: segment.edges.filter(edge => edge.key !== key),\n })),\n }\n : connection\n\n/** The connection with `edge` where `place` says: before an edge, or at a segment's end. */\nexport const withEdge = (\n connection: Connection,\n added: Edge,\n place: Extract<RowPlace, { readonly _tag: 'Before' | 'End' }>,\n): Connection => ({\n ...connection,\n segments: connection.segments.map((segment, index) => {\n if (index !== place.segment) return segment\n const at = Match.value(place).pipe(\n Match.tagsExhaustive({\n Before: ({ edge }) => segment.edges.findIndex(held => held.key === edge),\n End: () => segment.edges.length,\n }),\n )\n return { ...segment, edges: [...segment.edges.slice(0, at), added, ...segment.edges.slice(at)] }\n }),\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 { QueryEvaluateError, 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 let judged: Judged\n try {\n judged = matchingEncoded(store, descriptor, encoded, { among: [key] })\n } catch (error) {\n // A body the reference interpreter refuses for this input (text holding\n // NUL) cannot settle membership; the server refuses it too.\n if (error instanceof QueryEvaluateError) return 'unknown'\n throw error\n }\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","/**\n * What a write did to the lists the client holds: given one change and one\n * loaded connection, whether the connection is still right as it stands.\n *\n * Pure, and asked once per connection a write could touch. The answer is never\n * a guess: a connection kept must be provably unchanged in which rows it holds\n * and in what order, a connection placed is the client's exact deduction of\n * what the server now lists, and everything else is invalidated, with the\n * reason, for the read entry to fetch again.\n *\n * Membership is judged by the query's body, as a live insert is\n * (`belongsEncoded`), and position by its declared order (`placeIn`), when\n * the order is placeable. A body that names no order leaves it to the server,\n * by fields the client cannot see, so any change to a row it holds\n * invalidates it.\n */\nimport { Query as Relational, dependenciesOf, type OrderTerm } from 'foldkit-entity'\nimport { defineTaggedUnion } from 'foldkit/schema'\nimport { edge, hasNext, hasPrevious, isGapped, type Connection } from './connection.js'\nimport { RowPlace, placeIn, withEdge, withoutEdge } from './placement.js'\nimport { Data, Schema } from 'effect'\nimport { sameData } from './data.js'\nimport { belongsEncoded } from './matching.js'\nimport type { NormalizedPatch } from './mutation.js'\nimport type { ConnectionSpec, QueryDescriptor } from './query.js'\nimport { entityKey, type EntityKey, type EntityStore } from './store.js'\n\n/**\n * One row a write changed: the fields it wrote, and whether the client held\n * no values of the row before (`created`), or its deletion.\n */\nexport const EntityChange = defineTaggedUnion({\n Changed: {\n entity: Schema.String,\n id: Schema.String,\n fields: Schema.Array(Schema.String),\n created: Schema.Boolean,\n },\n Deleted: { entity: Schema.String, id: Schema.String },\n})\nexport type EntityChange = typeof EntityChange.Type\n\n/**\n * What a mutation's answer changed, against `before`, the store as the server\n * last said it: each patch's fields whose value is new, and each deletion. An\n * answer returns more than it changed (a whole row, say), and counting an\n * unchanged ordering field would refetch every list on every save.\n */\nexport const changesOf = (\n answer: {\n readonly entities: ReadonlyArray<NormalizedPatch>\n readonly deleted?: ReadonlyArray<{ readonly entity: string; readonly id: string }> | undefined\n },\n before: EntityStore,\n): ReadonlyArray<EntityChange> => [\n ...answer.entities.flatMap(patch => {\n const held = before[entityKey(patch.entity, patch.id)]?.values\n const fields = Object.keys(patch.values).filter(\n field =>\n held === undefined ||\n !Object.hasOwn(held, field) ||\n !sameData(held[field], patch.values[field]),\n )\n return fields.length === 0\n ? []\n : [\n EntityChange.Changed({\n entity: patch.entity,\n id: patch.id,\n fields,\n created: held === undefined,\n }),\n ]\n }),\n ...(answer.deleted ?? []).map(gone => EntityChange.Deleted({ entity: gone.entity, id: gone.id })),\n]\n\n/**\n * What a change does to a connection: nothing it shows, a change the client\n * places itself (`Placed`, the connection as it now is), or a change it\n * cannot place, for its read entry to fetch again.\n */\nexport type Impact = Data.TaggedEnum<{\n Kept: {}\n Placed: { readonly connection: Connection }\n Invalidated: { readonly reason: string }\n}>\nexport const Impact = Data.taggedEnum<Impact>()\n\n/** A loaded connection, as impact needs it. */\nexport interface HeldConnection {\n readonly descriptor: QueryDescriptor<string, unknown, unknown>\n /** The connection's input, encoded, as its identity carries it. */\n readonly encoded: Readonly<Record<string, unknown>>\n /** The rows it shows now, overlays included. */\n readonly holds: ReadonlySet<EntityKey>\n /** Its pages as the server sent them, which a placement edits. */\n readonly connection: Connection\n /** The members its Entity's server filters rows by under a rule the client does not run. */\n readonly filtered: ReadonlyArray<string>\n}\n\nconst kept = Impact.Kept()\n\n/** Whether two versions of a list hold the same rows in the same order, segment by segment. */\nconst sameOrder = (left: Connection, right: Connection): boolean =>\n left.segments.length === right.segments.length &&\n left.segments.every((segment, index) => {\n const other = right.segments[index]!.edges\n return (\n segment.edges.length === other.length &&\n segment.edges.every((edge, position) => edge.key === other[position]!.key)\n )\n })\n\n/**\n * What `change` does to `connection`, judged against `store`, the store after\n * the write.\n */\nexport const impactOn = (\n connection: HeldConnection,\n store: EntityStore,\n change: EntityChange,\n): Impact => {\n const { descriptor } = connection\n const body = descriptor.body\n const over = body?.entity.name ?? (descriptor.Result as Partial<ConnectionSpec>).entity\n if (over !== change.entity) return kept\n return EntityChange.match(change, {\n // A deletion leaves every list through its tombstone; nothing to fetch.\n Deleted: () => kept,\n Changed: ({ fields, created }) => {\n if (body === undefined) {\n return Impact.Invalidated({\n reason: `query \"${descriptor.name}\" declares no body, so what it reads is unknown`,\n })\n }\n const key = entityKey(change.entity, change.id)\n const held = connection.holds.has(key)\n // The server lists only the rows its read rules admit, and the client\n // runs none of them: a row this list does not hold may have joined it\n // on a change to what those rules read, which only the server can say.\n const ruled = fields.find(field => connection.filtered.includes(field))\n if (!held && ruled !== undefined) {\n return Impact.Invalidated({\n reason: `${key} changed \"${ruled}\", which the server's read rule for ${change.entity} filters on`,\n })\n }\n const roles = Relational.dependencies(body)\n const touches = (keys: ReadonlyArray<{ readonly key: string }>) =>\n keys.some(field => fields.includes(field.key))\n // The order this list was read in: a chosen order is the field its own\n // input names, not every field it could have named.\n let order: ReadonlyArray<OrderTerm>\n try {\n order = Relational.orderFor(body, connection.encoded)\n } catch {\n return Impact.Invalidated({\n reason: `\"${descriptor.name}\" was read in an order its body does not offer`,\n })\n }\n\n if (held && body.orderBy.length === 0) {\n return Impact.Invalidated({\n reason: `${key} changed, and \"${descriptor.name}\" is ordered by the server, by fields its body does not name`,\n })\n }\n const pages = connection.connection\n const reorders = touches(dependenciesOf(...order).fields)\n const refilters = touches(roles.predicate)\n // A row the list does not hold can join it: one new to the client,\n // whatever the list filters on, and one whose order moved it in from\n // rows the list has not loaded.\n const unloaded = hasPrevious(pages) || hasNext(pages) || isGapped(pages)\n const joins = !held && (created || (reorders && unloaded))\n if (!(held && reorders) && !refilters && !joins) return kept\n\n // A held row whose order alone changed still matches.\n const belongs =\n held && !refilters ? 'yes' : belongsEncoded(store, descriptor, connection.encoded, key)\n if (belongs === 'unknown') {\n return Impact.Invalidated({\n reason: `${key} changed a field \"${descriptor.name}\" filters on, and the client cannot judge it`,\n })\n }\n // Not held and still not matching, or held and still matching where it was.\n if (!held && belongs === 'no') return kept\n if (held && belongs === 'yes' && !reorders) return kept\n\n // The list's rows, or their order, changed: placed where the client can.\n const inPages = pages.segments.some(segment => segment.edges.some(edge => edge.key === key))\n if (held && !inPages) {\n return Impact.Invalidated({\n reason: `${key} is shown in \"${descriptor.name}\" by an overlay, which a placement does not move`,\n })\n }\n // Leaving is exact whatever the order: membership is the body's.\n if (belongs === 'no') return Impact.Placed({ connection: withoutEdge(pages, key) })\n /** The row where `place` says; the list as it was when that is where it already stood. */\n const placedAt = (place: Extract<RowPlace, { readonly _tag: 'Before' | 'End' }>) => {\n const next = withEdge(\n withoutEdge(pages, key),\n edge({ entity: change.entity, id: change.id }),\n place,\n )\n return sameOrder(pages, next) ? kept : Impact.Placed({ connection: next })\n }\n return RowPlace.$match(placeIn(store, pages, body, connection.encoded, key), {\n Before: placedAt,\n End: placedAt,\n // It belongs to rows not loaded: gone from these, if they showed it.\n Outside: () => (held ? Impact.Placed({ connection: withoutEdge(pages, key) }) : kept),\n Unknown: ({ reason }) =>\n Impact.Invalidated({\n reason: `${key} ${held ? 'moved in' : 'joined'} \"${descriptor.name}\", and cannot be placed: ${reason}`,\n }),\n })\n },\n })\n}\n","/** A serializable summary of a RemoteModel for DevTools and diagnostics. */\nimport type { Dependencies } from 'foldkit-entity'\n\n/** A query body's `Dependencies` as plain data: each field by its Entity's name and key. */\nexport interface ExplainedDependencies {\n readonly fields: ReadonlyArray<{ readonly entity: string; readonly key: string }>\n readonly inputs: Dependencies['inputs']\n readonly operations: Dependencies['operations']\n}\nimport type { Failures, PlacementMismatch, 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 unavailable: 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 /** Under `verifyPlacement`, each placement the server's page disagreed with. */\n readonly placementMismatches: ReadonlyArray<PlacementMismatch>\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 unavailable: [...entry.unavailable],\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 placementMismatches: model.placementMismatches,\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 * Why a read shows what it shows, in words, and for `Initial`, which of the\n * usual mistakes it is.\n *\n * `Initial` means nothing is fetching the read, and that is almost always\n * wiring rather than the network: no active Surface reads it, or one does and\n * Remote's Subscriptions are not running. The Model can tell those apart when\n * it is given the active record, so this says which, and what to do.\n */\nexport interface ReadDiagnosis {\n readonly state: RemoteData<unknown>['_tag']\n /**\n * For `Initial` only. `NotObserved`: no active Surface reads it.\n * `NotFetching`: one does, and nothing is fetching it, so Remote's\n * Subscriptions are most likely not installed. `Unknown`: no active record\n * was given to tell.\n */\n readonly reason?: 'NotObserved' | 'NotFetching' | 'Unknown' | undefined\n /** One or two sentences a developer can act on. */\n readonly message: string\n /** The active Surfaces reading it, when the active record was given. */\n readonly surfaces?: ReadonlyArray<string> | undefined\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 /**\n * The fields, inputs and operations the body reads; absent with the body.\n * Plain data, so it serializes: a field is its Entity's name and key, which\n * is unambiguous because a query reads one Entity.\n */\n readonly dependencies?: ExplainedDependencies | 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 {\n reconcileMutation,\n type MutationAnswer,\n type MutationState,\n type NormalizedPatch,\n} from './mutation.js'\nimport { entityKey, isTombstone, writeEntities, 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 if (patches.length === 0 && changes.length === 0) return optimistic\n return {\n layers:\n patches.length === 0 ? optimistic.layers : [...optimistic.layers, { id: requestId, patches }],\n overlays:\n changes.length === 0\n ? optimistic.overlays\n : [...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 at = optimistic.overlays.findIndex(overlay => overlay.id === requestId)\n if (at === -1 && changes.length === 0) return optimistic\n const confirmed = toOverlays(id, changes)\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 const layers = optimistic.layers.filter(layer => layer.id !== id)\n return layers.length === optimistic.layers.length ? optimistic : { ...optimistic, layers }\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 const overlays = optimistic.overlays.filter(overlay => overlay.id !== id)\n return overlays.length === optimistic.overlays.length ? optimistic : { ...optimistic, overlays }\n}\n\n/**\n * Base store with every layer applied in order. Later layers win. A patch is\n * not news from the server, so it keeps the date of the value under it; an\n * entity only a request holds (a temporary id) is not the server's to age, and\n * is dated `Infinity`, so freshness never plans or times it.\n */\nexport const visibleStore = (base: EntityStore, optimistic: OptimisticState): EntityStore =>\n writeEntities(\n base,\n optimistic.layers.flatMap(layer =>\n layer.patches.map(patch => {\n const key = entityKey(patch.entity, patch.id)\n const under = base[key]\n return {\n key,\n values: patch.values,\n updatedAt: under === undefined || under.tombstone ? Infinity : under.updatedAt,\n }\n }),\n ),\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 let changed = false\n const 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 // An overlay a live remove emptied goes too: it shows nothing.\n if (edges.length > 0 && edges.length === overlay.edges.length) return [overlay]\n changed = true\n return edges.length === 0 ? [] : [{ ...overlay, edges }]\n })\n return changed ? { ...optimistic, overlays } : optimistic\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 answer: MutationAnswer & {\n /** Connection changes the server confirmed; they replace the request's own. */\n readonly connections?: ReadonlyArray<ConnectionChange> | undefined\n },\n): {\n readonly store: EntityStore\n readonly state: MutationState\n readonly optimistic: OptimisticState\n} => {\n const reconciled = reconcileMutation(base, state, requestId, answer)\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 answer.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\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 if (overlay.connection !== connection || overlay.position === 'remove') return overlay\n const edges = overlay.edges.filter(edge => edge.key !== key)\n return edges.length === overlay.edges.length ? overlay : { ...overlay, edges }\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\n/** When present values next go stale, and the requirements of the entities that do. */\nexport interface Deadline {\n readonly at: number\n readonly due: ReadonlyArray<Requirement>\n}\n\n/**\n * The earliest moment a value `requirements` read, following the relations the\n * store holds as `plan` does, goes stale under `freshness`, with the\n * requirements of the entities that go stale then. A field the server settled\n * without a value ages with its entity too, since `plan` asks for it again once\n * the entity expires. Nothing when no such field is still fresh: what is\n * already expired or stale is planned, not awaited, which is what keeps a\n * timer from firing on what it already fired on. It is the next moment the\n * plan can change with the clock alone, which the read entry relies on to\n * reuse its plan until then.\n */\nexport const deadlineOf = (\n store: EntityStore,\n requirements: readonly Requirement[],\n freshness: PlanFreshness,\n): Deadline | undefined => {\n let at: number | undefined\n let due: Requirement[] = []\n const walk = (group: Requirement): void => {\n const key = entityKey(group.entity, group.id)\n const entry = store[key]\n if (entry === undefined || entry.tombstone) return\n const fresh = group.fields.some(\n field =>\n (entry.present.has(field) && !entry.stale.has(field)) || entry.unavailable.has(field),\n )\n if (fresh) {\n const expires = entry.updatedAt + freshness.freshness\n // An entity dated `Infinity` never ages (see `visibleStore`): no deadline.\n // At `expires` itself `plan` does not yet fetch it, so it is still awaited.\n if (expires >= freshness.now && Number.isFinite(expires)) {\n if (at === undefined || expires < at) {\n at = expires\n due = [group]\n } else if (expires === at) due.push(group)\n }\n }\n for (const [field, relation] of Object.entries(group.relations ?? {})) {\n const value = readField(store, key, field)\n if (value._tag === 'Some')\n for (const next of followRelation(value.value, relation)) walk(next)\n }\n }\n for (const group of Requirement.merge(requirements)) walk(group)\n return at === undefined ? undefined : { at, due: Requirement.merge(due) }\n}\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 = keptOf(state.entities, key => kept.has(key))\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 = keptOf(state.connections, identity => keptConnections.has(identity))\n const overlays = state.optimistic.overlays.filter(\n overlay => pending.has(overlay.id) || keptConnections.has(overlay.connection),\n )\n const optimistic: OptimisticState =\n overlays.length === state.optimistic.overlays.length\n ? state.optimistic\n : { layers: state.optimistic.layers, overlays }\n return { entities, connections, optimistic }\n}\n\n/** The entries whose key is kept; `record` itself when that is all of them. */\nconst keptOf = <T>(\n record: Readonly<Record<string, T>>,\n keep: (key: string) => boolean,\n): Readonly<Record<string, T>> => {\n const entries = Object.entries(record)\n const kept = entries.filter(([key]) => keep(key))\n return kept.length === entries.length ? record : Object.fromEntries(kept)\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/persistence'\nimport { 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 = 5\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 unavailable: 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 unavailable: sorted(entry.unavailable),\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 (!isStringArray(entry.unavailable)) throw new Error('entry.unavailable 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 unavailable: new Set(entry.unavailable),\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 =>\n Object.keys(snapshot).length === 0\n ? current\n : policy === 'replace'\n ? { ...current, ...snapshot }\n : { ...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'\nimport { defineTaggedUnion } from 'foldkit/schema'\n\nexport interface RemoteError {\n readonly _tag: string\n readonly message: string\n /**\n * A refused mutation's refusal, encoded as the server sent it. Read it\n * decoded, by its mutation, with `Data.refusal`.\n */\n readonly refusal?: unknown\n /**\n * Why the server refused who is asking (`_tag: 'Unauthenticated'` or\n * `'Forbidden'`), when it said. Read it with `RemoteData.denied`.\n */\n readonly reason?: string | undefined\n}\n\n/**\n * The server would not answer who is asking: their session ended or was\n * never there (`Unauthenticated`, a 401), or they may not (`Forbidden`, a\n * 403). `reason` is the server's sentence, when it gave one. Not a mutation's\n * declared `refusal`, which the server answered and `Data.refusal` reads.\n */\nexport const Denied = defineTaggedUnion({\n Unauthenticated: { reason: Schema.Option(Schema.String) },\n Forbidden: { reason: Schema.Option(Schema.String) },\n})\nexport type Denied = typeof Denied.Type\n\n/** The tags `denied` reads: a `RemoteError`'s `_tag` is open, for any failure a transport reports. */\nconst denials: ReadonlySet<string> = new Set<Denied['_tag']>(['Unauthenticated', 'Forbidden'])\nconst isDenial = (tag: string): tag is Denied['_tag'] => denials.has(tag)\nconst deny = { Unauthenticated: Denied.Unauthenticated, Forbidden: Denied.Forbidden }\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({\n _tag: Schema.String,\n message: Schema.String,\n refusal: Schema.optional(Schema.Unknown),\n reason: Schema.optional(Schema.String),\n})\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 /**\n * Whether the read has an answer: `Ready`, `Refreshing`, `Failed` or\n * `NotFound`. `Initial` and `Loading` are still waiting for one.\n */\n answered: <A>(data: RemoteData<A>): boolean =>\n RemoteData.match(data, {\n Initial: () => false,\n Loading: () => false,\n Ready: () => true,\n Refreshing: () => true,\n Failed: () => true,\n NotFound: () => true,\n }),\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 /**\n * The denial a failure was, typed, or none for any other failure (a\n * network error, a protocol mismatch): what to read before telling a reader\n * to sign in again.\n *\n * ```ts\n * Option.match(RemoteData.denied(error), {\n * onNone: () => 'Could not load',\n * onSome: Denied.match({ Unauthenticated: () => 'Sign in again', Forbidden: () => 'Not yours' }),\n * })\n * ```\n */\n denied: (error: RemoteError): Option.Option<Denied> =>\n // tag-check: open — a RemoteError carries any transport failure's tag.\n isDenial(error._tag)\n ? Option.some(deny[error._tag]({ reason: Option.fromUndefinedOr(error.reason) }))\n : Option.none(),\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 case 'Initial':\n case 'Loading':\n case 'NotFound':\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 { Option, Schema } from 'effect'\nimport type { RelationRequirement, Requirement } from './requirement.js'\nimport {\n emptyConnection,\n merge,\n unknown as unknownBoundary,\n type Boundary,\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 setUnavailable,\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 {\n NormalizedEntity,\n ReadBatchResult,\n ReadRequest,\n RelationRequest,\n SettledFields,\n} 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 /**\n * How many rows `Data.more` has grown a read's window to, by\n * `windowGrowthKey`. A read shows at most its window, so this is what \"load\n * more\" changes; it lives here because a list holds no state of its own.\n */\n readonly grown: Readonly<Record<string, number>>\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 /**\n * Streams that broke, by an error or by an event ahead of their cursor, and\n * have not resubscribed since: changes after the break are missed until the\n * live entry restarts them and refetches what they cover.\n */\n readonly gaps: ReadonlySet<string>\n /** Each live stream that has ever broken, by stream key. One that never broke is absent. */\n readonly streams: Readonly<Record<string, StreamHealth>>\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 * The storage key the cache was last restored from, through `Hydrated`'s\n * `from`. `Data.persistence` saves under a key only once its own snapshot is\n * in, so a save at startup cannot write the empty store over it.\n */\n readonly restoredFrom: Option.Option<string>\n /**\n * Under `verifyPlacement`, the order each list was placed in, by edge key,\n * and the rows placing took out of its first page, until the server's page\n * for it arrives to be compared with them.\n */\n readonly placed: Readonly<Record<string, PlacedOrder>>\n /** Under `verifyPlacement`, each placement the server's page disagreed with. */\n readonly placementMismatches: ReadonlyArray<PlacementMismatch>\n}\n\n/** A list's first page as the client placed it: its keys in order, and those it took out. */\nexport interface PlacedOrder {\n readonly order: ReadonlyArray<string>\n readonly dropped: ReadonlyArray<string>\n}\n\n/** A list the client placed rows in one order and the server then listed in another. */\nexport interface PlacementMismatch {\n readonly connection: string\n /** The keys as placed, as far as the server's page reached. */\n readonly placed: ReadonlyArray<string>\n /** The keys of the server's first page. */\n readonly served: ReadonlyArray<string>\n}\n\n/** How a live stream has fared, as its live entry restarts it. */\nexport interface StreamHealth {\n /** How many times it broke. The live entry restarts on each, so it only grows. */\n readonly restarts: number\n /** Breaks since its last applied event: what the restart's backoff grows with. */\n readonly failures: number\n /** Why it last broke; none for a gap, which is not an error. */\n readonly error: Option.Option<RemoteError>\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 * The generation every entry is refreshed at, at least: `forgetRemote` moves\n * it, so every read and live entry restarts, and a read or stream begun for\n * the principal before is interrupted rather than landing after.\n */\n readonly floor: number\n}\n\nexport const emptyRefresh: RefreshState = {\n generation: 0,\n requested: new Map(),\n started: new Map(),\n floor: 0,\n}\n\n/**\n * The Model with everything the server told it forgotten: values, tombstones,\n * unavailable fields, connections, live cursors, failures, and what is in\n * flight. For a change of principal, whose facts these were. The mutation\n * sequence is kept, so request ids stay unique, and a mutation in flight is\n * treated as applied: its answer, when it comes, writes nothing here.\n */\nexport const forgetRemote = (model: RemoteModel): RemoteModel => {\n const generation = model.refresh.generation + 1\n return {\n ...initialRemoteModel,\n refresh: { generation, requested: new Map(), started: new Map(), floor: generation },\n mutations: {\n ...emptyMutationState,\n sequence: model.mutations.sequence,\n applied: new Set([...model.mutations.applied, ...model.mutations.pending]),\n },\n }\n}\n\nexport const initialRemoteModel: RemoteModel = {\n entities: emptyStore,\n connections: {},\n grown: {},\n optimistic: emptyOptimistic,\n live: {},\n mutations: emptyMutationState,\n gaps: new Set(),\n streams: {},\n loading: new Set(),\n refresh: emptyRefresh,\n failures: noFailures,\n restoredFrom: Option.none(),\n placed: {},\n placementMismatches: [],\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 grown: Schema.Record(Schema.String, Schema.Number),\n optimistic: runtimeSchema,\n live: Schema.Record(Schema.String, runtimeSchema),\n mutations: runtimeSchema,\n gaps: runtimeSchema,\n streams: Schema.Record(Schema.String, 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 restoredFrom: runtimeSchema,\n placed: runtimeSchema,\n placementMismatches: runtimeSchema,\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 live\n * entry restarts it.\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 /** The storage key the snapshot was read from, when it was: `restoredFrom`. */\n readonly from?: string | undefined\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 /** Injected clock reading of the answer: how fresh the written entities are. */\n readonly now: number\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 /** `Data.more`: a read's window, by `windowGrowthKey`, now shows `size` rows. */\n | { readonly _tag: 'WindowGrown'; readonly window: string; readonly size: number }\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 * The slice the query asked for, so the payload's entities write like a\n * read: one request per matching edge. Absent for a page from a server\n * that predates payload planning, which carries edges only.\n */\n readonly select?: RelationRequirement | undefined\n /** The selected fields of the page's items, as a read batch returns them. */\n readonly entities?:\n | ReadonlyArray<{\n readonly entity: string\n readonly id: string\n readonly values: Record<string, unknown>\n }>\n | undefined\n /** Fields asked for that the server settled without a value. */\n readonly settled?:\n | ReadonlyArray<{\n readonly entity: string\n readonly id: string\n readonly fields: ReadonlyArray<string>\n }>\n | undefined\n /** Injected clock reading of the answer, dating what the payload writes. */\n readonly now?: number | 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 /**\n * What `Data.preload` read for a destination, as the Messages that wrote it,\n * reduced in order into the Model as it is now rather than the one the\n * preload started from.\n */\n | { readonly _tag: 'Preloaded'; readonly messages: ReadonlyArray<RemoteMessage> }\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 from: Schema.optional(Schema.String),\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 now: Schema.Number,\n },\n MutationFailed: { requestId: Schema.String, error: remoteErrorSchema },\n OverlayShown: { id: Schema.String, optimistic: Schema.Array(Schema.Unknown) },\n OverlayLifted: { id: Schema.String },\n WindowGrown: { window: Schema.String, size: Schema.Number },\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 select: Schema.optional(RelationRequest),\n entities: Schema.optional(Schema.Array(NormalizedEntity)),\n settled: Schema.optional(Schema.Array(SettledFields)),\n now: Schema.optional(Schema.Number),\n },\n ConnectionInvalidated: { connection: Schema.String },\n ConnectionRefreshed: { connection: Schema.String },\n QueryFailed: { connection: Schema.String, error: remoteErrorSchema },\n Preloaded: {\n messages: Schema.Array(Schema.suspend(() => remoteMessageSchema)),\n },\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.Codec<RemoteMessage, unknown>\n\n/** An overlay's layer, named apart from every request's: a request id is the application's to choose too. */\nconst OVERLAY = 'overlay:'\nconst overlayLayer = (id: string): string => `${OVERLAY}${id}`\n\n/** The ids `OverlayShown` shows now, each once, in the order they are drawn. */\nexport const overlaysOf = (model: RemoteModel): ReadonlyArray<string> => [\n ...new Set(\n [...model.optimistic.layers, ...model.optimistic.overlays].flatMap(({ id }) =>\n id.startsWith(OVERLAY) ? [id.slice(OVERLAY.length)] : [],\n ),\n ),\n]\n\n/** The key a grown window is kept under: its connection and the window first asked for. */\nexport const windowGrowthKey = (identity: string, window: string): string =>\n `${identity}\\u0000${window}`\n\n/**\n * Whether only overlays show this entity: the server has told the store\n * nothing of it and no request's layer writes it, so nothing will fetch what an\n * overlay leaves out.\n */\nexport const onlyOverlaid = (model: RemoteModel, entity: string, id: string): boolean => {\n if (Object.hasOwn(model.entities, entityKey(entity, id))) return false\n const writers = model.optimistic.layers.filter(layer =>\n layer.patches.some(patch => patch.entity === entity && patch.id === id),\n )\n return writers.length > 0 && writers.every(layer => layer.id.startsWith('overlay:'))\n}\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.size === loading.size ? loading : 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.size === loading.size ? loading : 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 prunedLoading = (\n loading: ReadonlySet<string>,\n roots: RetentionRoots,\n reached: () => ReadonlySet<string>,\n): ReadonlySet<string> => {\n if (loading.size === 0) return loading\n const named = new Set(roots.connections.map(root => connectionMark(root.identity)))\n // A field mark goes with its entity, exactly as a connection's goes with the\n // connection: a read the entry stopped waiting for must not leave a value\n // reading `Loading` with nothing fetching it.\n const kept = [...loading].filter(mark =>\n mark.startsWith(connectionPrefix) ? named.has(mark) : reached().has(markEntity(mark)),\n )\n return kept.length === loading.size ? loading : new Set(kept)\n}\n\n/**\n * The windows grown on connections retention keeps; a dropped one starts over.\n * The same record when every one is kept.\n */\nconst keptWindows = (\n grown: RemoteModel['grown'],\n connections: Retained['connections'],\n): RemoteModel['grown'] => {\n const kept = Object.entries(grown).filter(([key]) =>\n Object.hasOwn(connections, key.slice(0, key.lastIndexOf('\\u0000'))),\n )\n return kept.length === Object.keys(grown).length ? grown : Object.fromEntries(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 = refresh.floor\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 * Marks connections as needing to be asked again, and restarts a read of them\n * already in flight: a page requested before what invalidated it could land\n * after it, saying what is no longer true. `Remote.refresh` marks the same way.\n */\nexport const invalidateConnections = (\n model: RemoteModel,\n connections: ReadonlyArray<string>,\n): RemoteModel => {\n if (connections.length === 0) return model\n const marked = connections.reduce(\n (current, connection) => updateRemote(current, { _tag: 'ConnectionInvalidated', connection }),\n model,\n )\n return { ...marked, refresh: withRefreshRequested(marked.refresh, [], connections) }\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]\n if (current?.stale === stale) return connections\n return { ...connections, [connection]: { ...(current ?? emptyConnection), stale } }\n}\n\nconst withLiveState = (\n live: RemoteModel['live'],\n stream: string,\n state: LiveState,\n): RemoteModel['live'] => (live[stream] === state ? live : { ...live, [stream]: state })\n\nconst noHealth: StreamHealth = { restarts: 0, failures: 0, error: Option.none() }\n\n/**\n * A stream broke: it is marked a gap and its restart count moves, which\n * restarts its live entry. A stream already broken and not yet restarted\n * changes nothing, so the events a dying stream still delivers restart it once.\n */\nconst broke = (\n model: RemoteModel,\n stream: string,\n error: Option.Option<RemoteError>,\n): RemoteModel => {\n if (model.gaps.has(stream)) return model\n const health = model.streams[stream] ?? noHealth\n return {\n ...model,\n gaps: new Set([...model.gaps, stream]),\n streams: {\n ...model.streams,\n [stream]: { restarts: health.restarts + 1, failures: health.failures + 1, error },\n },\n }\n}\n\n/**\n * An event applied on a stream that resubscribed: it works, so its next break\n * backs off from the start. A broken stream's last events prove nothing.\n */\nconst healthy = (model: RemoteModel, stream: string): RemoteModel => {\n const health = model.streams[stream]\n return health === undefined || health.failures === 0 || model.gaps.has(stream)\n ? model\n : {\n ...model,\n streams: { ...model.streams, [stream]: { ...health, failures: 0, error: Option.none() } },\n }\n}\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 its\n * live entry restarts it rather than silently missing facts. When every field a Message\n * touches keeps its identity, `model` itself is returned, so the application's\n * root keeps its identity and Foldkit does not render. The common no-ops do (a\n * duplicate live event, a repeated `ReadStarted`); a repeated failure, or a\n * `preserve-existing` restore of entities already held, still makes an equal\n * copy.\n */\nexport const updateRemote = (model: RemoteModel, message: RemoteMessage): RemoteModel => {\n const next = reduceRemote(model, message)\n return next === model || !sameFields(model, next) ? next : model\n}\n\n/** Whether every field of `next` is the one `model` holds. */\nconst sameFields = (model: RemoteModel, next: RemoteModel): boolean => {\n const keys = Object.keys(next) as Array<keyof RemoteModel>\n return (\n keys.length === Object.keys(model).length && keys.every(key => Object.is(model[key], next[key]))\n )\n}\n\n/**\n * A placement compared with the server's first page of the list it placed\n * in, under `verifyPlacement`: the keys as far as both reach must agree, and\n * no row placing took out may be one the page still lists. The record goes\n * once compared; a disagreement is kept.\n */\nconst checkedPlacement = (\n model: RemoteModel,\n connection: string,\n page: { readonly edges: ReadonlyArray<{ readonly key: string }>; readonly start: Boundary },\n refreshes: boolean,\n): Pick<RemoteModel, 'placed' | 'placementMismatches'> => {\n const placed = model.placed[connection]\n if (placed === undefined || !refreshes || page.start._tag !== 'Terminal') {\n return { placed: model.placed, placementMismatches: model.placementMismatches }\n }\n const { [connection]: _, ...rest } = model.placed\n const reach = Math.min(placed.order.length, page.edges.length)\n const served = page.edges.slice(0, reach).map(edge => edge.key)\n const asPlaced = placed.order.slice(0, reach)\n const listed = new Set(page.edges.map(edge => edge.key))\n const agrees =\n served.every((key, index) => key === asPlaced[index]) &&\n !placed.dropped.some(key => listed.has(key))\n return {\n placed: rest,\n placementMismatches: agrees\n ? model.placementMismatches\n : [...model.placementMismatches, { connection, placed: asPlaced, served }],\n }\n}\n\nconst reduceRemote = (model: RemoteModel, message: RemoteMessage): RemoteModel => {\n switch (message._tag) {\n case 'Preloaded':\n return message.messages.reduce(reduceRemote, model)\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) {\n return broke(model, message.stream, Option.some(message.error))\n }\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 // Retention's own walk over the Model before collection. It counts a\n // relation's target and a list's row the store does not hold, which is\n // exactly a value whose first read failed or is still in flight.\n let reachedKeys: ReadonlySet<string> | undefined\n const reached = () =>\n (reachedKeys ??= reachable(\n model.entities,\n message.roots,\n model.connections,\n model.optimistic,\n model.mutations.pending,\n ))\n return {\n ...model,\n ...retained,\n grown: keptWindows(model.grown, retained.connections),\n refresh: prunedRefresh(model.refresh, retained),\n failures: prunedFailures(model.failures, message.roots, reached),\n loading: prunedLoading(model.loading, message.roots, reached),\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 // A restored value is a write like any other, and settles a failure on the\n // field it writes: every field under `replace`, and only fields of\n // entities the store did not hold under `preserve-existing`.\n const written = Object.entries(message.entities).flatMap(([key, entry]) =>\n message.merge === 'replace' || !(key in model.entities)\n ? [...entry.present].map(field => `${key}\\u0000${field}`)\n : [],\n )\n return {\n ...model,\n entities: RemotePersistence.mergeStores(model.entities, message.entities, message.merge),\n failures: withoutFieldFailures(model.failures, written),\n connections:\n restored.length === 0\n ? model.connections\n : message.merge === 'replace'\n ? { ...model.connections, ...Object.fromEntries(restored) }\n : { ...Object.fromEntries(restored), ...model.connections },\n restoredFrom: message.from === undefined ? model.restoredFrom : Option.some(message.from),\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 // A field the server settled without a value is asked for again the same\n // way, and reads `Loading` while it is.\n const marks = marksOf(message.requests)\n const entities = setUnavailable(setStale(asked, marks, true), marks, false)\n // Asking again is also how a failed field is retried, including one that\n // never loaded and so has nothing to mark stale, and one on a relation's\n // target, which the request reaches only through the store: a server need\n // not expand a relation, and the target is then planned by id once more.\n const failures = withoutFieldFailures(\n model.failures,\n reachedMarks(model.entities, message.requests),\n )\n return { ...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,\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 'WindowGrown':\n return { ...model, grown: { ...model.grown, [message.window]: message.size } }\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 broke(model, message.stream, Option.none())\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 const next = {\n ...model,\n entities: applied.store,\n live: withLiveState(model.live, message.stream, applied.state),\n failures: withoutFieldFailures(model.failures, settled),\n }\n return applied.outcome === 'applied' ? healthy(next, message.stream) : next\n }\n const applied = applyConnectionEvent(state, model.optimistic, message.event, message.policy)\n if (applied.outcome === 'gap') return broke(model, message.stream, Option.none())\n const written = {\n ...model,\n optimistic: applied.optimistic,\n live: withLiveState(model.live, message.stream, applied.state),\n }\n const next = applied.outcome === 'applied' ? healthy(written, message.stream) : written\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 : invalidateConnections(next, [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 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 // A query payload writes like a read: one synthetic request per matching\n // edge, so windows, nested relations and settled fields behave as they do\n // for `ReadReceived`. A page without a payload only merges the connection.\n // Entities without a select are unsolicited and ignored: there is nowhere\n // to write them, and they must not clear failures they do not answer.\n const payload = message.select === undefined ? [] : (message.entities ?? [])\n const settled = message.select === undefined ? [] : (message.settled ?? [])\n const requests =\n message.select === undefined || (payload.length === 0 && settled.length === 0)\n ? []\n : message.page.edges\n .filter(edge => edge.ref.entity === message.select!.entity)\n .map(edge => ({ ...message.select!, id: edge.ref.id }))\n const entities =\n requests.length === 0\n ? model.entities\n : writeRead(\n model.entities,\n requests,\n { entities: [...payload], settled: [...settled] },\n message.now ?? 0,\n )\n // Like `ReadReceived`: the answer settles what it was asked, whether\n // with values or as settled, so a prior failure does not outlive it.\n const failures = withoutFieldFailures(\n withoutConnectionFailure(model.failures, message.connection),\n [...fieldMarks(requests), ...patchedMarks(payload)],\n )\n return {\n ...model,\n ...checkedPlacement(model, message.connection, message.page, message.refreshes === true),\n entities,\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.\n // A connection is often both: a failed refresh stays due, and `Hydrated`\n // restores one stale. Asking again must still settle its failure.\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 pages stay as they were, and a refresh that failed is still owed:\n // the connection stays stale. The failure is what stops the planner\n // asking again on its own; whatever settles it next (a retry, or a page\n // from \"load more\") leaves the connection due, so the refresh then runs\n // rather than a later page quietly passing for current.\n return {\n ...model,\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 * Every field a read's requests reach: their own, and through each relation\n * the store already holds, the fields they ask of its targets. A request with\n * a relation riding on it names no target id; the store does, and a failure\n * recorded on a target is reached only this way.\n */\nconst reachedMarks = (\n store: EntityStore,\n requests: ReadonlyArray<Requirement>,\n): ReadonlyArray<string> => {\n const marks: string[] = []\n const walked = new Map<string, Set<RelationRequirement>>()\n const walk = (entity: string, id: string, requirement: RelationRequirement): void => {\n const key = entityKey(entity, id)\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 marks.push(fieldMark(entity, id, field))\n const nested = requirement.relations?.[field]\n if (nested === undefined) continue\n const value = readField(store, key, field)\n if (value._tag === 'None') continue\n for (const ref of targetsOf(value.value, nested)) walk(ref.entity, ref.id, nested)\n }\n }\n for (const request of requests) walk(request.entity, request.id, request)\n return marks\n}\n\n/** The entity key a field mark belongs to. */\nconst markEntity = (mark: string): string => mark.slice(0, mark.indexOf('\\u0000'))\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 = (\n failures: Failures,\n roots: RetentionRoots,\n reached: () => ReadonlySet<string>,\n): Failures => {\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 fields =\n Object.keys(failures.fields).length === 0\n ? []\n : Object.entries(failures.fields).filter(([mark]) => reached().has(markEntity(mark)))\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 * Whether a read is fetching any field `relation` reads of an entity, its own\n * or, through each relation the store holds, its targets'. A value whose owner\n * is being fetched is loading, not `Initial`: nothing is missing a fetch.\n */\nexport const isLoadingThrough = (\n model: RemoteModel,\n entity: string,\n id: string,\n relation: RelationRequirement,\n): boolean => {\n if (model.loading.size === 0) return false\n const walked = new Map<string, Set<RelationRequirement>>()\n const walk = (target: string, targetId: string, requirement: RelationRequirement): boolean => {\n const key = entityKey(target, targetId)\n const seen = walked.get(key) ?? new Set()\n if (seen.has(requirement)) return false\n seen.add(requirement)\n walked.set(key, seen)\n for (const field of requirement.fields) {\n if (model.loading.has(fieldMark(target, targetId, field))) return true\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 if (walk(ref.entity, ref.id, nested)) return true\n }\n }\n return false\n }\n return walk(entity, id, relation)\n}\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, and\n // without settling any of their fields: whether the entity never existed or\n // is gone, the client knows the same thing: it is not there. Without this the\n // read would stay `Loading` for good. A forced plan (`refresh`) asks again,\n // and any later write clears the tombstone.\n //\n // An id the server settled fields of is not absent: it was asked about and\n // the answer was \"not this\", which is about the fields, not the entity. What\n // the store already holds of it stays.\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 const settled = new Set(result.settled.map(entry => entityKey(entry.entity, entry.id)))\n let answered = store\n for (const request of requests) {\n const key = entityKey(request.entity, request.id)\n if (!returned.has(key) && !settled.has(key)) answered = tombstone(answered, key)\n }\n // Settled after the values: a field the same result also answers is present,\n // and a present field is never marked.\n return setUnavailable(\n writeEntities(answered, writes, now),\n result.settled.map(entry => [entityKey(entry.entity, entry.id), entry.fields] as const),\n true,\n )\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 * What of Remote's state crosses from a server render to the browser.\n *\n * A page rendered a moment ago sends exactly what its active Surfaces read:\n * for each requirement the fields it names, following relations through the\n * refs the store holds, and each connection whole, with its boundaries, so\n * \"load more\" knows where the server stopped. A live subscription's cursor\n * crosses with the entities it covers, so a subscription started in the\n * browser resumes where the server's left off.\n *\n * This is not a `Snapshot`, which is built for a cache that survived a reload\n * and deliberately keeps no cursors. Nothing else of `RemoteModel` crosses:\n * loading marks, failures, the mutation ledger, optimistic layers, gaps and\n * retention start from their initial values in the browser.\n */\nimport { Result, Schema } from 'effect'\nimport type { Metadata, ModelRef } from 'foldkit-surface'\nimport type { Boundary, Connection, Segment } from './connection.js'\nimport type { LiveState } from './live.js'\nimport type { RemoteModel } from './model.js'\nimport { targetsOf } from './relation.js'\nimport { RemoteConnections, RemoteRequirements, type RelationRequirement } from './requirement.js'\nimport { entityKey, readField, type EntityEntry } from './store.js'\n\nconst CapturedEntry = Schema.Struct({\n values: Schema.Record(Schema.String, Schema.Unknown),\n present: Schema.Array(Schema.String),\n stale: Schema.Array(Schema.String),\n unavailable: Schema.Array(Schema.String),\n windows: Schema.Record(Schema.String, Schema.String),\n tombstone: Schema.Boolean,\n updatedAt: Schema.Number,\n})\n\nconst CapturedBoundary = Schema.Union([\n Schema.TaggedStruct('Terminal', {}),\n Schema.TaggedStruct('Cursor', { cursor: Schema.String }),\n Schema.TaggedStruct('Unknown', {}),\n])\n\nconst CapturedConnection = Schema.Struct({\n segments: Schema.Array(\n Schema.Struct({\n edges: Schema.Array(\n Schema.Struct({\n key: Schema.String,\n ref: Schema.Struct({ entity: Schema.String, id: Schema.String }),\n }),\n ),\n start: CapturedBoundary,\n end: CapturedBoundary,\n }),\n ),\n stale: Schema.Boolean,\n})\n\nconst CapturedLive = Schema.Struct({\n cursor: Schema.Number,\n boundary: Schema.Record(\n Schema.String,\n Schema.Struct({ before: Schema.Number, after: Schema.Number }),\n ),\n})\n\n/**\n * Marks a Subscription entry Remote built as one that may start late under\n * `foldkit-ssr`'s deferred boot (its decision 10): a read with resumed data\n * plans nothing, a live subscription resumes from the cursor the envelope\n * carries, and retention running late collects late. Non-enumerable, so the\n * runtime's iteration of an entry never sees it.\n */\nexport const DEFERRABLE: unique symbol = Symbol.for('foldkit-remote/deferrable')\n\n/** Marks every entry of a record Remote built, lifted or not. */\nexport const markAll = <Entries extends object>(entries: Entries): Entries => {\n for (const entry of Object.values(entries)) {\n Object.defineProperty(entry, DEFERRABLE, { value: true, enumerable: false })\n }\n return entries\n}\n\n/** The captured part of a Remote store, as JSON. */\nexport const RemoteCapture = Schema.Struct({\n entities: Schema.Record(Schema.String, CapturedEntry),\n connections: Schema.Record(Schema.String, CapturedConnection),\n live: Schema.Record(Schema.String, CapturedLive),\n})\nexport type RemoteCapture = typeof RemoteCapture.Type\n\ntype MutableEntry = {\n values: Record<string, unknown>\n present: Set<string>\n stale: Set<string>\n unavailable: Set<string>\n windows: Record<string, string>\n tombstone: boolean\n updatedAt: number\n}\n\n/** What some projections read, from their metadata. */\nconst askedOf = (projections: ReadonlyArray<{ readonly metadata: Metadata }>) => ({\n requirements: projections.flatMap(projection => RemoteRequirements.get(projection.metadata)),\n connections: projections.flatMap(projection => RemoteConnections.get(projection.metadata)),\n})\n\n/** Whether every `entity:id:fields` part of a live stream key was captured with those fields. */\nconst liveCovered = (stream: string, entries: ReadonlyMap<string, MutableEntry>): boolean =>\n stream.split('|').every(part => {\n const split = part.lastIndexOf(':')\n const entry = entries.get(part.slice(0, split))\n const fields = part\n .slice(split + 1)\n .split(',')\n .filter(field => field !== '')\n return entry !== undefined && fields.every(field => entry.present.has(field))\n })\n\n/**\n * Captures what some projections read from a store: the fields each\n * requirement names, through its relations; each connection whole, and the\n * fields its selection reads of each item; and each live cursor whose\n * entities were all captured with the fields it follows.\n */\nexport const captureRemote = (\n remote: RemoteModel,\n projections: ReadonlyArray<{ readonly metadata: Metadata }>,\n): RemoteCapture => {\n const store = remote.entities\n const entries = new Map<string, MutableEntry>()\n const walked = new Map<string, Set<RelationRequirement>>()\n\n const walk = (entity: string, id: string, requirement: RelationRequirement): void => {\n const key = entityKey(entity, id)\n const seen = walked.get(key) ?? new Set()\n if (seen.has(requirement)) return\n seen.add(requirement)\n walked.set(key, seen)\n const stored: EntityEntry | undefined = store[key]\n if (stored === undefined) return\n const entry = entries.get(key) ?? {\n values: {},\n present: new Set<string>(),\n stale: new Set<string>(),\n unavailable: new Set<string>(),\n windows: {},\n tombstone: stored.tombstone,\n updatedAt: stored.updatedAt,\n }\n entries.set(key, entry)\n for (const field of requirement.fields) {\n // A field the server settled without a value is knowledge too: the\n // browser would otherwise ask for it once more.\n if (stored.unavailable.has(field)) entry.unavailable.add(field)\n if (!stored.present.has(field)) continue\n entry.values[field] = stored.values[field]\n entry.present.add(field)\n if (stored.stale.has(field)) entry.stale.add(field)\n const window = stored.windows[field]\n if (window !== undefined) entry.windows[field] = window\n const nested = requirement.relations?.[field]\n if (nested === undefined) continue\n const value = readField(store, key, field)\n if (value._tag === 'None') continue\n for (const ref of targetsOf(value.value, nested)) walk(ref.entity, ref.id, nested)\n }\n }\n\n const asked = askedOf(projections)\n for (const requirement of asked.requirements) {\n walk(requirement.entity, requirement.id, requirement)\n }\n const connections: Record<string, Connection> = {}\n for (const { identity, select } of asked.connections) {\n const connection = remote.connections[identity]\n if (connection === undefined) continue\n connections[identity] = connection\n for (const segment of connection.segments) {\n for (const edge of segment.edges) walk(edge.ref.entity, edge.ref.id, select)\n }\n }\n const live: Record<string, LiveState> = {}\n for (const [stream, state] of Object.entries(remote.live)) {\n if (liveCovered(stream, entries)) live[stream] = state\n }\n\n return {\n entities: Object.fromEntries(\n [...entries].map(([key, entry]) => [\n key,\n {\n values: entry.values,\n present: [...entry.present],\n stale: [...entry.stale],\n unavailable: [...entry.unavailable],\n windows: entry.windows,\n tombstone: entry.tombstone,\n updatedAt: entry.updatedAt,\n },\n ]),\n ),\n connections: Object.fromEntries(\n Object.entries(connections).map(([identity, connection]) => [\n identity,\n {\n segments: connection.segments.map(segment => ({\n edges: segment.edges.map(edge => ({ key: edge.key, ref: edge.ref })),\n start: segment.start,\n end: segment.end,\n })),\n stale: connection.stale,\n },\n ]),\n ),\n live,\n }\n}\n\n/**\n * Sets a capture onto a store: its entities, connections and live cursors\n * replace any held under the same keys, and nothing else of the store changes.\n */\nexport const restoreRemote = <Store extends RemoteModel>(\n remote: Store,\n capture: RemoteCapture,\n): Store => ({\n ...remote,\n entities: {\n ...remote.entities,\n ...Object.fromEntries(\n Object.entries(capture.entities).map(([key, entry]) => [\n key,\n {\n values: entry.values,\n present: new Set(entry.present),\n stale: new Set(entry.stale),\n unavailable: new Set(entry.unavailable),\n windows: entry.windows,\n tombstone: entry.tombstone,\n updatedAt: entry.updatedAt,\n } satisfies EntityEntry,\n ]),\n ),\n },\n connections: {\n ...remote.connections,\n ...Object.fromEntries(\n Object.entries(capture.connections).map(([identity, connection]) => [\n identity,\n {\n segments: connection.segments.map((segment): Segment => ({\n edges: segment.edges,\n start: segment.start as Boundary,\n end: segment.end as Boundary,\n })),\n stale: connection.stale,\n } satisfies Connection,\n ]),\n ),\n },\n live: { ...remote.live, ...capture.live },\n})\n\n/**\n * A resume part, in the shape `foldkit-ssr`'s `SSR.plan` takes in `parts`.\n * Declared here structurally, so neither package depends on the other.\n */\nexport interface RemoteResumePart<AppModel> {\n readonly id: string\n /** The metadata key names whose reads this part resumes. */\n readonly covers: ReadonlyArray<string>\n readonly capture: (\n model: AppModel,\n projections: ReadonlyArray<{ readonly metadata: Metadata }>,\n ) => unknown\n readonly restore: (model: AppModel, value: unknown) => Result.Result<AppModel, string>\n /** Whether a Subscription entry is one of this domain's, which may start late. */\n readonly deferrable: (key: string, entry: unknown) => boolean\n}\n\nconst encodeCapture = Schema.encodeSync(RemoteCapture)\nconst decodeCapture = Schema.decodeUnknownResult(RemoteCapture)\n\n/**\n * The resume part for a Remote domain, for `SSR.plan`'s `parts`: it sends\n * what the plan's active Surfaces read from this domain's store, and nothing\n * else of it. `id` tells two domains in one application apart.\n */\nexport const resumePart = <AppModel, Store extends RemoteModel>(\n domain: { readonly store: ModelRef<AppModel, Store> },\n options: { readonly id?: string | undefined } = {},\n): RemoteResumePart<AppModel> => ({\n id: options.id ?? 'remote',\n covers: [RemoteRequirements.name, RemoteConnections.name],\n deferrable: (_key, entry) => typeof entry === 'object' && entry !== null && DEFERRABLE in entry,\n capture: (model, projections) =>\n encodeCapture(captureRemote(domain.store.get(model), projections)),\n restore: (model, value) =>\n Result.match(decodeCapture(value), {\n onFailure: error => Result.fail(`Remote's state does not decode: ${error.message}`),\n onSuccess: capture =>\n Result.succeed(domain.store.set(model, restoreRemote(domain.store.get(model), capture))),\n }),\n})\n","/**\n * Remote's three calls as JSON: one request, `{ operation, payload }`, and one\n * answer, `{ result }` or `{ error }`. `RemoteServer.answer` is the other end.\n * The client takes any way of sending the request text and receiving the\n * answer, so the same client speaks HTTP (`http`), a worker, or a server\n * running in the page. There is no live stream over it.\n */\nimport { Effect, Option, Schema, Stream } from 'effect'\nimport type { RemoteRpcClient } from './client.js'\nimport {\n RemoteForbidden,\n RemoteMutationError,\n RemoteQueryError,\n RemoteReadError,\n RemoteUnauthenticated,\n} from './wire.js'\n\n/** A request: which of Remote's calls, and its payload as the RPC protocol encodes it. */\nexport const RemoteJsonRequest = Schema.Struct({\n operation: Schema.Literals(['read', 'query', 'mutate']),\n payload: Schema.Unknown,\n})\nexport type RemoteJsonRequest = typeof RemoteJsonRequest.Type\n\n/** An answer: the call's result, or why there is none. */\nexport const RemoteJsonAnswer = Schema.Union([\n Schema.Struct({ result: Schema.Unknown }),\n Schema.Struct({\n error: Schema.String,\n refusal: Schema.optional(Schema.Unknown),\n /** Who is asking was refused, with the application's reason when it gave one. */\n forbidden: Schema.optional(Schema.Struct({ reason: Schema.optional(Schema.String) })),\n /** Who is asking could not be told, with the reason when one was given; a 401. */\n unauthenticated: Schema.optional(Schema.Struct({ reason: Schema.optional(Schema.String) })),\n }),\n])\nexport type RemoteJsonAnswer = typeof RemoteJsonAnswer.Type\n\ntype ErrorAnswer = Extract<RemoteJsonAnswer, { readonly error: string }>\n\nconst decodeAnswer = Schema.decodeUnknownEffect(RemoteJsonAnswer)\n\n/**\n * Sends one request's text and resolves with its answer as parsed JSON. It\n * rejects when nothing came back, and the call fails with that message.\n */\nexport type RemoteJsonSend = (request: string) => Promise<unknown>\n\nconst call = <A, E>(\n send: RemoteJsonSend,\n operation: RemoteJsonRequest['operation'],\n payload: unknown,\n fail: (answer: ErrorAnswer) => E,\n): Effect.Effect<A, E> =>\n Effect.tryPromise({\n try: () => send(JSON.stringify({ operation, payload })),\n catch: error => fail({ error: error instanceof Error ? error.message : String(error) }),\n }).pipe(\n Effect.flatMap(answer =>\n decodeAnswer(answer).pipe(\n Effect.mapError(() =>\n fail({ error: 'The server answered with something that is not an answer' }),\n ),\n ),\n ),\n Effect.flatMap(answer =>\n 'error' in answer\n ? Effect.fail(fail(answer))\n : // The answer is to the request this call sent, so its result is this call's.\n Effect.succeed(answer.result as A),\n ),\n )\n\n/**\n * An error answer as its call's failure: a refusal of who is asking, of\n * every call kind alike, or the call's own error.\n */\nconst failure =\n <E>(own: (answer: ErrorAnswer) => E) =>\n (answer: ErrorAnswer): E | RemoteUnauthenticated =>\n answer.unauthenticated === undefined\n ? own(answer)\n : new RemoteUnauthenticated({\n message: answer.error,\n ...(answer.unauthenticated.reason === undefined\n ? {}\n : { reason: answer.unauthenticated.reason }),\n })\n\n/** Remote's client over `send`, for `Remote.clientLayer`. */\nexport const json = (send: RemoteJsonSend): RemoteRpcClient => ({\n FoldkitRemoteRead: payload =>\n call(\n send,\n 'read',\n payload,\n failure(({ error }) => new RemoteReadError({ message: error })),\n ),\n FoldkitRemoteQuery: payload =>\n call(\n send,\n 'query',\n payload,\n failure(({ error }) => new RemoteQueryError({ message: error })),\n ),\n FoldkitRemoteMutate: payload =>\n call(\n send,\n 'mutate',\n payload,\n failure(({ error, refusal, forbidden }) =>\n forbidden === undefined\n ? new RemoteMutationError({ message: error, refusal })\n : new RemoteForbidden({\n message: error,\n ...(forbidden.reason === undefined ? {} : { reason: forbidden.reason }),\n }),\n ),\n ),\n FoldkitRemoteLive: () => Stream.empty,\n})\n\n/** A body that did not parse, told apart from every value one can parse to, `null` included. */\nconst notJson = Symbol('not JSON')\n\nconst Reason = Schema.Struct({ reason: Schema.optional(Schema.String) })\n/** A refusal in Remote's own words, by the key it is given under. */\nconst ownRefusal: Record<\n 'unauthenticated' | 'forbidden',\n (body: unknown) => Option.Option<Partial<RemoteJsonAnswer>>\n> = {\n unauthenticated: Schema.decodeUnknownOption(\n Schema.Struct({ error: Schema.String, unauthenticated: Reason }),\n ),\n forbidden: Schema.decodeUnknownOption(Schema.Struct({ error: Schema.String, forbidden: Reason })),\n}\n\n/**\n * A 401's or 403's answer, whatever its body: Remote's own refusal as it is,\n * and anything else (`{ error }` from middleware, HTML, a shape of its own)\n * as the status alone, so it never reaches a decoder that would call it a\n * broken answer.\n */\nconst refusalOf = (\n body: unknown,\n kind: 'unauthenticated' | 'forbidden',\n status: string,\n): Partial<RemoteJsonAnswer> =>\n Option.getOrElse(ownRefusal[kind](body), () => ({ error: status, [kind]: {} }))\n\n/**\n * Remote's client over HTTP: each call a `POST` of the request to `url`, the\n * answer its JSON body whatever its status. A 401 is answered as\n * unauthenticated, for every call kind, and a 403 as forbidden, whatever the\n * body says: the server's own says why, and middleware in front of Remote\n * may say anything.\n * `headers` is read per request, so a token that changes reaches the next\n * call. `fetch` defaults to the global one; pass it to route calls through\n * another implementation in tests.\n */\nexport const http = (\n url: string,\n options: {\n readonly headers?: (() => Readonly<Record<string, string>>) | undefined\n readonly fetch?: typeof fetch | undefined\n } = {},\n): RemoteRpcClient =>\n json(async request => {\n const via = options.fetch ?? fetch\n const response = await via(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json', ...options.headers?.() },\n body: request,\n })\n const status = `${response.status} ${response.statusText}`\n const body: unknown = await response.json().catch(() => notJson)\n if (response.status === 401) return refusalOf(body, 'unauthenticated', status)\n if (response.status === 403) return refusalOf(body, 'forbidden', status)\n if (body === notJson) throw new Error(status)\n return body\n })\n","/**\n * Remote live over fetch with SSE framing: the other end of\n * `foldkit-remote-server/fetch`'s live open. One `POST` carries the live\n * requirement; the answer is a `text/event-stream` of `LiveChange` frames,\n * one `data:` frame per change, closing when the server has nothing more or\n * failing on a terminal `event: error` frame. Abandoning the stream aborts\n * the request, which interrupts the subscription server-side.\n *\n * `httpWithLive` is this live stream beside `http`'s reads, queries, and\n * mutations, for `Remote.clientLayer`.\n */\nimport { Effect, Predicate, Schema, Stream } from 'effect'\nimport type { RemoteRpcClient } from './client.js'\nimport { http } from './json.js'\nimport { LiveChange, RemoteLiveError, RemoteUnauthenticated, type LiveRequirement } from './wire.js'\n\n/** What `httpWithLive` needs besides the URL. Mirrors `http`, plus the fetch itself. */\nexport interface LiveFetchOptions {\n /** Read per request, so a token that changes reaches the next call. */\n readonly headers?: (() => Readonly<Record<string, string>>) | undefined\n /** Defaults to the global one; pass it to route calls elsewhere in tests. */\n readonly fetch?: typeof fetch | undefined\n}\n\nconst decodeChange = Schema.decodeUnknownSync(LiveChange)\n\n/**\n * One SSE frame: its event (default `message`) and its data lines. Comment\n * and other lines decide nothing and are left out rather than kept.\n */\ninterface Frame {\n readonly event: string\n readonly data: ReadonlyArray<string>\n}\n\nconst parseFrame = (text: string): Frame => {\n let event = 'message'\n const data: string[] = []\n for (const line of text.split(/\\r\\n|\\n/)) {\n if (line.startsWith(':') || line === '') continue\n const colon = line.indexOf(':')\n if (colon < 0) continue\n const field = line.slice(0, colon)\n const value = line.slice(colon + 1).startsWith(' ')\n ? line.slice(colon + 2)\n : line.slice(colon + 1)\n if (field === 'event') event = value\n else if (field === 'data') data.push(value)\n }\n return { event, data }\n}\n\n/** The frames of a body, split liberally: a blank line ends a frame. */\nasync function* frames(body: ReadableStream<Uint8Array>): AsyncGenerator<Frame> {\n const reader = body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n try {\n for (;;) {\n const next = await reader.read()\n if (next.done) break\n buffer += decoder.decode(next.value, { stream: true })\n for (;;) {\n const found = /(?:\\r\\n|\\n){2}/.exec(buffer)\n if (found === null) break\n yield parseFrame(buffer.slice(0, found.index))\n buffer = buffer.slice(found.index + found[0].length)\n }\n }\n buffer += decoder.decode()\n if (buffer.trim() !== '') yield parseFrame(buffer)\n } finally {\n await reader.cancel().catch(() => {})\n reader.releaseLock()\n }\n}\n\n/** The wire changes of a live body: data frames decoded, error frames failed. */\nasync function* changes(\n body: ReadableStream<Uint8Array>,\n): AsyncGenerator<Schema.Schema.Type<typeof LiveChange>> {\n for await (const frame of frames(body)) {\n if (frame.data.length === 0) continue\n const text = frame.data.join('\\n')\n if (frame.event === 'error') {\n const said: unknown = JSON.parse(text)\n const message =\n Predicate.isObject(said) && typeof said.message === 'string' ? said.message : text\n // A stream ended because who it serves could no longer be told says so.\n if (Predicate.isObject(said) && Predicate.isObject(said.unauthenticated)) {\n const reason = said.unauthenticated.reason\n throw new RemoteUnauthenticated({\n message,\n ...(typeof reason === 'string' ? { reason } : {}),\n })\n }\n throw new RemoteLiveError({ message })\n }\n yield decodeChange(JSON.parse(text))\n }\n}\n\nconst liveError = (error: unknown): RemoteLiveError | RemoteUnauthenticated =>\n error instanceof RemoteLiveError || error instanceof RemoteUnauthenticated\n ? error\n : new RemoteLiveError({ message: error instanceof Error ? error.message : String(error) })\n\n/** Remote's live stream over fetch: `serveFetch`'s live open as a `Stream`. */\nexport const liveFetch =\n (url: string, options: LiveFetchOptions = {}): RemoteRpcClient['FoldkitRemoteLive'] =>\n (payload: Schema.Schema.Type<typeof LiveRequirement>) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const via = options.fetch ?? fetch\n const controller = yield* Effect.acquireRelease(\n Effect.sync(() => new AbortController()),\n open => Effect.sync(() => open.abort()),\n )\n const response = yield* Effect.tryPromise({\n try: () =>\n via(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json', ...options.headers?.() },\n body: JSON.stringify({ operation: 'live', payload }),\n signal: controller.signal,\n }),\n catch: liveError,\n })\n if (!response.ok) {\n // A body that is not an answer still answers: null stands in for it.\n const answered = yield* Effect.tryPromise({\n try: () => response.json().catch(() => null) as Promise<unknown>,\n catch: liveError,\n })\n const message =\n Predicate.isObject(answered) && 'error' in answered\n ? String(answered.error)\n : `HTTP ${response.status} ${response.statusText}`\n if (response.status === 401) {\n // `serveFetch` says why under `unauthenticated`; middleware may say nothing.\n const said =\n Predicate.isObject(answered) && Predicate.isObject(answered.unauthenticated)\n ? answered.unauthenticated.reason\n : undefined\n return yield* new RemoteUnauthenticated({\n message,\n ...(typeof said === 'string' ? { reason: said } : {}),\n })\n }\n return yield* new RemoteLiveError({ message })\n }\n if (response.body === null) {\n return yield* new RemoteLiveError({ message: 'The server answered live with no body' })\n }\n return Stream.fromAsyncIterable(changes(response.body), liveError)\n }),\n )\n\n/**\n * Remote's client over HTTP with live: reads, queries, and mutations as\n * `http` sends them, live as `liveFetch` streams it, for `clientLayer`.\n */\nexport const httpWithLive = (url: string, options: LiveFetchOptions = {}): RemoteRpcClient => ({\n ...http(url, options),\n FoldkitRemoteLive: liveFetch(url, options),\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 { Duration, Effect, Layer, Option, Record, Result, Schema, Stream } from 'effect'\nimport { KeyValueStore } from 'effect/persistence'\nimport {\n Entity as DomainEntity,\n Query as Relational,\n QueryEvaluateError,\n ReadFilter,\n SelectionTypeId,\n} from 'foldkit-entity'\nimport type * as Domain from 'foldkit-entity'\nimport type { RpcClientError } from 'effect/rpc'\nimport { mapMessage, type Command } from 'foldkit/command'\nimport { defineMessageUnion } from 'foldkit/message'\nimport type * as Update from 'foldkit/update'\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 SurfaceSource,\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 items,\n type Connection,\n type Edge,\n} from './connection.js'\nimport {\n Entity,\n type EntityDescriptor,\n type EntityPatch,\n type EntityRef,\n type FieldsFrom,\n} from './entity.js'\nimport { Impact, changesOf, impactOn, type EntityChange, type HeldConnection } from './impact.js'\nimport { belongsEncoded, matching, type Judged, type Matched } from './matching.js'\n\n/** A body's dependencies as an explanation carries them: without the owner identity, which holds a symbol. */\nconst explainedDependencies = (dependencies: Domain.Dependencies): ExplainedDependencies => ({\n fields: dependencies.fields.map(({ entity, key }) => ({ entity, key })),\n inputs: dependencies.inputs,\n operations: dependencies.operations,\n})\nimport {\n inspectEntity,\n inspectRemote,\n type ExplainedDependencies,\n type QueryExplanation,\n type ReadDiagnosis,\n type RemoteInspection,\n} from './inspect.js'\nimport type { LiveCursor, LiveEvent } from './live.js'\nimport {\n failureOf,\n initialRemoteModel,\n overlaysOf,\n isFieldFailed,\n isLoadingThrough,\n onlyOverlaid,\n windowGrowthKey,\n isQueryLoading,\n isRemoteMessage,\n forgetRemote,\n refreshIsInFlight,\n refreshedAt,\n remoteMessageCases,\n remoteMessageSchema,\n remoteModelSchema,\n retentionRootsSchema,\n invalidateConnections,\n updateRemote,\n withRefreshRequested,\n writeRead,\n type RemoteMessage,\n type RemoteMessageInput,\n type RemoteModel,\n} from './model.js'\nimport {\n mutationStatus,\n optimisticOfWrite,\n type MutationDescriptor,\n type MutationStatus,\n type NormalizedPatch,\n} from './mutation.js'\nimport {\n connectionIdentity,\n emptyOptimistic,\n visibleItems,\n visibleStore,\n type ConnectionIdentity,\n type ConnectionOverlay,\n type OptimisticState,\n type OptimisticOperation,\n} from './optimistic.js'\nimport { RowPlace, placeIn, withEdge } from './placement.js'\nimport { deadlineOf, plan, type Deadline, 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 {\n Selection,\n assemble,\n pageSchema,\n relationOf,\n unavailableOf,\n type Page,\n} from './selection.js'\nimport { sameData } from './data.js'\nimport {\n emptyStore,\n entityKey,\n isTombstone,\n missingFields,\n readField,\n type EntityStore,\n} from './store.js'\nimport { RemotePersistence, type Snapshot } from './persistence.js'\nimport { targetsOf } from './relation.js'\nimport {\n QueryRequest,\n QueryResult,\n ReadRequest,\n RelationRequest,\n REMOTE_PROTOCOL_VERSION,\n WindowSchema,\n RemoteLiveError,\n RemoteMutationError,\n RemoteProtocolError,\n RemoteQueryError,\n RemoteReadError,\n RemoteRpc,\n RemoteUnauthenticated,\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'\nimport { markAll, resumePart } from './resume.js'\n\nimport { http as httpClient, json as jsonClient } from './json.js'\nimport { httpWithLive as httpWithLiveClient } from './sse.js'\nexport * from './client.js'\nexport type { RemoteResumePart } from './resume.js'\nexport * from './coalesce.js'\nexport { RemoteJsonAnswer, RemoteJsonRequest, type RemoteJsonSend } from './json.js'\nexport { httpWithLive, liveFetch, type LiveFetchOptions } from './sse.js'\nexport * from './connection.js'\nexport * from './entity.js'\nexport * from './inspect.js'\nexport * from './live.js'\nexport * from './matching.js'\nexport { placeIn, RowPlace } from './placement.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\n/** The Remote descriptor either kind of entity reads as, at the type level. */\ntype DescriptorOf<E extends EntityLike> =\n E extends EntityDescriptor<any, any>\n ? E\n : E extends Domain.AnyEntity\n ? EntityDescriptor<E['name'], FieldsFrom<E>>\n : never\n\ntype NameOf<E extends EntityLike> =\n DescriptorOf<E> extends EntityDescriptor<infer N, any> ? N : never\ntype FieldsOf<E extends EntityLike> =\n DescriptorOf<E> extends EntityDescriptor<any, infer F> ? F : never\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 * Per entity name, the members its server filters rows by under a rule\n * the client does not run (`ReadFilter`), so a change to one is fetched,\n * not placed.\n */\n readonly filtered: ReadonlyMap<string, ReadonlyArray<string>>\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\n/** How `Data.persistence` keeps the cache across a reload. */\nexport interface PersistenceOptions<AppModel> {\n /**\n * Where the snapshot is stored, from the Model: one key per principal, so a\n * change of principal reads and writes another snapshot.\n */\n readonly key: (model: AppModel) => string\n /** Who the snapshot is for; one taken under another scope is discarded. */\n readonly scope: (model: AppModel) => string\n /** The query connections whose rows survive a reload; none by default. */\n readonly connections?: ReadonlyArray<ConnectionIdentity> | undefined\n /** What to keep, when it is not `snapshotOf` the `connections`. */\n readonly snapshot?: ((remote: RemoteModel) => Snapshot) | undefined\n /** A snapshot larger than this is neither written nor read. */\n readonly maxBytes?: number | undefined\n /** How long the cache must be unchanged before it is written; default 250 milliseconds. */\n readonly debounce?: Duration.Input | undefined\n}\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 /** The clock `MutationSucceeded` stamps the answer with; default `Date.now`, read at each use. */\n readonly now?: (() => number) | undefined\n /**\n * For a mutation that is a `Write`: the input keys to write, when only some\n * changed (what an author edited). The rest of the input is still sent, whole.\n */\n readonly keys?: ReadonlyArray<string> | undefined\n}\n\n/**\n * One entry of the active record `subscriptions`, `wiring` and `satisfy`\n * take: a Surface as the Model activates it (`Surface.at`/`Surface.when`),\n * a source of keyed instances (`Surface.each`, or any `SurfaceSource`), or a\n * Surface without params read whole. A family joins its parent's\n * requirements with its instances', so passing the family alone fetches both\n * the page and what the page reveals.\n */\nexport type ActiveEntry<AppModel> =\n ActiveSurface<AppModel> | Surface<AppModel, any, any, void> | SurfaceSource<AppModel>\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, Message = RemoteMessage> = {\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`]: EntryWithoutKeepAlive<\n AppModel,\n Message,\n ReadDependencies,\n RemoteClient\n >\n} & {\n readonly [K in keyof Active & (string | number) as `${K}.live`]: EntryWithoutKeepAlive<\n AppModel,\n Message,\n LiveDependencies,\n RemoteClient\n >\n} & {\n readonly retain: EntryWithoutKeepAlive<AppModel, Message, RetentionRoots, never>\n}\n\n/** The dependencies of a live entry: what it subscribes to, and where a restart resumes. */\nexport interface LiveDependencies {\n readonly requirements: ReadonlyArray<Requirement>\n readonly cursor: LiveCursor\n readonly floor: number\n /** How many times the stream broke; each break restarts it. */\n readonly restarts: number\n /** Breaks since its last applied event, which the restart's backoff grows with. */\n readonly failures: number\n}\n\n/**\n * Whether what an active entry reads live is arriving. `Reconnecting` is a\n * stream that broke and waits to resubscribe; until it has, changes are\n * missed, and its rows may be out of date.\n */\nexport type LiveStatus =\n /** It reads nothing live. */\n | { readonly _tag: 'Idle' }\n /** Subscribed, and not broken since. */\n | { readonly _tag: 'Live' }\n | {\n readonly _tag: 'Reconnecting'\n /** Breaks in a row, the first being 1. */\n readonly attempt: number\n /** Why it broke; none for a gap in its events. */\n readonly error: Option.Option<RemoteError>\n }\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 keyof typeof remoteMessageCases\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 /**\n * \"Load more\": the Model with the read's window grown by one page, so it\n * shows that many more rows; the read entry fetches what the connection\n * lacks. None when the read shows everything there is (or is not a sized\n * window). Called from `update`.\n */\n more<Name extends string, Input>(\n model: AppModel,\n projection: QueryProjection<AppModel, any, Name, Input>,\n ): Option.Option<AppModel>\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?:\n Readonly<Record<string, ActiveSurface<AppModel> | SurfaceSource<AppModel>>> | undefined\n },\n ): QueryExplanation\n /**\n * Why a read shows what it shows, in words. Any Remote read: `Data.get`,\n * `Data.live` or `Data.query`.\n *\n * Its point is `Initial`, which means nothing is fetching the read and is\n * almost always a wiring mistake. Given `surfaces`, the same active record\n * `subscriptions` takes, it says which: no active Surface reads it, or one\n * does and Remote's Subscriptions are not running. Pure, like `explain`.\n */\n why(\n model: AppModel,\n projection: Projection<AppModel, RemoteData<unknown>>,\n options?: {\n readonly surfaces?:\n Readonly<Record<string, ActiveSurface<AppModel> | SurfaceSource<AppModel>>> | undefined\n },\n ): ReadDiagnosis\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 /**\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`. A read\n * of an entity only overlays show, lacking a field it selects, is `Failed`\n * (`Overlaid`): nothing will fetch that field.\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 /**\n * The ids `overlay` shows now, in the order they are drawn, a later one over\n * an earlier: what a caller that overlays from its own state reconciles\n * against.\n */\n overlays(model: AppModel): ReadonlyArray<string>\n /**\n * The edges a connection shows, as its reads draw them: the server's pages\n * with pending edits placed, each inserted row where the body's order puts\n * it (or at the end its overlay names, when it cannot be placed), minus\n * removed edges and tombstones. Takes the `RemoteModel`, so a persistence\n * `snapshot` can store a list as it is shown.\n */\n visibleItems(remote: RemoteModel, connection: ConnectionIdentity): ReadonlyArray<Edge>\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 /** `Remote.forget`: the Model with every server-derived fact gone, for a change of principal. */\n forget(model: AppModel): AppModel\n /**\n * A read of this domain as an active Surface, for `subscriptions` and\n * `wiring`: `projectionOf` is what it reads for a Model, none while it\n * reads nothing. It belongs to the domain's application, and lists no\n * Messages: it is a requirement, not a sender. A domain made from a raw\n * optic names no application, so this throws for one.\n */\n active<Value>(\n name: string,\n projectionOf: (model: AppModel) => Option.Option<Projection<AppModel, Value>>,\n ): ActiveSurface<AppModel>\n /**\n * The Foldkit Subscription entries for the active record, keyed for\n * `Subscription.make`: a read entry per record entry (`Remote.observe`), a\n * live entry per record entry that reads through `live` (`Remote.live`), and\n * one retain entry (`Remote.retain`). A `Surface.each` family is one record\n * entry whose read unions its parent's requirements with its instances'.\n * Retention is the domain's: the retain entry of every call roots the active\n * Surfaces of every call, so reads split over calls (one per policy) do not\n * collect each other's data. A Surface's params are a function of the Model\n * (`Surface.at`), so what is fetched, subscribed, and retained follows the\n * Model.\n */\n subscriptions<const Active extends Readonly<Record<string, ActiveEntry<AppModel>>>>(\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.meta`: when what a projection shows was last received, and whether it is stale or loading. */\n meta<Value>(model: AppModel, projection: Projection<AppModel, Value>): ReadMeta\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<\n AppModel,\n RemoteReadError | RemoteProtocolError | RemoteQueryError | RemoteUnauthenticated,\n RemoteClient\n >\n /**\n * The Model with everything the active Surfaces read, for a render that\n * fetches nothing (SSR, a prerender). Each pass prefetches every Surface\n * that plans a read, over the Model the one before it left, so a Surface\n * active only once another's read has arrived is read in the next pass (or\n * the same one, when it comes later in `active`). It stops at the first\n * pass that plans nothing, and fails with `RemoteUnsatisfied` when\n * `options.passes` run out first. Reads are cache-first: a field already\n * held is not asked again. A server that could not tell who is asking\n * fails it with `RemoteUnauthenticated`, for the host to answer as it\n * answers a lost session.\n */\n satisfy(\n model: AppModel,\n active: Readonly<Record<string, ActiveEntry<AppModel>>>,\n options?: SatisfyOptions,\n ): Effect.Effect<\n AppModel,\n | RemoteReadError\n | RemoteProtocolError\n | RemoteQueryError\n | RemoteUnauthenticated\n | RemoteUnsatisfied,\n RemoteClient\n >\n /**\n * `satisfy` from `update`, for a destination the reader has not reached:\n * a hover over a link, or a navigation the app expects. `model` is the\n * Model as it would be there (the route set to the target's); the Command\n * reads what `active` would read in it and yields one `Preloaded`\n * carrying the Messages that wrote it, which reduce into the Model as it is\n * by then. It never fails: a read that fails is one the destination makes\n * again, and what was read before it still arrives.\n *\n * What it reads is kept like any other read until the next change of what\n * is retained, so preload close to the navigation it expects.\n */\n preload(\n model: AppModel,\n active: Readonly<Record<string, ActiveEntry<AppModel>>>,\n options?: SatisfyOptions,\n ): Command<RemoteMessage, never, 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 /**\n * Why the server refused a mutation, as the value its `Refusal` declares:\n * none while it is pending or applied, when it failed for another reason,\n * or when the refusal does not decode as `mutation`'s.\n */\n refusal<Refused>(\n model: AppModel,\n requestId: string,\n mutation: MutationDescriptor<string, any, any, Refused>,\n ): Option.Option<Refused>\n /**\n * Whether what `active` reads live is arriving: `Reconnecting` from the\n * moment its stream breaks until it resubscribes, which its live entry does\n * on its own, with backoff.\n */\n liveStatus(model: AppModel, active: ActiveEntry<AppModel>): LiveStatus\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: <const Active extends Readonly<Record<string, ActiveEntry<AppModel>>>>(\n active: Active,\n options?: SubscriptionsOptions,\n ) => RemoteWiring<AppModel>\n /**\n * Keeps the cache across a reload, as a wiring beside `wiring`: at start and\n * whenever `key` changes, the stored snapshot is restored (`Hydrated`, with\n * what the store already holds kept over it, so a page resumed from the\n * server wins); and the cache is written back when it changes, once its own\n * snapshot is in. Overlays, optimistic layers, the mutation ledger, live\n * cursors and gaps are never stored. A change of principal should `forget`\n * in `update`, and name another `key`.\n */\n persistence(\n options: PersistenceOptions<AppModel>,\n ): Wiring<AppModel, RemoteMessage, KeyValueStore.KeyValueStore>\n /** `Remote.inspect` of the bound slice. */\n inspect(model: AppModel): RemoteInspection\n}\n\n/** What `Remote.fold(Data, …).mutate` starts: `Data.mutate`'s result with its Command lifted. */\nexport type FoldedMutationStarted<AppModel, ParentMessage> = Omit<\n MutationStarted<AppModel>,\n 'command'\n> & {\n readonly command: Command<ParentMessage, never, RemoteClient>\n}\n\n/**\n * A bound domain folded under one of the application's own Message variants,\n * from `Remote.fold`. Calling it reduces a Remote Message into the Model; the\n * members that produce Messages, `fetch`, `mutate`, and `subscriptions`,\n * yield the wrapper Message instead of `RemoteMessage`, with the lift recorded\n * so Story and Scene can resolve a fetch or a mutation by Remote's own answer.\n * Members that only read or write the Model (`get`, `refresh`, `next`,\n * `overlay`, and the rest) stay on the domain itself.\n */\nexport interface RemoteFold<\n AppModel,\n ParentMessage,\n Domain extends RemoteDomain<AppModel, any, any, any, any>,\n> {\n (\n model: AppModel,\n message: RemoteMessage | RemoteMessageInput,\n ): Update.Return<AppModel, ParentMessage>\n /** `Data.mutate`, its Command lifted. */\n readonly mutate: (\n ...args: Parameters<Domain['mutate']>\n ) => FoldedMutationStarted<AppModel, ParentMessage>\n /** `Data.preload`, its Command lifted. */\n readonly preload: (\n ...args: Parameters<Domain['preload']>\n ) => Command<ParentMessage, never, RemoteClient>\n /** `Data.subscriptions`, every entry lifted to the wrapper Message. */\n readonly subscriptions: <const Active extends Readonly<Record<string, ActiveEntry<AppModel>>>>(\n active: Active,\n options?: SubscriptionsOptions,\n ) => SubscriptionEntries<AppModel, Active, ParentMessage>\n}\n\n/** The application Model a bound domain is over. */\nexport type ModelOfDomain<Domain> =\n Domain extends RemoteDomain<infer AppModel, any, any, any, any> ? AppModel : never\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 * A read contract whose connection, when a client can place rows in it, also\n * reads every field its body filters and orders by: a changed row is then\n * compared with neighbours that hold those fields. What the view reads, and so\n * decodes, stays its Selection.\n */\nconst placeableReadContract = <Name extends string, Input>(\n contract: ReadContract<Name, Input>,\n body: Domain.AnyQuery | undefined,\n): ReadContract<Name, Input> => {\n if (body === undefined) return contract\n const { requirement, ref } = contract\n const encoded = Schema.encodeSync(ref.Input)(ref.input) as Readonly<Record<string, unknown>>\n if (Relational.placement(body, encoded)._tag !== 'Placeable') return contract\n const missing = Relational.dependencies(body).fields.filter(\n field => !requirement.select.fields.includes(field.key),\n )\n if (missing.length === 0) return contract\n return {\n ...contract,\n requirement: {\n ...requirement,\n select: {\n ...requirement.select,\n fields: [...requirement.select.fields, ...missing.map(field => field.key)],\n },\n },\n }\n}\n\n/**\n * When what a projection shows was last received, and whether it is stale\n * or loading. See `Remote.meta`.\n */\nexport interface ReadMeta {\n /** The newest server write among what is shown; none received reads `undefined`. */\n readonly updatedAt: number | undefined\n /** Any shown field or connection is marked stale. */\n readonly stale: boolean\n /** Any shown field or connection is in flight. */\n readonly loading: boolean\n}\n\nconst metaOf = (remote: RemoteModel, asked: Asked): ReadMeta => {\n const visible = visibleStoreOf(remote.entities, remote.optimistic)\n let updatedAt: number | undefined\n let stale = false\n let loading = false\n const seen = new Set<string>()\n const touch = (entity: string, id: string, requirement: RelationRequirement): void => {\n const key = entityKey(entity, id)\n const memo = `${key}\\u0000${stableStringify(requirement)}`\n if (seen.has(memo)) return\n seen.add(memo)\n const entry = visible[key]\n if (entry !== undefined && !entry.tombstone) {\n for (const field of requirement.fields) {\n if (!entry.present.has(field)) continue\n if (Number.isFinite(entry.updatedAt))\n updatedAt =\n updatedAt === undefined ? entry.updatedAt : Math.max(updatedAt, entry.updatedAt)\n if (entry.stale.has(field)) stale = true\n }\n }\n if (isLoadingThrough(remote, entity, id, requirement)) loading = true\n for (const [field, relation] of Object.entries(requirement.relations ?? {})) {\n const value = readField(visible, key, field)\n if (value._tag === 'None' || value.value === null || value.value === undefined) continue\n for (const ref of targetsOf(value.value, relation)) touch(ref.entity, ref.id, relation)\n }\n }\n for (const requirement of asked.requirements)\n touch(requirement.entity, requirement.id, requirement)\n for (const connection of asked.connections) {\n const known = remote.connections[connection.identity]\n if (known === undefined) {\n if (isQueryLoading(remote, connection.identity)) loading = true\n continue\n }\n if (known.stale) stale = true\n if (isQueryLoading(remote, connection.identity)) loading = true\n for (const edge of visibleItems(\n known,\n connection.identity,\n remote.optimistic.overlays,\n remote.entities,\n )) {\n if (edge.ref.entity !== connection.select.entity) continue\n touch(edge.ref.entity, edge.ref.id, connection.select)\n }\n }\n return { updatedAt, stale, loading }\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. Keyed on\n// the layers rather than the whole optimistic state, which also changes with\n// every overlay (a live insert, a page pruning one) that no layer is part of.\nconst visibleStores = new WeakMap<object, WeakMap<EntityStore, EntityStore>>()\n\nconst visibleStoreOf = (entities: EntityStore, optimistic: OptimisticState): EntityStore => {\n let byStore = visibleStores.get(optimistic.layers)\n if (byStore === undefined) {\n byStore = new WeakMap()\n visibleStores.set(optimistic.layers, 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/**\n * `Failed` naming a field the server settled without a value, when one is\n * among what `relation` reads of the entity; otherwise nothing, and the store\n * merely lacks the value. The reason stays with the server, so a view shows\n * the field it cannot have, not why.\n */\nconst unavailableFailure = (\n store: EntityStore,\n key: string,\n relation: RelationRequirement,\n): { readonly _tag: 'Failed'; readonly error: RemoteError } | undefined => {\n const field = unavailableOf(store, key, relation)\n return field === undefined\n ? undefined\n : {\n _tag: 'Failed',\n error: {\n _tag: 'Unavailable',\n message: `The server answered without ${field}, and will not answer with it: the field is not available to this client.`,\n },\n }\n}\n\n/**\n * A row's decoded value, kept while the data it was assembled from is the same,\n * so a refetch or live patch that brought equal data hands a view the object it\n * already rendered. Keyed on the row's own values object, which the store keeps\n * across equal writes; a relation's targets are covered by comparing what was\n * assembled.\n */\nconst decodedRows = new WeakMap<\n object,\n {\n readonly decode: (values: unknown) => Result.Result<unknown, Schema.SchemaError>\n readonly rows: WeakMap<object, { readonly values: unknown; readonly decoded: unknown }>\n }\n>()\n\nconst decodeRow = <Value>(\n schema: Schema.Codec<Value, unknown, never, never>,\n source: object,\n values: unknown,\n): Result.Result<Value, Schema.SchemaError> => {\n let bySchema = decodedRows.get(schema)\n if (bySchema === undefined) {\n bySchema = { decode: Schema.decodeUnknownResult(schema), rows: new WeakMap() }\n decodedRows.set(schema, bySchema)\n }\n const cached = bySchema.rows.get(source)\n if (cached !== undefined && sameData(cached.values, values)) {\n return cached.decoded as Result.Result<Value, Schema.SchemaError>\n }\n const decoded = bySchema.decode(values)\n bySchema.rows.set(source, { values, decoded })\n return decoded as Result.Result<Value, Schema.SchemaError>\n}\n\ninterface ReadScope {\n readonly inner: WeakMap<object, ReadScope>\n readonly results: Map<string, unknown>\n}\n\nconst readResults: ReadScope = { inner: new WeakMap(), results: new Map() }\n\n// A read's result per snapshot of everything it reads. `Remote.storeOf` is\n// shared across every read of one Model state, so equal reads of one render\n// assemble and decode once and return one value (a view may compare by\n// identity). A query read also depends on its connection and the overlays,\n// which change independently of the store, so it keys on those too. Weak on\n// every scope, bounded by what is read.\nconst memoRead = <T>(scopes: ReadonlyArray<object>, key: string, compute: () => T): T => {\n let scope = readResults\n for (const by of scopes) {\n let inner = scope.inner.get(by)\n if (inner === undefined) {\n inner = { inner: new WeakMap(), results: new Map() }\n scope.inner.set(by, inner)\n }\n scope = inner\n }\n if (scope.results.has(key)) return scope.results.get(key) as T\n const value = compute()\n scope.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 /** The clock `MutationSucceeded` stamps the answer with; default `Date.now`, read at each use. */\n readonly now?: (() => number) | undefined\n}\n\n/**\n * The default clock. It reads `Date.now` when called rather than holding the\n * function, so fake timers installed after the domain was made move it.\n */\nconst wallClock = (): number => Date.now()\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`, read at each use. */\n readonly now?: (() => number) | undefined\n}\n\n/** How `Data.satisfy` reads: how many passes it may take, and the clock. */\nexport interface SatisfyOptions {\n /** At most this many passes over the Surfaces; default 8. */\n readonly passes?: number | undefined\n /** The clock the reads are stamped with; default `Date.now`, read at each use. */\n readonly now?: (() => number) | undefined\n}\n\n/**\n * `Data.satisfy` reached its bound with Surfaces still reading, such as a\n * chain whose every read reveals one more. It names them, so a page that\n * would have rendered them loading fails instead. (A read the server leaves\n * unanswered settles as missing and ends the loop.)\n */\nexport class RemoteUnsatisfied extends Schema.TaggedError<RemoteUnsatisfied>()(\n 'RemoteUnsatisfied',\n { surfaces: Schema.Array(Schema.String), passes: Schema.Number },\n) {}\n\nexport interface LiveOptions {\n /** The clock `LiveReceived` stamps events with; default `Date.now`, read at each use. */\n readonly now?: (() => number) | undefined\n /**\n * The first restart's delay after a stream breaks, doubled for each break in\n * a row, with ±20% jitter: Sync's transport policy. Default `50 millis`.\n */\n readonly retryBase?: Duration.Input | undefined\n /** The longest a restart waits. Default `5 seconds`. */\n readonly maxRetryDelay?: Duration.Input | 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 // Read from the Entities as given: a descriptor keeps no metadata.\n filtered: new Map(\n config.entities.flatMap(entity =>\n DomainEntity.is(entity) ? [[entity.name, ReadFilter.members(entity.metadata)]] : [],\n ),\n ),\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 askedOf = (projection: Projection<any, unknown>): Asked => ({\n requirements: requirementsOf(projection),\n connections: connectionsOf(projection),\n})\n\n/**\n * Whether `outer` asks for everything `inner` does of one entity: each field,\n * each relation's own slice of its target, and each page window alike.\n */\nconst sliceCovers = (outer: RelationRequirement, inner: RelationRequirement): boolean =>\n outer.entity === inner.entity &&\n inner.fields.every(field => outer.fields.includes(field)) &&\n Object.entries(inner.relations ?? {}).every(([field, relation]) => {\n const wider = outer.relations?.[field]\n return wider !== undefined && sliceCovers(wider, relation)\n }) &&\n Object.entries(inner.windows ?? {}).every(\n ([field, window]) =>\n outer.windows?.[field] !== undefined &&\n stableStringify(outer.windows[field]) === stableStringify(window),\n )\n\n/**\n * Whether what `outer` asks includes everything `inner` asks: each list with\n * the slice it selects of its rows, and each entity with the slice it reads,\n * relations included. A Surface that shows a read is one whose projection\n * asks for all of it; one that reads part of it cannot be why it is fetched.\n * A Surface that asks for one entity in several pieces is already one\n * requirement here: projection metadata unions them per entity and id.\n */\nconst covers = (outer: Asked, inner: Asked): boolean => {\n const { connections, requirements } = outer\n return (\n inner.connections.every(connection =>\n connections.some(\n wider =>\n wider.identity === connection.identity &&\n (connection.select === undefined ||\n (wider.select !== undefined && sliceCovers(wider.select, connection.select))),\n ),\n ) &&\n inner.requirements.every(requirement =>\n requirements.some(wider => wider.id === requirement.id && sliceCovers(wider, requirement)),\n )\n )\n}\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 /** Under a freshness, when what is held next goes stale; `null` when nothing held will. */\n readonly expires: Deadline | null\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 */\n/**\n * One requirement per connection and direction: of the sized windows reading\n * a connection from its start (or end), the widest, which covers the rest.\n * Windows with a cursor are pages of their own and stay as they are.\n */\nconst widest = (\n remote: RemoteModel,\n connections: ReadonlyArray<QueryRequirement>,\n): ReadonlyArray<QueryRequirement> => {\n const kept = new Map<string, QueryRequirement>()\n const rest: QueryRequirement[] = []\n for (const connection of connections) {\n const size = windowSize(remote, connection)\n if (size === undefined) {\n rest.push(connection)\n continue\n }\n const key = `${connection.identity}${String.fromCharCode(0)}${connection.window.first === undefined ? 'last' : 'first'}`\n const current = kept.get(key)\n if (current === undefined) kept.set(key, connection)\n else if (size > (windowSize(remote, current) ?? 0))\n kept.set(key, {\n ...connection,\n select: Requirement.mergeRelation(current.select, connection.select),\n })\n else\n kept.set(key, {\n ...current,\n select: Requirement.mergeRelation(current.select, connection.select),\n })\n }\n return [...kept.values(), ...rest]\n}\n\nconst withWindow = (connection: QueryRequirement, window: QueryWindow): QueryRequirement => ({\n ...connection,\n window,\n ref: { ...connection.ref, window },\n})\n\n/**\n * The page a connection lacks for a window of `size` from its start (or end):\n * the rows after its first segment's end cursor (or before its last's start).\n * Undefined when it holds enough, reaches the end, or does not know where it\n * starts.\n */\nconst missingRows = (\n known: Connection,\n window: QueryWindow,\n size: number,\n): QueryWindow | undefined => {\n const forward = window.first !== undefined\n const segment = forward ? known.segments[0] : known.segments[known.segments.length - 1]\n if (segment === undefined) return undefined\n const [from, to] = forward ? [segment.start, segment.end] : [segment.end, segment.start]\n if (from._tag !== 'Terminal' || to._tag !== 'Cursor' || segment.edges.length >= size)\n return undefined\n const lacking = size - segment.edges.length\n return forward ? { first: lacking, after: to.cursor } : { last: lacking, before: to.cursor }\n}\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 widest(remote, connections)) {\n const known = remote.connections[connection.identity]\n const failed = options.force !== true && connection.identity in remote.failures.connections\n const size = windowSize(remote, connection)\n if (!failed && (known === undefined || known.stale || options.force === true)) {\n queries.push(\n size === undefined\n ? connection\n : withWindow(\n connection,\n connection.window.first === undefined ? { last: size } : { first: size },\n ),\n )\n continue\n }\n if (known === undefined) continue\n // A wider window than the connection holds asks for the rows it lacks.\n const tail =\n failed || size === undefined ? undefined : missingRows(known, connection.window, size)\n if (tail !== undefined) queries.push(withWindow(connection, tail))\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 visible = visibleStoreOf(remote.entities, remote.optimistic)\n const read = [...asked.requirements, ...items]\n const planned = plan(visible, read, options)\n return {\n requirements: options.force === true ? planned : withoutFailedFields(remote, planned),\n queries,\n expires:\n options.freshness === undefined\n ? null\n : (deadlineOf(visible, read, options.freshness) ?? null),\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 readonly select?: RelationRequirement | undefined\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 ...(query.select === undefined ? {} : { select: query.select }),\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 select?: RelationRequirement | undefined,\n now?: number | undefined,\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 const hasPayload =\n select !== undefined &&\n ((result.entities !== undefined && result.entities.length > 0) ||\n (result.settled !== undefined && result.settled.length > 0))\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 ...(select === undefined || !hasPayload ? {} : { select }),\n ...(hasPayload\n ? {\n entities: [...(result.entities ?? [])],\n settled: [...(result.settled ?? [])],\n now: now ?? 0,\n }\n : {}),\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 = (\n query: {\n readonly identity: string\n readonly window: QueryWindow\n readonly select?: RelationRequirement | undefined\n },\n now: () => number = wallClock,\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, query.select, now())\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 * Under a refreshing policy, when a value the entry holds next ages out and\n * what is due then. Time reaches Remote only as a Message: the entry sleeps\n * until then and emits `RefreshStarted`, which marks the fields stale, and\n * the plan that follows fetches them. A Model that does not change past its\n * `maxAge` is otherwise never looked at again.\n */\n readonly expires: Deadline | null\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 = wallClock } = 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, now), toMessage)\n // A plan is a function of the Remote model, what is asked, and the clock only\n // until the next value ages out (`expires`, which `deadlineOf` computes as\n // exactly that moment), so a Model change the Remote model is not part of\n // (typing in a field) reuses it rather than walking every row again.\n const planned = new WeakMap<\n RemoteModel,\n Map<string, { readonly until: number; readonly dependencies: ReadDependencies }>\n >()\n return {\n dependenciesSchema: Schema.Struct({\n requirements: Schema.Array(ReadRequest),\n queries: Schema.Array(PlannedQuery),\n refresh: Schema.Number,\n expires: Schema.NullOr(Schema.Struct({ at: Schema.Number, due: Schema.Array(ReadRequest) })),\n }),\n modelToDependencies: model => {\n const remote = bound.store.get(model)\n const asked = askedOf(model)\n const askedKey = stableStringify(asked)\n const at = now()\n let byAsked = planned.get(remote)\n const known = byAsked?.get(askedKey)\n if (known !== undefined && at < known.until) return known.dependencies\n const plan = planAsked(remote, asked, RemotePolicy.toPlan(policy, at))\n const dependencies: ReadDependencies = {\n refresh: refreshedAt(\n remote.refresh,\n plan.requirements,\n plan.queries.map(query => query.identity),\n ),\n requirements: plan.requirements,\n queries: plan.queries.map(({ identity, window, select }) => ({\n identity,\n window,\n select,\n })),\n expires: plan.expires,\n }\n if (byAsked === undefined) {\n byAsked = new Map()\n planned.set(remote, byAsked)\n }\n byAsked.set(askedKey, { until: plan.expires?.at ?? Infinity, dependencies })\n return dependencies\n },\n dependenciesToStream: ({ requirements, queries, refresh, expires }) =>\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.merge(\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 // The clock's say, as a Message. Under the Effect clock, so a test\n // can move it; against `now`, so the same clock sets and fires it.\n expires === null\n ? Stream.empty\n : Stream.fromEffect(\n Effect.as(\n Effect.sleep(Math.max(0, expires.at - now())),\n toMessage({ _tag: 'RefreshStarted', requests: expires.due }),\n ),\n ),\n ),\n ),\n }\n}\n\n// Where a restarted stream resumes, not a reason to restart it: every applied\n// event advances the cursor, and a restart per event would close and reopen\n// the server stream each time. Said in the schema rather than with Foldkit's\n// `keepAliveEquivalence`, which would change the entry's public type\n// (`EntryWithoutKeepAlive`, the only entry type Foldkit exports) for every\n// application that spreads Remote's entries into its own.\nconst resumeCursor = Schema.Number.pipe(Schema.overrideToEquivalence(() => () => true))\n\n/** The wait before a stream's restart after `failures` breaks in a row: Sync's transport backoff. */\nconst restartDelay = (options: LiveOptions, failures: number): Duration.Duration => {\n const base = Duration.toMillis(Duration.fromInputUnsafe(options.retryBase ?? '50 millis'))\n const max = Duration.toMillis(Duration.fromInputUnsafe(options.maxRetryDelay ?? '5 seconds'))\n const backoff = Math.min(max, base * 2 ** Math.min(Math.max(failures, 1) - 1, 30))\n return Duration.millis(backoff * (0.8 + Math.random() * 0.4))\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<AppModel, Message, LiveDependencies, RemoteClient> => ({\n dependenciesSchema: Schema.Struct({\n requirements: Schema.Array(ReadRequest),\n cursor: resumeCursor,\n floor: Schema.Number,\n restarts: Schema.Number,\n // Read when a break restarts the stream; an applied event resetting it is no reason to.\n failures: resumeCursor,\n }),\n modelToDependencies: model => {\n const requirements = requirementsOf(model)\n const stream = liveStreamKey(requirements)\n const remote = bound.store.get(model)\n const health = remote.streams[stream]\n return {\n requirements,\n cursor: remote.live[stream]?.cursor ?? 0,\n // A stream is the principal's: `forget` moves the floor, and it restarts.\n floor: remote.refresh.floor,\n restarts: health?.restarts ?? 0,\n failures: health?.failures ?? 0,\n }\n },\n dependenciesToStream: ({ requirements, cursor, restarts, failures }) => {\n if (requirements.length === 0) return Stream.empty\n const stream = liveStreamKey(requirements)\n const live = 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 ?? wallClock)(),\n }),\n ),\n Stream.catchIf(\n (_error): _error is RemoteLiveError | RemoteProtocolError | RemoteUnauthenticated => 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 if (restarts === 0) return live\n // The server replays nothing a stream missed while it was down, so a\n // restart refetches what the stream covers. The gap closes before the\n // resubscribe, so a resubscribe that fails is a break of its own; were the\n // two concurrent, its failure could land on the open gap and be ignored,\n // and the late `GapCleared` would leave the stream stopped.\n return Stream.fromEffect(Effect.sleep(restartDelay(options, failures))).pipe(\n Stream.drain,\n Stream.concat(\n Stream.make(\n toMessage({ _tag: 'RefreshStarted', requests: requirements }),\n toMessage({ _tag: 'GapCleared', stream }),\n ),\n ),\n Stream.concat(live),\n )\n },\n})\n\n/** The projection an active entry has for this Model; none while it is inactive. */\nconst projectionOf = <AppModel>(\n entry: ActiveEntry<AppModel>,\n model: AppModel,\n): Option.Option<Projection<AppModel, unknown>> => {\n if ('projectionOf' in entry) return entry.projectionOf(model)\n // A bare Surface without params reads whole; a source without `instancesOf`\n // cannot happen, and resolves to nothing if it does.\n if ('projection' in entry) return Option.some(entry.projection())\n return Option.none()\n}\n\n/** One of an entry's reads, named for diagnostics: a lone Surface keeps its name, a family instance takes `Child[key]`. */\ninterface NamedProjection<AppModel> {\n readonly name: string\n readonly projection: Projection<AppModel, unknown>\n}\n\n/**\n * Every projection an entry resolves to for a Model: the lone one of a\n * `Surface.at`/`Surface.when` value or a bare Surface, or a family's parent\n * first and then each instance. The parent joins so an unloaded parent is\n * fetched before what it reveals; `Data.satisfy` reaches the instances in a\n * later pass. A caller that also passes the parent separately double-covers\n * its requirements, as overlapping Surfaces already do.\n */\nconst resolvedOf = <AppModel>(\n entry: ActiveEntry<AppModel>,\n model: AppModel,\n): ReadonlyArray<NamedProjection<AppModel>> => {\n const source = entry as Partial<SurfaceSource<AppModel>>\n if (typeof source.instancesOf === 'function') {\n const instances = source.instancesOf(model)\n const from = (entry as { readonly from?: ActiveSurface<AppModel> }).from\n // A lone `Surface.at`/`Surface.when` keeps its name; a family names each\n // instance after its key, with the parent first.\n if (from === undefined)\n return instances.map(instance => ({ name: entry.name, projection: instance.projection }))\n return [\n ...Option.toArray(from.projectionOf(model)).map(projection => ({\n name: from.name,\n projection,\n })),\n ...instances.map(instance => ({\n name: `${entry.name}[${instance.key}]`,\n projection: instance.projection,\n })),\n ]\n }\n return Option.toArray(projectionOf(entry, model)).map(projection => ({\n name: entry.name,\n projection,\n }))\n}\n\n/** What some projections ask for together: their requirements and connections unioned. */\nconst askedUnion = (projections: ReadonlyArray<Projection<any, unknown>>): Asked => ({\n requirements: projections.flatMap(requirementsOf),\n connections: projections.flatMap(connectionsOf),\n})\n\n/**\n * `resolvedOf` computed once per Model: the read, live, and retain entries\n * all derive their dependencies from the same projections 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 memoizedResolved = <AppModel>(\n entry: ActiveEntry<AppModel>,\n): ((model: AppModel) => ReadonlyArray<NamedProjection<AppModel>>) => {\n const cache = new WeakMap<object, ReadonlyArray<NamedProjection<AppModel>>>()\n return model => {\n const key: unknown = model\n if (typeof key !== 'object' || key === null) return resolvedOf(entry, model)\n const known = cache.get(key)\n if (known !== undefined) return known\n const resolved = resolvedOf(entry, model)\n cache.set(key, resolved)\n return resolved\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 * Remote's Messages as one Schema, for a wrapper variant in the\n * application's union: `GotRemoteMessage: { message: Remote.Message }`. With\n * a wrapper, `update` matches the application's union exhaustively and\n * `Remote.fold` reduces what arrives inside it.\n */\n Message: defineMessageUnion(remoteMessageCases),\n /**\n * A bound domain under one wrapper variant of the application's union, the\n * same shape Foldkit gives a Submodel: `toParentMessage` wraps Remote's\n * Messages, the fold reduces them, and its `fetch`, `mutate`, and\n * `subscriptions` yield the wrapper. Spreading `Remote.messages` and\n * narrowing with `Remote.reduces` remains the shorter path for an\n * application whose `update` only reduces.\n *\n * @example\n * ```ts\n * const Message = defineMessageUnion({ GotRemoteMessage: { message: Remote.Message } })\n * const foldData = Remote.fold(Data, message => Message.GotRemoteMessage({ message }))\n *\n * const update = (model: Model, message: Message): Return =>\n * Message.match(message, {\n * GotRemoteMessage: ({ message }) => foldData(model, message),\n * })\n * const subscriptions = Subscription.make<Model, Message, RemoteClient>()(() =>\n * foldData.subscriptions({ page: Surface.at(ProjectPage, …) }),\n * )\n * ```\n */\n fold: <Domain extends RemoteDomain<any, any, any, any, any>, ParentMessage>(\n domain: Domain,\n toParentMessage: (message: RemoteMessage) => ParentMessage,\n ): RemoteFold<ModelOfDomain<Domain>, ParentMessage, Domain> => {\n type AppModel = ModelOfDomain<Domain>\n const fold = (model: AppModel, message: RemoteMessage | RemoteMessageInput) => ({\n model: domain.reduce(model, message),\n })\n return Object.assign(fold, {\n mutate: (...args: Parameters<Domain['mutate']>) => {\n const started = domain.mutate(\n ...(args as Parameters<RemoteDomain<AppModel, any, any, any, any>['mutate']>),\n )\n return { ...started, command: mapMessage(started.command, toParentMessage) }\n },\n preload: (...args: Parameters<Domain['preload']>) =>\n mapMessage(\n domain.preload(\n ...(args as Parameters<RemoteDomain<AppModel, any, any, any, any>['preload']>),\n ),\n toParentMessage,\n ),\n subscriptions: (\n active: Readonly<Record<string, ActiveEntry<AppModel>>>,\n options?: SubscriptionsOptions,\n ) =>\n markAll(\n messagesAs(brandEntries(domain.subscriptions(active, options)), toParentMessage),\n ) as never,\n })\n },\n\n /**\n * A patch of one entity's values, for a mutation's `optimistic` list or an\n * overlay. Takes a `foldkit-entity` Entity or a Remote descriptor alike, so\n * the domain you declared once is the one you patch:\n * `Remote.patch(Project, 'p1', { name: 'Apollo II' })`. Values are the\n * fields' wire shape, as the server writes them; a relation is its ref key\n * (`'User:u1'`).\n */\n patch: <E extends EntityLike>(\n entity: E,\n id: string,\n values: Partial<Schema.Struct.Encoded<FieldsOf<E>>>,\n ): EntityPatch<NameOf<E>, FieldsOf<E>> =>\n descriptorOf(entity).patch(id, values) as EntityPatch<NameOf<E>, FieldsOf<E>>,\n\n /**\n * A reference to one entity, for `ConnectionChange` and anything else that\n * names a row: `Remote.ref(Project, 'p3')`. Either kind of entity, as with\n * `Remote.patch`.\n */\n ref: <E extends EntityLike>(entity: E, id: string): EntityRef<NameOf<E>, FieldsOf<E>> =>\n descriptorOf(entity).ref(id) as EntityRef<NameOf<E>, FieldsOf<E>>,\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 /**\n * Places what the server said (a mutation's answer, a read, a live\n * patch) as usual, and also fetches each list it placed in, comparing the\n * server's first page with the order it placed: a disagreement is kept in\n * `placementMismatches` (`Data.inspect`). A pending edit is not checked,\n * since the server does not have it yet. For development and tests, where\n * a collation that drifts should be found.\n */\n readonly verifyPlacement?: boolean | undefined\n }): RemoteDomain<AppModel, Store, Entities, Queries, Mutations> =>\n bindDomain(defineRemote(config), config.model, { verifyPlacement: config.verifyPlacement }),\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 * The resume part for this domain, for `foldkit-ssr`'s `SSR.plan({ parts })`:\n * a server render sends what the plan's active Surfaces read from the store,\n * each connection with its boundaries and each live cursor with it, and\n * nothing else. `id` tells two domains in one application apart.\n */\n resume: resumePart,\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 const relationKey = stableStringify(relation)\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 `${key}\\u0000${relationKey}`,\n () => {\n if (isTombstone(store, key)) return { _tag: 'NotFound' }\n const assembled = assemble(store, key, relation)\n if (assembled === undefined) return unavailableFailure(store, key, relation)\n const decoded = decodeRow(selection.schema, store[key]!.values, 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 (isLoadingThrough(remote, selection.entity, id, relation)) return { _tag: 'Loading' }\n if (failure !== undefined) return { _tag: 'Failed', error: failure }\n // A preview of something the server has not seen: what the overlay\n // leaves out will never arrive, so waiting would be `Initial` for good.\n if (onlyOverlaid(remote, selection.entity, id)) {\n const lacking = missingFields(store, key, relation.fields)\n return {\n _tag: 'Failed',\n error: {\n _tag: 'Overlaid',\n message: `${selection.entity} ${id} is shown only by an overlay, which does not hold ${\n lacking.length === 0 ? 'what its relations select' : lacking.join(', ')\n }; the server has not seen it, so nothing will fetch them.`,\n },\n }\n }\n // Nothing is fetching this: no active Surface observes it, which is\n // usually a wiring mistake.\n return { _tag: 'Initial' }\n },\n })\n },\n\n /**\n * When what a projection shows was last received, and whether it is stale\n * or loading. Pure, so a view can show \"updated 5s ago\" without I/O.\n *\n * `updatedAt` is the newest server write among what is shown, as the\n * store dates it; `undefined` when nothing shown was received (nothing\n * loaded, or only an optimistic preview). `stale` is any shown field or\n * connection marked stale; `loading` is any of them in flight. Optimistic\n * previews do not date: showing only one reads `updatedAt: undefined`.\n */\n meta: <AppModel, Store extends RemoteModel, Value>(\n bound: BoundRemote<AppModel, Store>,\n model: AppModel,\n projection: Projection<AppModel, Value>,\n ): ReadMeta => metaOf(bound.store.get(model), askedOf(projection)),\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 = wallClock } = 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 * Forgets everything the server told this Model: values, tombstones,\n * unavailable fields, connections, live cursors, failures. What is known is\n * known for a principal, and this is the one boundary for a login, a logout\n * or a switch of organization: called from `update`, it performs no I/O, and\n * every active Surface's read and live entries restart, so the screen asks\n * again as whoever the client now is. A read or stream begun before is\n * interrupted rather than landing after. A mutation in flight is treated as\n * applied: its answer writes nothing here.\n */\n forget: <AppModel, Store extends RemoteModel>(\n bound: BoundRemote<AppModel, Store>,\n model: AppModel,\n ): AppModel => bound.store.set(model, forgetRemote(bound.store.get(model)) as Store),\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. The client `RpcClient.make`\n * builds is accepted as it is: when its transport fails (`RpcClientError`),\n * the call fails with its own Remote error, which the application shows and\n * retries like any failed read, query, mutation or live stream.\n */\n /**\n * Remote's client over any way of sending one JSON request and receiving its\n * answer, for `clientLayer`: a worker, a server in the page. `RemoteServer.answer`\n * is the other end.\n */\n json: jsonClient,\n\n /**\n * Remote's client over HTTP, for `clientLayer`: each call a `POST` of the JSON\n * request to `url`. `headers` is read per request (a session token, say).\n */\n http: httpClient,\n\n /**\n * Remote's client over HTTP with live, for `clientLayer`: reads, queries,\n * and mutations as `http` sends them, live requirements as one `POST`\n * answered with a `text/event-stream` of changes.\n * `foldkit-remote-server/fetch` is the other end.\n */\n httpWithLive: httpWithLiveClient,\n\n clientLayer: <R = never>(\n client: RemoteRpcClient<R, RpcClientError.RpcClientError>,\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 =>\n client.FoldkitRemoteRead(batch).pipe(\n Effect.catchTag('RpcClientError', error =>\n Effect.fail(new RemoteReadError({ message: error.message })),\n ),\n Effect.provideContext(context),\n ),\n query: request =>\n client.FoldkitRemoteQuery(request).pipe(\n Effect.catchTag('RpcClientError', error =>\n Effect.fail(new RemoteQueryError({ message: error.message })),\n ),\n Effect.provideContext(context),\n ),\n mutate: request =>\n client.FoldkitRemoteMutate(request).pipe(\n Effect.catchTag('RpcClientError', error =>\n Effect.fail(new RemoteMutationError({ message: error.message })),\n ),\n Effect.provideContext(context),\n ),\n live: ({ requirements, after }) =>\n client\n .FoldkitRemoteLive({ version: REMOTE_PROTOCOL_VERSION, requirements, after })\n .pipe(\n Stream.catchTag('RpcClientError', error =>\n Stream.fail(new RemoteLiveError({ message: error.message })),\n ),\n Stream.map(liveEventOf),\n Stream.provideContext(context),\n ),\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 * With `select`, the server also returns the selected fields of the page's\n * items, so one response populates both the connection and the store.\n */\n query: Effect.fn('Remote.query')(function* <Name extends string, Input>(\n ref: QueryRef<Name, Input>,\n select?: RelationRequirement | undefined,\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({\n query: ref.query,\n input,\n window: ref.window,\n ...(select === undefined ? {} : { select }),\n })\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 select?: RelationRequirement | undefined,\n now?: number | undefined,\n ): RemoteMessage => pageMessage(ref.identity, result, false, ref.window, select, now),\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 now: (options.now ?? wallClock)(),\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, and restarts the entry after a\n * backoff; the restart refetches what it covers. 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<AppModel, Message, LiveDependencies, 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.\n/**\n * Each entry with its Messages as the parent's and its dependencies as they\n * were. The Model is the parent's already, and `Subscription.lift` would wrap\n * every entry's dependencies in `maybeDependencies` (since Foldkit 0.166).\n */\nconst messagesAs = <AppModel, ParentMessage>(\n entries: Subscription.Subscriptions<AppModel, RemoteMessage, RemoteClient>,\n toParentMessage: (message: RemoteMessage) => ParentMessage,\n) =>\n Record.map(entries, entry => ({\n ...entry,\n dependenciesToStream: (dependencies: unknown, read: () => unknown) =>\n Stream.map(entry.dependenciesToStream(dependencies, read), toParentMessage),\n }))\n\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/** Why a read failed, in words: Remote's own failures say what to do, and a server's error says itself. */\nconst failedReadWords = (error: RemoteError): string => {\n // tag-check: open — a server names its own errors; only these three are Remote's.\n switch (error._tag) {\n case 'DecodeError':\n return `What the server sent does not decode against the Selection: ${error.message}`\n case 'Unavailable':\n return `${error.message} Select without it, or Data.refresh asks again.`\n case 'Overlaid':\n return `${error.message} Overlay every field the Selection reads, or select fewer.`\n default:\n return `Its request failed: ${error.message}. Nothing retries a failed read on its own; Data.refresh asks again.`\n }\n}\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 options: { readonly verifyPlacement?: boolean | undefined } = {},\n): RemoteDomain<AppModel, Store, Entities, Queries, Mutations> => {\n const bound = bindRemote(definition, store)\n // Every reader any `subscriptions` call names, and every connection one keeps:\n // retention is the domain's, so each call's retain entry roots them all, and\n // one call with its own policy does not collect what another call reads.\n const readers = new Map<\n ActiveEntry<AppModel>,\n (model: AppModel) => ReadonlyArray<NamedProjection<AppModel>>\n >()\n const keptConnections = new Set<string>()\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._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 const remote = store.get(model)\n const reduced = updateRemote(remote, resolved as RemoteMessage)\n const answer =\n message._tag === 'MutationSucceeded'\n ? (message as Extract<RemoteMessage, { _tag: 'MutationSucceeded' }>)\n : undefined\n // A repeated answer finds every value it carries already held, so it\n // changes nothing and invalidates nothing.\n const next =\n answer === undefined\n ? placedNews(reduced, newsOf(message), remote.entities)\n : impactOf(reduced, answer, remote.entities)\n return next === remote ? model : store.set(model, next as Store)\n }\n\n /** The registered query a connection identity names, and its encoded input. */\n const queryOf = (\n identity: string,\n ): Option.Option<Pick<HeldConnection, 'descriptor' | 'encoded' | 'filtered'>> => {\n const separator = identity.indexOf(IDENTITY_SEPARATOR)\n const descriptor = definition.registry.queries.get(identity.slice(0, separator))\n if (descriptor === undefined) return Option.none()\n const encoded = JSON.parse(identity.slice(separator + 1)) as Record<string, unknown>\n const over = descriptor.body?.entity.name\n const filtered = (over === undefined ? undefined : definition.registry.filtered.get(over)) ?? []\n return Option.some({ descriptor, encoded, filtered })\n }\n\n /**\n * `pages` with each change to a row they hold placed, judged against\n * `store`: a row that moved goes where the body's order puts it, and one\n * that stopped matching leaves. A row a change brings in is not added,\n * since what the list selects of it may not be loaded, and a change the\n * client cannot place leaves the row where it is.\n */\n const placedHeld = (\n identity: string,\n pages: Connection,\n changes: ReadonlyArray<EntityChange>,\n store: EntityStore,\n ): Connection => {\n const query = queryOf(identity)\n if (Option.isNone(query)) return pages\n // Built once: each change is of a row of its own, judged against the store\n // as every change left it, so what the list held before them all is enough.\n const holds = new Set(items(pages).map(edge => entityKey(edge.ref.entity, edge.ref.id)))\n let placed = pages\n for (const change of changes) {\n if (!holds.has(entityKey(change.entity, change.id))) continue\n placed = Impact.$match(\n impactOn({ ...query.value, connection: placed, holds }, store, change),\n {\n Kept: () => placed,\n Placed: ({ connection }) => connection,\n Invalidated: () => placed,\n },\n )\n }\n return placed\n }\n\n /**\n * A loaded list with the pending layers placed in its pages, so a row a\n * pending edit moves, or takes out of the list, shows where its answer\n * will be placed until the edit settles.\n */\n const pendingPlaced = (remote: RemoteModel, identity: string, pages: Connection): Connection => {\n const { layers } = remote.optimistic\n if (layers.length === 0) return pages\n return memoRead([pages, layers, remote.entities], `placed:${identity}`, () =>\n placedHeld(\n identity,\n pages,\n changesOf({ entities: layers.flatMap(layer => layer.patches) }, remote.entities),\n visibleStoreOf(remote.entities, remote.optimistic),\n ),\n )\n }\n\n /**\n * The edges a loaded list shows: its pages with pending edits placed, and\n * each row an insert overlay shows (a pending create, a confirmed or a live\n * insert) where the body's order puts it, or left out when it sorts past\n * what is loaded. An overlay says a row is in the list; in a list the\n * client can place, the order says where. A row it cannot place stays at\n * the end its overlay names.\n */\n const shownEdges = (\n remote: RemoteModel,\n identity: string,\n connection: Connection,\n ): ReadonlyArray<Edge> => {\n const pages = pendingPlaced(remote, identity, connection)\n const inserts = remote.optimistic.overlays.some(\n overlay => overlay.connection === identity && overlay.position !== 'remove',\n )\n const shown = inserts\n ? insertsPlaced(remote, identity, pages)\n : { pages, overlays: remote.optimistic.overlays }\n return visibleItems(shown.pages, identity, shown.overlays, remote.entities)\n }\n\n const insertsPlaced = (\n remote: RemoteModel,\n identity: string,\n pages: Connection,\n ): { readonly pages: Connection; readonly overlays: ReadonlyArray<ConnectionOverlay> } => {\n const { overlays } = remote.optimistic\n const store = visibleStoreOf(remote.entities, remote.optimistic)\n return memoRead([pages, overlays, store], `inserted:${identity}`, () => {\n const query = queryOf(identity)\n const body = Option.isSome(query) ? query.value.descriptor.body : undefined\n if (Option.isNone(query) || body === undefined) return { pages, overlays }\n // A row a later remove hides is placed too: `visibleItems` hides it\n // wherever it is.\n const inserted = new Map<string, Edge>()\n for (const overlay of overlays) {\n if (overlay.connection !== identity || overlay.position === 'remove') continue\n for (const edge of overlay.edges) inserted.set(edge.key, edge)\n }\n const held = new Set(items(pages).map(edge => edge.key))\n let placed = pages\n const outside: Array<Edge> = []\n for (const edge of inserted.values()) {\n if (held.has(edge.key)) continue\n const key = entityKey(edge.ref.entity, edge.ref.id)\n RowPlace.$match(placeIn(store, placed, body, query.value.encoded, key), {\n Before: place => void (placed = withEdge(placed, edge, place)),\n End: place => void (placed = withEdge(placed, edge, place)),\n Outside: () => void outside.push(edge),\n Unknown: () => undefined,\n })\n }\n return {\n pages: placed,\n overlays:\n outside.length === 0\n ? overlays\n : [\n ...overlays,\n { id: 'placed:outside', connection: identity, edges: outside, position: 'remove' },\n ],\n }\n })\n }\n\n /**\n * The loaded lists with what the server said of rows they hold placed: a\n * read or a live patch that changes a held row's ordering or filtered field\n * moves it, or takes it out, as a mutation's answer does. A list it cannot\n * place stands as it is, as a read is no write: its own refetch or live\n * stream says otherwise. Only a value the client held before counts, so a\n * row's first read judges nothing.\n */\n const placedNews = (\n remote: RemoteModel,\n news: ReadonlyArray<NormalizedPatch>,\n before: EntityStore,\n ): RemoteModel => {\n if (news.length === 0) return remote\n const held = news.map(patch => {\n const values = before[entityKey(patch.entity, patch.id)]?.values ?? {}\n return {\n ...patch,\n values: Object.fromEntries(\n Object.entries(patch.values).filter(([field]) => Object.hasOwn(values, field)),\n ),\n }\n })\n const changes = changesOf({ entities: held }, before)\n if (changes.length === 0) return remote\n const placed: Record<string, Connection> = {}\n for (const [identity, pages] of Object.entries(remote.connections)) {\n const after = placedHeld(identity, pages, changes, remote.entities)\n if (after !== pages) placed[identity] = after\n }\n return withPlacements(remote, placed, [])\n }\n\n /** The rows a read or a live patch says the server holds now. */\n const newsOf = (message: RemoteMessage | RemoteMessageInput): ReadonlyArray<NormalizedPatch> => {\n if (message._tag === 'ReadReceived') return message.result.entities\n if (message._tag !== 'LiveReceived') return []\n const event = message.event as LiveEvent\n if (event._tag !== 'EntityPatched') return []\n return [{ entity: event.ref.entity, id: event.ref.id, values: event.values }]\n }\n\n /**\n * The loaded connections as a write left them: each judged by its body\n * against the store as the write left it, a change it can place placed in\n * its pages, and one it cannot invalidated for its read entry to fetch.\n */\n const impactOf = (\n remote: RemoteModel,\n answer: Extract<RemoteMessage, { readonly _tag: 'MutationSucceeded' }>,\n // The store before the answer, to tell a value it changed from one it repeated.\n before: EntityStore,\n ): RemoteModel => {\n const changes = changesOf(answer, before)\n if (changes.length === 0) return remote\n // A row the answer itself put in or took out of a list is where the server\n // says; every other change to that list's rows is judged as anywhere.\n const named = new Map<string, Set<string>>()\n for (const change of answer.connections ?? []) {\n const keys = named.get(change.connection) ?? new Set<string>()\n keys.add(change.edge.key)\n named.set(change.connection, keys)\n }\n const visible = visibleStoreOf(remote.entities, remote.optimistic)\n const placed: Record<string, Connection> = {}\n const invalidated: Array<string> = []\n for (const identity of Object.keys(remote.connections)) {\n const answered = named.get(identity)\n const judged =\n answered === undefined\n ? changes\n : changes.filter(change => !answered.has(entityKey(change.entity, change.id)))\n if (judged.length === 0) continue\n const query = queryOf(identity)\n if (Option.isNone(query)) continue\n const original = remote.connections[identity]!\n // Each change is judged against the pages the one before it left. What the\n // list holds is read once: a change is of a row of its own, judged against\n // the store as the whole answer left it.\n const holds = new Set(\n visibleItems(original, identity, remote.optimistic.overlays, remote.entities).map(edge =>\n entityKey(edge.ref.entity, edge.ref.id),\n ),\n )\n let pages = original\n let invalid = false\n for (const change of judged) {\n const held: HeldConnection = { ...query.value, connection: pages, holds }\n const after = Impact.$match(impactOn(held, visible, change), {\n Kept: () => Option.some(pages),\n Placed: ({ connection }) => Option.some(connection),\n Invalidated: () => Option.none<Connection>(),\n })\n if (Option.isNone(after)) {\n invalid = true\n break\n }\n pages = after.value\n }\n if (invalid) invalidated.push(identity)\n else if (pages !== original) placed[identity] = pages\n }\n return withPlacements(remote, placed, invalidated)\n }\n\n /**\n * The lists placed and invalidated. Under `verifyPlacement`, each placed\n * list is fetched too, and the order it was placed in kept to compare with\n * the server's page.\n */\n const withPlacements = (\n remote: RemoteModel,\n placed: Readonly<Record<string, Connection>>,\n invalidated: ReadonlyArray<string>,\n ): RemoteModel => {\n const identities = Object.keys(placed)\n if (identities.length === 0) return invalidateConnections(remote, invalidated)\n const withPlaced = { ...remote, connections: { ...remote.connections, ...placed } }\n if (options.verifyPlacement !== true) return invalidateConnections(withPlaced, invalidated)\n const firstPage = (connection: Connection | undefined) =>\n (connection?.segments[0]?.edges ?? []).map(edge => edge.key)\n const orders = Object.fromEntries(\n identities.map(identity => {\n const order = firstPage(placed[identity])\n const kept = new Set(order)\n return [\n identity,\n {\n order,\n dropped: firstPage(remote.connections[identity]).filter(key => !kept.has(key)),\n },\n ]\n }),\n )\n return invalidateConnections({ ...withPlaced, placed: { ...remote.placed, ...orders } }, [\n ...invalidated,\n ...identities,\n ])\n }\n // Two applications can have the same Model type; the owner token tells them apart.\n const assertOwned = (entry: ActiveEntry<AppModel>) => {\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 from = (entry as { readonly from?: ActiveSurface<AppModel> }).from\n if (\n from !== undefined &&\n bound.contract.owner !== undefined &&\n from.owner !== bound.contract.owner\n ) {\n throw new Error(\n `Remote: Surface \"${from.name}\" belongs to another application than domain \"${bound.contract.name}\"`,\n )\n }\n }\n /**\n * `prefetch` and `satisfy`, each Message they reduce also kept in `heard`,\n * so `preload` can hand them to the Model as it is by the time they land.\n */\n const prefetchInto = (\n model: AppModel,\n projection: Projection<AppModel, unknown>,\n options: ObserveOptions,\n heard: Array<RemoteMessage>,\n ) => {\n const hear = (current: AppModel, message: RemoteMessage): AppModel => {\n heard.push(message)\n return reduce(current, message)\n }\n return Effect.gen(function* () {\n const { policy = RemotePolicy.cacheFirst, now = wallClock } = 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. A\n // page with a payload already writes its items' selected fields, so\n // the read below is only for what the server left out.\n for (const query of planAsked(store.get(current), askedOf(projection), planOptions).queries) {\n const page = yield* queryRequestOf(query).pipe(\n Effect.flatMap(request => client.query(request)),\n )\n current = hear(\n current,\n pageMessage(query.identity, page, true, query.window, query.select, now()),\n )\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 hear(current, { _tag: 'ReadReceived', requests: requirements, result, now: at })\n })\n }\n const satisfyInto = (\n model: AppModel,\n active: Readonly<Record<string, ActiveEntry<AppModel>>>,\n options: SatisfyOptions,\n heard: Array<RemoteMessage>,\n ) =>\n Effect.gen(function* () {\n const { passes = 8, now = wallClock } = options\n const entries = Object.values(active)\n entries.forEach(assertOwned)\n const planOptions = RemotePolicy.toPlan(RemotePolicy.cacheFirst, now())\n const plans = (\n current: AppModel,\n projections: ReadonlyArray<Projection<AppModel, unknown>>,\n ) => {\n const planned = planAsked(store.get(current), askedUnion(projections), planOptions)\n return planned.queries.length > 0 || planned.requirements.length > 0\n }\n let current = model\n for (let pass = 0; pass < passes; pass++) {\n if (\n !entries.some(entry =>\n plans(\n current,\n resolvedOf(entry, current).map(({ projection }) => projection),\n ),\n )\n )\n return current\n for (const entry of entries) {\n // Asked again over the Model the Surface before it left. A family\n // resolves its parent first: a pass fetches the parent, and the\n // instances the parent reveals are read in a later pass.\n for (const { projection } of resolvedOf(entry, current))\n current = yield* prefetchInto(current, projection, { now }, heard)\n }\n }\n const reading = entries.flatMap(entry =>\n resolvedOf(entry, current).filter(({ projection }) => plans(current, [projection])),\n )\n if (reading.length === 0) return current\n return yield* new RemoteUnsatisfied({\n surfaces: reading.map(({ name }) => name),\n passes,\n })\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 active: (name, projectionOf) => {\n const { owner } = bound.contract\n if (owner === undefined)\n throw new Error(\n `Remote: \"${name}\" reads domain \"${bound.contract.name}\", whose Model field is a raw optic that names no application; make the domain from an application's field (App.model.remote) to give it reads`,\n )\n return { name, owner, messages: [], projectionOf }\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 // Checked before any reader joins the domain, so a refused call adds none.\n for (const entry of Object.values(active)) assertOwned(entry)\n for (const [key, entry] of Object.entries(active)) {\n const resolvedAt = readers.get(entry) ?? memoizedResolved(entry)\n readers.set(entry, resolvedAt)\n const asked = (model: AppModel) =>\n askedUnion(resolvedAt(model).map(({ projection }) => projection))\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 for (const identity of options.connections ?? [])\n keptConnections.add(connectionIdentity(identity))\n entries.retain = {\n dependenciesSchema: retentionRootsSchema,\n modelToDependencies: model =>\n rootsOf(\n [...readers.values()].flatMap(resolvedAt =>\n resolvedAt(model).map(({ projection }) => projection),\n ),\n { connections: [...keptConnections] },\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 markAll(entries)\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 meta: (model, projection) => Remote.meta(bound, model, projection),\n storeOf: model => storeOf(bound, model),\n confirmed: projection => confirmed(bound, projection),\n prefetch: (model, projection, options = {}) => prefetchInto(model, projection, options, []),\n satisfy: (model, active, options = {}) => satisfyInto(model, active, options, []),\n preload: (model, active, options = {}) => {\n // A Surface of another application is a mistake in `update`, refused there.\n Object.values(active).forEach(assertOwned)\n return {\n name: 'Remote.preload',\n args: { active: Object.keys(active).join(', ') },\n effect: Effect.suspend(() => {\n const heard: Array<RemoteMessage> = []\n // Speculative: however the read ends, defects included, what it\n // heard is all it hands on, and the destination reads the rest.\n return satisfyInto(model, active, options, heard).pipe(\n Effect.exit,\n Effect.map((): RemoteMessage => ({ _tag: 'Preloaded', messages: heard })),\n )\n }),\n }\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, relation, requirement } = placeableReadContract(\n readContract(query.ref(input), select, window),\n query.body,\n )\n const relationKey = stableStringify(relation)\n // A read shows at most its window, whatever else loaded the connection:\n // a picker's `first: 50` and a Block's `first: 3` of one query share it.\n const sizeOf = (remote: RemoteModel) => windowSize(remote, ref)\n const shown = (remote: RemoteModel, connection: Connection) =>\n cutToWindow(shownEdges(remote, ref.identity, connection), ref.window, sizeOf(remote))\n // The first failed field among the rows a list shows, if any. Decided\n // outside the memo, which is keyed on what the rows are read from: a\n // failure can arrive without any of it 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 shown(remote, connection).edges) {\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 shown(remote, connection).edges) {\n if (edge.ref.entity !== relation.entity) continue\n if (isLoadingThrough(remote, edge.ref.entity, edge.ref.id, relation)) {\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, connection, remote.optimistic.overlays],\n `${ref.identity}\\u0000${relationKey}\\u0000${String(sizeOf(remote))}`,\n () => {\n const items: Value[] = []\n let refreshing = connection.stale\n const { edges, cutBefore, cutAfter } = shown(remote, connection)\n for (const edge of edges) {\n const key = entityKey(edge.ref.entity, edge.ref.id)\n const assembled = assemble(visible, key, relation)\n if (assembled === undefined) return unavailableFailure(visible, key, relation)\n const decoded = decodeRow(select.schema, visible[key]!.values, 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: cutAfter || hasNext(connection),\n hasPrevious: cutBefore || hasPrevious(connection),\n }\n return refreshing ? { _tag: 'Refreshing', value: page } : { _tag: 'Ready', value: page }\n },\n )\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 case 'Initial':\n case 'Loading':\n case 'NotFound':\n return { _tag: 'Failed', error: failure }\n }\n },\n }\n },\n more: (model, projection) => {\n const remote = store.get(model)\n const { ref } = projection\n const size = windowSize(remote, ref)\n const page = ref.window.first ?? ref.window.last\n if (size === undefined || page === undefined || page === 0) return Option.none()\n const read = projection.read(model)\n const beyond =\n (read._tag === 'Ready' || read._tag === 'Refreshing') &&\n (ref.window.first === undefined ? read.value.hasPrevious : read.value.hasNext)\n return beyond\n ? Option.some(\n bound.store.set(\n model,\n updateRemote(remote, {\n _tag: 'WindowGrown',\n window: windowGrowthKey(ref.identity, stableStringify(ref.window)),\n size: size + page,\n }) as Store,\n ),\n )\n : Option.none()\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. A family names\n // each reading instance (`Grid[all]`), not just the Surface.\n const reading = Object.values(options?.surfaces ?? {}).flatMap(source => {\n const matched = resolvedOf(source, model).filter(({ projection: shown }) =>\n connectionsOf(shown).some(connection => connection.identity === ref.identity),\n )\n // An inactive Surface reads nothing, which is not the same as reading\n // something else.\n if (matched.length === 0) return []\n return [{ source, names: matched.map(({ name }) => name) }]\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 : {\n body: Relational.show(body),\n dependencies: explainedDependencies(Relational.dependencies(body)),\n }),\n state: projection.read(model)._tag,\n ...(options?.surfaces === undefined\n ? {}\n : {\n surfaces: reading.flatMap(read => read.names),\n activation: reading.flatMap(read => {\n const activation = 'activation' in read.source ? read.source.activation : undefined\n return activation === undefined\n ? []\n : [{ surface: read.source.name, ...activation }]\n }),\n }),\n }\n },\n why: (model, projection, options) => {\n const state = projection.read(model)\n const asked = askedOf(projection)\n const reading =\n options?.surfaces === undefined\n ? undefined\n : Object.values(options.surfaces).flatMap(source =>\n resolvedOf(source, model)\n .filter(({ projection: shown }) => covers(askedOf(shown), asked))\n .map(({ name }) => name),\n )\n const withSurfaces = reading === undefined ? {} : { surfaces: reading }\n switch (state._tag) {\n case 'Ready':\n return { state: state._tag, message: 'Everything it selects is here.', ...withSurfaces }\n case 'Refreshing':\n return {\n state: state._tag,\n message: 'It is shown while a newer value is fetched.',\n ...withSurfaces,\n }\n case 'Loading':\n return { state: state._tag, message: 'A request for it is in flight.', ...withSurfaces }\n case 'NotFound':\n return {\n state: state._tag,\n message:\n 'The server answered without it: it does not exist, or this principal may not see it.',\n ...withSurfaces,\n }\n case 'Failed':\n return {\n state: state._tag,\n message: failedReadWords(state.error),\n ...withSurfaces,\n }\n case 'Initial':\n if (reading === undefined) {\n return {\n state: state._tag,\n reason: 'Unknown',\n message:\n 'Nothing is fetching it. Pass the active record you give Data.subscriptions as `surfaces` to tell whether an active Surface reads it.',\n }\n }\n return reading.length === 0\n ? {\n state: state._tag,\n reason: 'NotObserved',\n message:\n 'No active Surface reads it, so nothing fetches it. Include it in a Surface that is active for this Model, in the record given to Data.subscriptions.',\n surfaces: reading,\n }\n : {\n state: state._tag,\n reason: 'NotFetching',\n message: `${reading.join(', ')} ${reading.length === 1 ? 'reads it and is' : 'read it and are'} active, yet nothing is fetching it. Remote's Subscriptions are most likely not installed: give the runtime Data.subscriptions (or Data.wiring) and a RemoteClient.`,\n surfaces: reading,\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 ? [] : shownEdges(remote, over.ref.identity, connection)\n const among = edges.map(edge => entityKey(edge.ref.entity, edge.ref.id))\n let judged: Judged\n try {\n judged = matching(visible, by, input, { among })\n } catch (error) {\n // An input the reference interpreter refuses (a search holding NUL) is\n // one the server refuses too: nothing here can be said about the list.\n // Thrown on, it would end the `update` that asked.\n if (error instanceof QueryEvaluateError) return { items: [], complete: false }\n throw error\n }\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 = decodeRow(over.selection.schema, visible[key]!.values, 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. `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 forget: model => Remote.forget(bound, model),\n overlay: (model, id, optimistic) => reduce(model, { _tag: 'OverlayShown', id, optimistic }),\n lift: (model, id) => reduce(model, { _tag: 'OverlayLifted', id }),\n overlays: model => overlaysOf(store.get(model)),\n visibleItems: (remote, connection) => {\n const identity = connectionIdentity(connection)\n return shownEdges(remote, identity, remote.connections[identity] ?? emptyConnection)\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 // A declared write shows what it writes until the server answers; one given wins.\n const optimistic =\n typeof options.optimistic === 'function'\n ? options.optimistic({ requestId, tempId })\n : (options.optimistic ??\n (mutation.write === undefined\n ? undefined\n : optimisticOfWrite(mutation.write, input, options.keys)))\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, options.keys).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 now: (options.now ?? wallClock)(),\n }),\n }),\n ),\n },\n }\n },\n mutation: (model, requestId) => mutationStatus(store.get(model).mutations, requestId),\n refusal: (model, requestId, mutation) => {\n const status = mutationStatus(store.get(model).mutations, requestId)\n if (status._tag !== 'Failed') return Option.none()\n const { refusal } = status.error\n return refusal === undefined\n ? Option.none()\n : Schema.decodeUnknownOption(mutation.Refusal)(refusal)\n },\n liveStatus: (model, active) => {\n assertOwned(active)\n const resolvedAt = readers.get(active) ?? memoizedResolved(active)\n const requirements = askedUnion(\n resolvedAt(model).map(({ projection }) => projection),\n ).requirements.filter(requirement => requirement.live === true)\n if (requirements.length === 0) return { _tag: 'Idle' }\n const remote = store.get(model)\n const stream = liveStreamKey(requirements)\n const health = remote.streams[stream]\n return health === undefined || !remote.gaps.has(stream)\n ? { _tag: 'Live' }\n : { _tag: 'Reconnecting', attempt: health.failures, error: health.error }\n },\n reduce,\n inspect: model => inspectRemote(store.get(model)),\n persistence: options => {\n const connections = (options.connections ?? []).map(connectionIdentity)\n const snapshotOf =\n options.snapshot ??\n ((remote: RemoteModel) => RemotePersistence.snapshotOf(remote, { connections }))\n const debounce = options.debounce ?? '250 millis'\n // The snapshot text is derived on every Model change; it changes only with\n // the store, the connections and the scope, so it is kept by them.\n let last: {\n readonly entities: EntityStore\n readonly connections: RemoteModel['connections']\n readonly scope: string\n readonly text: Option.Option<string>\n } = { entities: emptyStore, connections: {}, scope: '', text: Option.none() }\n const textOf = (remote: RemoteModel, scope: string): Option.Option<string> => {\n if (\n last.entities !== remote.entities ||\n last.connections !== remote.connections ||\n last.scope !== scope\n ) {\n last = {\n entities: remote.entities,\n connections: remote.connections,\n scope,\n text: Option.fromUndefinedOr(\n RemotePersistence.dehydrate(snapshotOf(remote), {\n scope,\n maxBytes: options.maxBytes,\n }),\n ),\n }\n }\n return last.text\n }\n const restore: EntryWithoutKeepAlive<\n AppModel,\n RemoteMessage,\n { readonly key: string; readonly scope: string },\n KeyValueStore.KeyValueStore\n > = {\n dependenciesSchema: Schema.Struct({ key: Schema.String, scope: Schema.String }),\n modelToDependencies: model => ({ key: options.key(model), scope: options.scope(model) }),\n // A store that cannot be read restores nothing, so nothing is saved\n // under this key: an unread snapshot is never written over.\n dependenciesToStream: ({ key, scope }) =>\n Stream.fromEffect(\n RemotePersistence.restore({ key, scope, maxBytes: options.maxBytes }).pipe(\n Effect.option,\n ),\n ).pipe(\n Stream.flatMap(read =>\n Option.match(read, {\n onNone: (): Stream.Stream<RemoteMessage> => Stream.empty,\n onSome: (snapshot): Stream.Stream<RemoteMessage> =>\n Stream.make({\n _tag: 'Hydrated',\n entities: snapshot.entities,\n connections: snapshot.connections,\n merge: 'preserve-existing',\n from: key,\n }),\n }),\n ),\n ),\n }\n const save: EntryWithoutKeepAlive<\n AppModel,\n RemoteMessage,\n { readonly key: string; readonly restored: boolean; readonly text: Option.Option<string> },\n KeyValueStore.KeyValueStore\n > = {\n dependenciesSchema: Schema.Struct({\n key: Schema.String,\n restored: Schema.Boolean,\n text: Schema.OptionFromNullOr(Schema.String),\n }),\n modelToDependencies: model => {\n const remote = store.get(model)\n const key = options.key(model)\n const restored = Option.contains(remote.restoredFrom, key)\n return {\n key,\n restored,\n text: restored ? textOf(remote, options.scope(model)) : Option.none(),\n }\n },\n // A changed cache restarts this stream, so the wait is the debounce.\n dependenciesToStream: ({ key, restored, text }) =>\n restored\n ? Stream.fromEffect(\n Effect.gen(function* () {\n yield* Effect.sleep(debounce)\n const kv = yield* KeyValueStore.KeyValueStore\n // Too large to keep: no stale smaller snapshot may outlive it.\n yield* Option.match(text, {\n onNone: () => kv.remove(key),\n onSome: written => kv.set(key, written),\n })\n }).pipe(\n // A full store keeps the snapshot it had; the next change tries again.\n Effect.ignore,\n ),\n ).pipe(Stream.drain)\n : Stream.empty,\n }\n return {\n key: `persistence:${bound.contract.name}`,\n handles: [],\n subscriptions: Subscription.make<AppModel, RemoteMessage, KeyValueStore.KeyValueStore>()(\n () => ({ 'persistence.restore': restore, 'persistence.save': save }),\n ),\n }\n },\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: Record.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. */\n/**\n * How many rows a read of `ref` shows: its window's `first` or `last`, as\n * `Data.more` has grown it. `undefined` for a window with a cursor or no size,\n * which shows whatever the connection holds.\n */\nconst windowSize = (\n remote: RemoteModel,\n ref: { readonly identity: string; readonly window: QueryWindow },\n): number | undefined => {\n const { first, last, after, before } = ref.window\n if (after !== undefined || before !== undefined) return undefined\n const size = first ?? last\n return size === undefined\n ? undefined\n : (remote.grown[windowGrowthKey(ref.identity, stableStringify(ref.window))] ?? size)\n}\n\n/** The edges a window of `size` shows, from the start (`first`) or the end (`last`), and which end it cut. */\nconst cutToWindow = (\n edges: ReadonlyArray<Edge>,\n window: QueryWindow,\n size: number | undefined,\n): {\n readonly edges: ReadonlyArray<Edge>\n readonly cutBefore: boolean\n readonly cutAfter: boolean\n} => {\n if (size === undefined || edges.length <= size) {\n return { edges, cutBefore: false, cutAfter: false }\n }\n return window.first === undefined\n ? { edges: edges.slice(edges.length - size), cutBefore: true, cutAfter: false }\n : { edges: edges.slice(0, size), cutBefore: false, cutAfter: true }\n}\n\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"],"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,IA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