diff --git a/src/compat/realtime-mock.ts b/src/compat/realtime-mock.ts index 539e009d7..c95e80612 100644 --- a/src/compat/realtime-mock.ts +++ b/src/compat/realtime-mock.ts @@ -178,7 +178,15 @@ function createSocket(_url: string, handlers: SocketHandlers): RealtimeSocket { } switch (request.cmd) { case 'bind': { - if (!state.values.has(request.name)) addVariable(state, request.name, null); + // A function can add a variable after `registerSystem`, as a plain property. The + // first binding keeps its value. + if (!state.values.has(request.name)) { + addVariable( + state, + request.name, + Reflect.get(state.module, request.name) ?? null, + ); + } const notify: Listener = (value) => reply({ id: request.id, type: 'notify', value: value ?? null, meta }); bound.get(key)?.(); diff --git a/test/compat.test.ts b/test/compat.test.ts index 9c60d1e18..3163757fb 100644 --- a/test/compat.test.ts +++ b/test/compat.test.ts @@ -250,6 +250,34 @@ test('a 7.x binding and call use a 6.x mock system', async () => { realtime.stop(); }); +test('a binding keeps the value of a variable that a function added', async () => { + registerSystem('sys-2', { + Debug: [ + { + $post(this: Record, id: string, value: string) { + this[`logs:${id}`] = value; + }, + }, + ], + }); + const realtime = createRealtime({ + base_url: 'http://mock.invalid', + auth: { kind: 'none' }, + environment: mockRealtimeEnvironment(), + }); + const logs = { sys: 'sys-2', mod: 'Debug', index: 1, name: 'post' }; + expect(await realtime.exec(logs, ['a', 'first'])).toEqual({ ok: true, value: null }); + const states: BindingState[] = []; + const release = realtime.bind({ ...logs, name: 'logs:a' }, (state) => states.push(state)); + await waitFor(() => lastValue(states) === 'first'); + + // After the binding, a change notifies it. + expect((await realtime.exec(logs, ['a', 'second'])).ok).toBe(true); + await waitFor(() => lastValue(states) === 'second'); + release(); + realtime.stop(); +}); + function lastValue(states: readonly BindingState[]): unknown { const last = states.at(-1); return last?.kind === 'value' ? last.value : undefined;