diff --git a/.changeset/client-options.md b/.changeset/client-options.md new file mode 100644 index 0000000..53f8720 --- /dev/null +++ b/.changeset/client-options.md @@ -0,0 +1,8 @@ +--- +'convex-svelte': patch +--- + +### Fixes + +- **No WebSocket during server rendering** - the client created by `setupConvex()` / `initConvex()` is now always disabled on the server, even when a caller passes `disabled: false`. Whether code runs on the server is decided at runtime (`typeof document`) instead of by the bundler's resolution of `esm-env`. +- **Ignored client options are reported** - client options only take effect where the shared client is created, like the `ConvexReactClient` constructor in React. When `setupConvex()` or a repeated `initConvex()` passes options that differ from the ones the client was created with (e.g. `expectAuth` in the root layout while `initConvex()` in `hooks.ts` created the client), a dev warning now names them instead of dropping them silently. Only primitive options are compared; functions and objects such as `logger` get a new identity on every hot reload. diff --git a/src/lib/client.svelte.ts b/src/lib/client.svelte.ts index 1c224aa..7849586 100644 --- a/src/lib/client.svelte.ts +++ b/src/lib/client.svelte.ts @@ -13,10 +13,12 @@ import { parseArgsWithSkip } from './internal/args.svelte.js'; import { getConvexClient, getSingletonClient, + getSingletonOptions, getSingletonUrl, setSingleton, flushDeferredSubscriptions } from './internal/singleton.js'; +import { warnIgnoredOptions, withServerDisabled } from './internal/client_options.js'; import { isClientActive } from './internal/client_status.js'; const _contextKey = '$$_convexClient'; @@ -54,9 +56,12 @@ export const setupConvex = (url: string, options: ConvexClientOptions = {}): Con 'Only one deployment per app is supported. Call closeConvex() first to switch deployments.' ); } - const client = existing ?? new ConvexClient(url, { disabled: !BROWSER, ...options }); + if (existing) { + warnIgnoredOptions('setupConvex', getSingletonOptions(), options); + } + const client = existing ?? new ConvexClient(url, withServerDisabled(options)); if (!existing) { - setSingleton(url, client); + setSingleton(url, client, options); } setConvexClientContext(client); diff --git a/src/lib/internal/client_options.spec.ts b/src/lib/internal/client_options.spec.ts new file mode 100644 index 0000000..2195467 --- /dev/null +++ b/src/lib/internal/client_options.spec.ts @@ -0,0 +1,93 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; + +const env = vi.hoisted(() => ({ dev: true })); +vi.mock('esm-env', () => ({ + get DEV() { + return env.dev; + } +})); + +import { differingOptions, warnIgnoredOptions, withServerDisabled } from './client_options.js'; + +/** Run with or without a `document`, i.e. as in the browser or on the server. */ +function inBrowser(browser: boolean) { + if (browser) globalThis.document = {} as Document; + else delete (globalThis as { document?: Document }).document; +} + +afterEach(() => { + env.dev = true; + delete (globalThis as { document?: Document }).document; + vi.restoreAllMocks(); +}); + +describe('withServerDisabled', () => { + it('always disables the client on the server, even with disabled: false', () => { + inBrowser(false); + + expect(withServerDisabled({})).toEqual({ disabled: true }); + expect(withServerDisabled({ disabled: false, verbose: true })).toEqual({ + disabled: true, + verbose: true + }); + }); + + it('enables the client in the browser unless disabled: true is passed', () => { + inBrowser(true); + + expect(withServerDisabled({})).toEqual({ disabled: false }); + expect(withServerDisabled({ disabled: true })).toEqual({ disabled: true }); + }); +}); + +describe('differingOptions', () => { + it('reports primitive options that differ from the creation options', () => { + expect(differingOptions({ verbose: true }, { verbose: true, expectAuth: true })).toEqual([ + 'expectAuth' + ]); + expect(differingOptions({ expectAuth: true }, { expectAuth: false })).toEqual(['expectAuth']); + }); + + it('ignores disabled, functions and objects (new identity on every hot reload)', () => { + expect( + differingOptions( + {}, + { + disabled: false, + logger: { logVerbose() {} } as never, + webSocketConstructor: class {} as never + } + ) + ).toEqual([]); + }); +}); + +describe('warnIgnoredOptions', () => { + it('warns in the browser during development, naming the ignored options', () => { + inBrowser(true); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + warnIgnoredOptions('setupConvex', {}, { expectAuth: true }); + + expect(warn).toHaveBeenCalledOnce(); + expect(warn.mock.calls[0][0]).toContain('setupConvex(): '); + expect(warn.mock.calls[0][0]).toContain('ignored: expectAuth'); + }); + + it('stays quiet for matching options, on the server, and in production', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + inBrowser(true); + warnIgnoredOptions('initConvex', { expectAuth: true }, { expectAuth: true }); + warnIgnoredOptions('initConvex', { expectAuth: true }, {}); + + inBrowser(false); + warnIgnoredOptions('initConvex', {}, { expectAuth: true }); + + inBrowser(true); + env.dev = false; + warnIgnoredOptions('initConvex', {}, { expectAuth: true }); + + expect(warn).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/internal/client_options.ts b/src/lib/internal/client_options.ts new file mode 100644 index 0000000..3988d85 --- /dev/null +++ b/src/lib/internal/client_options.ts @@ -0,0 +1,60 @@ +/** + * Options of the shared ConvexClient. + * + * Like `new ConvexReactClient(url, options)` in React, client options can only + * take effect where the client is created: `initConvex()` (SvelteKit, in + * `hooks.ts`) or the first `setupConvex()`. Later calls reuse the client, so + * options they pass are reported instead of silently dropped. + */ +import { DEV } from 'esm-env'; +import type { ConvexClientOptions } from 'convex/browser'; + +const isServer = () => typeof globalThis.document === 'undefined'; + +/** + * Options for a new client. On the server the client is always disabled, so + * server rendering never opens a WebSocket — even if a caller passes + * `disabled: false`. Decided at runtime rather than by build-time conditions, + * so it can't go wrong with how a bundler resolves packages. + */ +export function withServerDisabled(options: ConvexClientOptions): ConvexClientOptions { + return { ...options, disabled: isServer() || options.disabled === true }; +} + +/** + * Names of `requested` options that differ from the ones the client was + * created with. Only primitive values are compared: functions and objects + * (e.g. `logger`) get a new identity on every hot reload. `disabled` is + * managed by convex-svelte. + */ +export function differingOptions( + created: ConvexClientOptions, + requested: ConvexClientOptions +): string[] { + return Object.entries(requested) + .filter(([name, value]) => { + if (name === 'disabled' || (typeof value === 'object' && value !== null)) return false; + if (typeof value === 'function') return false; + return created[name as keyof ConvexClientOptions] !== value; + }) + .map(([name]) => name); +} + +/** + * Dev only, in the browser (where the options matter): report options that a + * call passed for a client that already exists. + */ +export function warnIgnoredOptions( + caller: 'setupConvex' | 'initConvex', + created: ConvexClientOptions, + requested: ConvexClientOptions +): void { + if (!DEV || isServer()) return; + const ignored = differingOptions(created, requested); + if (ignored.length === 0) return; + console.warn( + `[convex-svelte] ${caller}(): the Convex client already exists, so these options are ` + + `ignored: ${ignored.join(', ')}. Client options only take effect where the client is ` + + 'created, e.g. initConvex(url, options) in src/hooks.ts.' + ); +} diff --git a/src/lib/internal/singleton.ts b/src/lib/internal/singleton.ts index 6654b85..a8a2d59 100644 --- a/src/lib/internal/singleton.ts +++ b/src/lib/internal/singleton.ts @@ -7,10 +7,12 @@ * * This avoids a circular dependency between core and sveltekit. */ -import type { ConvexClient } from 'convex/browser'; +import type { ConvexClient, ConvexClientOptions } from 'convex/browser'; let _singletonClient: ConvexClient | null = null; let _singletonUrl: string | null = null; +// Options the singleton was created with (see client_options.ts). +let _singletonOptions: ConvexClientOptions = {}; // --------------------------------------------------------------------------- // Deferred subscription queue for transport.decode → setupAuth coordination. @@ -84,6 +86,7 @@ export function getSingletonClient(): ConvexClient | null { if (_singletonClient?.closed) { _singletonClient = null; _singletonUrl = null; + _singletonOptions = {}; return null; } return _singletonClient; @@ -105,6 +108,7 @@ export async function closeConvex(): Promise { const client = _singletonClient; _singletonClient = null; _singletonUrl = null; + _singletonOptions = {}; // Restore defer mode so the next init cycle coordinates with setupAuth // again instead of firing subscriptions immediately. _deferredSubscriptions = []; @@ -118,9 +122,19 @@ export function getSingletonUrl(): string | null { return _singletonUrl; } -export function setSingleton(url: string, client: ConvexClient): void { +/** Options the current client was created with. */ +export function getSingletonOptions(): ConvexClientOptions { + return _singletonOptions; +} + +export function setSingleton( + url: string, + client: ConvexClient, + options: ConvexClientOptions = {} +): void { _singletonUrl = url; _singletonClient = client; + _singletonOptions = options; } /** diff --git a/src/lib/sveltekit/client.spec.ts b/src/lib/sveltekit/client.spec.ts index d27f285..8637cac 100644 --- a/src/lib/sveltekit/client.spec.ts +++ b/src/lib/sveltekit/client.spec.ts @@ -105,4 +105,12 @@ describe('initConvex — queryCache', () => { verbose: true }); }); + + it('keeps the client disabled on the server even when disabled: false is passed', () => { + initConvex('https://example.convex.cloud', { disabled: false }); + + expect(clientConstructed).toHaveBeenCalledWith('https://example.convex.cloud', { + disabled: true + }); + }); }); diff --git a/src/lib/sveltekit/client.ts b/src/lib/sveltekit/client.ts index 0ff3836..7d3e35c 100644 --- a/src/lib/sveltekit/client.ts +++ b/src/lib/sveltekit/client.ts @@ -6,11 +6,15 @@ * - `setupConvex(url)` in root layout — handles context + cleanup, calls initConvex internally */ import { ConvexClient, type ConvexClientOptions } from 'convex/browser'; -import { getSingletonClient, getSingletonUrl, setSingleton } from '../internal/singleton.js'; +import { + getSingletonClient, + getSingletonOptions, + getSingletonUrl, + setSingleton +} from '../internal/singleton.js'; +import { warnIgnoredOptions, withServerDisabled } from '../internal/client_options.js'; import { configureQueryCache, type QueryCacheOptions } from './query-lifecycle.js'; -const IS_BROWSER = typeof globalThis.document !== 'undefined'; - export type InitConvexOptions = ConvexClientOptions & { /** * Idle buffer for queries created by `convexLoad()` / `convexLoadPaginated()`. @@ -27,6 +31,8 @@ export type InitConvexOptions = ConvexClientOptions & { * Initialize the Convex client at module level (before any component mounts). * Call from `hooks.client.ts` to ensure the client exists before `transport.decode`. * Idempotent — subsequent calls with the same URL return the existing client. + * Client options only apply when the client is created (like the + * `ConvexReactClient` constructor); later calls with different ones warn in dev. * A `queryCache` option is still applied, so editing it in `hooks.ts` takes * effect on HMR. * @@ -53,9 +59,10 @@ export function initConvex(url: string, options: InitConvexOptions = {}): Convex configureQueryCache(queryCache); } if (existing) { + warnIgnoredOptions('initConvex', getSingletonOptions(), clientOptions); return existing; } - const client = new ConvexClient(url, { disabled: !IS_BROWSER, ...clientOptions }); - setSingleton(url, client); + const client = new ConvexClient(url, withServerDisabled(clientOptions)); + setSingleton(url, client, clientOptions); return client; }