foldkit-sync 0.12.0 → 0.12.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/do.d.mts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"do.d.mts","names":[],"sources":["../src/do.ts"],"mappings":";;;;;;iBAyCiB;WACN;;;iBAIM,mBAAmB,SAAS,QAAQ,WAAW,KAAK;;WAE1D,MAAM,KAAK,SAAS;;;;;;;;WAQpB,cACP,KAAK,qBACL,KAAK,QACF,QAAQ,QAAQ,WAAW,QAAQ,WAAW;;;;;;;;WAQ1C,mBACP,SAAS,SACT,KAAK,QACF,OAAO,OAAO,WAAW,uBAAuB;;;;;;;WAO5C,WAEH,KAAK,KACL,SAAS,QAAQ,WAAW,QAAQ,WAAW,eAC5C,OAAO;;;;;;;;;;WAWP;aAEM,OAAO,SAAS;aAChB,QAAQ,WAAW;;;WAIzB,UAAU,WAAW,cAAc,OAAO;;;;;WAK1C,UAEH,WAAW,WACX,WAAW,cACR,oBAAoB,OAAO,OAAO;;;;;;WAOlC,wBAAwB,QAAQ,WAAW,QAAQ;;;;;;;;YASlD,kBAAkB,KAAK,OAAO;WAC3B;;WACA,QAAQ,KAAK,QAAQ,MAAM,MAAM;;;;;;iBAM/B,2BAA2B;EAC1C;;;;;;;;qBAsCW,qBAAsB,SAAS,QAAQ,WAAW,KAAK,YAAU,WACjE,KAAK,qBAAqB,KAAK,gBAAc,QAChD,mBAAmB,SAAS,QAAQ,WAAW,KAAK,MAAM,kBAAkB,KAAK,aACnF,KAAK,qBAAqB,KAAK;EAAU,MAAM,SAAS,UAAU,QAAQ"}
1
+ {"version":3,"file":"do.d.mts","names":[],"sources":["../src/do.ts"],"mappings":";;;;;;iBAyCiB;WACN;;;iBAIM,mBAAmB,SAAS,QAAQ,WAAW,KAAK;;WAE1D,MAAM,KAAK,SAAS;;;;;;;;WAQpB,cACP,KAAK,qBACL,KAAK,QACF,QAAQ,QAAQ,WAAW,QAAQ,WAAW;;;;;;;;WAQ1C,mBACP,SAAS,SACT,KAAK,QACF,OAAO,OAAO,WAAW,uBAAuB;;;;;;;WAO5C,WAEH,KAAK,KACL,SAAS,QAAQ,WAAW,QAAQ,WAAW,eAC5C,OAAO;;;;;;;;;;WAWP;aAEM,OAAO,SAAS;aAChB,QAAQ,WAAW;;;WAIzB,UAAU,WAAW,cAAc,OAAO;;;;;WAK1C,UAEH,WAAW,WACX,WAAW,cACR,oBAAoB,OAAO,OAAO;;;;;;WAOlC,wBAAwB,QAAQ,WAAW,QAAQ;;;;;;;;YASlD,kBAAkB,KAAK,OAAO;WAC3B;;WACA,QAAQ,KAAK,QAAQ,MAAM,MAAM;;;;;;iBAM/B,2BAA2B;EAC1C;;;;;;;;qBAuCW,qBAAsB,SAAS,QAAQ,WAAW,KAAK,YAAU,WACjE,KAAK,qBAAqB,KAAK,gBAAc,QAChD,mBAAmB,SAAS,QAAQ,WAAW,KAAK,MAAM,kBAAkB,KAAK,aACnF,KAAK,qBAAqB,KAAK;EAAU,MAAM,SAAS,UAAU,QAAQ"}
package/dist/do.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"do.mjs","names":[],"sources":["../src/do.ts"],"sourcesContent":["/**\n * `foldkit-sync/do`: serve one document's Sync exchange from a Cloudflare\n * Durable Object, the single writer its journal wants. Each socket the\n * object accepts exchanges against the same journal through `serveJournal`;\n * the replica side already exists as `Sync.transport.socket` over the\n * object's `wss://…` URL, which hears other writers' commits as notices.\n *\n * The class takes its `DurableObject` base as a parameter, so this module\n * imports no worker runtime and loads anywhere:\n *\n * ```ts\n * import { DurableObject } from 'cloudflare:workers'\n *\n * export class SyncHost extends defineDocumentHost(DurableObject, {\n * sync: Todos,\n * openJournal: (_ctx, env) => openTodosJournal(env.DB),\n * resolvePrincipal: request =>\n * Effect.succeed({ actorId: request.headers.get('x-actor') ?? 'anon' }),\n * }) {}\n * ```\n *\n * Open the journal once per object: on the first upgrade, so probes never\n * provision storage. Route one object per document (`idFromName(sync\n * .documentId)`); its in-memory cache and change stream are then exact\n * because nothing else writes.\n */\nimport { type Duration, type Effect, type Layer, Result } from 'effect'\nimport type { RemoteUnauthenticated } from 'foldkit-remote'\nimport type { Journal } from 'foldkit-durable/core'\nimport {\n documentHost,\n type Accepted,\n type DocumentHostOptions,\n type DocumentHostOptionsLayer,\n} from './journal.js'\nimport { checkRevalidate } from './revalidate.js'\nimport type { AuthorizeDecision } from './make.js'\nimport type { Operation, Sync } from './sync.js'\nimport { workerSocket } from './transport.js'\n\n/** The sliver of a Durable Object the host uses: state for the journal to open with. */\nexport interface DocumentHostContext {\n readonly storage?: unknown\n}\n\n/** What `defineDocumentHost` needs of the application, per document. */\nexport interface DocumentHostConfig<Message, Shared, Principal, Env, RP = never> {\n /** The document's contract: its codecs and journal shape. */\n readonly sync: Sync<Message, Shared>\n /**\n * Opens the document's journal, once: on the first upgrade, not on\n * construction, so probes never provision storage. Over D1 (`d1: true`),\n * or the object's SQLite storage through `ctx`. May build with Effect and\n * unwrap; a rejection answers the upgrade with a 500, and the next upgrade\n * tries again.\n */\n readonly openJournal: (\n ctx: DocumentHostContext,\n env: Env,\n ) => Promise<Journal<Operation, Shared, Principal, Operation>>\n /**\n * Who is opening this socket, from the upgrade request. Fails with a\n * `RemoteUnauthenticated` (`foldkit-remote`; `RemoteServer.unauthenticated()`\n * makes one) to refuse it: a 401 carrying its message. A defect is a 500\n * that says nothing of it. What it needs (a session store) comes from\n * `layer`.\n */\n readonly resolvePrincipal: (\n request: Request,\n env: Env,\n ) => Effect.Effect<Principal, RemoteUnauthenticated, RP>\n /**\n * Runs after each exchange's appends and before the reply is read: apply\n * what committed to another store, through `journal.recover`. Takes the\n * environment — a D1 binding, say — and the journal, because both live\n * outside the exchange. See `serveJournal`.\n */\n readonly settle?:\n | ((\n env: Env,\n journal: Journal<Operation, Shared, Principal, Operation>,\n ) => Effect.Effect<void, unknown>)\n | undefined\n /**\n * Asks `resolvePrincipal` again, of the upgrade request, every `every`\n * while the socket is open: a refusal closes it with 4401, and a principal\n * whose `key` differs from the one it opened with (`Policy.keyOf`) closes\n * it with 1012, which the replica reconnects after, as the new principal;\n * without `key` only a refusal closes it. Without it a socket\n * serves the principal it opened with until it closes, a revoked session\n * included.\n */\n readonly revalidate?:\n | {\n readonly every: Duration.Input\n readonly key?: ((principal: Principal) => unknown) | undefined\n }\n | undefined\n /** Whether `principal` may open the document. See `journalExchange`'s `opens`. */\n readonly opens?: ((principal: Principal) => Effect.Effect<boolean>) | undefined\n /**\n * Whether an operation from `principal` may be appended, before the journal\n * sees it. See `journalExchange`'s `admit`.\n */\n readonly admit?:\n | ((\n principal: Principal,\n operation: Operation,\n ) => AuthorizeDecision | Effect.Effect<AuthorizeDecision, unknown>)\n | undefined\n /**\n * Makes the socket pair for an upgrade: the server end is accepted before\n * serving. Defaults to the `WebSocketPair` global where one exists (a\n * worker, miniflare); pass one in tests.\n */\n readonly pair?: (() => readonly [client: WebSocket, server: AcceptingWebSocket]) | undefined\n}\n\n/**\n * What the resolver needs, from the environment: required exactly when it\n * needs something. Built per upgrade and kept until the socket closes, since\n * `revalidate` asks the resolver again while it is open; an upgrade that is\n * refused closes it at once.\n */\nexport type DocumentHostLayer<Env, RP> = [RP] extends [never]\n ? { readonly layer?: undefined }\n : { readonly layer: (env: Env) => Layer.Layer<RP> }\n\n/**\n * A server `WebSocket`: accepted once it serves. The `accept` member is a\n * worker-runtime extension the DOM type does not declare.\n */\nexport interface AcceptingWebSocket extends WebSocket {\n accept(): void\n}\n\n/**\n * Closes a socket with `code`, and `reason` when the platform takes it: a\n * reason past 123 bytes, or a socket already gone, still closes or is closed.\n */\nconst closeWith = (socket: WebSocket, code: number, reason: string): void => {\n try {\n socket.close(code, reason)\n } catch {\n try {\n socket.close(code)\n } catch {\n // Already closed.\n }\n }\n}\n\nconst defaultPair = (): readonly [client: WebSocket, server: AcceptingWebSocket] => {\n const maker = (\n globalThis as {\n readonly WebSocketPair?:\n (new () => { readonly 0: WebSocket; readonly 1: AcceptingWebSocket }) | undefined\n }\n ).WebSocketPair\n if (maker === undefined)\n throw new Error('DocumentHost: no WebSocketPair global; pass `pair` explicitly')\n const pair = new maker()\n return [pair[0], pair[1]] as const\n}\n\n/**\n * Defines the Durable Object class serving one document's Sync exchange.\n * Non-upgrades are 404s that open nothing; a refused principal is a 401; a\n * resolver that breaks, or a journal that never opened, a 500 that says\n * nothing of it.\n */\nexport const defineDocumentHost = <Message, Shared, Principal, Env, RP = never>(\n Base: new (ctx: DocumentHostContext, env: Env) => object,\n config: DocumentHostConfig<Message, Shared, Principal, Env, RP> & DocumentHostLayer<Env, RP>,\n): new (ctx: DocumentHostContext, env: Env) => { fetch(request: Request): Promise<Response> } => {\n checkRevalidate(config.revalidate, 'defineDocumentHost')\n return class extends Base {\n private readonly host: (request: Request) => Promise<Result.Result<Accepted, Response>>\n\n constructor(ctx: DocumentHostContext, env: Env) {\n super(ctx, env)\n let ready: Promise<Journal<Operation, Shared, Principal, Operation>> | undefined\n const { layer, settle } = config\n this.host = documentHost<Message, Shared, Principal, RP>({\n sync: config.sync,\n // Opened on the first upgrade a principal passes, so probes never\n // provision storage; a failed open is tried again on the next.\n journal: () =>\n (ready ??= config.openJournal(ctx, env)).catch((error: unknown) => {\n ready = undefined\n throw error\n }),\n resolvePrincipal: request => config.resolvePrincipal(request, env),\n layer: layer === undefined ? undefined : () => layer(env),\n revalidate: config.revalidate,\n settle: settle === undefined ? undefined : journal => settle(env, journal),\n opens: config.opens,\n admit: config.admit,\n // `DocumentHostLayer` already tied `layer` to `RP` on the config; the\n // conditional cannot be resolved for an `RP` still generic here.\n } as DocumentHostOptions<Message, Shared, Principal, RP> & DocumentHostOptionsLayer<RP>)\n }\n\n async fetch(request: Request): Promise<Response> {\n if (request.headers.get('Upgrade')?.toLowerCase() !== 'websocket')\n return Response.json({ error: 'not found' }, { status: 404 })\n // Made first: a runtime without WebSocketPair is a 500 that resolves no one.\n let pair: readonly [client: WebSocket, server: AcceptingWebSocket]\n try {\n pair = (config.pair ?? defaultPair)()\n } catch (error) {\n // The replica learns nothing of it; whoever runs the host must.\n console.error('[foldkit-sync] serving an upgrade broke:', error)\n return Response.json({ error: 'Internal error' }, { status: 500 })\n }\n const [client, server] = pair\n const answered = await this.host(request)\n if (Result.isFailure(answered)) return answered.failure\n const { serve, abandon } = answered.success\n try {\n server.accept()\n serve({\n ...workerSocket(server),\n closeWith: (code, reason) => closeWith(server, code, reason),\n })\n return new Response(null, {\n status: 101,\n // The worker runtime reads the client out of the upgrade response;\n // the DOM's `ResponseInit` has no such member.\n webSocket: client,\n } as ResponseInit)\n } catch (error) {\n console.error('[foldkit-sync] serving an upgrade broke:', error)\n abandon()\n return Response.json({ error: 'Internal error' }, { status: 500 })\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4IA,MAAM,aAAa,QAAmB,MAAc,WAAyB;CAC3E,IAAI;EACF,OAAO,MAAM,MAAM,MAAM;CAC3B,QAAQ;EACN,IAAI;GACF,OAAO,MAAM,IAAI;EACnB,QAAQ,CAER;CACF;AACF;AAEA,MAAM,oBAA8E;CAClF,MAAM,QACJ,WAIA;CACF,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,MAAM,+DAA+D;CACjF,MAAM,OAAO,IAAI,MAAM;CACvB,OAAO,CAAC,KAAK,IAAI,KAAK,EAAE;AAC1B;;;;;;;AAQA,MAAa,sBACX,MACA,WAC+F;CAC/F,gBAAgB,OAAO,YAAY,oBAAoB;CACvD,OAAO,cAAc,KAAK;EACxB;EAEA,YAAY,KAA0B,KAAU;GAC9C,MAAM,KAAK,GAAG;GACd,IAAI;GACJ,MAAM,EAAE,OAAO,WAAW;GAC1B,KAAK,OAAO,aAA6C;IACvD,MAAM,OAAO;IAGb,gBACG,UAAU,OAAO,YAAY,KAAK,GAAG,EAAA,CAAG,OAAO,UAAmB;KACjE,QAAQ,KAAA;KACR,MAAM;IACR,CAAC;IACH,mBAAkB,YAAW,OAAO,iBAAiB,SAAS,GAAG;IACjE,OAAO,UAAU,KAAA,IAAY,KAAA,UAAkB,MAAM,GAAG;IACxD,YAAY,OAAO;IACnB,QAAQ,WAAW,KAAA,IAAY,KAAA,KAAY,YAAW,OAAO,KAAK,OAAO;IACzE,OAAO,OAAO;IACd,OAAO,OAAO;GAGhB,CAAuF;EACzF;EAEA,MAAM,MAAM,SAAqC;GAC/C,IAAI,QAAQ,QAAQ,IAAI,SAAS,CAAC,EAAE,YAAY,MAAM,aACpD,OAAO,SAAS,KAAK,EAAE,OAAO,YAAY,GAAG,EAAE,QAAQ,IAAI,CAAC;GAE9D,IAAI;GACJ,IAAI;IACF,QAAQ,OAAO,QAAQ,YAAA,CAAa;GACtC,SAAS,OAAO;IAEd,QAAQ,MAAM,4CAA4C,KAAK;IAC/D,OAAO,SAAS,KAAK,EAAE,OAAO,iBAAiB,GAAG,EAAE,QAAQ,IAAI,CAAC;GACnE;GACA,MAAM,CAAC,QAAQ,UAAU;GACzB,MAAM,WAAW,MAAM,KAAK,KAAK,OAAO;GACxC,IAAI,OAAO,UAAU,QAAQ,GAAG,OAAO,SAAS;GAChD,MAAM,EAAE,OAAO,YAAY,SAAS;GACpC,IAAI;IACF,OAAO,OAAO;IACd,MAAM;KACJ,GAAG,aAAa,MAAM;KACtB,YAAY,MAAM,WAAW,UAAU,QAAQ,MAAM,MAAM;IAC7D,CAAC;IACD,OAAO,IAAI,SAAS,MAAM;KACxB,QAAQ;KAGR,WAAW;IACb,CAAiB;GACnB,SAAS,OAAO;IACd,QAAQ,MAAM,4CAA4C,KAAK;IAC/D,QAAQ;IACR,OAAO,SAAS,KAAK,EAAE,OAAO,iBAAiB,GAAG,EAAE,QAAQ,IAAI,CAAC;GACnE;EACF;CACF;AACF"}
1
+ {"version":3,"file":"do.mjs","names":[],"sources":["../src/do.ts"],"sourcesContent":["/**\n * `foldkit-sync/do`: serve one document's Sync exchange from a Cloudflare\n * Durable Object, the single writer its journal wants. Each socket the\n * object accepts exchanges against the same journal through `serveJournal`;\n * the replica side already exists as `Sync.transport.socket` over the\n * object's `wss://…` URL, which hears other writers' commits as notices.\n *\n * The class takes its `DurableObject` base as a parameter, so this module\n * imports no worker runtime and loads anywhere:\n *\n * ```ts\n * import { DurableObject } from 'cloudflare:workers'\n *\n * export class SyncHost extends defineDocumentHost(DurableObject, {\n * sync: Todos,\n * openJournal: (_ctx, env) => openTodosJournal(env.DB),\n * resolvePrincipal: request =>\n * Effect.succeed({ actorId: request.headers.get('x-actor') ?? 'anon' }),\n * }) {}\n * ```\n *\n * Open the journal once per object: on the first upgrade, so probes never\n * provision storage. Route one object per document (`idFromName(sync\n * .documentId)`); its in-memory cache and change stream are then exact\n * because nothing else writes.\n */\nimport { type Duration, type Effect, type Layer, Result } from 'effect'\nimport type { RemoteUnauthenticated } from 'foldkit-remote'\nimport type { Journal } from 'foldkit-durable/core'\nimport {\n documentHost,\n type Accepted,\n type DocumentHostOptions,\n type DocumentHostOptionsLayer,\n} from './journal.js'\nimport { checkRevalidate } from './revalidate.js'\nimport type { AuthorizeDecision } from './make.js'\nimport type { Operation, Sync } from './sync.js'\nimport { workerSocket } from './transport.js'\n\n/** The sliver of a Durable Object the host uses: state for the journal to open with. */\nexport interface DocumentHostContext {\n readonly storage?: unknown\n}\n\n/** What `defineDocumentHost` needs of the application, per document. */\nexport interface DocumentHostConfig<Message, Shared, Principal, Env, RP = never> {\n /** The document's contract: its codecs and journal shape. */\n readonly sync: Sync<Message, Shared>\n /**\n * Opens the document's journal, once: on the first upgrade, not on\n * construction, so probes never provision storage. Over D1 (`d1: true`),\n * or the object's SQLite storage through `ctx`. May build with Effect and\n * unwrap; a rejection answers the upgrade with a 500, and the next upgrade\n * tries again.\n */\n readonly openJournal: (\n ctx: DocumentHostContext,\n env: Env,\n ) => Promise<Journal<Operation, Shared, Principal, Operation>>\n /**\n * Who is opening this socket, from the upgrade request. Fails with a\n * `RemoteUnauthenticated` (`foldkit-remote`; `RemoteServer.unauthenticated()`\n * makes one) to refuse it: a 401 carrying its message. A defect is a 500\n * that says nothing of it. What it needs (a session store) comes from\n * `layer`.\n */\n readonly resolvePrincipal: (\n request: Request,\n env: Env,\n ) => Effect.Effect<Principal, RemoteUnauthenticated, RP>\n /**\n * Runs after each exchange's appends and before the reply is read: apply\n * what committed to another store, through `journal.recover`. Takes the\n * environment — a D1 binding, say — and the journal, because both live\n * outside the exchange. See `serveJournal`.\n */\n readonly settle?:\n | ((\n env: Env,\n journal: Journal<Operation, Shared, Principal, Operation>,\n ) => Effect.Effect<void, unknown>)\n | undefined\n /**\n * Asks `resolvePrincipal` again, of the upgrade request, every `every`\n * while the socket is open: a refusal closes it with 4401, and a principal\n * whose `key` differs from the one it opened with (`Policy.keyOf`) closes\n * it with 1012, which the replica reconnects after, as the new principal;\n * without `key` only a refusal closes it. Without it a socket\n * serves the principal it opened with until it closes, a revoked session\n * included.\n */\n readonly revalidate?:\n | {\n readonly every: Duration.Input\n readonly key?: ((principal: Principal) => unknown) | undefined\n }\n | undefined\n /** Whether `principal` may open the document. See `journalExchange`'s `opens`. */\n readonly opens?: ((principal: Principal) => Effect.Effect<boolean>) | undefined\n /**\n * Whether an operation from `principal` may be appended, before the journal\n * sees it. See `journalExchange`'s `admit`.\n */\n readonly admit?:\n | ((\n principal: Principal,\n operation: Operation,\n ) => AuthorizeDecision | Effect.Effect<AuthorizeDecision, unknown>)\n | undefined\n /**\n * Makes the socket pair for an upgrade: the server end is accepted before\n * serving. Defaults to the `WebSocketPair` global where one exists (a\n * worker, miniflare); pass one in tests.\n */\n readonly pair?: (() => readonly [client: WebSocket, server: AcceptingWebSocket]) | undefined\n}\n\n/**\n * What the resolver needs, from the environment: required exactly when it\n * needs something. Built per upgrade and kept until the socket closes, since\n * `revalidate` asks the resolver again while it is open; an upgrade that is\n * refused closes it at once.\n */\nexport type DocumentHostLayer<Env, RP> = [RP] extends [never]\n ? { readonly layer?: undefined }\n : { readonly layer: (env: Env) => Layer.Layer<RP> }\n\n/**\n * A server `WebSocket`: accepted once it serves. The `accept` member is a\n * worker-runtime extension the DOM type does not declare.\n */\nexport interface AcceptingWebSocket extends WebSocket {\n accept(): void\n}\n\n/**\n * Closes a socket with `code`, and `reason` when the platform takes it: a\n * reason past 123 bytes, or a socket already gone, still closes or is closed.\n */\nconst closeWith = (socket: WebSocket, code: number, reason: string): void => {\n try {\n socket.close(code, reason)\n } catch {\n try {\n socket.close(code)\n } catch {\n // Already closed.\n }\n }\n}\n\nconst defaultPair = (): readonly [client: WebSocket, server: AcceptingWebSocket] => {\n const maker = (\n globalThis as {\n readonly WebSocketPair?:\n | (new () => { readonly 0: WebSocket; readonly 1: AcceptingWebSocket })\n | undefined\n }\n ).WebSocketPair\n if (maker === undefined)\n throw new Error('DocumentHost: no WebSocketPair global; pass `pair` explicitly')\n const pair = new maker()\n return [pair[0], pair[1]] as const\n}\n\n/**\n * Defines the Durable Object class serving one document's Sync exchange.\n * Non-upgrades are 404s that open nothing; a refused principal is a 401; a\n * resolver that breaks, or a journal that never opened, a 500 that says\n * nothing of it.\n */\nexport const defineDocumentHost = <Message, Shared, Principal, Env, RP = never>(\n Base: new (ctx: DocumentHostContext, env: Env) => object,\n config: DocumentHostConfig<Message, Shared, Principal, Env, RP> & DocumentHostLayer<Env, RP>,\n): new (ctx: DocumentHostContext, env: Env) => { fetch(request: Request): Promise<Response> } => {\n checkRevalidate(config.revalidate, 'defineDocumentHost')\n return class extends Base {\n private readonly host: (request: Request) => Promise<Result.Result<Accepted, Response>>\n\n constructor(ctx: DocumentHostContext, env: Env) {\n super(ctx, env)\n let ready: Promise<Journal<Operation, Shared, Principal, Operation>> | undefined\n const { layer, settle } = config\n this.host = documentHost<Message, Shared, Principal, RP>({\n sync: config.sync,\n // Opened on the first upgrade a principal passes, so probes never\n // provision storage; a failed open is tried again on the next.\n journal: () =>\n (ready ??= config.openJournal(ctx, env)).catch((error: unknown) => {\n ready = undefined\n throw error\n }),\n resolvePrincipal: request => config.resolvePrincipal(request, env),\n layer: layer === undefined ? undefined : () => layer(env),\n revalidate: config.revalidate,\n settle: settle === undefined ? undefined : journal => settle(env, journal),\n opens: config.opens,\n admit: config.admit,\n // `DocumentHostLayer` already tied `layer` to `RP` on the config; the\n // conditional cannot be resolved for an `RP` still generic here.\n } as DocumentHostOptions<Message, Shared, Principal, RP> & DocumentHostOptionsLayer<RP>)\n }\n\n async fetch(request: Request): Promise<Response> {\n if (request.headers.get('Upgrade')?.toLowerCase() !== 'websocket')\n return Response.json({ error: 'not found' }, { status: 404 })\n // Made first: a runtime without WebSocketPair is a 500 that resolves no one.\n let pair: readonly [client: WebSocket, server: AcceptingWebSocket]\n try {\n pair = (config.pair ?? defaultPair)()\n } catch (error) {\n // The replica learns nothing of it; whoever runs the host must.\n console.error('[foldkit-sync] serving an upgrade broke:', error)\n return Response.json({ error: 'Internal error' }, { status: 500 })\n }\n const [client, server] = pair\n const answered = await this.host(request)\n if (Result.isFailure(answered)) return answered.failure\n const { serve, abandon } = answered.success\n try {\n server.accept()\n serve({\n ...workerSocket(server),\n closeWith: (code, reason) => closeWith(server, code, reason),\n })\n return new Response(null, {\n status: 101,\n // The worker runtime reads the client out of the upgrade response;\n // the DOM's `ResponseInit` has no such member.\n webSocket: client,\n } as ResponseInit)\n } catch (error) {\n console.error('[foldkit-sync] serving an upgrade broke:', error)\n abandon()\n return Response.json({ error: 'Internal error' }, { status: 500 })\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4IA,MAAM,aAAa,QAAmB,MAAc,WAAyB;CAC3E,IAAI;EACF,OAAO,MAAM,MAAM,MAAM;CAC3B,QAAQ;EACN,IAAI;GACF,OAAO,MAAM,IAAI;EACnB,QAAQ,CAER;CACF;AACF;AAEA,MAAM,oBAA8E;CAClF,MAAM,QACJ,WAKA;CACF,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,MAAM,+DAA+D;CACjF,MAAM,OAAO,IAAI,MAAM;CACvB,OAAO,CAAC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,QAAQ,MAAM,MAAM;IAC7D,CAAC;IACD,OAAO,IAAI,SAAS,MAAM;KACxB,QAAQ;KAGR,WAAW;IACb,CAAiB;GACnB,SAAS,OAAO;IACd,QAAQ,MAAM,4CAA4C,KAAK;IAC/D,QAAQ;IACR,OAAO,SAAS,KAAK,EAAE,OAAO,iBAAiB,GAAG,EAAE,QAAQ,IAAI,CAAC;GACnE;EACF;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/errors.ts","../src/indexedDb.ts","../src/lww.ts","../src/sync.ts","../src/make.ts","../src/mount.ts","../src/presence.ts","../src/index.ts"],"sourcesContent":["import { Schema } from 'effect'\n\n/** The persisted storage could not be read or written. */\nexport class StorageError extends Schema.TaggedError<StorageError>()('StorageError', {\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown),\n}) {}\n\n/** The stored clock state targets a schema version this build does not support. */\nexport class UnsupportedClockVersionError extends Schema.TaggedError<UnsupportedClockVersionError>()(\n 'UnsupportedClockVersionError',\n {\n schemaVersion: Schema.NullOr(Schema.Number),\n message: Schema.String,\n },\n) {}\n\n/** The storage holds a different replica's state. */\nexport class WrongReplicaStorageError extends Schema.TaggedError<WrongReplicaStorageError>()(\n 'WrongReplicaStorageError',\n {\n documentId: Schema.String,\n replicaId: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/** The persisted replica history is internally inconsistent. */\nexport class InvalidReplicaHistoryError extends Schema.TaggedError<InvalidReplicaHistoryError>()(\n 'InvalidReplicaHistoryError',\n {\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown),\n },\n) {}\n\n/** The server's exchange response did not match the protocol schema. */\nexport class InvalidExchangeError extends Schema.TaggedError<InvalidExchangeError>()(\n 'InvalidExchangeError',\n {\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown),\n },\n) {}\n\n/** A persisted pending operation could not have been produced by this replica. */\nexport class InvalidOutboxError extends Schema.TaggedError<InvalidOutboxError>()(\n 'InvalidOutboxError',\n {\n message: Schema.String,\n },\n) {}\n\n/** The server sent a checkpoint older than the replica's cursor. */\nexport class CheckpointRegressionError extends Schema.TaggedError<CheckpointRegressionError>()(\n 'CheckpointRegressionError',\n {\n cursor: Schema.Number,\n checkpointCursor: Schema.Number,\n message: Schema.String,\n },\n) {}\n\n/** Committed operations were not contiguous from the replica's cursor. */\nexport class CommittedOrderError extends Schema.TaggedError<CommittedOrderError>()(\n 'CommittedOrderError',\n {\n expected: Schema.Number,\n actual: Schema.Number,\n message: Schema.String,\n },\n) {}\n\n/** The server rejected an operation the replica never sent. */\nexport class ForeignRejectionError extends Schema.TaggedError<ForeignRejectionError>()(\n 'ForeignRejectionError',\n {\n opId: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/**\n * The server answered an operation this request never sent, or both\n * acknowledged and rejected it. Acting on either would let a faulty or hostile\n * server delete local work.\n */\nexport class ForeignAcknowledgementError extends Schema.TaggedError<ForeignAcknowledgementError>()(\n 'ForeignAcknowledgementError',\n {\n opId: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/** The replica was closed while work was still being submitted. */\nexport class ReplicaClosedError extends Schema.TaggedError<ReplicaClosedError>()(\n 'ReplicaClosedError',\n {\n message: Schema.String,\n },\n) {}\n\n/** The stored replica state targets a protocol or schema version this build does not support. */\nexport class UnsupportedReplicaVersionError extends Schema.TaggedError<UnsupportedReplicaVersionError>()(\n 'UnsupportedReplicaVersionError',\n {\n protocolVersion: Schema.NullOr(Schema.Number),\n schemaVersion: Schema.NullOr(Schema.Number),\n message: Schema.String,\n },\n) {}\n\n/**\n * `replay` threw for a submitted Message, so it could never be applied here or\n * on any other replica; nothing was written.\n */\nexport class ReplayError extends Schema.TaggedError<ReplayError>()('ReplayError', {\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown),\n}) {}\n\nexport type ReplicaError =\n | StorageError\n | ReplayError\n | WrongReplicaStorageError\n | InvalidReplicaHistoryError\n | InvalidExchangeError\n | UnsupportedReplicaVersionError\n | InvalidOutboxError\n | CheckpointRegressionError\n | CommittedOrderError\n | ForeignRejectionError\n | ForeignAcknowledgementError\n | ReplicaClosedError\n","import { Config, Effect } from 'effect'\nimport { StorageError } from './errors.js'\n\n/** One submitted operation, as `Storage.append` records it. */\nexport interface OutboxEntry {\n /** The replica's revision once this operation is in its outbox. */\n readonly revision: number\n readonly nextLocalSequence: number\n /**\n * The operation's local sequence. An entry with the sequence of one already in the\n * outbox replaces it: a coalesced submit rewrites the last operation.\n */\n readonly localSequence: number\n /** The operation, encoded. */\n readonly operation: unknown\n}\n\n/** Persists a replica's state with compare-and-swap on its revision. */\nexport interface Storage {\n /**\n * The saved state, with every operation appended since in its `pending` (replacing the\n * one of the same local sequence), and the last one's `revision` and `nextLocalSequence`.\n */\n load: () => Effect.Effect<unknown, StorageError>\n /** Replaces the whole state, and with it every appended operation. */\n save: (state: unknown, expectedRevision: number | null) => Effect.Effect<void, StorageError>\n /**\n * Optional. Records one submitted operation without rewriting the rest of the state, so\n * a submit costs the operation's size rather than the document's. Without it, a submit\n * saves the whole state.\n */\n append?: (entry: OutboxEntry, expectedRevision: number) => Effect.Effect<void, StorageError>\n /** Idempotent; the caller closes the connection explicitly. */\n close: Effect.Effect<void>\n}\n\nconst storageError = (message: string, cause: unknown): StorageError =>\n new StorageError({\n message: `${message}: ${cause instanceof Error ? cause.message : String(cause)}`,\n cause,\n })\n\nconst openDatabase = (\n name: string,\n factory: IDBFactory,\n): Effect.Effect<IDBDatabase, StorageError> =>\n Effect.tryPromise({\n try: () =>\n new Promise<IDBDatabase>((resolve, reject) => {\n const request = factory.open(name, 2)\n // Version 2 adds the outbox that `append` writes; a version 1 database keeps its\n // state, and its revision is read from that state until the next write.\n request.onupgradeneeded = event => {\n const database = request.result\n if (event.oldVersion < 1) database.createObjectStore('replica')\n if (event.oldVersion < 2) database.createObjectStore('outbox')\n }\n let blocked = false\n // A blocked open still succeeds once the other connection closes, after the\n // effect has failed; nothing else would ever close that connection.\n request.onsuccess = () => (blocked ? request.result.close() : resolve(request.result))\n request.onerror = () => reject(request.error)\n // Without this, a version upgrade blocked by another open connection\n // never settles and the effect hangs.\n request.onblocked = () => {\n blocked = true\n reject(new Error('IndexedDB upgrade is blocked by another connection'))\n }\n }),\n catch: cause => storageError('Could not open the storage', cause),\n })\n\n/** One database per document/replica; CAS prevents two tabs from sharing a writer identity. */\nexport const indexedDb = Effect.fn('Storage.indexedDb')(function* (\n name: Config.Config<string> | string,\n factory: IDBFactory = globalThis.indexedDB,\n) {\n const databaseName =\n typeof name === 'string'\n ? name\n : yield* name.pipe(\n Effect.catchTag('ConfigError', cause =>\n Effect.fail(storageError('Could not read the storage name', cause)),\n ),\n )\n const database = yield* Effect.acquireRelease(openDatabase(databaseName, factory), database =>\n Effect.sync(() => database.close()),\n )\n database.onversionchange = () => database.close()\n /**\n * Writes under compare-and-swap: `write` runs only if the stored revision is the one\n * expected. The revision is its own key, so an append need not read the state; a database\n * written before it existed has it inside the state.\n */\n const write = (\n expectedRevision: number | null,\n writing: (replica: IDBObjectStore, outbox: IDBObjectStore) => void,\n ): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n const transaction = database.transaction(['replica', 'outbox'], 'readwrite', {\n durability: 'strict',\n })\n const replica = transaction.objectStore('replica')\n let conflict = false\n const check = (revision: number | null): void => {\n if (revision !== expectedRevision) {\n conflict = true\n transaction.abort()\n return\n }\n writing(replica, transaction.objectStore('outbox'))\n }\n const stored = replica.get('revision')\n stored.onsuccess = () => {\n if (stored.result !== undefined) return check(stored.result as number)\n const state = replica.get('state')\n state.onsuccess = () =>\n check((state.result as { revision: number } | undefined)?.revision ?? null)\n }\n transaction.oncomplete = () => resolve()\n transaction.onabort = () =>\n reject(\n conflict\n ? new Error('Replica was changed by another writer')\n : (transaction.error ?? new Error('IndexedDB write aborted')),\n )\n })\n // Every member, `append` included, so a caller need not check for it.\n const storage: Required<Storage> = {\n load: () =>\n Effect.tryPromise({\n try: () =>\n new Promise((resolve, reject) => {\n const transaction = database.transaction(['replica', 'outbox'], 'readonly')\n const state = transaction.objectStore('replica').get('state')\n // In key order, which is local-sequence order.\n const appended = transaction.objectStore('outbox').getAll()\n transaction.oncomplete = () => {\n const saved = state.result as\n { pending: ReadonlyArray<{ readonly localSequence?: unknown }> } | undefined\n const entries = appended.result as ReadonlyArray<OutboxEntry>\n // Only the last operation is ever rewritten, so the last row is the latest.\n const latest = entries[entries.length - 1]\n const replaced = new Set(entries.map(entry => entry.localSequence))\n resolve(\n saved === undefined || latest === undefined\n ? saved\n : {\n ...saved,\n revision: latest.revision,\n nextLocalSequence: latest.nextLocalSequence,\n pending: [\n ...saved.pending.filter(\n operation => !replaced.has(operation.localSequence as number),\n ),\n ...entries.map(entry => entry.operation),\n ],\n },\n )\n }\n transaction.onabort = () =>\n reject(transaction.error ?? new Error('IndexedDB read aborted'))\n }),\n catch: cause => storageError('Could not read the replica', cause),\n }),\n save: (state, expectedRevision) =>\n Effect.tryPromise({\n try: () =>\n write(expectedRevision, (replica, outbox) => {\n replica.put(state, 'state')\n replica.put((state as { revision: number }).revision, 'revision')\n outbox.clear()\n }),\n catch: cause => storageError('Could not save the replica', cause),\n }),\n append: (entry, expectedRevision) =>\n Effect.tryPromise({\n try: () =>\n write(expectedRevision, (replica, outbox) => {\n outbox.put(entry, entry.localSequence)\n replica.put(entry.revision, 'revision')\n }),\n catch: cause => storageError('Could not save the replica', cause),\n }),\n close: Effect.sync(() => database.close()),\n }\n return storage\n})\n","import { Effect, Exit, Ref, Schema, SynchronizedRef } from 'effect'\nimport { StorageError, UnsupportedClockVersionError } from './errors.js'\nimport { DocumentId, ReplicaId } from './ids.js'\nimport type { Storage } from './indexedDb.js'\n\n/** A logical write time; replica ids break concurrent ties using UTF-16 order. */\nconst Stamp = Schema.Struct({\n counter: Schema.Number.check(\n Schema.isInt(),\n Schema.isGreaterThanOrEqualTo(0),\n Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER),\n ),\n replicaId: ReplicaId,\n})\n\n/** The persisted clock format. A bump must handle the older value explicitly. */\nconst CLOCK_SCHEMA_VERSION = 1\n\nconst ClockState = Schema.Struct({\n schemaVersion: Schema.Literal(CLOCK_SCHEMA_VERSION),\n documentId: DocumentId,\n replicaId: ReplicaId,\n // The high-water counter also serves as the storage's CAS revision.\n revision: Stamp.fields.counter,\n})\nexport type LwwClockState = typeof ClockState.Type\n\nexport interface LwwClock {\n /** Persists a timestamp beyond the saved counter and supplied observation. */\n next: (observedCounter?: number) => Effect.Effect<typeof Stamp.Type, StorageError>\n /** Drains accepted allocations, then closes storage. Repeated calls no-op. */\n close: Effect.Effect<void>\n}\n\nconst decodeClock = Schema.decodeUnknownSync(ClockState, { onExcessProperty: 'error' })\nconst decodeCounter = Schema.decodeUnknownSync(Stamp.fields.counter)\n\nconst clockError = (message: string, cause: unknown): StorageError =>\n new StorageError({\n message: `${message}: ${cause instanceof Error ? cause.message : String(cause)}`,\n cause,\n })\n\nconst VersionProbe = Schema.Struct({ schemaVersion: Schema.optional(Schema.Number) })\n/**\n * Tells a version this build does not understand apart from malformed data, so\n * the caller gets an actionable failure and the stored state is preserved.\n */\nconst unsupportedVersion = (input: unknown): UnsupportedClockVersionError | undefined => {\n let found: { readonly schemaVersion?: number | undefined }\n try {\n found = Schema.decodeUnknownSync(VersionProbe)(input)\n } catch {\n return undefined\n }\n if (found.schemaVersion === CLOCK_SCHEMA_VERSION) return undefined\n return new UnsupportedClockVersionError({\n schemaVersion: found.schemaVersion ?? null,\n message: `Stored clock uses schema ${found.schemaVersion ?? '?'}; this build supports ${CLOCK_SCHEMA_VERSION}`,\n })\n}\n\n/**\n * Opens a durable clock over the caller's storage.\n *\n * Allocations are serialized through a `SynchronizedRef` and each persists before\n * its stamp is returned. A crash after the save may skip a timestamp but never\n * reuse one. Storage is owned by the caller; a failed open closes it so a partial\n * initialization does not leak the connection.\n */\nexport const openLwwClock = Effect.fn('Lww.openClock')(\n function* (options: {\n readonly documentId: DocumentId\n readonly replicaId: ReplicaId\n readonly storage: Storage\n }) {\n const { documentId, replicaId, storage } = options\n yield* Effect.annotateCurrentSpan({ documentId, replicaId })\n const initial = decodeClock({\n schemaVersion: CLOCK_SCHEMA_VERSION,\n documentId,\n replicaId,\n revision: 0,\n })\n const saved = yield* storage.load()\n const state = yield* Effect.try({\n try: () => (saved === undefined ? initial : decodeClock(saved)),\n catch: cause =>\n unsupportedVersion(saved) ?? clockError('Stored clock state is invalid', cause),\n })\n if (state.documentId !== documentId || state.replicaId !== replicaId)\n return yield* new StorageError({ message: 'Wrong clock storage' })\n if (saved === undefined) yield* storage.save(state, null)\n\n const stateRef = yield* SynchronizedRef.make(state)\n const closed = yield* Ref.make(false)\n\n const next = Effect.fn('Lww.next')(function* (observedCounter = 0) {\n if (yield* Ref.get(closed)) return yield* new StorageError({ message: 'Clock is closed' })\n return yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.gen(function* () {\n // Re-check under the lock: a `close` that set the flag while this\n // allocation was queued must not save to a closed connection.\n if (yield* Ref.get(closed)) return yield* new StorageError({ message: 'Clock is closed' })\n const allocated = yield* Effect.try({\n try: () =>\n decodeClock({\n ...current,\n revision: Math.max(current.revision, decodeCounter(observedCounter)) + 1,\n }),\n catch: cause => clockError('Invalid clock allocation', cause),\n })\n yield* storage.save(allocated, current.revision)\n return [{ counter: allocated.revision, replicaId }, allocated] as const\n }),\n )\n })\n\n const close = Effect.fn('Lww.close')(function* () {\n const alreadyClosed = yield* Ref.modify(closed, current => [current, true] as const)\n if (alreadyClosed) return\n // Drains any accepted allocation before releasing the connection.\n yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.succeed([undefined, current] as const),\n )\n yield* storage.close\n })()\n\n return { next, close }\n },\n (effect, options) =>\n // Close a partially initialized storage on any failure, including a defect,\n // so a failed open cannot leak the connection.\n effect.pipe(\n Effect.onExit(exit =>\n Exit.isSuccess(exit) ? Effect.void : options.storage.close.pipe(Effect.ignore),\n ),\n ),\n)\n\n/**\n * A schema and reducer helper for a last-writer-wins register.\n * Allocate a unique stamp per write before dispatch, and retain it in the Message.\n * Merge is for decoded values; the application's schema validates wire input.\n */\nexport const lwwRegister = <Value, Encoded, RD, RE>(\n value: Schema.Codec<Value, Encoded, RD, RE>,\n) => {\n const schema = Schema.Struct({ stamp: Stamp, value })\n type Register = typeof schema.Type\n const equivalent = Schema.toEquivalence(value)\n\n const merge = (left: Register, right: Register): Register => {\n if (left.stamp.counter !== right.stamp.counter)\n return left.stamp.counter > right.stamp.counter ? left : right\n if (left.stamp.replicaId !== right.stamp.replicaId)\n return left.stamp.replicaId > right.stamp.replicaId ? left : right\n // Reusing a write identity for different values would make arrival order win.\n if (!equivalent(left.value, right.value)) throw new Error('Conflicting LWW write identity')\n return left\n }\n\n return { schema, merge }\n}\n","import {\n Effect,\n Exit,\n Metric,\n Option,\n PubSub,\n Queue,\n Ref,\n Schema,\n Stream,\n SynchronizedRef,\n} from 'effect'\nimport {\n CheckpointRegressionError,\n CommittedOrderError,\n ForeignAcknowledgementError,\n ForeignRejectionError,\n InvalidExchangeError,\n InvalidOutboxError,\n InvalidReplicaHistoryError,\n ReplayError,\n ReplicaClosedError,\n UnsupportedReplicaVersionError,\n WrongReplicaStorageError,\n type ReplicaError,\n} from './errors.js'\nimport type { Storage } from './indexedDb.js'\nimport {\n DocumentId,\n LocalSequence,\n OpId,\n ReplicaId,\n Sequence,\n localSequence,\n sequence,\n} from './ids.js'\nimport { Transport, TransportError } from './transport.js'\n\n/** Wire and persisted-format versions. A bump must handle the older value explicitly. */\nconst PROTOCOL_VERSION = 1\nconst SCHEMA_VERSION = 1\n\n/** A client-authored operation envelope. `message` is the application's encoded Message. */\nconst OperationSchema = Schema.Struct({\n protocolVersion: Schema.Literal(PROTOCOL_VERSION),\n schemaVersion: Schema.Literal(SCHEMA_VERSION),\n documentId: DocumentId,\n replicaId: ReplicaId,\n localSequence: LocalSequence,\n opId: OpId,\n baseCursor: Sequence,\n message: Schema.Unknown,\n})\nexport type Operation = typeof OperationSchema.Type\n\n/** An operation the server committed, with its authoritative order and actor. */\nconst CommittedSchema = Schema.Struct({\n ...OperationSchema.fields,\n serverSequence: Sequence.check(Schema.isGreaterThanOrEqualTo(1)),\n actorId: Schema.NonEmptyString,\n})\n/** Named to avoid colliding with `foldkit-durable`'s `Committed`. */\nexport type CommittedOperation = typeof CommittedSchema.Type\n\nconst decodeOperation = Schema.decodeUnknownSync(OperationSchema, { onExcessProperty: 'error' })\nconst decodeCommitted = Schema.decodeUnknownSync(CommittedSchema, { onExcessProperty: 'error' })\n\n/**\n * How many committed-operation ids a replica retains for duplicate detection.\n * Committed sequences are contiguous and the server enforces `opId`\n * uniqueness, so this is defence in depth; bounding it keeps replica state from\n * growing without limit on a log that is never checkpointed.\n */\nconst COMMITTED_ID_WINDOW = 1024\n/** How long `start` waits after a failed exchange: doubling from the base, up to the cap, in ms. */\nconst START_RETRY_BASE = 500\nconst START_RETRY_MAX = 30_000\n\n/** Counters and a histogram an application can scrape. */\nexport const syncMetrics = {\n exchanges: Metric.counter('foldkit_sync_exchanges_total'),\n applied: Metric.counter('foldkit_sync_commits_applied_total'),\n checkpoints: Metric.counter('foldkit_sync_checkpoints_adopted_total'),\n exchangePending: Metric.histogram('foldkit_sync_exchange_pending', {\n boundaries: [1, 4, 16, 64, 256, 1024],\n }),\n}\n\nexport interface Checkpoint<Shared> {\n readonly cursor: Sequence\n readonly model: Shared\n}\n\nexport interface Exchange<Shared> {\n /** Server-committed operations as they arrived; validated against `CommittedOperation` on adoption. */\n readonly operations: ReadonlyArray<unknown>\n readonly rejected: ReadonlyArray<OpId>\n /**\n * Why some of `rejected` were refused, in words the server chose for a person:\n * a policy's reason, never an internal error. One without a reason is still rejected.\n */\n readonly reasons?: ReadonlyArray<{ readonly opId: OpId; readonly reason: string }> | undefined\n /** Sends from the request that are durably committed, so the replica can drop them. */\n readonly acknowledged?: ReadonlyArray<OpId> | undefined\n /** The snapshot a replica predating compaction adopts in place of the log. */\n readonly checkpoint?: Checkpoint<Shared> | undefined\n /** The server sent only part of what is after the cursor; the replica asks again. */\n readonly more?: boolean | undefined\n /**\n * The identity of the server's history. The replica sends back the one it last saw; a\n * server that finds another answers from the start of its own history, and the replica,\n * seeing a new epoch, rebuilds its committed state from that answer and keeps its outbox.\n */\n readonly epoch?: string | undefined\n}\n\nexport interface ReplicaState<Shared> {\n readonly protocolVersion: typeof PROTOCOL_VERSION\n readonly schemaVersion: typeof SCHEMA_VERSION\n readonly documentId: DocumentId\n readonly replicaId: ReplicaId\n readonly revision: number\n readonly nextLocalSequence: LocalSequence\n readonly cursor: Sequence\n readonly committed: Shared\n readonly committedIds: ReadonlyArray<string>\n readonly pending: ReadonlyArray<Operation>\n /** The server history `cursor` points into, once an exchange has named one. */\n readonly epoch?: string\n}\n\n/**\n * What the promise-based edge adapter consumes; the Effect `Transport` service\n * is the primary seam.\n */\nexport interface TransportClient {\n /** `epoch` is the server history the replica's cursor points into, when it knows one. */\n exchange(\n cursor: Sequence,\n pending: ReadonlyArray<Operation>,\n epoch?: string | undefined,\n ): Promise<unknown>\n}\n\n/** A redacted view of a replica's state, for a UI to explain and recover. */\nexport interface ReplicaStatus {\n readonly pending: number\n readonly cursor: Sequence\n /** The last exchange failure, cleared by a successful exchange. */\n readonly lastError: string | undefined\n /** Operations the server refused, most recent first, with its reason when it gave one. */\n readonly rejected: ReadonlyArray<Rejection>\n /**\n * The server history the cursor points into, once a server named one. A new\n * one means the server was reset: what the replica had committed is gone.\n */\n readonly epoch: Option.Option<string>\n}\n\n/**\n * An operation the server refused, and why, when it said. It carries the\n * operation itself: the replica drops it from the outbox in the same step,\n * so what it changed can be read from here rather than looked up in time.\n */\nexport interface Rejection {\n readonly opId: OpId\n readonly reason: Option.Option<string>\n readonly operation: Operation\n}\n\n/**\n * A consistent status and optimistic-shared pair, read from one replica state.\n * `Replica.changes` emits it so a UI can hold a single subscription.\n */\nexport interface ReplicaSnapshot<Shared> {\n readonly status: ReplicaStatus\n readonly shared: Shared\n /** The server-confirmed state the optimistic `shared` is built on. */\n readonly committed: Shared\n /**\n * The local sequence the next submitted operation takes. Only a successful\n * submit moves it, so a caller that submits one Message at a time can tell\n * from one snapshot whether `shared` already holds it.\n */\n readonly nextLocalSequence: LocalSequence\n}\n\nexport interface Replica<Message, Shared> {\n /** The id this replica's operations carry, one per tab: what its commits are stamped with. */\n readonly replicaId: ReplicaId\n /** The optimistic projection: committed state with pending operations replayed. */\n readonly shared: Effect.Effect<Shared>\n /**\n * The server-confirmed state through `cursor`, with no pending operation\n * applied. A pending edit reaches it only once the server commits it, and a\n * rejected one never does.\n */\n readonly committed: Effect.Effect<Shared>\n readonly pending: Effect.Effect<ReadonlyArray<Operation>>\n readonly cursor: Effect.Effect<Sequence>\n /**\n * Waiting/recovery information without exposing Messages or the Model. It is a\n * snapshot; `statusChanges` re-emits it after every submit and exchange.\n */\n readonly status: Effect.Effect<ReplicaStatus>\n /** The status, re-emitted after every submit and exchange. */\n readonly statusChanges: Stream.Stream<ReplicaStatus>\n /**\n * The status and the optimistic shared value together, re-emitted after every\n * submit and exchange, so a UI can subscribe once instead of to both.\n */\n readonly changes: Stream.Stream<ReplicaSnapshot<Shared>>\n /** The status, `shared`, `committed` and next local sequence, read from one replica state. */\n readonly snapshot: Effect.Effect<ReplicaSnapshot<Shared>>\n readonly submit: (message: Message) => Effect.Effect<void, ReplicaError>\n /** Reconciles against the server. The `Transport` service must be provided. */\n readonly synchronize: Effect.Effect<void, ReplicaError | TransportError, Transport>\n /**\n * The exchange loop: exchanges once, then after every `submit` and every\n * notice on the transport's `changes`, until the replica closes or the fiber\n * is interrupted. A failed exchange is recorded\n * in `status.lastError` and retried on a backoff (from 0.5 s, doubling up to\n * 30 s), or at once on the next `submit`, so the fiber never fails. Fork it\n * with `Effect.forkScoped` and provide `Transport`.\n */\n readonly start: Effect.Effect<void, never, Transport>\n readonly close: Effect.Effect<void>\n}\n\nexport interface SyncDefinition<Message, Shared, MessageEncoded, SharedEncoded> {\n readonly documentId: DocumentId\n readonly message: Schema.Codec<Message, MessageEncoded, never, never>\n readonly shared: Schema.Codec<Shared, SharedEncoded, never, never>\n readonly empty: Shared\n readonly durable: (message: Message) => boolean\n readonly replay: (shared: Shared, message: Message) => Shared\n /**\n * Optional. Merges a durable Message into the one submitted before it, while that one\n * has not been sent: one operation instead of two, for a burst of typing. Replaying the\n * result must equal replaying `last` then `next`. Undefined keeps them apart.\n */\n readonly coalesce?: ((last: Message, next: Message) => Message | undefined) | undefined\n /**\n * Optional. Writes what the server's commit decided into a durable Message, on the\n * server only: the journal stores, reduces and sends the stamped Message, so every\n * replica replays the same one in place of what it sent.\n */\n readonly stamp?: ((message: Message, commit: CommitStamp) => Message) | undefined\n}\n\n/**\n * What a commit decided, for `stamp`: the operation's place in the order, who\n * committed it, and from which replica. `actorId` is the principal, shared by\n * every tab a person has open; `replicaId` tells those tabs apart.\n */\nexport interface CommitStamp {\n readonly sequence: number\n readonly actorId: string\n readonly replicaId: string\n}\n\nexport interface Sync<Message, Shared> {\n readonly documentId: DocumentId\n /** Whether a Message is one the replica records and replays. */\n readonly durable: (message: Message) => boolean\n /**\n * Low-level wire codecs for adapters and the transport. Most applications use\n * `journalContract` and `openReplica`; these are exposed for a custom\n * transport or a server that must speak the operation envelope directly.\n */\n readonly codec: {\n readonly normalizeOperation: (input: unknown) => Operation\n readonly operationFrom: (input: unknown, documentId: DocumentId) => Operation\n readonly committedFrom: (input: unknown, documentId: DocumentId) => CommittedOperation\n readonly decodeExchange: (input: unknown) => Exchange<Shared>\n }\n /** The codecs and pure reducer `foldkit-durable`'s `makeJournal` consumes. */\n readonly journalContract: () => JournalContract<Operation, Shared>\n readonly openReplica: (\n replicaId: ReplicaId,\n storage: Storage,\n ) => Effect.Effect<Replica<Message, Shared>, ReplicaError>\n}\n\n/** Structural match for `foldkit-durable`'s journal options; Sync stays independent. */\nexport interface JournalContract<Operation, Shared> {\n /** The replica each operation came from, which Durable binds to its first committer. */\n readonly replicaId: (operation: Operation) => string\n /** Sync's operation id includes the replica, even after Durable compacts its payload. */\n readonly legacyReplicaId: (opId: string) => string\n readonly operation: {\n /** Operations are stored in their encoded form, so this is the identity. */\n readonly encode: (operation: Operation) => Operation\n readonly decode: (input: unknown) => Operation\n }\n readonly snapshot: {\n readonly encode: (snapshot: Shared) => unknown\n readonly decode: (input: unknown) => Shared\n }\n readonly empty: () => Shared\n readonly reduce: (snapshot: Shared, operation: Operation) => Shared\n /** Present when the definition stamps: Durable's `stamp`, over the operation's Message. */\n readonly stamp?: (\n operation: Operation,\n commit: { readonly sequence: number; readonly actorId: string },\n ) => Operation\n}\n\n/**\n * Binds the replicated-state protocol to one application contract.\n *\n * The returned codecs decide what is a valid operation and what the shared\n * projection means; the replica owns the local outbox, optimistic projection,\n * and reconciliation as Effects, and never runs a second reducer.\n */\nexport const defineSync = <Message, Shared, MessageEncoded, SharedEncoded>(\n definition: SyncDefinition<Message, Shared, MessageEncoded, SharedEncoded>,\n): Sync<Message, Shared> => {\n const documentId = definition.documentId\n const decodeMessage = Schema.decodeUnknownSync(definition.message, { onExcessProperty: 'error' })\n const encodeMessage = Schema.encodeSync(definition.message)\n const decodeShared = Schema.decodeUnknownSync(definition.shared, { onExcessProperty: 'error' })\n const encodeShared = Schema.encodeSync(definition.shared)\n\n const ReplicaStateSchema = Schema.Struct({\n protocolVersion: Schema.Literal(PROTOCOL_VERSION),\n schemaVersion: Schema.Literal(SCHEMA_VERSION),\n documentId: DocumentId,\n replicaId: ReplicaId,\n revision: Schema.Number,\n nextLocalSequence: LocalSequence,\n cursor: Sequence,\n committed: definition.shared,\n committedIds: Schema.Array(Schema.String),\n pending: Schema.Array(OperationSchema),\n epoch: Schema.optionalKey(Schema.NonEmptyString),\n })\n const CheckpointSchema = Schema.Struct({ cursor: Sequence, model: definition.shared })\n const ExchangeSchema = Schema.Struct({\n operations: Schema.Array(Schema.Unknown),\n rejected: Schema.Array(OpId),\n // A server's words for a person, bounded: a reply is not a place for a document.\n reasons: Schema.optional(\n Schema.Array(\n Schema.Struct({ opId: OpId, reason: Schema.String.check(Schema.isMaxLength(500)) }),\n ),\n ),\n acknowledged: Schema.optional(Schema.Array(OpId)),\n checkpoint: Schema.optional(CheckpointSchema),\n more: Schema.optional(Schema.Boolean),\n epoch: Schema.optional(Schema.NonEmptyString),\n })\n const decodeState = Schema.decodeUnknownSync(ReplicaStateSchema, { onExcessProperty: 'error' })\n const encodeState = Schema.encodeSync(ReplicaStateSchema)\n const encodeOperation = Schema.encodeSync(OperationSchema)\n const VersionProbe = Schema.Struct({\n protocolVersion: Schema.optional(Schema.Number),\n schemaVersion: Schema.optional(Schema.Number),\n })\n /**\n * Tells a version this build does not understand apart from malformed data,\n * so the caller gets an actionable failure and the stored state is preserved.\n */\n const unsupportedVersion = (input: unknown): UnsupportedReplicaVersionError | undefined => {\n let found: {\n readonly protocolVersion?: number | undefined\n readonly schemaVersion?: number | undefined\n }\n try {\n found = Schema.decodeUnknownSync(VersionProbe)(input)\n } catch {\n return undefined\n }\n if (found.protocolVersion === PROTOCOL_VERSION && found.schemaVersion === SCHEMA_VERSION)\n return undefined\n const protocolVersion = found.protocolVersion ?? null\n const schemaVersion = found.schemaVersion ?? null\n return new UnsupportedReplicaVersionError({\n protocolVersion,\n schemaVersion,\n message: `Stored replica uses protocol ${protocolVersion ?? '?'} / schema ${schemaVersion ?? '?'}; this build supports ${PROTOCOL_VERSION}/${SCHEMA_VERSION}`,\n })\n }\n const decodeExchange = (input: unknown): Exchange<Shared> =>\n Schema.decodeUnknownSync(ExchangeSchema, { onExcessProperty: 'error' })(\n input,\n ) as Exchange<Shared>\n\n const checkIdentity = (operation: Operation): void => {\n // `LocalSequence` already rejects a non-positive counter; this checks the\n // derived identity.\n if (operation.opId !== `${operation.replicaId}:${operation.localSequence}`) {\n throw new Error('Invalid operation identity')\n }\n }\n const decodeDurable = (message: unknown): Message => {\n const decoded = decodeMessage(message)\n if (!definition.durable(decoded)) throw new Error('Message is local-only')\n return decoded\n }\n const shape = <O extends Operation>(operation: O): O => {\n checkIdentity(operation)\n return { ...operation, message: encodeMessage(decodeDurable(operation.message)) }\n }\n const assertDocument = <O extends Operation>(operation: O, key: DocumentId): O => {\n if (operation.documentId !== key) throw new Error('Wrong document')\n return operation\n }\n const normalizeOperation = (input: unknown): Operation => shape(decodeOperation(input))\n const operationFrom = (input: unknown, key: DocumentId): Operation =>\n assertDocument(normalizeOperation(input), key)\n /**\n * A committed operation arrives with its message already encoded, so decode it\n * once for the contract check and hand it to `replay` instead of decoding and\n * re-encoding it on the way through `shape`.\n */\n const decodeCommittedOperation = (\n input: unknown,\n key: DocumentId,\n ): { readonly committed: CommittedOperation; readonly message: Message } => {\n const committed = assertDocument(decodeCommitted(input), key)\n checkIdentity(committed)\n return { committed, message: decodeDurable(committed.message) }\n }\n const committedFrom = (input: unknown, key: DocumentId): CommittedOperation =>\n decodeCommittedOperation(input, key).committed\n\n const journalContract = (): JournalContract<Operation, Shared> => ({\n replicaId: operation => operation.replicaId,\n legacyReplicaId: opId => opId.slice(0, opId.lastIndexOf(':')),\n // Operations are stored in their encoded form: `normalizeOperation` has\n // already encoded the Message and validated the identity.\n operation: { encode: operation => operation, decode: normalizeOperation },\n snapshot: { encode: encodeShared, decode: decodeShared },\n empty: () => definition.empty,\n reduce: (snapshot, operation) => definition.replay(snapshot, decodeMessage(operation.message)),\n ...(definition.stamp === undefined\n ? {}\n : {\n stamp: (\n operation: Operation,\n commit: { readonly sequence: number; readonly actorId: string },\n ): Operation => ({\n ...operation,\n message: encodeMessage(\n definition.stamp!(decodeMessage(operation.message), {\n ...commit,\n replicaId: operation.replicaId,\n }),\n ),\n }),\n }),\n })\n\n const optimistic = (state: ReplicaState<Shared>): Shared =>\n state.pending.reduce(\n (model, operation) => definition.replay(model, decodeMessage(operation.message)),\n state.committed,\n )\n\n const openReplica = Effect.fn('Sync.openReplica')(\n function* (replicaId: ReplicaId, storage: Storage) {\n yield* Effect.annotateCurrentSpan({ documentId, replicaId })\n const saved = yield* storage.load()\n const initial: ReplicaState<Shared> = {\n protocolVersion: PROTOCOL_VERSION,\n schemaVersion: SCHEMA_VERSION,\n documentId,\n replicaId,\n revision: 0,\n nextLocalSequence: localSequence(1),\n cursor: sequence(0),\n committed: definition.empty,\n committedIds: [],\n pending: [],\n }\n const state: ReplicaState<Shared> =\n saved === undefined\n ? initial\n : yield* Effect.try({\n try: () => decodeState(saved),\n catch: cause =>\n unsupportedVersion(saved) ??\n new InvalidReplicaHistoryError({\n message: 'Stored replica state is invalid',\n cause,\n }),\n })\n if (state.documentId !== documentId || state.replicaId !== replicaId)\n return yield* new WrongReplicaStorageError({\n documentId,\n replicaId,\n message: 'The stored replica belongs to a different document or replica',\n })\n const committedIds = new Set(state.committedIds)\n if (state.nextLocalSequence < 1 || committedIds.size !== state.committedIds.length)\n return yield* new InvalidReplicaHistoryError({ message: 'Invalid replica history' })\n const pendingIds = new Set<string>()\n for (const pending of state.pending) {\n const operation = yield* Effect.try({\n try: () => operationFrom(pending, documentId),\n catch: () => new InvalidOutboxError({ message: 'Invalid outbox' }),\n })\n if (\n operation.replicaId !== replicaId ||\n operation.localSequence >= state.nextLocalSequence ||\n committedIds.has(operation.opId) ||\n pendingIds.has(operation.opId)\n )\n return yield* new InvalidOutboxError({ message: 'Invalid outbox' })\n pendingIds.add(operation.opId)\n }\n // Storage holds the schema's encoded side, so a transforming `shared`\n // codec round-trips: decode on load, encode before every save. Encoding\n // also rejects an invalid `empty` on first creation rather than at reload.\n const store = Effect.fn('Sync.store')(function* (\n next: ReplicaState<Shared>,\n expectedRevision: number | null,\n ) {\n const encoded = yield* Effect.try({\n try: () => encodeState(next),\n catch: cause =>\n new InvalidReplicaHistoryError({\n message: 'Could not encode the replica state',\n cause,\n }),\n })\n yield* storage.save(encoded, expectedRevision)\n })\n if (saved === undefined) yield* store(state, null)\n\n const stateRef = yield* SynchronizedRef.make(state)\n const closed = yield* Ref.make(false)\n const lastError = yield* Ref.make<string | undefined>(undefined)\n const rejectedOps = yield* Ref.make<ReadonlyArray<Rejection>>([])\n // Operations submitted since opening that no exchange has carried yet. Only these may\n // be coalesced: one that was sent may already be committed as it was.\n const unsent = yield* Ref.make<ReadonlySet<string>>(new Set())\n // One pending wake-up is enough: the loop exchanges the whole outbox.\n const wake = yield* Queue.sliding<void>(1)\n const statusSignals = yield* PubSub.sliding<void>(1)\n // The current value, then again after every change. Subscribed before the\n // first read, so a change made while a subscriber holds that value, or\n // between the read and the subscription, is still told.\n const following = <A>(read: Effect.Effect<A>): Stream.Stream<A> =>\n Stream.unwrap(\n Effect.map(PubSub.subscribe(statusSignals), signals =>\n Stream.concat(\n Stream.fromEffect(read),\n Stream.fromSubscription(signals).pipe(Stream.mapEffect(() => read)),\n ),\n ),\n )\n // The projection is pure over an immutable state, so a cached value is\n // reused until a write replaces the state object. A UI reads `shared` far\n // more often than it writes, and replaying a large outbox per read is\n // quadratic (see `bench/projection.bench.ts`).\n const projection = yield* Ref.make<\n { readonly state: ReplicaState<Shared>; readonly shared: Shared } | undefined\n >(undefined)\n const snapshot = Effect.fn('Sync.snapshot')(function* () {\n const current = yield* SynchronizedRef.get(stateRef)\n const cached = yield* Ref.get(projection)\n let projected: Shared\n if (cached !== undefined && cached.state === current) projected = cached.shared\n else {\n projected = optimistic(current)\n yield* Ref.set(projection, { state: current, shared: projected })\n }\n return {\n status: {\n pending: current.pending.length,\n cursor: current.cursor,\n lastError: yield* Ref.get(lastError),\n rejected: yield* Ref.get(rejectedOps),\n epoch: Option.fromUndefinedOr(current.epoch),\n },\n shared: projected,\n committed: current.committed,\n nextLocalSequence: current.nextLocalSequence,\n }\n })()\n const shared = Effect.map(snapshot, value => value.shared)\n const status = Effect.map(snapshot, value => value.status)\n\n // `SynchronizedRef.modifyEffect` installs the returned state itself, so\n // persisting must not also set the ref (that would re-enter the lock).\n const persist = (next: ReplicaState<Shared>, current: ReplicaState<Shared>) =>\n store(next, current.revision)\n\n const submit = Effect.fn('Sync.submit')(function* (message: Message) {\n yield* Effect.annotateCurrentSpan({ documentId, replicaId })\n const result = yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.gen(function* () {\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n if (!definition.durable(message))\n return yield* new InvalidOutboxError({ message: 'Message is local-only' })\n const last = current.pending[current.pending.length - 1]\n const merged =\n last !== undefined &&\n definition.coalesce !== undefined &&\n (yield* Ref.get(unsent)).has(last.opId)\n ? definition.coalesce(decodeMessage(last.message), message)\n : undefined\n if (merged !== undefined && !definition.durable(merged))\n return yield* new InvalidOutboxError({\n message: 'coalesce returned a local-only Message',\n })\n // A merged Message takes the place of the last operation, under its identity.\n const operation = yield* Effect.try({\n try: () =>\n operationFrom(\n merged === undefined\n ? {\n protocolVersion: PROTOCOL_VERSION,\n schemaVersion: SCHEMA_VERSION,\n documentId,\n replicaId,\n localSequence: current.nextLocalSequence,\n opId: `${replicaId}:${current.nextLocalSequence}`,\n baseCursor: current.cursor,\n message: encodeMessage(message),\n }\n : { ...last!, message: encodeMessage(merged) },\n documentId,\n ),\n catch: () => new InvalidOutboxError({ message: 'Invalid outbox' }),\n })\n // Replay before writing: a Message replay refuses can never be\n // applied, here or on another replica, so it must not reach the\n // outbox. The result is the next optimistic projection, so the\n // cache is seeded instead of replaying the outbox on the next read.\n // Rebuilding the projection replays the outbox, which can throw\n // too (an upgrade that changed `update` for a pending Message), so\n // it sits inside the same typed error as the new Message's replay.\n const cached = yield* Ref.get(projection)\n const replayed = yield* Effect.try({\n try: () =>\n definition.replay(\n cached !== undefined && cached.state === current\n ? cached.shared\n : optimistic(current),\n message,\n ),\n catch: cause =>\n new ReplayError({\n message: cause instanceof Error ? cause.message : 'Replay failed',\n cause,\n }),\n })\n // Validated and encoded by `persist`; decoding here would demand the\n // encoded side and break a transforming `shared` codec.\n // The sequence moves on a merge too, so every submit is visible in it; a gap\n // in local sequences is harmless.\n const next: ReplicaState<Shared> = {\n ...current,\n revision: current.revision + 1,\n nextLocalSequence: localSequence(current.nextLocalSequence + 1),\n pending: [\n ...(merged === undefined ? current.pending : current.pending.slice(0, -1)),\n operation,\n ],\n }\n // Only the new operation is written when the storage can append it.\n if (storage.append === undefined) yield* persist(next, current)\n else {\n const encoded = yield* Effect.try({\n try: () => encodeOperation(operation),\n catch: cause =>\n new InvalidReplicaHistoryError({\n message: 'Could not encode the operation',\n cause,\n }),\n })\n yield* storage.append(\n {\n revision: next.revision,\n nextLocalSequence: next.nextLocalSequence,\n localSequence: operation.localSequence,\n operation: encoded,\n },\n current.revision,\n )\n }\n yield* Ref.set(projection, { state: next, shared: replayed })\n yield* Ref.update(unsent, ids => new Set(ids).add(operation.opId))\n yield* Queue.offer(wake, undefined)\n return [undefined, next] as const\n }),\n )\n // Outside the lock, so a `statusChanges` subscriber reads the new state.\n yield* PubSub.publish(statusSignals, undefined)\n return result\n })\n\n /** One exchange; whether the server has more to send and this one made progress. */\n const exchangeOnce = Effect.fn('Sync.exchange')(function* () {\n yield* Effect.annotateCurrentSpan({ documentId })\n const transport = yield* Transport\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n // Read under the lock, as a submit writes, so no submit can merge into an operation\n // between its being read here and its being marked sent.\n const sent = yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Ref.update(unsent, ids => {\n const left = new Set(ids)\n for (const operation of current.pending) left.delete(operation.opId)\n return left\n }).pipe(Effect.as([current, current] as const)),\n )\n yield* Metric.update(syncMetrics.exchanges, 1)\n yield* Metric.update(syncMetrics.exchangePending, sent.pending.length)\n const response = yield* Effect.gen(function* () {\n const raw = yield* transport.exchange(sent.cursor, sent.pending, sent.epoch)\n // The response is untrusted: a malformed shape is a typed failure, not\n // a defect that escapes the declared error channel.\n return yield* Effect.try({\n try: () => decodeExchange(raw),\n catch: cause =>\n new InvalidExchangeError({ message: 'Invalid sync exchange response', cause }),\n })\n })\n const restarted = yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.gen(function* () {\n // A `close` during the exchange must not persist its result.\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n // Another epoch means the server's history is not the one the cursor points\n // into (it was reset): the answer starts from its beginning, so the committed\n // state is rebuilt from it. The outbox is the user's intent and is kept.\n const restarted =\n response.epoch !== undefined &&\n current.epoch !== undefined &&\n response.epoch !== current.epoch\n if (restarted)\n yield* Effect.logWarning('sync server history changed; rebuilding', {\n documentId,\n replicaId,\n })\n let cursor = restarted ? sequence(0) : current.cursor\n let committed = restarted ? definition.empty : current.committed\n // A checkpoint folds committed history into its snapshot, so the\n // retained id set starts over from it, as it does on a new epoch.\n const ids =\n response.checkpoint === undefined && !restarted\n ? new Set(current.committedIds)\n : new Set<string>()\n if (response.checkpoint !== undefined) {\n if (response.checkpoint.cursor < cursor)\n return yield* new CheckpointRegressionError({\n cursor,\n checkpointCursor: response.checkpoint.cursor,\n message: 'Checkpoint is behind the replica',\n })\n committed = response.checkpoint.model\n cursor = response.checkpoint.cursor\n yield* Metric.update(syncMetrics.checkpoints, 1)\n yield* Effect.logDebug('sync checkpoint adopted', { documentId, replicaId, cursor })\n }\n const acknowledged = new Set(response.acknowledged ?? [])\n const rejected = new Set(response.rejected)\n const sentIds = new Set(sent.pending.map(operation => operation.opId))\n for (const id of acknowledged)\n if (!sentIds.has(id))\n return yield* new ForeignAcknowledgementError({\n opId: id,\n message: 'Server acknowledged an operation that was not sent',\n })\n for (const id of rejected) {\n if (!sentIds.has(id))\n return yield* new ForeignRejectionError({\n opId: id,\n message: 'Server rejected an operation that was not sent',\n })\n // An id cannot be both; removal would be ambiguous and a faulty\n // server must not be able to make a pending operation vanish.\n if (acknowledged.has(id))\n return yield* new ForeignAcknowledgementError({\n opId: id,\n message: 'Server both acknowledged and rejected an operation',\n })\n }\n for (const { opId } of response.reasons ?? [])\n if (!rejected.has(opId))\n return yield* new ForeignRejectionError({\n opId,\n message: 'Server gave a reason for an operation it did not reject',\n })\n let applied = 0\n for (const raw of response.operations) {\n const { committed: operation, message } = yield* Effect.try({\n try: () => decodeCommittedOperation(raw, documentId),\n catch: cause =>\n new InvalidReplicaHistoryError({ message: 'Invalid committed operation', cause }),\n })\n if (operation.serverSequence <= cursor) continue\n if (operation.serverSequence !== cursor + 1 || ids.has(operation.opId))\n return yield* new CommittedOrderError({\n expected: cursor + 1,\n actual: operation.serverSequence,\n message: 'Invalid committed order',\n })\n // A throw here would be a defect, which bypasses `lastError` and leaves\n // `start` retrying the same page in silence.\n const replaying = committed\n committed = yield* Effect.try({\n try: () => definition.replay(replaying, message),\n catch: cause =>\n new ReplayError({\n message: cause instanceof Error ? cause.message : 'Replay failed',\n cause,\n }),\n })\n ids.add(operation.opId)\n cursor = operation.serverSequence\n applied += 1\n }\n if (applied > 0) yield* Metric.update(syncMetrics.applied, applied)\n // Validated and encoded by `persist`, for the same reason as submit.\n const epoch = response.epoch ?? current.epoch\n const next: ReplicaState<Shared> = {\n ...current,\n revision: current.revision + 1,\n committed,\n cursor,\n ...(epoch === undefined ? {} : { epoch }),\n committedIds: [...ids].slice(-COMMITTED_ID_WINDOW),\n // While the server has more to send, an acknowledged operation's committed\n // copy may be on a later page, so it stays in the optimistic view until then.\n // An acknowledged operation the replica is already past (committed before a\n // checkpoint, say) never arrives, so it goes once there is no more to read.\n pending: current.pending.filter(\n operation =>\n !ids.has(operation.opId) &&\n !(acknowledged.has(operation.opId) && response.more !== true) &&\n !rejected.has(operation.opId),\n ),\n }\n yield* persist(next, current)\n return [restarted, next] as const\n }),\n )\n yield* Ref.set(lastError, undefined)\n if (response.rejected.length > 0) {\n const reasonOf = new Map(\n (response.reasons ?? []).map(({ opId, reason }) => [opId, reason] as const),\n )\n // Every rejected id was sent: an unknown one failed the exchange above.\n const sentOf = new Map(\n sent.pending.map(operation => [operation.opId, operation] as const),\n )\n const refused = response.rejected.map((opId): Rejection => ({\n opId,\n reason: Option.fromUndefinedOr(reasonOf.get(opId)),\n operation: sentOf.get(opId)!,\n }))\n yield* Ref.update(rejectedOps, previous => [...refused, ...previous].slice(0, 32))\n }\n yield* PubSub.publish(statusSignals, undefined)\n const reached = (yield* SynchronizedRef.get(stateRef)).cursor\n return response.more === true && reached > (restarted ? 0 : sent.cursor)\n })\n\n // A server that pages its answer says there is more, and the replica asks again at\n // once; a round that moves the cursor nowhere ends it.\n const synchronize = Effect.gen(function* () {\n while (yield* exchangeOnce()) {}\n }).pipe(\n Effect.withSpan('Sync.synchronize'),\n // Any failed exchange, a refused response included, is what a UI shows,\n // so it is recorded and announced rather than left for the next submit.\n Effect.tapError(error =>\n Effect.gen(function* () {\n yield* Effect.logWarning('sync exchange failed', {\n documentId,\n replicaId,\n error: error.message,\n })\n yield* Ref.set(lastError, error.message)\n yield* PubSub.publish(statusSignals, undefined)\n }),\n ),\n )\n\n const start: Effect.Effect<void, never, Transport> = Effect.gen(function* () {\n const transport = yield* Transport\n // A server's notice wakes the loop as a submit does; the fiber ends with this one.\n // It starts at once so it is subscribed before the first exchange, which a\n // notice may arrive during.\n if (transport.changes !== undefined)\n yield* Effect.forkChild(\n Stream.runForEach(transport.changes, () => Queue.offer(wake, undefined)),\n { startImmediately: true },\n )\n let failures = 0\n while (!(yield* Ref.get(closed))) {\n const exit = yield* Effect.exit(synchronize)\n if (yield* Ref.get(closed)) return\n if (exit._tag === 'Success') {\n failures = 0\n yield* Queue.take(wake)\n } else {\n // Retried on a backoff, or sooner on a submit: an outbox must not\n // wait for the next keystroke to be delivered.\n failures += 1\n const backoff = Math.min(\n START_RETRY_MAX,\n START_RETRY_BASE * 2 ** Math.min(failures - 1, 16),\n )\n yield* Effect.raceFirst(Queue.take(wake), Effect.sleep(backoff))\n }\n }\n })\n\n return {\n replicaId,\n shared,\n snapshot,\n committed: Effect.map(SynchronizedRef.get(stateRef), state => state.committed),\n pending: Effect.map(SynchronizedRef.get(stateRef), state => state.pending),\n cursor: Effect.map(SynchronizedRef.get(stateRef), state => state.cursor),\n status,\n statusChanges: following(status),\n changes: following(snapshot),\n submit,\n synchronize,\n start,\n close: Effect.fn('Sync.close')(function* () {\n yield* Ref.set(closed, true)\n // Wake `start` so it can observe `closed` and return.\n yield* Queue.offer(wake, undefined)\n yield* storage.close\n })(),\n }\n },\n (effect, _replicaId, storage) =>\n // Close a partially initialized storage on any failure, including a\n // defect, so a failed open cannot leak the connection.\n effect.pipe(\n Effect.onExit(exit =>\n Exit.isSuccess(exit) ? Effect.void : storage.close.pipe(Effect.ignore),\n ),\n ),\n )\n\n return {\n documentId,\n durable: definition.durable,\n codec: { normalizeOperation, operationFrom, committedFrom, decodeExchange },\n journalContract,\n openReplica,\n }\n}\n","/**\n * The Foldkit-facing sync layer: `Sync.forApplication(App).make(config)`\n * compiles an application, a writable projection, and a durable Message subset\n * into the low-level `defineSync` contract, and exposes a read-only Surface over\n * the same projection.\n */\nimport { Equal, Option, Predicate, Schema } from 'effect'\nimport {\n MessageSet,\n Projection,\n Surface,\n type AppScope,\n type Contract,\n type MergeConstructors,\n type MergeFields,\n type RunnableApplication,\n type Wiring,\n type WritableProjection,\n} from 'foldkit-surface'\nimport type { DocumentId } from './ids.js'\nimport {\n defineSync,\n type CommitStamp,\n type JournalContract,\n type Operation,\n type Sync,\n} from './sync.js'\n\ntype MessageConstructor<Message> = (...args: never[]) => Message\n\n/** The Message union a tuple of constructors produces. */\nexport type MsgOf<Ms extends readonly unknown[]> = Ms[number] extends (...args: never[]) => infer M\n ? M\n : never\n\ntype AppMessage<\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n> = Schema.Schema.Type<AppScope<AppModel, F, Cases>['Message']>\n\n/** Reads the tag off a Foldkit Message constructor without constructing one. */\nconst messageTag = (constructor: unknown): string | undefined => {\n const literal = (constructor as { fields?: { _tag?: { ast?: { literal?: unknown } } } }).fields\n ?._tag?.ast?.literal\n return typeof literal === 'string' ? literal : undefined\n}\n\n/** A Message's tag. The application's union is generic here, so its `_tag` is read, not typed. */\nconst tagOf = (message: unknown): Option.Option<string> =>\n Predicate.hasProperty(message, '_tag') && typeof message._tag === 'string'\n ? Option.some(message._tag)\n : Option.none()\n\n/** The `_tag` literal of the Message a constructor produces. */\ntype TagOf<C> = C extends (...args: never[]) => infer M\n ? M extends { readonly _tag: infer T extends string }\n ? T\n : never\n : never\n\n/**\n * A journal contract that also carries the declared authorization policy, in\n * the shape `makeJournal` takes, so `makeJournal({ ...contract })` applies it.\n */\nexport interface PolicyJournalContract<Operation, Shared, Principal> extends JournalContract<\n Operation,\n Shared\n> {\n readonly authorize?: (request: {\n readonly principal: Principal\n readonly operation: Operation\n readonly snapshot: Shared\n }) => AuthorizeDecision\n}\n\n/**\n * What a rule decides: allowed, refused, or refused with a reason the server\n * sends to the person whose edit it was. The shape of Durable's own decision.\n */\nexport type AuthorizeDecision = boolean | { readonly allowed: false; readonly reason: string }\n\n/** What a per-variant `authorize` rule sees before the journal commits. */\nexport interface AuthorizeRequest<Principal, Message, Shared> {\n readonly principal: Principal\n readonly message: Message\n readonly shared: Shared\n}\n\n/**\n * Per-variant policy, keyed by durable tag: `message` is that variant exactly,\n * `shared` the authoritative snapshot. A variant without a rule is allowed; the\n * server may still refuse on its own grounds.\n */\nexport type AuthorizePolicy<\n Principal,\n Fields extends Schema.Struct.Fields,\n Ms extends readonly unknown[],\n> = {\n readonly [K in TagOf<Ms[number]>]?: (\n request: AuthorizeRequest<\n Principal,\n Extract<MsgOf<Ms>, { readonly _tag: K }>,\n Schema.Struct.Type<Fields>\n >,\n ) => AuthorizeDecision\n}\n\n/**\n * Per-variant commit stamps, keyed by durable tag: each writes what the server's commit\n * decided (its sequence, its actor) into that variant, and returns the same variant. A\n * variant without one is committed as sent.\n */\nexport type StampPolicy<Ms extends readonly unknown[]> = {\n readonly [K in TagOf<Ms[number]>]?: (\n message: Extract<MsgOf<Ms>, { readonly _tag: K }>,\n commit: CommitStamp,\n ) => Extract<MsgOf<Ms>, { readonly _tag: K }>\n}\n\ninterface BaseOptions<\n Principal,\n Fields extends Schema.Struct.Fields,\n Ms extends readonly unknown[],\n> {\n readonly documentId: DocumentId\n /** Name for the generated `surface`; defaults to the document id. */\n readonly name?: string\n /**\n * Replaces the replay derived from the application's `update`. It is a pure\n * reducer over the shared subset; only durable Messages reach it, and it runs\n * during admission, replay, and optimistic projection. It is not guarded: the\n * author owns its agreement with `update`.\n */\n readonly replay?: (\n shared: Schema.Struct.Type<NoInfer<Fields>>,\n message: MsgOf<NoInfer<Ms>>,\n ) => Schema.Struct.Type<NoInfer<Fields>>\n /** Authorization the server journal applies before committing; see `AuthorizePolicy`. */\n readonly authorize?: AuthorizePolicy<Principal, NoInfer<Fields>, NoInfer<Ms>>\n /** What the server's commit writes into a durable Message; see `StampPolicy`. */\n readonly stamp?: StampPolicy<NoInfer<Ms>>\n /**\n * Merges a durable Message into the one submitted before it while that one is unsent,\n * so a burst of edits is one operation. Replaying the result must equal replaying\n * `last` then `next`; undefined keeps them apart.\n */\n readonly coalesce?: (\n last: MsgOf<NoInfer<Ms>>,\n next: MsgOf<NoInfer<Ms>>,\n ) => MsgOf<NoInfer<Ms>> | undefined\n}\n\nexport interface MakeOptions<\n AppModel,\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<any>[],\n Principal = unknown,\n> extends BaseOptions<Principal, Fields, Ms> {\n /** The writable projection of the shared fields. */\n readonly shared: WritableProjection<AppModel, Fields>\n /** The Message subset the replica durably records and replays. */\n readonly durable: MessageSet<AppModel, any, Subset, Ms>\n}\n\n/**\n * One feature's contribution to a document: the fields it shares and the\n * Messages it records. `compose` merges fragments into one, to spread into\n * `make`; a field declared twice with a different codec or a tag declared twice\n * is rejected there.\n */\nexport interface SyncFragment<\n AppModel,\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<any>[],\n> {\n readonly shared: WritableProjection<AppModel, Fields>\n readonly durable: MessageSet<AppModel, any, Subset, Ms>\n}\n\ntype SharedOf<Fs extends readonly SyncFragment<any, any, any, any>[]> = {\n readonly [K in keyof Fs]: Fs[K]['shared']\n}\ntype DurableOf<Fs extends readonly SyncFragment<any, any, any, any>[]> = {\n readonly [K in keyof Fs]: Fs[K]['durable']\n}\n/** The merged shared fields of several fragments. */\nexport type FragmentFields<Fs extends readonly SyncFragment<any, any, any, any>[]> = MergeFields<\n SharedOf<Fs>\n>\n/** The concatenated durable constructors of several fragments. */\nexport type FragmentConstructors<Fs extends readonly SyncFragment<any, any, any, any>[]> =\n MergeConstructors<DurableOf<Fs>>\n\n/** The union of Messages several fragments record. */\nexport type FragmentMessages<Fs extends readonly SyncFragment<any, any, any, any>[]> =\n Fs[number] extends SyncFragment<any, any, infer V, any> ? V : never\n\n/**\n * The value `make` returns: the low-level `Sync` protocol plus the writable\n * projection, the declared Messages, and a read-only Surface over the\n * projection. Exported so a consumer can name the type.\n */\nexport interface DefinedSync<\n AppModel,\n Fields extends Schema.Struct.Fields,\n Message,\n Ms extends readonly unknown[],\n Principal = unknown,\n /** `true` when `make` was given `authorize`, so the contract's `authorize` is present. */\n Authorized extends boolean = false,\n> extends Sync<Message, Schema.Struct.Type<Fields>> {\n readonly surface: Surface<AppModel, Schema.Struct.Type<Fields>, MsgOf<Ms>, void>\n readonly projection: WritableProjection<AppModel, Fields>\n /** The reducer the replica replays durable Messages with: derived from `update`, or `make`'s `replay`. */\n readonly replay: (\n shared: Schema.Struct.Type<Fields>,\n message: Message,\n ) => Schema.Struct.Type<Fields>\n readonly messages: Ms\n /** For `Module`: this contract owns the shared projection's paths and records the durable tags. */\n readonly contract: Contract\n /**\n * How this contract joins an assembly: contract-only, so the Module sees it.\n * It routes nothing, runs nothing, and subscribes to nothing; Sync owns the\n * runtime through `mount` rather than joining it.\n */\n readonly wiring: () => Wiring<AppModel, never>\n /** The durable journal's codecs, reducer, and, when declared, authorization. */\n readonly journalContract: () => Authorized extends true\n ? PolicyJournalContract<Operation, Schema.Struct.Type<Fields>, Principal> &\n Required<\n Pick<PolicyJournalContract<Operation, Schema.Struct.Type<Fields>, Principal>, 'authorize'>\n >\n : PolicyJournalContract<Operation, Schema.Struct.Type<Fields>, Principal>\n}\n\n/** The sync constructors specialized to one application. */\nexport interface ApplicationSync<\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n Principal = unknown,\n> {\n /**\n * Fixes the `Principal` that `authorize` rules see. A `Principal` cannot be a\n * positional type argument beside an inferred Model, so it is supplied here:\n * `Sync.forApplication(App).withPrincipal<User>()`. Type-only.\n */\n readonly withPrincipal: <P>() => ApplicationSync<AppModel, F, Cases, P>\n /** One feature's shared fields and durable Messages, for `compose`. */\n readonly fragment: <\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[],\n >(config: {\n readonly shared: WritableProjection<AppModel, Fields>\n readonly durable: MessageSet<AppModel, any, Subset, Ms>\n }) => SyncFragment<AppModel, Fields, Subset, Ms>\n /**\n * Merges fragments into one: `make({ documentId, ...compose(Todos, Members) })`.\n * A field declared twice with a different codec, a tag declared twice, or a\n * fragment from another application throws.\n */\n readonly compose: <const Fs extends readonly SyncFragment<AppModel, any, any, any>[]>(\n ...fragments: Fs\n ) => SyncFragment<AppModel, FragmentFields<Fs>, FragmentMessages<Fs>, FragmentConstructors<Fs>>\n readonly make: {\n <\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[],\n >(\n options: MakeOptions<AppModel, Fields, Subset, Ms, Principal> & {\n readonly authorize: AuthorizePolicy<Principal, NoInfer<Fields>, NoInfer<Ms>>\n },\n ): DefinedSync<AppModel, Fields, AppMessage<AppModel, F, Cases>, Ms, Principal, true>\n <\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[],\n >(\n options: MakeOptions<AppModel, Fields, Subset, Ms, Principal>,\n ): DefinedSync<AppModel, Fields, AppMessage<AppModel, F, Cases>, Ms, Principal>\n }\n}\n\n/**\n * Replay derived from the application's own `update`: install the shared slice\n * into the initial Model, apply the Message, and read the slice back.\n *\n * A durable Message must be a deterministic, state-only transition of the shared\n * projection. Replay refuses one that returns a Command (a live effect cannot be\n * replayed) or that changes a Model field outside the projection (the change\n * would be silently lost), so a Message that needs either stays local and emits\n * a durable fact once the effect settles.\n */\nconst derivedReplay = <\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n Fields extends Schema.Struct.Fields,\n>(\n app: RunnableApplication<AppModel, F, Cases, any>,\n shared: WritableProjection<AppModel, Fields>,\n): ((\n value: Schema.Struct.Type<Fields>,\n message: AppMessage<AppModel, F, Cases>,\n) => Schema.Struct.Type<Fields>) => {\n const { initial, update } = app\n // Per-field equivalences for the fields the projection does not own outright,\n // built once, so a violation names the fields and replay (which runs per\n // pending operation on every optimistic read) does not re-compare the shared\n // slice against itself. A partially shared field is still compared.\n const owned = new Set(shared.dependencies.filter(path => path.length === 1).map(path => path[0]))\n const fields = Object.entries(app.Model.fields)\n .filter(([key]) => !owned.has(key))\n .map(\n ([key, field]) =>\n [key, Schema.toEquivalence(field as unknown as Schema.Schema<unknown>)] as const,\n )\n return (value, message) => {\n const result = update(shared.set(initial, value), message)\n if (result.commands !== undefined && result.commands.length > 0)\n throw new Error(\n `Sync.forApplication: durable \"${Option.getOrElse(tagOf(message), () => 'untagged')}\" returned ${result.commands.length} Command(s); a durable transition is state-only`,\n )\n const next = shared.get(result.model)\n // Writing the projection back into the baseline reproduces `update`'s\n // result exactly when it touched only shared fields.\n const written = shared.set(initial, next) as Record<string, unknown>\n const actual = result.model as Record<string, unknown>\n const changed = fields.filter(([key, equal]) => !equal(actual[key], written[key]))\n if (changed.length > 0)\n throw new Error(\n `Sync.forApplication: durable \"${Option.getOrElse(tagOf(message), () => 'untagged')}\" changed Model fields outside the shared projection: ${changed.map(([key]) => key).join(', ')}`,\n )\n return next\n }\n}\n\n/**\n * Merges fragments into one. The primitives reject a conflicting field, a\n * duplicate tag, and a subset from another application.\n */\nconst composeFragments = (\n fragments: readonly SyncFragment<any, any, any, any>[],\n): SyncFragment<any, any, any, any> => {\n const compose = Projection.compose as (\n ...projections: readonly WritableProjection<any, any>[]\n ) => WritableProjection<any, any>\n const union = MessageSet.union as (\n ...subsets: readonly MessageSet<any, any, any, any>[]\n ) => MessageSet<any, any, any, any>\n return {\n shared: compose(...fragments.map(fragment => fragment.shared)),\n durable: union(...fragments.map(fragment => fragment.durable)),\n }\n}\n\n/**\n * Specializes the sync constructors to a `Surface.application`, so\n * `Sync.forApplication(App).make({ documentId, shared, durable })` derives the\n * shared codec, the initial snapshot, the durable predicate, and replay from\n * the application, and refuses a subset that belongs to another application.\n * `defineSync` remains the protocol primitive when there is no application to\n * derive from.\n */\nexport const forApplication = <\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n>(\n app: RunnableApplication<AppModel, F, Cases, any>,\n): ApplicationSync<AppModel, F, Cases> => build(app)\n\nconst build = <\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n Principal,\n>(\n app: RunnableApplication<AppModel, F, Cases, any>,\n): ApplicationSync<AppModel, F, Cases, Principal> => {\n type Message = AppMessage<AppModel, F, Cases>\n const decodeMessage = Schema.decodeUnknownSync(\n app.Message as unknown as Schema.Codec<Message, unknown>,\n )\n\n const make = (\n options: MakeOptions<AppModel, any, any, any, Principal>,\n ): DefinedSync<AppModel, any, Message, any, Principal, boolean> => {\n type Shared = Record<string, unknown>\n const { shared, durable } = options\n\n // Two applications can have structurally identical Message unions, so the\n // types cannot separate them; the owner token can.\n if (durable.owner !== app.owner)\n throw new Error('Sync.make: the durable subset belongs to a different application')\n\n const replay: (value: Shared, message: Message) => Shared =\n options.replay === undefined\n ? derivedReplay(app, shared)\n : // `durable` has already rejected anything outside the declared subset.\n (value, message) => options.replay!(value, message as never)\n const durableTags = new Set(\n (durable.constructors as readonly unknown[])\n .map(messageTag)\n .filter((tag): tag is string => tag !== undefined),\n )\n // `AppScope` does not constrain its schemas' services; a Foldkit Message union\n // and a Struct are pure, so the low-level contract's `never` is satisfied.\n const sharedCodec = shared.schema as unknown as Schema.Codec<Shared, unknown>\n const stamps = options.stamp as\n Record<string, (message: Message, commit: CommitStamp) => Message> | undefined\n const sync = defineSync<Message, Shared, unknown, unknown>({\n documentId: options.documentId,\n message: app.Message as unknown as Schema.Codec<Message, unknown>,\n shared: sharedCodec,\n empty: shared.get(app.initial),\n durable: message => Option.exists(tagOf(message), tag => durableTags.has(tag)),\n replay,\n // `durable` has already rejected anything outside the declared subset.\n coalesce: options.coalesce as\n ((last: Message, next: Message) => Message | undefined) | undefined,\n ...(stamps === undefined\n ? {}\n : {\n stamp: (message: Message, commit: CommitStamp): Message =>\n Option.match(\n Option.flatMapNullishOr(tagOf(message), tag => stamps[tag]),\n {\n onNone: () => message,\n onSome: rule => {\n const stamped = rule(message, commit)\n if (!Equal.equals(tagOf(stamped), tagOf(message)))\n throw new Error('A stamp must return the variant it was given')\n return stamped\n },\n },\n ),\n }),\n })\n\n const rules = options.authorize as\n | Record<string, (request: AuthorizeRequest<Principal, Message, Shared>) => AuthorizeDecision>\n | undefined\n const journalContract = (): PolicyJournalContract<Operation, Shared, Principal> => {\n const base = sync.journalContract()\n if (rules === undefined) return base\n return {\n ...base,\n authorize: ({ principal, operation, snapshot }) => {\n const message = decodeMessage(operation.message)\n return Option.match(\n Option.flatMapNullishOr(tagOf(message), tag => rules[tag]),\n {\n onNone: () => true,\n onSome: rule => rule({ principal, message, shared: snapshot }),\n },\n )\n },\n }\n }\n\n const readOnly: Projection<AppModel, Shared> = Projection.fromReader(sharedCodec, shared.get, {\n dependencies: shared.dependencies,\n })\n const surface = Surface.make(app, options.name ?? String(options.documentId), {\n model: () => readOnly,\n messages: durable.constructors,\n })\n const contract: Contract = {\n kind: 'sync',\n name: surface.name,\n owner: app.owner,\n owns: shared.dependencies,\n observes: shared.dependencies,\n messages: [...durable.tags],\n metadata: [],\n }\n return {\n ...sync,\n journalContract,\n surface,\n projection: shared,\n replay,\n messages: durable.constructors,\n contract,\n wiring: () => ({ key: `sync:${contract.name}`, handles: [], contract }),\n }\n }\n\n return {\n withPrincipal: <P>() => build<AppModel, F, Cases, P>(app),\n fragment: config => {\n if (config.durable.owner !== app.owner)\n throw new Error('Sync.fragment: the durable subset belongs to a different application')\n return { shared: config.shared, durable: config.durable }\n },\n compose: ((...fragments: readonly SyncFragment<any, any, any, any>[]) =>\n composeFragments(fragments)) as ApplicationSync<AppModel, F, Cases, Principal>['compose'],\n make: make as ApplicationSync<AppModel, F, Cases, Principal>['make'],\n }\n}\n","/**\n * `Sync.mount`: runs a Foldkit application over a replica with one reducer.\n *\n * A durable Message is a state-only, deterministic transition of the shared\n * projection (the derived replay enforces it), so the application's own `update`\n * is applied at once and the Message is persisted afterwards in a Command. The\n * shared slice is re-installed from the replica when an exchange changes it or\n * a persist fails, through one private Message the application never sees.\n */\nimport { Effect, Exit, Layer, Option, Schema, Stream } from 'effect'\nimport { absurd } from 'effect/Function'\nimport type { Document, HtmlBuilder } from 'foldkit/html'\nimport * as Navigation from 'foldkit/navigation'\nimport type { UrlRequest } from 'foldkit/navigation'\nimport * as Port from 'foldkit/port'\nimport * as Runtime from 'foldkit/runtime'\nimport * as Subscription from 'foldkit/subscription'\nimport type { Subscriptions } from 'foldkit/subscription'\nimport type * as Update from 'foldkit/update'\nimport * as Url from 'foldkit/url'\nimport type { RunnableApplication } from 'foldkit-surface'\nimport type { ReplicaError } from './errors.js'\nimport type { DefinedSync } from './make.js'\nimport type { Replica, ReplicaStatus } from './sync.js'\n\nconst REFRESH = 'foldkit-sync/Refresh'\nconst PERSISTED = 'foldkit-sync/Persisted'\nconst FAILED = 'foldkit-sync/PersistenceFailed'\nconst NAVIGATE = 'foldkit-sync/Navigate'\nconst NAVIGATED = 'foldkit-sync/Navigated'\nconst DISPATCHED = 'foldkit-sync/Dispatched'\n\ntype Private =\n // Every replica status, applied in order, so `settled` counts one seen only once `update` has it.\n | { readonly _tag: typeof REFRESH; readonly status: ReplicaStatus; readonly changed: boolean }\n | { readonly _tag: typeof PERSISTED }\n | { readonly _tag: typeof FAILED; readonly error: ReplicaError }\n | { readonly _tag: typeof NAVIGATE; readonly request: UrlRequest }\n | { readonly _tag: typeof NAVIGATED }\n // An application Message sent through `dispatch`, so `settled` counts it in.\n | { readonly _tag: typeof DISPATCHED; readonly message: unknown }\n\n// A key per private tag, so a variant added to `Private` must be added here too.\nconst PRIVATE: Readonly<Record<Private['_tag'], true>> = {\n [REFRESH]: true,\n [PERSISTED]: true,\n [FAILED]: true,\n [NAVIGATE]: true,\n [NAVIGATED]: true,\n [DISPATCHED]: true,\n}\n\nconst isPrivate = (message: { readonly _tag: string }): message is Private =>\n Object.hasOwn(PRIVATE, message._tag)\n\n// A registered symbol, so two copies of this package in one bundle recognize each other's.\nconst FACT = Symbol.for('foldkit-sync/fact')\n\n/**\n * A Command that dispatches `message` as the next transition, which under `Sync.mount`\n * means within this one: the mount applies it straight after the `update` that returned\n * it, and persists it if it is durable, before any other Message is processed. This is\n * how a local intent turns into a durable fact that needs something only the intent's\n * transition knows, such as an id minted from local state, without a later Message\n * seeing the Model before the fact. Elsewhere, or once a parent has mapped the Command,\n * it is an ordinary Command that yields `message`, and so is one a durable Message's\n * update returns: replay would not apply it, and with derived replay the durable Message's\n * persist fails with `ReplayError` as for any Command.\n */\nexport const fact = <Message>(\n message: Message,\n): { readonly name: string; readonly effect: Effect.Effect<Message> } =>\n // Not enumerable, so the spread a mapping Command is copied with drops the marker, and a\n // mapped fact is the ordinary Command it now is rather than the unmapped Message.\n Object.defineProperty({ name: 'foldkit-sync/fact', effect: Effect.succeed(message) }, FACT, {\n value: message,\n enumerable: false,\n })\n\nconst factOf = (command: unknown): { readonly message: unknown } | undefined =>\n typeof command === 'object' && command !== null && FACT in command\n ? { message: (command as { readonly [FACT]: unknown })[FACT] }\n : undefined\n\n/**\n * The URL as part of the application: `onUrlChange` names the Message the\n * runtime sends for the current URL at start and on every navigation (so a\n * `foldkit-mirror` URL mirror reads back in), `init` reduces the URL into the\n * Model before the first render, and `onUrlRequest` names the Message for a\n * link click; omitted, the mount follows the link itself (an internal one is\n * pushed, an external one loaded).\n */\nexport interface MountUrl<Model, Message> {\n readonly init?: ((model: Model, url: Url.Url) => Model) | undefined\n readonly onUrlChange: (url: Url.Url) => Message\n readonly onUrlRequest?: ((request: UrlRequest) => Message) | undefined\n}\n\nexport interface MountOptions<Model, Message, Shared, Resources> {\n /** An open replica of this contract; `mount` does not close it. */\n readonly replica: Replica<Message, Shared>\n /** The element the application renders into; Foldkit requires it to have an `id`. */\n readonly container: HTMLElement\n readonly view: (model: Model, h: HtmlBuilder<Message>) => Document\n readonly subscriptions?: Subscriptions<Model, Message, Resources> | undefined\n readonly resources?: Layer.Layer<Resources> | undefined\n /** Route the URL through the application; without it the mount ignores the URL. */\n readonly url?: MountUrl<Model, Message> | undefined\n /**\n * Reflects a refused or failed persist in the Model, after the durable edit\n * has been reverted. Omitted, the edit is reverted silently.\n */\n readonly onPersistenceFailure?: ((model: Model, error: ReplicaError) => Model) | undefined\n /**\n * Runs when the mount replaces the shared slice outside `update`: an exchange committed,\n * acknowledged or rejected something, or a persist failed and its edit was reverted.\n * `previous` is the Model before; what it returns is the transition, so an application\n * can carry local state across the change (a selection held by what it points at) or\n * return Commands (a DOM the change has to reach). Omitted, the Model is `next`. It is\n * not called for a status that changes nothing the Model shows, such as the first.\n */\n readonly onReinstall?:\n | ((\n next: Model,\n previous: Model,\n change: Reinstall,\n ) => Update.Return<Model, Message, Resources>)\n | undefined\n /**\n * Runs on the Model after every update of the mounted application, a durable\n * Message's and a reinstall's included, and never in replay: for local state\n * derived from the shared slice, which a durable transition may not write\n * (the overlays `foldkit-sync/remote` keeps in Remote). With nothing to\n * change it returns the Model it was given.\n */\n readonly afterUpdate?: ((model: Model) => Update.Return<Model, Message, Resources>) | undefined\n}\n\n/**\n * What a reinstall came from. `reset` is a server reset: the replica's\n * committed history is a new one, so anything an application derived from\n * the old one (reads cached by commit sequence, say) is to be read again.\n */\nexport interface Reinstall {\n readonly reset: boolean\n}\n\n/**\n * The shared slice as the server has confirmed it, outside the Model. It is a\n * source for waiting consumers, the shape `Agent.when({ source })` reads, and\n * not a Projection: it does not render and is not derived from the Model.\n */\nexport interface CommittedView<Shared> {\n readonly get: () => Shared\n /** Told after every exchange, including one that moves no cursor (a checkpoint). */\n readonly subscribe: (listener: () => void) => () => void\n}\n\nexport interface Mounted<Model, Message, Shared = unknown> {\n /** Sends an application Message through the runtime; the `Exit` reports a decode failure. */\n readonly dispatch: (message: Message) => Exit.Exit<void, unknown>\n /** The Model after the last transition. */\n readonly model: () => Model\n /** Notified after every transition; with `model` and `dispatch`, the host an agent binds to. */\n readonly subscribe: (listener: () => void) => () => void\n /**\n * Every application Message the runtime applies, from any origin, so an\n * agent contract that declares a `completion` can see the Message that\n * finishes its work. The mount's private Messages are not reported.\n */\n readonly observe: (listener: (message: Message) => void) => () => void\n /**\n * The shared slice without pending local edits, for an agent that must not\n * report an optimistic edit as done: `Agent.when({ source: mounted.committed, … })`.\n */\n readonly committed: CommittedView<Shared>\n /**\n * Resolves once the Model has caught up with the replica: no persist in\n * flight or unanswered, every replica status the mount was told of seen,\n * and every reinstall it asked for applied. It observes and never does the\n * work. Frames are not its to wait for (`Frames.track` in\n * `foldkit-mixins/testing` is), nor I/O a Command started. Rejects after\n * `dispose`.\n */\n readonly settled: () => Promise<void>\n /** Waits for in-flight persists, then disposes the runtime. The replica stays open. */\n readonly dispose: () => Promise<void>\n}\n\n/**\n * Commits, rejections and acknowledgments change what the replica holds; a\n * submit only echoes a local edit. An acknowledgment that does not return the\n * operation moves no cursor, but it still drops the edit from the outbox.\n */\nconst sharedChanged = (previous: ReplicaStatus | undefined, next: ReplicaStatus): boolean =>\n previous === undefined ||\n previous.cursor !== next.cursor ||\n next.pending < previous.pending ||\n previous.rejected.length !== next.rejected.length ||\n previous.rejected.some((rejection, index) => rejection.opId !== next.rejected[index]?.opId)\n\n/**\n * A durable edit the Model already shows. `started` is the replica's next local\n * sequence when its submit began, `undefined` while it waits for its turn.\n */\nexport interface LocalEdit<Message> {\n readonly message: Message\n started: number | undefined\n}\n\n/**\n * The edits a replica whose next local sequence is `next` does not hold yet.\n * Submits run one at a time, so the one in flight is in the replica exactly\n * when its submit has moved the sequence past `started`.\n */\nexport const unconfirmedEdits = <Message>(\n edits: ReadonlyArray<LocalEdit<Message>>,\n next: number,\n): ReadonlyArray<Message> =>\n edits.filter(edit => edit.started === undefined || next <= edit.started).map(edit => edit.message)\n\n/** The application's Message union, as `Surface.application` types it. */\ntype MessageOf<App> =\n App extends RunnableApplication<any, any, any, any> ? Schema.Schema.Type<App['Message']> : never\n\nexport const mount = <\n Model,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n Fields extends Schema.Struct.Fields,\n Ms extends readonly unknown[],\n Resources = never,\n Principal = unknown,\n>(\n app: RunnableApplication<Model, F, Cases, Resources>,\n sync: DefinedSync<\n Model,\n Fields,\n MessageOf<RunnableApplication<Model, F, Cases, Resources>>,\n Ms,\n Principal\n >,\n options: MountOptions<\n Model,\n MessageOf<RunnableApplication<Model, F, Cases, Resources>>,\n Schema.Struct.Type<Fields>,\n Resources\n >,\n): Mounted<\n Model,\n MessageOf<RunnableApplication<Model, F, Cases, Resources>>,\n Schema.Struct.Type<Fields>\n> => {\n // Foldkit reports a missing id only inside the runtime fiber, where nothing\n // renders and nothing is thrown; fail here instead.\n if (options.container.id === '')\n throw new Error('Sync.mount: the container needs an id (`container.id = \"app\"`)')\n type Message = MessageOf<RunnableApplication<Model, F, Cases, Resources>>\n // The application's Messages are tagged structs; the generic cannot say so.\n type Tagged = { readonly _tag: string }\n type RuntimeMessage = (Message & Tagged) | Private\n type Shared = Schema.Struct.Type<Fields>\n const { replica } = options\n const durable = new Set(sync.contract.messages)\n\n // Durable edits whose submit has not settled, in dispatch order.\n const edits: Array<LocalEdit<Message>> = []\n // An edit shows before it is stored, so a reload while one waits would lose\n // what the reader saw: the browser asks first, from the first such edit\n // until the last is stored.\n const holdUnload = (event: Event): void => event.preventDefault()\n const unloadGuarded = (guarded: boolean): void => {\n if (typeof window === 'undefined') return\n if (guarded) window.addEventListener('beforeunload', holdUnload)\n else window.removeEventListener('beforeunload', holdUnload)\n }\n // Settles when the latest edit's submit does; the next submit waits for it.\n let tail: Promise<void> = Promise.resolve()\n\n // The replica's `shared` holds every settled edit, and the one in flight once\n // its submit lands; the rest are replayed on top. Read from one snapshot, so\n // a refresh neither hides an edit still waiting for the replica nor applies\n // one the replica already holds.\n // The replica's shared value the Model was last installed from, and whether a durable\n // edit has changed the Model's copy since. The replica keeps one object per state, so\n // the same object with no edit since is the shared slice the Model already shows.\n let installedFrom: Shared | undefined\n let editedSinceInstall = false\n const install = (model: Model): Model => {\n const snapshot = Effect.runSync(replica.snapshot)\n installedFrom = snapshot.shared\n editedSinceInstall = false\n const shared = unconfirmedEdits(edits, snapshot.nextLocalSequence).reduce<Shared>(\n (value, message) => {\n try {\n return sync.replay(value, message)\n } catch {\n // The replica refuses it too; its FAILED re-installs without it.\n return value\n }\n },\n snapshot.shared,\n )\n return sync.projection.set(model, shared)\n }\n\n const inFlight = new Set<Promise<void>>()\n // What `settled` waits on: dispatches and persists not yet answered in\n // `update`, and the last replica status `update` applied.\n let dispatchesOwed = 0\n let persistsOwed = 0\n let applied: ReplicaStatus | undefined\n let disposed = false\n const waiters = new Set<{\n readonly resolve: () => void\n readonly reject: (error: Error) => void\n }>()\n const quiet = (): boolean =>\n dispatchesOwed === 0 &&\n persistsOwed === 0 &&\n !sharedChanged(applied, Effect.runSync(replica.status))\n const notifySettled = (): void => {\n if (!quiet()) return\n for (const waiter of [...waiters]) {\n waiters.delete(waiter)\n waiter.resolve()\n }\n }\n /**\n * A private transition that leaves the Model as it was: the runtime sends\n * no Subscription the change, so `settled` is told here, once it returns.\n */\n const unchanged = (model: Model): Update.Return<Model, RuntimeMessage, Resources> => {\n queueMicrotask(notifySettled)\n return { model }\n }\n let latest: Model = install(app.initial)\n const modelListeners = new Set<() => void>()\n const committedListeners = new Set<() => void>()\n const messageListeners = new Set<(message: Message) => void>()\n // Listeners run inside `update`, a Subscription, and the refresh stream. A\n // throwing one must not break those or skip the listeners after it, so its\n // error is reported asynchronously, as an event listener's would be.\n const notifyEach = <A>(listeners: ReadonlySet<(value: A) => void>, value: A): void => {\n for (const listener of [...listeners]) {\n try {\n listener(value)\n } catch (error) {\n queueMicrotask(() => {\n throw error\n })\n }\n }\n }\n const notifyCommitted = (): void => notifyEach(committedListeners, undefined)\n\n const updatePrivate = (\n model: Model,\n message: Private,\n ): Update.Return<Model, RuntimeMessage, Resources> => {\n switch (message._tag) {\n // Installs at once: edits still waiting for the replica are replayed on\n // top, so nothing is deferred behind them.\n case REFRESH: {\n // The server's history changed under the replica: a reset.\n const reset =\n applied !== undefined &&\n Option.isSome(applied.epoch) &&\n Option.isSome(message.status.epoch) &&\n applied.epoch.value !== message.status.epoch.value\n applied = message.status\n // The first status, and any other that changed nothing the Model shows, reinstall\n // nothing, so `onReinstall` hears only of a real change.\n if (\n !message.changed ||\n (!editedSinceInstall && Effect.runSync(replica.snapshot).shared === installedFrom)\n ) {\n return unchanged(model)\n }\n return reinstalled(install(model), model, { reset })\n }\n case PERSISTED:\n persistsOwed--\n return unchanged(model)\n case FAILED: {\n persistsOwed--\n const { error } = message\n const reverted = install(model)\n return reinstalled(options.onPersistenceFailure?.(reverted, error) ?? reverted, model, {\n reset: false,\n })\n }\n case NAVIGATE: {\n // A link the application did not claim: follow it. The runtime then\n // reports the new URL through `onUrlChange`.\n const { request } = message\n const follow =\n request._tag === 'Internal'\n ? Navigation.pushUrl(Url.toString(request.url))\n : Navigation.load(request.href)\n return {\n model,\n commands: [\n {\n name: 'foldkit-sync/navigate',\n effect: follow.pipe(Effect.as({ _tag: NAVIGATED } as RuntimeMessage)),\n },\n ],\n }\n }\n case NAVIGATED:\n return { model }\n case DISPATCHED:\n dispatchesOwed--\n return transition(model, message.message as Message & Tagged)\n default:\n return absurd(message)\n }\n }\n\n const update = (\n model: Model,\n message: RuntimeMessage,\n ): Update.Return<Model, RuntimeMessage, Resources> => {\n const result = isPrivate(message)\n ? updatePrivate(model, message)\n : transition(model, message as Message & Tagged)\n if (options.afterUpdate === undefined) return result\n const after = applyFacts(\n options.afterUpdate(result.model) as Update.Return<Model, RuntimeMessage, Resources>,\n )\n return after.model === result.model && (after.commands ?? []).length === 0\n ? result\n : { model: after.model, commands: [...(result.commands ?? []), ...(after.commands ?? [])] }\n }\n\n const reinstalled = (\n next: Model,\n previous: Model,\n change: Reinstall,\n ): Update.Return<Model, RuntimeMessage, Resources> =>\n options.onReinstall === undefined\n ? { model: next }\n : applyFacts(\n options.onReinstall(next, previous, change) as Update.Return<\n Model,\n RuntimeMessage,\n Resources\n >,\n )\n\n /** The application's transition for one of its Messages, with the persist a durable one needs. */\n const step = (\n model: Model,\n message: Message & Tagged,\n ): Update.Return<Model, RuntimeMessage, Resources> => {\n notifyEach(messageListeners, message)\n const result = app.update(model, message) as Update.Return<Model, RuntimeMessage, Resources>\n if (!durable.has(message._tag)) return result\n editedSinceInstall = true\n persistsOwed++\n const edit: LocalEdit<Message> = { message, started: undefined }\n edits.push(edit)\n if (edits.length === 1) unloadGuarded(true)\n const previous = tail\n let settle!: () => void\n const done = new Promise<void>(resolve => {\n settle = resolve\n })\n tail = done\n const release = (): void => {\n const index = edits.indexOf(edit)\n if (index !== -1) edits.splice(index, 1)\n if (edits.length === 0) unloadGuarded(false)\n inFlight.delete(done)\n settle()\n }\n const persist = {\n name: 'foldkit-sync/persist',\n effect: Effect.gen(function* () {\n // Tracked so `dispose` can wait instead of interrupting a persist.\n inFlight.add(done)\n // One submit at a time, in dispatch order, so `started` is the\n // sequence this edit takes if its submit succeeds.\n yield* Effect.promise(() => previous)\n edit.started = (yield* replica.snapshot).nextLocalSequence\n const outcome = yield* Effect.result(replica.submit(edit.message))\n return outcome._tag === 'Success'\n ? ({ _tag: PERSISTED } as RuntimeMessage)\n : ({ _tag: FAILED, error: outcome.failure } as RuntimeMessage)\n }).pipe(\n // `ensuring`, so a defect in storage still releases the next submit and `dispose`.\n Effect.ensuring(Effect.sync(release)),\n ),\n }\n return { model: result.model, commands: [...(result.commands ?? []), persist] }\n }\n\n /**\n * A Message's transition, with the facts it returned applied after it. A durable\n * Message's are not: replay would not apply them, so they stay ordinary Commands.\n */\n const transition = (\n model: Model,\n message: Message & Tagged,\n ): Update.Return<Model, RuntimeMessage, Resources> => {\n const result = step(model, message)\n return durable.has(message._tag) ? result : applyFacts(result)\n }\n\n /** Applies the facts a transition returned, in order, each as the transition after it. */\n const applyFacts = (\n result: Update.Return<Model, RuntimeMessage, Resources>,\n ): Update.Return<Model, RuntimeMessage, Resources> => {\n let model = result.model\n const kept: Array<Update.Commands<RuntimeMessage, Resources>[number]> = []\n for (const command of result.commands ?? []) {\n const found = factOf(command)\n if (found === undefined) {\n kept.push(command)\n continue\n }\n const next = transition(model, found.message as Message & Tagged)\n model = next.model\n kept.push(...(next.commands ?? []))\n }\n return { model, commands: kept }\n }\n\n const ports = {\n inbound: { message: Port.inbound(app.Message as unknown as Schema.Codec<Message, unknown>) },\n }\n const own = Subscription.make<Model, RuntimeMessage, Resources>()(() => ({\n message: Port.subscriptionEntry(ports.inbound.message, (message): RuntimeMessage => ({\n _tag: DISPATCHED,\n message,\n })),\n // The replica's status carries the cursor and rejections, which is exactly\n // when the shared slice held locally can differ from the replica's.\n refresh: Subscription.persistentEntry<RuntimeMessage, Resources>(\n replica.statusChanges.pipe(\n // Every status, not only a changed cursor: a checkpoint at the same\n // cursor still replaces the committed state a waiter reads.\n Stream.tap(() => Effect.sync(notifyCommitted)),\n Stream.mapAccum(\n (): ReplicaStatus | undefined => undefined,\n (previous, status): readonly [ReplicaStatus, ReadonlyArray<RuntimeMessage>] => [\n status,\n [{ _tag: REFRESH, status, changed: sharedChanged(previous, status) }],\n ],\n ),\n ),\n ),\n // `modelToDependencies` runs on every transition, so it doubles as the Model\n // getter the runtime does not expose.\n latest: {\n dependenciesSchema: Schema.Struct({}),\n modelToDependencies: (model: Model) => {\n latest = model\n notifyEach(modelListeners, undefined)\n // After every transition, so `settled` resolves once `model()` has it.\n notifySettled()\n return {}\n },\n dependenciesToStream: () => Stream.never,\n },\n }))\n const subscriptions =\n options.subscriptions === undefined\n ? own\n : Subscription.aggregate<Model, RuntimeMessage, Resources>()(\n options.subscriptions as Subscriptions<Model, RuntimeMessage, Resources>,\n own,\n )\n\n const view = (model: Model, h: HtmlBuilder<RuntimeMessage>): Document =>\n // Sound: the view constructs only application Messages, a subset of the\n // runtime's union.\n options.view(model, h as unknown as HtmlBuilder<Message>)\n const common = {\n Model: app.Model as unknown as Schema.Codec<Model, any, unknown, unknown>,\n container: options.container,\n ports,\n update,\n subscriptions,\n ...(options.resources === undefined ? {} : { resources: options.resources }),\n view,\n }\n const url = options.url\n const program =\n url === undefined\n ? Runtime.makeApplication({ ...common, init: () => ({ model: latest }) })\n : Runtime.makeApplication({\n ...common,\n routing: {\n onUrlChange: (at: Url.Url) => url.onUrlChange(at) as RuntimeMessage,\n onUrlRequest: (request: UrlRequest): RuntimeMessage =>\n url.onUrlRequest === undefined\n ? { _tag: NAVIGATE, request }\n : (url.onUrlRequest(request) as RuntimeMessage),\n },\n init: (at: Url.Url) => {\n latest = url.init === undefined ? latest : url.init(latest, at)\n return { model: latest }\n },\n })\n const handle = Runtime.embed(program)\n const encodeMessage = Schema.encodeExit(app.Message as unknown as Schema.Codec<Message, unknown>)\n\n return {\n // The port decodes what it is sent, so it takes the Message encoded: a\n // Message is sent as its type is, Option fields and all.\n dispatch: message =>\n Exit.match(encodeMessage(message), {\n onSuccess: encoded => {\n // Counted before the send, in case the port delivers within it.\n dispatchesOwed++\n const sent = handle.ports.message.send(encoded)\n if (Exit.isFailure(sent)) dispatchesOwed--\n return sent\n },\n onFailure: cause => Exit.failCause(cause),\n }),\n model: () => latest,\n subscribe: listener => {\n modelListeners.add(listener)\n return () => modelListeners.delete(listener)\n },\n observe: listener => {\n messageListeners.add(listener)\n return () => messageListeners.delete(listener)\n },\n committed: {\n get: () => Effect.runSync(replica.committed),\n subscribe: listener => {\n committedListeners.add(listener)\n return () => committedListeners.delete(listener)\n },\n },\n settled: () => {\n if (disposed) return Promise.reject(new Error('Sync.mount: settled() after dispose'))\n if (quiet()) return Promise.resolve()\n return new Promise<void>((resolve, reject) => waiters.add({ resolve, reject }))\n },\n dispose: async () => {\n disposed = true\n for (const waiter of [...waiters]) {\n waiters.delete(waiter)\n waiter.reject(new Error('Sync.mount: disposed before it settled'))\n }\n await Promise.all([...inFlight])\n handle.dispose()\n },\n }\n}\n","import {\n Clock,\n Duration,\n Effect,\n Fiber,\n PubSub,\n Ref,\n Stream,\n SynchronizedRef,\n type Scope,\n} from 'effect'\nimport type { SocketLike } from './transport.js'\n\n/** One peer's presence. A `null` value means the peer left. */\nexport interface PresenceUpdate<Update> {\n readonly id: string\n readonly value: Update | null\n}\n\n/**\n * The ephemeral channel presence travels on.\n *\n * `updates` is the inbound bus a peer consumes; `publish` sends one to the bus.\n * Splitting them keeps an inbound update from being echoed straight back out.\n * This is deliberately not the durable transport: presence is broadcast, never\n * journaled, so a dropped or duplicated update is harmless.\n */\nexport interface PresenceChannel<Update> {\n readonly updates: PubSub.PubSub<PresenceUpdate<Update>>\n readonly publish: (update: PresenceUpdate<Update>) => Effect.Effect<void>\n}\n\nexport interface PresenceOptions<Update> {\n /** This peer's identity on the channel. */\n readonly id: string\n /** How long a peer may go without refreshing before it is dropped. */\n readonly ttl: Duration.Input\n /**\n * Validates the untrusted value a peer sends before it is stored. Presence\n * crosses a wire, so this is required rather than trusting the type\n * parameter; a value it rejects is dropped.\n */\n readonly decodeValue: (value: unknown) => Update\n readonly channel?: PresenceChannel<Update> | undefined\n /**\n * The least time between two values sent on the channel. `set` still takes effect here at\n * once; a value set sooner waits, and only the latest one waiting is sent when the time is\n * up. A departure is never held back. Absent, every `set` is sent at once.\n */\n readonly throttle?: Duration.Input | undefined\n}\n\nexport interface PresencePeer<Update> {\n readonly id: string\n readonly value: Update\n readonly updatedAt: number\n}\n\nexport interface Presence<Update> {\n /** Sets this peer's value and broadcasts it, no sooner than `throttle` allows. */\n readonly set: (value: Update) => Effect.Effect<void>\n /** Removes this peer and broadcasts the departure. */\n readonly leave: Effect.Effect<void>\n /** Live peers, self included, with stale ones excluded. */\n readonly peers: Effect.Effect<ReadonlyArray<PresencePeer<Update>>>\n /** Drops expired peers; notifies if any went. */\n readonly prune: Effect.Effect<void>\n /** Notified when the peer set changes. */\n readonly subscribe: (listener: () => void) => () => void\n /**\n * The live peers, re-emitted whenever the set changes. The `Stream` form of\n * `subscribe`, for a consumer that composes with Effect.\n */\n readonly changes: Stream.Stream<ReadonlyArray<PresencePeer<Update>>>\n /** Stops consuming the channel; the enclosing scope also does this on exit. */\n readonly close: Effect.Effect<void>\n}\n\n/**\n * Tracks ephemeral peers with a time-to-live.\n *\n * Nothing here touches the durable log: presence is state a peer refreshes, and\n * a peer that stops refreshing is dropped, not replayed. Time comes from the\n * `Clock`, so a `TestClock` drives the TTL deterministically.\n */\nexport const createPresence = Effect.fn('Presence.create')(function* <Update>(\n options: PresenceOptions<Update>,\n) {\n const ttl = Duration.toMillis(options.ttl)\n const throttle = options.throttle === undefined ? 0 : Duration.toMillis(options.throttle)\n const scope = yield* Effect.scope\n // What a throttled channel has sent and holds. Every decision about it is made under\n // this one lock, so two `set`s cannot both send in one interval, a value held while a\n // flush finds nothing cannot be stranded, and a flush is never forked and lost.\n const outbound = yield* SynchronizedRef.make<{\n readonly lastSent: number | undefined\n readonly held: { readonly value: Update } | undefined\n readonly flusher: Fiber.Fiber<void> | undefined\n }>({ lastSent: undefined, held: undefined, flusher: undefined })\n const peers = yield* Ref.make(new Map<string, PresencePeer<Update>>())\n const closed = yield* Ref.make(false)\n const signals = yield* PubSub.sliding<void>(1)\n const listeners = new Set<() => void>()\n /** A subscriber must never fail an update. */\n const notify = (): Effect.Effect<void> =>\n Effect.gen(function* () {\n for (const listener of [...listeners]) {\n try {\n listener()\n } catch {\n // Deliberately swallowed.\n }\n }\n yield* PubSub.publish(signals, undefined)\n })\n const expired = (peer: PresencePeer<Update>, at: number): boolean => at - peer.updatedAt > ttl\n\n const put = (id: string, value: Update, at: number): Effect.Effect<void> =>\n Ref.update(peers, map => {\n const next = new Map(map)\n next.set(id, { id, value, updatedAt: at })\n return next\n })\n const remove = (id: string): Effect.Effect<boolean> =>\n Ref.modify(peers, map => {\n if (!map.has(id)) return [false, map] as const\n const next = new Map(map)\n next.delete(id)\n return [true, next] as const\n })\n\n const receive = Effect.fn('Presence.receive')(function* (update: PresenceUpdate<Update>) {\n if (update.id === options.id) return\n if (update.value === null) {\n if (yield* remove(update.id)) yield* notify()\n return\n }\n let value: Update\n try {\n value = options.decodeValue(update.value)\n } catch {\n // A peer's value that fails the contract is dropped, never stored.\n return\n }\n yield* put(update.id, value, yield* Clock.currentTimeMillis)\n yield* notify()\n })\n\n const channel = options.channel\n const consuming =\n channel === undefined\n ? undefined\n : yield* Stream.runForEach(Stream.fromPubSub(channel.updates), receive).pipe(\n Effect.forkScoped,\n )\n\n const publish = (value: Update): Effect.Effect<void> =>\n channel!.publish({ id: options.id, value })\n\n /** Drops a value waiting to be sent, so nothing older goes out after what comes next. */\n const cancelHeld = SynchronizedRef.updateEffect(outbound, state =>\n (state.flusher === undefined ? Effect.void : Fiber.interrupt(state.flusher)).pipe(\n Effect.as({ ...state, held: undefined, flusher: undefined }),\n ),\n )\n\n /** Sends what is held once per interval, until an interval passes with nothing held. */\n const flush = (wait: number): Effect.Effect<void> =>\n Effect.gen(function* () {\n for (let delay = wait; ; delay = throttle) {\n yield* Effect.sleep(delay)\n const now = yield* Clock.currentTimeMillis\n const latest = yield* SynchronizedRef.modify(outbound, state =>\n state.held === undefined\n ? ([undefined, { ...state, flusher: undefined }] as const)\n : ([state.held, { ...state, held: undefined, lastSent: now }] as const),\n )\n if (latest === undefined) return\n yield* publish(latest.value)\n }\n })\n\n const broadcast = (value: Update, at: number): Effect.Effect<void> =>\n Effect.gen(function* () {\n const sends = yield* SynchronizedRef.modifyEffect(outbound, state =>\n Effect.gen(function* () {\n // `set` checked too, but `close` may have run since; a flush forked now would outlive it.\n if (yield* Ref.get(closed)) return [false, state] as const\n if (state.flusher !== undefined) return [false, { ...state, held: { value } }] as const\n // Without a throttle the wait is never positive, so every value goes at once; a\n // clock set back never makes one wait longer than an interval.\n const wait =\n state.lastSent === undefined ? 0 : Math.min(throttle, state.lastSent + throttle - at)\n if (wait <= 0) return [true, { ...state, lastSent: at }] as const\n const flusher = yield* Effect.forkIn(flush(wait), scope)\n return [false, { ...state, held: { value }, flusher }] as const\n }).pipe(Effect.uninterruptible),\n )\n if (sends) yield* publish(value)\n })\n\n const set = Effect.fn('Presence.set')(function* (value: Update) {\n if (yield* Ref.get(closed)) return\n const at = yield* Clock.currentTimeMillis\n yield* put(options.id, value, at)\n if (channel !== undefined) yield* broadcast(value, at)\n yield* notify()\n })\n\n const leave = Effect.fn('Presence.leave')(function* () {\n if (yield* Ref.get(closed)) return\n yield* cancelHeld\n yield* remove(options.id)\n if (channel !== undefined) yield* channel.publish({ id: options.id, value: null })\n yield* notify()\n })()\n\n const peerList = Effect.fn('Presence.peers')(function* () {\n const at = yield* Clock.currentTimeMillis\n const map = yield* Ref.get(peers)\n return [...map.values()].filter(peer => !expired(peer, at)).map(peer => ({ ...peer }))\n })()\n\n const prune = Effect.fn('Presence.prune')(function* () {\n if (yield* Ref.get(closed)) return\n const at = yield* Clock.currentTimeMillis\n const changed = yield* Ref.modify(peers, map => {\n let removed = false\n const next = new Map(map)\n for (const [id, peer] of map) {\n if (expired(peer, at)) {\n next.delete(id)\n removed = true\n }\n }\n return [removed, next] as const\n })\n if (changed) yield* notify()\n })()\n\n const close = Effect.fn('Presence.close')(function* () {\n if (yield* Ref.get(closed)) return\n yield* Ref.set(closed, true)\n yield* cancelHeld\n if (consuming !== undefined) yield* Fiber.interrupt(consuming)\n yield* Effect.sync(() => listeners.clear())\n yield* PubSub.shutdown(signals)\n })()\n\n return {\n set,\n leave,\n peers: peerList,\n prune,\n subscribe: (listener: () => void) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n changes: Stream.concat(\n Stream.fromEffect(peerList),\n Stream.fromPubSub(signals).pipe(Stream.mapEffect(() => peerList)),\n ),\n close,\n }\n})\n\n/** An in-process channel, for tests and single-process demos. */\nexport const loopbackPresenceChannel = Effect.fn('Presence.loopbackChannel')(function* <Update>() {\n const updates = yield* PubSub.unbounded<PresenceUpdate<Update>>()\n return {\n updates,\n publish: (update: PresenceUpdate<Update>) => PubSub.publish(updates, update),\n }\n})\n\n/** Broadcasts presence updates among connected peers. */\nexport interface PresenceHub<Update> {\n /** Registers a peer's send; returns a leave function. */\n join(send: (update: PresenceUpdate<Update>) => void): () => void\n /** Fans an update out to every joined peer. */\n publish(update: PresenceUpdate<Update>): void\n}\n\nexport const createPresenceHub = <Update>(): PresenceHub<Update> => {\n const peers = new Set<(update: PresenceUpdate<Update>) => void>()\n return {\n join: send => {\n peers.add(send)\n return () => peers.delete(send)\n },\n publish: update => {\n for (const send of [...peers]) {\n try {\n send(update)\n } catch {\n // One broken peer must not starve the rest of the fan-out.\n }\n }\n },\n }\n}\n\nconst frameType = 'presence'\n\n/** A presence frame. `id` is set by the server that owns the identity. */\ninterface PresenceFrame<Update> {\n readonly id: string | undefined\n readonly value: Update | null\n}\n\n/** Decodes a presence frame, ignoring anything else a socket may carry. */\nconst decodePresence = <Update>(data: string): PresenceFrame<Update> | undefined => {\n let frame: unknown\n try {\n frame = JSON.parse(data)\n } catch {\n return undefined\n }\n if (typeof frame !== 'object' || frame === null) return undefined\n const payload = (frame as Record<string, unknown>)[frameType]\n if (typeof payload !== 'object' || payload === null) return undefined\n const { id, value } = payload as { id?: unknown; value?: unknown }\n return { id: typeof id === 'string' ? id : undefined, value: (value ?? null) as Update | null }\n}\n\n/**\n * A presence channel fed by stamped frames from the server, sent back without an\n * id: the server owns peer identity, so a client cannot assert another's.\n */\nexport const socketPresenceChannel = <Update>(\n socket: SocketLike,\n): Effect.Effect<PresenceChannel<Update>, never, Scope.Scope> =>\n Effect.gen(function* () {\n const updates = yield* PubSub.unbounded<PresenceUpdate<Update>>()\n yield* Effect.acquireRelease(\n Effect.sync(() =>\n socket.onMessage(data => {\n const frame = decodePresence<Update>(data)\n // An unstamped frame is not from the server and carries no identity.\n if (frame === undefined || frame.id === undefined) return\n PubSub.publishUnsafe(updates, { id: frame.id, value: frame.value })\n }),\n ),\n off => Effect.sync(off),\n )\n return {\n updates,\n publish: update =>\n Effect.sync(() => socket.send(JSON.stringify({ [frameType]: { value: update.value } }))),\n }\n })\n\n/**\n * Serves presence frames on an accepted socket, stamping the connection's\n * identity, until the socket closes or the returned function is called.\n * With `opens`, the connection joins only once it answers that it may open\n * the document the presence accompanies: until then, and for good when it\n * is refused or fails, nothing reaches it and nothing it sends is relayed.\n */\nexport const servePresence = <Update>(\n socket: SocketLike,\n hub: PresenceHub<Update>,\n options: {\n readonly peerId: string\n readonly opens?: Effect.Effect<boolean, unknown> | undefined\n },\n): (() => void) => {\n const send = (update: PresenceUpdate<Update>): void =>\n socket.send(JSON.stringify({ [frameType]: { id: update.id, value: update.value } }))\n let stopped = false\n let leave = (): void => {}\n let off = (): void => {}\n const join = (): void => {\n leave = hub.join(send)\n off = socket.onMessage(data => {\n const frame = decodePresence<Update>(data)\n if (frame === undefined) return\n // The connection owns the identity; a client-supplied id is ignored.\n const publish = () => hub.publish({ id: options.peerId, value: frame.value })\n if (options.opens === undefined) return publish()\n // Asked again with each frame: one no longer let open the document leaves.\n void Effect.runPromise(options.opens).then(\n open => {\n if (stopped) return\n if (open) publish()\n else stop()\n },\n () => stop(),\n )\n })\n }\n if (options.opens === undefined) join()\n else\n void Effect.runPromise(options.opens).then(\n open => {\n if (open && !stopped) join()\n },\n () => {},\n )\n const stop = (): void => {\n stopped = true\n off()\n leave()\n }\n const stopClose = socket.onClose(stop)\n return () => {\n stop()\n stopClose()\n }\n}\n","/**\n * `foldkit-sync` — a local-first replica of a shared Foldkit projection.\n *\n * The application's Message union and update function stay authoritative: sync\n * wraps them rather than introducing a second reducer. The replica owns the\n * local outbox, optimistic projection, and reconciliation; a durable server\n * journal provides authoritative order.\n *\n * `Sync` is the namespace: `Sync.forApplication`, `Sync.mount`,\n * `Sync.transport.socket`. Ids are branded schemas, so they construct through\n * `DocumentId.make('todos')`. Every name is also exported on its own.\n */\nimport { indexedDb } from './indexedDb.js'\nimport { lwwRegister, openLwwClock } from './lww.js'\nimport { forApplication } from './make.js'\nimport { fact, mount } from './mount.js'\nimport {\n createPresence,\n createPresenceHub,\n loopbackPresenceChannel,\n servePresence,\n socketPresenceChannel,\n} from './presence.js'\nimport { defineSync, syncMetrics, type Sync as SyncContract } from './sync.js'\nimport {\n layerFromPromise,\n layerLoopback,\n layerSocket,\n nativeSocket,\n portSocket,\n serveSocket,\n toPromise,\n workerSocket,\n} from './transport.js'\n\n/**\n * The contract `Sync.define` and `Sync.forApplication(App).make` produce: the\n * wire codecs, the server journal's contract, and `openReplica`.\n *\n * This is the type; `Sync` is also the value namespace below, the way\n * `Effect.Effect` is both.\n */\nexport type Sync<Message, Shared> = SyncContract<Message, Shared>\n\n/** The package's public surface, grouped. Each entry is the exported function itself. */\nexport const Sync = {\n /** Derives a sync contract from a Foldkit application: `Sync.forApplication(App).make({…})`. */\n forApplication,\n /** The protocol primitive, for a client with no Foldkit application to derive from. */\n define: defineSync,\n /** Runs a Foldkit application over an open replica with one reducer. */\n mount,\n /** A Command whose Message the mount applies within the transition that returned it. */\n fact,\n /** Counters and a histogram an application can scrape. */\n metrics: syncMetrics,\n /** The only storage adapter: one IndexedDB database per document/replica. */\n indexedDb,\n\n /** The `Transport` service's layers, and the bridges to and from a promise client. */\n transport: {\n /** A reconnecting WebSocket client layer. */\n socket: layerSocket,\n /** An in-process layer, for tests and single-process demos. */\n loopback: layerLoopback,\n /** Wraps the promise-based client the replica already speaks. */\n fromPromise: layerFromPromise,\n /** Bridges the service back to that promise client. */\n toPromise,\n /** The server side of one accepted socket connection. */\n serve: serveSocket,\n /** The accepted end of a Cloudflare `WebSocketPair`, for `serve`. */\n workerSocket,\n /** The default socket factory: the platform `WebSocket`. */\n nativeSocket,\n /** A socket over a `MessagePort`, closed by `close()` or an abort signal. */\n portSocket,\n },\n\n /** An ephemeral, TTL'd peer registry, deliberately outside the durable log. */\n presence: {\n make: createPresence,\n /** Broadcasts presence updates among connected peers, on the server. */\n hub: createPresenceHub,\n /** Serves presence frames on an accepted socket, stamping the connection's identity. */\n serve: servePresence,\n socketChannel: socketPresenceChannel,\n loopbackChannel: loopbackPresenceChannel,\n },\n\n /** Last-writer-wins registers (experimental): a per-field merge on logical time. */\n lww: {\n register: lwwRegister,\n /** The durable counter a stamp is allocated from, before dispatch. */\n openClock: openLwwClock,\n },\n}\n\nexport { indexedDb, type OutboxEntry, type Storage } from './indexedDb.js'\nexport {\n fact,\n mount,\n type CommittedView,\n type MountOptions,\n type Reinstall,\n type MountUrl,\n type Mounted,\n} from './mount.js'\nexport {\n forApplication,\n type ApplicationSync,\n type AuthorizeDecision,\n type AuthorizePolicy,\n type AuthorizeRequest,\n type DefinedSync,\n type FragmentMessages,\n type MakeOptions,\n type MsgOf,\n type PolicyJournalContract,\n type StampPolicy,\n type SyncFragment,\n} from './make.js'\nexport {\n DocumentId,\n LocalSequence,\n OpId,\n ReplicaId,\n Sequence,\n documentId,\n localSequence,\n opId,\n replicaId,\n sequence,\n} from './ids.js'\nexport {\n CheckpointRegressionError,\n CommittedOrderError,\n ForeignAcknowledgementError,\n ForeignRejectionError,\n InvalidExchangeError,\n InvalidOutboxError,\n InvalidReplicaHistoryError,\n ReplayError,\n ReplicaClosedError,\n StorageError,\n UnsupportedClockVersionError,\n UnsupportedReplicaVersionError,\n WrongReplicaStorageError,\n type ReplicaError,\n} from './errors.js'\nexport { lwwRegister, openLwwClock, type LwwClock, type LwwClockState } from './lww.js'\nexport {\n createPresence,\n createPresenceHub,\n loopbackPresenceChannel,\n servePresence,\n socketPresenceChannel,\n type Presence,\n type PresenceChannel,\n type PresenceHub,\n type PresenceOptions,\n type PresencePeer,\n type PresenceUpdate,\n} from './presence.js'\nexport {\n layerFromPromise,\n layerLoopback,\n layerSocket,\n nativeSocket,\n portSocket,\n serveSocket,\n toPromise,\n workerSocket,\n Transport,\n TransportError,\n type ExchangeFrame,\n type ExchangeReply,\n type NotifyFrame,\n type SocketLike,\n type SocketOptions,\n type TransportShape,\n} from './transport.js'\nexport {\n defineSync,\n syncMetrics,\n type Checkpoint,\n type CommitStamp,\n type CommittedOperation,\n type Exchange,\n type JournalContract,\n type Operation,\n type Rejection,\n type Replica,\n type ReplicaSnapshot,\n type ReplicaState,\n type ReplicaStatus,\n type SyncDefinition,\n type TransportClient,\n} from './sync.js'\n"],"mappings":";;;;;;;;;;;AAGA,IAAa,eAAb,cAAkC,OAAO,YAA0B,CAAC,CAAC,gBAAgB;CACnF,SAAS,OAAO;CAChB,OAAO,OAAO,SAAS,OAAO,OAAO;AACvC,CAAC,CAAC,CAAC,CAAC;;AAGJ,IAAa,+BAAb,cAAkD,OAAO,YAA0C,CAAC,CAClG,gCACA;CACE,eAAe,OAAO,OAAO,OAAO,MAAM;CAC1C,SAAS,OAAO;AAClB,CACF,CAAC,CAAC,CAAC;;AAGH,IAAa,2BAAb,cAA8C,OAAO,YAAsC,CAAC,CAC1F,4BACA;CACE,YAAY,OAAO;CACnB,WAAW,OAAO;CAClB,SAAS,OAAO;AAClB,CACF,CAAC,CAAC,CAAC;;AAGH,IAAa,6BAAb,cAAgD,OAAO,YAAwC,CAAC,CAC9F,8BACA;CACE,SAAS,OAAO;CAChB,OAAO,OAAO,SAAS,OAAO,OAAO;AACvC,CACF,CAAC,CAAC,CAAC;;AAGH,IAAa,uBAAb,cAA0C,OAAO,YAAkC,CAAC,CAClF,wBACA;CACE,SAAS,OAAO;CAChB,OAAO,OAAO,SAAS,OAAO,OAAO;AACvC,CACF,CAAC,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gBAAgB,IAAI,QAAQ;IAAE,IAAI,QAAQ;IAAQ,OAAO,MAAM;GAAM,CAAC;GAC5E,IAAI,QAAQ,UAAU,KAAA,GAAW,OAAO,QAAQ;GAEhD,OAAY,WAAW,QAAQ,KAAK,CAAC,CAAC,MACpC,SAAQ;IACN,IAAI,SAAS;IACb,IAAI,MAAM,QAAQ;SACb,KAAK;GACZ,SACM,KAAK,CACb;EACF,CAAC;CACH;CACA,IAAI,QAAQ,UAAU,KAAA,GAAW,KAAK;MAEpC,OAAY,WAAW,QAAQ,KAAK,CAAC,CAAC,MACpC,SAAQ;EACN,IAAI,QAAQ,CAAC,SAAS,KAAK;CAC7B,SACM,CAAC,CACT;CACF,MAAM,aAAmB;EACvB,UAAU;EACV,IAAI;EACJ,MAAM;CACR;CACA,MAAM,YAAY,OAAO,QAAQ,IAAI;CACrC,aAAa;EACX,KAAK;EACL,UAAU;CACZ;AACF;;;;;;;;;;;;;;;;AC5WA,MAAa,OAAO;;CAElB;;CAEA,QAAQ;;CAER;;CAEA;;CAEA,SAAS;;CAET;;CAGA,WAAW;;EAET,QAAQ;;EAER,UAAU;;EAEV,aAAa;;EAEb;;EAEA,OAAO;;EAEP;;EAEA;;EAEA;CACF;;CAGA,UAAU;EACR,MAAM;;EAEN,KAAK;;EAEL,OAAO;EACP,eAAe;EACf,iBAAiB;CACnB;;CAGA,KAAK;EACH,UAAU;;EAEV,WAAW;CACb;AACF"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/errors.ts","../src/indexedDb.ts","../src/lww.ts","../src/sync.ts","../src/make.ts","../src/mount.ts","../src/presence.ts","../src/index.ts"],"sourcesContent":["import { Schema } from 'effect'\n\n/** The persisted storage could not be read or written. */\nexport class StorageError extends Schema.TaggedError<StorageError>()('StorageError', {\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown),\n}) {}\n\n/** The stored clock state targets a schema version this build does not support. */\nexport class UnsupportedClockVersionError extends Schema.TaggedError<UnsupportedClockVersionError>()(\n 'UnsupportedClockVersionError',\n {\n schemaVersion: Schema.NullOr(Schema.Number),\n message: Schema.String,\n },\n) {}\n\n/** The storage holds a different replica's state. */\nexport class WrongReplicaStorageError extends Schema.TaggedError<WrongReplicaStorageError>()(\n 'WrongReplicaStorageError',\n {\n documentId: Schema.String,\n replicaId: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/** The persisted replica history is internally inconsistent. */\nexport class InvalidReplicaHistoryError extends Schema.TaggedError<InvalidReplicaHistoryError>()(\n 'InvalidReplicaHistoryError',\n {\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown),\n },\n) {}\n\n/** The server's exchange response did not match the protocol schema. */\nexport class InvalidExchangeError extends Schema.TaggedError<InvalidExchangeError>()(\n 'InvalidExchangeError',\n {\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown),\n },\n) {}\n\n/** A persisted pending operation could not have been produced by this replica. */\nexport class InvalidOutboxError extends Schema.TaggedError<InvalidOutboxError>()(\n 'InvalidOutboxError',\n {\n message: Schema.String,\n },\n) {}\n\n/** The server sent a checkpoint older than the replica's cursor. */\nexport class CheckpointRegressionError extends Schema.TaggedError<CheckpointRegressionError>()(\n 'CheckpointRegressionError',\n {\n cursor: Schema.Number,\n checkpointCursor: Schema.Number,\n message: Schema.String,\n },\n) {}\n\n/** Committed operations were not contiguous from the replica's cursor. */\nexport class CommittedOrderError extends Schema.TaggedError<CommittedOrderError>()(\n 'CommittedOrderError',\n {\n expected: Schema.Number,\n actual: Schema.Number,\n message: Schema.String,\n },\n) {}\n\n/** The server rejected an operation the replica never sent. */\nexport class ForeignRejectionError extends Schema.TaggedError<ForeignRejectionError>()(\n 'ForeignRejectionError',\n {\n opId: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/**\n * The server answered an operation this request never sent, or both\n * acknowledged and rejected it. Acting on either would let a faulty or hostile\n * server delete local work.\n */\nexport class ForeignAcknowledgementError extends Schema.TaggedError<ForeignAcknowledgementError>()(\n 'ForeignAcknowledgementError',\n {\n opId: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/** The replica was closed while work was still being submitted. */\nexport class ReplicaClosedError extends Schema.TaggedError<ReplicaClosedError>()(\n 'ReplicaClosedError',\n {\n message: Schema.String,\n },\n) {}\n\n/** The stored replica state targets a protocol or schema version this build does not support. */\nexport class UnsupportedReplicaVersionError extends Schema.TaggedError<UnsupportedReplicaVersionError>()(\n 'UnsupportedReplicaVersionError',\n {\n protocolVersion: Schema.NullOr(Schema.Number),\n schemaVersion: Schema.NullOr(Schema.Number),\n message: Schema.String,\n },\n) {}\n\n/**\n * `replay` threw for a submitted Message, so it could never be applied here or\n * on any other replica; nothing was written.\n */\nexport class ReplayError extends Schema.TaggedError<ReplayError>()('ReplayError', {\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown),\n}) {}\n\nexport type ReplicaError =\n | StorageError\n | ReplayError\n | WrongReplicaStorageError\n | InvalidReplicaHistoryError\n | InvalidExchangeError\n | UnsupportedReplicaVersionError\n | InvalidOutboxError\n | CheckpointRegressionError\n | CommittedOrderError\n | ForeignRejectionError\n | ForeignAcknowledgementError\n | ReplicaClosedError\n","import { Config, Effect } from 'effect'\nimport { StorageError } from './errors.js'\n\n/** One submitted operation, as `Storage.append` records it. */\nexport interface OutboxEntry {\n /** The replica's revision once this operation is in its outbox. */\n readonly revision: number\n readonly nextLocalSequence: number\n /**\n * The operation's local sequence. An entry with the sequence of one already in the\n * outbox replaces it: a coalesced submit rewrites the last operation.\n */\n readonly localSequence: number\n /** The operation, encoded. */\n readonly operation: unknown\n}\n\n/** Persists a replica's state with compare-and-swap on its revision. */\nexport interface Storage {\n /**\n * The saved state, with every operation appended since in its `pending` (replacing the\n * one of the same local sequence), and the last one's `revision` and `nextLocalSequence`.\n */\n load: () => Effect.Effect<unknown, StorageError>\n /** Replaces the whole state, and with it every appended operation. */\n save: (state: unknown, expectedRevision: number | null) => Effect.Effect<void, StorageError>\n /**\n * Optional. Records one submitted operation without rewriting the rest of the state, so\n * a submit costs the operation's size rather than the document's. Without it, a submit\n * saves the whole state.\n */\n append?: (entry: OutboxEntry, expectedRevision: number) => Effect.Effect<void, StorageError>\n /** Idempotent; the caller closes the connection explicitly. */\n close: Effect.Effect<void>\n}\n\nconst storageError = (message: string, cause: unknown): StorageError =>\n new StorageError({\n message: `${message}: ${cause instanceof Error ? cause.message : String(cause)}`,\n cause,\n })\n\nconst openDatabase = (\n name: string,\n factory: IDBFactory,\n): Effect.Effect<IDBDatabase, StorageError> =>\n Effect.tryPromise({\n try: () =>\n new Promise<IDBDatabase>((resolve, reject) => {\n const request = factory.open(name, 2)\n // Version 2 adds the outbox that `append` writes; a version 1 database keeps its\n // state, and its revision is read from that state until the next write.\n request.onupgradeneeded = event => {\n const database = request.result\n if (event.oldVersion < 1) database.createObjectStore('replica')\n if (event.oldVersion < 2) database.createObjectStore('outbox')\n }\n let blocked = false\n // A blocked open still succeeds once the other connection closes, after the\n // effect has failed; nothing else would ever close that connection.\n request.onsuccess = () => (blocked ? request.result.close() : resolve(request.result))\n request.onerror = () => reject(request.error)\n // Without this, a version upgrade blocked by another open connection\n // never settles and the effect hangs.\n request.onblocked = () => {\n blocked = true\n reject(new Error('IndexedDB upgrade is blocked by another connection'))\n }\n }),\n catch: cause => storageError('Could not open the storage', cause),\n })\n\n/** One database per document/replica; CAS prevents two tabs from sharing a writer identity. */\nexport const indexedDb = Effect.fn('Storage.indexedDb')(function* (\n name: Config.Config<string> | string,\n factory: IDBFactory = globalThis.indexedDB,\n) {\n const databaseName =\n typeof name === 'string'\n ? name\n : yield* name.pipe(\n Effect.catchTag('ConfigError', cause =>\n Effect.fail(storageError('Could not read the storage name', cause)),\n ),\n )\n const database = yield* Effect.acquireRelease(openDatabase(databaseName, factory), database =>\n Effect.sync(() => database.close()),\n )\n database.onversionchange = () => database.close()\n /**\n * Writes under compare-and-swap: `write` runs only if the stored revision is the one\n * expected. The revision is its own key, so an append need not read the state; a database\n * written before it existed has it inside the state.\n */\n const write = (\n expectedRevision: number | null,\n writing: (replica: IDBObjectStore, outbox: IDBObjectStore) => void,\n ): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n const transaction = database.transaction(['replica', 'outbox'], 'readwrite', {\n durability: 'strict',\n })\n const replica = transaction.objectStore('replica')\n let conflict = false\n const check = (revision: number | null): void => {\n if (revision !== expectedRevision) {\n conflict = true\n transaction.abort()\n return\n }\n writing(replica, transaction.objectStore('outbox'))\n }\n const stored = replica.get('revision')\n stored.onsuccess = () => {\n if (stored.result !== undefined) return check(stored.result as number)\n const state = replica.get('state')\n state.onsuccess = () =>\n check((state.result as { revision: number } | undefined)?.revision ?? null)\n }\n transaction.oncomplete = () => resolve()\n transaction.onabort = () =>\n reject(\n conflict\n ? new Error('Replica was changed by another writer')\n : (transaction.error ?? new Error('IndexedDB write aborted')),\n )\n })\n // Every member, `append` included, so a caller need not check for it.\n const storage: Required<Storage> = {\n load: () =>\n Effect.tryPromise({\n try: () =>\n new Promise((resolve, reject) => {\n const transaction = database.transaction(['replica', 'outbox'], 'readonly')\n const state = transaction.objectStore('replica').get('state')\n // In key order, which is local-sequence order.\n const appended = transaction.objectStore('outbox').getAll()\n transaction.oncomplete = () => {\n const saved = state.result as\n | { pending: ReadonlyArray<{ readonly localSequence?: unknown }> }\n | undefined\n const entries = appended.result as ReadonlyArray<OutboxEntry>\n // Only the last operation is ever rewritten, so the last row is the latest.\n const latest = entries[entries.length - 1]\n const replaced = new Set(entries.map(entry => entry.localSequence))\n resolve(\n saved === undefined || latest === undefined\n ? saved\n : {\n ...saved,\n revision: latest.revision,\n nextLocalSequence: latest.nextLocalSequence,\n pending: [\n ...saved.pending.filter(\n operation => !replaced.has(operation.localSequence as number),\n ),\n ...entries.map(entry => entry.operation),\n ],\n },\n )\n }\n transaction.onabort = () =>\n reject(transaction.error ?? new Error('IndexedDB read aborted'))\n }),\n catch: cause => storageError('Could not read the replica', cause),\n }),\n save: (state, expectedRevision) =>\n Effect.tryPromise({\n try: () =>\n write(expectedRevision, (replica, outbox) => {\n replica.put(state, 'state')\n replica.put((state as { revision: number }).revision, 'revision')\n outbox.clear()\n }),\n catch: cause => storageError('Could not save the replica', cause),\n }),\n append: (entry, expectedRevision) =>\n Effect.tryPromise({\n try: () =>\n write(expectedRevision, (replica, outbox) => {\n outbox.put(entry, entry.localSequence)\n replica.put(entry.revision, 'revision')\n }),\n catch: cause => storageError('Could not save the replica', cause),\n }),\n close: Effect.sync(() => database.close()),\n }\n return storage\n})\n","import { Effect, Exit, Ref, Schema, SynchronizedRef } from 'effect'\nimport { StorageError, UnsupportedClockVersionError } from './errors.js'\nimport { DocumentId, ReplicaId } from './ids.js'\nimport type { Storage } from './indexedDb.js'\n\n/** A logical write time; replica ids break concurrent ties using UTF-16 order. */\nconst Stamp = Schema.Struct({\n counter: Schema.Number.check(\n Schema.isInt(),\n Schema.isGreaterThanOrEqualTo(0),\n Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER),\n ),\n replicaId: ReplicaId,\n})\n\n/** The persisted clock format. A bump must handle the older value explicitly. */\nconst CLOCK_SCHEMA_VERSION = 1\n\nconst ClockState = Schema.Struct({\n schemaVersion: Schema.Literal(CLOCK_SCHEMA_VERSION),\n documentId: DocumentId,\n replicaId: ReplicaId,\n // The high-water counter also serves as the storage's CAS revision.\n revision: Stamp.fields.counter,\n})\nexport type LwwClockState = typeof ClockState.Type\n\nexport interface LwwClock {\n /** Persists a timestamp beyond the saved counter and supplied observation. */\n next: (observedCounter?: number) => Effect.Effect<typeof Stamp.Type, StorageError>\n /** Drains accepted allocations, then closes storage. Repeated calls no-op. */\n close: Effect.Effect<void>\n}\n\nconst decodeClock = Schema.decodeUnknownSync(ClockState, { onExcessProperty: 'error' })\nconst decodeCounter = Schema.decodeUnknownSync(Stamp.fields.counter)\n\nconst clockError = (message: string, cause: unknown): StorageError =>\n new StorageError({\n message: `${message}: ${cause instanceof Error ? cause.message : String(cause)}`,\n cause,\n })\n\nconst VersionProbe = Schema.Struct({ schemaVersion: Schema.optional(Schema.Number) })\n/**\n * Tells a version this build does not understand apart from malformed data, so\n * the caller gets an actionable failure and the stored state is preserved.\n */\nconst unsupportedVersion = (input: unknown): UnsupportedClockVersionError | undefined => {\n let found: { readonly schemaVersion?: number | undefined }\n try {\n found = Schema.decodeUnknownSync(VersionProbe)(input)\n } catch {\n return undefined\n }\n if (found.schemaVersion === CLOCK_SCHEMA_VERSION) return undefined\n return new UnsupportedClockVersionError({\n schemaVersion: found.schemaVersion ?? null,\n message: `Stored clock uses schema ${found.schemaVersion ?? '?'}; this build supports ${CLOCK_SCHEMA_VERSION}`,\n })\n}\n\n/**\n * Opens a durable clock over the caller's storage.\n *\n * Allocations are serialized through a `SynchronizedRef` and each persists before\n * its stamp is returned. A crash after the save may skip a timestamp but never\n * reuse one. Storage is owned by the caller; a failed open closes it so a partial\n * initialization does not leak the connection.\n */\nexport const openLwwClock = Effect.fn('Lww.openClock')(\n function* (options: {\n readonly documentId: DocumentId\n readonly replicaId: ReplicaId\n readonly storage: Storage\n }) {\n const { documentId, replicaId, storage } = options\n yield* Effect.annotateCurrentSpan({ documentId, replicaId })\n const initial = decodeClock({\n schemaVersion: CLOCK_SCHEMA_VERSION,\n documentId,\n replicaId,\n revision: 0,\n })\n const saved = yield* storage.load()\n const state = yield* Effect.try({\n try: () => (saved === undefined ? initial : decodeClock(saved)),\n catch: cause =>\n unsupportedVersion(saved) ?? clockError('Stored clock state is invalid', cause),\n })\n if (state.documentId !== documentId || state.replicaId !== replicaId)\n return yield* new StorageError({ message: 'Wrong clock storage' })\n if (saved === undefined) yield* storage.save(state, null)\n\n const stateRef = yield* SynchronizedRef.make(state)\n const closed = yield* Ref.make(false)\n\n const next = Effect.fn('Lww.next')(function* (observedCounter = 0) {\n if (yield* Ref.get(closed)) return yield* new StorageError({ message: 'Clock is closed' })\n return yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.gen(function* () {\n // Re-check under the lock: a `close` that set the flag while this\n // allocation was queued must not save to a closed connection.\n if (yield* Ref.get(closed)) return yield* new StorageError({ message: 'Clock is closed' })\n const allocated = yield* Effect.try({\n try: () =>\n decodeClock({\n ...current,\n revision: Math.max(current.revision, decodeCounter(observedCounter)) + 1,\n }),\n catch: cause => clockError('Invalid clock allocation', cause),\n })\n yield* storage.save(allocated, current.revision)\n return [{ counter: allocated.revision, replicaId }, allocated] as const\n }),\n )\n })\n\n const close = Effect.fn('Lww.close')(function* () {\n const alreadyClosed = yield* Ref.modify(closed, current => [current, true] as const)\n if (alreadyClosed) return\n // Drains any accepted allocation before releasing the connection.\n yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.succeed([undefined, current] as const),\n )\n yield* storage.close\n })()\n\n return { next, close }\n },\n (effect, options) =>\n // Close a partially initialized storage on any failure, including a defect,\n // so a failed open cannot leak the connection.\n effect.pipe(\n Effect.onExit(exit =>\n Exit.isSuccess(exit) ? Effect.void : options.storage.close.pipe(Effect.ignore),\n ),\n ),\n)\n\n/**\n * A schema and reducer helper for a last-writer-wins register.\n * Allocate a unique stamp per write before dispatch, and retain it in the Message.\n * Merge is for decoded values; the application's schema validates wire input.\n */\nexport const lwwRegister = <Value, Encoded, RD, RE>(\n value: Schema.Codec<Value, Encoded, RD, RE>,\n) => {\n const schema = Schema.Struct({ stamp: Stamp, value })\n type Register = typeof schema.Type\n const equivalent = Schema.toEquivalence(value)\n\n const merge = (left: Register, right: Register): Register => {\n if (left.stamp.counter !== right.stamp.counter)\n return left.stamp.counter > right.stamp.counter ? left : right\n if (left.stamp.replicaId !== right.stamp.replicaId)\n return left.stamp.replicaId > right.stamp.replicaId ? left : right\n // Reusing a write identity for different values would make arrival order win.\n if (!equivalent(left.value, right.value)) throw new Error('Conflicting LWW write identity')\n return left\n }\n\n return { schema, merge }\n}\n","import {\n Effect,\n Exit,\n Metric,\n Option,\n PubSub,\n Queue,\n Ref,\n Schema,\n Stream,\n SynchronizedRef,\n} from 'effect'\nimport {\n CheckpointRegressionError,\n CommittedOrderError,\n ForeignAcknowledgementError,\n ForeignRejectionError,\n InvalidExchangeError,\n InvalidOutboxError,\n InvalidReplicaHistoryError,\n ReplayError,\n ReplicaClosedError,\n UnsupportedReplicaVersionError,\n WrongReplicaStorageError,\n type ReplicaError,\n} from './errors.js'\nimport type { Storage } from './indexedDb.js'\nimport {\n DocumentId,\n LocalSequence,\n OpId,\n ReplicaId,\n Sequence,\n localSequence,\n sequence,\n} from './ids.js'\nimport { Transport, TransportError } from './transport.js'\n\n/** Wire and persisted-format versions. A bump must handle the older value explicitly. */\nconst PROTOCOL_VERSION = 1\nconst SCHEMA_VERSION = 1\n\n/** A client-authored operation envelope. `message` is the application's encoded Message. */\nconst OperationSchema = Schema.Struct({\n protocolVersion: Schema.Literal(PROTOCOL_VERSION),\n schemaVersion: Schema.Literal(SCHEMA_VERSION),\n documentId: DocumentId,\n replicaId: ReplicaId,\n localSequence: LocalSequence,\n opId: OpId,\n baseCursor: Sequence,\n message: Schema.Unknown,\n})\nexport type Operation = typeof OperationSchema.Type\n\n/** An operation the server committed, with its authoritative order and actor. */\nconst CommittedSchema = Schema.Struct({\n ...OperationSchema.fields,\n serverSequence: Sequence.check(Schema.isGreaterThanOrEqualTo(1)),\n actorId: Schema.NonEmptyString,\n})\n/** Named to avoid colliding with `foldkit-durable`'s `Committed`. */\nexport type CommittedOperation = typeof CommittedSchema.Type\n\nconst decodeOperation = Schema.decodeUnknownSync(OperationSchema, { onExcessProperty: 'error' })\nconst decodeCommitted = Schema.decodeUnknownSync(CommittedSchema, { onExcessProperty: 'error' })\n\n/**\n * How many committed-operation ids a replica retains for duplicate detection.\n * Committed sequences are contiguous and the server enforces `opId`\n * uniqueness, so this is defence in depth; bounding it keeps replica state from\n * growing without limit on a log that is never checkpointed.\n */\nconst COMMITTED_ID_WINDOW = 1024\n/** How long `start` waits after a failed exchange: doubling from the base, up to the cap, in ms. */\nconst START_RETRY_BASE = 500\nconst START_RETRY_MAX = 30_000\n\n/** Counters and a histogram an application can scrape. */\nexport const syncMetrics = {\n exchanges: Metric.counter('foldkit_sync_exchanges_total'),\n applied: Metric.counter('foldkit_sync_commits_applied_total'),\n checkpoints: Metric.counter('foldkit_sync_checkpoints_adopted_total'),\n exchangePending: Metric.histogram('foldkit_sync_exchange_pending', {\n boundaries: [1, 4, 16, 64, 256, 1024],\n }),\n}\n\nexport interface Checkpoint<Shared> {\n readonly cursor: Sequence\n readonly model: Shared\n}\n\nexport interface Exchange<Shared> {\n /** Server-committed operations as they arrived; validated against `CommittedOperation` on adoption. */\n readonly operations: ReadonlyArray<unknown>\n readonly rejected: ReadonlyArray<OpId>\n /**\n * Why some of `rejected` were refused, in words the server chose for a person:\n * a policy's reason, never an internal error. One without a reason is still rejected.\n */\n readonly reasons?: ReadonlyArray<{ readonly opId: OpId; readonly reason: string }> | undefined\n /** Sends from the request that are durably committed, so the replica can drop them. */\n readonly acknowledged?: ReadonlyArray<OpId> | undefined\n /** The snapshot a replica predating compaction adopts in place of the log. */\n readonly checkpoint?: Checkpoint<Shared> | undefined\n /** The server sent only part of what is after the cursor; the replica asks again. */\n readonly more?: boolean | undefined\n /**\n * The identity of the server's history. The replica sends back the one it last saw; a\n * server that finds another answers from the start of its own history, and the replica,\n * seeing a new epoch, rebuilds its committed state from that answer and keeps its outbox.\n */\n readonly epoch?: string | undefined\n}\n\nexport interface ReplicaState<Shared> {\n readonly protocolVersion: typeof PROTOCOL_VERSION\n readonly schemaVersion: typeof SCHEMA_VERSION\n readonly documentId: DocumentId\n readonly replicaId: ReplicaId\n readonly revision: number\n readonly nextLocalSequence: LocalSequence\n readonly cursor: Sequence\n readonly committed: Shared\n readonly committedIds: ReadonlyArray<string>\n readonly pending: ReadonlyArray<Operation>\n /** The server history `cursor` points into, once an exchange has named one. */\n readonly epoch?: string\n}\n\n/**\n * What the promise-based edge adapter consumes; the Effect `Transport` service\n * is the primary seam.\n */\nexport interface TransportClient {\n /** `epoch` is the server history the replica's cursor points into, when it knows one. */\n exchange(\n cursor: Sequence,\n pending: ReadonlyArray<Operation>,\n epoch?: string | undefined,\n ): Promise<unknown>\n}\n\n/** A redacted view of a replica's state, for a UI to explain and recover. */\nexport interface ReplicaStatus {\n readonly pending: number\n readonly cursor: Sequence\n /** The last exchange failure, cleared by a successful exchange. */\n readonly lastError: string | undefined\n /** Operations the server refused, most recent first, with its reason when it gave one. */\n readonly rejected: ReadonlyArray<Rejection>\n /**\n * The server history the cursor points into, once a server named one. A new\n * one means the server was reset: what the replica had committed is gone.\n */\n readonly epoch: Option.Option<string>\n}\n\n/**\n * An operation the server refused, and why, when it said. It carries the\n * operation itself: the replica drops it from the outbox in the same step,\n * so what it changed can be read from here rather than looked up in time.\n */\nexport interface Rejection {\n readonly opId: OpId\n readonly reason: Option.Option<string>\n readonly operation: Operation\n}\n\n/**\n * A consistent status and optimistic-shared pair, read from one replica state.\n * `Replica.changes` emits it so a UI can hold a single subscription.\n */\nexport interface ReplicaSnapshot<Shared> {\n readonly status: ReplicaStatus\n readonly shared: Shared\n /** The server-confirmed state the optimistic `shared` is built on. */\n readonly committed: Shared\n /**\n * The local sequence the next submitted operation takes. Only a successful\n * submit moves it, so a caller that submits one Message at a time can tell\n * from one snapshot whether `shared` already holds it.\n */\n readonly nextLocalSequence: LocalSequence\n}\n\nexport interface Replica<Message, Shared> {\n /** The id this replica's operations carry, one per tab: what its commits are stamped with. */\n readonly replicaId: ReplicaId\n /** The optimistic projection: committed state with pending operations replayed. */\n readonly shared: Effect.Effect<Shared>\n /**\n * The server-confirmed state through `cursor`, with no pending operation\n * applied. A pending edit reaches it only once the server commits it, and a\n * rejected one never does.\n */\n readonly committed: Effect.Effect<Shared>\n readonly pending: Effect.Effect<ReadonlyArray<Operation>>\n readonly cursor: Effect.Effect<Sequence>\n /**\n * Waiting/recovery information without exposing Messages or the Model. It is a\n * snapshot; `statusChanges` re-emits it after every submit and exchange.\n */\n readonly status: Effect.Effect<ReplicaStatus>\n /** The status, re-emitted after every submit and exchange. */\n readonly statusChanges: Stream.Stream<ReplicaStatus>\n /**\n * The status and the optimistic shared value together, re-emitted after every\n * submit and exchange, so a UI can subscribe once instead of to both.\n */\n readonly changes: Stream.Stream<ReplicaSnapshot<Shared>>\n /** The status, `shared`, `committed` and next local sequence, read from one replica state. */\n readonly snapshot: Effect.Effect<ReplicaSnapshot<Shared>>\n readonly submit: (message: Message) => Effect.Effect<void, ReplicaError>\n /** Reconciles against the server. The `Transport` service must be provided. */\n readonly synchronize: Effect.Effect<void, ReplicaError | TransportError, Transport>\n /**\n * The exchange loop: exchanges once, then after every `submit` and every\n * notice on the transport's `changes`, until the replica closes or the fiber\n * is interrupted. A failed exchange is recorded\n * in `status.lastError` and retried on a backoff (from 0.5 s, doubling up to\n * 30 s), or at once on the next `submit`, so the fiber never fails. Fork it\n * with `Effect.forkScoped` and provide `Transport`.\n */\n readonly start: Effect.Effect<void, never, Transport>\n readonly close: Effect.Effect<void>\n}\n\nexport interface SyncDefinition<Message, Shared, MessageEncoded, SharedEncoded> {\n readonly documentId: DocumentId\n readonly message: Schema.Codec<Message, MessageEncoded, never, never>\n readonly shared: Schema.Codec<Shared, SharedEncoded, never, never>\n readonly empty: Shared\n readonly durable: (message: Message) => boolean\n readonly replay: (shared: Shared, message: Message) => Shared\n /**\n * Optional. Merges a durable Message into the one submitted before it, while that one\n * has not been sent: one operation instead of two, for a burst of typing. Replaying the\n * result must equal replaying `last` then `next`. Undefined keeps them apart.\n */\n readonly coalesce?: ((last: Message, next: Message) => Message | undefined) | undefined\n /**\n * Optional. Writes what the server's commit decided into a durable Message, on the\n * server only: the journal stores, reduces and sends the stamped Message, so every\n * replica replays the same one in place of what it sent.\n */\n readonly stamp?: ((message: Message, commit: CommitStamp) => Message) | undefined\n}\n\n/**\n * What a commit decided, for `stamp`: the operation's place in the order, who\n * committed it, and from which replica. `actorId` is the principal, shared by\n * every tab a person has open; `replicaId` tells those tabs apart.\n */\nexport interface CommitStamp {\n readonly sequence: number\n readonly actorId: string\n readonly replicaId: string\n}\n\nexport interface Sync<Message, Shared> {\n readonly documentId: DocumentId\n /** Whether a Message is one the replica records and replays. */\n readonly durable: (message: Message) => boolean\n /**\n * Low-level wire codecs for adapters and the transport. Most applications use\n * `journalContract` and `openReplica`; these are exposed for a custom\n * transport or a server that must speak the operation envelope directly.\n */\n readonly codec: {\n readonly normalizeOperation: (input: unknown) => Operation\n readonly operationFrom: (input: unknown, documentId: DocumentId) => Operation\n readonly committedFrom: (input: unknown, documentId: DocumentId) => CommittedOperation\n readonly decodeExchange: (input: unknown) => Exchange<Shared>\n }\n /** The codecs and pure reducer `foldkit-durable`'s `makeJournal` consumes. */\n readonly journalContract: () => JournalContract<Operation, Shared>\n readonly openReplica: (\n replicaId: ReplicaId,\n storage: Storage,\n ) => Effect.Effect<Replica<Message, Shared>, ReplicaError>\n}\n\n/** Structural match for `foldkit-durable`'s journal options; Sync stays independent. */\nexport interface JournalContract<Operation, Shared> {\n /** The replica each operation came from, which Durable binds to its first committer. */\n readonly replicaId: (operation: Operation) => string\n /** Sync's operation id includes the replica, even after Durable compacts its payload. */\n readonly legacyReplicaId: (opId: string) => string\n readonly operation: {\n /** Operations are stored in their encoded form, so this is the identity. */\n readonly encode: (operation: Operation) => Operation\n readonly decode: (input: unknown) => Operation\n }\n readonly snapshot: {\n readonly encode: (snapshot: Shared) => unknown\n readonly decode: (input: unknown) => Shared\n }\n readonly empty: () => Shared\n readonly reduce: (snapshot: Shared, operation: Operation) => Shared\n /** Present when the definition stamps: Durable's `stamp`, over the operation's Message. */\n readonly stamp?: (\n operation: Operation,\n commit: { readonly sequence: number; readonly actorId: string },\n ) => Operation\n}\n\n/**\n * Binds the replicated-state protocol to one application contract.\n *\n * The returned codecs decide what is a valid operation and what the shared\n * projection means; the replica owns the local outbox, optimistic projection,\n * and reconciliation as Effects, and never runs a second reducer.\n */\nexport const defineSync = <Message, Shared, MessageEncoded, SharedEncoded>(\n definition: SyncDefinition<Message, Shared, MessageEncoded, SharedEncoded>,\n): Sync<Message, Shared> => {\n const documentId = definition.documentId\n const decodeMessage = Schema.decodeUnknownSync(definition.message, { onExcessProperty: 'error' })\n const encodeMessage = Schema.encodeSync(definition.message)\n const decodeShared = Schema.decodeUnknownSync(definition.shared, { onExcessProperty: 'error' })\n const encodeShared = Schema.encodeSync(definition.shared)\n\n const ReplicaStateSchema = Schema.Struct({\n protocolVersion: Schema.Literal(PROTOCOL_VERSION),\n schemaVersion: Schema.Literal(SCHEMA_VERSION),\n documentId: DocumentId,\n replicaId: ReplicaId,\n revision: Schema.Number,\n nextLocalSequence: LocalSequence,\n cursor: Sequence,\n committed: definition.shared,\n committedIds: Schema.Array(Schema.String),\n pending: Schema.Array(OperationSchema),\n epoch: Schema.optionalKey(Schema.NonEmptyString),\n })\n const CheckpointSchema = Schema.Struct({ cursor: Sequence, model: definition.shared })\n const ExchangeSchema = Schema.Struct({\n operations: Schema.Array(Schema.Unknown),\n rejected: Schema.Array(OpId),\n // A server's words for a person, bounded: a reply is not a place for a document.\n reasons: Schema.optional(\n Schema.Array(\n Schema.Struct({ opId: OpId, reason: Schema.String.check(Schema.isMaxLength(500)) }),\n ),\n ),\n acknowledged: Schema.optional(Schema.Array(OpId)),\n checkpoint: Schema.optional(CheckpointSchema),\n more: Schema.optional(Schema.Boolean),\n epoch: Schema.optional(Schema.NonEmptyString),\n })\n const decodeState = Schema.decodeUnknownSync(ReplicaStateSchema, { onExcessProperty: 'error' })\n const encodeState = Schema.encodeSync(ReplicaStateSchema)\n const encodeOperation = Schema.encodeSync(OperationSchema)\n const VersionProbe = Schema.Struct({\n protocolVersion: Schema.optional(Schema.Number),\n schemaVersion: Schema.optional(Schema.Number),\n })\n /**\n * Tells a version this build does not understand apart from malformed data,\n * so the caller gets an actionable failure and the stored state is preserved.\n */\n const unsupportedVersion = (input: unknown): UnsupportedReplicaVersionError | undefined => {\n let found: {\n readonly protocolVersion?: number | undefined\n readonly schemaVersion?: number | undefined\n }\n try {\n found = Schema.decodeUnknownSync(VersionProbe)(input)\n } catch {\n return undefined\n }\n if (found.protocolVersion === PROTOCOL_VERSION && found.schemaVersion === SCHEMA_VERSION)\n return undefined\n const protocolVersion = found.protocolVersion ?? null\n const schemaVersion = found.schemaVersion ?? null\n return new UnsupportedReplicaVersionError({\n protocolVersion,\n schemaVersion,\n message: `Stored replica uses protocol ${protocolVersion ?? '?'} / schema ${schemaVersion ?? '?'}; this build supports ${PROTOCOL_VERSION}/${SCHEMA_VERSION}`,\n })\n }\n const decodeExchange = (input: unknown): Exchange<Shared> =>\n Schema.decodeUnknownSync(ExchangeSchema, { onExcessProperty: 'error' })(\n input,\n ) as Exchange<Shared>\n\n const checkIdentity = (operation: Operation): void => {\n // `LocalSequence` already rejects a non-positive counter; this checks the\n // derived identity.\n if (operation.opId !== `${operation.replicaId}:${operation.localSequence}`) {\n throw new Error('Invalid operation identity')\n }\n }\n const decodeDurable = (message: unknown): Message => {\n const decoded = decodeMessage(message)\n if (!definition.durable(decoded)) throw new Error('Message is local-only')\n return decoded\n }\n const shape = <O extends Operation>(operation: O): O => {\n checkIdentity(operation)\n return { ...operation, message: encodeMessage(decodeDurable(operation.message)) }\n }\n const assertDocument = <O extends Operation>(operation: O, key: DocumentId): O => {\n if (operation.documentId !== key) throw new Error('Wrong document')\n return operation\n }\n const normalizeOperation = (input: unknown): Operation => shape(decodeOperation(input))\n const operationFrom = (input: unknown, key: DocumentId): Operation =>\n assertDocument(normalizeOperation(input), key)\n /**\n * A committed operation arrives with its message already encoded, so decode it\n * once for the contract check and hand it to `replay` instead of decoding and\n * re-encoding it on the way through `shape`.\n */\n const decodeCommittedOperation = (\n input: unknown,\n key: DocumentId,\n ): { readonly committed: CommittedOperation; readonly message: Message } => {\n const committed = assertDocument(decodeCommitted(input), key)\n checkIdentity(committed)\n return { committed, message: decodeDurable(committed.message) }\n }\n const committedFrom = (input: unknown, key: DocumentId): CommittedOperation =>\n decodeCommittedOperation(input, key).committed\n\n const journalContract = (): JournalContract<Operation, Shared> => ({\n replicaId: operation => operation.replicaId,\n legacyReplicaId: opId => opId.slice(0, opId.lastIndexOf(':')),\n // Operations are stored in their encoded form: `normalizeOperation` has\n // already encoded the Message and validated the identity.\n operation: { encode: operation => operation, decode: normalizeOperation },\n snapshot: { encode: encodeShared, decode: decodeShared },\n empty: () => definition.empty,\n reduce: (snapshot, operation) => definition.replay(snapshot, decodeMessage(operation.message)),\n ...(definition.stamp === undefined\n ? {}\n : {\n stamp: (\n operation: Operation,\n commit: { readonly sequence: number; readonly actorId: string },\n ): Operation => ({\n ...operation,\n message: encodeMessage(\n definition.stamp!(decodeMessage(operation.message), {\n ...commit,\n replicaId: operation.replicaId,\n }),\n ),\n }),\n }),\n })\n\n const optimistic = (state: ReplicaState<Shared>): Shared =>\n state.pending.reduce(\n (model, operation) => definition.replay(model, decodeMessage(operation.message)),\n state.committed,\n )\n\n const openReplica = Effect.fn('Sync.openReplica')(\n function* (replicaId: ReplicaId, storage: Storage) {\n yield* Effect.annotateCurrentSpan({ documentId, replicaId })\n const saved = yield* storage.load()\n const initial: ReplicaState<Shared> = {\n protocolVersion: PROTOCOL_VERSION,\n schemaVersion: SCHEMA_VERSION,\n documentId,\n replicaId,\n revision: 0,\n nextLocalSequence: localSequence(1),\n cursor: sequence(0),\n committed: definition.empty,\n committedIds: [],\n pending: [],\n }\n const state: ReplicaState<Shared> =\n saved === undefined\n ? initial\n : yield* Effect.try({\n try: () => decodeState(saved),\n catch: cause =>\n unsupportedVersion(saved) ??\n new InvalidReplicaHistoryError({\n message: 'Stored replica state is invalid',\n cause,\n }),\n })\n if (state.documentId !== documentId || state.replicaId !== replicaId)\n return yield* new WrongReplicaStorageError({\n documentId,\n replicaId,\n message: 'The stored replica belongs to a different document or replica',\n })\n const committedIds = new Set(state.committedIds)\n if (state.nextLocalSequence < 1 || committedIds.size !== state.committedIds.length)\n return yield* new InvalidReplicaHistoryError({ message: 'Invalid replica history' })\n const pendingIds = new Set<string>()\n for (const pending of state.pending) {\n const operation = yield* Effect.try({\n try: () => operationFrom(pending, documentId),\n catch: () => new InvalidOutboxError({ message: 'Invalid outbox' }),\n })\n if (\n operation.replicaId !== replicaId ||\n operation.localSequence >= state.nextLocalSequence ||\n committedIds.has(operation.opId) ||\n pendingIds.has(operation.opId)\n )\n return yield* new InvalidOutboxError({ message: 'Invalid outbox' })\n pendingIds.add(operation.opId)\n }\n // Storage holds the schema's encoded side, so a transforming `shared`\n // codec round-trips: decode on load, encode before every save. Encoding\n // also rejects an invalid `empty` on first creation rather than at reload.\n const store = Effect.fn('Sync.store')(function* (\n next: ReplicaState<Shared>,\n expectedRevision: number | null,\n ) {\n const encoded = yield* Effect.try({\n try: () => encodeState(next),\n catch: cause =>\n new InvalidReplicaHistoryError({\n message: 'Could not encode the replica state',\n cause,\n }),\n })\n yield* storage.save(encoded, expectedRevision)\n })\n if (saved === undefined) yield* store(state, null)\n\n const stateRef = yield* SynchronizedRef.make(state)\n const closed = yield* Ref.make(false)\n const lastError = yield* Ref.make<string | undefined>(undefined)\n const rejectedOps = yield* Ref.make<ReadonlyArray<Rejection>>([])\n // Operations submitted since opening that no exchange has carried yet. Only these may\n // be coalesced: one that was sent may already be committed as it was.\n const unsent = yield* Ref.make<ReadonlySet<string>>(new Set())\n // One pending wake-up is enough: the loop exchanges the whole outbox.\n const wake = yield* Queue.sliding<void>(1)\n const statusSignals = yield* PubSub.sliding<void>(1)\n // The current value, then again after every change. Subscribed before the\n // first read, so a change made while a subscriber holds that value, or\n // between the read and the subscription, is still told.\n const following = <A>(read: Effect.Effect<A>): Stream.Stream<A> =>\n Stream.unwrap(\n Effect.map(PubSub.subscribe(statusSignals), signals =>\n Stream.concat(\n Stream.fromEffect(read),\n Stream.fromSubscription(signals).pipe(Stream.mapEffect(() => read)),\n ),\n ),\n )\n // The projection is pure over an immutable state, so a cached value is\n // reused until a write replaces the state object. A UI reads `shared` far\n // more often than it writes, and replaying a large outbox per read is\n // quadratic (see `bench/projection.bench.ts`).\n const projection = yield* Ref.make<\n { readonly state: ReplicaState<Shared>; readonly shared: Shared } | undefined\n >(undefined)\n const snapshot = Effect.fn('Sync.snapshot')(function* () {\n const current = yield* SynchronizedRef.get(stateRef)\n const cached = yield* Ref.get(projection)\n let projected: Shared\n if (cached !== undefined && cached.state === current) projected = cached.shared\n else {\n projected = optimistic(current)\n yield* Ref.set(projection, { state: current, shared: projected })\n }\n return {\n status: {\n pending: current.pending.length,\n cursor: current.cursor,\n lastError: yield* Ref.get(lastError),\n rejected: yield* Ref.get(rejectedOps),\n epoch: Option.fromUndefinedOr(current.epoch),\n },\n shared: projected,\n committed: current.committed,\n nextLocalSequence: current.nextLocalSequence,\n }\n })()\n const shared = Effect.map(snapshot, value => value.shared)\n const status = Effect.map(snapshot, value => value.status)\n\n // `SynchronizedRef.modifyEffect` installs the returned state itself, so\n // persisting must not also set the ref (that would re-enter the lock).\n const persist = (next: ReplicaState<Shared>, current: ReplicaState<Shared>) =>\n store(next, current.revision)\n\n const submit = Effect.fn('Sync.submit')(function* (message: Message) {\n yield* Effect.annotateCurrentSpan({ documentId, replicaId })\n const result = yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.gen(function* () {\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n if (!definition.durable(message))\n return yield* new InvalidOutboxError({ message: 'Message is local-only' })\n const last = current.pending[current.pending.length - 1]\n const merged =\n last !== undefined &&\n definition.coalesce !== undefined &&\n (yield* Ref.get(unsent)).has(last.opId)\n ? definition.coalesce(decodeMessage(last.message), message)\n : undefined\n if (merged !== undefined && !definition.durable(merged))\n return yield* new InvalidOutboxError({\n message: 'coalesce returned a local-only Message',\n })\n // A merged Message takes the place of the last operation, under its identity.\n const operation = yield* Effect.try({\n try: () =>\n operationFrom(\n merged === undefined\n ? {\n protocolVersion: PROTOCOL_VERSION,\n schemaVersion: SCHEMA_VERSION,\n documentId,\n replicaId,\n localSequence: current.nextLocalSequence,\n opId: `${replicaId}:${current.nextLocalSequence}`,\n baseCursor: current.cursor,\n message: encodeMessage(message),\n }\n : { ...last!, message: encodeMessage(merged) },\n documentId,\n ),\n catch: () => new InvalidOutboxError({ message: 'Invalid outbox' }),\n })\n // Replay before writing: a Message replay refuses can never be\n // applied, here or on another replica, so it must not reach the\n // outbox. The result is the next optimistic projection, so the\n // cache is seeded instead of replaying the outbox on the next read.\n // Rebuilding the projection replays the outbox, which can throw\n // too (an upgrade that changed `update` for a pending Message), so\n // it sits inside the same typed error as the new Message's replay.\n const cached = yield* Ref.get(projection)\n const replayed = yield* Effect.try({\n try: () =>\n definition.replay(\n cached !== undefined && cached.state === current\n ? cached.shared\n : optimistic(current),\n message,\n ),\n catch: cause =>\n new ReplayError({\n message: cause instanceof Error ? cause.message : 'Replay failed',\n cause,\n }),\n })\n // Validated and encoded by `persist`; decoding here would demand the\n // encoded side and break a transforming `shared` codec.\n // The sequence moves on a merge too, so every submit is visible in it; a gap\n // in local sequences is harmless.\n const next: ReplicaState<Shared> = {\n ...current,\n revision: current.revision + 1,\n nextLocalSequence: localSequence(current.nextLocalSequence + 1),\n pending: [\n ...(merged === undefined ? current.pending : current.pending.slice(0, -1)),\n operation,\n ],\n }\n // Only the new operation is written when the storage can append it.\n if (storage.append === undefined) yield* persist(next, current)\n else {\n const encoded = yield* Effect.try({\n try: () => encodeOperation(operation),\n catch: cause =>\n new InvalidReplicaHistoryError({\n message: 'Could not encode the operation',\n cause,\n }),\n })\n yield* storage.append(\n {\n revision: next.revision,\n nextLocalSequence: next.nextLocalSequence,\n localSequence: operation.localSequence,\n operation: encoded,\n },\n current.revision,\n )\n }\n yield* Ref.set(projection, { state: next, shared: replayed })\n yield* Ref.update(unsent, ids => new Set(ids).add(operation.opId))\n yield* Queue.offer(wake, undefined)\n return [undefined, next] as const\n }),\n )\n // Outside the lock, so a `statusChanges` subscriber reads the new state.\n yield* PubSub.publish(statusSignals, undefined)\n return result\n })\n\n /** One exchange; whether the server has more to send and this one made progress. */\n const exchangeOnce = Effect.fn('Sync.exchange')(function* () {\n yield* Effect.annotateCurrentSpan({ documentId })\n const transport = yield* Transport\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n // Read under the lock, as a submit writes, so no submit can merge into an operation\n // between its being read here and its being marked sent.\n const sent = yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Ref.update(unsent, ids => {\n const left = new Set(ids)\n for (const operation of current.pending) left.delete(operation.opId)\n return left\n }).pipe(Effect.as([current, current] as const)),\n )\n yield* Metric.update(syncMetrics.exchanges, 1)\n yield* Metric.update(syncMetrics.exchangePending, sent.pending.length)\n const response = yield* Effect.gen(function* () {\n const raw = yield* transport.exchange(sent.cursor, sent.pending, sent.epoch)\n // The response is untrusted: a malformed shape is a typed failure, not\n // a defect that escapes the declared error channel.\n return yield* Effect.try({\n try: () => decodeExchange(raw),\n catch: cause =>\n new InvalidExchangeError({ message: 'Invalid sync exchange response', cause }),\n })\n })\n const restarted = yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.gen(function* () {\n // A `close` during the exchange must not persist its result.\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n // Another epoch means the server's history is not the one the cursor points\n // into (it was reset): the answer starts from its beginning, so the committed\n // state is rebuilt from it. The outbox is the user's intent and is kept.\n const restarted =\n response.epoch !== undefined &&\n current.epoch !== undefined &&\n response.epoch !== current.epoch\n if (restarted)\n yield* Effect.logWarning('sync server history changed; rebuilding', {\n documentId,\n replicaId,\n })\n let cursor = restarted ? sequence(0) : current.cursor\n let committed = restarted ? definition.empty : current.committed\n // A checkpoint folds committed history into its snapshot, so the\n // retained id set starts over from it, as it does on a new epoch.\n const ids =\n response.checkpoint === undefined && !restarted\n ? new Set(current.committedIds)\n : new Set<string>()\n if (response.checkpoint !== undefined) {\n if (response.checkpoint.cursor < cursor)\n return yield* new CheckpointRegressionError({\n cursor,\n checkpointCursor: response.checkpoint.cursor,\n message: 'Checkpoint is behind the replica',\n })\n committed = response.checkpoint.model\n cursor = response.checkpoint.cursor\n yield* Metric.update(syncMetrics.checkpoints, 1)\n yield* Effect.logDebug('sync checkpoint adopted', { documentId, replicaId, cursor })\n }\n const acknowledged = new Set(response.acknowledged ?? [])\n const rejected = new Set(response.rejected)\n const sentIds = new Set(sent.pending.map(operation => operation.opId))\n for (const id of acknowledged)\n if (!sentIds.has(id))\n return yield* new ForeignAcknowledgementError({\n opId: id,\n message: 'Server acknowledged an operation that was not sent',\n })\n for (const id of rejected) {\n if (!sentIds.has(id))\n return yield* new ForeignRejectionError({\n opId: id,\n message: 'Server rejected an operation that was not sent',\n })\n // An id cannot be both; removal would be ambiguous and a faulty\n // server must not be able to make a pending operation vanish.\n if (acknowledged.has(id))\n return yield* new ForeignAcknowledgementError({\n opId: id,\n message: 'Server both acknowledged and rejected an operation',\n })\n }\n for (const { opId } of response.reasons ?? [])\n if (!rejected.has(opId))\n return yield* new ForeignRejectionError({\n opId,\n message: 'Server gave a reason for an operation it did not reject',\n })\n let applied = 0\n for (const raw of response.operations) {\n const { committed: operation, message } = yield* Effect.try({\n try: () => decodeCommittedOperation(raw, documentId),\n catch: cause =>\n new InvalidReplicaHistoryError({ message: 'Invalid committed operation', cause }),\n })\n if (operation.serverSequence <= cursor) continue\n if (operation.serverSequence !== cursor + 1 || ids.has(operation.opId))\n return yield* new CommittedOrderError({\n expected: cursor + 1,\n actual: operation.serverSequence,\n message: 'Invalid committed order',\n })\n // A throw here would be a defect, which bypasses `lastError` and leaves\n // `start` retrying the same page in silence.\n const replaying = committed\n committed = yield* Effect.try({\n try: () => definition.replay(replaying, message),\n catch: cause =>\n new ReplayError({\n message: cause instanceof Error ? cause.message : 'Replay failed',\n cause,\n }),\n })\n ids.add(operation.opId)\n cursor = operation.serverSequence\n applied += 1\n }\n if (applied > 0) yield* Metric.update(syncMetrics.applied, applied)\n // Validated and encoded by `persist`, for the same reason as submit.\n const epoch = response.epoch ?? current.epoch\n const next: ReplicaState<Shared> = {\n ...current,\n revision: current.revision + 1,\n committed,\n cursor,\n ...(epoch === undefined ? {} : { epoch }),\n committedIds: [...ids].slice(-COMMITTED_ID_WINDOW),\n // While the server has more to send, an acknowledged operation's committed\n // copy may be on a later page, so it stays in the optimistic view until then.\n // An acknowledged operation the replica is already past (committed before a\n // checkpoint, say) never arrives, so it goes once there is no more to read.\n pending: current.pending.filter(\n operation =>\n !ids.has(operation.opId) &&\n !(acknowledged.has(operation.opId) && response.more !== true) &&\n !rejected.has(operation.opId),\n ),\n }\n yield* persist(next, current)\n return [restarted, next] as const\n }),\n )\n yield* Ref.set(lastError, undefined)\n if (response.rejected.length > 0) {\n const reasonOf = new Map(\n (response.reasons ?? []).map(({ opId, reason }) => [opId, reason] as const),\n )\n // Every rejected id was sent: an unknown one failed the exchange above.\n const sentOf = new Map(\n sent.pending.map(operation => [operation.opId, operation] as const),\n )\n const refused = response.rejected.map((opId): Rejection => ({\n opId,\n reason: Option.fromUndefinedOr(reasonOf.get(opId)),\n operation: sentOf.get(opId)!,\n }))\n yield* Ref.update(rejectedOps, previous => [...refused, ...previous].slice(0, 32))\n }\n yield* PubSub.publish(statusSignals, undefined)\n const reached = (yield* SynchronizedRef.get(stateRef)).cursor\n return response.more === true && reached > (restarted ? 0 : sent.cursor)\n })\n\n // A server that pages its answer says there is more, and the replica asks again at\n // once; a round that moves the cursor nowhere ends it.\n const synchronize = Effect.gen(function* () {\n while (yield* exchangeOnce()) {}\n }).pipe(\n Effect.withSpan('Sync.synchronize'),\n // Any failed exchange, a refused response included, is what a UI shows,\n // so it is recorded and announced rather than left for the next submit.\n Effect.tapError(error =>\n Effect.gen(function* () {\n yield* Effect.logWarning('sync exchange failed', {\n documentId,\n replicaId,\n error: error.message,\n })\n yield* Ref.set(lastError, error.message)\n yield* PubSub.publish(statusSignals, undefined)\n }),\n ),\n )\n\n const start: Effect.Effect<void, never, Transport> = Effect.gen(function* () {\n const transport = yield* Transport\n // A server's notice wakes the loop as a submit does; the fiber ends with this one.\n // It starts at once so it is subscribed before the first exchange, which a\n // notice may arrive during.\n if (transport.changes !== undefined)\n yield* Effect.forkChild(\n Stream.runForEach(transport.changes, () => Queue.offer(wake, undefined)),\n { startImmediately: true },\n )\n let failures = 0\n while (!(yield* Ref.get(closed))) {\n const exit = yield* Effect.exit(synchronize)\n if (yield* Ref.get(closed)) return\n if (exit._tag === 'Success') {\n failures = 0\n yield* Queue.take(wake)\n } else {\n // Retried on a backoff, or sooner on a submit: an outbox must not\n // wait for the next keystroke to be delivered.\n failures += 1\n const backoff = Math.min(\n START_RETRY_MAX,\n START_RETRY_BASE * 2 ** Math.min(failures - 1, 16),\n )\n yield* Effect.raceFirst(Queue.take(wake), Effect.sleep(backoff))\n }\n }\n })\n\n return {\n replicaId,\n shared,\n snapshot,\n committed: Effect.map(SynchronizedRef.get(stateRef), state => state.committed),\n pending: Effect.map(SynchronizedRef.get(stateRef), state => state.pending),\n cursor: Effect.map(SynchronizedRef.get(stateRef), state => state.cursor),\n status,\n statusChanges: following(status),\n changes: following(snapshot),\n submit,\n synchronize,\n start,\n close: Effect.fn('Sync.close')(function* () {\n yield* Ref.set(closed, true)\n // Wake `start` so it can observe `closed` and return.\n yield* Queue.offer(wake, undefined)\n yield* storage.close\n })(),\n }\n },\n (effect, _replicaId, storage) =>\n // Close a partially initialized storage on any failure, including a\n // defect, so a failed open cannot leak the connection.\n effect.pipe(\n Effect.onExit(exit =>\n Exit.isSuccess(exit) ? Effect.void : storage.close.pipe(Effect.ignore),\n ),\n ),\n )\n\n return {\n documentId,\n durable: definition.durable,\n codec: { normalizeOperation, operationFrom, committedFrom, decodeExchange },\n journalContract,\n openReplica,\n }\n}\n","/**\n * The Foldkit-facing sync layer: `Sync.forApplication(App).make(config)`\n * compiles an application, a writable projection, and a durable Message subset\n * into the low-level `defineSync` contract, and exposes a read-only Surface over\n * the same projection.\n */\nimport { Equal, Option, Predicate, Schema } from 'effect'\nimport {\n MessageSet,\n Projection,\n Surface,\n type AppScope,\n type Contract,\n type MergeConstructors,\n type MergeFields,\n type RunnableApplication,\n type Wiring,\n type WritableProjection,\n} from 'foldkit-surface'\nimport type { DocumentId } from './ids.js'\nimport {\n defineSync,\n type CommitStamp,\n type JournalContract,\n type Operation,\n type Sync,\n} from './sync.js'\n\ntype MessageConstructor<Message> = (...args: never[]) => Message\n\n/** The Message union a tuple of constructors produces. */\nexport type MsgOf<Ms extends readonly unknown[]> = Ms[number] extends (...args: never[]) => infer M\n ? M\n : never\n\ntype AppMessage<\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n> = Schema.Schema.Type<AppScope<AppModel, F, Cases>['Message']>\n\n/** Reads the tag off a Foldkit Message constructor without constructing one. */\nconst messageTag = (constructor: unknown): string | undefined => {\n const literal = (constructor as { fields?: { _tag?: { ast?: { literal?: unknown } } } }).fields\n ?._tag?.ast?.literal\n return typeof literal === 'string' ? literal : undefined\n}\n\n/** A Message's tag. The application's union is generic here, so its `_tag` is read, not typed. */\nconst tagOf = (message: unknown): Option.Option<string> =>\n Predicate.hasProperty(message, '_tag') && typeof message._tag === 'string'\n ? Option.some(message._tag)\n : Option.none()\n\n/** The `_tag` literal of the Message a constructor produces. */\ntype TagOf<C> = C extends (...args: never[]) => infer M\n ? M extends { readonly _tag: infer T extends string }\n ? T\n : never\n : never\n\n/**\n * A journal contract that also carries the declared authorization policy, in\n * the shape `makeJournal` takes, so `makeJournal({ ...contract })` applies it.\n */\nexport interface PolicyJournalContract<Operation, Shared, Principal> extends JournalContract<\n Operation,\n Shared\n> {\n readonly authorize?: (request: {\n readonly principal: Principal\n readonly operation: Operation\n readonly snapshot: Shared\n }) => AuthorizeDecision\n}\n\n/**\n * What a rule decides: allowed, refused, or refused with a reason the server\n * sends to the person whose edit it was. The shape of Durable's own decision.\n */\nexport type AuthorizeDecision = boolean | { readonly allowed: false; readonly reason: string }\n\n/** What a per-variant `authorize` rule sees before the journal commits. */\nexport interface AuthorizeRequest<Principal, Message, Shared> {\n readonly principal: Principal\n readonly message: Message\n readonly shared: Shared\n}\n\n/**\n * Per-variant policy, keyed by durable tag: `message` is that variant exactly,\n * `shared` the authoritative snapshot. A variant without a rule is allowed; the\n * server may still refuse on its own grounds.\n */\nexport type AuthorizePolicy<\n Principal,\n Fields extends Schema.Struct.Fields,\n Ms extends readonly unknown[],\n> = {\n readonly [K in TagOf<Ms[number]>]?: (\n request: AuthorizeRequest<\n Principal,\n Extract<MsgOf<Ms>, { readonly _tag: K }>,\n Schema.Struct.Type<Fields>\n >,\n ) => AuthorizeDecision\n}\n\n/**\n * Per-variant commit stamps, keyed by durable tag: each writes what the server's commit\n * decided (its sequence, its actor) into that variant, and returns the same variant. A\n * variant without one is committed as sent.\n */\nexport type StampPolicy<Ms extends readonly unknown[]> = {\n readonly [K in TagOf<Ms[number]>]?: (\n message: Extract<MsgOf<Ms>, { readonly _tag: K }>,\n commit: CommitStamp,\n ) => Extract<MsgOf<Ms>, { readonly _tag: K }>\n}\n\ninterface BaseOptions<\n Principal,\n Fields extends Schema.Struct.Fields,\n Ms extends readonly unknown[],\n> {\n readonly documentId: DocumentId\n /** Name for the generated `surface`; defaults to the document id. */\n readonly name?: string\n /**\n * Replaces the replay derived from the application's `update`. It is a pure\n * reducer over the shared subset; only durable Messages reach it, and it runs\n * during admission, replay, and optimistic projection. It is not guarded: the\n * author owns its agreement with `update`.\n */\n readonly replay?: (\n shared: Schema.Struct.Type<NoInfer<Fields>>,\n message: MsgOf<NoInfer<Ms>>,\n ) => Schema.Struct.Type<NoInfer<Fields>>\n /** Authorization the server journal applies before committing; see `AuthorizePolicy`. */\n readonly authorize?: AuthorizePolicy<Principal, NoInfer<Fields>, NoInfer<Ms>>\n /** What the server's commit writes into a durable Message; see `StampPolicy`. */\n readonly stamp?: StampPolicy<NoInfer<Ms>>\n /**\n * Merges a durable Message into the one submitted before it while that one is unsent,\n * so a burst of edits is one operation. Replaying the result must equal replaying\n * `last` then `next`; undefined keeps them apart.\n */\n readonly coalesce?: (\n last: MsgOf<NoInfer<Ms>>,\n next: MsgOf<NoInfer<Ms>>,\n ) => MsgOf<NoInfer<Ms>> | undefined\n}\n\nexport interface MakeOptions<\n AppModel,\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<any>[],\n Principal = unknown,\n> extends BaseOptions<Principal, Fields, Ms> {\n /** The writable projection of the shared fields. */\n readonly shared: WritableProjection<AppModel, Fields>\n /** The Message subset the replica durably records and replays. */\n readonly durable: MessageSet<AppModel, any, Subset, Ms>\n}\n\n/**\n * One feature's contribution to a document: the fields it shares and the\n * Messages it records. `compose` merges fragments into one, to spread into\n * `make`; a field declared twice with a different codec or a tag declared twice\n * is rejected there.\n */\nexport interface SyncFragment<\n AppModel,\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<any>[],\n> {\n readonly shared: WritableProjection<AppModel, Fields>\n readonly durable: MessageSet<AppModel, any, Subset, Ms>\n}\n\ntype SharedOf<Fs extends readonly SyncFragment<any, any, any, any>[]> = {\n readonly [K in keyof Fs]: Fs[K]['shared']\n}\ntype DurableOf<Fs extends readonly SyncFragment<any, any, any, any>[]> = {\n readonly [K in keyof Fs]: Fs[K]['durable']\n}\n/** The merged shared fields of several fragments. */\nexport type FragmentFields<Fs extends readonly SyncFragment<any, any, any, any>[]> = MergeFields<\n SharedOf<Fs>\n>\n/** The concatenated durable constructors of several fragments. */\nexport type FragmentConstructors<Fs extends readonly SyncFragment<any, any, any, any>[]> =\n MergeConstructors<DurableOf<Fs>>\n\n/** The union of Messages several fragments record. */\nexport type FragmentMessages<Fs extends readonly SyncFragment<any, any, any, any>[]> =\n Fs[number] extends SyncFragment<any, any, infer V, any> ? V : never\n\n/**\n * The value `make` returns: the low-level `Sync` protocol plus the writable\n * projection, the declared Messages, and a read-only Surface over the\n * projection. Exported so a consumer can name the type.\n */\nexport interface DefinedSync<\n AppModel,\n Fields extends Schema.Struct.Fields,\n Message,\n Ms extends readonly unknown[],\n Principal = unknown,\n /** `true` when `make` was given `authorize`, so the contract's `authorize` is present. */\n Authorized extends boolean = false,\n> extends Sync<Message, Schema.Struct.Type<Fields>> {\n readonly surface: Surface<AppModel, Schema.Struct.Type<Fields>, MsgOf<Ms>, void>\n readonly projection: WritableProjection<AppModel, Fields>\n /** The reducer the replica replays durable Messages with: derived from `update`, or `make`'s `replay`. */\n readonly replay: (\n shared: Schema.Struct.Type<Fields>,\n message: Message,\n ) => Schema.Struct.Type<Fields>\n readonly messages: Ms\n /** For `Module`: this contract owns the shared projection's paths and records the durable tags. */\n readonly contract: Contract\n /**\n * How this contract joins an assembly: contract-only, so the Module sees it.\n * It routes nothing, runs nothing, and subscribes to nothing; Sync owns the\n * runtime through `mount` rather than joining it.\n */\n readonly wiring: () => Wiring<AppModel, never>\n /** The durable journal's codecs, reducer, and, when declared, authorization. */\n readonly journalContract: () => Authorized extends true\n ? PolicyJournalContract<Operation, Schema.Struct.Type<Fields>, Principal> &\n Required<\n Pick<PolicyJournalContract<Operation, Schema.Struct.Type<Fields>, Principal>, 'authorize'>\n >\n : PolicyJournalContract<Operation, Schema.Struct.Type<Fields>, Principal>\n}\n\n/** The sync constructors specialized to one application. */\nexport interface ApplicationSync<\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n Principal = unknown,\n> {\n /**\n * Fixes the `Principal` that `authorize` rules see. A `Principal` cannot be a\n * positional type argument beside an inferred Model, so it is supplied here:\n * `Sync.forApplication(App).withPrincipal<User>()`. Type-only.\n */\n readonly withPrincipal: <P>() => ApplicationSync<AppModel, F, Cases, P>\n /** One feature's shared fields and durable Messages, for `compose`. */\n readonly fragment: <\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[],\n >(config: {\n readonly shared: WritableProjection<AppModel, Fields>\n readonly durable: MessageSet<AppModel, any, Subset, Ms>\n }) => SyncFragment<AppModel, Fields, Subset, Ms>\n /**\n * Merges fragments into one: `make({ documentId, ...compose(Todos, Members) })`.\n * A field declared twice with a different codec, a tag declared twice, or a\n * fragment from another application throws.\n */\n readonly compose: <const Fs extends readonly SyncFragment<AppModel, any, any, any>[]>(\n ...fragments: Fs\n ) => SyncFragment<AppModel, FragmentFields<Fs>, FragmentMessages<Fs>, FragmentConstructors<Fs>>\n readonly make: {\n <\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[],\n >(\n options: MakeOptions<AppModel, Fields, Subset, Ms, Principal> & {\n readonly authorize: AuthorizePolicy<Principal, NoInfer<Fields>, NoInfer<Ms>>\n },\n ): DefinedSync<AppModel, Fields, AppMessage<AppModel, F, Cases>, Ms, Principal, true>\n <\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[],\n >(\n options: MakeOptions<AppModel, Fields, Subset, Ms, Principal>,\n ): DefinedSync<AppModel, Fields, AppMessage<AppModel, F, Cases>, Ms, Principal>\n }\n}\n\n/**\n * Replay derived from the application's own `update`: install the shared slice\n * into the initial Model, apply the Message, and read the slice back.\n *\n * A durable Message must be a deterministic, state-only transition of the shared\n * projection. Replay refuses one that returns a Command (a live effect cannot be\n * replayed) or that changes a Model field outside the projection (the change\n * would be silently lost), so a Message that needs either stays local and emits\n * a durable fact once the effect settles.\n */\nconst derivedReplay = <\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n Fields extends Schema.Struct.Fields,\n>(\n app: RunnableApplication<AppModel, F, Cases, any>,\n shared: WritableProjection<AppModel, Fields>,\n): ((\n value: Schema.Struct.Type<Fields>,\n message: AppMessage<AppModel, F, Cases>,\n) => Schema.Struct.Type<Fields>) => {\n const { initial, update } = app\n // Per-field equivalences for the fields the projection does not own outright,\n // built once, so a violation names the fields and replay (which runs per\n // pending operation on every optimistic read) does not re-compare the shared\n // slice against itself. A partially shared field is still compared.\n const owned = new Set(shared.dependencies.filter(path => path.length === 1).map(path => path[0]))\n const fields = Object.entries(app.Model.fields)\n .filter(([key]) => !owned.has(key))\n .map(\n ([key, field]) =>\n [key, Schema.toEquivalence(field as unknown as Schema.Schema<unknown>)] as const,\n )\n return (value, message) => {\n const result = update(shared.set(initial, value), message)\n if (result.commands !== undefined && result.commands.length > 0)\n throw new Error(\n `Sync.forApplication: durable \"${Option.getOrElse(tagOf(message), () => 'untagged')}\" returned ${result.commands.length} Command(s); a durable transition is state-only`,\n )\n const next = shared.get(result.model)\n // Writing the projection back into the baseline reproduces `update`'s\n // result exactly when it touched only shared fields.\n const written = shared.set(initial, next) as Record<string, unknown>\n const actual = result.model as Record<string, unknown>\n const changed = fields.filter(([key, equal]) => !equal(actual[key], written[key]))\n if (changed.length > 0)\n throw new Error(\n `Sync.forApplication: durable \"${Option.getOrElse(tagOf(message), () => 'untagged')}\" changed Model fields outside the shared projection: ${changed.map(([key]) => key).join(', ')}`,\n )\n return next\n }\n}\n\n/**\n * Merges fragments into one. The primitives reject a conflicting field, a\n * duplicate tag, and a subset from another application.\n */\nconst composeFragments = (\n fragments: readonly SyncFragment<any, any, any, any>[],\n): SyncFragment<any, any, any, any> => {\n const compose = Projection.compose as (\n ...projections: readonly WritableProjection<any, any>[]\n ) => WritableProjection<any, any>\n const union = MessageSet.union as (\n ...subsets: readonly MessageSet<any, any, any, any>[]\n ) => MessageSet<any, any, any, any>\n return {\n shared: compose(...fragments.map(fragment => fragment.shared)),\n durable: union(...fragments.map(fragment => fragment.durable)),\n }\n}\n\n/**\n * Specializes the sync constructors to a `Surface.application`, so\n * `Sync.forApplication(App).make({ documentId, shared, durable })` derives the\n * shared codec, the initial snapshot, the durable predicate, and replay from\n * the application, and refuses a subset that belongs to another application.\n * `defineSync` remains the protocol primitive when there is no application to\n * derive from.\n */\nexport const forApplication = <\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n>(\n app: RunnableApplication<AppModel, F, Cases, any>,\n): ApplicationSync<AppModel, F, Cases> => build(app)\n\nconst build = <\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n Principal,\n>(\n app: RunnableApplication<AppModel, F, Cases, any>,\n): ApplicationSync<AppModel, F, Cases, Principal> => {\n type Message = AppMessage<AppModel, F, Cases>\n const decodeMessage = Schema.decodeUnknownSync(\n app.Message as unknown as Schema.Codec<Message, unknown>,\n )\n\n const make = (\n options: MakeOptions<AppModel, any, any, any, Principal>,\n ): DefinedSync<AppModel, any, Message, any, Principal, boolean> => {\n type Shared = Record<string, unknown>\n const { shared, durable } = options\n\n // Two applications can have structurally identical Message unions, so the\n // types cannot separate them; the owner token can.\n if (durable.owner !== app.owner)\n throw new Error('Sync.make: the durable subset belongs to a different application')\n\n const replay: (value: Shared, message: Message) => Shared =\n options.replay === undefined\n ? derivedReplay(app, shared)\n : // `durable` has already rejected anything outside the declared subset.\n (value, message) => options.replay!(value, message as never)\n const durableTags = new Set(\n (durable.constructors as readonly unknown[])\n .map(messageTag)\n .filter((tag): tag is string => tag !== undefined),\n )\n // `AppScope` does not constrain its schemas' services; a Foldkit Message union\n // and a Struct are pure, so the low-level contract's `never` is satisfied.\n const sharedCodec = shared.schema as unknown as Schema.Codec<Shared, unknown>\n const stamps = options.stamp as\n | Record<string, (message: Message, commit: CommitStamp) => Message>\n | undefined\n const sync = defineSync<Message, Shared, unknown, unknown>({\n documentId: options.documentId,\n message: app.Message as unknown as Schema.Codec<Message, unknown>,\n shared: sharedCodec,\n empty: shared.get(app.initial),\n durable: message => Option.exists(tagOf(message), tag => durableTags.has(tag)),\n replay,\n // `durable` has already rejected anything outside the declared subset.\n coalesce: options.coalesce as\n | ((last: Message, next: Message) => Message | undefined)\n | undefined,\n ...(stamps === undefined\n ? {}\n : {\n stamp: (message: Message, commit: CommitStamp): Message =>\n Option.match(\n Option.flatMapNullishOr(tagOf(message), tag => stamps[tag]),\n {\n onNone: () => message,\n onSome: rule => {\n const stamped = rule(message, commit)\n if (!Equal.equals(tagOf(stamped), tagOf(message)))\n throw new Error('A stamp must return the variant it was given')\n return stamped\n },\n },\n ),\n }),\n })\n\n const rules = options.authorize as\n | Record<string, (request: AuthorizeRequest<Principal, Message, Shared>) => AuthorizeDecision>\n | undefined\n const journalContract = (): PolicyJournalContract<Operation, Shared, Principal> => {\n const base = sync.journalContract()\n if (rules === undefined) return base\n return {\n ...base,\n authorize: ({ principal, operation, snapshot }) => {\n const message = decodeMessage(operation.message)\n return Option.match(\n Option.flatMapNullishOr(tagOf(message), tag => rules[tag]),\n {\n onNone: () => true,\n onSome: rule => rule({ principal, message, shared: snapshot }),\n },\n )\n },\n }\n }\n\n const readOnly: Projection<AppModel, Shared> = Projection.fromReader(sharedCodec, shared.get, {\n dependencies: shared.dependencies,\n })\n const surface = Surface.make(app, options.name ?? String(options.documentId), {\n model: () => readOnly,\n messages: durable.constructors,\n })\n const contract: Contract = {\n kind: 'sync',\n name: surface.name,\n owner: app.owner,\n owns: shared.dependencies,\n observes: shared.dependencies,\n messages: [...durable.tags],\n metadata: [],\n }\n return {\n ...sync,\n journalContract,\n surface,\n projection: shared,\n replay,\n messages: durable.constructors,\n contract,\n wiring: () => ({ key: `sync:${contract.name}`, handles: [], contract }),\n }\n }\n\n return {\n withPrincipal: <P>() => build<AppModel, F, Cases, P>(app),\n fragment: config => {\n if (config.durable.owner !== app.owner)\n throw new Error('Sync.fragment: the durable subset belongs to a different application')\n return { shared: config.shared, durable: config.durable }\n },\n compose: ((...fragments: readonly SyncFragment<any, any, any, any>[]) =>\n composeFragments(fragments)) as ApplicationSync<AppModel, F, Cases, Principal>['compose'],\n make: make as ApplicationSync<AppModel, F, Cases, Principal>['make'],\n }\n}\n","/**\n * `Sync.mount`: runs a Foldkit application over a replica with one reducer.\n *\n * A durable Message is a state-only, deterministic transition of the shared\n * projection (the derived replay enforces it), so the application's own `update`\n * is applied at once and the Message is persisted afterwards in a Command. The\n * shared slice is re-installed from the replica when an exchange changes it or\n * a persist fails, through one private Message the application never sees.\n */\nimport { Effect, Exit, Layer, Option, Schema, Stream } from 'effect'\nimport { absurd } from 'effect/Function'\nimport type { Document, HtmlBuilder } from 'foldkit/html'\nimport * as Navigation from 'foldkit/navigation'\nimport type { UrlRequest } from 'foldkit/navigation'\nimport * as Port from 'foldkit/port'\nimport * as Runtime from 'foldkit/runtime'\nimport * as Subscription from 'foldkit/subscription'\nimport type { Subscriptions } from 'foldkit/subscription'\nimport type * as Update from 'foldkit/update'\nimport * as Url from 'foldkit/url'\nimport type { RunnableApplication } from 'foldkit-surface'\nimport type { ReplicaError } from './errors.js'\nimport type { DefinedSync } from './make.js'\nimport type { Replica, ReplicaStatus } from './sync.js'\n\nconst REFRESH = 'foldkit-sync/Refresh'\nconst PERSISTED = 'foldkit-sync/Persisted'\nconst FAILED = 'foldkit-sync/PersistenceFailed'\nconst NAVIGATE = 'foldkit-sync/Navigate'\nconst NAVIGATED = 'foldkit-sync/Navigated'\nconst DISPATCHED = 'foldkit-sync/Dispatched'\n\ntype Private =\n // Every replica status, applied in order, so `settled` counts one seen only once `update` has it.\n | { readonly _tag: typeof REFRESH; readonly status: ReplicaStatus; readonly changed: boolean }\n | { readonly _tag: typeof PERSISTED }\n | { readonly _tag: typeof FAILED; readonly error: ReplicaError }\n | { readonly _tag: typeof NAVIGATE; readonly request: UrlRequest }\n | { readonly _tag: typeof NAVIGATED }\n // An application Message sent through `dispatch`, so `settled` counts it in.\n | { readonly _tag: typeof DISPATCHED; readonly message: unknown }\n\n// A key per private tag, so a variant added to `Private` must be added here too.\nconst PRIVATE: Readonly<Record<Private['_tag'], true>> = {\n [REFRESH]: true,\n [PERSISTED]: true,\n [FAILED]: true,\n [NAVIGATE]: true,\n [NAVIGATED]: true,\n [DISPATCHED]: true,\n}\n\nconst isPrivate = (message: { readonly _tag: string }): message is Private =>\n Object.hasOwn(PRIVATE, message._tag)\n\n// A registered symbol, so two copies of this package in one bundle recognize each other's.\nconst FACT = Symbol.for('foldkit-sync/fact')\n\n/**\n * A Command that dispatches `message` as the next transition, which under `Sync.mount`\n * means within this one: the mount applies it straight after the `update` that returned\n * it, and persists it if it is durable, before any other Message is processed. This is\n * how a local intent turns into a durable fact that needs something only the intent's\n * transition knows, such as an id minted from local state, without a later Message\n * seeing the Model before the fact. Elsewhere, or once a parent has mapped the Command,\n * it is an ordinary Command that yields `message`, and so is one a durable Message's\n * update returns: replay would not apply it, and with derived replay the durable Message's\n * persist fails with `ReplayError` as for any Command.\n */\nexport const fact = <Message>(\n message: Message,\n): { readonly name: string; readonly effect: Effect.Effect<Message> } =>\n // Not enumerable, so the spread a mapping Command is copied with drops the marker, and a\n // mapped fact is the ordinary Command it now is rather than the unmapped Message.\n Object.defineProperty({ name: 'foldkit-sync/fact', effect: Effect.succeed(message) }, FACT, {\n value: message,\n enumerable: false,\n })\n\nconst factOf = (command: unknown): { readonly message: unknown } | undefined =>\n typeof command === 'object' && command !== null && FACT in command\n ? { message: (command as { readonly [FACT]: unknown })[FACT] }\n : undefined\n\n/**\n * The URL as part of the application: `onUrlChange` names the Message the\n * runtime sends for the current URL at start and on every navigation (so a\n * `foldkit-mirror` URL mirror reads back in), `init` reduces the URL into the\n * Model before the first render, and `onUrlRequest` names the Message for a\n * link click; omitted, the mount follows the link itself (an internal one is\n * pushed, an external one loaded).\n */\nexport interface MountUrl<Model, Message> {\n readonly init?: ((model: Model, url: Url.Url) => Model) | undefined\n readonly onUrlChange: (url: Url.Url) => Message\n readonly onUrlRequest?: ((request: UrlRequest) => Message) | undefined\n}\n\nexport interface MountOptions<Model, Message, Shared, Resources> {\n /** An open replica of this contract; `mount` does not close it. */\n readonly replica: Replica<Message, Shared>\n /** The element the application renders into; Foldkit requires it to have an `id`. */\n readonly container: HTMLElement\n readonly view: (model: Model, h: HtmlBuilder<Message>) => Document\n readonly subscriptions?: Subscriptions<Model, Message, Resources> | undefined\n readonly resources?: Layer.Layer<Resources> | undefined\n /** Route the URL through the application; without it the mount ignores the URL. */\n readonly url?: MountUrl<Model, Message> | undefined\n /**\n * Reflects a refused or failed persist in the Model, after the durable edit\n * has been reverted. Omitted, the edit is reverted silently.\n */\n readonly onPersistenceFailure?: ((model: Model, error: ReplicaError) => Model) | undefined\n /**\n * Runs when the mount replaces the shared slice outside `update`: an exchange committed,\n * acknowledged or rejected something, or a persist failed and its edit was reverted.\n * `previous` is the Model before; what it returns is the transition, so an application\n * can carry local state across the change (a selection held by what it points at) or\n * return Commands (a DOM the change has to reach). Omitted, the Model is `next`. It is\n * not called for a status that changes nothing the Model shows, such as the first.\n */\n readonly onReinstall?:\n | ((\n next: Model,\n previous: Model,\n change: Reinstall,\n ) => Update.Return<Model, Message, Resources>)\n | undefined\n /**\n * Runs on the Model after every update of the mounted application, a durable\n * Message's and a reinstall's included, and never in replay: for local state\n * derived from the shared slice, which a durable transition may not write\n * (the overlays `foldkit-sync/remote` keeps in Remote). With nothing to\n * change it returns the Model it was given.\n */\n readonly afterUpdate?: ((model: Model) => Update.Return<Model, Message, Resources>) | undefined\n}\n\n/**\n * What a reinstall came from. `reset` is a server reset: the replica's\n * committed history is a new one, so anything an application derived from\n * the old one (reads cached by commit sequence, say) is to be read again.\n */\nexport interface Reinstall {\n readonly reset: boolean\n}\n\n/**\n * The shared slice as the server has confirmed it, outside the Model. It is a\n * source for waiting consumers, the shape `Agent.when({ source })` reads, and\n * not a Projection: it does not render and is not derived from the Model.\n */\nexport interface CommittedView<Shared> {\n readonly get: () => Shared\n /** Told after every exchange, including one that moves no cursor (a checkpoint). */\n readonly subscribe: (listener: () => void) => () => void\n}\n\nexport interface Mounted<Model, Message, Shared = unknown> {\n /** Sends an application Message through the runtime; the `Exit` reports a decode failure. */\n readonly dispatch: (message: Message) => Exit.Exit<void, unknown>\n /** The Model after the last transition. */\n readonly model: () => Model\n /** Notified after every transition; with `model` and `dispatch`, the host an agent binds to. */\n readonly subscribe: (listener: () => void) => () => void\n /**\n * Every application Message the runtime applies, from any origin, so an\n * agent contract that declares a `completion` can see the Message that\n * finishes its work. The mount's private Messages are not reported.\n */\n readonly observe: (listener: (message: Message) => void) => () => void\n /**\n * The shared slice without pending local edits, for an agent that must not\n * report an optimistic edit as done: `Agent.when({ source: mounted.committed, … })`.\n */\n readonly committed: CommittedView<Shared>\n /**\n * Resolves once the Model has caught up with the replica: no persist in\n * flight or unanswered, every replica status the mount was told of seen,\n * and every reinstall it asked for applied. It observes and never does the\n * work. Frames are not its to wait for (`Frames.track` in\n * `foldkit-mixins/testing` is), nor I/O a Command started. Rejects after\n * `dispose`.\n */\n readonly settled: () => Promise<void>\n /** Waits for in-flight persists, then disposes the runtime. The replica stays open. */\n readonly dispose: () => Promise<void>\n}\n\n/**\n * Commits, rejections and acknowledgments change what the replica holds; a\n * submit only echoes a local edit. An acknowledgment that does not return the\n * operation moves no cursor, but it still drops the edit from the outbox.\n */\nconst sharedChanged = (previous: ReplicaStatus | undefined, next: ReplicaStatus): boolean =>\n previous === undefined ||\n previous.cursor !== next.cursor ||\n next.pending < previous.pending ||\n previous.rejected.length !== next.rejected.length ||\n previous.rejected.some((rejection, index) => rejection.opId !== next.rejected[index]?.opId)\n\n/**\n * A durable edit the Model already shows. `started` is the replica's next local\n * sequence when its submit began, `undefined` while it waits for its turn.\n */\nexport interface LocalEdit<Message> {\n readonly message: Message\n started: number | undefined\n}\n\n/**\n * The edits a replica whose next local sequence is `next` does not hold yet.\n * Submits run one at a time, so the one in flight is in the replica exactly\n * when its submit has moved the sequence past `started`.\n */\nexport const unconfirmedEdits = <Message>(\n edits: ReadonlyArray<LocalEdit<Message>>,\n next: number,\n): ReadonlyArray<Message> =>\n edits.filter(edit => edit.started === undefined || next <= edit.started).map(edit => edit.message)\n\n/** The application's Message union, as `Surface.application` types it. */\ntype MessageOf<App> =\n App extends RunnableApplication<any, any, any, any> ? Schema.Schema.Type<App['Message']> : never\n\nexport const mount = <\n Model,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n Fields extends Schema.Struct.Fields,\n Ms extends readonly unknown[],\n Resources = never,\n Principal = unknown,\n>(\n app: RunnableApplication<Model, F, Cases, Resources>,\n sync: DefinedSync<\n Model,\n Fields,\n MessageOf<RunnableApplication<Model, F, Cases, Resources>>,\n Ms,\n Principal\n >,\n options: MountOptions<\n Model,\n MessageOf<RunnableApplication<Model, F, Cases, Resources>>,\n Schema.Struct.Type<Fields>,\n Resources\n >,\n): Mounted<\n Model,\n MessageOf<RunnableApplication<Model, F, Cases, Resources>>,\n Schema.Struct.Type<Fields>\n> => {\n // Foldkit reports a missing id only inside the runtime fiber, where nothing\n // renders and nothing is thrown; fail here instead.\n if (options.container.id === '')\n throw new Error('Sync.mount: the container needs an id (`container.id = \"app\"`)')\n type Message = MessageOf<RunnableApplication<Model, F, Cases, Resources>>\n // The application's Messages are tagged structs; the generic cannot say so.\n type Tagged = { readonly _tag: string }\n type RuntimeMessage = (Message & Tagged) | Private\n type Shared = Schema.Struct.Type<Fields>\n const { replica } = options\n const durable = new Set(sync.contract.messages)\n\n // Durable edits whose submit has not settled, in dispatch order.\n const edits: Array<LocalEdit<Message>> = []\n // An edit shows before it is stored, so a reload while one waits would lose\n // what the reader saw: the browser asks first, from the first such edit\n // until the last is stored.\n const holdUnload = (event: Event): void => event.preventDefault()\n const unloadGuarded = (guarded: boolean): void => {\n if (typeof window === 'undefined') return\n if (guarded) window.addEventListener('beforeunload', holdUnload)\n else window.removeEventListener('beforeunload', holdUnload)\n }\n // Settles when the latest edit's submit does; the next submit waits for it.\n let tail: Promise<void> = Promise.resolve()\n\n // The replica's `shared` holds every settled edit, and the one in flight once\n // its submit lands; the rest are replayed on top. Read from one snapshot, so\n // a refresh neither hides an edit still waiting for the replica nor applies\n // one the replica already holds.\n // The replica's shared value the Model was last installed from, and whether a durable\n // edit has changed the Model's copy since. The replica keeps one object per state, so\n // the same object with no edit since is the shared slice the Model already shows.\n let installedFrom: Shared | undefined\n let editedSinceInstall = false\n const install = (model: Model): Model => {\n const snapshot = Effect.runSync(replica.snapshot)\n installedFrom = snapshot.shared\n editedSinceInstall = false\n const shared = unconfirmedEdits(edits, snapshot.nextLocalSequence).reduce<Shared>(\n (value, message) => {\n try {\n return sync.replay(value, message)\n } catch {\n // The replica refuses it too; its FAILED re-installs without it.\n return value\n }\n },\n snapshot.shared,\n )\n return sync.projection.set(model, shared)\n }\n\n const inFlight = new Set<Promise<void>>()\n // What `settled` waits on: dispatches and persists not yet answered in\n // `update`, and the last replica status `update` applied.\n let dispatchesOwed = 0\n let persistsOwed = 0\n let applied: ReplicaStatus | undefined\n let disposed = false\n const waiters = new Set<{\n readonly resolve: () => void\n readonly reject: (error: Error) => void\n }>()\n const quiet = (): boolean =>\n dispatchesOwed === 0 &&\n persistsOwed === 0 &&\n !sharedChanged(applied, Effect.runSync(replica.status))\n const notifySettled = (): void => {\n if (!quiet()) return\n for (const waiter of [...waiters]) {\n waiters.delete(waiter)\n waiter.resolve()\n }\n }\n /**\n * A private transition that leaves the Model as it was: the runtime sends\n * no Subscription the change, so `settled` is told here, once it returns.\n */\n const unchanged = (model: Model): Update.Return<Model, RuntimeMessage, Resources> => {\n queueMicrotask(notifySettled)\n return { model }\n }\n let latest: Model = install(app.initial)\n const modelListeners = new Set<() => void>()\n const committedListeners = new Set<() => void>()\n const messageListeners = new Set<(message: Message) => void>()\n // Listeners run inside `update`, a Subscription, and the refresh stream. A\n // throwing one must not break those or skip the listeners after it, so its\n // error is reported asynchronously, as an event listener's would be.\n const notifyEach = <A>(listeners: ReadonlySet<(value: A) => void>, value: A): void => {\n for (const listener of [...listeners]) {\n try {\n listener(value)\n } catch (error) {\n queueMicrotask(() => {\n throw error\n })\n }\n }\n }\n const notifyCommitted = (): void => notifyEach(committedListeners, undefined)\n\n const updatePrivate = (\n model: Model,\n message: Private,\n ): Update.Return<Model, RuntimeMessage, Resources> => {\n switch (message._tag) {\n // Installs at once: edits still waiting for the replica are replayed on\n // top, so nothing is deferred behind them.\n case REFRESH: {\n // The server's history changed under the replica: a reset.\n const reset =\n applied !== undefined &&\n Option.isSome(applied.epoch) &&\n Option.isSome(message.status.epoch) &&\n applied.epoch.value !== message.status.epoch.value\n applied = message.status\n // The first status, and any other that changed nothing the Model shows, reinstall\n // nothing, so `onReinstall` hears only of a real change.\n if (\n !message.changed ||\n (!editedSinceInstall && Effect.runSync(replica.snapshot).shared === installedFrom)\n ) {\n return unchanged(model)\n }\n return reinstalled(install(model), model, { reset })\n }\n case PERSISTED:\n persistsOwed--\n return unchanged(model)\n case FAILED: {\n persistsOwed--\n const { error } = message\n const reverted = install(model)\n return reinstalled(options.onPersistenceFailure?.(reverted, error) ?? reverted, model, {\n reset: false,\n })\n }\n case NAVIGATE: {\n // A link the application did not claim: follow it. The runtime then\n // reports the new URL through `onUrlChange`.\n const { request } = message\n const follow =\n request._tag === 'Internal'\n ? Navigation.pushUrl(Url.toString(request.url))\n : Navigation.load(request.href)\n return {\n model,\n commands: [\n {\n name: 'foldkit-sync/navigate',\n effect: follow.pipe(Effect.as({ _tag: NAVIGATED } as RuntimeMessage)),\n },\n ],\n }\n }\n case NAVIGATED:\n return { model }\n case DISPATCHED:\n dispatchesOwed--\n return transition(model, message.message as Message & Tagged)\n default:\n return absurd(message)\n }\n }\n\n const update = (\n model: Model,\n message: RuntimeMessage,\n ): Update.Return<Model, RuntimeMessage, Resources> => {\n const result = isPrivate(message)\n ? updatePrivate(model, message)\n : transition(model, message as Message & Tagged)\n if (options.afterUpdate === undefined) return result\n const after = applyFacts(\n options.afterUpdate(result.model) as Update.Return<Model, RuntimeMessage, Resources>,\n )\n return after.model === result.model && (after.commands ?? []).length === 0\n ? result\n : { model: after.model, commands: [...(result.commands ?? []), ...(after.commands ?? [])] }\n }\n\n const reinstalled = (\n next: Model,\n previous: Model,\n change: Reinstall,\n ): Update.Return<Model, RuntimeMessage, Resources> =>\n options.onReinstall === undefined\n ? { model: next }\n : applyFacts(\n options.onReinstall(next, previous, change) as Update.Return<\n Model,\n RuntimeMessage,\n Resources\n >,\n )\n\n /** The application's transition for one of its Messages, with the persist a durable one needs. */\n const step = (\n model: Model,\n message: Message & Tagged,\n ): Update.Return<Model, RuntimeMessage, Resources> => {\n notifyEach(messageListeners, message)\n const result = app.update(model, message) as Update.Return<Model, RuntimeMessage, Resources>\n if (!durable.has(message._tag)) return result\n editedSinceInstall = true\n persistsOwed++\n const edit: LocalEdit<Message> = { message, started: undefined }\n edits.push(edit)\n if (edits.length === 1) unloadGuarded(true)\n const previous = tail\n let settle!: () => void\n const done = new Promise<void>(resolve => {\n settle = resolve\n })\n tail = done\n const release = (): void => {\n const index = edits.indexOf(edit)\n if (index !== -1) edits.splice(index, 1)\n if (edits.length === 0) unloadGuarded(false)\n inFlight.delete(done)\n settle()\n }\n const persist = {\n name: 'foldkit-sync/persist',\n effect: Effect.gen(function* () {\n // Tracked so `dispose` can wait instead of interrupting a persist.\n inFlight.add(done)\n // One submit at a time, in dispatch order, so `started` is the\n // sequence this edit takes if its submit succeeds.\n yield* Effect.promise(() => previous)\n edit.started = (yield* replica.snapshot).nextLocalSequence\n const outcome = yield* Effect.result(replica.submit(edit.message))\n return outcome._tag === 'Success'\n ? ({ _tag: PERSISTED } as RuntimeMessage)\n : ({ _tag: FAILED, error: outcome.failure } as RuntimeMessage)\n }).pipe(\n // `ensuring`, so a defect in storage still releases the next submit and `dispose`.\n Effect.ensuring(Effect.sync(release)),\n ),\n }\n return { model: result.model, commands: [...(result.commands ?? []), persist] }\n }\n\n /**\n * A Message's transition, with the facts it returned applied after it. A durable\n * Message's are not: replay would not apply them, so they stay ordinary Commands.\n */\n const transition = (\n model: Model,\n message: Message & Tagged,\n ): Update.Return<Model, RuntimeMessage, Resources> => {\n const result = step(model, message)\n return durable.has(message._tag) ? result : applyFacts(result)\n }\n\n /** Applies the facts a transition returned, in order, each as the transition after it. */\n const applyFacts = (\n result: Update.Return<Model, RuntimeMessage, Resources>,\n ): Update.Return<Model, RuntimeMessage, Resources> => {\n let model = result.model\n const kept: Array<Update.Commands<RuntimeMessage, Resources>[number]> = []\n for (const command of result.commands ?? []) {\n const found = factOf(command)\n if (found === undefined) {\n kept.push(command)\n continue\n }\n const next = transition(model, found.message as Message & Tagged)\n model = next.model\n kept.push(...(next.commands ?? []))\n }\n return { model, commands: kept }\n }\n\n const ports = {\n inbound: { message: Port.inbound(app.Message as unknown as Schema.Codec<Message, unknown>) },\n }\n const own = Subscription.make<Model, RuntimeMessage, Resources>()(() => ({\n message: Port.subscriptionEntry(ports.inbound.message, (message): RuntimeMessage => ({\n _tag: DISPATCHED,\n message,\n })),\n // The replica's status carries the cursor and rejections, which is exactly\n // when the shared slice held locally can differ from the replica's.\n refresh: Subscription.persistentEntry<RuntimeMessage, Resources>(\n replica.statusChanges.pipe(\n // Every status, not only a changed cursor: a checkpoint at the same\n // cursor still replaces the committed state a waiter reads.\n Stream.tap(() => Effect.sync(notifyCommitted)),\n Stream.mapAccum(\n (): ReplicaStatus | undefined => undefined,\n (previous, status): readonly [ReplicaStatus, ReadonlyArray<RuntimeMessage>] => [\n status,\n [{ _tag: REFRESH, status, changed: sharedChanged(previous, status) }],\n ],\n ),\n ),\n ),\n // `modelToDependencies` runs on every transition, so it doubles as the Model\n // getter the runtime does not expose.\n latest: {\n dependenciesSchema: Schema.Struct({}),\n modelToDependencies: (model: Model) => {\n latest = model\n notifyEach(modelListeners, undefined)\n // After every transition, so `settled` resolves once `model()` has it.\n notifySettled()\n return {}\n },\n dependenciesToStream: () => Stream.never,\n },\n }))\n const subscriptions =\n options.subscriptions === undefined\n ? own\n : Subscription.aggregate<Model, RuntimeMessage, Resources>()(\n options.subscriptions as Subscriptions<Model, RuntimeMessage, Resources>,\n own,\n )\n\n const view = (model: Model, h: HtmlBuilder<RuntimeMessage>): Document =>\n // Sound: the view constructs only application Messages, a subset of the\n // runtime's union.\n options.view(model, h as unknown as HtmlBuilder<Message>)\n const common = {\n Model: app.Model as unknown as Schema.Codec<Model, any, unknown, unknown>,\n container: options.container,\n ports,\n update,\n subscriptions,\n ...(options.resources === undefined ? {} : { resources: options.resources }),\n view,\n }\n const url = options.url\n const program =\n url === undefined\n ? Runtime.makeApplication({ ...common, init: () => ({ model: latest }) })\n : Runtime.makeApplication({\n ...common,\n routing: {\n onUrlChange: (at: Url.Url) => url.onUrlChange(at) as RuntimeMessage,\n onUrlRequest: (request: UrlRequest): RuntimeMessage =>\n url.onUrlRequest === undefined\n ? { _tag: NAVIGATE, request }\n : (url.onUrlRequest(request) as RuntimeMessage),\n },\n init: (at: Url.Url) => {\n latest = url.init === undefined ? latest : url.init(latest, at)\n return { model: latest }\n },\n })\n const handle = Runtime.embed(program)\n const encodeMessage = Schema.encodeExit(app.Message as unknown as Schema.Codec<Message, unknown>)\n\n return {\n // The port decodes what it is sent, so it takes the Message encoded: a\n // Message is sent as its type is, Option fields and all.\n dispatch: message =>\n Exit.match(encodeMessage(message), {\n onSuccess: encoded => {\n // Counted before the send, in case the port delivers within it.\n dispatchesOwed++\n const sent = handle.ports.message.send(encoded)\n if (Exit.isFailure(sent)) dispatchesOwed--\n return sent\n },\n onFailure: cause => Exit.failCause(cause),\n }),\n model: () => latest,\n subscribe: listener => {\n modelListeners.add(listener)\n return () => modelListeners.delete(listener)\n },\n observe: listener => {\n messageListeners.add(listener)\n return () => messageListeners.delete(listener)\n },\n committed: {\n get: () => Effect.runSync(replica.committed),\n subscribe: listener => {\n committedListeners.add(listener)\n return () => committedListeners.delete(listener)\n },\n },\n settled: () => {\n if (disposed) return Promise.reject(new Error('Sync.mount: settled() after dispose'))\n if (quiet()) return Promise.resolve()\n return new Promise<void>((resolve, reject) => waiters.add({ resolve, reject }))\n },\n dispose: async () => {\n disposed = true\n for (const waiter of [...waiters]) {\n waiters.delete(waiter)\n waiter.reject(new Error('Sync.mount: disposed before it settled'))\n }\n await Promise.all([...inFlight])\n handle.dispose()\n },\n }\n}\n","import {\n Clock,\n Duration,\n Effect,\n Fiber,\n PubSub,\n Ref,\n Stream,\n SynchronizedRef,\n type Scope,\n} from 'effect'\nimport type { SocketLike } from './transport.js'\n\n/** One peer's presence. A `null` value means the peer left. */\nexport interface PresenceUpdate<Update> {\n readonly id: string\n readonly value: Update | null\n}\n\n/**\n * The ephemeral channel presence travels on.\n *\n * `updates` is the inbound bus a peer consumes; `publish` sends one to the bus.\n * Splitting them keeps an inbound update from being echoed straight back out.\n * This is deliberately not the durable transport: presence is broadcast, never\n * journaled, so a dropped or duplicated update is harmless.\n */\nexport interface PresenceChannel<Update> {\n readonly updates: PubSub.PubSub<PresenceUpdate<Update>>\n readonly publish: (update: PresenceUpdate<Update>) => Effect.Effect<void>\n}\n\nexport interface PresenceOptions<Update> {\n /** This peer's identity on the channel. */\n readonly id: string\n /** How long a peer may go without refreshing before it is dropped. */\n readonly ttl: Duration.Input\n /**\n * Validates the untrusted value a peer sends before it is stored. Presence\n * crosses a wire, so this is required rather than trusting the type\n * parameter; a value it rejects is dropped.\n */\n readonly decodeValue: (value: unknown) => Update\n readonly channel?: PresenceChannel<Update> | undefined\n /**\n * The least time between two values sent on the channel. `set` still takes effect here at\n * once; a value set sooner waits, and only the latest one waiting is sent when the time is\n * up. A departure is never held back. Absent, every `set` is sent at once.\n */\n readonly throttle?: Duration.Input | undefined\n}\n\nexport interface PresencePeer<Update> {\n readonly id: string\n readonly value: Update\n readonly updatedAt: number\n}\n\nexport interface Presence<Update> {\n /** Sets this peer's value and broadcasts it, no sooner than `throttle` allows. */\n readonly set: (value: Update) => Effect.Effect<void>\n /** Removes this peer and broadcasts the departure. */\n readonly leave: Effect.Effect<void>\n /** Live peers, self included, with stale ones excluded. */\n readonly peers: Effect.Effect<ReadonlyArray<PresencePeer<Update>>>\n /** Drops expired peers; notifies if any went. */\n readonly prune: Effect.Effect<void>\n /** Notified when the peer set changes. */\n readonly subscribe: (listener: () => void) => () => void\n /**\n * The live peers, re-emitted whenever the set changes. The `Stream` form of\n * `subscribe`, for a consumer that composes with Effect.\n */\n readonly changes: Stream.Stream<ReadonlyArray<PresencePeer<Update>>>\n /** Stops consuming the channel; the enclosing scope also does this on exit. */\n readonly close: Effect.Effect<void>\n}\n\n/**\n * Tracks ephemeral peers with a time-to-live.\n *\n * Nothing here touches the durable log: presence is state a peer refreshes, and\n * a peer that stops refreshing is dropped, not replayed. Time comes from the\n * `Clock`, so a `TestClock` drives the TTL deterministically.\n */\nexport const createPresence = Effect.fn('Presence.create')(function* <Update>(\n options: PresenceOptions<Update>,\n) {\n const ttl = Duration.toMillis(options.ttl)\n const throttle = options.throttle === undefined ? 0 : Duration.toMillis(options.throttle)\n const scope = yield* Effect.scope\n // What a throttled channel has sent and holds. Every decision about it is made under\n // this one lock, so two `set`s cannot both send in one interval, a value held while a\n // flush finds nothing cannot be stranded, and a flush is never forked and lost.\n const outbound = yield* SynchronizedRef.make<{\n readonly lastSent: number | undefined\n readonly held: { readonly value: Update } | undefined\n readonly flusher: Fiber.Fiber<void> | undefined\n }>({ lastSent: undefined, held: undefined, flusher: undefined })\n const peers = yield* Ref.make(new Map<string, PresencePeer<Update>>())\n const closed = yield* Ref.make(false)\n const signals = yield* PubSub.sliding<void>(1)\n const listeners = new Set<() => void>()\n /** A subscriber must never fail an update. */\n const notify = (): Effect.Effect<void> =>\n Effect.gen(function* () {\n for (const listener of [...listeners]) {\n try {\n listener()\n } catch {\n // Deliberately swallowed.\n }\n }\n yield* PubSub.publish(signals, undefined)\n })\n const expired = (peer: PresencePeer<Update>, at: number): boolean => at - peer.updatedAt > ttl\n\n const put = (id: string, value: Update, at: number): Effect.Effect<void> =>\n Ref.update(peers, map => {\n const next = new Map(map)\n next.set(id, { id, value, updatedAt: at })\n return next\n })\n const remove = (id: string): Effect.Effect<boolean> =>\n Ref.modify(peers, map => {\n if (!map.has(id)) return [false, map] as const\n const next = new Map(map)\n next.delete(id)\n return [true, next] as const\n })\n\n const receive = Effect.fn('Presence.receive')(function* (update: PresenceUpdate<Update>) {\n if (update.id === options.id) return\n if (update.value === null) {\n if (yield* remove(update.id)) yield* notify()\n return\n }\n let value: Update\n try {\n value = options.decodeValue(update.value)\n } catch {\n // A peer's value that fails the contract is dropped, never stored.\n return\n }\n yield* put(update.id, value, yield* Clock.currentTimeMillis)\n yield* notify()\n })\n\n const channel = options.channel\n const consuming =\n channel === undefined\n ? undefined\n : yield* Stream.runForEach(Stream.fromPubSub(channel.updates), receive).pipe(\n Effect.forkScoped,\n )\n\n const publish = (value: Update): Effect.Effect<void> =>\n channel!.publish({ id: options.id, value })\n\n /** Drops a value waiting to be sent, so nothing older goes out after what comes next. */\n const cancelHeld = SynchronizedRef.updateEffect(outbound, state =>\n (state.flusher === undefined ? Effect.void : Fiber.interrupt(state.flusher)).pipe(\n Effect.as({ ...state, held: undefined, flusher: undefined }),\n ),\n )\n\n /** Sends what is held once per interval, until an interval passes with nothing held. */\n const flush = (wait: number): Effect.Effect<void> =>\n Effect.gen(function* () {\n for (let delay = wait; ; delay = throttle) {\n yield* Effect.sleep(delay)\n const now = yield* Clock.currentTimeMillis\n const latest = yield* SynchronizedRef.modify(outbound, state =>\n state.held === undefined\n ? ([undefined, { ...state, flusher: undefined }] as const)\n : ([state.held, { ...state, held: undefined, lastSent: now }] as const),\n )\n if (latest === undefined) return\n yield* publish(latest.value)\n }\n })\n\n const broadcast = (value: Update, at: number): Effect.Effect<void> =>\n Effect.gen(function* () {\n const sends = yield* SynchronizedRef.modifyEffect(outbound, state =>\n Effect.gen(function* () {\n // `set` checked too, but `close` may have run since; a flush forked now would outlive it.\n if (yield* Ref.get(closed)) return [false, state] as const\n if (state.flusher !== undefined) return [false, { ...state, held: { value } }] as const\n // Without a throttle the wait is never positive, so every value goes at once; a\n // clock set back never makes one wait longer than an interval.\n const wait =\n state.lastSent === undefined ? 0 : Math.min(throttle, state.lastSent + throttle - at)\n if (wait <= 0) return [true, { ...state, lastSent: at }] as const\n const flusher = yield* Effect.forkIn(flush(wait), scope)\n return [false, { ...state, held: { value }, flusher }] as const\n }).pipe(Effect.uninterruptible),\n )\n if (sends) yield* publish(value)\n })\n\n const set = Effect.fn('Presence.set')(function* (value: Update) {\n if (yield* Ref.get(closed)) return\n const at = yield* Clock.currentTimeMillis\n yield* put(options.id, value, at)\n if (channel !== undefined) yield* broadcast(value, at)\n yield* notify()\n })\n\n const leave = Effect.fn('Presence.leave')(function* () {\n if (yield* Ref.get(closed)) return\n yield* cancelHeld\n yield* remove(options.id)\n if (channel !== undefined) yield* channel.publish({ id: options.id, value: null })\n yield* notify()\n })()\n\n const peerList = Effect.fn('Presence.peers')(function* () {\n const at = yield* Clock.currentTimeMillis\n const map = yield* Ref.get(peers)\n return [...map.values()].filter(peer => !expired(peer, at)).map(peer => ({ ...peer }))\n })()\n\n const prune = Effect.fn('Presence.prune')(function* () {\n if (yield* Ref.get(closed)) return\n const at = yield* Clock.currentTimeMillis\n const changed = yield* Ref.modify(peers, map => {\n let removed = false\n const next = new Map(map)\n for (const [id, peer] of map) {\n if (expired(peer, at)) {\n next.delete(id)\n removed = true\n }\n }\n return [removed, next] as const\n })\n if (changed) yield* notify()\n })()\n\n const close = Effect.fn('Presence.close')(function* () {\n if (yield* Ref.get(closed)) return\n yield* Ref.set(closed, true)\n yield* cancelHeld\n if (consuming !== undefined) yield* Fiber.interrupt(consuming)\n yield* Effect.sync(() => listeners.clear())\n yield* PubSub.shutdown(signals)\n })()\n\n return {\n set,\n leave,\n peers: peerList,\n prune,\n subscribe: (listener: () => void) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n changes: Stream.concat(\n Stream.fromEffect(peerList),\n Stream.fromPubSub(signals).pipe(Stream.mapEffect(() => peerList)),\n ),\n close,\n }\n})\n\n/** An in-process channel, for tests and single-process demos. */\nexport const loopbackPresenceChannel = Effect.fn('Presence.loopbackChannel')(function* <Update>() {\n const updates = yield* PubSub.unbounded<PresenceUpdate<Update>>()\n return {\n updates,\n publish: (update: PresenceUpdate<Update>) => PubSub.publish(updates, update),\n }\n})\n\n/** Broadcasts presence updates among connected peers. */\nexport interface PresenceHub<Update> {\n /** Registers a peer's send; returns a leave function. */\n join(send: (update: PresenceUpdate<Update>) => void): () => void\n /** Fans an update out to every joined peer. */\n publish(update: PresenceUpdate<Update>): void\n}\n\nexport const createPresenceHub = <Update>(): PresenceHub<Update> => {\n const peers = new Set<(update: PresenceUpdate<Update>) => void>()\n return {\n join: send => {\n peers.add(send)\n return () => peers.delete(send)\n },\n publish: update => {\n for (const send of [...peers]) {\n try {\n send(update)\n } catch {\n // One broken peer must not starve the rest of the fan-out.\n }\n }\n },\n }\n}\n\nconst frameType = 'presence'\n\n/** A presence frame. `id` is set by the server that owns the identity. */\ninterface PresenceFrame<Update> {\n readonly id: string | undefined\n readonly value: Update | null\n}\n\n/** Decodes a presence frame, ignoring anything else a socket may carry. */\nconst decodePresence = <Update>(data: string): PresenceFrame<Update> | undefined => {\n let frame: unknown\n try {\n frame = JSON.parse(data)\n } catch {\n return undefined\n }\n if (typeof frame !== 'object' || frame === null) return undefined\n const payload = (frame as Record<string, unknown>)[frameType]\n if (typeof payload !== 'object' || payload === null) return undefined\n const { id, value } = payload as { id?: unknown; value?: unknown }\n return { id: typeof id === 'string' ? id : undefined, value: (value ?? null) as Update | null }\n}\n\n/**\n * A presence channel fed by stamped frames from the server, sent back without an\n * id: the server owns peer identity, so a client cannot assert another's.\n */\nexport const socketPresenceChannel = <Update>(\n socket: SocketLike,\n): Effect.Effect<PresenceChannel<Update>, never, Scope.Scope> =>\n Effect.gen(function* () {\n const updates = yield* PubSub.unbounded<PresenceUpdate<Update>>()\n yield* Effect.acquireRelease(\n Effect.sync(() =>\n socket.onMessage(data => {\n const frame = decodePresence<Update>(data)\n // An unstamped frame is not from the server and carries no identity.\n if (frame === undefined || frame.id === undefined) return\n PubSub.publishUnsafe(updates, { id: frame.id, value: frame.value })\n }),\n ),\n off => Effect.sync(off),\n )\n return {\n updates,\n publish: update =>\n Effect.sync(() => socket.send(JSON.stringify({ [frameType]: { value: update.value } }))),\n }\n })\n\n/**\n * Serves presence frames on an accepted socket, stamping the connection's\n * identity, until the socket closes or the returned function is called.\n * With `opens`, the connection joins only once it answers that it may open\n * the document the presence accompanies: until then, and for good when it\n * is refused or fails, nothing reaches it and nothing it sends is relayed.\n */\nexport const servePresence = <Update>(\n socket: SocketLike,\n hub: PresenceHub<Update>,\n options: {\n readonly peerId: string\n readonly opens?: Effect.Effect<boolean, unknown> | undefined\n },\n): (() => void) => {\n const send = (update: PresenceUpdate<Update>): void =>\n socket.send(JSON.stringify({ [frameType]: { id: update.id, value: update.value } }))\n let stopped = false\n let leave = (): void => {}\n let off = (): void => {}\n const join = (): void => {\n leave = hub.join(send)\n off = socket.onMessage(data => {\n const frame = decodePresence<Update>(data)\n if (frame === undefined) return\n // The connection owns the identity; a client-supplied id is ignored.\n const publish = () => hub.publish({ id: options.peerId, value: frame.value })\n if (options.opens === undefined) return publish()\n // Asked again with each frame: one no longer let open the document leaves.\n void Effect.runPromise(options.opens).then(\n open => {\n if (stopped) return\n if (open) publish()\n else stop()\n },\n () => stop(),\n )\n })\n }\n if (options.opens === undefined) join()\n else\n void Effect.runPromise(options.opens).then(\n open => {\n if (open && !stopped) join()\n },\n () => {},\n )\n const stop = (): void => {\n stopped = true\n off()\n leave()\n }\n const stopClose = socket.onClose(stop)\n return () => {\n stop()\n stopClose()\n }\n}\n","/**\n * `foldkit-sync` — a local-first replica of a shared Foldkit projection.\n *\n * The application's Message union and update function stay authoritative: sync\n * wraps them rather than introducing a second reducer. The replica owns the\n * local outbox, optimistic projection, and reconciliation; a durable server\n * journal provides authoritative order.\n *\n * `Sync` is the namespace: `Sync.forApplication`, `Sync.mount`,\n * `Sync.transport.socket`. Ids are branded schemas, so they construct through\n * `DocumentId.make('todos')`. Every name is also exported on its own.\n */\nimport { indexedDb } from './indexedDb.js'\nimport { lwwRegister, openLwwClock } from './lww.js'\nimport { forApplication } from './make.js'\nimport { fact, mount } from './mount.js'\nimport {\n createPresence,\n createPresenceHub,\n loopbackPresenceChannel,\n servePresence,\n socketPresenceChannel,\n} from './presence.js'\nimport { defineSync, syncMetrics, type Sync as SyncContract } from './sync.js'\nimport {\n layerFromPromise,\n layerLoopback,\n layerSocket,\n nativeSocket,\n portSocket,\n serveSocket,\n toPromise,\n workerSocket,\n} from './transport.js'\n\n/**\n * The contract `Sync.define` and `Sync.forApplication(App).make` produce: the\n * wire codecs, the server journal's contract, and `openReplica`.\n *\n * This is the type; `Sync` is also the value namespace below, the way\n * `Effect.Effect` is both.\n */\nexport type Sync<Message, Shared> = SyncContract<Message, Shared>\n\n/** The package's public surface, grouped. Each entry is the exported function itself. */\nexport const Sync = {\n /** Derives a sync contract from a Foldkit application: `Sync.forApplication(App).make({…})`. */\n forApplication,\n /** The protocol primitive, for a client with no Foldkit application to derive from. */\n define: defineSync,\n /** Runs a Foldkit application over an open replica with one reducer. */\n mount,\n /** A Command whose Message the mount applies within the transition that returned it. */\n fact,\n /** Counters and a histogram an application can scrape. */\n metrics: syncMetrics,\n /** The only storage adapter: one IndexedDB database per document/replica. */\n indexedDb,\n\n /** The `Transport` service's layers, and the bridges to and from a promise client. */\n transport: {\n /** A reconnecting WebSocket client layer. */\n socket: layerSocket,\n /** An in-process layer, for tests and single-process demos. */\n loopback: layerLoopback,\n /** Wraps the promise-based client the replica already speaks. */\n fromPromise: layerFromPromise,\n /** Bridges the service back to that promise client. */\n toPromise,\n /** The server side of one accepted socket connection. */\n serve: serveSocket,\n /** The accepted end of a Cloudflare `WebSocketPair`, for `serve`. */\n workerSocket,\n /** The default socket factory: the platform `WebSocket`. */\n nativeSocket,\n /** A socket over a `MessagePort`, closed by `close()` or an abort signal. */\n portSocket,\n },\n\n /** An ephemeral, TTL'd peer registry, deliberately outside the durable log. */\n presence: {\n make: createPresence,\n /** Broadcasts presence updates among connected peers, on the server. */\n hub: createPresenceHub,\n /** Serves presence frames on an accepted socket, stamping the connection's identity. */\n serve: servePresence,\n socketChannel: socketPresenceChannel,\n loopbackChannel: loopbackPresenceChannel,\n },\n\n /** Last-writer-wins registers (experimental): a per-field merge on logical time. */\n lww: {\n register: lwwRegister,\n /** The durable counter a stamp is allocated from, before dispatch. */\n openClock: openLwwClock,\n },\n}\n\nexport { indexedDb, type OutboxEntry, type Storage } from './indexedDb.js'\nexport {\n fact,\n mount,\n type CommittedView,\n type MountOptions,\n type Reinstall,\n type MountUrl,\n type Mounted,\n} from './mount.js'\nexport {\n forApplication,\n type ApplicationSync,\n type AuthorizeDecision,\n type AuthorizePolicy,\n type AuthorizeRequest,\n type DefinedSync,\n type FragmentMessages,\n type MakeOptions,\n type MsgOf,\n type PolicyJournalContract,\n type StampPolicy,\n type SyncFragment,\n} from './make.js'\nexport {\n DocumentId,\n LocalSequence,\n OpId,\n ReplicaId,\n Sequence,\n documentId,\n localSequence,\n opId,\n replicaId,\n sequence,\n} from './ids.js'\nexport {\n CheckpointRegressionError,\n CommittedOrderError,\n ForeignAcknowledgementError,\n ForeignRejectionError,\n InvalidExchangeError,\n InvalidOutboxError,\n InvalidReplicaHistoryError,\n ReplayError,\n ReplicaClosedError,\n StorageError,\n UnsupportedClockVersionError,\n UnsupportedReplicaVersionError,\n WrongReplicaStorageError,\n type ReplicaError,\n} from './errors.js'\nexport { lwwRegister, openLwwClock, type LwwClock, type LwwClockState } from './lww.js'\nexport {\n createPresence,\n createPresenceHub,\n loopbackPresenceChannel,\n servePresence,\n socketPresenceChannel,\n type Presence,\n type PresenceChannel,\n type PresenceHub,\n type PresenceOptions,\n type PresencePeer,\n type PresenceUpdate,\n} from './presence.js'\nexport {\n layerFromPromise,\n layerLoopback,\n layerSocket,\n nativeSocket,\n portSocket,\n serveSocket,\n toPromise,\n workerSocket,\n Transport,\n TransportError,\n type ExchangeFrame,\n type ExchangeReply,\n type NotifyFrame,\n type SocketLike,\n type SocketOptions,\n type TransportShape,\n} from './transport.js'\nexport {\n defineSync,\n syncMetrics,\n type Checkpoint,\n type CommitStamp,\n type CommittedOperation,\n type Exchange,\n type JournalContract,\n type Operation,\n type Rejection,\n type Replica,\n type ReplicaSnapshot,\n type ReplicaState,\n type ReplicaStatus,\n type SyncDefinition,\n type TransportClient,\n} from './sync.js'\n"],"mappings":";;;;;;;;;;;AAGA,IAAa,eAAb,cAAkC,OAAO,YAA0B,CAAC,CAAC,gBAAgB;CACnF,SAAS,OAAO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ElB;;CAEA,QAAQ;;CAER;;CAEA;;CAEA,SAAS;;CAET;;CAGA,WAAW;;EAET,QAAQ;;EAER,UAAU;;EAEV,aAAa;;EAEb;;EAEA,OAAO;;EAEP;;EAEA;;EAEA;CACF;;CAGA,UAAU;EACR,MAAM;;EAEN,KAAK;;EAEL,OAAO;EACP,eAAe;EACf,iBAAiB;CACnB;;CAGA,KAAK;EACH,UAAU;;EAEV,WAAW;CACb;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldkit-sync",
3
- "version": "0.12.0",
3
+ "version": "0.12.2",
4
4
  "description": "A local-first replica of a shared Foldkit projection: offline outbox, optimistic updates, and reconciliation.",
5
5
  "keywords": [
6
6
  "foldkit",
@@ -59,13 +59,13 @@
59
59
  "LICENSE"
60
60
  ],
61
61
  "dependencies": {
62
- "foldkit-surface": "0.10.0"
62
+ "foldkit-surface": "0.10.2"
63
63
  },
64
64
  "peerDependencies": {
65
65
  "effect": "^4.0.0",
66
- "foldkit": "^0.168.0",
67
- "foldkit-durable": "0.9.0",
68
- "foldkit-remote": "0.18.0"
66
+ "foldkit": "^0.169.0",
67
+ "foldkit-durable": "0.9.1",
68
+ "foldkit-remote": "0.19.0"
69
69
  },
70
70
  "peerDependenciesMeta": {
71
71
  "foldkit-durable": {
@@ -76,20 +76,20 @@
76
76
  }
77
77
  },
78
78
  "devDependencies": {
79
- "@cloudflare/workers-types": "5.20261013.1",
80
- "@effect/platform-browser": "^4.0.4",
81
- "@effect/sql-d1": "^4.0.4",
82
- "effect": "^4.0.4",
79
+ "@cloudflare/workers-types": "5.20261022.1",
80
+ "@effect/platform-browser": "^4.0.5",
81
+ "@effect/sql-d1": "^4.0.5",
82
+ "effect": "^4.0.5",
83
83
  "esbuild": "0.28.2",
84
- "foldkit": "0.168.0",
85
- "jsdom": "30.1.2",
84
+ "foldkit": "0.169.0",
85
+ "jsdom": "30.1.3",
86
86
  "miniflare": "4.20260730.0",
87
87
  "tsdown": "^0.23.1",
88
88
  "typescript": "7.0.2",
89
- "foldkit-durable": "0.9.0",
90
- "foldkit-agent": "0.8.1",
91
- "foldkit-remote": "0.18.0",
92
- "foldkit-entity": "0.10.0"
89
+ "foldkit-agent": "0.8.3",
90
+ "foldkit-durable": "0.9.1",
91
+ "foldkit-remote": "0.19.0",
92
+ "foldkit-entity": "0.11.0"
93
93
  },
94
94
  "scripts": {
95
95
  "build": "tsdown",