@terreno/syncdb 57.19.2 → 57.20.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.
Files changed (44) hide show
  1. package/CHANGELOG.md +393 -0
  2. package/README.md +2 -1
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +19 -2
  5. package/dist/client.js.map +1 -1
  6. package/dist/client.test.js +65 -1
  7. package/dist/client.test.js.map +1 -1
  8. package/dist/devConsoleLogger.d.ts +16 -0
  9. package/dist/devConsoleLogger.d.ts.map +1 -0
  10. package/dist/devConsoleLogger.js +162 -0
  11. package/dist/devConsoleLogger.js.map +1 -0
  12. package/dist/devConsoleLogger.test.d.ts +2 -0
  13. package/dist/devConsoleLogger.test.d.ts.map +1 -0
  14. package/dist/devConsoleLogger.test.js +271 -0
  15. package/dist/devConsoleLogger.test.js.map +1 -0
  16. package/dist/index.d.ts +5 -2
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +10 -2
  19. package/dist/index.js.map +1 -1
  20. package/dist/query/localQuery.test.d.ts +2 -0
  21. package/dist/query/localQuery.test.d.ts.map +1 -0
  22. package/dist/query/localQuery.test.js +14 -0
  23. package/dist/query/localQuery.test.js.map +1 -0
  24. package/dist/react/hooks.test.js +51 -2
  25. package/dist/react/hooks.test.js.map +1 -1
  26. package/dist/react/windowHooks.test.js +21 -0
  27. package/dist/react/windowHooks.test.js.map +1 -1
  28. package/dist/sync/httpChannel.d.ts +19 -2
  29. package/dist/sync/httpChannel.d.ts.map +1 -1
  30. package/dist/sync/httpChannel.js +16 -3
  31. package/dist/sync/httpChannel.js.map +1 -1
  32. package/dist/sync/httpChannel.test.js +23 -1
  33. package/dist/sync/httpChannel.test.js.map +1 -1
  34. package/package.json +6 -1
  35. package/src/client.test.ts +68 -1
  36. package/src/client.ts +24 -2
  37. package/src/devConsoleLogger.test.ts +332 -0
  38. package/src/devConsoleLogger.ts +192 -0
  39. package/src/index.ts +16 -1
  40. package/src/query/localQuery.test.ts +16 -0
  41. package/src/react/hooks.test.tsx +62 -2
  42. package/src/react/windowHooks.test.tsx +25 -0
  43. package/src/sync/httpChannel.test.ts +26 -0
  44. package/src/sync/httpChannel.ts +36 -5
package/src/index.ts CHANGED
@@ -15,12 +15,14 @@
15
15
  * debug broadcast bridge. Reach for `client.store`/`client.outbox` (or the React
16
16
  * hooks) instead, and open an issue if something genuinely needs promoting.
17
17
  *
18
- * Two other entry points exist:
18
+ * Three other entry points exist:
19
19
  * - `@terreno/syncdb/react` (src/react/index.ts) — React bindings. They live on
20
20
  * their own subpath because react is an optional peer dependency and this entry
21
21
  * must stay importable without it.
22
22
  * - `@terreno/syncdb/testing` (src/testing/index.ts) — test doubles such as
23
23
  * `createFakeTransport`, kept out of production bundles.
24
+ * - `@terreno/syncdb/devConsoleLogger` (src/devConsoleLogger.ts) — the dev console
25
+ * logger alone, so `@terreno/rtk` can re-export it without bundling the client.
24
26
  */
25
27
 
26
28
  // --- Client ---------------------------------------------------------------
@@ -153,6 +155,8 @@ export {
153
155
  type HttpChannelConfig,
154
156
  ListRequestError,
155
157
  QueryFieldNotAllowedError,
158
+ RequestSupersededError,
159
+ type SupersedableRequestOptions,
156
160
  } from "./sync/httpChannel";
157
161
  export {createSocketTransport, type SocketTransportConfig} from "./sync/socketTransport";
158
162
  export {
@@ -179,3 +183,14 @@ export type {
179
183
  SyncDebugSnapshot,
180
184
  SyncDebugStats,
181
185
  } from "./debug/debugLog";
186
+
187
+ // --- Dev console logger ---------------------------------------------------
188
+ // Dev-only bridge from client console errors to the backend's
189
+ // `POST /__terreno/browser-logs` route (read back by terreno-mcp-local `read_logs`).
190
+ // Also exposed as `@terreno/syncdb/devConsoleLogger` so callers can import it
191
+ // without bundling the sync client.
192
+
193
+ export {
194
+ type InstallTerrenoDevConsoleLoggerArgs,
195
+ installTerrenoDevConsoleLogger,
196
+ } from "./devConsoleLogger";
@@ -0,0 +1,16 @@
1
+ import {describe, it} from "bun:test";
2
+ import {assert} from "chai";
3
+ import type {SyncEntity} from "../storage/types";
4
+ import {applyLocalQuery} from "./localQuery";
5
+
6
+ describe("applyLocalQuery", () => {
7
+ it("rejects a where the local compiler cannot evaluate", (): void => {
8
+ const entities: SyncEntity<{title: string}>[] = [
9
+ {data: {title: "a"}, deleted: false, id: "1", seq: 0},
10
+ ];
11
+
12
+ assert.throws((): void => {
13
+ applyLocalQuery(entities, {where: {$search: "a"}});
14
+ }, /cannot evaluate locally/);
15
+ });
16
+ });
@@ -7,7 +7,15 @@ import {memoryPersisterFactory} from "../persisters/memoryPersister";
7
7
  import {AuthRequiredError} from "../sync/httpChannel";
8
8
  import {createFakeTransport, type FakeTransport} from "../testing/fakeTransport";
9
9
  import type {AuthProvider, SyncDelta} from "../types";
10
- import {useConflicts, useEntity, useEntityIds, useMutate, useQuery, useSyncStatus} from "./hooks";
10
+ import {
11
+ useConflicts,
12
+ useEntity,
13
+ useEntityIds,
14
+ useMutate,
15
+ useQuery,
16
+ useSyncDebugLog,
17
+ useSyncStatus,
18
+ } from "./hooks";
11
19
  import {SyncDbProvider, useSyncDbClient} from "./provider";
12
20
 
13
21
  interface TodoData {
@@ -51,12 +59,13 @@ interface Harness {
51
59
  wrapper: React.FC<{children: React.ReactNode}>;
52
60
  }
53
61
 
54
- const setup = async (): Promise<Harness> => {
62
+ const setup = async (options?: {debug?: boolean}): Promise<Harness> => {
55
63
  const transport = createFakeTransport();
56
64
  const auth = makeAuthProvider("u1");
57
65
  const client = createSyncDb({
58
66
  authProvider: auth,
59
67
  collections: ["todos"],
68
+ debug: options?.debug,
60
69
  name: uniqueName(),
61
70
  persisterFactory: memoryPersisterFactory,
62
71
  reconcileIntervalMs: 0,
@@ -762,4 +771,55 @@ describe("listener cleanup on unmount (E4)", () => {
762
771
  await client.stop();
763
772
  });
764
773
  });
774
+
775
+ it("useEntityIds removes its table listener on unmount", async () => {
776
+ const {client, wrapper} = await setup();
777
+ const baseline = client.store.raw.getListenerStats();
778
+ const {unmount} = renderHook(() => useEntityIds<TodoData>("todos"), {wrapper});
779
+ expect(client.store.raw.getListenerStats().table).toBe(baseline.table + 1);
780
+ unmount();
781
+ expect(client.store.raw.getListenerStats()).toEqual(baseline);
782
+ await act(async () => {
783
+ await client.stop();
784
+ });
785
+ });
786
+ });
787
+
788
+ describe("useSyncDebugLog", () => {
789
+ it("stays disabled and clear is a no-op when the client has no debug log", async () => {
790
+ const {client, wrapper} = await setup();
791
+ const {result, unmount} = renderHook(() => useSyncDebugLog(), {wrapper});
792
+ expect(result.current.enabled).toBe(false);
793
+ expect(result.current.events).toEqual([]);
794
+ expect(result.current.log).toBeUndefined();
795
+ expect(result.current.stats).toBeUndefined();
796
+ act(() => {
797
+ result.current.clear();
798
+ });
799
+ expect(result.current.events).toEqual([]);
800
+ unmount();
801
+ await act(async () => {
802
+ await client.stop();
803
+ });
804
+ });
805
+
806
+ it("reads recorded events and clears them when debug is on", async () => {
807
+ const {client, wrapper} = await setup({debug: true});
808
+ const {result, unmount} = renderHook(() => useSyncDebugLog(), {wrapper});
809
+ expect(result.current.enabled).toBe(true);
810
+ act(() => {
811
+ client.debug?.record({direction: "system", label: "seed", type: "connect"});
812
+ });
813
+ expect(result.current.events.some((event) => event.label === "seed")).toBe(true);
814
+ expect(result.current.stats?.retained).toBeGreaterThan(0);
815
+ act(() => {
816
+ result.current.clear();
817
+ });
818
+ expect(client.debug?.getEvents()).toEqual([]);
819
+ expect(client.debug?.getStats().retained).toBe(0);
820
+ unmount();
821
+ await act(async () => {
822
+ await client.stop();
823
+ });
824
+ });
765
825
  });
@@ -140,6 +140,31 @@ describe("useWindowQuery", () => {
140
140
  });
141
141
  });
142
142
 
143
+ it("refetches, loads the next page, and drops listeners on unmount", async () => {
144
+ const harness = await setup();
145
+ const {client, wrapper} = harness;
146
+ const baseline = client.store.raw.getListenerStats();
147
+ const {result, unmount} = renderHook(
148
+ () => useWindowQuery<Message>("messages", {where: {threadId: "a"}}),
149
+ {wrapper}
150
+ );
151
+ await waitFor(() => {
152
+ expect(result.current.ids).toEqual(["m1", "m2"]);
153
+ });
154
+ await act(async () => {
155
+ await result.current.refetch();
156
+ });
157
+ await act(async () => {
158
+ await result.current.fetchNextPage();
159
+ });
160
+ expect(result.current.ids).toEqual(["m1", "m2"]);
161
+ unmount();
162
+ expect(client.store.raw.getListenerStats()).toEqual(baseline);
163
+ await act(async () => {
164
+ await client.stop();
165
+ });
166
+ });
167
+
143
168
  it("does nothing while skip is set", async () => {
144
169
  const harness = await setup();
145
170
  const {client, wrapper} = harness;
@@ -7,6 +7,7 @@ import {
7
7
  type FetchLike,
8
8
  ListRequestError,
9
9
  QueryFieldNotAllowedError,
10
+ RequestSupersededError,
10
11
  } from "./httpChannel";
11
12
 
12
13
  const authProvider: Pick<AuthProvider, "getToken"> = {
@@ -185,6 +186,31 @@ describe("createHttpChannel", () => {
185
186
  const channel = createHttpChannel({authProvider, baseUrl: "http://api", fetchImpl});
186
187
  await expect(channel.fetchStreams()).rejects.toThrow("status 500");
187
188
  });
189
+ it("sends nothing when the caller was superseded while the token resolved", async () => {
190
+ const {fetchImpl, requests} = makeFetch(() => json({streams: []}));
191
+ let superseded = false;
192
+ const channel = createHttpChannel({
193
+ authProvider: {
194
+ getToken: async (): Promise<string> => {
195
+ superseded = true;
196
+ return "token-123";
197
+ },
198
+ },
199
+ baseUrl: "http://api",
200
+ fetchImpl,
201
+ });
202
+ await expect(channel.fetchStreams({isSuperseded: () => superseded})).rejects.toBeInstanceOf(
203
+ RequestSupersededError
204
+ );
205
+ expect(requests).toHaveLength(0);
206
+ });
207
+
208
+ it("sends the request while the caller is still current", async () => {
209
+ const {fetchImpl, requests} = makeFetch(() => json({streams: []}));
210
+ const channel = createHttpChannel({authProvider, baseUrl: "http://api", fetchImpl});
211
+ await expect(channel.fetchStreams({isSuperseded: () => false})).resolves.toEqual([]);
212
+ expect(requests).toHaveLength(1);
213
+ });
188
214
  });
189
215
 
190
216
  describe("sendMutation", () => {
@@ -26,6 +26,27 @@ export class AuthRequiredError extends Error {
26
26
  }
27
27
  }
28
28
 
29
+ /**
30
+ * Thrown instead of sending a request whose caller was superseded while the token was being
31
+ * read, for example a reconcile that a stop() overtook. Nothing reached the server.
32
+ */
33
+ export class RequestSupersededError extends Error {
34
+ constructor(message = "Request superseded before it was sent") {
35
+ super(message);
36
+ this.name = "RequestSupersededError";
37
+ }
38
+ }
39
+
40
+ /** Options for a request a caller may abandon while it waits for a token. */
41
+ export interface SupersedableRequestOptions {
42
+ /**
43
+ * Checked after the token resolves and before the request is sent. When it returns true the
44
+ * request is not sent and the call rejects with {@link RequestSupersededError}, so a request
45
+ * started under a session the app has since stopped syncing for never reaches the server.
46
+ */
47
+ isSuperseded?: () => boolean;
48
+ }
49
+
29
50
  export interface FetchSnapshotPageArgs {
30
51
  /** C2: the stream key to page (e.g. "todos|owner:123"), not a collection. */
31
52
  stream: string;
@@ -64,9 +85,10 @@ export interface HttpChannel {
64
85
  * C2: the authoritative set of streams the caller currently belongs to
65
86
  * (`GET /sync/streams`). Drives join-backfill / leave-purge diffs; 401 rejects with
66
87
  * {@link AuthRequiredError} so a transport/auth error is never mistaken for a
67
- * membership change (INV-2).
88
+ * membership change (INV-2). `isSuperseded` drops the request before it is sent
89
+ * ({@link RequestSupersededError}).
68
90
  */
69
- fetchStreams: () => Promise<SyncStreamInfo[]>;
91
+ fetchStreams: (options?: SupersedableRequestOptions) => Promise<SyncStreamInfo[]>;
70
92
  /**
71
93
  * `GET {path}?{params}` against a `modelRouter` list endpoint, for query windows.
72
94
  * Params are qs-encoded so Mongo operators (`$in`, `$gte`, …) survive.
@@ -244,8 +266,15 @@ export const createHttpChannel = ({
244
266
  }: HttpChannelConfig): HttpChannel => {
245
267
  const fetcher: FetchLike = fetchImpl ?? ((input, init) => globalThis.fetch(input, init));
246
268
 
247
- const request = async (path: string, init?: RequestInit): Promise<Response> => {
269
+ const request = async (
270
+ path: string,
271
+ init?: RequestInit,
272
+ {isSuperseded}: SupersedableRequestOptions = {}
273
+ ): Promise<Response> => {
248
274
  const token = await authProvider.getToken();
275
+ if (isSuperseded?.()) {
276
+ throw new RequestSupersededError(`${path} superseded before it was sent`);
277
+ }
249
278
  const organizationId = organizationIdProvider?.()?.trim();
250
279
  const headers: Record<string, string> = {
251
280
  Accept: "application/json",
@@ -339,8 +368,10 @@ export const createHttpChannel = ({
339
368
  return (await response.json()) as ListResponse;
340
369
  };
341
370
 
342
- const fetchStreams = async (): Promise<SyncStreamInfo[]> => {
343
- const response = await request("/sync/streams");
371
+ const fetchStreams = async (
372
+ options: SupersedableRequestOptions = {}
373
+ ): Promise<SyncStreamInfo[]> => {
374
+ const response = await request("/sync/streams", undefined, options);
344
375
  if (!response.ok) {
345
376
  throw new Error(`Sync streams request failed with status ${response.status}`);
346
377
  }