From bac41dd5c00ab6ecc4388fd27fcca0e449eb8231 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 27 Jun 2026 19:02:46 +0100 Subject: [PATCH] Add reactive CultMesh TS document proxies --- packages/cultmesh-ts/src/index.ts | 189 +++++++++++++++++++++ packages/cultmesh-ts/test/cultmesh.test.ts | 38 +++++ 2 files changed, 227 insertions(+) diff --git a/packages/cultmesh-ts/src/index.ts b/packages/cultmesh-ts/src/index.ts index 5a9079e6..aba1b530 100644 --- a/packages/cultmesh-ts/src/index.ts +++ b/packages/cultmesh-ts/src/index.ts @@ -201,6 +201,21 @@ export interface CultMeshPollingWatchOptions { readonly equals?: (left: TResult, right: TResult) => boolean; } +export interface CultMeshReactiveDocumentOptions { + readonly context?: CultMeshQueryContext | string; + readonly watch?: boolean; + readonly debounceMs?: number; + readonly onError?: (error: unknown) => void; +} + +export interface CultMeshReactiveDocument { + readonly current: TDocument; + readonly ready: Promise; + readonly disposed: boolean; + refresh(): Promise; + dispose(): void; +} + export interface CultMeshNativeSliceColumn { readonly name: string; readonly valueType: string; @@ -929,6 +944,15 @@ export class CultMeshDocumentHandle { return next; } + public reactive( + options: CultMeshReactiveDocumentOptions = {}, + ): CultMeshReactiveDocument { + return new CultMeshReactiveDocumentHandle( + this as unknown as CultMeshDocumentHandle, + options, + ); + } + public asSchemaAlias( schema: CultMeshDocumentSchemaDescriptor, options: { parse?: (value: unknown) => TAlias } = {}, @@ -976,6 +1000,162 @@ export class CultMeshDocumentHandle { } } +class CultMeshReactiveDocumentHandle + implements CultMeshReactiveDocument { + readonly #document: CultMeshDocumentHandle; + readonly #context: CultMeshQueryContext | string; + readonly #onError: (error: unknown) => void; + readonly #debounceMs: number; + #current: TDocument; + #disposed = false; + #applyingRemote = false; + #pendingSet: Promise = Promise.resolve(); + #flushScheduled = false; + #flushTimer: ReturnType | undefined; + #unsubscribe: CultMeshUnsubscribe | undefined; + + public readonly ready: Promise; + + public constructor( + document: CultMeshDocumentHandle, + options: CultMeshReactiveDocumentOptions = {}, + ) { + this.#document = document; + this.#context = options.context ?? "local"; + this.#debounceMs = options.debounceMs ?? 0; + this.#onError = options.onError ?? ((error) => { + queueMicrotask(() => { + throw error; + }); + }); + this.#current = this.createProxy({} as TDocument); + this.ready = this.refresh(); + + if (options.watch !== false) { + try { + this.#unsubscribe = document.watch(this.#context, value => { + this.applySnapshot(value); + }); + } catch (error) { + this.#onError(error); + } + } + } + + public get current(): TDocument { + return this.#current; + } + + public get disposed(): boolean { + return this.#disposed; + } + + public async refresh(): Promise { + const latest = await this.#document.latest(this.#context); + this.applySnapshot(latest); + return this.#current; + } + + public dispose(): void { + this.#disposed = true; + if (this.#flushTimer !== undefined) { + clearTimeout(this.#flushTimer); + this.#flushTimer = undefined; + } + this.#flushScheduled = false; + this.#unsubscribe?.(); + this.#unsubscribe = undefined; + } + + private applySnapshot(value: TDocument): void { + this.#applyingRemote = true; + try { + for (const key of Reflect.ownKeys(this.#current)) { + if (!Reflect.has(value, key)) { + Reflect.deleteProperty(this.#current, key); + } + } + Object.assign(this.#current, cloneCultMeshDocument(value)); + } finally { + this.#applyingRemote = false; + } + } + + private createProxy(seed: TDocument): TDocument { + return new Proxy(seed, { + set: (target, property, value) => { + const changed = !Object.is(Reflect.get(target, property), value); + const ok = Reflect.set(target, property, value); + if (ok && changed && !this.#applyingRemote) { + this.queueSet(); + } + return ok; + }, + deleteProperty: (target, property) => { + const hadProperty = Reflect.has(target, property); + const ok = Reflect.deleteProperty(target, property); + if (ok && hadProperty && !this.#applyingRemote) { + this.queueSet(); + } + return ok; + }, + }); + } + + private queueSet(): void { + if (this.#disposed) { + return; + } + if (this.#flushScheduled) { + return; + } + + this.#flushScheduled = true; + const flush = () => { + this.#flushScheduled = false; + this.#flushTimer = undefined; + if (this.#disposed) { + return; + } + + const snapshot = cloneCultMeshDocument(this.#current); + this.#pendingSet = this.#pendingSet + .catch(() => undefined) + .then(() => this.#document.set(this.#context, snapshot)) + .catch(error => this.#onError(error)); + }; + + const debounceMs = this.#debounceMs; + if (debounceMs > 0) { + this.#flushTimer = setTimeout(flush, debounceMs); + return; + } + + const requestFrame = (globalThis as { + requestAnimationFrame?: (callback: FrameRequestCallback) => number; + }).requestAnimationFrame; + if (typeof requestFrame === "function") { + requestFrame(() => flush()); + return; + } + + this.#flushTimer = setTimeout(flush, 0); + } +} + +function cloneCultMeshDocument(value: TDocument): TDocument { + if (typeof structuredClone === "function") { + try { + return structuredClone(value); + } catch (error) { + if ((error as { name?: string }).name !== "DataCloneError") { + throw error; + } + } + } + return JSON.parse(JSON.stringify(value)) as TDocument; +} + export class CultMeshBoundDocumentHandle { public constructor( public readonly verse: CultMeshVerseContext, @@ -1030,6 +1210,15 @@ export class CultMeshBoundDocumentHandle { return this.document.update(cultMeshQueryContextFromVerse(this.verse), update); } + public reactive( + options: Omit = {}, + ): CultMeshReactiveDocument { + return this.document.reactive({ + ...options, + context: cultMeshQueryContextFromVerse(this.verse), + }); + } + public asSchemaAlias( schema: CultMeshDocumentSchemaDescriptor, options: { parse?: (value: unknown) => TAlias } = {}, diff --git a/packages/cultmesh-ts/test/cultmesh.test.ts b/packages/cultmesh-ts/test/cultmesh.test.ts index b44b1770..82c096e2 100644 --- a/packages/cultmesh-ts/test/cultmesh.test.ts +++ b/packages/cultmesh-ts/test/cultmesh.test.ts @@ -202,6 +202,44 @@ test("CultMesh TS document handles submit predictions through configured authori ); }); +test("CultMesh TS reactive documents submit predictions from member writes", async () => { + let current = { + noteId: "note:reactive", + body: "initial", + }; + const predictions: string[] = []; + const document = CultMesh.document( + "cultmesh.note:reactive", + noteDocument, + async () => current, + { + routeHint: CultMesh.routeHint("network", "CultNet prediction"), + submitPrediction: async (_context, value) => { + predictions.push(value.body); + current = value; + }, + }, + ); + + const reactive = document.reactive({ + watch: false, + }); + await reactive.ready; + reactive.current.body = "member-write-prediction"; + reactive.current.body = "member-write-prediction-final"; + await waitFor( + () => predictions.includes("member-write-prediction-final"), + "reactive member write prediction", + ); + + assert.equal(current.body, "member-write-prediction-final"); + assert.deepEqual(predictions, ["member-write-prediction-final"]); + reactive.dispose(); + reactive.current.body = "after-dispose"; + await new Promise(resolve => setTimeout(resolve, 20)); + assert.deepEqual(predictions, ["member-write-prediction-final"]); +}); + test("CultMesh TS document handles read schema publications from single-file stores", async () => { const filePath = join(await mkdtemp(join(tmpdir(), "cultmesh-ts-publication-")), "publication.ccmp"); const node = await CultMesh.startNode(filePath, {