foldkit-sync 0.17.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/do.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"do.js","names":["JournalDocumentId"],"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 { Cause, Duration, Effect, Exit, type Layer, Option, Result } from 'effect'\nimport type { RemoteUnauthenticated } from 'foldkit-remote'\nimport type { Diagnostic } from 'foldkit-surface'\nimport { DocumentId as JournalDocumentId, 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 { hostDefect, reportTo } from './diagnostics.js'\nimport type { AuthorizeDecision } from './make.js'\nimport type { Operation, Sync, WrittenOperation } from './sync.js'\nimport { workerSocket } from './transport.js'\nimport { serverJournal, type Reaction, type ServerJournal } from './serverJournal.js'\n\n/** How long after a commit the alarm is set for: what resumes a run eviction cut off. */\nconst ALARM_AFTER_COMMIT = Duration.seconds(1)\n/** When the alarm comes back after a pass that broke: never left to the runtime's retries. */\nconst ALARM_AFTER_DEFECT = Duration.seconds(30)\n\n/** The alarm a Durable Object's storage keeps: one per object. */\nexport interface AlarmStorage {\n getAlarm(): Promise<number | null>\n setAlarm(scheduledTime: number): Promise<void>\n}\n\n/**\n * Brings a Durable Object's alarm to `at` (ms since the Unix epoch) unless it\n * is already sooner: what an application's own `alarm()` uses beside the\n * host's, which shares the object's one alarm. Inside `alarm()` the runtime\n * may still answer the alarm being run, so a time already past counts as no\n * alarm.\n */\nexport const armAlarm = async (storage: AlarmStorage, at: number): Promise<void> => {\n const current = await storage.getAlarm()\n if (current === null || current <= Date.now() || current > at) await storage.setAlarm(at)\n}\n\nconst alarmsOf = (storage: unknown): Option.Option<AlarmStorage> =>\n typeof storage === 'object' &&\n storage !== null &&\n typeof (storage as Partial<AlarmStorage>).getAlarm === 'function' &&\n typeof (storage as Partial<AlarmStorage>).setAlarm === 'function'\n ? Option.some(storage as AlarmStorage)\n : Option.none()\n\n/**\n * The sliver of a Durable Object the host uses: state for the journal to\n * open with, and, with `server`, the storage's alarm (`getAlarm`,\n * `setAlarm`). Left `unknown` so `openJournal` can read the rest of it (the\n * object's SQLite) as its own type.\n */\nexport interface DocumentHostContext {\n readonly storage?: unknown\n}\n\n/** The server's own side of the document, for `defineDocumentHost`'s `server`. */\nexport interface DocumentHostServer<Principal, Env> {\n /** Who the server commits as. Never resolved from a request, and never changed. */\n readonly principal: Principal\n /** The document's reactions, made from the environment (a mailer's key, a binding). */\n readonly reactions: (env: Env) => ReadonlyArray<Reaction<unknown, never>>\n /** The most runs one pass starts. */\n readonly runsPerPass?: number | undefined\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, WrittenOperation>>\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, WrittenOperation>,\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 * The server's own side: who it commits as, and the document's reactions\n * (`foldkit-sync/journal`'s `reaction`), for a contract from\n * `Sync.forApplication(App).make`. The host registers them when it opens\n * the journal, before the first socket is served. After an exchange that\n * committed, it sets the object's alarm and then runs them without holding\n * the reply; `alarm()` runs them and sets the alarm again from what they\n * answer. A run eviction cut off is resumed by the alarm, never by the\n * runtime's retries of a throwing `alarm()`. The object has one alarm:\n * the host only ever brings it earlier.\n */\n readonly server?: DocumentHostServer<Principal, Env> | 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 * Where each upgrade's diagnostics go, with its request: a `HostDefect`\n * for every failure answered \"Internal error\" (making the socket pair,\n * the resolver, the journal, the exchange) and the rest `documentHost`\n * reports. A pass of reactions that broke has no request of its own: it is\n * reported with one for `https://durable-object/alarm`. The reporter in the\n * Effect context when not given, by default the log.\n */\n readonly diagnostics?:\n | ((diagnostic: Diagnostic, request: Request) => Effect.Effect<void>)\n | 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 (\n ctx: DocumentHostContext,\n env: Env,\n) => {\n fetch(request: Request): Promise<Response>\n alarm(...info: Array<unknown>): Promise<void>\n} => {\n checkRevalidate(config.revalidate, 'defineDocumentHost')\n // The application's own alarm, if its base has one: run after the reactions'.\n const baseAlarm = (Base.prototype as { readonly alarm?: unknown }).alarm\n return class extends Base {\n private readonly host: (request: Request) => Promise<Result.Result<Accepted, Response>>\n private readonly react: () => Promise<void>\n\n constructor(ctx: DocumentHostContext, env: Env) {\n super(ctx, env)\n interface Opened {\n readonly journal: Journal<Operation, Shared, Principal, WrittenOperation>\n readonly server: Option.Option<ServerJournal<unknown, never>>\n }\n let ready: Promise<Opened> | undefined\n const { layer, settle, server } = config\n const alarms = Option.flatMap(Option.fromUndefinedOr(server), () => alarmsOf(ctx.storage))\n if (server !== undefined && Option.isNone(alarms))\n throw new Error('defineDocumentHost: `server` needs the object’s storage alarm')\n // Made now, so one declared for another contract fails here and not at\n // the first upgrade; `serverJournal` checks the rest when it opens.\n const reactions = server === undefined ? [] : server.reactions(env)\n for (const each of reactions)\n if (each.sync !== config.sync)\n throw new Error(\n `defineDocumentHost: reaction ${each.name} was declared for another contract`,\n )\n /** Reports a pass that broke; a reporter that fails itself is not let out of `alarm()`. */\n const report = (stage: 'Alarm', cause: Cause.Cause<unknown>): Promise<void> =>\n Effect.runPromise(\n reportTo(\n config.diagnostics === undefined\n ? undefined\n : diagnostic =>\n config.diagnostics!(diagnostic, new Request('https://durable-object/alarm')),\n hostDefect(stage, cause),\n ),\n ).catch(() => undefined)\n const arm = (after: Duration.Duration): Promise<void> =>\n armAlarm(Option.getOrThrow(alarms), Date.now() + Duration.toMillis(after))\n // The journal and the reactions' registration in one, once per object:\n // registered before any socket is served, so no commit is missed.\n const open = (): Promise<Opened> =>\n (ready ??= config.openJournal(ctx, env).then(async journal => ({\n journal,\n server:\n server === undefined\n ? Option.none()\n : Option.some(\n await Effect.runPromise(\n // The contract's own type is not kept here: `serverJournal`\n // refuses a reaction declared for another at run time.\n serverJournal({\n sync: config.sync,\n journal,\n server: server.principal,\n reactions,\n runsPerPass: server.runsPerPass,\n } as never) as Effect.Effect<ServerJournal<unknown, never>>,\n ),\n ),\n }))).catch((error: unknown) => {\n ready = undefined\n throw error\n })\n /**\n * One pass, then the alarm from its answer. Never rejects: a pass that\n * broke (the journal would not open, a reaction was never registered)\n * is reported and brings the alarm back later.\n */\n const runPass = async (): Promise<void> => {\n if (server === undefined) return\n const exit = await Effect.runPromiseExit(\n Effect.gen(function* () {\n const { server: running } = yield* Effect.promise(open)\n if (Option.isNone(running)) return\n const next = yield* running.value.react\n if (Option.isSome(next)) yield* Effect.promise(() => arm(next.value))\n }),\n )\n if (Exit.isSuccess(exit)) return\n await report('Alarm', exit.cause)\n await arm(ALARM_AFTER_DEFECT).catch(() => undefined)\n }\n // `serverJournal` runs one pass at a time itself.\n const pass = runPass\n this.react = pass\n // What the host knows was committed, so only an exchange that moved it arms the alarm.\n let seen = -1\n const afterExchange = (journal: Journal<Operation, Shared, Principal, WrittenOperation>) =>\n Effect.gen(function* () {\n const at = yield* journal.cursor(JournalDocumentId.make(config.sync.documentId))\n if (at === seen) return\n // Before the reply, so a run cut off by eviction is resumed. One that\n // fails is reported, and `seen` stays, so the next exchange arms again.\n const armed = yield* Effect.promise(() =>\n arm(ALARM_AFTER_COMMIT).then(\n () => true,\n async (error: unknown) => {\n await report('Alarm', Cause.die(error))\n return false\n },\n ),\n )\n if (armed) seen = at\n // Not awaited: the reply does not wait on a provider.\n void pass()\n })\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: () => open().then(opened => opened.journal),\n resolvePrincipal: request => config.resolvePrincipal(request, env),\n layer: layer === undefined ? undefined : () => layer(env),\n revalidate: config.revalidate,\n settle:\n settle === undefined && server === undefined\n ? undefined\n : journal =>\n Effect.gen(function* () {\n // First: a settle that fails still leaves what committed to be reacted to.\n if (server !== undefined) yield* afterExchange(journal)\n if (settle !== undefined) yield* settle(env, journal)\n }),\n opens: config.opens,\n admit: config.admit,\n diagnostics: config.diagnostics,\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 /**\n * The object's alarm: runs the reactions and sets the alarm again from\n * what they answer, then the base class's own `alarm()`, if it has one,\n * with what the runtime passed. The reactions' part never throws, so the\n * runtime's few retries of a throwing alarm are never what a run depends\n * on. The object has one alarm, shared: the base runs on every wake, so\n * it decides itself what is due, and sets its next with `armAlarm`, which\n * only brings the alarm earlier. A subclass that overrides `alarm()` calls\n * `super.alarm()`, or the reactions stop being resumed.\n */\n async alarm(...info: Array<unknown>): Promise<void> {\n await this.react()\n if (typeof baseAlarm === 'function')\n await (baseAlarm as (...info: Array<unknown>) => Promise<void>).apply(this, info)\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 // The replica learns nothing of it; whoever runs the host must.\n const broke = async (error: unknown): Promise<Response> => {\n const { diagnostics } = config\n await Effect.runPromise(\n reportTo(\n diagnostics === undefined ? undefined : diagnostic => diagnostics(diagnostic, request),\n hostDefect('Upgrade', Cause.die(error)),\n ),\n )\n return Response.json({ error: 'Internal error' }, { status: 500 })\n }\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 return broke(error)\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 abandon()\n return broke(error)\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,MAAM,qBAAqB,SAAS,QAAQ,CAAC;;AAE7C,MAAM,qBAAqB,SAAS,QAAQ,EAAE;;;;;;;;AAe9C,MAAa,WAAW,OAAO,SAAuB,OAA8B;CAClF,MAAM,UAAU,MAAM,QAAQ,SAAS;CACvC,IAAI,YAAY,QAAQ,WAAW,KAAK,IAAI,KAAK,UAAU,IAAI,MAAM,QAAQ,SAAS,EAAE;AAC1F;AAEA,MAAM,YAAY,YAChB,OAAO,YAAY,YACnB,YAAY,QACZ,OAAQ,QAAkC,aAAa,cACvD,OAAQ,QAAkC,aAAa,aACnD,OAAO,KAAK,OAAuB,IACnC,OAAO,KAAK;;;;;AA4IlB,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,KAAK,IAAI,KAAK,EAAE;AAC1B;;;;;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],"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 { Cause, Duration, Effect, Exit, type Layer, Option, Result } from 'effect'\nimport type { RemoteUnauthenticated } from 'foldkit-remote'\nimport type { Diagnostic } from 'foldkit-surface'\nimport { DocumentId as JournalDocumentId, 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 { answerHostDefect, hostDefect, reportTo } from './diagnostics.js'\nimport type { AuthorizeDecision } from './make.js'\nimport type { Operation, Sync, WrittenOperation } from './sync.js'\nimport { workerSocket } from './transport.js'\nimport { serverJournal, type Reaction, type ServerJournal } from './serverJournal.js'\n\n/** How long after a commit the alarm is set for: what resumes a run eviction cut off. */\nconst ALARM_AFTER_COMMIT = Duration.seconds(1)\n/** When the alarm comes back after a pass that broke: never left to the runtime's retries. */\nconst ALARM_AFTER_DEFECT = Duration.seconds(30)\n\n/** The alarm a Durable Object's storage keeps: one per object. */\nexport interface AlarmStorage {\n getAlarm(): Promise<number | null>\n setAlarm(scheduledTime: number): Promise<void>\n}\n\n/**\n * Brings a Durable Object's alarm to `at` (ms since the Unix epoch) unless it\n * is already sooner: what an application's own `alarm()` uses beside the\n * host's, which shares the object's one alarm. Inside `alarm()` the runtime\n * may still answer the alarm being run, so a time already past counts as no\n * alarm.\n */\nexport const armAlarm = async (storage: AlarmStorage, at: number): Promise<void> => {\n const current = await storage.getAlarm()\n if (current === null || current <= Date.now() || current > at) await storage.setAlarm(at)\n}\n\nconst alarmsOf = (storage: unknown): Option.Option<AlarmStorage> =>\n typeof storage === 'object' &&\n storage !== null &&\n typeof (storage as Partial<AlarmStorage>).getAlarm === 'function' &&\n typeof (storage as Partial<AlarmStorage>).setAlarm === 'function'\n ? Option.some(storage as AlarmStorage)\n : Option.none()\n\n/**\n * The sliver of a Durable Object the host uses: state for the journal to\n * open with, and, with `server`, the storage's alarm (`getAlarm`,\n * `setAlarm`). Left `unknown` so `openJournal` can read the rest of it (the\n * object's SQLite) as its own type.\n */\nexport interface DocumentHostContext {\n readonly storage?: unknown\n}\n\n/** The server's own side of the document, for `defineDocumentHost`'s `server`. */\nexport interface DocumentHostServer<Principal, Env> {\n /** Who the server commits as. Never resolved from a request, and never changed. */\n readonly principal: Principal\n /** The document's reactions, made from the environment (a mailer's key, a binding). */\n readonly reactions: (env: Env) => ReadonlyArray<Reaction<unknown, never>>\n /** The most runs one pass starts. */\n readonly runsPerPass?: number | undefined\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, WrittenOperation>>\n /**\n * Who is opening this socket, from the upgrade request. Fails with a\n * `RemoteUnauthenticated` (`foldkit-remote`; `RemoteServer.unauthenticated(reason?)`\n * makes one) to refuse it: a 401 that says \"Unauthenticated\", or its\n * `reason` when it has one, and never its `message`. A defect, or any\n * other failure, is a 500 that says nothing of it. What it needs (a session\n * store) comes from `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, WrittenOperation>,\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 the reason\n * \"Unauthenticated\", or the refusal's `reason` when it has one, and a\n * principal whose `key` differs from the one it opened with\n * (`Policy.keyOf`) closes it with 1012, which the replica reconnects\n * after, as the new principal; without `key` only a refusal closes it. A\n * resolver that breaks closes it with 1011. Without `revalidate` 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 * The server's own side: who it commits as, and the document's reactions\n * (`foldkit-sync/journal`'s `reaction`), for a contract from\n * `Sync.forApplication(App).make`. The host registers them when it opens\n * the journal, before the first socket is served. After an exchange that\n * committed, it sets the object's alarm and then runs them without holding\n * the reply; `alarm()` runs them and sets the alarm again from what they\n * answer. A run eviction cut off is resumed by the alarm, never by the\n * runtime's retries of a throwing `alarm()`. The object has one alarm:\n * the host only ever brings it earlier.\n */\n readonly server?: DocumentHostServer<Principal, Env> | 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 * Where each upgrade's diagnostics go, with its request: a `HostDefect`\n * for every failure answered \"Internal error\" (making the socket pair,\n * the resolver, the journal, the exchange) and the rest `documentHost`\n * reports. A pass of reactions that broke has no request of its own: it is\n * reported with one for `https://durable-object/alarm`. The reporter in the\n * Effect context when not given, by default the log.\n */\n readonly diagnostics?:\n | ((diagnostic: Diagnostic, request: Request) => Effect.Effect<void>)\n | 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 (\n ctx: DocumentHostContext,\n env: Env,\n) => {\n fetch(request: Request): Promise<Response>\n alarm(...info: Array<unknown>): Promise<void>\n} => {\n checkRevalidate(config.revalidate, 'defineDocumentHost')\n // The application's own alarm, if its base has one: run after the reactions'.\n const baseAlarm = (Base.prototype as { readonly alarm?: unknown }).alarm\n return class extends Base {\n private readonly host: (request: Request) => Promise<Result.Result<Accepted, Response>>\n private readonly react: () => Promise<void>\n\n constructor(ctx: DocumentHostContext, env: Env) {\n super(ctx, env)\n interface Opened {\n readonly journal: Journal<Operation, Shared, Principal, WrittenOperation>\n readonly server: Option.Option<ServerJournal<unknown, never>>\n }\n let ready: Promise<Opened> | undefined\n const { layer, settle, server } = config\n const alarms = Option.flatMap(Option.fromUndefinedOr(server), () => alarmsOf(ctx.storage))\n if (server !== undefined && Option.isNone(alarms))\n throw new Error('defineDocumentHost: `server` needs the object’s storage alarm')\n // Made now, so one declared for another contract fails here and not at\n // the first upgrade; `serverJournal` checks the rest when it opens.\n const reactions = server === undefined ? [] : server.reactions(env)\n for (const each of reactions)\n if (each.sync !== config.sync)\n throw new Error(\n `defineDocumentHost: reaction ${each.name} was declared for another contract`,\n )\n /** Reports a pass that broke; a reporter that fails itself is not let out of `alarm()`. */\n const report = (stage: 'Alarm', cause: Cause.Cause<unknown>): Promise<void> =>\n Effect.runPromise(\n reportTo(\n config.diagnostics === undefined\n ? undefined\n : diagnostic =>\n config.diagnostics!(diagnostic, new Request('https://durable-object/alarm')),\n hostDefect(stage, cause),\n ),\n ).catch(() => undefined)\n const arm = (after: Duration.Duration): Promise<void> =>\n armAlarm(Option.getOrThrow(alarms), Date.now() + Duration.toMillis(after))\n // The journal and the reactions' registration in one, once per object:\n // registered before any socket is served, so no commit is missed.\n const open = (): Promise<Opened> =>\n (ready ??= config.openJournal(ctx, env).then(async journal => ({\n journal,\n server:\n server === undefined\n ? Option.none()\n : Option.some(\n await Effect.runPromise(\n // The contract's own type is not kept here: `serverJournal`\n // refuses a reaction declared for another at run time.\n serverJournal({\n sync: config.sync,\n journal,\n server: server.principal,\n reactions,\n runsPerPass: server.runsPerPass,\n } as never) as Effect.Effect<ServerJournal<unknown, never>>,\n ),\n ),\n }))).catch((error: unknown) => {\n ready = undefined\n throw error\n })\n /**\n * One pass, then the alarm from its answer. Never rejects: a pass that\n * broke (the journal would not open, a reaction was never registered)\n * is reported and brings the alarm back later.\n */\n const runPass = async (): Promise<void> => {\n if (server === undefined) return\n const exit = await Effect.runPromiseExit(\n Effect.gen(function* () {\n const { server: running } = yield* Effect.promise(open)\n if (Option.isNone(running)) return\n const next = yield* running.value.react\n if (Option.isSome(next)) yield* Effect.promise(() => arm(next.value))\n }),\n )\n if (Exit.isSuccess(exit)) return\n await report('Alarm', exit.cause)\n await arm(ALARM_AFTER_DEFECT).catch(() => undefined)\n }\n // `serverJournal` runs one pass at a time itself.\n const pass = runPass\n this.react = pass\n // What the host knows was committed, so only an exchange that moved it arms the alarm.\n let seen = -1\n const afterExchange = (journal: Journal<Operation, Shared, Principal, WrittenOperation>) =>\n Effect.gen(function* () {\n const at = yield* journal.cursor(JournalDocumentId.make(config.sync.documentId))\n if (at === seen) return\n // Before the reply, so a run cut off by eviction is resumed. One that\n // fails is reported, and `seen` stays, so the next exchange arms again.\n const armed = yield* Effect.promise(() =>\n arm(ALARM_AFTER_COMMIT).then(\n () => true,\n async (error: unknown) => {\n await report('Alarm', Cause.die(error))\n return false\n },\n ),\n )\n if (armed) seen = at\n // Not awaited: the reply does not wait on a provider.\n void pass()\n })\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: () => open().then(opened => opened.journal),\n resolvePrincipal: request => config.resolvePrincipal(request, env),\n layer: layer === undefined ? undefined : () => layer(env),\n revalidate: config.revalidate,\n settle:\n settle === undefined && server === undefined\n ? undefined\n : journal =>\n Effect.gen(function* () {\n // First: a settle that fails still leaves what committed to be reacted to.\n if (server !== undefined) yield* afterExchange(journal)\n if (settle !== undefined) yield* settle(env, journal)\n }),\n opens: config.opens,\n admit: config.admit,\n diagnostics: config.diagnostics,\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 /**\n * The object's alarm: runs the reactions and sets the alarm again from\n * what they answer, then the base class's own `alarm()`, if it has one,\n * with what the runtime passed. The reactions' part never throws, so the\n * runtime's few retries of a throwing alarm are never what a run depends\n * on. The object has one alarm, shared: the base runs on every wake, so\n * it decides itself what is due, and sets its next with `armAlarm`, which\n * only brings the alarm earlier. A subclass that overrides `alarm()` calls\n * `super.alarm()`, or the reactions stop being resumed.\n */\n async alarm(...info: Array<unknown>): Promise<void> {\n await this.react()\n if (typeof baseAlarm === 'function')\n await (baseAlarm as (...info: Array<unknown>) => Promise<void>).apply(this, info)\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 // The replica learns nothing of it; whoever runs the host must.\n const broke = (error: unknown): Promise<Response> => {\n const { diagnostics } = config\n return Effect.runPromise(\n answerHostDefect(\n diagnostics === undefined ? undefined : diagnostic => diagnostics(diagnostic, request),\n 'Upgrade',\n Cause.die(error),\n ),\n )\n }\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 return broke(error)\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 abandon()\n return broke(error)\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,MAAM,qBAAqB,SAAS,QAAQ,CAAC;;AAE7C,MAAM,qBAAqB,SAAS,QAAQ,EAAE;;;;;;;;AAe9C,MAAa,WAAW,OAAO,SAAuB,OAA8B;CAClF,MAAM,UAAU,MAAM,QAAQ,SAAS;CACvC,IAAI,YAAY,QAAQ,WAAW,KAAK,IAAI,KAAK,UAAU,IAAI,MAAM,QAAQ,SAAS,EAAE;AAC1F;AAEA,MAAM,YAAY,YAChB,OAAO,YAAY,YACnB,YAAY,QACZ,OAAQ,QAAkC,aAAa,cACvD,OAAQ,QAAkC,aAAa,aACnD,OAAO,KAAK,OAAuB,IACnC,OAAO,KAAK;;;;;AA+IlB,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,KAAK,IAAI,KAAK,EAAE;AAC1B;;;;;;;AAQA,MAAa,sBACX,MACA,WAOG;CACH,gBAAgB,OAAO,YAAY,oBAAoB;CAEvD,MAAM,YAAa,K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;;;;;;;;;;;EAYA,MAAM,MAAM,GAAG,MAAqC;GAClD,MAAM,KAAK,MAAM;GACjB,IAAI,OAAO,cAAc,YACvB,MAAO,UAAyD,MAAM,MAAM,IAAI;EACpF;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,MAAM,SAAS,UAAsC;IACnD,MAAM,EAAE,gBAAgB;IACxB,OAAO,OAAO,WACZ,iBACE,gBAAgB,KAAA,IAAY,KAAA,KAAY,eAAc,YAAY,YAAY,OAAO,GACrF,WACA,MAAM,IAAI,KAAK,CACjB,CACF;GACF;GAEA,IAAI;GACJ,IAAI;IACF,QAAQ,OAAO,QAAQ,YAAA,CAAa;GACtC,SAAS,OAAO;IACd,OAAO,MAAM,KAAK;GACpB;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;IACR,OAAO,MAAM,KAAK;GACpB;EACF;CACF;AACF"}
package/dist/errors.d.ts CHANGED
@@ -173,10 +173,23 @@ declare const ReplayError_base: Schema.Class<ReplayError, Schema.TaggedStruct<"R
173
173
  readonly cause: Schema.optional<Schema.Unknown>;
174
174
  }>, import("effect/Cause").YieldableError>;
175
175
  /**
176
- * `replay` threw for a submitted Message, so it could never be applied here or
177
- * on any other replica; nothing was written.
176
+ * `replay` threw for a submitted Message, or a law threw over its result, so
177
+ * it could never be applied here or on any other replica; nothing was written.
178
178
  */
179
179
  export declare class ReplayError extends ReplayError_base {}
180
- export type ReplicaError = StorageError | ReplayError | WrongReplicaStorageError | InvalidReplicaHistoryError | InvalidExchangeError | UnsupportedReplicaVersionError | UnsupportedMessageVersionError | InvalidOutboxError | CheckpointRegressionError | CommittedOrderError | ForeignRejectionError | ForeignAcknowledgementError | ReplicaClosedError;
180
+ declare const LawBrokenError_base: Schema.Class<LawBrokenError, Schema.TaggedStruct<"LawBrokenError", {
181
+ /** The law's id, as declared in `laws`. */
182
+ readonly rule: Schema.String;
183
+ readonly message: Schema.String;
184
+ readonly path: Schema.$Array<Schema.String>;
185
+ }>, import("effect/Cause").YieldableError>;
186
+ /**
187
+ * `submit` replayed the Message over the optimistic snapshot, and the result
188
+ * breaks one of the document's laws: nothing was written. A hint, not the
189
+ * verdict: the optimistic snapshot holds pending edits the server may refuse,
190
+ * and the server judges again over the snapshot it commits on.
191
+ */
192
+ export declare class LawBrokenError extends LawBrokenError_base {}
193
+ export type ReplicaError = StorageError | ReplayError | LawBrokenError | WrongReplicaStorageError | InvalidReplicaHistoryError | InvalidExchangeError | UnsupportedReplicaVersionError | UnsupportedMessageVersionError | InvalidOutboxError | CheckpointRegressionError | CommittedOrderError | ForeignRejectionError | ForeignAcknowledgementError | ReplicaClosedError;
181
194
  export {};
182
195
  //# sourceMappingURL=errors.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","names":[],"sources":["../src/errors.ts"],"mappings":";;;;;;qBAGa,qBAAqB;;;;;;qBAMrB,qCAAqC;;;;;;;qBASrC,iCAAiC;;;;;;qBAUjC,mCAAmC;;;;;;qBASnC,6BAA6B;;;;;qBAS7B,2BAA2B;;;;;;;qBAQ3B,kCAAkC;;;;;;;qBAUlC,4BAA4B;;;;;;qBAU5B,8BAA8B;;;;;;;;;;qBAa9B,oCAAoC;;;;;qBASpC,2BAA2B;;;;;;;qBAQ3B,uCAAuC;;;;;;;;;;;;;;;;qBAgBvC,uCAAuC;;;;;;;;;;;;;qBAkBvC,+BAA+B;;;;;;;;;;;qBAgB/B,+BAA+B;;;;;;;;;;qBAa/B,8BAA8B;;;;;;;;qBAY9B,6BAA6B;MAI3B;;;;;;;;;;;qBAUF,4BAA4B;MAI1B;;;;;;;;;;;;;;;;;;;;qBAiBF,+BAA+B;;;;;;;;;qBAc/B,oBAAoB;YAKrB,eACR,eACA,cACA,2BACA,6BACA,uBACA,iCACA,iCACA,qBACA,4BACA,sBACA,wBACA,8BACA"}
1
+ {"version":3,"file":"errors.d.ts","names":[],"sources":["../src/errors.ts"],"mappings":";;;;;;qBAGa,qBAAqB;;;;;;qBAMrB,qCAAqC;;;;;;;qBASrC,iCAAiC;;;;;;qBAUjC,mCAAmC;;;;;;qBASnC,6BAA6B;;;;;qBAS7B,2BAA2B;;;;;;;qBAQ3B,kCAAkC;;;;;;;qBAUlC,4BAA4B;;;;;;qBAU5B,8BAA8B;;;;;;;;;;qBAa9B,oCAAoC;;;;;qBASpC,2BAA2B;;;;;;;qBAQ3B,uCAAuC;;;;;;;;;;;;;;;;qBAgBvC,uCAAuC;;;;;;;;;;;;;qBAkBvC,+BAA+B;;;;;;;;;;;qBAgB/B,+BAA+B;;;;;;;;;;qBAa/B,8BAA8B;;;;;;;;qBAY9B,6BAA6B;MAI3B;;;;;;;;;;;qBAUF,4BAA4B;MAI1B;;;;;;;;;;;;;;;;;;;;qBAiBF,+BAA+B;;;;;;;;;qBAc/B,oBAAoB;;;;;;;;;;;;;qBAWpB,uBAAuB;YAOxB,eACR,eACA,cACA,iBACA,2BACA,6BACA,uBACA,iCACA,iCACA,qBACA,4BACA,sBACA,wBACA,8BACA"}
package/dist/errors.js CHANGED
@@ -149,13 +149,25 @@ var UnreadableHistoryError = class extends Schema.TaggedError()("UnreadableHisto
149
149
  message: Schema.String
150
150
  }) {};
151
151
  /**
152
- * `replay` threw for a submitted Message, so it could never be applied here or
153
- * on any other replica; nothing was written.
152
+ * `replay` threw for a submitted Message, or a law threw over its result, so
153
+ * it could never be applied here or on any other replica; nothing was written.
154
154
  */
155
155
  var ReplayError = class extends Schema.TaggedError()("ReplayError", {
156
156
  message: Schema.String,
157
157
  cause: Schema.optional(Schema.Unknown)
158
158
  }) {};
159
- export { AmbiguousMessageError, CheckpointRegressionError, CommittedOrderError, ForeignAcknowledgementError, ForeignRejectionError, InvalidExchangeError, InvalidOutboxError, InvalidReplicaHistoryError, ReplayError, ReplicaClosedError, ServerKeyReusedError, ServerOnlyMessageError, StaleParkedRunError, StorageError, UnreadableHistoryError, UnreadableMessageError, UnsupportedClockVersionError, UnsupportedMessageVersionError, UnsupportedReplicaVersionError, WrongReplicaStorageError };
159
+ /**
160
+ * `submit` replayed the Message over the optimistic snapshot, and the result
161
+ * breaks one of the document's laws: nothing was written. A hint, not the
162
+ * verdict: the optimistic snapshot holds pending edits the server may refuse,
163
+ * and the server judges again over the snapshot it commits on.
164
+ */
165
+ var LawBrokenError = class extends Schema.TaggedError()("LawBrokenError", {
166
+ /** The law's id, as declared in `laws`. */
167
+ rule: Schema.String,
168
+ message: Schema.String,
169
+ path: Schema.Array(Schema.String)
170
+ }) {};
171
+ export { AmbiguousMessageError, CheckpointRegressionError, CommittedOrderError, ForeignAcknowledgementError, ForeignRejectionError, InvalidExchangeError, InvalidOutboxError, InvalidReplicaHistoryError, LawBrokenError, ReplayError, ReplicaClosedError, ServerKeyReusedError, ServerOnlyMessageError, StaleParkedRunError, StorageError, UnreadableHistoryError, UnreadableMessageError, UnsupportedClockVersionError, UnsupportedMessageVersionError, UnsupportedReplicaVersionError, WrongReplicaStorageError };
160
172
 
161
173
  //# sourceMappingURL=errors.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","names":[],"sources":["../src/errors.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 * An operation was written at a Message version above this build's: a newer\n * build wrote it. Nothing is removed; a build that has the version reads it.\n * The replica refuses to open on one in its outbox, and an exchange fails on\n * one the server committed: this client is older than its server, and reads\n * the document once it runs the new build.\n */\nexport class UnsupportedMessageVersionError extends Schema.TaggedError<UnsupportedMessageVersionError>()(\n 'UnsupportedMessageVersionError',\n {\n opId: Schema.String,\n /** The version the operation was written at. */\n found: Schema.Number,\n /** The newest version this build reads. */\n supported: Schema.Number,\n message: Schema.String,\n },\n) {}\n\n/**\n * An operation written at an older Message version that no step of the\n * history reads: a step's Schema refused it, or its `up` threw. Thrown by\n * Sync's operation codec; a replica moves such a pending operation to\n * `refused`, and `journalExchange` rejects one as `Unreadable`.\n */\nexport class UnreadableMessageError extends Schema.TaggedError<UnreadableMessageError>()(\n 'UnreadableMessageError',\n {\n opId: Schema.String,\n version: Schema.Number,\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown),\n },\n) {}\n\n/**\n * A sent entry carries a Message only the server appends (`serverOnly`),\n * judged after upcasting. Thrown by every reader of an entry someone sent\n * (`codec.writtenFrom`, `normalizeOperation`, `operationFrom`);\n * `journalExchange` rejects it as `Forbidden`. History reads it.\n */\nexport class ServerOnlyMessageError extends Schema.TaggedError<ServerOnlyMessageError>()(\n 'ServerOnlyMessageError',\n {\n opId: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/**\n * A Message both `durable` and `serverOnly` accept: `Sync.define`'s two\n * predicates overlap, which cannot be told when they are given. It is refused\n * wherever it is read, never treated as either.\n */\nexport class AmbiguousMessageError extends Schema.TaggedError<AmbiguousMessageError>()(\n 'AmbiguousMessageError',\n {\n opId: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/**\n * `appendAsServer` was given a key already used for another Message: the\n * first fact stands, and nothing was appended.\n */\nexport class ServerKeyReusedError extends Schema.TaggedError<ServerKeyReusedError>()(\n 'SyncServerKeyReusedError',\n { key: Schema.String },\n) {\n override get message(): string {\n return `The server key \"${this.key}\" was already used for another Message`\n }\n}\n\n/**\n * `retry` was given a run parked in a history since reset: its sequence names\n * whatever the new history committed there. Dismiss it; if its operation is\n * sent again, it commits and is reacted to in the new history.\n */\nexport class StaleParkedRunError extends Schema.TaggedError<StaleParkedRunError>()(\n 'SyncStaleParkedRunError',\n { reaction: Schema.String, opId: Schema.String },\n) {\n override get message(): string {\n return `The run of ${this.reaction} at ${this.opId} was parked before the document was reset`\n }\n}\n\n/**\n * A committed operation of the document will not read: written at a version\n * this server's history lacks, or at one no step reads. The journal reads a\n * stored row only when it needs it, so this fails what needs that row: an\n * exchange from a replica whose cursor is before it (after appending what\n * that replica sent, which commits, and is acknowledged on a retry once a\n * build reads the row), a retransmission of its id, and, while the row is\n * after the stored snapshot, every append and load of the document. A\n * replica past the row is served. Other documents are not affected.\n * Server-side only: its fields are for the server's logs, and its message,\n * which a socket sends, names neither.\n */\nexport class UnreadableHistoryError extends Schema.TaggedError<UnreadableHistoryError>()(\n 'UnreadableHistoryError',\n {\n documentId: Schema.String,\n opId: Schema.String,\n version: 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 | UnsupportedMessageVersionError\n | InvalidOutboxError\n | CheckpointRegressionError\n | CommittedOrderError\n | ForeignRejectionError\n | ForeignAcknowledgementError\n | ReplicaClosedError\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,CAAC,CAAC;;AAGH,IAAa,qBAAb,cAAwC,OAAO,YAAgC,CAAC,CAC9E,sBACA,EACE,SAAS,OAAO,OAClB,CACF,CAAC,CAAC,CAAC;;AAGH,IAAa,4BAAb,cAA+C,OAAO,YAAuC,CAAC,CAC5F,6BACA;CACE,QAAQ,OAAO;CACf,kBAAkB,OAAO;CACzB,SAAS,OAAO;AAClB,CACF,CAAC,C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MAAM,OAAO;CACb,SAAS,OAAO;AAClB,CACF,CAAC,CAAC,CAAC;;;;;AAMH,IAAa,uBAAb,cAA0C,OAAO,YAAkC,CAAC,CAClF,4BACA,EAAE,KAAK,OAAO,OAAO,CACvB,CAAC,CAAC;CACA,IAAa,UAAkB;EAC7B,OAAO,mBAAmB,KAAK,IAAI;CACrC;AACF;;;;;;AAOA,IAAa,sBAAb,cAAyC,OAAO,YAAiC,CAAC,CAChF,2BACA;CAAE,UAAU,OAAO;CAAQ,MAAM,OAAO;AAAO,CACjD,CAAC,CAAC;CACA,IAAa,UAAkB;EAC7B,OAAO,cAAc,KAAK,SAAS,MAAM,KAAK,KAAK;CACrD;AACF;;;;;;;;;;;;;AAcA,IAAa,yBAAb,cAA4C,OAAO,YAAoC,CAAC,CACtF,0BACA;CACE,YAAY,OAAO;CACnB,MAAM,OAAO;CACb,SAAS,OAAO;CAChB,SAAS,OAAO;AAClB,CACF,CAAC,CAAC,CAAC;;;;;AAMH,IAAa,cAAb,cAAiC,OAAO,YAAyB,CAAC,CAAC,eAAe;CAChF,SAAS,OAAO;CAChB,OAAO,OAAO,SAAS,OAAO,OAAO;AACvC,CAAC,CAAC,CAAC,CAAC"}
1
+ {"version":3,"file":"errors.js","names":[],"sources":["../src/errors.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 * An operation was written at a Message version above this build's: a newer\n * build wrote it. Nothing is removed; a build that has the version reads it.\n * The replica refuses to open on one in its outbox, and an exchange fails on\n * one the server committed: this client is older than its server, and reads\n * the document once it runs the new build.\n */\nexport class UnsupportedMessageVersionError extends Schema.TaggedError<UnsupportedMessageVersionError>()(\n 'UnsupportedMessageVersionError',\n {\n opId: Schema.String,\n /** The version the operation was written at. */\n found: Schema.Number,\n /** The newest version this build reads. */\n supported: Schema.Number,\n message: Schema.String,\n },\n) {}\n\n/**\n * An operation written at an older Message version that no step of the\n * history reads: a step's Schema refused it, or its `up` threw. Thrown by\n * Sync's operation codec; a replica moves such a pending operation to\n * `refused`, and `journalExchange` rejects one as `Unreadable`.\n */\nexport class UnreadableMessageError extends Schema.TaggedError<UnreadableMessageError>()(\n 'UnreadableMessageError',\n {\n opId: Schema.String,\n version: Schema.Number,\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown),\n },\n) {}\n\n/**\n * A sent entry carries a Message only the server appends (`serverOnly`),\n * judged after upcasting. Thrown by every reader of an entry someone sent\n * (`codec.writtenFrom`, `normalizeOperation`, `operationFrom`);\n * `journalExchange` rejects it as `Forbidden`. History reads it.\n */\nexport class ServerOnlyMessageError extends Schema.TaggedError<ServerOnlyMessageError>()(\n 'ServerOnlyMessageError',\n {\n opId: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/**\n * A Message both `durable` and `serverOnly` accept: `Sync.define`'s two\n * predicates overlap, which cannot be told when they are given. It is refused\n * wherever it is read, never treated as either.\n */\nexport class AmbiguousMessageError extends Schema.TaggedError<AmbiguousMessageError>()(\n 'AmbiguousMessageError',\n {\n opId: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/**\n * `appendAsServer` was given a key already used for another Message: the\n * first fact stands, and nothing was appended.\n */\nexport class ServerKeyReusedError extends Schema.TaggedError<ServerKeyReusedError>()(\n 'SyncServerKeyReusedError',\n { key: Schema.String },\n) {\n override get message(): string {\n return `The server key \"${this.key}\" was already used for another Message`\n }\n}\n\n/**\n * `retry` was given a run parked in a history since reset: its sequence names\n * whatever the new history committed there. Dismiss it; if its operation is\n * sent again, it commits and is reacted to in the new history.\n */\nexport class StaleParkedRunError extends Schema.TaggedError<StaleParkedRunError>()(\n 'SyncStaleParkedRunError',\n { reaction: Schema.String, opId: Schema.String },\n) {\n override get message(): string {\n return `The run of ${this.reaction} at ${this.opId} was parked before the document was reset`\n }\n}\n\n/**\n * A committed operation of the document will not read: written at a version\n * this server's history lacks, or at one no step reads. The journal reads a\n * stored row only when it needs it, so this fails what needs that row: an\n * exchange from a replica whose cursor is before it (after appending what\n * that replica sent, which commits, and is acknowledged on a retry once a\n * build reads the row), a retransmission of its id, and, while the row is\n * after the stored snapshot, every append and load of the document. A\n * replica past the row is served. Other documents are not affected.\n * Server-side only: its fields are for the server's logs, and its message,\n * which a socket sends, names neither.\n */\nexport class UnreadableHistoryError extends Schema.TaggedError<UnreadableHistoryError>()(\n 'UnreadableHistoryError',\n {\n documentId: Schema.String,\n opId: Schema.String,\n version: Schema.Number,\n message: Schema.String,\n },\n) {}\n\n/**\n * `replay` threw for a submitted Message, or a law threw over its result, so\n * it could never be applied here or 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\n/**\n * `submit` replayed the Message over the optimistic snapshot, and the result\n * breaks one of the document's laws: nothing was written. A hint, not the\n * verdict: the optimistic snapshot holds pending edits the server may refuse,\n * and the server judges again over the snapshot it commits on.\n */\nexport class LawBrokenError extends Schema.TaggedError<LawBrokenError>()('LawBrokenError', {\n /** The law's id, as declared in `laws`. */\n rule: Schema.String,\n message: Schema.String,\n path: Schema.Array(Schema.String),\n}) {}\n\nexport type ReplicaError =\n | StorageError\n | ReplayError\n | LawBrokenError\n | WrongReplicaStorageError\n | InvalidReplicaHistoryError\n | InvalidExchangeError\n | UnsupportedReplicaVersionError\n | UnsupportedMessageVersionError\n | InvalidOutboxError\n | CheckpointRegressionError\n | CommittedOrderError\n | ForeignRejectionError\n | ForeignAcknowledgementError\n | ReplicaClosedError\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,CAAC,CAAC;;AAGH,IAAa,qBAAb,cAAwC,OAAO,YAAgC,CAAC,CAC9E,sBACA,EACE,SAAS,OAAO,OAClB,CACF,CAAC,CAAC,CAAC;;AAGH,IAAa,4BAAb,cAA+C,OAAO,YAAuC,CAAC,CAC5F,6BACA;CACE,QAAQ,OAAO;CACf,kBAAkB,OAAO;CACzB,SAAS,OAAO;AAClB,CACF,CAAC,CAAC,CAAC;;AAGH,IAAa,sBAAb,cAAyC,OAAO,YAAiC,CA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AC;;;;;AAMH,IAAa,uBAAb,cAA0C,OAAO,YAAkC,CAAC,CAClF,4BACA,EAAE,KAAK,OAAO,OAAO,CACvB,CAAC,CAAC;CACA,IAAa,UAAkB;EAC7B,OAAO,mBAAmB,KAAK,IAAI;CACrC;AACF;;;;;;AAOA,IAAa,sBAAb,cAAyC,OAAO,YAAiC,CAAC,CAChF,2BACA;CAAE,UAAU,OAAO;CAAQ,MAAM,OAAO;AAAO,CACjD,CAAC,CAAC;CACA,IAAa,UAAkB;EAC7B,OAAO,cAAc,KAAK,SAAS,MAAM,KAAK,KAAK;CACrD;AACF;;;;;;;;;;;;;AAcA,IAAa,yBAAb,cAA4C,OAAO,YAAoC,CAAC,CACtF,0BACA;CACE,YAAY,OAAO;CACnB,MAAM,OAAO;CACb,SAAS,OAAO;CAChB,SAAS,OAAO;AAClB,CACF,CAAC,CAAC,CAAC;;;;;AAMH,IAAa,cAAb,cAAiC,OAAO,YAAyB,CAAC,CAAC,eAAe;CAChF,SAAS,OAAO;CAChB,OAAO,OAAO,SAAS,OAAO,OAAO;AACvC,CAAC,CAAC,CAAC,CAAC;;;;;;;AAQJ,IAAa,iBAAb,cAAoC,OAAO,YAA4B,CAAC,CAAC,kBAAkB;;CAEzF,MAAM,OAAO;CACb,SAAS,OAAO;CAChB,MAAM,OAAO,MAAM,OAAO,MAAM;AAClC,CAAC,CAAC,CAAC,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,15 +1,15 @@
1
- import { ExchangeFailed, HistoryRebuilt, HostDefect, HostStage, ListenerFailed, ListenerSite, ReactionFailed, ReactionParked, ReactionSkipped, ServerOnlySubmitted, SyncDiagnostic, UnknownRefusal } from "./diagnostics.js";
2
- import { ExchangeFrame, ExchangeReply, NotifyFrame, SocketLike, SocketOptions, Transport, TransportError, TransportShape, TransportSocket, layerFromPromise, layerFromPromise as layerFromPromise$1, layerLoopback, layerLoopback as layerLoopback$1, layerSocket, layerSocket as layerSocket$1, nativeSocket, nativeSocket as nativeSocket$1, portSocket, portSocket as portSocket$1, serveSocket, serveSocket as serveSocket$1, toPromise, toPromise as toPromise$1, workerSocket, workerSocket as workerSocket$1 } from "./transport.js";
1
+ import { ExchangeDefect, ExchangeFailed, HistoryRebuilt, HostDefect, HostStage, ListenerFailed, ListenerSite, ReactionFailed, ReactionParked, ReactionSkipped, ServerOnlySubmitted, SyncDiagnostic, UnknownRefusal } from "./diagnostics.js";
2
+ import { ExchangeFrame, ExchangeRefused, ExchangeReply, NotifyFrame, SocketLike, SocketOptions, Transport, TransportError, TransportShape, TransportSocket, layerFromPromise, layerFromPromise as layerFromPromise$1, layerLoopback, layerLoopback as layerLoopback$1, layerSocket, layerSocket as layerSocket$1, nativeSocket, nativeSocket as nativeSocket$1, portSocket, portSocket as portSocket$1, serveSocket, serveSocket as serveSocket$1, toPromise, toPromise as toPromise$1, workerSocket, workerSocket as workerSocket$1 } from "./transport.js";
3
3
  import { OutboxEntry, Storage, TabStorageOptions, indexedDb, tabStorage } from "./indexedDb.js";
4
4
  import { LwwClock, LwwClockState, lwwRegister, lwwRegister as lwwRegister$1, openLwwClock } from "./lww.js";
5
- import { ApplicationSync, AuthorizeDecision, AuthorizePolicy, AuthorizeRequest, DefinedSync, FragmentMessages, HistoryOption, MakeOptions, MsgOf, PolicyJournalContract, ServerMsgOf, StampPolicy, SyncFragment, forApplication, forApplication as forApplication$1 } from "./make.js";
5
+ import { ApplicationSync, AuthorizeDecision, AuthorizePolicy, AuthorizeRequest, DefinedSync, FragmentMessages, HistoryOption, Law, LawsOption, MakeOptions, MsgOf, PolicyJournalContract, ServerMsgOf, StampPolicy, SyncFragment, forApplication, forApplication as forApplication$1 } from "./make.js";
6
6
  import { Migrations, migrations, migrations as migrations$1 } from "./migrations.js";
7
7
  import { CommittedView, MountOptions, MountUrl, Mounted, Reinstall, fact, fact as fact$1, mount, mount as mount$1 } from "./mount.js";
8
8
  import { Presence, PresenceChannel, PresenceHub, PresenceOptions, PresencePeer, PresenceUpdate, createPresence, createPresenceHub, createPresenceHub as createPresenceHub$1, loopbackPresenceChannel, servePresence, servePresence as servePresence$1, socketPresenceChannel, socketPresenceChannel as socketPresenceChannel$1 } from "./presence.js";
9
- import { Checkpoint, CommitStamp, CommittedOperation, Exchange, JournalContract, MessageHistory, OpenReplicaOptions, Operation, Rejection, Replica, ReplicaSnapshot, ReplicaState, ReplicaStatus, Sync as Sync$1, SyncDefinition, SyncDefinitionOptions, TransportClient, WrittenOperation, defineSync, defineSync as defineSync$1, syncMetrics } from "./sync.js";
10
- import { SyncRefusal } from "./refusal.js";
9
+ import { SyncRefusal, isInvalidBy, isInvalidBy as isInvalidBy$1 } from "./refusal.js";
10
+ import { Checkpoint, CommitStamp, CommittedOperation, DeclaredLaw, Exchange, JournalContract, MessageHistory, OpenReplicaOptions, Operation, Rejection, Replica, ReplicaSnapshot, ReplicaState, ReplicaStatus, Sync as Sync$1, SyncDefinition, SyncDefinitionOptions, TransportClient, WrittenOperation, defineSync, defineSync as defineSync$1, syncMetrics } from "./sync.js";
11
11
  import { DocumentId, LocalSequence, OpId, ReplicaId, Sequence, documentId, localSequence, opId, replicaId, sequence } from "./ids.js";
12
- import { AmbiguousMessageError, CheckpointRegressionError, CommittedOrderError, ForeignAcknowledgementError, ForeignRejectionError, InvalidExchangeError, InvalidOutboxError, InvalidReplicaHistoryError, ReplayError, ReplicaClosedError, ReplicaError, ServerKeyReusedError, ServerOnlyMessageError, StaleParkedRunError, StorageError, UnreadableHistoryError, UnreadableMessageError, UnsupportedClockVersionError, UnsupportedMessageVersionError, UnsupportedReplicaVersionError, WrongReplicaStorageError } from "./errors.js";
12
+ import { AmbiguousMessageError, CheckpointRegressionError, CommittedOrderError, ForeignAcknowledgementError, ForeignRejectionError, InvalidExchangeError, InvalidOutboxError, InvalidReplicaHistoryError, LawBrokenError, ReplayError, ReplicaClosedError, ReplicaError, ServerKeyReusedError, ServerOnlyMessageError, StaleParkedRunError, StorageError, UnreadableHistoryError, UnreadableMessageError, UnsupportedClockVersionError, UnsupportedMessageVersionError, UnsupportedReplicaVersionError, WrongReplicaStorageError } from "./errors.js";
13
13
  /**
14
14
  * The contract `Sync.define` and `Sync.forApplication(App).make` produce: the
15
15
  * wire codecs, the server journal's contract, and `openReplica`.
@@ -28,6 +28,8 @@ export declare const Sync: {
28
28
  migrations: typeof migrations$1;
29
29
  /** Runs a Foldkit application over an open replica with one reducer. */
30
30
  mount: typeof mount$1;
31
+ /** Whether a refusal is the server's answer that a declared law broke: `Sync.isInvalidBy(refusal, contract.laws.capped)`. */
32
+ isInvalidBy: typeof isInvalidBy$1;
31
33
  /** A Command whose Message the mount applies within the transition that returned it. */
32
34
  fact: typeof fact$1;
33
35
  /** Counters and a histogram an application can scrape. */
@@ -106,5 +108,5 @@ export declare const Sync: {
106
108
  }, import("./errors.js").StorageError | import("./errors.js").UnsupportedClockVersionError, never>;
107
109
  };
108
110
  };
109
- export { AmbiguousMessageError, type ApplicationSync, type AuthorizeDecision, type AuthorizePolicy, type AuthorizeRequest, type Checkpoint, CheckpointRegressionError, type CommitStamp, type CommittedOperation, CommittedOrderError, type CommittedView, type DefinedSync, DocumentId, type Exchange, type ExchangeFailed, type ExchangeFrame, type ExchangeReply, ForeignAcknowledgementError, ForeignRejectionError, type FragmentMessages, type HistoryOption, type HistoryRebuilt, type HostDefect, type HostStage, InvalidExchangeError, InvalidOutboxError, InvalidReplicaHistoryError, type JournalContract, type ListenerFailed, type ListenerSite, LocalSequence, type LwwClock, type LwwClockState, type MakeOptions, type MessageHistory, type Migrations, type MountOptions, type MountUrl, type Mounted, type MsgOf, type NotifyFrame, OpId, type OpenReplicaOptions, type Operation, type OutboxEntry, type PolicyJournalContract, type Presence, type PresenceChannel, type PresenceHub, type PresenceOptions, type PresencePeer, type PresenceUpdate, type ReactionFailed, type ReactionParked, type ReactionSkipped, type Reinstall, type Rejection, ReplayError, type Replica, ReplicaClosedError, type ReplicaError, ReplicaId, type ReplicaSnapshot, type ReplicaState, type ReplicaStatus, Sequence, ServerKeyReusedError, type ServerMsgOf, ServerOnlyMessageError, type ServerOnlySubmitted, type SocketLike, type SocketOptions, StaleParkedRunError, type StampPolicy, type Storage, StorageError, type SyncDefinition, type SyncDefinitionOptions, type SyncDiagnostic, type SyncFragment, SyncRefusal, type TabStorageOptions, Transport, type TransportClient, TransportError, type TransportShape, TransportSocket, type UnknownRefusal, UnreadableHistoryError, UnreadableMessageError, UnsupportedClockVersionError, UnsupportedMessageVersionError, UnsupportedReplicaVersionError, type WrittenOperation, WrongReplicaStorageError, createPresence, createPresenceHub, defineSync, documentId, fact, forApplication, indexedDb, layerFromPromise, layerLoopback, layerSocket, localSequence, loopbackPresenceChannel, lwwRegister, migrations, mount, nativeSocket, opId, openLwwClock, portSocket, replicaId, sequence, servePresence, serveSocket, socketPresenceChannel, syncMetrics, tabStorage, toPromise, workerSocket };
111
+ export { AmbiguousMessageError, type ApplicationSync, type AuthorizeDecision, type AuthorizePolicy, type AuthorizeRequest, type Checkpoint, CheckpointRegressionError, type CommitStamp, type CommittedOperation, CommittedOrderError, type CommittedView, type DeclaredLaw, type DefinedSync, DocumentId, type Exchange, type ExchangeDefect, type ExchangeFailed, type ExchangeFrame, ExchangeRefused, type ExchangeReply, ForeignAcknowledgementError, ForeignRejectionError, type FragmentMessages, type HistoryOption, type HistoryRebuilt, type HostDefect, type HostStage, InvalidExchangeError, InvalidOutboxError, InvalidReplicaHistoryError, type JournalContract, type Law, LawBrokenError, type LawsOption, type ListenerFailed, type ListenerSite, LocalSequence, type LwwClock, type LwwClockState, type MakeOptions, type MessageHistory, type Migrations, type MountOptions, type MountUrl, type Mounted, type MsgOf, type NotifyFrame, OpId, type OpenReplicaOptions, type Operation, type OutboxEntry, type PolicyJournalContract, type Presence, type PresenceChannel, type PresenceHub, type PresenceOptions, type PresencePeer, type PresenceUpdate, type ReactionFailed, type ReactionParked, type ReactionSkipped, type Reinstall, type Rejection, ReplayError, type Replica, ReplicaClosedError, type ReplicaError, ReplicaId, type ReplicaSnapshot, type ReplicaState, type ReplicaStatus, Sequence, ServerKeyReusedError, type ServerMsgOf, ServerOnlyMessageError, type ServerOnlySubmitted, type SocketLike, type SocketOptions, StaleParkedRunError, type StampPolicy, type Storage, StorageError, type SyncDefinition, type SyncDefinitionOptions, type SyncDiagnostic, type SyncFragment, SyncRefusal, type TabStorageOptions, Transport, type TransportClient, TransportError, type TransportShape, TransportSocket, type UnknownRefusal, UnreadableHistoryError, UnreadableMessageError, UnsupportedClockVersionError, UnsupportedMessageVersionError, UnsupportedReplicaVersionError, type WrittenOperation, WrongReplicaStorageError, createPresence, createPresenceHub, defineSync, documentId, fact, forApplication, indexedDb, isInvalidBy, layerFromPromise, layerLoopback, layerSocket, localSequence, loopbackPresenceChannel, lwwRegister, migrations, mount, nativeSocket, opId, openLwwClock, portSocket, replicaId, sequence, servePresence, serveSocket, socketPresenceChannel, syncMetrics, tabStorage, toPromise, workerSocket };
110
112
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":["SyncContract","forApplication","defineSync","migrations","mount","fact","layerSocket","layerLoopback","layerFromPromise","toPromise","serveSocket","workerSocket","nativeSocket","portSocket","createPresenceHub","servePresence","socketPresenceChannel","lwwRegister"],"sources":["../src/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;YA2CY,KAAK,SAAS,QAAQ,UAAU,WAAWA,OAAa,SAAS,QAAQ;;qBAGxE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAwCT,OAAI,QAAA,iCAAA,gBAAA,oCAAA;;;;;;;;;;;;;;;;;;IAEJ,YAAGc;;IAEH,cAAKC;IACL,sBAAaC;IACb,kBAAe,qCAAA;;;;;;;IAKf,iBAAQC;;IAER,YAAS"}
1
+ {"version":3,"file":"index.d.ts","names":["SyncContract","forApplication","defineSync","migrations","mount","isInvalidBy","fact","layerSocket","layerLoopback","layerFromPromise","toPromise","serveSocket","workerSocket","nativeSocket","portSocket","createPresenceHub","servePresence","socketPresenceChannel","lwwRegister"],"sources":["../src/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;YA4CY,KAAK,SAAS,QAAQ,UAAU,WAAWA,OAAa,SAAS,QAAQ;;qBAGxE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA0CT,OAAI,QAAA,iCAAA,gBAAA,oCAAA;;;;;;;;;;;;;;;;;;IAEJ,YAAGe;;IAEH,cAAKC;IACL,sBAAaC;IACb,kBAAe,qCAAA;;;;;;;IAKf,iBAAQC;;IAER,YAAS"}
package/dist/index.js CHANGED
@@ -1,14 +1,14 @@
1
- import { Transport, TransportError, TransportSocket, layerFromPromise, layerFromPromise as layerFromPromise$1, layerLoopback, layerLoopback as layerLoopback$1, layerSocket, layerSocket as layerSocket$1, nativeSocket, nativeSocket as nativeSocket$1, portSocket, portSocket as portSocket$1, serveSocket, serveSocket as serveSocket$1, toPromise, toPromise as toPromise$1, workerSocket, workerSocket as workerSocket$1 } from "./transport.js";
1
+ import { ExchangeRefused, Transport, TransportError, TransportSocket, layerFromPromise, layerFromPromise as layerFromPromise$1, layerLoopback, layerLoopback as layerLoopback$1, layerSocket, layerSocket as layerSocket$1, nativeSocket, nativeSocket as nativeSocket$1, portSocket, portSocket as portSocket$1, serveSocket, serveSocket as serveSocket$1, toPromise, toPromise as toPromise$1, workerSocket, workerSocket as workerSocket$1 } from "./transport.js";
2
2
  import { indexedDb, indexedDb as indexedDb$1, tabStorage, tabStorage as tabStorage$1 } from "./indexedDb.js";
3
3
  import { lwwRegister, lwwRegister as lwwRegister$1, openLwwClock, openLwwClock as openLwwClock$1 } from "./lww.js";
4
4
  import { forApplication, forApplication as forApplication$1 } from "./make.js";
5
5
  import { migrations, migrations as migrations$1 } from "./migrations.js";
6
6
  import { fact, fact as fact$1, mount, mount as mount$1 } from "./mount.js";
7
7
  import { createPresence, createPresence as createPresence$1, createPresenceHub, createPresenceHub as createPresenceHub$1, loopbackPresenceChannel, loopbackPresenceChannel as loopbackPresenceChannel$1, servePresence, servePresence as servePresence$1, socketPresenceChannel, socketPresenceChannel as socketPresenceChannel$1 } from "./presence.js";
8
+ import { SyncRefusal, isInvalidBy, isInvalidBy as isInvalidBy$1 } from "./refusal.js";
8
9
  import { defineSync, defineSync as defineSync$1, syncMetrics, syncMetrics as syncMetrics$1 } from "./sync.js";
9
- import { SyncRefusal } from "./refusal.js";
10
10
  import { DocumentId, LocalSequence, OpId, ReplicaId, Sequence, documentId, localSequence, opId, replicaId, sequence } from "./ids.js";
11
- import { AmbiguousMessageError, CheckpointRegressionError, CommittedOrderError, ForeignAcknowledgementError, ForeignRejectionError, InvalidExchangeError, InvalidOutboxError, InvalidReplicaHistoryError, ReplayError, ReplicaClosedError, ServerKeyReusedError, ServerOnlyMessageError, StaleParkedRunError, StorageError, UnreadableHistoryError, UnreadableMessageError, UnsupportedClockVersionError, UnsupportedMessageVersionError, UnsupportedReplicaVersionError, WrongReplicaStorageError } from "./errors.js";
11
+ import { AmbiguousMessageError, CheckpointRegressionError, CommittedOrderError, ForeignAcknowledgementError, ForeignRejectionError, InvalidExchangeError, InvalidOutboxError, InvalidReplicaHistoryError, LawBrokenError, ReplayError, ReplicaClosedError, ServerKeyReusedError, ServerOnlyMessageError, StaleParkedRunError, StorageError, UnreadableHistoryError, UnreadableMessageError, UnsupportedClockVersionError, UnsupportedMessageVersionError, UnsupportedReplicaVersionError, WrongReplicaStorageError } from "./errors.js";
12
12
  // src/index.ts
13
13
  /**
14
14
  * `foldkit-sync` — a local-first replica of a shared Foldkit projection.
@@ -32,6 +32,8 @@ const Sync = {
32
32
  migrations: migrations$1,
33
33
  /** Runs a Foldkit application over an open replica with one reducer. */
34
34
  mount: mount$1,
35
+ /** Whether a refusal is the server's answer that a declared law broke: `Sync.isInvalidBy(refusal, contract.laws.capped)`. */
36
+ isInvalidBy: isInvalidBy$1,
35
37
  /** A Command whose Message the mount applies within the transition that returned it. */
36
38
  fact: fact$1,
37
39
  /** Counters and a histogram an application can scrape. */
@@ -76,6 +78,6 @@ const Sync = {
76
78
  openClock: openLwwClock$1
77
79
  }
78
80
  };
79
- export { AmbiguousMessageError, CheckpointRegressionError, CommittedOrderError, DocumentId, ForeignAcknowledgementError, ForeignRejectionError, InvalidExchangeError, InvalidOutboxError, InvalidReplicaHistoryError, LocalSequence, OpId, ReplayError, ReplicaClosedError, ReplicaId, Sequence, ServerKeyReusedError, ServerOnlyMessageError, StaleParkedRunError, StorageError, Sync, SyncRefusal, Transport, TransportError, TransportSocket, UnreadableHistoryError, UnreadableMessageError, UnsupportedClockVersionError, UnsupportedMessageVersionError, UnsupportedReplicaVersionError, WrongReplicaStorageError, createPresence, createPresenceHub, defineSync, documentId, fact, forApplication, indexedDb, layerFromPromise, layerLoopback, layerSocket, localSequence, loopbackPresenceChannel, lwwRegister, migrations, mount, nativeSocket, opId, openLwwClock, portSocket, replicaId, sequence, servePresence, serveSocket, socketPresenceChannel, syncMetrics, tabStorage, toPromise, workerSocket };
81
+ export { AmbiguousMessageError, CheckpointRegressionError, CommittedOrderError, DocumentId, ExchangeRefused, ForeignAcknowledgementError, ForeignRejectionError, InvalidExchangeError, InvalidOutboxError, InvalidReplicaHistoryError, LawBrokenError, LocalSequence, OpId, ReplayError, ReplicaClosedError, ReplicaId, Sequence, ServerKeyReusedError, ServerOnlyMessageError, StaleParkedRunError, StorageError, Sync, SyncRefusal, Transport, TransportError, TransportSocket, UnreadableHistoryError, UnreadableMessageError, UnsupportedClockVersionError, UnsupportedMessageVersionError, UnsupportedReplicaVersionError, WrongReplicaStorageError, createPresence, createPresenceHub, defineSync, documentId, fact, forApplication, indexedDb, isInvalidBy, layerFromPromise, layerLoopback, layerSocket, localSequence, loopbackPresenceChannel, lwwRegister, migrations, mount, nativeSocket, opId, openLwwClock, portSocket, replicaId, sequence, servePresence, serveSocket, socketPresenceChannel, syncMetrics, tabStorage, toPromise, workerSocket };
80
82
 
81
83
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["defineSync","syncMetrics","layerSocket","layerLoopback","layerFromPromise","serveSocket","createPresence","createPresenceHub","servePresence","socketPresenceChannel","loopbackPresenceChannel","lwwRegister","openLwwClock"],"sources":["../src/index.ts"],"sourcesContent":["/**\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, tabStorage } from './indexedDb.js'\nimport { lwwRegister, openLwwClock } from './lww.js'\nimport { forApplication } from './make.js'\nimport { migrations } from './migrations.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, Durable = Message> = SyncContract<Message, Shared, Durable>\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 /** Starts a document's Message history: `Sync.migrations(V1).next(V2, up)`. */\n migrations,\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 storage adapter: one IndexedDB database per replica, named by the caller. */\n indexedDb,\n /** This tab's IndexedDB store, kept across reloads: what a browser opens a replica on. */\n tabStorage,\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 type {\n ExchangeFailed,\n HistoryRebuilt,\n HostDefect,\n HostStage,\n ListenerFailed,\n ListenerSite,\n ReactionFailed,\n ReactionParked,\n ReactionSkipped,\n ServerOnlySubmitted,\n SyncDiagnostic,\n UnknownRefusal,\n} from './diagnostics.js'\nexport { SyncRefusal } from './refusal.js'\nexport {\n indexedDb,\n tabStorage,\n type OutboxEntry,\n type Storage,\n type TabStorageOptions,\n} 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 HistoryOption,\n type MakeOptions,\n type MsgOf,\n type PolicyJournalContract,\n type ServerMsgOf,\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 AmbiguousMessageError,\n CheckpointRegressionError,\n CommittedOrderError,\n ForeignAcknowledgementError,\n ForeignRejectionError,\n InvalidExchangeError,\n InvalidOutboxError,\n InvalidReplicaHistoryError,\n ReplayError,\n ReplicaClosedError,\n ServerKeyReusedError,\n ServerOnlyMessageError,\n StaleParkedRunError,\n StorageError,\n UnreadableHistoryError,\n UnreadableMessageError,\n UnsupportedClockVersionError,\n UnsupportedMessageVersionError,\n UnsupportedReplicaVersionError,\n WrongReplicaStorageError,\n type ReplicaError,\n} from './errors.js'\nexport { migrations, type Migrations } from './migrations.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 TransportSocket,\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 MessageHistory,\n type OpenReplicaOptions,\n type Operation,\n type Rejection,\n type Replica,\n type ReplicaSnapshot,\n type ReplicaState,\n type ReplicaStatus,\n type SyncDefinition,\n type SyncDefinitionOptions,\n type TransportClient,\n type WrittenOperation,\n} from './sync.js'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAa,OAAO;;CAElB,gBAAA;;CAEA,QAAQA;;CAER,YAAA;;CAEA,OAAA;;CAEA,MAAA;;CAEA,SAASC;;CAET,WAAA;;CAEA,YAAA;;CAGA,WAAW;;EAET,QAAQC;;EAER,UAAUC;;EAEV,aAAaC;;EAEb,WAAA;;EAEA,OAAOC;;EAEP,cAAA;;EAEA,cAAA;;EAEA,YAAA;CACF;;CAGA,UAAU;EACR,MAAMC;;EAEN,KAAKC;;EAEL,OAAOC;EACP,eAAeC;EACf,iBAAiBC;CACnB;;CAGA,KAAK;EACH,UAAUC;;EAEV,WAAWC;CACb;AACF"}
1
+ {"version":3,"file":"index.js","names":["defineSync","syncMetrics","layerSocket","layerLoopback","layerFromPromise","serveSocket","createPresence","createPresenceHub","servePresence","socketPresenceChannel","loopbackPresenceChannel","lwwRegister","openLwwClock"],"sources":["../src/index.ts"],"sourcesContent":["/**\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, tabStorage } from './indexedDb.js'\nimport { lwwRegister, openLwwClock } from './lww.js'\nimport { forApplication } from './make.js'\nimport { migrations } from './migrations.js'\nimport { fact, mount } from './mount.js'\nimport {\n createPresence,\n createPresenceHub,\n loopbackPresenceChannel,\n servePresence,\n socketPresenceChannel,\n} from './presence.js'\nimport { isInvalidBy } from './refusal.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, Durable = Message> = SyncContract<Message, Shared, Durable>\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 /** Starts a document's Message history: `Sync.migrations(V1).next(V2, up)`. */\n migrations,\n /** Runs a Foldkit application over an open replica with one reducer. */\n mount,\n /** Whether a refusal is the server's answer that a declared law broke: `Sync.isInvalidBy(refusal, contract.laws.capped)`. */\n isInvalidBy,\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 storage adapter: one IndexedDB database per replica, named by the caller. */\n indexedDb,\n /** This tab's IndexedDB store, kept across reloads: what a browser opens a replica on. */\n tabStorage,\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 type {\n ExchangeDefect,\n ExchangeFailed,\n HistoryRebuilt,\n HostDefect,\n HostStage,\n ListenerFailed,\n ListenerSite,\n ReactionFailed,\n ReactionParked,\n ReactionSkipped,\n ServerOnlySubmitted,\n SyncDiagnostic,\n UnknownRefusal,\n} from './diagnostics.js'\nexport { SyncRefusal, isInvalidBy } from './refusal.js'\nexport {\n indexedDb,\n tabStorage,\n type OutboxEntry,\n type Storage,\n type TabStorageOptions,\n} 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 HistoryOption,\n type Law,\n type LawsOption,\n type MakeOptions,\n type MsgOf,\n type PolicyJournalContract,\n type ServerMsgOf,\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 AmbiguousMessageError,\n CheckpointRegressionError,\n CommittedOrderError,\n ForeignAcknowledgementError,\n ForeignRejectionError,\n InvalidExchangeError,\n InvalidOutboxError,\n InvalidReplicaHistoryError,\n LawBrokenError,\n ReplayError,\n ReplicaClosedError,\n ServerKeyReusedError,\n ServerOnlyMessageError,\n StaleParkedRunError,\n StorageError,\n UnreadableHistoryError,\n UnreadableMessageError,\n UnsupportedClockVersionError,\n UnsupportedMessageVersionError,\n UnsupportedReplicaVersionError,\n WrongReplicaStorageError,\n type ReplicaError,\n} from './errors.js'\nexport { migrations, type Migrations } from './migrations.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 TransportSocket,\n TransportError,\n ExchangeRefused,\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 DeclaredLaw,\n type Exchange,\n type JournalContract,\n type MessageHistory,\n type OpenReplicaOptions,\n type Operation,\n type Rejection,\n type Replica,\n type ReplicaSnapshot,\n type ReplicaState,\n type ReplicaStatus,\n type SyncDefinition,\n type SyncDefinitionOptions,\n type TransportClient,\n type WrittenOperation,\n} from './sync.js'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,MAAa,OAAO;;CAElB,gBAAA;;CAEA,QAAQA;;CAER,YAAA;;CAEA,OAAA;;CAEA,aAAA;;CAEA,MAAA;;CAEA,SAASC;;CAET,WAAA;;CAEA,YAAA;;CAGA,WAAW;;EAET,QAAQC;;EAER,UAAUC;;EAEV,aAAaC;;EAEb,WAAA;;EAEA,OAAOC;;EAEP,cAAA;;EAEA,cAAA;;EAEA,YAAA;CACF;;CAGA,UAAU;EACR,MAAMC;;EAEN,KAAKC;;EAEL,OAAOC;EACP,eAAeC;EACf,iBAAiBC;CACnB;;CAGA,KAAK;EACH,UAAUC;;EAEV,WAAWC;CACb;AACF"}
package/dist/journal.d.ts CHANGED
@@ -204,19 +204,25 @@ export interface DocumentHostOptions<Message, Shared, Principal, RP = never> {
204
204
  readonly journal: () => Promise<Journal<Operation, Shared, Principal, WrittenOperation>>;
205
205
  /**
206
206
  * Who is opening the socket, from the upgrade request. Fails with a
207
- * `RemoteUnauthenticated` (`RemoteServer.unauthenticated()`) to refuse it:
208
- * a 401 carrying its message. A defect is a 500 that says nothing of it.
209
- * A browser's `WebSocket` sends no header of the page's: `Origin` and the
210
- * cookie are what it has.
207
+ * `RemoteUnauthenticated` (`RemoteServer.unauthenticated(reason?)`) to
208
+ * refuse it: a 401 that says "Unauthenticated", or its `reason`, the words
209
+ * written for the caller, when it has one. Its `message` is never sent. A
210
+ * defect, or a failure that is no `RemoteUnauthenticated`, is a 500 that
211
+ * says nothing of it: a session store that is down is no refusal, so let
212
+ * it die (`Effect.orDie`). A browser's `WebSocket` sends no header of the
213
+ * page's: `Origin` and the cookie are what it has.
211
214
  */
212
215
  readonly resolvePrincipal: (request: Request) => Effect.Effect<Principal, RemoteUnauthenticated, RP>;
213
216
  /**
214
217
  * Asks `resolvePrincipal` again, of the upgrade request, every `every`
215
- * while the socket is open: a refusal closes it with 4401, and a principal
216
- * whose `key` differs from the one it opened with (`Policy.keyOf`) closes
217
- * it with 1012, which the replica reconnects after, as the new principal;
218
- * without `key` only a refusal closes it. Without it a socket serves the
219
- * principal it opened with until it closes, a revoked session included.
218
+ * while the socket is open: a refusal closes it with 4401 and the reason
219
+ * "Unauthenticated", or the refusal's `reason` when it has one (cut to the
220
+ * 123 bytes a close carries), and a principal whose `key` differs from the
221
+ * one it opened with (`Policy.keyOf`) closes it with 1012, which the
222
+ * replica reconnects after, as the new principal; without `key` only a
223
+ * refusal closes it. A resolver that breaks closes it with 1011. Without
224
+ * `revalidate` a socket serves the principal it opened with until it
225
+ * closes, a revoked session included.
220
226
  */
221
227
  readonly revalidate?: {
222
228
  readonly every: Duration.Input;
@@ -1 +1 @@
1
- {"version":3,"file":"journal.d.ts","names":["ServerJournal"],"sources":["../src/journal.ts"],"mappings":";;;;;;;;;iBAsEiB,uBAAuB,SAAS,QAAQ;;WAE9C,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1
- import { Cause, Context, Effect, Exit, Fiber, Layer, Match, Option, Result, Schema, Scope, Stream } from "effect";
1
+ import { Cause, Context, Effect, Exit, Fiber, Layer, Match, Option, Predicate, Result, Schema, Scope, Stream } from "effect";
2
2
  import { Cursor, DocumentId, JournalError, Sequence } from "foldkit-durable/core";
3
3
  import { checkRevalidate } from "./revalidate.js";
4
- import { hostDefect, listenerFailed, reportTo, serverOnlySubmitted } from "./diagnostics.js";
5
- import { serveSocket } from "./transport.js";
4
+ import { answerHostDefect, hostDefect, listenerFailed, reportTo, serverOnlySubmitted } from "./diagnostics.js";
5
+ import { ExchangeRefused, serveSocket } from "./transport.js";
6
6
  import { reaction, serverJournal } from "./serverJournal.js";
7
7
  import { SyncRefusal, fitWords } from "./refusal.js";
8
8
  import { sequence } from "./ids.js";
@@ -29,9 +29,9 @@ const invalidAs = (message) => SyncRefusal.Invalid({
29
29
  /** The version an entry claims, read before anything else of it, so a newer one is told from a malformed one. */
30
30
  const claimedVersion = Schema.decodeUnknownOption(Schema.Struct({ messageVersion: Schema.optionalKey(Schema.Number) }));
31
31
  /**
32
- * What the replica is told: a socket sends an error's message, and the
33
- * operation's id and version are another replica's. They stay on the error,
34
- * for the server's own logs.
32
+ * What the replica is told, and all of it: the operation's id and version are
33
+ * another replica's. They stay on the error, which a socket reports
34
+ * (`ExchangeDefect`) and does not send.
35
35
  */
36
36
  const HISTORY_UNREADABLE = "This server cannot read the history of this document";
37
37
  /**
@@ -115,15 +115,15 @@ const journalExchange = (options) => {
115
115
  return written;
116
116
  };
117
117
  const exchange = (cursor, pending, seen) => Effect.gen(function* () {
118
- if (options.opens !== void 0 && !(yield* options.opens)) return yield* Effect.fail(/* @__PURE__ */ new Error("This connection may not open the document"));
118
+ if (options.opens !== void 0 && !(yield* options.opens)) return yield* Effect.fail(new ExchangeRefused({ message: "This connection may not open the document" }));
119
119
  const epoch = yield* journal.epoch(key);
120
120
  const from = seen !== void 0 && seen !== epoch ? 0 : cursor;
121
121
  const at = yield* journal.cursor(key);
122
- if (from > at) return yield* Effect.fail(/* @__PURE__ */ new Error(`Cursor ${cursor} is ahead of the server's ${at}`));
122
+ if (from > at) return yield* Effect.fail(new ExchangeRefused({ message: `Cursor ${cursor} is ahead of the server's ${at}` }));
123
123
  for (const input of pending) {
124
124
  const found = Option.flatMapNullishOr(claimedVersion(input), (probe) => probe.messageVersion);
125
125
  if (Option.isSome(found) && found.value > supported) return yield* Option.match(idOf(input), {
126
- onNone: () => Effect.fail(/* @__PURE__ */ new Error("A pending entry names no operation")),
126
+ onNone: () => Effect.fail(new ExchangeRefused({ message: "A pending entry names no operation" })),
127
127
  onSome: (opId) => Effect.fail(new UnsupportedMessageVersionError({
128
128
  opId,
129
129
  found: found.value,
@@ -151,12 +151,21 @@ const journalExchange = (options) => {
151
151
  reject(opId, SyncRefusal.Forbidden({ reason: Option.fromUndefinedOr(fitted) }), fitted ?? otherwise);
152
152
  };
153
153
  const invalid = (opId, message) => reject(opId, invalidAs(message), message);
154
+ const broke = (opId, rule, reason, path) => {
155
+ const message = fitWords(reason ?? "It breaks a law of the document");
156
+ reject(opId, SyncRefusal.Invalid({
157
+ entity: Option.none(),
158
+ rule: Option.some(fitWords(rule)),
159
+ message,
160
+ path: (path ?? []).slice(0, 16).map(fitWords)
161
+ }), message);
162
+ };
154
163
  const acknowledged = [];
155
164
  for (const input of pending) {
156
165
  const decoded = operationOf(input);
157
166
  if (Result.isFailure(decoded)) {
158
167
  const id = idOf(input);
159
- if (Option.isNone(id)) return yield* Effect.fail(/* @__PURE__ */ new Error("A pending entry names no operation"));
168
+ if (Option.isNone(id)) return yield* Effect.fail(new ExchangeRefused({ message: "A pending entry names no operation" }));
160
169
  const failure = decoded.failure;
161
170
  if (failure === "invalid") invalid(id.value, "Not an operation this server accepts");
162
171
  else if (failure instanceof UnreadableMessageError) reject(id.value, SyncRefusal.Unreadable({ version: failure.version }), "Written by a version of the app this server cannot read");
@@ -177,7 +186,7 @@ const journalExchange = (options) => {
177
186
  Committed: ({ committed }) => committed.operation.opId,
178
187
  AlreadyCommitted: ({ opId }) => opId
179
188
  }))), Effect.catchTags({
180
- OperationRejectedError: (error) => Effect.sync(() => forbid(error.opId, error.reason, "Refused by the server")),
189
+ OperationRejectedError: (error) => Effect.sync(() => error.rule === void 0 ? forbid(error.opId, error.reason, "Refused by the server") : broke(error.opId, error.rule, error.reason, error.path)),
181
190
  InvalidOperationError: () => Effect.sync(() => invalid(operation.opId, "Not a valid operation")),
182
191
  IdentityConflictError: () => Effect.sync(() => invalid(operation.opId, "Its id was already used for another"))
183
192
  }));
@@ -237,6 +246,7 @@ const serveJournal = (socket, options) => {
237
246
  const { opens, diagnostics } = options;
238
247
  const report = (cause) => reportTo(diagnostics, hostDefect("Notice", cause));
239
248
  return serveSocket(socket, {
249
+ diagnostics,
240
250
  exchange: (cursor, pending, epoch) => client.exchange(sequence(cursor), pending, epoch),
241
251
  changes: opens === void 0 ? notices : (listener) => notices(() => void Effect.runPromise(Effect.catchCause(opens, (cause) => Effect.as(report(cause), false))).then((open) => {
242
252
  if (open) listener();
@@ -328,7 +338,29 @@ const editsJournal = (options) => {
328
338
  };
329
339
  /** What a revalidation that found another principal fails with. */
330
340
  const changed = Symbol("changed");
331
- const internalError = () => Response.json({ error: "Internal error" }, { status: 500 });
341
+ /** What a caller the resolver refused reads when the refusal gives no `reason`. */
342
+ const UNAUTHENTICATED = "Unauthenticated";
343
+ /**
344
+ * Whether a resolver failed with the refusal its type promises. Asked of the
345
+ * value, since a resolver compiled past its type (a cast, plain JavaScript)
346
+ * can fail with a driver's error, which must not read as "sign in again".
347
+ */
348
+ const isRefusal = (failure) => Predicate.isTagged(failure, "Unauthenticated");
349
+ /** The most UTF-8 bytes a close reason carries; a longer one makes a platform refuse the close. */
350
+ const CLOSE_REASON_BYTES = 123;
351
+ /** `words` as a close reason: cut to fit, between characters, and marked where cut. */
352
+ const fitCloseReason = (words) => {
353
+ const encoder = new TextEncoder();
354
+ if (encoder.encode(words).length <= CLOSE_REASON_BYTES) return words;
355
+ let fitted = "";
356
+ let bytes = encoder.encode("…").length;
357
+ for (const character of words) {
358
+ bytes += encoder.encode(character).length;
359
+ if (bytes > CLOSE_REASON_BYTES) break;
360
+ fitted += character;
361
+ }
362
+ return `${fitted}…`;
363
+ };
332
364
  /**
333
365
  * One document's Sync host, for any runtime that upgrades a request to a
334
366
  * socket: a Durable Object (`foldkit-sync/do`), or Node's `ws`. Each
@@ -351,12 +383,9 @@ const documentHost = (options) => {
351
383
  const { diagnostics } = options;
352
384
  const reporter = diagnostics === void 0 ? void 0 : (diagnostic) => diagnostics(diagnostic, request);
353
385
  const report = (stage, cause) => reportTo(reporter, hostDefect(stage, cause));
354
- const defect = async (stage, cause) => {
355
- await Effect.runPromise(report(stage, cause));
356
- return refuse(internalError());
357
- };
386
+ const defect = async (stage, cause) => refuse(await Effect.runPromise(answerHostDefect(reporter, stage, cause)));
358
387
  const { layer } = options;
359
- const ask = Effect.suspend(() => options.resolvePrincipal(request));
388
+ const ask = Effect.suspend(() => options.resolvePrincipal(request)).pipe(Effect.catch((failure) => isRefusal(failure) ? Effect.fail(failure) : Effect.die(failure)));
360
389
  const opened = await Effect.runPromiseExit(Effect.gen(function* () {
361
390
  const services = layer === void 0 ? Context.empty() : yield* Layer.buildWithScope(layer(), scope);
362
391
  const resolve = Effect.provide(ask, services);
@@ -367,7 +396,7 @@ const documentHost = (options) => {
367
396
  }));
368
397
  if (Exit.isFailure(opened)) return defect("Resolve", opened.cause);
369
398
  const { resolve, resolved } = opened.value;
370
- if (Result.isFailure(resolved)) return refuse(Response.json({ error: resolved.failure.message }, { status: 401 }));
399
+ if (Result.isFailure(resolved)) return refuse(Response.json({ error: resolved.failure.reason ?? UNAUTHENTICATED }, { status: 401 }));
371
400
  const principal = resolved.success;
372
401
  const journal = await Promise.resolve().then(options.journal).then((open) => Result.succeed(open), (error) => Result.fail(error));
373
402
  if (Result.isFailure(journal)) return defect("Journal", Cause.die(journal.failure));
@@ -399,7 +428,7 @@ const documentHost = (options) => {
399
428
  stop();
400
429
  const [code, reason] = Option.match(Cause.findErrorOption(cause), {
401
430
  onNone: () => [1011, "Internal error"],
402
- onSome: (error) => error === changed ? [1012, "Who is asking changed"] : [4401, error.message]
431
+ onSome: (error) => error === changed ? [1012, "Who is asking changed"] : [4401, fitCloseReason(error.reason ?? UNAUTHENTICATED)]
403
432
  });
404
433
  try {
405
434
  socket.closeWith(code, reason);