From 413afef9c89396cd80647743f4e966e3ba4a1508 Mon Sep 17 00:00:00 2001 From: Chris Nelson Date: Tue, 29 Aug 2023 13:54:43 -0400 Subject: [PATCH] accept version number rollover --- src/LiveState.ts | 6 +++++- test/live-state-test.ts | 27 +++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/LiveState.ts b/src/LiveState.ts index b2dcea6..11646bd 100644 --- a/src/LiveState.ts +++ b/src/LiveState.ts @@ -168,7 +168,7 @@ export class LiveState implements EventTarget { this.eventTarget.dispatchEvent(new CustomEvent('livestate-patch', { detail: {patch, version} })); - if (version === this.stateVersion + 1) { + if (this.versionMatches(version)) { const { doc, res } = applyPatch(this.state, patch, { mutate: false }); this.state = doc; this.stateVersion = version; @@ -183,6 +183,10 @@ export class LiveState implements EventTarget { } } + versionMatches(version) { + return (version === this.stateVersion + 1) || (version === 0); + } + pushEvent(eventName, payload) { this.dispatchEvent(new CustomEvent(eventName, {detail: payload})); } diff --git a/test/live-state-test.ts b/test/live-state-test.ts index 44f7210..1b06764 100644 --- a/test/live-state-test.ts +++ b/test/live-state-test.ts @@ -87,6 +87,33 @@ describe('LiveState', () => { expect(state).to.deep.equal(newState); }); + it('accepts version number rollover in json patch', () => { + const initialState = { foo: "bar" }; + const newState = { foo: "baz"}; + const patch = compare(initialState, newState); + socketMock.expects('connect').exactly(1); + liveState.connect(); + let state = {}; + let receivedPatch; + + liveState.addEventListener('livestate-change', ({detail: {state: newState}}) => state = newState); + liveState.addEventListener('livestate-patch', ({detail: {patch: thePatch}}) => receivedPatch = thePatch); + + const onChangeArgs = liveState.channel.on.getCall(0).args; + expect(onChangeArgs[0]).to.equal("state:change"); + const onChangeHandler = onChangeArgs[1]; + onChangeHandler({state: initialState, version: 1000}); + + const onPatchArgs = liveState.channel.on.getCall(1).args; + expect(onPatchArgs[0]).to.equal("state:patch"); + const onPatchHandler = onPatchArgs[1]; + onPatchHandler({patch, version: 0}); + + expect(receivedPatch).to.equal(patch); + expect(state).to.deep.equal(newState); + + }) + it('requests new state when receiving patch with incorrect version', () => { const initialState = { foo: "bar" }; const newState = { foo: "baz", bing: [1, 2] };