foldkit-remote-server 0.21.0 → 0.23.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-B1JAs_gH.mjs","names":[],"sources":["../src/diagnostics.ts","../src/refusal.ts","../src/body.ts","../src/index.ts"],"sourcesContent":["/**\n * What a Remote server answers past without telling the caller why: a defect\n * it answered \"Internal error\", a committed mutation whose answer's read or\n * live publish failed, and a client's time it would not take. Each is\n * reported through `Diagnostics.report`, so a host's log (a Worker's\n * `wrangler tail`) shows it by default.\n */\nimport { Cause } from 'effect'\nimport type { Diagnostic } from 'foldkit-remote'\n\nconst source = 'foldkit-remote-server'\n\n/** A failure on this side, answered \"Internal error\"; the caller is told nothing of it. */\nexport interface ServerDefect extends Diagnostic {\n readonly _tag: 'ServerDefect'\n readonly cause: Cause.Cause<unknown>\n}\n\n/**\n * A mutation that committed, answered without the read of the rows it names or\n * of a list it was asked for: the client reads them again.\n */\nexport interface AnswerUnread extends Diagnostic {\n readonly _tag: 'AnswerUnread'\n readonly mutation: string\n /** Why the read failed. */\n readonly reason: string\n}\n\n/** A mutation that committed, whose live publish failed: live subscribers do not hear it. */\nexport interface PublishFailed extends Diagnostic {\n readonly _tag: 'PublishFailed'\n readonly mutation: string\n readonly cause: Cause.Cause<unknown>\n}\n\n/**\n * A write sent at a time further from this server's clock than its\n * `clockSkew`: the server wrote its own time instead, so what the client\n * predicted of it is off until the answer lands.\n */\nexport interface ClockSkewed extends Diagnostic {\n readonly _tag: 'ClockSkewed'\n readonly mutation: string\n /** The client's time, in milliseconds since the epoch. */\n readonly sent: number\n /** This server's clock when it read the write, which it wrote instead. */\n readonly own: number\n /** The bound, in milliseconds. */\n readonly bound: number\n}\n\n/**\n * A read the server judged public answered otherwise for who asked than for\n * the visitor (`serveFetch`'s `cache.check`): its declaration or a source's\n * `read` depends on who asks, so it must not be cached. The asker was given\n * their own answer.\n */\nexport interface CachedReadDiffers extends Diagnostic {\n readonly _tag: 'CachedReadDiffers'\n /** The request, as the JSON it was sent as. */\n readonly request: string\n}\n\n/** Every diagnostic a Remote server reports. */\nexport type RemoteServerDiagnostic =\n | ServerDefect\n | AnswerUnread\n | PublishFailed\n | ClockSkewed\n | CachedReadDiffers\n\nexport const serverDefect = (cause: Cause.Cause<unknown>): ServerDefect => ({\n _tag: 'ServerDefect',\n source,\n level: 'error',\n message: `a request failed on this side, and its caller was answered \"Internal error\"\\n${Cause.pretty(cause)}`,\n cause,\n})\n\nexport const answerUnread = (mutation: string, reason: string): AnswerUnread => ({\n _tag: 'AnswerUnread',\n source,\n level: 'warning',\n message: `${mutation} committed, but reading its answer failed (${reason}): the client reads what it lacks again.`,\n mutation,\n reason,\n})\n\nexport const publishFailed = (mutation: string, cause: Cause.Cause<unknown>): PublishFailed => ({\n _tag: 'PublishFailed',\n source,\n level: 'error',\n message: `${mutation} committed, but its live publish failed, so live subscribers do not hear it\\n${Cause.pretty(cause)}`,\n mutation,\n cause,\n})\n\nexport const clockSkewed = (\n facts: Pick<ClockSkewed, 'mutation' | 'sent' | 'own' | 'bound'>,\n): ClockSkewed => ({\n _tag: 'ClockSkewed',\n source,\n level: 'warning',\n message: `${facts.mutation} was sent at ${facts.sent}, ${Math.abs(facts.sent - facts.own)} ms from this server's clock (${facts.own}), past its clockSkew of ${facts.bound} ms: it was written at the server's time, so the client's prediction of it moves when the answer lands. The client's clock is off, or the request waited that long.`,\n ...facts,\n})\n\nexport const cachedReadDiffers = (request: string): CachedReadDiffers => ({\n _tag: 'CachedReadDiffers',\n source,\n level: 'error',\n message: `a read judged public was answered otherwise for who asked than for a visitor, so it is not the same for everyone and must not be cached; find what in its sources depends on who asks: ${request}`,\n request,\n})\n","import type { RemoteJsonAnswer, RemoteUnauthenticated } from 'foldkit-remote'\n\n/** A caller who could not be told, as a 401 body: the twin of `answer`'s 403. */\nexport const unauthenticatedAnswer = (refusal: RemoteUnauthenticated) =>\n ({\n status: 401,\n body: {\n error: refusal.message,\n unauthenticated: refusal.reason === undefined ? {} : { reason: refusal.reason },\n } satisfies RemoteJsonAnswer,\n }) as const\n","/**\n * A request body read up to a limit, refused past it before anything decodes\n * it: what `serveFetch` and `bodyLimit` share. The limit is checked against\n * `content-length` before a byte is read, and against the bytes as they\n * arrive, so a body without one, or with one that lies, is cancelled the\n * moment it passes the limit rather than buffered whole.\n */\nimport { Data, Effect } from 'effect'\nimport { HttpServerRequest, HttpServerResponse } from 'effect/http'\nimport { DEFAULT_MAX_BODY_BYTES, type RemoteJsonAnswer } from 'foldkit-remote'\n\n/** The body passed the limit; nothing past it was kept. */\nclass BodyTooLarge extends Error {}\n\n/** Remote's answer to a body over `limit`, sent as a 413. */\nexport const tooLargeAnswer = (limit: number): RemoteJsonAnswer => ({\n error: `The request body is larger than ${limit} bytes`,\n tooLarge: { limit },\n})\n\n/** Whether `request` says it is larger than `limit`, before any of it is read. */\nexport const declaresTooLarge = (request: Request, limit: number): boolean => {\n const length = Number(request.headers.get('content-length') ?? Number.NaN)\n return Number.isFinite(length) && length > limit\n}\n\n/**\n * Consumes a body nobody read, before a refusal is answered: workerd drops the\n * connection the next request shares when an answer leaves a body unread, and\n * cancelling it is not enough. Read up to `limit` bytes and discarded, then\n * cancelled, so a refusal never reads more than a request may carry.\n */\nexport const discardBody = async (request: Request, limit: number): Promise<void> => {\n if (request.body === null || request.bodyUsed) return\n const reader = request.body.getReader()\n let total = 0\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) return\n total += value.byteLength\n if (total > limit) break\n }\n } catch {\n return\n }\n await reader.cancel().catch(() => {})\n}\n\n/**\n * `request`'s body, at most `limit` bytes of it. Rejects with `BodyTooLarge`\n * once more arrive, having cancelled the rest, or with the stream's own error.\n */\nconst readBounded = async (request: Request, limit: number): Promise<Uint8Array<ArrayBuffer>> => {\n if (declaresTooLarge(request, limit)) throw new BodyTooLarge()\n if (request.body === null) return new Uint8Array()\n const reader = request.body.getReader()\n const chunks: Uint8Array[] = []\n let total = 0\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n total += value.byteLength\n if (total > limit) {\n void reader.cancel().catch(() => {})\n throw new BodyTooLarge()\n }\n chunks.push(value)\n }\n const body = new Uint8Array(total)\n let offset = 0\n for (const chunk of chunks) {\n body.set(chunk, offset)\n offset += chunk.byteLength\n }\n return body\n}\n\n/** What a body read up to a limit came to: its bytes, or why there are none. */\ntype BoundedBody = Data.TaggedEnum<{\n Read: { readonly bytes: Uint8Array<ArrayBuffer> }\n TooLarge: {}\n Unreadable: {}\n}>\nconst BoundedBody = Data.taggedEnum<BoundedBody>()\n\n/** `request`'s body read up to `limit` bytes; never fails. */\nconst readBody = (request: Request, limit: number): Effect.Effect<BoundedBody> =>\n Effect.tryPromise(() => readBounded(request, limit)).pipe(\n Effect.match({\n onSuccess: bytes => BoundedBody.Read({ bytes }),\n onFailure: error =>\n error.cause instanceof BodyTooLarge ? BoundedBody.TooLarge() : BoundedBody.Unreadable(),\n }),\n )\n\n/** A body refused before any handler: the status and Remote's answer. */\nexport class BodyRefused extends Data.TaggedError('BodyRefused')<{\n readonly status: 400 | 413\n readonly answer: RemoteJsonAnswer\n}> {}\n\n/** Decodes a body as UTF-8, refusing bytes that are not, as `JSON.parse` would refuse the text. */\nconst utf8 = new TextDecoder('utf-8', { fatal: true })\n\n/** `request`'s body read up to `limit` bytes and parsed as JSON, or refused. */\nexport const readJson = (request: Request, limit: number): Effect.Effect<unknown, BodyRefused> => {\n const notJson = new BodyRefused({ status: 400, answer: { error: 'The body is not JSON' } })\n return Effect.flatMap(readBody(request, limit), body =>\n BoundedBody.$match(body, {\n Read: ({ bytes }) =>\n Effect.try({ try: (): unknown => JSON.parse(utf8.decode(bytes)), catch: () => notJson }),\n TooLarge: () => Effect.fail(new BodyRefused({ status: 413, answer: tooLargeAnswer(limit) })),\n Unreadable: () => Effect.fail(notJson),\n }),\n )\n}\n\n/**\n * Effect HTTP middleware refusing a request body over `maxBytes` (default\n * 1 MiB, `serveFetch`'s) with a 413 and Remote's `tooLarge` answer, before\n * the endpoint reads it. For an endpoint that serves `RemoteRpc` through\n * `RpcServer`, where Effect's own `MaxBodySize` fails the body read as a\n * defect, a 500:\n *\n * ```ts\n * HttpRouter.add('POST', '/rpc', bodyLimit(64 * 1024)(rpcHttpEffect))\n * ```\n *\n * A body within the limit reaches the endpoint whole, read once.\n */\nexport const bodyLimit =\n (maxBytes: number = DEFAULT_MAX_BODY_BYTES) =>\n <E, R>(\n endpoint: Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>,\n ): Effect.Effect<\n HttpServerResponse.HttpServerResponse,\n E,\n R | HttpServerRequest.HttpServerRequest\n > =>\n Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest\n const web = yield* Effect.orDie(HttpServerRequest.toWeb(request))\n const body = yield* readBody(web, maxBytes)\n return yield* BoundedBody.$match(body, {\n TooLarge: () =>\n Effect.succeed(HttpServerResponse.jsonUnsafe(tooLargeAnswer(maxBytes), { status: 413 })),\n Unreadable: () =>\n Effect.succeed(\n HttpServerResponse.jsonUnsafe({ error: 'The body could not be read' }, { status: 400 }),\n ),\n Read: ({ bytes }) =>\n Effect.provideService(\n endpoint,\n HttpServerRequest.HttpServerRequest,\n HttpServerRequest.fromWeb(new Request(web, { body: bytes })),\n ),\n })\n })\n","/**\n * `foldkit-remote-server` — server-side Sources and handler compilation.\n *\n * Owns entity/query Sources, **selection authorization**, normalization, and\n * turning them into Effect RPC handlers. It does not own HTTP, serialization, or\n * auth protocol; `principal` is resolved outside, and passed in or provided.\n */\nimport {\n Cause,\n Clock,\n Context,\n Data,\n Duration,\n Effect,\n Layer,\n Match,\n Option,\n Queue,\n Schema,\n Stream,\n} from 'effect'\nimport {\n Derivation,\n Entity,\n Held,\n Operators,\n SchemaShape,\n Write,\n assertSupported,\n evaluate,\n Query,\n type AnyEntity,\n type AnyQuery,\n type ExprContext,\n type MemoryOperators,\n type AnyWrite,\n type BoundWrite,\n type Computation,\n type EntityMember,\n type EntityRef,\n type Row,\n type WriteAssignment,\n} from 'foldkit-entity'\nimport {\n // One default for both ends, so a client cuts its reads to what the server takes.\n DEFAULT_MAX_IDS_PER_ENTITY,\n Diagnostics,\n EdgeCache,\n REMOTE_PROTOCOL_VERSION,\n Remote,\n RemoteClient,\n RemoteForbidden,\n RemotePrincipalChanged,\n RemoteUnauthenticated,\n RemoteLiveError,\n RemoteLiveRefused,\n RemoteMutationError,\n RemoteProtocolError,\n RemoteQueryError,\n RemoteReadError,\n Refusal,\n connectionIdentity,\n entityKey,\n refParts,\n refsIn,\n relationShape,\n queryIdentity,\n stableStringify,\n type Boundary,\n type ConnectionChangeSchema,\n type ConnectionSpec,\n type ConnectionIdentity,\n type LiveChange,\n type MutationDescriptor,\n type NormalizedPatch,\n type QueryDescriptor,\n type QueryWindow,\n type RelationRequirement,\n type RemoteDescriptor,\n Requirement,\n type RemoteRpcClient,\n MutationRequest,\n QueryRequest,\n QueryResult,\n ReadBatch,\n RemoteJsonAnswer,\n RemoteJsonRequest,\n RELATION_ALIAS,\n aliasedField,\n type CachePolicy,\n} from 'foldkit-remote'\nimport { answerUnread, clockSkewed, publishFailed, serverDefect } from './diagnostics.js'\nimport { unauthenticatedAnswer } from './refusal.js'\n\n/** What a call `RemoteServer.answer` makes can fail with, before the answer says so. */\ntype AnswerError =\n | Schema.SchemaError\n | RemoteUnauthenticated\n | RemoteReadError\n | RemoteQueryError\n | RemoteMutationError\n | RemoteForbidden\n | RemotePrincipalChanged\n | RemoteProtocolError\n\nexport class RemoteServerError extends Schema.TaggedError<RemoteServerError>()(\n 'RemoteServerError',\n {\n message: Schema.String,\n },\n) {}\n\n/**\n * A writer's word that the row does not hold what the write's `when` asks of\n * it, where the write would commit: `RemoteServer.write` answers it as the\n * mutation's `Unmet` refusal.\n */\nexport class RemoteUnmet extends Schema.TaggedError<RemoteUnmet>()('RemoteUnmet', {\n message: Schema.String,\n}) {}\n\n/**\n * A writer's word that a row already holds the id an insert names, and its\n * ledger records no insert of this operation that made it: `RemoteServer.write`\n * answers it as the mutation's `Taken` refusal. It says nothing of the row,\n * which may be hidden from whoever asked.\n */\nexport class RemoteTaken extends Schema.TaggedError<RemoteTaken>()('RemoteTaken', {\n message: Schema.String,\n}) {}\n\n/**\n * A writer's word that the row a write would leave breaks one of its Entity's\n * invariants: `RemoteServer.write` answers it as the mutation's `Invalid`\n * refusal. `rule` and `path` are none and empty when saying them would tell\n * the caller what a member hidden from them holds.\n */\nexport class RemoteInvalid extends Schema.TaggedError<RemoteInvalid>()('RemoteInvalid', {\n message: Schema.String,\n rule: Schema.Option(Schema.String),\n path: Schema.Array(Schema.String),\n}) {}\n\n/** A write's precondition as a writer is handed it: the body, and the input encoded. */\nexport interface WriteWhen {\n readonly body: AnyQuery\n readonly input: Readonly<Record<string, unknown>>\n}\n\n/**\n * A mutation Source's refusal, as the value its descriptor's `Refusal`\n * declares: made with `RemoteServer.refuse`, which checks the value's type\n * against the mutation, and sent to the client encoded, beside a message.\n */\nexport class MutationRefused extends Schema.TaggedError<MutationRefused>()('MutationRefused', {\n /** The mutation the refusal was made for: a Source refusing as another is a bug. */\n mutation: Schema.String,\n refusal: Schema.Unknown,\n /** What a person reads: the error's message beside the refusal. */\n message: Schema.String,\n}) {}\n\nexport interface EntityRecord {\n readonly id: string\n readonly values: Readonly<Record<string, unknown>>\n}\n\nexport interface EntitySourceContext<P> {\n readonly ids: readonly string[]\n readonly fields: readonly string[]\n /** A pagination window per requested relation field. */\n readonly windows?: Readonly<Record<string, QueryWindow>> | undefined\n readonly principal: P\n /**\n * Who asks, as a row: the server's `viewer` of the principal, none for a\n * visitor. Given by the server a source is mounted in; a read made outside\n * one (a test, a tool) gives none, and a source refuses it a member that\n * depends on who reads it.\n */\n readonly viewer?: Option.Option<EntityRef> | undefined\n}\n\nexport interface EntitySource<P, R = never> {\n readonly entity: string\n /** The fields the entity declares; a request for any other never reaches `read`. */\n readonly fields?: ReadonlySet<string> | undefined\n readonly read: (\n context: EntitySourceContext<P>,\n ) => Effect.Effect<ReadonlyArray<EntityRecord>, RemoteServerError, R>\n /** Returns the fields this principal may read; omitted means all requested. */\n readonly authorize?: (principal: P, fields: readonly string[]) => readonly string[]\n /**\n * Decides, per record, what a principal sees of the fields `authorize`\n * allowed: run once per read, before `read`. A member it drops from a\n * record is settled unread, as one the source did not return.\n */\n readonly filter?: (\n principal: P,\n fields: readonly string[],\n ) => Effect.Effect<ReadPlan, RemoteServerError, R>\n /**\n * The rule that decides which rows this source returns, as it was given one\n * (a Drizzle binding's `visible`, `RemoteServer.memory`'s `readable`). The\n * server never runs it: it is here so a check at startup, such as\n * `GuardServer.validate`, can confirm a source applies the rule its Entity\n * requires.\n */\n readonly visible?: unknown\n /**\n * The fields every principal reads alike, of every row: no rule about who\n * is asking hides the row or the field, or changes its value. A promise the\n * server keeps by trusting it: the live hub sends a declared write's value\n * of one to every subscriber as it is, with no read per principal.\n */\n readonly shared?: ReadonlySet<string> | undefined\n /**\n * The members answered for whoever reads them (a `Derived.exists`): a\n * server mounting this source must have a `viewer`, and refuses to be made\n * without one.\n */\n readonly perViewer?: ReadonlyArray<string> | undefined\n /**\n * How long a read of these rows stays fresh, from the Entity's declaration\n * (`EdgeCache.of`). It never makes a read public: `serveFetch` caches one\n * only where nothing about it depends on who asks.\n */\n readonly cache?: CachePolicy | undefined\n}\n\n/** What `EntitySource.filter` decides for one read. */\nexport interface ReadPlan {\n /** The fields to read: those allowed, and any the decision itself needs. */\n readonly fields: readonly string[]\n /** One record as the principal sees it: a member dropped, or its value replaced. */\n readonly apply: (record: EntityRecord) => EntityRecord\n}\n\n/** `source.read` of `fields`, through the source's `filter` when it has one. */\nconst readFiltered = <P, R>(\n source: EntitySource<P, R>,\n principal: P,\n fields: readonly string[],\n read: (\n fields: readonly string[],\n ) => Effect.Effect<ReadonlyArray<EntityRecord>, RemoteServerError, R>,\n): Effect.Effect<ReadonlyArray<EntityRecord>, RemoteServerError, R> =>\n source.filter === undefined\n ? read(fields)\n : Effect.flatMap(source.filter(principal, fields), plan =>\n Effect.map(read(plan.fields), records => records.map(plan.apply)),\n )\n\n/**\n * A read as the handlers make it for `context.principal`: the asked fields the\n * source declares and `authorize` allows, through `filter`, each record holding\n * no other field. None when the principal may read none of the fields asked,\n * so a caller can tell nothing to read from a row that is gone.\n */\nconst readAs = <P, R>(\n source: EntitySource<P, R>,\n context: EntitySourceContext<P>,\n): Effect.Effect<Option.Option<ReadonlyArray<EntityRecord>>, RemoteServerError, R> => {\n const { ids, principal, viewer } = context\n const allowed = allowedFields(source, principal, context.fields)\n if (allowed.length === 0) return Effect.succeed(Option.none())\n return readFiltered(source, principal, allowed, fields =>\n source.read({ ids, fields, principal, viewer, ...windowsOf(context.windows, allowed) }),\n ).pipe(\n Effect.map(records =>\n Option.some(\n records.map(record => {\n const values: Record<string, unknown> = Object.create(null)\n for (const field of allowed) {\n if (Object.hasOwn(record.values, field)) values[field] = record.values[field]\n }\n return { id: record.id, values }\n }),\n ),\n ),\n )\n}\n\n/**\n * Where a declared write lands: one row's new values, encoded as the store holds\n * them. With `expect`, the row is written only while its revision is still that\n * value, and the revision moves on with the write. With `when`, only while the\n * row holds its body, checked in the statement that writes it; a row there at\n * the expected revision that does not hold it fails with `RemoteUnmet`. The row\n * as written answers; none when no row matched.\n */\n/**\n * What the row an update or a delete finds must hold for it to land, judged\n * in the statement that writes it: a guard's rule that reads another row (a\n * path, an exists), against what that row holds as the statement runs.\n */\nexport type RowRequirement = Data.TaggedEnum<{\n /** A body over the row, with its input and what its context terms read. */\n Body: {\n readonly query: AnyQuery\n readonly input: Readonly<Record<string, unknown>>\n readonly context: ExprContext\n }\n All: { readonly of: ReadonlyArray<RowRequirement> }\n Any: { readonly of: ReadonlyArray<RowRequirement> }\n}>\nexport const RowRequirement = Data.taggedEnum<RowRequirement>()\n\n/** A row requirement, and the words a refusal of it gives, when its rule explains itself. */\nexport interface WriteRequirement {\n readonly holds: RowRequirement\n readonly reason: Option.Option<string>\n}\n\n/**\n * What each row of `entity` a cascading delete would take must hold (#348):\n * that Entity's `Delete` rule for the person deleting. A writer with\n * `cascades` refuses the whole delete as `Forbidden` when any such row does\n * not, and removes nothing. Only rows reached through a relation whose\n * `authorizedBy` is `child` are held to it.\n */\nexport interface CascadeRequirement {\n readonly entity: string\n readonly requires: WriteRequirement\n}\n\n/** A row a delete removed with the row it was asked to delete (`onDelete: 'cascade'`). */\nexport interface CascadedRow {\n readonly entity: string\n readonly id: string\n /** Each `one` relation it pointed, by key: what the answer re-reads (the counts it moved). */\n readonly links: Readonly<Record<string, Option.Option<EntityRef>>>\n}\n\n/**\n * What a writer's `delete` did. `Deleted`: the row is gone, with `cascaded`,\n * the rows declared to go with it (`Relation.one(…, { onDelete: 'cascade' })`)\n * that the principal may see, and `cleared`, those whose link to it was\n * cleared (`onDelete: 'setNull'`), which stay. `Absent`: no row, so nothing to delete (a\n * retry's case). `Moved`: the row is there at another revision, and stays.\n * `Referenced`: rows still point at it through `relation` (`Like.post`),\n * declared `onDelete: 'restrict'`, so it stays; which rows is not said.\n */\nexport type DeleteOutcome = Data.TaggedEnum<{\n Deleted: {\n readonly cascaded: ReadonlyArray<CascadedRow>\n readonly cleared: ReadonlyArray<EntityRef>\n }\n Absent: {}\n Moved: {}\n Referenced: { readonly entity: string; readonly relation: string }\n}>\nexport const DeleteOutcome = Data.taggedEnum<DeleteOutcome>()\n\nexport interface EntityWriter<P, R = never> {\n readonly entity: string\n /**\n * Whether `update` and `delete` hold the row to their `requires` in the\n * statement that writes it, and refuse one that does not with\n * `Forbidden`. A guard hands such a writer the rules it cannot judge over\n * one row, and refuses to wrap a writer without it.\n */\n readonly requires?: true\n /**\n * Whether `update` and `delete` honour `when`. `RemoteServer.write` refuses\n * a write with a precondition over a writer without it, which would write\n * whatever the row held.\n */\n readonly preconditions?: true\n /**\n * Whether `update` adds `increments` to their fields where it writes.\n * `RemoteServer.write` refuses a write with an increment over a writer\n * without it, which would leave the fields where they were.\n */\n readonly increments?: true\n /**\n * Whether `update` computes `assignments` where it writes, over the row it\n * writes. `RemoteServer.write` refuses a write computing a field over a\n * writer without it.\n */\n readonly assignments?: true\n /**\n * The memory table this writer works out the row a write leaves by\n * (`Write.apply`'s), where its own statement computes it: what a wrapping\n * writer (a guard) judges by, so it judges the value the database writes.\n */\n readonly operators?: MemoryOperators | undefined\n /**\n * Whether `update` writes only the row it read, at the revision it read it,\n * whatever the write `expect`s: what a guard does so its rules judge the row\n * written. Concurrent writes then cannot interleave, so an increment of a\n * real number, or any computed assignment, needs no `expect` of its own.\n */\n readonly pins?: true\n /**\n * Whether `assignment`, landed without `expect`, gives one result whatever\n * order concurrent writes land in: its operator `op(field, amount)`, with\n * commutativity and associativity tested for the implementations this\n * writer runs. `RemoteServer.write` asks of each computed assignment a\n * write lands without a revision.\n */\n readonly commutes?: (assignment: WriteAssignment) => boolean\n /**\n * Whether `update` and `insert` record each write they land under its\n * `operation`, in the transaction that writes, and answer a retry of it from\n * that record rather than writing again. An increment that expects no\n * revision needs one, and so does a create a client may send again.\n */\n readonly ledger?: true\n /**\n * Whether `update` and `insert` refuse a row, or a change, that would break\n * one of its Entity's invariants (`Entity.invariant`), with `RemoteInvalid`,\n * judged over the rows they write; an insert judges the state invariants\n * alone. `RemoteServer.write` refuses a write the Entity holds to any through\n * a writer without it.\n */\n readonly invariants?: true\n /**\n * Whether `delete` removes, in the transaction that deletes the row, every\n * row declared to go with it (`Entity.cascading`), and answers them as\n * `cascaded`; and holds those rows to the `cascading` requirements it is\n * given, judged before anything is removed, refusing the whole delete\n * where one fails. `RemoteServer.write` refuses a delete of an Entity that\n * cascades through a writer without it.\n */\n readonly cascades?: true\n /**\n * Whether `delete` refuses, in the statement that deletes, a row that rows\n * point at through a relation declared `onDelete: 'restrict'`\n * (`Entity.restricting`), answering `Referenced`. `RemoteServer.write`\n * refuses a delete of an Entity something restricts through a writer\n * without it.\n */\n readonly restricts?: true\n /**\n * Whether `delete` clears, in the transaction that deletes the row, the link\n * of every row pointing at it through a relation declared `onDelete:\n * 'setNull'` (`Entity.clearing`), answers the rows the principal may see as\n * `cleared`, and holds them to the `clearing` requirements it is given,\n * refusing the whole delete where one fails. `RemoteServer.write` refuses a\n * delete of an Entity something clears through a writer without it.\n */\n readonly clears?: true\n /**\n * Why this writer cannot land `write`, each a sentence; none when it can.\n * `RemoteServer.write` asks once, where the write is registered, for what\n * only the store knows: a column's type, say, which the Entity does not say.\n */\n readonly refuses?: (write: AnyWrite) => ReadonlyArray<string>\n /**\n * The answer recorded for `operation`, when this writer has a ledger and\n * holds one: what a wrapping writer (a guard) answers a retry with, without\n * deciding again over a row that has moved since. One recorded for another\n * `request` fails.\n */\n readonly recorded?: (context: {\n readonly operation: string\n /**\n * What was asked: the mutation's name, the keys it writes and its input,\n * encoded, as one text. Every retry of `operation` asks the same, so a\n * ledger holding the operation for another request refuses this one.\n */\n readonly request: string\n /** The row the operation writes: one operation may write several rows. */\n readonly id: string\n readonly principal: P\n }) => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R>\n readonly update: (context: {\n readonly id: string\n /** The operation's identity across clients, when the client sent one: a ledger's key. */\n readonly operation: Option.Option<string>\n /**\n * What was asked: the mutation's name, the keys it writes and its input,\n * encoded, as one text. Every retry of `operation` asks the same, so a\n * ledger holding the operation for another request refuses this one.\n */\n readonly request: string\n readonly values: Readonly<Record<string, unknown>>\n /**\n * Each field to move, by the amount, encoded: added to the stored value in\n * the statement that writes, never computed from a value read before it.\n */\n readonly increments: Readonly<Record<string, number>>\n /**\n * Each field to compute, as data (`Write.bind`'s): run in the statement\n * that writes, over the row as it is there.\n */\n readonly assignments: Readonly<Record<string, Computation>>\n /** Each `one` relation it points, by the relation's key: the row, or none. */\n readonly links: Readonly<Record<string, Option.Option<EntityRef>>>\n readonly expect: Option.Option<{ readonly field: string; readonly revision: unknown }>\n readonly when: Option.Option<WriteWhen>\n /** What the row must hold, judged where it is written; only a writer with `requires` is given one. */\n readonly requires?: WriteRequirement | undefined\n readonly principal: P\n }) => Effect.Effect<\n Option.Option<Readonly<Record<string, unknown>>>,\n RemoteServerError | RemoteForbidden | RemoteUnauthenticated | RemoteUnmet | RemoteInvalid,\n R\n >\n /**\n * Inserts the row and answers it. An id already taken fails with\n * `RemoteTaken`, whatever the row there holds and whether its asker may see\n * it, so a create never tells what it may not read; unless the writer's\n * ledger records `operation` as the insert that made it (a retry), answered\n * with the row as it now is.\n */\n readonly insert: (context: {\n readonly id: string\n /** The operation's identity across clients, when the client sent one: a ledger's key. */\n readonly operation: Option.Option<string>\n /**\n * What was asked: the mutation's name, the keys it writes and its input,\n * encoded, as one text. Every retry of `operation` asks the same, so a\n * ledger holding the operation for another request refuses this one.\n */\n readonly request: string\n readonly values: Readonly<Record<string, unknown>>\n readonly links: Readonly<Record<string, Option.Option<EntityRef>>>\n readonly principal: P\n }) => Effect.Effect<\n Readonly<Record<string, unknown>>,\n RemoteServerError | RemoteForbidden | RemoteUnauthenticated | RemoteInvalid | RemoteTaken,\n R\n >\n /**\n * Deletes the row, while it is still at the revision when one is expected,\n * and, when it `cascades`, the rows declared to go with it, in the same\n * transaction: a `DeleteOutcome`.\n */\n readonly delete: (context: {\n readonly id: string\n readonly expect: Option.Option<{ readonly field: string; readonly revision: unknown }>\n readonly when: Option.Option<WriteWhen>\n /** What the row must hold, judged where it is deleted; only a writer with `requires` is given one. */\n readonly requires?: WriteRequirement | undefined\n /**\n * What the rows a cascade takes must hold, by Entity; only a writer with\n * `cascades` is given them.\n */\n readonly cascading?: ReadonlyArray<CascadeRequirement> | undefined\n /**\n * What each row whose link the delete clears must hold, by Entity: its\n * `Update` rules over the link. Only a writer with `clears` is given them.\n */\n readonly clearing?: ReadonlyArray<CascadeRequirement> | undefined\n readonly principal: P\n }) => Effect.Effect<\n DeleteOutcome,\n RemoteServerError | RemoteForbidden | RemoteUnauthenticated | RemoteUnmet,\n R\n >\n /**\n * The row as `principal` may see it, under the read rule its Source applies:\n * none when there is no such row, or it is hidden. Given, a write's answer\n * is read back through it, so an answer never shows its writer a row it may\n * not read, and a row the write hid from them answers as deleted.\n */\n readonly read?: (context: {\n readonly id: string\n readonly fields: ReadonlyArray<string>\n readonly principal: P\n }) => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R>\n /**\n * Each of `relations`' links as stored, by ref key (`'Project:p1'`) or\n * `null`, whatever a reader may see of the row it points at; none when there\n * is no such row. A guard reads it to tell a write that unlinks a row hidden\n * from its writer from one that changes nothing.\n */\n readonly linked?: (context: {\n readonly id: string\n readonly relations: ReadonlyArray<string>\n }) => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R>\n}\n\n/** A connection change a mutation made, as the wire carries it. */\nexport type ConnectionChange = Schema.Schema.Type<typeof ConnectionChangeSchema>\n\nconst connectionChange = (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n position: 'prepend' | 'append' | 'remove',\n): ConnectionChange => {\n const edge = { entity: ref.entity, id: ref.id, key: entityKey(ref.entity, ref.id) }\n return position === 'remove'\n ? { _tag: 'Remove', connection: connectionIdentity(connection), edge }\n : { _tag: 'Insert', connection: connectionIdentity(connection), position, edge }\n}\n\n/**\n * The requested fields, in request order, that the source declares and the\n * principal may read. Never a field the client did not request, even if a\n * permissive `authorize` returns more.\n */\nconst allowedFields = <P, R>(\n source: EntitySource<P, R>,\n principal: P,\n requested: ReadonlyArray<string>,\n): ReadonlyArray<string> => {\n const declared =\n source.fields === undefined ? requested : requested.filter(field => source.fields!.has(field))\n if (declared.length === 0) return []\n const permitted = new Set(\n source.authorize === undefined ? declared : source.authorize(principal, declared),\n )\n return declared.filter(field => permitted.has(field))\n}\n\n/** The windows of the fields being read; only a field being read carries its window. */\nconst windowsOf = (\n windows: Readonly<Record<string, QueryWindow>> | undefined,\n fields: ReadonlyArray<string>,\n): { readonly windows?: Readonly<Record<string, QueryWindow>> } => {\n if (windows === undefined) return {}\n const kept = Object.fromEntries(\n fields.flatMap(field =>\n Object.hasOwn(windows, field) ? [[field, windows[field]!] as const] : [],\n ),\n )\n return Object.keys(kept).length === 0 ? {} : { windows: kept }\n}\n\nexport interface MutationOutcome<Output> {\n readonly output: Output\n readonly entities?: ReadonlyArray<NormalizedPatch>\n /** Connection changes the mutation made; the client settles them with its patches. */\n readonly connections?: ReadonlyArray<ConnectionChange>\n /**\n * Entities the mutation deleted. The client knows them absent from then on:\n * they leave every connection and read `NotFound`, with no connection to name.\n */\n readonly deleted?: ReadonlyArray<{ readonly entity: string; readonly id: string }>\n}\n\nexport interface MutationSource<P, R = never> {\n readonly mutation: string\n /**\n * For a declared write (`RemoteServer.write`), the Entity it writes, the\n * writer it lands through, as it was given one, and the write itself. The\n * server never reads it; a startup check such as `GuardServer.validate` does.\n */\n readonly writes?: { readonly entity: string; readonly writer: unknown; readonly write: AnyWrite }\n readonly Input: Schema.Codec<unknown>\n readonly Output: Schema.Codec<unknown>\n readonly Refusal: Schema.Codec<unknown, unknown>\n readonly run: (context: {\n readonly input: unknown\n readonly principal: P\n /**\n * Who asks, as a row (`RemoteServer.make`'s `viewer`), or none for a\n * visitor: what a declared write's `Expr.viewer` sets (`Entity.sets`).\n */\n readonly viewer: Option.Option<EntityRef>\n /**\n * The client's id for this request, the same on every retry of it. It is\n * unique within that client only: two clients' first requests can share\n * it. Key a record of the write by `operation`, never by this.\n */\n readonly requestId: string\n /**\n * The operation's identity across clients, the same on every retry of it,\n * when the client sent one (Remote's does); none from an older client.\n */\n readonly operation: Option.Option<string>\n /**\n * The write's time, in milliseconds since the epoch: when the reader\n * acted, as the client sent it, if within the server's `clockSkew` of its\n * own clock; otherwise the server's own. What a declared insert's\n * `Expr.now` sets (`Entity.sets`).\n */\n readonly now: number\n /**\n * One row of another Entity as the asker may see it, through the server's\n * own source for it (its read rule, the viewer): none for a row hidden or\n * not there. What a declared write reads a path from the viewer with.\n */\n readonly read: (\n ref: EntityRef,\n fields: ReadonlyArray<string>,\n ) => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError>\n /** For a declared write: the input keys to write, when the client named only some. */\n readonly keys?: ReadonlyArray<string> | undefined\n }) => Effect.Effect<\n {\n readonly output: unknown\n readonly entities: ReadonlyArray<NormalizedPatch>\n readonly connections: ReadonlyArray<ConnectionChange>\n readonly deleted: ReadonlyArray<{ readonly entity: string; readonly id: string }>\n /**\n * Rows the written row points at, before and after the write, whose\n * derived members it may have changed: the answer reads what the client\n * shows of each, and sends no patch of its own for them.\n */\n readonly pointed?: ReadonlyArray<{ readonly entity: string; readonly id: string }>\n },\n RemoteServerError | MutationRefused | RemoteForbidden | RemoteUnauthenticated,\n R\n >\n}\n\nexport interface QueryPage {\n readonly edges: ReadonlyArray<{\n readonly entity: string\n readonly id: string\n readonly key: string\n }>\n readonly start: Boundary\n readonly end: Boundary\n}\n\nexport interface QuerySource<P, R = never> {\n readonly query: string\n /** The entity whose rows it lists: a list read live selects rows of no other. */\n readonly entity: string\n readonly Input: Schema.Codec<unknown>\n readonly run: (context: {\n readonly input: unknown\n readonly window: QueryWindow\n readonly principal: P\n /** As `EntitySourceContext.viewer`: what a body's `Expr.viewer` reads. */\n readonly viewer?: Option.Option<EntityRef> | undefined\n /**\n * What the client reads of each item. A source may use it to answer\n * fields with the page, or ignore it: the handlers fetch what the page\n * leaves out through the entity sources, so one response still carries\n * both either way.\n */\n readonly select?: RelationRequirement | undefined\n }) => Effect.Effect<QueryPage, RemoteServerError, R>\n /** The rule that decides which rows the query lists. See `EntitySource.visible`. */\n readonly visible?: unknown\n /** How long an answer stays fresh, from the Query's declaration. See `EntitySource.cache`. */\n readonly cache?: CachePolicy | undefined\n}\n\n/**\n * A list a subscriber reads live (`liveQuery(Data, …)`), admitted\n * and resolved by `handlers`: what a live source diffs to tell a row that\n * joins, changes or leaves it.\n */\nexport interface LiveQuery<R = never> {\n /** The connection, as the client keys it: the query's name and input. */\n readonly identity: string\n /** What its read selects of each row, of the entity it lists. */\n readonly select: RelationRequirement\n /** Its window as the subscriber reads it now: the registered query, run as them. */\n readonly edges: Effect.Effect<QueryPage['edges'], RemoteServerError, R>\n}\n\nexport interface LiveSource<P, R = never> {\n readonly entity: string\n /**\n * Called by `handlers` only with requirements it has admitted: no more\n * distinct ids of one entity than `maxIdsPerEntity` (a live list's `first`\n * counted with them), and no more pages of one relation than a read may\n * ask. A larger subscription is refused with `RemoteLiveRefused` before any\n * live source is asked.\n *\n * A method, not a function property: `queries` carries `R` into the\n * parameter, which would make a source of `R = never` no `LiveSource<any, any>`.\n */\n subscribe(context: {\n readonly requirements: ReadonlyArray<Requirement>\n /** The lists of this entity the subscriber reads live. */\n readonly queries: ReadonlyArray<LiveQuery<R>>\n readonly after: number\n readonly principal: P\n /** As `EntitySourceContext.viewer`, for the re-reads it makes. */\n readonly viewer?: Option.Option<EntityRef> | undefined\n }): Stream.Stream<Schema.Schema.Type<typeof LiveChange>, RemoteServerError, R>\n /**\n * The entity source every value it sends is read through, as\n * `RemoteServer.readAs` reads (`pollLive` sets it). The server never reads\n * it: a startup check such as `GuardServer.validate` does, to accept a live\n * source over the source it has checked.\n */\n readonly reads?: EntitySource<P, R> | undefined\n}\n\nexport interface ServerDefinition<P, R = never> {\n readonly entities: ReadonlyMap<string, EntitySource<P, R>>\n readonly mutations: ReadonlyMap<string, MutationSource<P, R>>\n readonly queries: ReadonlyMap<string, QuerySource<P, R>>\n readonly live: ReadonlyMap<string, LiveSource<P, R>>\n /** Who asks, as a row: what a declared write's `Expr.viewer` sets. See `make`. */\n readonly viewer?: ((principal: P) => Option.Option<EntityRef>) | undefined\n /** How far from its own clock a client's time may be and still be the write's. See `make`. */\n readonly clockSkew?: Duration.Duration | undefined\n}\n\n/** How far from the server's clock a client's time is taken as a write's, unless `make` says. */\nconst DEFAULT_CLOCK_SKEW = Duration.seconds(60)\n\n/**\n * A write's time: the client's, when it sent one within `clockSkew` of this\n * server's clock, or this server's. A time refused past a bound above zero is\n * reported; at zero every client time is refused by design, so none is.\n */\nconst writeTime = (\n server: Pick<ServerDefinition<unknown, unknown>, 'clockSkew'>,\n mutation: string,\n sent: Option.Option<number>,\n): Effect.Effect<number> =>\n Effect.flatMap(Clock.currentTimeMillis, own =>\n Option.match(sent, {\n onNone: () => Effect.succeed(own),\n onSome: time => {\n const bound = Duration.toMillis(server.clockSkew ?? DEFAULT_CLOCK_SKEW)\n if (bound === 0) return Effect.succeed(own)\n return Math.abs(time - own) <= bound\n ? Effect.succeed(time)\n : Effect.as(Diagnostics.report(clockSkewed({ mutation, sent: time, own, bound })), own)\n },\n }),\n )\n\n/**\n * What a body's `Expr.viewer` and `Expr.now` read on this server: the viewer\n * the request was given, and the server's clock. A body that reads the viewer\n * in a run given none (not through a server) is refused, never read as a\n * visitor's.\n */\nexport const exprContext = (\n body: AnyQuery,\n viewer: Option.Option<EntityRef> | undefined,\n now: number,\n): ExprContext => {\n if (viewer === undefined && Query.dependencies(body).operations.includes('viewer')) {\n throw new Error(\n `[foldkit-remote-server] a query of ${body.entity.name} reads Expr.viewer, but was run outside a server, which gives the viewer`,\n )\n }\n return { viewer: viewer ?? Option.none(), now: Option.some(now) }\n}\n\n/** Who asks, as the server's `viewer` says: none for a visitor, or on a server with no viewer. */\nconst viewerOf = <P, R>(server: ServerDefinition<P, R>, principal: P): Option.Option<EntityRef> =>\n server.viewer === undefined ? Option.none() : server.viewer(principal)\n\n/**\n * Whom an answer is for, as the wire says it (#405): the key of who asks\n * (their `viewer`), `null` for a visitor, and nothing from a server that\n * names no `viewer`, which keeps no keys.\n */\nconst answeredFor = <P, R>(\n server: ServerDefinition<P, R>,\n principal: P,\n): { readonly principal?: string | null } =>\n server.viewer === undefined\n ? {}\n : {\n principal: Option.match(server.viewer(principal), {\n onNone: () => null,\n onSome: viewer => entityKey(viewer.entity, viewer.id),\n }),\n }\n\n/**\n * Refuses a write made for someone other than who asks, before anything of\n * it runs (#405): one made for someone, asked by a visitor, is asked to sign\n * in; any other told who is signed in changed, a visitor's (`null`) asked by\n * someone signed in included. A server that keeps no keys cannot tell, and\n * refuses any write that names one.\n */\nconst madeFor = <P, R>(\n server: ServerDefinition<P, R>,\n principal: P,\n expected: Option.Option<string | null>,\n): Effect.Effect<void, RemotePrincipalChanged | RemoteUnauthenticated> =>\n Option.match(expected, {\n onNone: () => Effect.void,\n onSome: key => {\n const asking = answeredFor(server, principal).principal\n if (asking === key) return Effect.void\n return asking === null\n ? Effect.fail(RemoteServer.unauthenticated())\n : Effect.fail(\n new RemotePrincipalChanged({\n message: 'The write was made for someone other than who is signed in now',\n }),\n )\n },\n })\n\n/**\n * One row as `principal` may see it, through the server's own source for its\n * Entity: the fields its `authorize` allows, filtered as the source filters.\n * None for a row hidden or not there.\n */\nconst rowAs =\n <P, R>(server: ServerDefinition<P, R>, principal: P) =>\n (\n ref: EntityRef,\n fields: ReadonlyArray<string>,\n ): Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R> => {\n const source = server.entities.get(ref.entity)\n if (source === undefined) {\n return Effect.fail(new RemoteServerError({ message: `No source serves ${ref.entity}` }))\n }\n const allowed = source.authorize?.(principal, fields) ?? fields\n return Effect.map(\n readFiltered(source, principal, allowed, read =>\n source.read({\n ids: [ref.id],\n fields: read,\n principal,\n viewer: viewerOf(server, principal),\n }),\n ),\n records => Option.map(Option.fromUndefinedOr(records[0]), record => record.values),\n )\n }\n\n/** `read` with the services the request already runs with, so its caller needs none. */\nconst withServices =\n <A extends ReadonlyArray<unknown>, B, E, R>(\n read: (...args: A) => Effect.Effect<B, E, R>,\n services: Context.Context<R>,\n ) =>\n (...args: A): Effect.Effect<B, E> =>\n Effect.provideContext(read(...args), services)\n\n/** A nested selection may not reach further than this many relation levels. */\nconst DEFAULT_MAX_DEPTH = 8\n\nexport interface HandlerOptions<P, R = never> {\n /**\n * A read or live subscription may not name more ids of one entity than\n * this; default 1000. A live subscription over it is refused with\n * `RemoteLiveRefused` before any live source or the hub sees it.\n */\n readonly maxIdsPerEntity?: number | undefined\n /** A nested selection may not reach further than this many relation levels; default 8. */\n readonly maxDepth?: number | undefined\n /** A hub whose `changed`/`deleted` signals reach the subscribers this handler registers. */\n readonly live?: LiveHub<P, R> | undefined\n}\n\n/**\n * Each page of a relation read beside another is a source read of its own, and\n * the names come from the client, so how many one relation may have is bounded.\n * A screen shows a list and a page or two of it, not dozens.\n */\nconst MAX_PAGES_PER_RELATION = 4\n\n/** The relation a request pages more ways than allowed, at any depth; `undefined` when none. */\nconst checkPagesPerRelation = (\n requirements: ReadonlyArray<RelationRequirement>,\n): string | undefined => {\n for (const requirement of requirements) {\n const pages = new Map<string, number>()\n for (const name of requirement.fields) {\n if (!name.includes(RELATION_ALIAS)) continue\n const field = aliasedField(name)\n const count = (pages.get(field) ?? 0) + 1\n if (count > MAX_PAGES_PER_RELATION) return `${requirement.entity}.${field}`\n pages.set(field, count)\n }\n const nested = checkPagesPerRelation(Object.values(requirement.relations ?? {}))\n if (nested !== undefined) return nested\n }\n return undefined\n}\n\n/** The entity the requirements name more distinct ids of than `maxIds`; `undefined` when none. */\nconst checkIdsPerEntity = (\n requirements: ReadonlyArray<Requirement>,\n maxIds: number,\n): string | undefined => {\n const ids = new Map<string, Set<string>>()\n for (const requirement of requirements) {\n const seen = ids.get(requirement.entity) ?? new Set<string>()\n seen.add(requirement.id)\n ids.set(requirement.entity, seen)\n if (seen.size > maxIds) return requirement.entity\n }\n return undefined\n}\n\n/** Why a live subscription asks more than a read may; `undefined` when it does not. */\nconst liveRefusal = (\n requirements: ReadonlyArray<Requirement>,\n maxIds: number,\n): RemoteLiveRefused | undefined => {\n const over = checkIdsPerEntity(requirements, maxIds)\n if (over !== undefined) {\n return new RemoteLiveRefused({\n message: `Too many \"${over}\" ids in one live subscription (at most ${maxIds})`,\n })\n }\n const paged = checkPagesPerRelation(requirements)\n if (paged !== undefined) {\n return new RemoteLiveRefused({\n message: `Too many pages of \"${paged}\" in one live subscription`,\n })\n }\n return undefined\n}\n\n/** A live list admitted: its request, the query that runs it, and its decoded input. */\ninterface AdmittedQuery<P, R> {\n readonly request: Schema.Schema.Type<typeof QueryRequest>\n readonly select: RelationRequirement\n readonly source: QuerySource<P, R>\n readonly input: unknown\n}\n\n/**\n * Admits each live list as a read of it is admitted, and refuses what a list\n * read again every tick may not be: a query the server does not register, an\n * input it does not decode, no `select` (a row is diffed by what it is drawn\n * with) or one of another entity than the query lists, no `first`, or a\n * `first` that, with the ids of its entity the subscription names, passes\n * `maxIds`.\n */\nconst admitQueries = <P, R>(\n server: ServerDefinition<P, R>,\n queries: ReadonlyArray<Schema.Schema.Type<typeof QueryRequest>>,\n requirements: ReadonlyArray<Requirement>,\n maxIds: number,\n): Effect.Effect<ReadonlyArray<AdmittedQuery<P, R>>, RemoteLiveRefused> =>\n Effect.gen(function* () {\n const refused = (message: string) => new RemoteLiveRefused({ message })\n const admitted: Array<AdmittedQuery<P, R>> = []\n const rows = new Map<string, number>()\n for (const request of queries) {\n const source = server.queries.get(request.query)\n if (source === undefined) return yield* refused(`Unknown query \"${request.query}\" read live`)\n const { select } = request\n if (select === undefined) {\n return yield* refused(`Query \"${request.query}\" is read live with no select`)\n }\n // Its rows are diffed as rows of the entity the select names, so a select\n // of another would read the list's ids as that entity's.\n if (select.entity !== source.entity) {\n return yield* refused(\n `Query \"${request.query}\" lists \"${source.entity}\", but is read live selecting \"${select.entity}\"`,\n )\n }\n const { first } = request.window\n if (first === undefined) {\n return yield* refused(`Query \"${request.query}\" is read live with no first`)\n }\n const paged = checkPagesPerRelation([select])\n if (paged !== undefined) {\n return yield* refused(`Too many pages of \"${paged}\" in one live subscription`)\n }\n const input = yield* Schema.decodeUnknownEffect(source.Input)(request.input).pipe(\n Effect.mapError(() => refused(`Invalid input of query \"${request.query}\" read live`)),\n )\n rows.set(select.entity, (rows.get(select.entity) ?? 0) + first)\n admitted.push({ request, select, source, input })\n }\n const ids = new Map<string, Set<string>>()\n for (const requirement of requirements) {\n const seen = ids.get(requirement.entity) ?? new Set<string>()\n seen.add(requirement.id)\n ids.set(requirement.entity, seen)\n }\n for (const [entity, listed] of rows) {\n if ((ids.get(entity)?.size ?? 0) + listed > maxIds) {\n return yield* refused(\n `Too many \"${entity}\" ids in one live subscription (at most ${maxIds}, the rows of its live lists counted)`,\n )\n }\n }\n return admitted\n })\n\ntype LiveChangeValue = Schema.Schema.Type<typeof LiveChange>\ntype Uncursored<T> = T extends unknown ? Omit<T, 'cursor'> : never\n\ninterface LiveRef {\n readonly entity: string\n readonly id: string\n}\n\n/**\n * The server-side \"these fields changed\" signal. A hub tracks each live\n * subscriber's requirements (entity, id, fields) and principal; `changed`\n * re-reads the changed fields a subscriber selects through the entity's own\n * source, under that subscriber's principal, and streams the patch to it.\n * Subscribers that select none of the changed fields do no work. Cursors\n * continue from the cursor each subscriber resumed at, so the client's\n * duplicate and gap handling is unchanged.\n */\nexport interface LiveHub<P, R = never> {\n /**\n * `values`, when given, are the row's stored values of `fields` (a declared\n * write's answer): a field of them the source declares `shared` is sent as\n * it is, and only the rest are re-read.\n */\n readonly changed: (\n ref: LiveRef,\n fields: ReadonlyArray<string>,\n values?: Readonly<Record<string, unknown>> | undefined,\n ) => Effect.Effect<void, RemoteServerError, R>\n /**\n * `ref` may be gone: each subscriber's selection of it is read again, and\n * one it is no longer there to is sent a deletion. A row deleted for one\n * writer may only be hidden from them, and still there to others.\n */\n readonly deleted: (ref: LiveRef) => Effect.Effect<void, RemoteServerError, R>\n /**\n * Registers a subscriber for the stream's lifetime; `handlers` calls this,\n * with requirements it has admitted (see `LiveSource.subscribe`).\n */\n readonly subscribe: (context: {\n readonly requirements: ReadonlyArray<Requirement>\n readonly after: number\n readonly principal: P\n /** As `EntitySourceContext.viewer`, for the re-reads it makes. */\n readonly viewer?: Option.Option<EntityRef> | undefined\n }) => Stream.Stream<LiveChangeValue, RemoteServerError>\n /** How many subscribers are registered now. */\n readonly size: Effect.Effect<number>\n}\n\ninterface Selected {\n readonly fields: Set<string>\n /** The window each paged field was subscribed with, so a re-read pages the same way. */\n readonly windows: Map<string, QueryWindow>\n}\n\n/** The subscribers one source read answers, and the fields each wants of it. */\ninterface ReadGroup<P> {\n readonly windows: Readonly<Record<string, QueryWindow>>\n /** The alias each field read here is answered under. */\n readonly renames: Readonly<Record<string, string>>\n readonly entries: Array<{ readonly subscriber: Subscriber<P>; readonly fields: string[] }>\n}\n\ninterface Subscriber<P> {\n /** Per entity:id, the fields (and their windows) this subscriber selects. */\n readonly selected: ReadonlyMap<string, Selected>\n readonly principal: P\n readonly viewer: Option.Option<EntityRef> | undefined\n readonly queue: Queue.Queue<LiveChangeValue>\n cursor: number\n}\n\n/** A subscriber's viewer as a group key: who, none for a visitor, or no server viewer. */\nconst viewerKeyOf = (viewer: Option.Option<EntityRef> | undefined): string =>\n viewer === undefined\n ? 'unset'\n : Option.match(viewer, {\n onNone: () => 'visitor',\n onSome: ref => `as ${ref.entity}:${ref.id}`,\n })\n\nconst liveHub = <P, R>(\n entities: ReadonlyArray<EntitySource<P, R>>,\n options: {\n /**\n * Who a principal is, for sharing re-reads: subscribers whose principals\n * have one key share one read, under the first one's principal. Default:\n * the principal itself, so only the same value shares. A source with\n * members answered per viewer (`perViewer`, a `Derived.exists`) is read\n * once per viewer within a key, so a key coarser than who asks (a role)\n * never sends one reader's value of such a member to another.\n */\n readonly key?: ((principal: P) => unknown) | undefined\n } = {},\n): Effect.Effect<LiveHub<P, R>> =>\n Effect.sync(() => {\n const keyOf = options.key ?? ((principal: P): unknown => principal)\n const sources = new Map(entities.map(source => [source.entity, source]))\n const subscribers = new Set<Subscriber<P>>()\n const emit = (subscriber: Subscriber<P>, change: Uncursored<LiveChangeValue>) => {\n subscriber.cursor += 1\n return Queue.offer(subscriber.queue, {\n ...change,\n cursor: subscriber.cursor,\n } as LiveChangeValue)\n }\n\n /**\n * Re-reads row `ref` for each subscriber that selects it, of `which` of\n * its fields (none: every field it selects), and sends what it now sees:\n * a patch, or, where the row is no longer there to it, a deletion. One\n * group's failed read fails the call after the others are sent.\n */\n const refresh = (\n ref: LiveRef,\n which: Option.Option<ReadonlyArray<string>>,\n values: Readonly<Record<string, unknown>> | undefined,\n ): Effect.Effect<void, RemoteServerError, R> =>\n Effect.gen(function* () {\n const key = `${ref.entity}:${ref.id}`\n const source = sources.get(ref.entity)\n if (source === undefined) {\n // Nothing to ask: a deletion reaches every subscriber as it is.\n if (Option.isSome(which)) return\n for (const subscriber of subscribers) {\n if (subscriber.selected.has(key))\n yield* emit(subscriber, { _tag: 'EntityDeleted', entity: ref.entity, id: ref.id })\n }\n return\n }\n // A shared field's written value is every subscriber's alike: it needs no read.\n const given = (field: string) =>\n values !== undefined &&\n source.shared !== undefined &&\n source.shared.has(field) &&\n Object.hasOwn(values, field)\n const perViewer = (source.perViewer ?? []).length > 0\n // One source read per principal key and window signature:\n // subscribers sharing both share the read, and a paged field is\n // re-read with the window the subscriber selected it with.\n const groups = new Map<\n unknown,\n { readonly principal: P; readonly byWindows: Map<string, ReadGroup<P>> }\n >()\n for (const subscriber of subscribers) {\n const selected = subscriber.selected.get(key)\n if (selected === undefined) continue\n const fields = Option.getOrElse(which, () => [\n ...new Set([...selected.fields].map(aliasedField)),\n ])\n const principalKey = keyOf(subscriber.principal)\n const viewerKey = perViewer ? viewerKeyOf(subscriber.viewer) : ''\n const sharing = groups.get(principalKey) ?? {\n principal: subscriber.principal,\n byWindows: new Map<string, ReadGroup<P>>(),\n }\n groups.set(principalKey, sharing)\n const { byWindows } = sharing\n const join = (\n windows: Readonly<Record<string, QueryWindow>>,\n renames: Readonly<Record<string, string>>,\n wanted: string[],\n ): void => {\n const groupKey = `${stableStringify(windows)}\\u0000${stableStringify(renames)}\\u0000${viewerKey}`\n const group = byWindows.get(groupKey) ?? { windows, renames, entries: [] }\n byWindows.set(groupKey, group)\n group.entries.push({ subscriber, fields: wanted })\n }\n const selects = fields.filter(field => selected.fields.has(field))\n // A paged field is read with its subscriber's window, so it is never sent as written.\n const sent = selects.filter(field => given(field) && !selected.windows.has(field))\n if (sent.length > 0) {\n const patch: Record<string, unknown> = Object.create(null)\n for (const field of sent) patch[field] = values![field]\n yield* emit(subscriber, {\n _tag: 'EntityPatched',\n entity: ref.entity,\n id: ref.id,\n values: patch,\n changed: sent,\n })\n }\n const sentSet = new Set(sent)\n const wanted = selects.filter(field => !sentSet.has(field))\n if (wanted.length > 0)\n join(\n Object.fromEntries(\n wanted.flatMap(field => {\n const window = selected.windows.get(field)\n return window === undefined ? [] : [[field, window] as const]\n }),\n ),\n {},\n wanted,\n )\n // A page read under an alias changes when the relation it reads does, and\n // is re-read on its own, with its window, so the whole list can be too.\n for (const alias of selected.fields) {\n const window = selected.windows.get(alias)\n const field = aliasedField(alias)\n if (field === alias || window === undefined || !fields.includes(field)) continue\n join({ [field]: window }, { [field]: alias }, [field])\n }\n }\n const gone = new Set<Subscriber<P>>()\n const read = (\n principal: P,\n { windows, renames, entries: group }: ReadGroup<P>,\n ): Effect.Effect<void, RemoteServerError, R> =>\n Effect.gen(function* () {\n const requested = [...new Set(group.flatMap(entry => entry.fields))]\n // The group shares a principal key and, where a member is per viewer, a viewer.\n const viewer = group[0]?.subscriber.viewer\n const records = yield* readAs(source, {\n ids: [ref.id],\n fields: requested,\n principal,\n viewer,\n windows,\n })\n if (Option.isNone(records)) return\n const record = records.value.find(candidate => candidate.id === ref.id)\n for (const { subscriber, fields: wanted } of group) {\n if (gone.has(subscriber)) continue\n if (record === undefined) {\n // Deleted, or no longer there to this principal: either way, gone.\n gone.add(subscriber)\n yield* emit(subscriber, { _tag: 'EntityDeleted', entity: ref.entity, id: ref.id })\n continue\n }\n const values: Record<string, unknown> = Object.create(null)\n for (const field of wanted) {\n if (Object.hasOwn(record.values, field)) {\n values[renamed(renames, field)] = record.values[field]\n }\n }\n const changed = Object.keys(values)\n if (changed.length === 0) continue\n yield* emit(subscriber, {\n _tag: 'EntityPatched',\n entity: ref.entity,\n id: ref.id,\n values,\n changed,\n })\n }\n })\n const failures: Array<RemoteServerError> = []\n for (const { principal, byWindows } of groups.values()) {\n for (const group of byWindows.values()) {\n yield* read(principal, group).pipe(\n Effect.catch(error => Effect.sync(() => void failures.push(error))),\n )\n }\n }\n if (failures.length > 0) return yield* Effect.fail(failures[0]!)\n })\n\n return {\n subscribe: ({ requirements, after, principal, viewer }) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const selected = new Map<string, Selected>()\n for (const requirement of requirements) {\n const key = `${requirement.entity}:${requirement.id}`\n const entry = selected.get(key) ?? { fields: new Set<string>(), windows: new Map() }\n for (const field of requirement.fields) entry.fields.add(field)\n for (const [field, window] of Object.entries(requirement.windows ?? {})) {\n entry.windows.set(field, window)\n }\n selected.set(key, entry)\n }\n const subscriber: Subscriber<P> = {\n selected,\n principal,\n viewer,\n queue: yield* Queue.unbounded<LiveChangeValue>(),\n cursor: after,\n }\n subscribers.add(subscriber)\n return Stream.fromQueue(subscriber.queue).pipe(\n Stream.ensuring(Effect.sync(() => void subscribers.delete(subscriber))),\n )\n }),\n ),\n\n changed: (ref, fields, values) => refresh(ref, Option.some(fields), values),\n // Gone for one writer may be hidden from them alone: each subscriber is asked again.\n deleted: ref => refresh(ref, Option.none(), undefined),\n\n size: Effect.sync(() => subscribers.size),\n }\n })\n\nconst protocolMismatch = (received: number): RemoteProtocolError | undefined =>\n received === REMOTE_PROTOCOL_VERSION\n ? undefined\n : new RemoteProtocolError({\n message: `Remote protocol version ${received} is not ${REMOTE_PROTOCOL_VERSION}`,\n expected: REMOTE_PROTOCOL_VERSION,\n received,\n })\n\ninterface EntityGroup {\n /** The fields each id was asked for: the union is read, and one id is settled only for its own. */\n readonly ids: Map<string, Set<string>>\n /** The union of the requests' fields, windows, and relations. */\n slice: RelationRequirement\n /** The alias each field read here is answered under; see `RELATION_ALIAS`. */\n readonly renames: Readonly<Record<string, string>>\n}\n\n/** A request, or the part of one that reads a relation under an alias. */\ntype Part = Requirement & { readonly renames?: Readonly<Record<string, string>> }\n\n/**\n * The name a field is answered under. A requested field is client input, so\n * `constructor` must find no rename rather than `Object.prototype`'s.\n */\nconst renamed = (renames: Readonly<Record<string, string>>, field: string): string =>\n Object.hasOwn(renames, field) ? renames[field]! : field\n\nconst pickNames = <T>(\n record: Readonly<Record<string, T>> | undefined,\n names: ReadonlyArray<string>,\n): Readonly<Record<string, T>> | undefined => {\n if (record === undefined) return undefined\n const picked = names.flatMap(name =>\n Object.hasOwn(record, name) ? [[name, record[name]!] as const] : [],\n )\n return picked.length === 0 ? undefined : Object.fromEntries(picked)\n}\n\n/**\n * A request's aliased fields, each as a read of its own. `comments@first=10` is\n * the `comments` relation read with the alias's window, so a source sees the\n * field it knows and one window for it, while the whole list rides beside it in\n * another read. The answer goes back under the alias, which is also the key of\n * the relation followed from it.\n */\nconst splitAliases = (request: Requirement): ReadonlyArray<Part> => {\n const aliases = request.fields.filter(field => field.includes(RELATION_ALIAS))\n if (aliases.length === 0) return [request]\n const plain = request.fields.filter(field => !field.includes(RELATION_ALIAS))\n interface Building {\n fields: string[]\n windows: Record<string, QueryWindow>\n relations: Record<string, RelationRequirement>\n renames: Record<string, string>\n }\n // Keyed by requested field names, so a `__proto__` names an entry, not the prototype.\n const keyed = <T>(entries?: Readonly<Record<string, T>>): Record<string, T> =>\n Object.assign(Object.create(null) as Record<string, T>, entries)\n const first: Building = {\n fields: [...plain],\n windows: keyed(pickNames(request.windows, plain)),\n relations: keyed(pickNames(request.relations, plain)),\n renames: keyed(),\n }\n const building: Building[] = [first]\n for (const alias of aliases) {\n const window = request.windows?.[alias]\n // An alias is a page: one that names no window asks for nothing.\n if (window === undefined) continue\n const field = aliasedField(alias)\n // It rides in a read that does not already read its relation, so a request\n // costs one read unless the list and a page of it are both wanted.\n let part = building.find(candidate => !candidate.fields.includes(field))\n if (part === undefined) {\n part = { fields: [], windows: keyed(), relations: keyed(), renames: keyed() }\n building.push(part)\n }\n part.fields.push(field)\n part.windows[field] = window\n part.renames[field] = alias\n const relation = request.relations?.[alias]\n if (relation !== undefined) part.relations[alias] = relation\n }\n return building\n .filter(part => part.fields.length > 0)\n .map(part => ({\n entity: request.entity,\n id: request.id,\n fields: part.fields,\n ...(Object.keys(part.windows).length === 0 ? {} : { windows: part.windows }),\n ...(Object.keys(part.relations).length === 0 ? {} : { relations: part.relations }),\n ...(Object.keys(part.renames).length === 0 ? {} : { renames: part.renames }),\n }))\n}\n\n/**\n * One level's requests grouped per entity and window signature: ids and\n * slices unioned. Requests that page a relation differently are separate\n * groups, so one window never answers for another id.\n */\nconst groupByEntity = (requests: ReadonlyArray<Requirement>): EntityGroup[] => {\n const grouped = new Map<string, EntityGroup>()\n for (const request of requests.flatMap(splitAliases)) {\n const renames = request.renames ?? {}\n const groupKey = `${request.entity}\\u0000${stableStringify(request.windows ?? null)}\\u0000${stableStringify(renames)}`\n const group = grouped.get(groupKey)\n if (group === undefined) {\n grouped.set(groupKey, {\n ids: new Map([[request.id, new Set(request.fields)]]),\n slice: Requirement.mergeRelation({ entity: request.entity, fields: [] }, request),\n renames,\n })\n } else {\n const asked = group.ids.get(request.id) ?? new Set<string>()\n for (const field of request.fields) asked.add(field)\n group.ids.set(request.id, asked)\n group.slice = Requirement.mergeRelation(group.slice, request)\n }\n }\n return [...grouped.values()]\n}\n\n/**\n * A descriptor's name and, when it declares them, its readable members: an\n * Entity's `members` (its fields, relations and derived members), or a plain\n * descriptor's `fields`.\n */\ninterface EntityName {\n readonly name: string\n readonly fields?: Readonly<Record<string, unknown>> | undefined\n readonly members?: Readonly<Record<string, unknown>> | undefined\n}\n\n/** One entity's rows in their wire shape: a relation is its ref key, `'User:u1'`. */\nexport type MemoryRows = Readonly<\n Record<string, ReadonlyArray<Readonly<Record<string, unknown>> & { readonly id: string }>>\n>\n\n/**\n * The rows a memory backend holds, which its mutations write through. A\n * change is what the next read sees; nothing is pushed to a client.\n */\nexport interface MemoryStore {\n /** The rows of one entity, in insertion order. */\n readonly rows: (entity: string) => ReadonlyArray<Readonly<Record<string, unknown>>>\n /** Writes these values onto a row, creating it if it is new. */\n readonly write: (entity: string, id: string, values: Readonly<Record<string, unknown>>) => void\n readonly remove: (entity: string, id: string) => void\n}\n\n/**\n * A memory backend made without a `principal`: its rows and the server over\n * them, answered as whoever its caller names per request (`serveFetch`,\n * `RemoteServer.handlers(served.server, principal)`).\n */\nexport interface MemoryServed<P> extends MemoryStore {\n /**\n * The rows' server, for serving them over a real transport, or as any\n * principal: `RemoteRpc.toLayer(RemoteServer.handlers(backend.server, principal))`.\n */\n readonly server: ServerDefinition<P>\n}\n\nexport interface MemoryBackend<P = undefined> extends MemoryServed<P> {\n /**\n * A `RemoteClient` answering from the rows as the configured `principal`.\n * Provide it where the real one would go.\n */\n readonly layer: Layer.Layer<RemoteClient>\n}\n\n/** What `RemoteServer.memory` is made from. See `memory`. */\nexport type MemoryConfig<P> = {\n readonly domain: Pick<RemoteDescriptor, 'registry'>\n readonly rows: MemoryRows\n /**\n * How the bodies' primitive operators are run: every query body is checked\n * against it where the server is built, and one calling an operator it lacks\n * is refused there. `Operators.kernel` when not given.\n */\n readonly operators?: MemoryOperators | undefined\n /**\n * Sources for entities the domain does not declare, which no row backs (a\n * `Me` row answered from the principal, `GuardServer.me`), served beside\n * the rows. One for a declared entity is refused: the rows serve it.\n */\n readonly entities?: ReadonlyArray<EntitySource<P>>\n /** Sources for queries, beside the domain's: one named as a declared query answers it instead of its body. */\n readonly queries?: ReadonlyArray<QuerySource<P>>\n readonly mutations?: (store: MemoryStore) => ReadonlyArray<MutationSource<P>>\n /** Per entity name, the fields a principal may read, as `RemoteServer.entity` takes it. */\n readonly authorize?: Readonly<Record<string, NonNullable<EntitySource<P>['authorize']>>>\n /** Per entity name, what a principal sees of each record, as `RemoteServer.entity` takes it. */\n readonly filter?: Readonly<Record<string, NonNullable<EntitySource<P>['filter']>>>\n /** Per entity name, the fields every principal reads alike: see `EntitySource.shared`. */\n readonly shared?: Readonly<Record<string, ReadonlyArray<string>>>\n /**\n * Which stored rows a principal may read, decided once per read. A row it\n * may not read is absent from a read by id and from every query, and a ref\n * to one is dropped from a relation (a `one` ref reads as `null`). `row`\n * looks another stored row up, for a decision that follows a relation.\n */\n readonly readable?: (\n principal: P,\n row: (entity: string, id: string) => Option.Option<Readonly<Record<string, unknown>>>,\n ) => Effect.Effect<MemoryReadable, RemoteServerError>\n /** Who the `layer` answers as. Without it there is no `layer`, unless `P` admits `undefined`. */\n readonly principal?: P\n /** Who asks, as a row: what a declared write's `Expr.viewer` sets. See `make`. */\n readonly viewer?: ((principal: P) => Option.Option<EntityRef>) | undefined\n}\n\n/** What a backend needs to give a `layer`: a principal to answer as, or one `undefined` can be. */\nexport type MemoryAnswering<P> = undefined extends P ? unknown : { readonly principal: P }\n\n/** Whether a stored row of `entity` may be read, given its whole stored values. */\nexport type MemoryReadable = (entity: string, row: Readonly<Record<string, unknown>>) => boolean\n\n/** Where a cursor falls among ordered items: before `index`, or at it when `exact`. */\ninterface Position {\n readonly index: number\n readonly exact: boolean\n}\n\n/**\n * One page of ordered items for a window, as a real server pages them. A\n * cursor is an item's id: a forward page starts at the `after` it was asked\n * for and ends at its last item while more follow, a backward page the\n * mirror, so a page fetched from another's end cursor joins it.\n *\n * `locate` places a cursor that is not among the items, as a keyset does: a\n * row that stopped matching still has a place in the order. Without it, such\n * a cursor is an error. A page of no items has no id of its own to end at, so\n * with more beyond it and no cursor to repeat, its boundary is `Unknown`.\n */\nconst pageOf = <Item>(\n items: ReadonlyArray<Item>,\n window: QueryWindow,\n idOf: (item: Item) => string,\n locate?: (cursor: string) => Position,\n): { readonly items: ReadonlyArray<Item>; readonly start: Boundary; readonly end: Boundary } => {\n if (\n (window.after !== undefined && window.before !== undefined) ||\n (window.first !== undefined && window.last !== undefined)\n ) {\n throw new Error('A query window cannot combine after with before, or first with last')\n }\n const position = (cursor: string): Position => {\n const index = items.findIndex(item => idOf(item) === cursor)\n if (index >= 0) return { index, exact: true }\n if (locate !== undefined) return locate(cursor)\n throw new Error(`Cursor \"${cursor}\" names nothing in these results`)\n }\n const cursor = (id: string): Boundary => ({ _tag: 'Cursor', cursor: id })\n const terminal: Boundary = { _tag: 'Terminal' }\n const unknown: Boundary = { _tag: 'Unknown' }\n if (window.last !== undefined || window.before !== undefined) {\n const to = window.before === undefined ? items.length : position(window.before).index\n const from = window.last === undefined ? 0 : Math.max(0, to - window.last)\n const page = items.slice(from, to)\n const start =\n from === 0\n ? terminal\n : page.length > 0\n ? cursor(idOf(page[0]!))\n : window.before === undefined\n ? unknown\n : cursor(window.before)\n return {\n items: page,\n start,\n end: window.before === undefined ? terminal : cursor(window.before),\n }\n }\n const at = window.after === undefined ? undefined : position(window.after)\n const from = at === undefined ? 0 : at.exact ? at.index + 1 : at.index\n const to = window.first === undefined ? items.length : Math.min(items.length, from + window.first)\n const page = items.slice(from, to)\n const end =\n to >= items.length\n ? terminal\n : page.length > 0\n ? cursor(idOf(page.at(-1)!))\n : window.after === undefined\n ? unknown\n : cursor(window.after)\n return { items: page, start: window.after === undefined ? terminal : cursor(window.after), end }\n}\n\n/**\n * A backend held in memory: the rows you give it, served through the same\n * handlers a real server uses. For a first run, a test, a story or a demo, with\n * no database and no network.\n *\n * Reads go through `handlers`, so field filtering and nested relations behave\n * as they do in production. A query declared with `Query.define` is answered\n * by running its body over the rows with the reference interpreter, the one\n * every interpreter is held to by the conformance suite. A query with no body\n * has nothing to run and is refused when the backend is made, unless `queries`\n * supplies a source for it. Mutations are yours to give: each one writes\n * through the store it is handed, and the next read sees the change.\n *\n * Every field of every row is readable unless `authorize` names the entity:\n * then its function decides, per principal, as `RemoteServer.entity`'s does.\n * `entities` adds Sources for entities no row backs, which the domain must not\n * declare. The `layer` answers as `principal`, and is absent without one\n * (unless `P` admits `undefined`); `server` answers as any. It does not push\n * live changes. It is not a server to deploy.\n */\nfunction memory<P = undefined>(config: MemoryConfig<P> & MemoryAnswering<P>): MemoryBackend<P>\nfunction memory<P = undefined>(config: MemoryConfig<P>): MemoryServed<P>\nfunction memory<P = undefined>(config: MemoryConfig<P>): MemoryBackend<P> {\n const operators = config.operators ?? Operators.kernel\n // A body this table cannot run would fail on its first read: refuse it here.\n for (const query of config.domain.registry.queries.values()) {\n if (query.body !== undefined) assertSupported(query.body, operators)\n }\n const declared = config.domain.registry.entities\n const extra = new Set<string>()\n for (const source of config.entities ?? []) {\n if (declared.has(source.entity))\n throw new Error(\n `RemoteServer.memory: \"${source.entity}\" is a declared entity, which the rows serve; give its rows, or leave it out of the domain and keep its source`,\n )\n if (extra.has(source.entity))\n throw new Error(`RemoteServer.memory: two sources in \\`entities\\` serve \"${source.entity}\"`)\n extra.add(source.entity)\n }\n const authorize = config.authorize ?? {}\n const filter = config.filter ?? {}\n const shared = config.shared ?? {}\n for (const [option, given] of [\n ['authorize', authorize],\n ['filter', filter],\n ['shared', shared],\n ] as const) {\n const unknown = Object.keys(given).filter(name => !config.domain.registry.entities.has(name))\n if (unknown.length > 0) {\n throw new Error(\n `RemoteServer.memory: \\`${option}\\` names ${unknown.map(name => `\"${name}\"`).join(', ')}, which the domain does not declare`,\n )\n }\n }\n for (const [name, fields] of Object.entries(shared)) {\n const entity: EntityName = config.domain.registry.entities.get(name)!\n const declared = entity.members ?? entity.fields\n const unserved = fields.filter(\n field => declared !== undefined && !Object.hasOwn(declared, field),\n )\n if (unserved.length > 0) {\n throw new Error(\n `RemoteServer.memory: ${name}'s shared fields name no member: ${unserved.join(', ')}`,\n )\n }\n }\n const everyRow: MemoryReadable = () => true\n const readableFor = (principal: P) =>\n config.readable === undefined\n ? Effect.succeed(everyRow)\n : config.readable(principal, (entity, id) => Option.fromUndefinedOr(table(entity).get(id)))\n const tables = new Map<string, Map<string, Record<string, unknown>>>()\n const table = (entity: string) => {\n const existing = tables.get(entity)\n if (existing !== undefined) return existing\n const created = new Map<string, Record<string, unknown>>()\n tables.set(entity, created)\n return created\n }\n for (const [entity, rows] of Object.entries(config.rows)) {\n // Keyed by the id as the wire carries it, a string, whatever JSON gave.\n for (const row of rows) table(entity).set(String(row.id), { ...row })\n }\n const store: MemoryStore = {\n rows: entity => [...table(entity).values()],\n write: (entity, id, values) => {\n table(entity).set(id, { ...table(entity).get(id), id, ...values })\n },\n remove: (entity, id) => {\n table(entity).delete(id)\n },\n }\n\n // A relation page is the refs in a window of the stored list. Its cursor is a\n // ref key, or a bare id, as a real server accepts either.\n const valueFor = (value: unknown, window: QueryWindow | undefined): unknown => {\n if (window === undefined || !Array.isArray(value)) return value\n // A ref listed twice would make a cursor ambiguous, and paging cycle.\n const refs = [...new Set(value as ReadonlyArray<string>)]\n const idOf = (ref: string) => ref.slice(ref.indexOf(':') + 1)\n const named = (cursor: string | undefined) =>\n cursor === undefined ? undefined : cursor.includes(':') ? idOf(cursor) : cursor\n let page: ReturnType<typeof pageOf<string>>\n try {\n page = pageOf(\n refs,\n { ...window, after: named(window.after), before: named(window.before) },\n idOf,\n )\n } catch {\n // A cursor that names nothing in the list answers this one field with an\n // empty page. Failing would fail the whole batch it rode in, every other\n // entity and field with it.\n return { refs: [], hasNext: false, hasPrevious: false }\n }\n // A cursor at either end is exactly \"more lie that way\".\n return {\n refs: page.items,\n hasNext: page.end._tag === 'Cursor',\n hasPrevious: page.start._tag === 'Cursor',\n }\n }\n\n // A relation's value is a ref, or a list of them; a ref to a row the\n // principal may not read is not shown, as a database binding hides it.\n const relationsOf = new Map(\n [...config.domain.registry.entities].map(([name, descriptor]) => [\n name,\n new Set(\n Object.entries(descriptor.fields as Readonly<Record<string, Schema.Top>>).flatMap(\n ([field, schema]) => (relationShape(schema) === undefined ? [] : [field]),\n ),\n ),\n ]),\n )\n const refsShown = (readable: MemoryReadable, entity: string, field: string, value: unknown) => {\n if (readable === everyRow || relationsOf.get(entity)?.has(field) !== true) return value\n const shown = (ref: unknown) => {\n if (typeof ref !== 'string') return true\n const { entity: target, id } = refParts(ref)\n const row = table(target).get(id)\n return row !== undefined && readable(target, row)\n }\n if (Array.isArray(value)) return value.filter(shown)\n return shown(value) ? value : null\n }\n\n // Every row this backend reads, it reads through `readable`.\n const visible = config.readable === undefined ? {} : { visible: config.readable }\n const entities = [...config.domain.registry.entities.keys()].map(name => ({\n ...visible,\n ...Option.match(Option.fromUndefinedOr(config.domain.registry.cached.get(name)), {\n onNone: () => ({}),\n onSome: cache => ({ cache }),\n }),\n ...RemoteServer.entity<P>(\n { name },\n {\n ...(Object.hasOwn(authorize, name) ? { authorize: authorize[name]! } : {}),\n ...(Object.hasOwn(filter, name) ? { filter: filter[name]! } : {}),\n ...(Object.hasOwn(shared, name) ? { shared: shared[name]! } : {}),\n read: ({ ids, fields, windows, principal }) =>\n Effect.flatMap(readableFor(principal), readable =>\n Effect.try({\n try: () =>\n ids.flatMap(id => {\n const row = table(name).get(id)\n if (row === undefined || !readable(name, row)) return []\n const values = Object.fromEntries(\n fields.flatMap(field =>\n Object.hasOwn(row, field)\n ? [\n [\n field,\n valueFor(\n refsShown(readable, name, field, row[field]),\n windows !== undefined && Object.hasOwn(windows, field)\n ? windows[field]\n : undefined,\n ),\n ] as const,\n ]\n : [],\n ),\n )\n return [{ id, values }]\n }),\n catch: error =>\n new RemoteServerError({\n message: error instanceof Error ? error.message : String(error),\n }),\n }),\n ),\n },\n ),\n }))\n\n const given = new Set((config.queries ?? []).map(source => source.query))\n const bodiless = [...config.domain.registry.queries.values()].filter(\n query => query.body === undefined && !given.has(query.name),\n )\n if (bodiless.length > 0) {\n throw new Error(\n `RemoteServer.memory: ${bodiless.map(query => `\"${query.name}\"`).join(', ')} ${bodiless.length === 1 ? 'has' : 'have'} no body to run. Declare ${bodiless.length === 1 ? 'it' : 'them'} with Query.define, or give a source in \\`queries\\`.`,\n )\n }\n const queries = [\n ...(config.queries ?? []),\n ...[...config.domain.registry.queries.values()]\n .filter(query => !given.has(query.name))\n .map(query => ({\n ...visible,\n ...RemoteServer.query<P>(query, ({ input, window, principal, viewer }) =>\n Effect.flatMap(\n Effect.all([readableFor(principal), Clock.currentTimeMillis]),\n ([readable, now]) =>\n Effect.try({\n try: () => {\n const body = query.body!\n const context = exprContext(body, viewer, now)\n const encoded = Schema.encodeSync(query.Input)(input) as Readonly<\n Record<string, unknown>\n >\n const entity = body.entity.name\n // The rows keep a link as its ref key; the body reads the id it points at.\n const rows = (store.rows(entity) as ReadonlyArray<Row>)\n .filter(row => readable(entity, row))\n .map(row => Held.fromRefs(body, row))\n const matched = evaluate(body, encoded, rows, { operators, context })\n // A cursor row that no longer matches still has a place in the\n // order, as a keyset has it: sort it among the matches with the\n // predicates set aside. One that no longer exists has none.\n const locate = (cursor: string) => {\n const row = rows.find(candidate => String(candidate.id) === cursor)\n if (row === undefined) {\n throw new Error(`Cursor \"${cursor}\" names a row that no longer exists`)\n }\n const placed = evaluate(\n { ...body, where: [] } as typeof body,\n encoded,\n [...matched, row],\n { operators, context },\n )\n return { index: placed.indexOf(row), exact: false }\n }\n const page = pageOf(matched, window, row => String(row.id), locate)\n return {\n edges: page.items.map(row => {\n const id = String(row.id)\n return { entity, id, key: entityKey(entity, id) }\n }),\n start: page.start,\n end: page.end,\n }\n },\n catch: error =>\n new RemoteServerError({\n message: error instanceof Error ? error.message : String(error),\n }),\n }),\n ),\n ),\n })),\n ]\n\n const server = RemoteServer.make<P>({\n entities: [...entities, ...(config.entities ?? [])],\n queries,\n mutations: config.mutations?.(store) ?? [],\n viewer: config.viewer,\n })\n return {\n ...store,\n server,\n // Typed only where `principal` was given or `P` admits `undefined` (the\n // overloads): otherwise it would answer as nobody, and is not offered.\n layer: Remote.clientLayer(\n RemoteServer.handlers(server, config.principal as P),\n ) as Layer.Layer<RemoteClient>,\n }\n}\n\n/** The entries of `record` whose key is in `keys`. */\nconst pickKeys = <T>(\n record: Readonly<Record<string, T>>,\n keys: ReadonlySet<string>,\n): Readonly<Record<string, T>> =>\n Object.fromEntries(Object.entries(record).filter(([key]) => keys.has(key)))\n\n/**\n * A fresh read, after a mutation, of what the client shows of each row its\n * outcome names: of each, the shown fields the answer left out, and every\n * shown relation, since the answer's ref alone does not reach what the client\n * reads of its target. Read as any read is, so `authorize` and `filter` hold.\n * Only rows the read returned are answered: a row hidden from the asker keeps\n * what the answer gave it rather than reading as gone.\n */\nconst answerRead = <P, R>(\n server: ServerDefinition<P, R>,\n principal: P,\n options: HandlerOptions<P, R>,\n shown: ReadonlyArray<RelationRequirement>,\n outcome: {\n readonly entities: ReadonlyArray<NormalizedPatch>\n readonly connections: ReadonlyArray<ConnectionChange>\n readonly deleted: ReadonlyArray<{ readonly entity: string; readonly id: string }>\n readonly pointed?: ReadonlyArray<{ readonly entity: string; readonly id: string }> | undefined\n },\n): Effect.Effect<\n Option.Option<{\n readonly requests: ReadonlyArray<Requirement>\n readonly result: Effect.Success<ReturnType<typeof RemoteServer.readHelper>>\n }>,\n RemoteReadError,\n R\n> =>\n Effect.gen(function* () {\n const slices = new Map<string, RelationRequirement>()\n for (const slice of shown) {\n const current = slices.get(slice.entity)\n slices.set(\n slice.entity,\n current === undefined ? slice : Requirement.mergeRelation(current, slice),\n )\n }\n const named = new Map<\n string,\n { readonly entity: string; readonly id: string; readonly answered: Set<string> }\n >()\n const name = (entity: string, id: string, answered: ReadonlyArray<string>): void => {\n const key = `${entity}:${id}`\n const row = named.get(key) ?? { entity, id, answered: new Set<string>() }\n for (const field of answered) row.answered.add(field)\n named.set(key, row)\n }\n for (const patch of outcome.entities) name(patch.entity, patch.id, Object.keys(patch.values))\n for (const change of outcome.connections)\n if (change._tag === 'Insert') name(change.edge.entity, change.edge.id, [])\n for (const row of outcome.pointed ?? []) name(row.entity, row.id, [])\n for (const gone of outcome.deleted) named.delete(`${gone.entity}:${gone.id}`)\n\n const requests: Array<Requirement> = []\n for (const row of named.values()) {\n const slice = slices.get(row.entity)\n if (slice === undefined) continue\n const relations = slice.relations ?? {}\n const fields = slice.fields.filter(\n field => !row.answered.has(field) || Object.hasOwn(relations, field),\n )\n const kept = new Set(fields)\n requests.push({\n entity: row.entity,\n id: row.id,\n fields,\n ...(slice.windows === undefined ? {} : { windows: pickKeys(slice.windows, kept) }),\n ...(slice.relations === undefined ? {} : { relations: pickKeys(slice.relations, kept) }),\n })\n }\n const read = yield* RemoteServer.readHelper(server, principal, options, requests)\n // A row is reached only when the read returned it: the read settles a field it\n // will not read for any id it was asked, so `settled` alone proves nothing, and\n // the asker never named these ids. What it settled of a named row it did not\n // reach goes unsent; a row reached through a ref the read returned is the asker's.\n const reached = new Set(read.entities.map(row => `${row.entity}:${row.id}`))\n const found = requests.filter(request => reached.has(`${request.entity}:${request.id}`))\n const unreached = new Set(\n requests.map(request => `${request.entity}:${request.id}`).filter(key => !reached.has(key)),\n )\n const result = {\n entities: read.entities,\n settled: read.settled.filter(row => !unreached.has(`${row.entity}:${row.id}`)),\n }\n return found.length === 0 ? Option.none() : Option.some({ requests: found, result })\n })\n\ntype QueryRequestValue = Schema.Schema.Type<typeof QueryRequest>\n\n/**\n * A query's page as `FoldkitRemoteQuery` answers it: the source's edges, and\n * with a select, what the page's items select, read through `readHelper`, so\n * `authorize` and `filter` hold. A mutation's answer reads its lists with it.\n */\nconst answerQuery = <P, R>(\n server: ServerDefinition<P, R>,\n caller: P,\n options: HandlerOptions<P, R>,\n payload: QueryRequestValue,\n): Effect.Effect<Schema.Schema.Type<typeof QueryResult>, RemoteQueryError, R> =>\n Effect.gen(function* () {\n const source = server.queries.get(payload.query)\n if (source === undefined) {\n return yield* new RemoteQueryError({ message: `Unknown query: ${payload.query}` })\n }\n\n const input = yield* Schema.decodeUnknownEffect(source.Input)(payload.input).pipe(\n Effect.catchTag('SchemaError', () =>\n Effect.fail(new RemoteQueryError({ message: 'Invalid query input' })),\n ),\n )\n\n const select = payload.select\n if (select !== undefined) {\n const paged = checkPagesPerRelation([select])\n if (paged !== undefined) {\n return yield* new RemoteQueryError({\n message: `Too many pages of \"${paged}\" in one query select`,\n })\n }\n }\n\n const page = yield* source\n .run({\n input,\n window: payload.window,\n principal: caller,\n viewer: viewerOf(server, caller),\n ...(select === undefined ? {} : { select }),\n })\n .pipe(\n Effect.catchTag('RemoteServerError', error =>\n Effect.fail(new RemoteQueryError({ message: error.message })),\n ),\n )\n\n if (select === undefined) return { edges: page.edges, start: page.start, end: page.end }\n // The page's items as requirements, so the selected fields ride back\n // with the edges in one response. Edges of another entity (a query\n // lists one) take no fields: the client's planner asks for them next.\n const requirements: Requirement[] = page.edges.flatMap(edge =>\n edge.entity === select.entity\n ? [\n {\n entity: select.entity,\n id: edge.id,\n fields: [...select.fields],\n ...(select.windows === undefined ? {} : { windows: select.windows }),\n ...(select.relations === undefined ? {} : { relations: select.relations }),\n },\n ]\n : [],\n )\n if (requirements.length === 0)\n return { edges: page.edges, start: page.start, end: page.end, entities: [], settled: [] }\n const read = yield* RemoteServer.readHelper(server, caller, options, requirements).pipe(\n Effect.catchTag('RemoteReadError', error =>\n Effect.fail(new RemoteQueryError({ message: error.message })),\n ),\n )\n return { edges: page.edges, start: page.start, end: page.end, ...read }\n })\n\n/**\n * The lists of a mutation request the server answers after the write, judged\n * before it runs: each a first page (`first`, no `after`) of a query it serves,\n * selecting that query's entity, within the select's page bound, while the\n * rows every admitted list may return stay within `maxIds` per entity. One\n * past these is not answered, and the client asks for it again; the write\n * runs either way.\n */\nconst admitLists = <P, R>(\n server: ServerDefinition<P, R>,\n lists: ReadonlyArray<QueryRequestValue>,\n maxIds: number,\n): ReadonlyArray<QueryRequestValue> => {\n const rows = new Map<string, number>()\n return lists.filter(request => {\n const source = server.queries.get(request.query)\n const { select, window } = request\n if (source === undefined || select === undefined || select.entity !== source.entity)\n return false\n if (window.first === undefined || window.after !== undefined) return false\n if (checkPagesPerRelation([select]) !== undefined) return false\n const listed = (rows.get(select.entity) ?? 0) + window.first\n if (listed > maxIds) return false\n rows.set(select.entity, listed)\n return true\n })\n}\n\n/**\n * A Source's refusal as the client receives it: encoded by the mutation's own\n * `Refusal`. A refusal made for another mutation, or one the mutation does not\n * declare, is this side's bug, and says so without the value.\n */\nconst refusalError = (\n Refusal: Schema.Codec<unknown, unknown>,\n mutation: string,\n refused: MutationRefused,\n): Effect.Effect<never, RemoteMutationError> =>\n Effect.gen(function* () {\n const invalid = new RemoteMutationError({ message: 'Invalid mutation refusal' })\n if (refused.mutation !== mutation) return yield* invalid\n const encoded = yield* Schema.encodeUnknownEffect(Refusal)(refused.refusal).pipe(\n Effect.mapError(() => invalid),\n )\n return yield* new RemoteMutationError({ message: refused.message, refusal: encoded })\n })\n\nexport const RemoteServer = {\n /** A backend held in memory, for a first run, a test or a demo. See `memory`. */\n memory,\n\n /** A mutation outcome's report that `ref` now heads the connection. */\n prepend: (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n ): ConnectionChange => connectionChange(connection, ref, 'prepend'),\n\n /** A mutation outcome's report that `ref` now ends the connection. */\n append: (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n ): ConnectionChange => connectionChange(connection, ref, 'append'),\n\n /** A mutation outcome's report that `ref` left the connection. */\n remove: (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n ): ConnectionChange => connectionChange(connection, ref, 'remove'),\n\n /**\n * An entity source. Given the Entity, every member it declares (fields,\n * relations, derived members) may be requested; given anything with a\n * `name` and `fields`, those fields. A request for anything else never\n * reaches `read` or `authorize`. Given only a `name`, every field passes.\n */\n entity: <P = unknown, R = never>(\n entity: EntityName,\n options: {\n readonly read: EntitySource<P, R>['read']\n readonly authorize?: EntitySource<P, R>['authorize']\n readonly filter?: EntitySource<P, R>['filter']\n /** See `EntitySource.shared`: each must be a member the source serves. */\n readonly shared?: ReadonlyArray<string> | undefined\n },\n ): EntitySource<P, R> => {\n const declared = entity.members ?? entity.fields\n const fields = declared === undefined ? undefined : new Set(Object.keys(declared))\n const cache = EdgeCache.policyOf(entity)\n const unserved = (options.shared ?? []).filter(\n field => fields !== undefined && !fields.has(field),\n )\n if (unserved.length > 0) {\n throw new Error(\n `[foldkit-remote-server] ${entity.name}'s shared fields name no member: ${unserved.join(', ')}`,\n )\n }\n return {\n entity: entity.name,\n ...(fields === undefined ? {} : { fields }),\n read: options.read,\n ...(options.authorize === undefined ? {} : { authorize: options.authorize }),\n ...(options.filter === undefined ? {} : { filter: options.filter }),\n ...(options.shared === undefined ? {} : { shared: new Set(options.shared) }),\n ...(Option.isSome(cache) ? { cache: cache.value } : {}),\n }\n },\n\n mutation: <\n P = unknown,\n R = never,\n Name extends string = string,\n Input = unknown,\n Output = unknown,\n Refused = unknown,\n >(\n mutation: MutationDescriptor<Name, Input, Output, Refused>,\n run: (context: {\n readonly input: Input\n readonly principal: P\n /** The client's id for this request, unique within that client only. */\n readonly requestId: string\n /** The operation's identity across clients, for a record of the write; see `MutationSource`. */\n readonly operation: Option.Option<string>\n /** The write's time: the client's within the server's `clockSkew`, or its own; see `MutationSource`. */\n readonly now: number\n }) => Effect.Effect<\n MutationOutcome<Output>,\n RemoteServerError | MutationRefused | RemoteForbidden | RemoteUnauthenticated,\n R\n >,\n ): MutationSource<P, R> => ({\n mutation: mutation.name,\n Input: mutation.Input,\n Output: mutation.Output,\n Refusal: mutation.Refusal,\n run: context =>\n run({\n input: context.input as Input,\n principal: context.principal,\n requestId: context.requestId,\n operation: context.operation,\n now: context.now,\n }).pipe(\n Effect.map(outcome => ({\n output: outcome.output,\n entities: outcome.entities ?? [],\n connections: outcome.connections ?? [],\n deleted: outcome.deleted ?? [],\n })),\n ),\n }),\n\n /**\n * A refusal of `mutation`, as a value of its declared `Refusal`: fail a\n * Source with it (`yield* RemoteServer.refuse(SavePost, { _tag: 'Field', ... })`)\n * and the client reads it, decoded, with `Data.refusal`. `message` is what a\n * person reads, beside it.\n */\n refuse: <Refused>(\n mutation: MutationDescriptor<string, any, any, Refused>,\n refusal: NoInfer<Refused>,\n message = `Mutation ${mutation.name} was refused`,\n ): MutationRefused => new MutationRefused({ mutation: mutation.name, refusal, message }),\n\n /**\n * A writer's refusal of a row that does not hold the write's `when`: fail\n * `update` or `delete` with it (`yield* RemoteServer.unmet()`), and\n * `RemoteServer.write` answers the mutation's `Unmet` refusal.\n */\n unmet: (message = 'The row does not hold what the write asks of it'): RemoteUnmet =>\n new RemoteUnmet({ message }),\n\n /**\n * A writer's refusal of an insert whose id a row already holds: fail\n * `insert` with it (`yield* RemoteServer.taken()`), and `RemoteServer.write`\n * answers the mutation's `Taken` refusal, naming the Entity and the id.\n */\n taken: (message = 'The id is already taken'): RemoteTaken => new RemoteTaken({ message }),\n\n /**\n * A writer's refusal of a row that would break an invariant: fail `update`\n * or `insert` with it, naming the invariant's id and path when the caller\n * may be told them, and `RemoteServer.write` answers the mutation's\n * `Invalid` refusal.\n */\n invalid: (\n message: string,\n rule: Option.Option<string> = Option.none(),\n path: ReadonlyArray<string> = [],\n ): RemoteInvalid => new RemoteInvalid({ message, rule, path }),\n\n /**\n * A refusal of who is asking: fail a Source with it\n * (`yield* RemoteServer.forbid()`) and the write never runs. `reason`, when\n * given, is what the person who asked reads; without it the refusal says\n * nothing of why. `answer` sends it as a 403, and the client's mutation\n * fails with `_tag: 'Forbidden'`.\n */\n forbid: (reason?: string): RemoteForbidden =>\n new RemoteForbidden({\n message: reason ?? 'Forbidden',\n ...(reason === undefined ? {} : { reason }),\n }),\n\n /**\n * A refusal of a caller who could not be told: a `serveFetch` or\n * `defineDocumentHost` resolver fails with it (`RemoteServer.unauthenticated()`)\n * when the credential it was sent no longer holds, and a write refused to a\n * visitor fails with it (`GuardServer` does), so a client can tell a session\n * that ended from a refusal. It answers 401, with `reason`, when given, for\n * the person who asked; a durable write so answered waits for a sign-in.\n */\n unauthenticated: (reason?: string): RemoteUnauthenticated =>\n new RemoteUnauthenticated({\n message: reason ?? 'Unauthenticated',\n ...(reason === undefined ? {} : { reason }),\n }),\n\n /**\n * The Source of a mutation that is a declared `Write`, with no handler: the\n * input bound to the write lands through `writer`, and the row as written\n * answers as a patch (a deletion as `deleted`). An update writes only the\n * keys the client named, when it named some, and fails for a row that is not\n * there; an insert of an id already taken is refused as taken, alike\n * whatever the row holds, unless the writer's ledger records this operation\n * as the insert that made it (a retry), answered with that row; a delete of\n * a row already gone succeeds. A row that moved past the revision the write\n * `expect`s is refused as a conflict, and one that does not hold its `when`\n * as unmet; a write with a `when` needs a writer that checks it\n * (`preconditions`), and is refused here without one.\n */\n write: <P = unknown, R = never, Name extends string = string, Input = unknown>(\n // Its `Refusal` is the one `Mutation.write` derived from the write's kind; each\n // refusal below is one that kind declares. Left `any`, so a list of writes of\n // every kind, each refused its own way, maps through here.\n mutation: MutationDescriptor<Name, Input, {}, any> & {\n readonly write: AnyWrite\n },\n writer: EntityWriter<P, R>,\n ): MutationSource<P, R> => {\n const { write } = mutation\n if (write.input.entity.name !== writer.entity) {\n throw new Error(\n `[foldkit-remote-server] write \"${mutation.name}\" writes ${write.input.entity.name}, but its writer is for ${writer.entity}`,\n )\n }\n // Without a revision, only a ledger tells a retry of an increment from a second one.\n if (write.increments.length > 0 && write.expect === undefined && writer.ledger !== true) {\n throw new Error(\n `[foldkit-remote-server] write \"${mutation.name}\" increments a field and expects no revision, so a retry could add twice; give it \\`expect\\`, or a writer with a ledger`,\n )\n }\n if (write.increments.length > 0 && writer.increments !== true) {\n throw new Error(\n `[foldkit-remote-server] write \"${mutation.name}\" increments a field, but its writer for ${writer.entity} does not add one (increments)`,\n )\n }\n // Concurrent increments land in either order: one result only where adding\n // associates, which integers do and floating-point reals do not.\n const real = write.increments.find(\n increment => !SchemaShape.holdsIntegers(Schema.toEncoded(increment.field.schema).ast),\n )\n if (real !== undefined && write.expect === undefined && writer.pins !== true) {\n throw new Error(\n `[foldkit-remote-server] write \"${mutation.name}\" increments \"${real.field.key}\", a real number, and expects no revision; adding reals does not associate, so concurrent increments could land as two different sums. Give it \\`expect\\``,\n )\n }\n if (write.assignments.length > 0 && writer.assignments !== true) {\n throw new Error(\n `[foldkit-remote-server] write \"${mutation.name}\" computes a field, but its writer for ${writer.entity} does not compute one (assignments)`,\n )\n }\n if (write.assignments.length > 0 && write.expect === undefined) {\n if (writer.ledger !== true) {\n throw new Error(\n `[foldkit-remote-server] write \"${mutation.name}\" computes a field and expects no revision, so a retry could compute twice; give it \\`expect\\`, or a writer with a ledger`,\n )\n }\n const order = write.assignments.find(\n assignment => writer.pins !== true && writer.commutes?.(assignment) !== true,\n )\n if (order !== undefined) {\n throw new Error(\n `[foldkit-remote-server] write \"${mutation.name}\" computes \"${order.field.key}\" and expects no revision, but its writer does not show concurrent writes of it land as one result (its operator commuting and associating, tested); give it \\`expect\\``,\n )\n }\n }\n const refused = writer.refuses?.(write) ?? []\n if (refused.length > 0) {\n throw new Error(\n `[foldkit-remote-server] write \"${mutation.name}\" cannot land through its writer for ${writer.entity}: ${refused.join('; ')}`,\n )\n }\n const kind = Match.value(write).pipe(\n Match.tagsExhaustive({\n Insert: () => ({ hasBefore: false, inserts: true, deletes: false }),\n Update: () => ({ hasBefore: true, inserts: false, deletes: false }),\n Delete: () => ({ hasBefore: false, inserts: false, deletes: true }),\n }),\n )\n // An update judges every invariant; an insert, with no row before, the state ones alone.\n const judged = Entity.invariants(write.input.entity).filter(\n held => kind.hasBefore || !Entity.readsBefore(held),\n )\n if (judged.length > 0 && writer.invariants !== true) {\n throw new Error(\n `[foldkit-remote-server] write \"${mutation.name}\" writes ${writer.entity}, which has invariants, but its writer does not judge them (invariants)`,\n )\n }\n // An insert's row is its values and its links (a `one` relation an invariant reads as the\n // id it points at): a member it leaves to a default the writer cannot judge.\n if (kind.inserts) {\n const sets = new Set([\n 'id',\n ...write.sets.map(set => set.field.key),\n ...write.links.map(link => link.relation.key),\n ...write.context.map(({ member }) => member.key),\n ])\n const unset = judged.flatMap(held =>\n held.after.filter(key => !sets.has(key)).map(key => `${held.id} reads ${key}`),\n )\n if (unset.length > 0) {\n throw new Error(\n `[foldkit-remote-server] insert \"${mutation.name}\" leaves unset a field an invariant reads (${unset.join('; ')})`,\n )\n }\n }\n if (Option.isSome(write.when) && writer.preconditions !== true) {\n throw new Error(\n `[foldkit-remote-server] write \"${mutation.name}\" has a precondition, but its writer for ${writer.entity} does not check one (preconditions)`,\n )\n }\n const encodeInput = Schema.encodeUnknownEffect(\n write.input.schema as unknown as Schema.Codec<unknown, Readonly<Record<string, unknown>>>,\n )\n // A row's derived members can change only with the rows pointing at it, so a\n // write that wrote names each row its row points at, before and after, whose\n // derived members the link can change: the answer reads what the client shows\n // of each (a post's like count, after a like). A count or an exists changes\n // with the relation it reads; a supplied member, which may read anything, with\n // every one. The links are read as the asker may see the row (`writer.read`),\n // so a write names no row its writer could not have reached by reading; only a\n // writer with no read rule to apply has its links read as stored.\n const pointersOf = (entity: AnyEntity): ReadonlyArray<string> => {\n const relations: Readonly<Record<string, EntityMember>> = entity.relations\n return Object.values(relations).flatMap(relation => {\n if (relation._tag !== 'Relation' || relation.cardinality !== 'one') return []\n const isThis = (read: EntityMember) =>\n read.owner.token === relation.owner.token && read.key === relation.key\n const changes = Object.values(relation.target().derived).some(\n member =>\n member._tag === 'Derived' &&\n Derivation.$match(member.derives, {\n Supplied: () => true,\n Count: ({ relation: read }) => isThis(read),\n Exists: ({ relation: read }) => isThis(read),\n }),\n )\n return changes ? [relation.key] : []\n })\n }\n const pointers = pointersOf(write.input.entity)\n // Every Entity a delete of this one removes rows of, by name, and what each points at\n // whose derived members the removal moves: the answer re-reads them as it does the row's.\n const cascadePointers = new Map<string, ReadonlyArray<string>>()\n if (kind.deletes) {\n const named = (entity: AnyEntity) =>\n Entity.restricting(entity)\n .map(({ relation, owner }) => `${owner.name}.${relation.key}`)\n .join(', ')\n const reach = (entity: AnyEntity): void => {\n for (const { owner } of Entity.cascading(entity)) {\n if (cascadePointers.has(owner.name)) continue\n // A row the cascade takes would need the refusal, or the clearing, too.\n if (Entity.clearing(owner).length > 0) {\n throw new Error(\n `[foldkit-remote-server] delete \"${mutation.name}\" removes ${write.input.entity.name}, whose cascade takes ${owner.name} rows, whose links ${Entity.clearing(\n owner,\n )\n .map(({ relation, owner: from }) => `${from.name}.${relation.key}`)\n .join(\n ', ',\n )} clear (onDelete: 'setNull'); a cascade into such an Entity is not supported`,\n )\n }\n if (Entity.restricting(owner).length > 0) {\n throw new Error(\n `[foldkit-remote-server] delete \"${mutation.name}\" removes ${write.input.entity.name}, whose cascade takes ${owner.name} rows, which ${named(owner)} restricts (onDelete: 'restrict'); a cascade into a restricted Entity is not supported: restrict ${write.input.entity.name} instead, or cascade ${owner.name}'s pointers too`,\n )\n }\n cascadePointers.set(owner.name, pointersOf(owner))\n reach(owner)\n }\n }\n reach(write.input.entity)\n if (cascadePointers.size > 0 && writer.cascades !== true) {\n throw new Error(\n `[foldkit-remote-server] delete \"${mutation.name}\" removes ${write.input.entity.name}, whose rows take ${[...cascadePointers.keys()].join(', ')} with them (onDelete: 'cascade'), but its writer does not remove them (cascades)`,\n )\n }\n if (Entity.restricting(write.input.entity).length > 0 && writer.restricts !== true) {\n throw new Error(\n `[foldkit-remote-server] delete \"${mutation.name}\" removes ${write.input.entity.name}, which ${named(write.input.entity)} restricts (onDelete: 'restrict'), but its writer does not refuse a row they point at (restricts)`,\n )\n }\n const cleared = Entity.clearing(write.input.entity)\n if (cleared.length > 0 && writer.clears !== true) {\n throw new Error(\n `[foldkit-remote-server] delete \"${mutation.name}\" removes ${write.input.entity.name}, whose rows ${cleared.map(({ relation, owner }) => `${owner.name}.${relation.key}`).join(', ')} point at (onDelete: 'setNull'), but its writer does not clear them (clears)`,\n )\n }\n }\n /** What a removed row pointed at that its removal moves, as refs. */\n const pointedBy = (row: CascadedRow): ReadonlyArray<EntityRef> =>\n (cascadePointers.get(row.entity) ?? []).flatMap(key =>\n Option.match(Option.flatten(Option.fromUndefinedOr(row.links[key])), {\n onNone: () => [],\n onSome: ref => [ref],\n }),\n )\n const seenLinks = (\n id: string,\n principal: P,\n ): Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R> =>\n writer.read !== undefined\n ? writer.read({ id, fields: pointers, principal })\n : writer.linked !== undefined\n ? writer.linked({ id, relations: pointers })\n : Effect.succeed(Option.none())\n const pointedAt = (\n id: string,\n principal: P,\n ): Effect.Effect<ReadonlyArray<EntityRef>, RemoteServerError, R> =>\n pointers.length === 0\n ? Effect.succeed([])\n : Effect.map(seenLinks(id, principal), held =>\n Option.match(held, {\n onNone: () => [],\n onSome: links =>\n pointers.flatMap(key => {\n const ref = Object.hasOwn(links, key) ? links[key] : undefined\n return typeof ref === 'string' ? [refParts(ref)] : []\n }),\n }),\n )\n const naming = <A extends object>(outcome: A, pointed: ReadonlyArray<EntityRef>) =>\n pointed.length === 0 ? outcome : { ...outcome, pointed }\n return {\n mutation: mutation.name,\n writes: { entity: writer.entity, writer, write },\n Input: mutation.Input,\n Output: mutation.Output,\n Refusal: mutation.Refusal,\n run: ({ input, principal, viewer, keys, operation, now, read }) => {\n /** A path from the viewer, read through the server's sources: a row hidden or gone is null. */\n const context = Write.contextValues(write, { viewer, now: Option.some(now) }, (row, key) =>\n Effect.map(read(row, [key]), found =>\n Held.of(\n Option.match(found, {\n onNone: () => null,\n // A withheld member is missing: never `Object`'s of the same name.\n onSome: values => (Object.hasOwn(values, key) ? values[key] : undefined),\n }),\n ),\n ),\n )\n // A member set from who asks, with nothing to set it from: a visitor is\n // asked to sign in, anyone else refused (#403).\n const unfilled = Option.isNone(viewer)\n ? RemoteServer.unauthenticated()\n : RemoteServer.forbid()\n const given = input as never\n const expect = Write.expected(write, given)\n const conflict = (bound: { readonly entity: string; readonly id: string }) =>\n RemoteServer.refuse(\n mutation,\n { _tag: 'Conflict' },\n `${bound.entity} ${bound.id} changed since it was read`,\n )\n // The body reads the input as a query's does: encoded, by its keys.\n const when = Option.match(write.when, {\n onNone: () => Effect.succeed(Option.none<WriteWhen>()),\n onSome: body =>\n encodeInput(given).pipe(\n Effect.map(encoded => Option.some({ body, input: encoded })),\n Effect.mapError(\n () => new RemoteServerError({ message: `${mutation.name}'s input did not encode` }),\n ),\n ),\n })\n const unmet = <A>(\n bound: { readonly entity: string; readonly id: string },\n writing: Effect.Effect<\n A,\n | RemoteServerError\n | RemoteForbidden\n | RemoteUnauthenticated\n | RemoteUnmet\n | RemoteInvalid,\n R\n >,\n ) =>\n Effect.catchTag(\n writing,\n 'RemoteUnmet',\n (): Effect.Effect<never, RemoteServerError | MutationRefused> =>\n Option.isNone(write.when)\n ? // A writer unmet with no precondition to meet is wrong, and the\n // mutation declares no such refusal: the server's error, not one.\n Effect.fail(\n new RemoteServerError({\n message: `${writer.entity}'s writer refused ${mutation.name}, which has no precondition, as unmet`,\n }),\n )\n : Effect.fail(\n RemoteServer.refuse(\n mutation,\n { _tag: 'Unmet' },\n `${bound.entity} ${bound.id} does not hold what ${mutation.name} asks of it`,\n ),\n ),\n )\n // The writer judged the row it would leave; the client is told what the writer said.\n const invalid = <A>(\n writing: Effect.Effect<\n A,\n | RemoteServerError\n | RemoteForbidden\n | RemoteUnauthenticated\n | MutationRefused\n | RemoteInvalid,\n R\n >,\n ) =>\n Effect.catchTag(writing, 'RemoteInvalid', refused =>\n Effect.fail(\n RemoteServer.refuse(\n mutation,\n {\n _tag: 'Invalid',\n // A writer judges the row it writes, so the invariant is that row's Entity's.\n entity: Option.some(write.input.entity.name),\n rule: refused.rule,\n message: refused.message,\n path: refused.path,\n },\n refused.message,\n ),\n ),\n )\n const answered = (bound: BoundWrite, values: Readonly<Record<string, unknown>>) => {\n const read = writer.read\n const shown =\n read === undefined\n ? Effect.succeed(Option.some(values))\n : read({ id: bound.id, fields: Object.keys(values), principal })\n return Effect.map(\n shown,\n Option.match({\n onNone: () => ({\n output: {},\n entities: [],\n connections: [],\n deleted: [{ entity: bound.entity, id: bound.id }],\n }),\n onSome: seen => ({\n output: {},\n entities: [{ entity: bound.entity, id: bound.id, values: seen }],\n connections: [],\n deleted: [],\n }),\n }),\n )\n }\n // What a ledger tells a retry from another use of its operation id by.\n const request = encodeInput(given).pipe(\n Effect.map(encoded => JSON.stringify([mutation.name, keys ?? null, encoded])),\n Effect.mapError(\n () => new RemoteServerError({ message: `${mutation.name}'s input did not encode` }),\n ),\n )\n return Match.value(write).pipe(\n Match.tagsExhaustive({\n Update: () =>\n Effect.gen(function* () {\n const named = Write.bind(write, given, keys)\n // An update sets what its Entity sets `on: 'write'`, whichever keys it names.\n const set = yield* context\n if (set.unfilled.length > 0) return yield* Effect.fail(unfilled)\n const bound = {\n ...named,\n values: { ...named.values, ...set.values },\n links: { ...named.links, ...set.links },\n }\n const before = yield* pointedAt(bound.id, principal)\n if (\n write.increments.length + write.assignments.length > 0 &&\n write.expect === undefined &&\n Option.isNone(operation)\n ) {\n // The ledger keys a write by its operation: with none, a retry could add twice.\n return yield* new RemoteServerError({\n message: `${mutation.name} moves a field with no revision, so it needs an operation id`,\n })\n }\n const written = yield* invalid(\n unmet(\n bound,\n writer.update({\n id: bound.id,\n operation,\n request: yield* request,\n values: bound.values,\n increments: bound.increments,\n assignments: bound.assignments,\n links: bound.links,\n expect,\n when: yield* when,\n principal,\n }),\n ),\n )\n if (Option.isSome(written))\n return naming(yield* answered(bound, written.value), [\n ...before,\n ...(yield* pointedAt(bound.id, principal)),\n ])\n return yield* Option.isSome(expect)\n ? Effect.fail(conflict(bound))\n : Effect.fail(\n new RemoteServerError({\n message: `No ${bound.entity} ${bound.id} to update`,\n }),\n )\n }),\n // Written whole: there is no row a client could have changed some keys of.\n Insert: () =>\n Effect.gen(function* () {\n const bound = Write.bind(write, given)\n const set = yield* context\n // A visitor, a viewer of another Entity, or a path reaching no row.\n if (set.unfilled.length > 0) return yield* Effect.fail(unfilled)\n const row = yield* invalid(\n writer\n .insert({\n id: bound.id,\n values: { ...bound.values, ...set.values },\n links: { ...bound.links, ...set.links },\n operation,\n request: yield* request,\n principal,\n })\n .pipe(\n // Built from the request alone: the row there may be hidden from who asked.\n Effect.catchTag('RemoteTaken', () =>\n Effect.fail(\n RemoteServer.refuse(\n mutation,\n {\n _tag: 'Taken',\n entity: bound.entity,\n id: bound.id,\n },\n `${bound.entity} ${bound.id} is already taken`,\n ),\n ),\n ),\n ),\n )\n return naming(yield* answered(bound, row), yield* pointedAt(bound.id, principal))\n }),\n Delete: () =>\n Effect.gen(function* () {\n const bound = Write.bind(write, given)\n const before = yield* pointedAt(bound.id, principal)\n const outcome = yield* invalid(\n unmet(\n bound,\n writer.delete({ id: bound.id, expect, when: yield* when, principal }),\n ),\n )\n const gone = (cascaded: ReadonlyArray<CascadedRow>) => ({\n output: {},\n entities: [],\n connections: [],\n deleted: [\n { entity: bound.entity, id: bound.id },\n ...cascaded.map(({ entity, id }) => ({ entity, id })),\n ],\n })\n return yield* DeleteOutcome.$match(outcome, {\n // Gone already is gone: only a revision the row moved past refuses.\n Moved: () => Effect.fail(conflict(bound)),\n // Named by the relation alone: the rows pointing may be hidden from who asked.\n Referenced: ({ entity, relation }) =>\n Effect.fail(\n RemoteServer.refuse(\n mutation,\n Refusal.referenced.make({ entity, relation }),\n `${bound.entity} ${bound.id} is still pointed at through ${entity}.${relation}`,\n ),\n ),\n // A delete that wrote nothing (the row gone, or hidden from its\n // writer) names nothing more, so it answers alike either way.\n Absent: () => Effect.succeed(gone([])),\n // A row whose link was cleared is read again, so its answer shows the link gone.\n Deleted: ({ cascaded, cleared }) =>\n Effect.succeed(\n naming(gone(cascaded), [\n ...before,\n ...cascaded.flatMap(pointedBy),\n ...cleared,\n ]),\n ),\n })\n }),\n }),\n )\n },\n }\n },\n\n query: <P = unknown, R = never, Input = unknown>(\n query: QueryDescriptor<string, Input, ConnectionSpec>,\n run: (context: {\n readonly input: Input\n readonly window: QueryWindow\n readonly principal: P\n /** As `EntitySourceContext.viewer`. */\n readonly viewer?: Option.Option<EntityRef> | undefined\n readonly select?: RelationRequirement | undefined\n }) => Effect.Effect<QueryPage, RemoteServerError, R>,\n ): QuerySource<P, R> => ({\n query: query.name,\n entity: query.Result.entity,\n Input: query.Input,\n ...(query.cache === undefined ? {} : { cache: query.cache }),\n run: context =>\n run({\n input: context.input as Input,\n window: context.window,\n principal: context.principal,\n viewer: context.viewer,\n ...(context.select === undefined ? {} : { select: context.select }),\n }),\n }),\n\n /**\n * Reads through `source` as the read handlers and the live hub do: only the\n * asked fields the source declares and its `authorize` allows, each record\n * through its `filter` and holding no other field. None when the principal\n * may read none of the fields asked. What a live source of its own reads\n * with, so it sends no more than a read would.\n */\n readAs,\n\n /**\n * The fields of `fields` that `readAs` reads for `principal`: those the\n * source declares and its `authorize` allows, in the order asked. Asks\n * nothing of the store.\n */\n allowedFields,\n\n /** Streams live entity patches for a client's live requirements. */\n live: <P = unknown, R = never>(\n entity: EntityName,\n options: { readonly subscribe: LiveSource<P, R>['subscribe'] },\n ): LiveSource<P, R> => ({\n entity: entity.name,\n subscribe: options.subscribe,\n }),\n\n /**\n * A `LiveHub` over entity sources. Pass it to `handlers` as `live`, and every\n * mutation's answered patches and deletions are published to it; call\n * `hub.changed(ref, fields)` yourself only for a write that is not a\n * mutation (a database trigger, a job). Each subscriber that selects any of\n * those fields receives them, re-read through the entity source under its\n * own principal.\n */\n liveHub,\n\n /**\n * The server: its sources by name. `viewer` says who asks, as a row\n * (`principal => Option.some(Remote.ref(User, principal.id))`), or none for\n * a visitor: what a declared write's `Expr.viewer` sets. A server\n * registering such an insert without one is refused here. It is also whom\n * each answer says it is for (`principal`, the row's key), which a durable\n * write carries back: one made for another viewer than who asks is refused\n * before it runs (`RemotePrincipalChanged`). A server without `viewer`\n * names no one in its answers, and refuses a write that names someone,\n * since it cannot check it; a write that names no one runs (#405).\n *\n * `clockSkew` is how far from this server's clock a client's time (the\n * `now` a write is sent with, when the reader acted) may be and still be\n * the write's time: 60 seconds unless given, and `0` to never take it. A\n * time beyond it is replaced by the server's own, and reported as\n * `ClockSkewed`. It bounds how far a client can backdate or postdate a row.\n */\n make: <P = unknown, R = never>(config: {\n readonly entities: readonly EntitySource<P, R>[]\n readonly mutations?: readonly MutationSource<P, R>[]\n readonly queries?: readonly QuerySource<P, R>[]\n readonly live?: readonly LiveSource<P, R>[]\n readonly viewer?: ((principal: P) => Option.Option<EntityRef>) | undefined\n readonly clockSkew?: Duration.Input | undefined\n }): ServerDefinition<P, R> => {\n // A path from the viewer is read through the sources this server mounts.\n const served = new Set(config.entities.map(source => source.entity))\n for (const source of config.mutations ?? []) {\n const reads = source.writes === undefined ? [] : Write.contextReads(source.writes.write)\n const unserved = reads.filter(entity => !served.has(entity))\n if (unserved.length > 0) {\n throw new Error(\n `[foldkit-remote-server] write \"${source.mutation}\" sets a member from a path through ${unserved.join(', ')}, which no source of this server serves; mount one in entities`,\n )\n }\n }\n if (config.viewer === undefined) {\n const viewing = (config.mutations ?? []).find(source =>\n (source.writes?.write.context ?? []).some(({ value }) => value._tag === 'Viewer'),\n )\n if (viewing !== undefined) {\n throw new Error(\n `[foldkit-remote-server] write \"${viewing.mutation}\" sets a member to whoever asks (Expr.viewer), but the server has no viewer; give RemoteServer.make a viewer`,\n )\n }\n const reading = config.entities.find(source => (source.perViewer ?? []).length > 0)\n if (reading !== undefined) {\n throw new Error(\n `[foldkit-remote-server] ${reading.entity}'s ${reading.perViewer!.join(', ')} depend on who reads them (Derived.exists), but the server has no viewer; give RemoteServer.make a viewer`,\n )\n }\n }\n return {\n entities: new Map(config.entities.map(source => [source.entity, source])),\n mutations: new Map((config.mutations ?? []).map(source => [source.mutation, source])),\n queries: new Map((config.queries ?? []).map(source => [source.query, source])),\n live: new Map((config.live ?? []).map(source => [source.entity, source])),\n viewer: config.viewer,\n // Read here, so a bound that is no duration fails where it is given.\n ...(config.clockSkew === undefined\n ? {}\n : { clockSkew: Duration.fromInputUnsafe(config.clockSkew) }),\n }\n },\n\n /**\n * Checks every source name against the declared domain, so an undeclared\n * entity/query/mutation fails at startup rather than returning nothing at\n * call time.\n */\n validate: (domain: RemoteDescriptor, server: ServerDefinition<any, any>): void => {\n const assertDeclared = (\n kind: string,\n declared: ReadonlyMap<string, unknown>,\n names: Iterable<string>,\n ): void => {\n for (const name of names) {\n if (!declared.has(name))\n throw new Error(`RemoteServer: ${kind} \"${name}\" is not declared in the Remote domain`)\n }\n }\n assertDeclared('entity', domain.registry.entities, server.entities.keys())\n assertDeclared('query', domain.registry.queries, server.queries.keys())\n assertDeclared('mutation', domain.registry.mutations, server.mutations.keys())\n },\n\n /**\n * Reads entity requirements through the entity sources, level by level,\n * following relations as `FoldkitRemoteRead` does. Shared by the read\n * handler and the query handler's payload: a query page's items are just\n * requirements the page names, so one response carries both.\n */\n readHelper: <P, R>(\n server: ServerDefinition<P, R>,\n principal: P,\n options: HandlerOptions<P, R>,\n requests: ReadonlyArray<Requirement>,\n ): Effect.Effect<\n {\n readonly entities: Array<{\n readonly entity: string\n readonly id: string\n readonly values: Record<string, unknown>\n }>\n readonly settled: Array<{\n readonly entity: string\n readonly id: string\n readonly fields: Array<string>\n }>\n },\n RemoteReadError,\n R\n > =>\n Effect.gen(function* () {\n const entities: Array<{\n readonly entity: string\n readonly id: string\n readonly values: Record<string, unknown>\n }> = []\n const settled = new Map<string, { entity: string; id: string; fields: Set<string> }>()\n const settle = (entity: string, id: string, fields: ReadonlyArray<string>): void => {\n if (fields.length === 0) return\n const key = `${entity}:${id}`\n const entry = settled.get(key) ?? { entity, id, fields: new Set<string>() }\n for (const field of fields) entry.fields.add(field)\n settled.set(key, entry)\n }\n const fetched = new Map<string, Set<string>>()\n const fetchedValues = new Map<string, Record<string, unknown>>()\n const viewer = viewerOf(server, principal)\n const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH\n const maxIds = Math.max(1, options.maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY)\n\n const over = checkIdsPerEntity(requests, maxIds)\n if (over !== undefined) {\n return yield* new RemoteReadError({ message: `Too many \"${over}\" ids in one read batch` })\n }\n const paged = checkPagesPerRelation(requests)\n if (paged !== undefined) {\n return yield* new RemoteReadError({ message: `Too many pages of \"${paged}\" in one read` })\n }\n\n let pending: ReadonlyArray<Requirement> = requests\n for (let depth = 0; pending.length > 0; depth++) {\n if (depth > maxDepth) {\n return yield* new RemoteReadError({\n message: `Nested selection deeper than ${maxDepth} relation levels`,\n })\n }\n const next: Requirement[] = []\n\n const follow = (\n values: Record<string, unknown>,\n relations: Readonly<Record<string, RelationRequirement>>,\n ): void => {\n for (const [field, relation] of Object.entries(relations)) {\n if (!Object.hasOwn(values, field)) continue\n for (const ref of refsIn(values[field])) {\n if (ref.entity !== relation.entity) continue\n const key = `${relation.entity}:${ref.id}`\n const read = fetched.get(key)\n const fields = relation.fields.filter(name => read?.has(name) !== true)\n if (fields.length > 0) {\n next.push({\n entity: relation.entity,\n id: ref.id,\n fields,\n ...(relation.windows === undefined ? {} : { windows: relation.windows }),\n ...(relation.relations === undefined ? {} : { relations: relation.relations }),\n })\n } else if (relation.relations !== undefined) {\n follow(fetchedValues.get(key) ?? {}, relation.relations)\n }\n }\n }\n }\n\n for (const { ids, slice, renames } of groupByEntity(pending)) {\n const name = slice.entity\n const source = server.entities.get(name)\n if (source === undefined) continue\n const allowed = allowedFields(source, principal, slice.fields)\n const allowedSet = new Set(allowed)\n const idList = [...ids.keys()]\n for (const [id, asked] of ids) {\n settle(\n name,\n id,\n [...asked]\n .filter(field => !allowedSet.has(field))\n .map(field => renamed(renames, field)),\n )\n }\n if (allowed.length === 0) continue\n\n const windows = windowsOf(slice.windows, allowed)\n const records = yield* readFiltered(source, principal, allowed, fields =>\n Effect.map(\n Effect.forEach(\n Array.from({ length: Math.ceil(idList.length / maxIds) }, (_, chunk) =>\n idList.slice(chunk * maxIds, (chunk + 1) * maxIds),\n ),\n chunk => source.read({ ids: chunk, fields, principal, viewer, ...windows }),\n ),\n chunks => chunks.flat(),\n ),\n ).pipe(\n Effect.catchTag('RemoteServerError', error =>\n Effect.fail(new RemoteReadError({ message: error.message })),\n ),\n )\n\n for (const record of records) {\n const values: Record<string, unknown> = Object.create(null)\n const omitted: string[] = []\n const asked = ids.get(record.id)\n for (const field of allowed) {\n if (Object.hasOwn(record.values, field))\n values[renamed(renames, field)] = record.values[field]\n else if (asked?.has(field) === true) omitted.push(renamed(renames, field))\n }\n entities.push({ entity: name, id: record.id, values })\n settle(name, record.id, omitted)\n\n const key = `${name}:${record.id}`\n const known = fetched.get(key) ?? new Set<string>()\n for (const field of allowed) known.add(renamed(renames, field))\n fetched.set(key, known)\n fetchedValues.set(key, { ...fetchedValues.get(key), ...values })\n\n follow(values, slice.relations ?? {})\n }\n }\n pending = next.flatMap(request => {\n const read = fetched.get(`${request.entity}:${request.id}`)\n const fields = request.fields.filter(field => read?.has(field) !== true)\n return fields.length === 0 ? [] : [{ ...request, fields }]\n })\n }\n\n return {\n entities,\n settled: [...settled.values()].map(entry => ({ ...entry, fields: [...entry.fields] })),\n }\n }),\n\n /**\n * Answers one JSON request through `handlers`: what an HTTP endpoint, a\n * worker or a server in the page calls with the body it received, parsed.\n * The request and its payload are decoded by the protocol's own schemas\n * before a handler sees them, so an operation name is one of Remote's three\n * and nothing else. A body that is not a request is a 400; a caller who\n * could not be told a 401; a refusal of who is asking a 403; a write made\n * for someone else (`RemotePrincipalChanged`) a 409; a mutation's\n * declared refusal a 422, or a 409 when it is `Refusal.taken`; a handler's\n * failure a 500 with its message; a defect a 500 that says nothing of it,\n * its cause reported as a `ServerDefect` (`Diagnostics`, by default the log).\n * `Remote.json` and `Remote.http` are the other end.\n */\n answer: <R>(\n handlers: RemoteRpcClient<R>,\n body: unknown,\n ): Effect.Effect<\n {\n readonly status: 200 | 400 | 401 | 403 | 409 | 422 | 500\n readonly body: RemoteJsonAnswer\n },\n never,\n R\n > => {\n const asked = {\n read: (payload: unknown) =>\n Effect.flatMap(Schema.decodeUnknownEffect(ReadBatch)(payload), handlers.FoldkitRemoteRead),\n query: (payload: unknown) =>\n Effect.flatMap(\n Schema.decodeUnknownEffect(QueryRequest)(payload),\n handlers.FoldkitRemoteQuery,\n ),\n mutate: (payload: unknown) =>\n Effect.flatMap(\n Schema.decodeUnknownEffect(MutationRequest)(payload),\n handlers.FoldkitRemoteMutate,\n ),\n }\n return Schema.decodeUnknownEffect(RemoteJsonRequest)(body).pipe(\n Effect.flatMap(({ operation, payload }): Effect.Effect<unknown, AnswerError, R> =>\n asked[operation](payload),\n ),\n Effect.map(result => ({ status: 200 as const, body: { result } })),\n Effect.catchTag('SchemaError', error =>\n Effect.succeed({ status: 400 as const, body: { error: error.message } }),\n ),\n Effect.catchTag('Unauthenticated', error => Effect.succeed(unauthenticatedAnswer(error))),\n // Not the asker's refusal, and not the write's: who is signed in changed.\n Effect.catchTag('PrincipalChanged', error =>\n Effect.succeed({\n status: 409 as const,\n body: { error: error.message, principalChanged: {} },\n }),\n ),\n Effect.catchTag('Forbidden', error =>\n Effect.succeed({\n status: 403 as const,\n body: {\n error: error.message,\n forbidden: error.reason === undefined ? {} : { reason: error.reason },\n },\n }),\n ),\n // A refusal is the mutation's answer, not a failure of the server.\n Effect.catchTag('RemoteMutationError', error =>\n Effect.succeed(\n error.refusal === undefined\n ? { status: 500 as const, body: { error: error.message } }\n : {\n status:\n Refusal.isTaken(error.refusal) || Refusal.isReferenced(error.refusal)\n ? (409 as const)\n : (422 as const),\n body: { error: error.message, refusal: error.refusal },\n },\n ),\n ),\n Effect.catch(error =>\n Effect.succeed({ status: 500 as const, body: { error: error.message } }),\n ),\n // A defect is a bug on this side: the caller learns there was one, not what,\n // and whoever runs the server learns what.\n Effect.catchCause(cause =>\n Diagnostics.report(serverDefect(cause)).pipe(\n Effect.as({ status: 500 as const, body: { error: 'Internal error' } }),\n ),\n ),\n )\n },\n\n /**\n * Compiles the server into Remote's RPC handlers, answering as `principal`:\n * a value, or a Context key (`G.Principal`) read on each call, which\n * authentication provides per request. Unknown entities, entities with no\n * allowed fields, and unknown mutations return an error or nothing rather\n * than leaking existence.\n */\n handlers: <P, R, I = never>(\n server: ServerDefinition<P, R>,\n principal: P | Context.Key<I, P>,\n options: HandlerOptions<P, R> = {},\n ): RemoteRpcClient<R | I> => {\n // A Context key is read on each call, so one handler set answers every request.\n const asking: Effect.Effect<P, never, I> = Context.isKey(principal)\n ? principal\n : Effect.succeed(principal)\n return {\n FoldkitRemoteRead: Effect.fn('RemoteServer.FoldkitRemoteRead')(function* (payload) {\n const mismatch = protocolMismatch(payload.version)\n if (mismatch !== undefined) return yield* mismatch\n const caller = yield* asking\n return {\n ...(yield* RemoteServer.readHelper(server, caller, options, payload.requests)),\n ...answeredFor(server, caller),\n }\n }),\n\n FoldkitRemoteMutate: Effect.fn('RemoteServer.FoldkitRemoteMutate')(function* (payload) {\n const source = server.mutations.get(payload.mutation)\n if (source === undefined) {\n return yield* new RemoteMutationError({\n message: `Unknown mutation: ${payload.mutation}`,\n })\n }\n\n const input = yield* Schema.decodeUnknownEffect(source.Input)(payload.input).pipe(\n Effect.catchTag('SchemaError', () =>\n Effect.fail(new RemoteMutationError({ message: 'Invalid mutation input' })),\n ),\n )\n\n // Judged before the write runs, so its bounds are the request's, not the outcome's.\n const lists = admitLists(\n server,\n payload.lists ?? [],\n Math.max(1, options.maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY),\n )\n const caller = yield* asking\n yield* madeFor(server, caller, Option.fromUndefinedOr(payload.principal))\n const outcome = yield* source\n .run({\n input,\n principal: caller,\n viewer: server.viewer === undefined ? Option.none() : server.viewer(caller),\n requestId: payload.requestId,\n operation: Option.fromUndefinedOr(payload.operation),\n now: yield* writeTime(server, payload.mutation, Option.fromUndefinedOr(payload.now)),\n read: withServices(rowAs(server, caller), yield* Effect.context<R>()),\n keys: payload.keys,\n })\n .pipe(\n Effect.catchTag('RemoteServerError', error =>\n Effect.fail(new RemoteMutationError({ message: error.message })),\n ),\n Effect.catchTag('MutationRefused', refused =>\n refusalError(source.Refusal, payload.mutation, refused),\n ),\n )\n\n const output = yield* Schema.encodeUnknownEffect(source.Output)(outcome.output).pipe(\n Effect.catchTag('SchemaError', () =>\n Effect.fail(new RemoteMutationError({ message: 'Invalid mutation output' })),\n ),\n )\n\n const read = yield* answerRead(server, caller, options, payload.shown ?? [], outcome).pipe(\n // The write has committed: answering without the read leaves the\n // client to fetch those fields, where failing would have it retry.\n Effect.catchTag('RemoteReadError', error =>\n Diagnostics.report(answerUnread(payload.mutation, error.message)).pipe(\n Effect.as(Option.none()),\n ),\n ),\n )\n\n // Each list read after the write, as a query of it is; one that fails is\n // left out, for the client to ask for again.\n const answered = yield* Effect.forEach(lists, request =>\n answerQuery(server, caller, options, request).pipe(\n Effect.map(result => [{ request, result }]),\n Effect.catchTag('RemoteQueryError', error =>\n Diagnostics.report(\n answerUnread(payload.mutation, `list \"${request.query}\": ${error.message}`),\n ).pipe(Effect.as([])),\n ),\n ),\n ).pipe(Effect.map(pages => pages.flat()))\n\n // What the mutation answers is what changed, so live subscribers hear it\n // without the handler naming it again. The write has committed by now: a\n // failed publish is logged, never the mutation's failure, which a client\n // would retry.\n const hub = options.live\n if (hub !== undefined) {\n // A declared write's answer is the row as stored; a handler's is its own claim.\n const stored = source.writes !== undefined\n yield* Effect.forEach(outcome.entities, patch =>\n hub.changed(\n { entity: patch.entity, id: patch.id },\n Object.keys(patch.values),\n stored ? patch.values : undefined,\n ),\n ).pipe(\n Effect.andThen(Effect.forEach(outcome.deleted, gone => hub.deleted(gone))),\n Effect.catchCause(cause => Diagnostics.report(publishFailed(payload.mutation, cause))),\n )\n }\n\n return {\n output,\n entities: outcome.entities.map(patch => ({\n entity: patch.entity,\n id: patch.id,\n values: patch.values,\n })),\n connections: outcome.connections,\n deleted: outcome.deleted.map(gone => ({ entity: gone.entity, id: gone.id })),\n ...Option.match(read, { onNone: () => ({}), onSome: value => ({ read: value }) }),\n ...(answered.length === 0 ? {} : { lists: answered }),\n ...answeredFor(server, caller),\n }\n }),\n\n FoldkitRemoteQuery: Effect.fn('RemoteServer.FoldkitRemoteQuery')(function* (payload) {\n const caller = yield* asking\n return {\n ...(yield* answerQuery(server, caller, options, payload)),\n ...answeredFor(server, caller),\n }\n }),\n\n FoldkitRemoteLive: payload => {\n const mismatch = protocolMismatch(payload.version)\n if (mismatch !== undefined) return Stream.fail(mismatch)\n // Admitted once, before any live source or the hub is asked, so every\n // live path is held to the bounds a read is.\n const maxIds = Math.max(1, options.maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY)\n const refusal = liveRefusal(payload.requirements, maxIds)\n if (refusal !== undefined) return Stream.fail(refusal)\n return Stream.unwrap(\n Effect.gen(function* () {\n const admitted = yield* admitQueries(\n server,\n payload.queries ?? [],\n payload.requirements,\n maxIds,\n )\n const caller = yield* asking\n const viewer = viewerOf(server, caller)\n const queries: ReadonlyArray<LiveQuery<R>> = admitted.map(\n ({ request, select, source, input }) => ({\n identity: queryIdentity(request.query, request.input),\n select,\n edges: Effect.map(\n source.run({ input, window: request.window, principal: caller, viewer, select }),\n page => page.edges,\n ),\n }),\n )\n const entities = [\n ...new Set([\n ...payload.requirements.map(request => request.entity),\n ...queries.map(query => query.select.entity),\n ]),\n ]\n const streams: Array<Stream.Stream<LiveChangeValue, RemoteServerError, R>> =\n entities.flatMap(entity => {\n const source = server.live.get(entity)\n if (source === undefined) return []\n return [\n source.subscribe({\n requirements: payload.requirements.filter(request => request.entity === entity),\n queries: queries.filter(query => query.select.entity === entity),\n after: payload.after,\n principal: caller,\n viewer,\n }),\n ]\n })\n if (options.live !== undefined) {\n streams.push(\n options.live.subscribe({\n requirements: payload.requirements,\n after: payload.after,\n principal: caller,\n viewer,\n }),\n )\n }\n // An entity with no live source simply contributes nothing; the client's\n // planner refetches it rather than the stream failing.\n return Stream.mergeAll(streams, { concurrency: 'unbounded' }).pipe(\n // Each source numbers its changes from `after` on its own, and the client\n // keeps one cursor for the stream, so two sources' would read as repeats.\n Stream.mapAccum(\n () => payload.after,\n (cursor, change) => [cursor + 1, [{ ...change, cursor: cursor + 1 }]] as const,\n ),\n Stream.mapError(error => new RemoteLiveError({ message: error.message })),\n )\n }),\n )\n },\n }\n },\n}\n\nexport * from './evaluate.js'\nexport { bodyLimit } from './body.js'\nexport type {\n AnswerUnread,\n CachedReadDiffers,\n ClockSkewed,\n PublishFailed,\n RemoteServerDiagnostic,\n ServerDefect,\n} from './diagnostics.js'\n"],"mappings":";;;;;;;;;;;;AAUA,MAAM,SAAS;AA8Df,MAAa,gBAAgB,WAA+C;CAC1E,MAAM;CACN;CACA,OAAO;CACP,SAAS,gFAAgF,MAAM,OAAO,KAAK;CAC3G;AACF;AAEA,MAAa,gBAAgB,UAAkB,YAAkC;CAC/E,MAAM;CACN;CACA,OAAO;CACP,SAAS,GAAG,SAAS,6CAA6C,O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AAO,CACL,OAAO,UAAU;OACf,cAAc,QAAQ,aAAa,QAAO,YAAW,QAAQ,WAAW,MAAM;OAC9E,SAAS,QAAQ,QAAO,UAAS,MAAM,OAAO,WAAW,MAAM;OAC/D,OAAO,QAAQ;OACf,WAAW;OACX;MACF,CAAC,CACH;KACF,CAAC;KACH,IAAI,QAAQ,SAAS,KAAA,GACnB,QAAQ,KACN,QAAQ,KAAK,UAAU;MACrB,cAAc,QAAQ;MACtB,OAAO,QAAQ;MACf,WAAW;MACX;KACF,CAAC,CACH;KAIF,OAAO,OAAO,SAAS,SAAS,EAAE,aAAa,YAAY,CAAC,CAAC,CAAC,KAG5D,OAAO,eACC,QAAQ,QACb,QAAQ,WAAW,CAAC,SAAS,GAAG,CAAC;MAAE,GAAG;MAAQ,QAAQ,SAAS;KAAE,CAAC,CAAC,CACtE,GACA,OAAO,UAAS,UAAS,IAAI,gBAAgB,EAAE,SAAS,MAAM,QAAQ,CAAC,CAAC,CAC1E;IACF,CAAC,CACH;GACF;EACF;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldkit-remote-server",
3
- "version": "0.21.0",
3
+ "version": "0.23.0",
4
4
  "description": "Server sources and handler compilation for foldkit-remote: entities, selection authorization, and normalization.",
5
5
  "keywords": [
6
6
  "foldkit",
@@ -49,8 +49,8 @@
49
49
  "LICENSE"
50
50
  ],
51
51
  "dependencies": {
52
- "foldkit-entity": "0.16.0",
53
- "foldkit-remote": "0.24.0"
52
+ "foldkit-remote": "0.26.0",
53
+ "foldkit-entity": "0.17.0"
54
54
  },
55
55
  "peerDependencies": {
56
56
  "effect": "^4.1.0"
@@ -61,7 +61,7 @@
61
61
  "foldkit": "0.170.0",
62
62
  "tsdown": "^0.23.1",
63
63
  "typescript": "7.0.2",
64
- "foldkit-surface": "0.13.0"
64
+ "foldkit-surface": "0.14.0"
65
65
  },
66
66
  "scripts": {
67
67
  "build": "node ../../scripts/declarations.mjs . && tsdown && node ../../scripts/declared-any.mjs .",
@@ -1 +0,0 @@
1
- {"version":3,"file":"index-pMrHmWZt.d.mts","names":[],"sources":["../src/body.ts","../src/diagnostics.ts","../src/index.ts"],"mappings":";;;;;;;;;;;;;;;;;cA4Ga,YAAS,uBAEnB,GAAG,GAAC,UACO,OAAO,OAAO,mBAAmB,oBAAoB,GAAG,OACjE,OAAO,OACR,mBAAmB,oBACnB,GACA,IAAI,kBAAkB;;UCtGT,qBAAqB;WAC3B;WACA,OAAO,MAAM;;;;;;UAOP,qBAAqB;WAC3B;WACA;;WAEA;;;UAIM,sBAAsB;WAC5B;WACA;WACA,OAAO,MAAM;;;;;;;UAQP,oBAAoB;WAC1B;WACA;;WAEA;;WAEA;;WAEA;;;;;;;;UASM,0BAA0B;WAChC;;WAEA;;;KAIC,yBACR,eACA,eACA,gBACA,cACA;;;;cCmCS,0BAA0B;;;;;;;;;cAY1B,oBAAoB;;;;;;;;;;cAUpB,oBAAoB;;;;;;;;;;;;cAUpB,sBAAsB;;UAOlB;WACN,MAAM;WACN,OAAO,SAAS;;;;;;;;;;;;;;cAQd,wBAAwB;UAQpB;WACN;WACA,QAAQ,SAAS;;UAGX,oBAAoB;WAC1B;WACA;;WAEA,UAAU,SAAS,eAAe;WAClC,WAAW;;;;;;;WAOX,SAAS,OAAO,OAAO;;UAGjB,aAAa,GAAG;WACtB;;WAEA,SAAS;WACT,OACP,SAAS,oBAAoB,OAC1B,OAAO,OAAO,cAAc,eAAe,mBAAmB;;WAE1D,aAAa,WAAW,GAAG;;;;;;WAM3B,UACP,WAAW,GACX,8BACG,OAAO,OAAO,UAAU,mBAAmB;;;;;;;;WAQvC;;;;;;;WAOA,SAAS;;;;;;WAMT,YAAY;;;;;;WAMZ,QAAQ;;;UAIF;;WAEN;;WAEA,QAAQ,QAAQ,iBAAiB;;;;;;;;cAwBtC,SAAU,GAAG,GAAC,QACV,aAAa,GAAG,IAAE,SACjB,oBAAoB,OAC5B,OAAO,OAAO,OAAO,OAAO,cAAc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