@rebasepro/client 0.13.0 → 0.13.1-canary.g1822133

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.
package/src/transport.ts CHANGED
@@ -190,6 +190,18 @@ export function buildQueryString(params?: FindParams): string {
190
190
 
191
191
  if (params.searchString) {
192
192
  parts.push(`searchString=${encodeURIComponent(params.searchString)}`);
193
+ if (params.searchExplain) parts.push("searchExplain=true");
194
+ }
195
+
196
+ // The server keys vector search off `vector_search` naming the property and
197
+ // `vector` carrying the embedding as a JSON array; both must be present or
198
+ // it ignores the pair entirely.
199
+ if (params.vectorSearch) {
200
+ const vs = params.vectorSearch;
201
+ parts.push(`vector_search=${encodeURIComponent(vs.property)}`);
202
+ parts.push(`vector=${encodeURIComponent(JSON.stringify(vs.vector))}`);
203
+ if (vs.distance) parts.push(`vector_distance=${encodeURIComponent(vs.distance)}`);
204
+ if (vs.threshold !== undefined) parts.push(`vector_threshold=${encodeURIComponent(String(vs.threshold))}`);
193
205
  }
194
206
 
195
207
  if (params.include && params.include.length > 0) {
@@ -259,6 +271,28 @@ function resolveBaseUrl(configured?: string): string {
259
271
  export function createTransport(config: RebaseClientConfig, environment?: TransportEnvironment): Transport {
260
272
  const fetchFn = config.fetch || globalThis.fetch;
261
273
  const apiPath = config.apiPath || "/api";
274
+
275
+ // `apiPath` is appended to `baseUrl`, so a `baseUrl` that already ends in it
276
+ // builds `/api/api/…` and every request 404s. That was documented on
277
+ // `baseUrl` and left to be discovered at runtime — including by this
278
+ // package's own tests, which configured it that way a dozen times. A 404 on
279
+ // every call looks like a server that is down, not like a doubled path.
280
+ // `storageUrlOrigin` is checked alongside it because `storage.ts` composes
281
+ // it the same way — `${storageUrlOrigin ?? baseUrl}${apiPath}` — and its own
282
+ // docblock carries the same "no path" caveat.
283
+ for (const field of ["baseUrl", "storageUrlOrigin"] as const) {
284
+ const value = config[field];
285
+ if (!value || !apiPath) continue;
286
+ const trimmed = value.replace(/\/+$/, "");
287
+ if (!trimmed.endsWith(apiPath)) continue;
288
+ console.warn(
289
+ `[Rebase] ${field} ${JSON.stringify(value)} already ends with the API path ` +
290
+ `${JSON.stringify(apiPath)}, which is appended to it — requests will go to ` +
291
+ `${trimmed}${apiPath}/… and 404. Pass the origin only ` +
292
+ `(${JSON.stringify(trimmed.slice(0, trimmed.length - apiPath.length) || "/")}), or set ` +
293
+ "`apiPath` if the server really does mount the API one level deeper."
294
+ );
295
+ }
262
296
  let token = config.token;
263
297
  let tokenGetter: (() => Promise<string | null>) | undefined;
264
298
  let onUnauthorizedHandler = config.onUnauthorized;
@@ -291,6 +325,27 @@ export function createTransport(config: RebaseClientConfig, environment?: Transp
291
325
  };
292
326
  }
293
327
 
328
+ /**
329
+ * The refusal for a success status carrying a body this client cannot read.
330
+ *
331
+ * The first 120 characters go in the message because they identify the
332
+ * sender at a glance: `<!doctype html>` says "you are talking to a web
333
+ * server, not to this API" faster than any wording here could.
334
+ *
335
+ * One function for both the first attempt and the post-refresh retry — the
336
+ * retry is a second copy of this whole response-reading path, and copies
337
+ * are how one of them ends up fixed and the other not.
338
+ */
339
+ function unreadableResponse(status: number, text: string): RebaseApiError {
340
+ return new RebaseApiError(
341
+ `The server answered ${status} with a body that is not JSON, so there is nothing to return. ` +
342
+ "This usually means the request reached something other than the Rebase API — a single-page-app " +
343
+ "fallback serving index.html, or a proxy error page — so check the API URL configuration " +
344
+ `(e.g. VITE_API_URL). The body began: ${JSON.stringify(text.slice(0, 120))}`,
345
+ { status, code: "INVALID_JSON_RESPONSE" }
346
+ );
347
+ }
348
+
294
349
  async function request<T = unknown>(path: string, init?: RequestInit): Promise<T> {
295
350
  const url = resolveBaseUrl(config.baseUrl) + apiPath + path;
296
351
 
@@ -322,11 +377,27 @@ headers });
322
377
 
323
378
  const text = await res.text().catch(() => "");
324
379
  let body: Record<string, unknown> = {};
380
+ /**
381
+ * Whether the body was there and could not be read as JSON.
382
+ *
383
+ * On an error status this does not matter — the status is the answer
384
+ * and the message falls back to `statusText`. On a *success* status it
385
+ * is the whole answer, and `{}` was being returned as though the server
386
+ * had sent it: `find()` answered `{}` instead of an array, `getOne()`
387
+ * an empty object, with nothing thrown.
388
+ *
389
+ * The case that produces it is not exotic. Point `VITE_API_URL` at the
390
+ * frontend's own host and `/api/data/posts` lands on the SPA fallback,
391
+ * which answers `200` with `index.html` — so the misconfiguration the
392
+ * 404 branch below spends four lines explaining reaches the caller, in
393
+ * its most common form, as an empty success.
394
+ */
395
+ let unreadableBody = false;
325
396
  if (text) {
326
397
  try {
327
398
  body = JSON.parse(text, rebaseReviver) as Record<string, unknown>;
328
399
  } catch (e) {
329
- // If not valid JSON, fallback
400
+ unreadableBody = true;
330
401
  }
331
402
  }
332
403
 
@@ -359,10 +430,13 @@ headers: retryHeaders });
359
430
  if (retryRes.status === 204) return undefined as T; // SAFETY: HTTP 204 No Content has no body
360
431
  const retryText = await retryRes.text().catch(() => "");
361
432
  let retryBody: Record<string, unknown> = {};
433
+ let retryUnreadable = false;
362
434
  if (retryText) {
363
435
  try {
364
436
  retryBody = JSON.parse(retryText, rebaseReviver);
365
- } catch (e) { /* ignore */ }
437
+ } catch (e) {
438
+ retryUnreadable = true;
439
+ }
366
440
  }
367
441
  if (!retryRes.ok) {
368
442
  let fallbackMessage = retryRes.statusText;
@@ -379,6 +453,7 @@ headers: retryHeaders });
379
453
  }
380
454
  );
381
455
  }
456
+ if (retryUnreadable) throw unreadableResponse(retryRes.status, retryText);
382
457
  return retryBody as T;
383
458
  }
384
459
  }
@@ -399,6 +474,8 @@ headers: retryHeaders });
399
474
  );
400
475
  }
401
476
 
477
+ if (unreadableBody) throw unreadableResponse(res.status, text);
478
+
402
479
  return body as T;
403
480
  }
404
481
 
@@ -0,0 +1,55 @@
1
+ /**
2
+ * The SDK's route to vector search.
3
+ *
4
+ * The Postgres driver has served `vector_search` since vectors landed, but no
5
+ * method on the query builder ever reached it and it appeared in no OpenAPI
6
+ * spec — so the only way to use a shipped feature was to hand-build the URL.
7
+ * These tests pin the wire format the server's parser actually expects.
8
+ */
9
+ import { buildQueryString } from "./transport";
10
+ import type { FindParams } from "@rebasepro/types";
11
+
12
+ const params = (p: FindParams): URLSearchParams =>
13
+ new URLSearchParams(buildQueryString(p).replace(/^\?/, ""));
14
+
15
+ describe("vector search serialization", () => {
16
+ it("sends the property under `vector_search` and the embedding as a JSON array", () => {
17
+ const q = params({ vectorSearch: { property: "embedding", vector: [0.1, -0.2, 0.3] } });
18
+ expect(q.get("vector_search")).toBe("embedding");
19
+ expect(q.get("vector")).toBe("[0.1,-0.2,0.3]");
20
+ });
21
+
22
+ it("omits distance and threshold when not asked for, so the server's defaults stand", () => {
23
+ const q = params({ vectorSearch: { property: "embedding", vector: [1] } });
24
+ expect(q.has("vector_distance")).toBe(false);
25
+ expect(q.has("vector_threshold")).toBe(false);
26
+ });
27
+
28
+ it("sends distance and threshold when given", () => {
29
+ const q = params({
30
+ vectorSearch: { property: "embedding", vector: [1], distance: "l2", threshold: 0.35 }
31
+ });
32
+ expect(q.get("vector_distance")).toBe("l2");
33
+ expect(q.get("vector_threshold")).toBe("0.35");
34
+ });
35
+
36
+ it("sends a threshold of 0, which is a real bound and not an absent one", () => {
37
+ const q = params({ vectorSearch: { property: "embedding", vector: [1], threshold: 0 } });
38
+ expect(q.get("vector_threshold")).toBe("0");
39
+ });
40
+
41
+ it("adds nothing at all when there is no vector search", () => {
42
+ expect(buildQueryString({ limit: 10 })).not.toContain("vector");
43
+ });
44
+
45
+ it("stacks with filters and limit, which the server ANDs before ordering by distance", () => {
46
+ const q = params({
47
+ vectorSearch: { property: "embedding", vector: [0.5] },
48
+ where: { status: ["==", "published"] },
49
+ limit: 5
50
+ });
51
+ expect(q.get("vector_search")).toBe("embedding");
52
+ expect(q.get("limit")).toBe("5");
53
+ expect(buildQueryString({ where: { status: ["==", "published"] } })).toContain("status");
54
+ });
55
+ });
@@ -0,0 +1,97 @@
1
+ import { jest } from "@jest/globals";
2
+ import { createRebaseClient } from "./index";
3
+
4
+ /**
5
+ * Where the realtime socket dials, given a `baseUrl`.
6
+ *
7
+ * The socket URL is derived rather than configured, so every disagreement
8
+ * between how it is derived and where the API actually lives shows up only as
9
+ * realtime not working — never as an error naming a cause.
10
+ */
11
+
12
+ function setWindow(origin: string | undefined) {
13
+ if (origin === undefined) {
14
+ delete (globalThis as never as { window?: unknown }).window;
15
+ return;
16
+ }
17
+ (globalThis as never as { window: unknown }).window = {
18
+ location: { origin, href: origin + "/" }
19
+ };
20
+ }
21
+
22
+ function trackingWebSocket() {
23
+ const opened: string[] = [];
24
+ class FakeWebSocket {
25
+ static readonly OPEN = 1;
26
+ readyState = 0;
27
+ onopen: (() => void) | null = null;
28
+ onclose: (() => void) | null = null;
29
+ onerror: (() => void) | null = null;
30
+ onmessage: (() => void) | null = null;
31
+ constructor(public url: string) { opened.push(url); }
32
+ close() { /* no-op */ }
33
+ send() { /* no-op */ }
34
+ }
35
+ return { FakeWebSocket: FakeWebSocket as unknown as typeof WebSocket, opened };
36
+ }
37
+
38
+ describe("realtime socket URL", () => {
39
+ const originalWebSocket = globalThis.WebSocket;
40
+
41
+ afterEach(() => {
42
+ globalThis.WebSocket = originalWebSocket;
43
+ setWindow(undefined);
44
+ jest.restoreAllMocks();
45
+ });
46
+
47
+ it("keeps the path of a relative baseUrl, as it does for an absolute one", () => {
48
+ // A backend mounted under a path is the reason `baseUrl` accepts one.
49
+ // Resolving the relative form to `.origin` dropped it, so the same
50
+ // deployment dialled two different URLs depending on whether its
51
+ // baseUrl was written as "/backend" or "https://app.example.com/backend".
52
+ const { FakeWebSocket, opened } = trackingWebSocket();
53
+ globalThis.WebSocket = FakeWebSocket;
54
+ setWindow("https://app.example.com");
55
+
56
+ const relative = createRebaseClient({ baseUrl: "/backend" });
57
+ relative.collection("posts").listen!(undefined, () => {});
58
+
59
+ const absolute = createRebaseClient({ baseUrl: "https://app.example.com/backend" });
60
+ absolute.collection("posts").listen!(undefined, () => {});
61
+
62
+ expect(opened[0]).toBe("wss://app.example.com/backend");
63
+ expect(opened[0]).toBe(opened[1]);
64
+ });
65
+
66
+ it("dials the page origin when no baseUrl is set in a browser", () => {
67
+ const { FakeWebSocket, opened } = trackingWebSocket();
68
+ globalThis.WebSocket = FakeWebSocket;
69
+ setWindow("https://app.example.com");
70
+
71
+ const client = createRebaseClient({});
72
+ client.collection("posts").listen!(undefined, () => {});
73
+
74
+ expect(opened[0]).toBe("wss://app.example.com");
75
+ });
76
+
77
+ it("says why realtime is unavailable when no URL could be derived", () => {
78
+ // Node, with a relative baseUrl there is nothing to resolve against.
79
+ // The client silently had no socket, and `realtime.channel()` then
80
+ // blamed `realtime: false` — an option the caller never passed.
81
+ setWindow(undefined);
82
+ const warn = jest.spyOn(console, "warn").mockImplementation(() => {});
83
+ const client = createRebaseClient({ baseUrl: "/backend" });
84
+
85
+ expect(client.ws).toBeUndefined();
86
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining("websocketUrl"));
87
+ expect(() => client.realtime.channel("room")).toThrow(/no WebSocket URL could be derived/i);
88
+ // It may still *suggest* `realtime: false` as the way to make this
89
+ // deliberate; what it must not do is claim that is what happened.
90
+ expect(() => client.realtime.channel("room")).not.toThrow(/disabled on this client/);
91
+ });
92
+
93
+ it("still blames the opt-out when realtime really was switched off", () => {
94
+ const client = createRebaseClient({ baseUrl: "https://api.example.com", realtime: false });
95
+ expect(() => client.realtime.channel("room")).toThrow(/realtime: false/);
96
+ });
97
+ });
package/src/websocket.ts CHANGED
@@ -76,9 +76,11 @@ const CHANNEL_MESSAGE_TYPES = new Set([
76
76
  *
77
77
  * @internal Not a stable app-facing API. `createRebaseClient()` constructs and
78
78
  * manages this internally (exposed as `client.ws`, typed by the minimal
79
- * `RebaseWebSocket` contract in `@rebasepro/types`). It is re-exported from the
80
- * package root only because the `@rebasepro/client-postgres` driver
81
- * instantiates it directly; its surface may change without a major bump.
79
+ * `RebaseWebSocket` contract in `@rebasepro/types`). It stays exported from the
80
+ * package root for the same reason it always was — a data-source driver may
81
+ * instantiate it directly — but nothing in this repo does since
82
+ * `@rebasepro/client-postgres` was removed; its surface may change without a
83
+ * major bump.
82
84
  */
83
85
  export class RebaseWebSocketClient {
84
86
  private websocketUrl: string;
@@ -895,6 +897,22 @@ export class RebaseWebSocketClient {
895
897
  } else {
896
898
  callback.onUpdate(message);
897
899
  }
900
+ return;
901
+ }
902
+
903
+ // An error that matched no waiter used to fall off the end of this
904
+ // method and disappear. Channel frames are the ones that always do:
905
+ // they are fire-and-forget by design, so no `pendingRequests` entry
906
+ // exists to reject and the server's errors about them — RATE_LIMITED,
907
+ // CHANNEL_FORBIDDEN, CHANNEL_HISTORY_WRITE_FAILED — were dropped while
908
+ // `await channel.broadcast(...)` resolved as if it had been sent. A
909
+ // console warning is the floor, not the answer: an `onError` on
910
+ // `RebaseRealtimeChannel` is the shape this should eventually take.
911
+ if (type === "ERROR" || type === "error" || message.error) {
912
+ const { errorMessage, errorCode } = extractMessageError(message);
913
+ console.warn(
914
+ `[Rebase] Realtime error from the server${errorCode ? ` (${errorCode})` : ""}: ${errorMessage}`
915
+ );
898
916
  }
899
917
  }
900
918
 
@@ -1288,6 +1306,9 @@ options }
1288
1306
 
1289
1307
  const obj = val as Record<string, unknown>;
1290
1308
  if (obj.__type === "relation") {
1309
+ // `data` is dropped on purpose: a relation compares by the
1310
+ // reference it holds, not by the row it happens to have loaded.
1311
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1291
1312
  const { data, ...rest } = obj;
1292
1313
  return rest;
1293
1314
  }
@@ -1803,16 +1824,22 @@ onError });
1803
1824
  }
1804
1825
 
1805
1826
  private createCollectionSubscriptionKey(props: FetchCollectionProps): string {
1806
- // Create a deterministic key based on subscription parameters
1827
+ // Derived from the props, not a hand-listed subset of them.
1828
+ //
1829
+ // Two subscriptions share one server subscription when their keys
1830
+ // match, so a field left off the key makes two different queries
1831
+ // collide and hands the second listener the first one's rows. `offset`
1832
+ // and `logical` were both missing: page two of a live list showed page
1833
+ // one, and two views filtered by different `or(...)` groups saw the
1834
+ // same rows. Listing fields by hand is what let that happen, so the key
1835
+ // now covers whatever `FetchCollectionProps` carries.
1836
+ //
1837
+ // `collection` is the exception: it is the whole collection config,
1838
+ // property thunks and all, so it contributes its name as before.
1839
+ const { collection, ...query } = props as FetchCollectionProps & Record<string, unknown>;
1807
1840
  const key = {
1808
- path: props.path,
1809
- filter: props.filter,
1810
- limit: props.limit,
1811
- startAfter: props.startAfter,
1812
- orderBy: props.orderBy,
1813
- order: props.order,
1814
- searchString: props.searchString,
1815
- collection: props.collection?.name
1841
+ ...query,
1842
+ collection: collection?.name
1816
1843
  };
1817
1844
  // Use replacer function (not array) to sort keys at all levels for deterministic output
1818
1845
  return JSON.stringify(key, (_, value) => {