@rebasepro/client 0.0.1-canary.4d4fb3e → 0.0.1-canary.ca2cb6e
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/dist/admin.d.ts +6 -6
- package/dist/auth.d.ts +67 -1
- package/dist/collection.d.ts +3 -3
- package/dist/cron.d.ts +25 -0
- package/dist/cron.test.d.ts +1 -0
- package/dist/index.d.ts +12 -7
- package/dist/index.es.js +523 -128
- package/dist/index.es.js.map +1 -1
- package/dist/index.umd.js +522 -129
- package/dist/index.umd.js.map +1 -1
- package/dist/query_builder.d.ts +3 -3
- package/dist/reviver.d.ts +1 -0
- package/dist/transport.d.ts +5 -5
- package/dist/websocket.d.ts +16 -10
- package/package.json +78 -74
- package/src/admin.ts +12 -12
- package/src/auth.ts +137 -25
- package/src/collection.ts +130 -79
- package/src/cron.test.ts +164 -0
- package/src/cron.ts +62 -0
- package/src/index.ts +39 -26
- package/src/query_builder.ts +7 -8
- package/src/reviver.ts +39 -0
- package/src/storage.ts +38 -38
- package/src/transport.ts +109 -23
- package/src/websocket.ts +104 -42
package/src/transport.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { FindParams as TypesFindParams, FindResponse as TypesFindResponse } from "@rebasepro/types";
|
|
1
|
+
import { FindParams as TypesFindParams, FindResponse as TypesFindResponse, WhereFieldValue } from "@rebasepro/types";
|
|
2
|
+
import { rebaseReviver } from "./reviver";
|
|
2
3
|
|
|
3
4
|
export interface RebaseClientConfig {
|
|
4
|
-
baseUrl
|
|
5
|
+
baseUrl?: string;
|
|
5
6
|
token?: string;
|
|
6
7
|
apiPath?: string;
|
|
7
8
|
fetch?: typeof globalThis.fetch;
|
|
@@ -13,14 +14,14 @@ export interface RebaseClientConfig {
|
|
|
13
14
|
* Re-export from `@rebasepro/types` for backward compatibility.
|
|
14
15
|
*/
|
|
15
16
|
export type FindParams = TypesFindParams;
|
|
16
|
-
export type FindResponse<T> = TypesFindResponse<T extends Record<string,
|
|
17
|
+
export type FindResponse<T> = TypesFindResponse<T extends Record<string, unknown> ? T : Record<string, unknown>>;
|
|
17
18
|
|
|
18
19
|
export class RebaseApiError extends Error {
|
|
19
20
|
status: number;
|
|
20
21
|
code?: string;
|
|
21
|
-
details?:
|
|
22
|
+
details?: unknown;
|
|
22
23
|
|
|
23
|
-
constructor(status: number, message: string, code?: string, details?:
|
|
24
|
+
constructor(status: number, message: string, code?: string, details?: unknown) {
|
|
24
25
|
super(message);
|
|
25
26
|
this.name = "RebaseApiError";
|
|
26
27
|
this.status = status;
|
|
@@ -29,6 +30,59 @@ export class RebaseApiError extends Error {
|
|
|
29
30
|
}
|
|
30
31
|
}
|
|
31
32
|
|
|
33
|
+
/**
|
|
34
|
+
* Maps a short operator alias to the PostgREST-style short code.
|
|
35
|
+
*/
|
|
36
|
+
const OP_MAP: Record<string, string> = {
|
|
37
|
+
"==": "eq",
|
|
38
|
+
"!=": "neq",
|
|
39
|
+
">": "gt",
|
|
40
|
+
">=": "gte",
|
|
41
|
+
"<": "lt",
|
|
42
|
+
"<=": "lte",
|
|
43
|
+
"not-in": "nin",
|
|
44
|
+
"array-contains": "cs",
|
|
45
|
+
"array-contains-any": "csa"
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Normalise a single `WhereFieldValue` into the PostgREST query-string
|
|
50
|
+
* representation the backend expects.
|
|
51
|
+
*
|
|
52
|
+
* Supports:
|
|
53
|
+
* - `null` → `"eq.null"`
|
|
54
|
+
* - `true`/`false` → `"eq.true"` / `"eq.false"`
|
|
55
|
+
* - `42` → `"42"` (plain equality)
|
|
56
|
+
* - `"active"` → `"active"` (plain equality, backward-compat)
|
|
57
|
+
* - `"gte.18"` → `"gte.18"` (pass-through PostgREST string)
|
|
58
|
+
* - `[">=", 18]` → `"gte.18"` (tuple syntax)
|
|
59
|
+
* - `["in", [1,2]]` → `"in.(1,2)"` (tuple with array value)
|
|
60
|
+
* - `["!=", null]` → `"neq.null"`
|
|
61
|
+
*/
|
|
62
|
+
function normalizeWhereValue(value: WhereFieldValue): string {
|
|
63
|
+
// Null → eq.null
|
|
64
|
+
if (value === null) return "eq.null";
|
|
65
|
+
|
|
66
|
+
// Boolean → eq.true / eq.false
|
|
67
|
+
if (typeof value === "boolean") return `eq.${value}`;
|
|
68
|
+
|
|
69
|
+
// Number → plain equality
|
|
70
|
+
if (typeof value === "number") return String(value);
|
|
71
|
+
|
|
72
|
+
// Tuple: [operator, val]
|
|
73
|
+
if (Array.isArray(value) && value.length === 2) {
|
|
74
|
+
const [rawOp, val] = value;
|
|
75
|
+
const op = OP_MAP[rawOp] ?? rawOp;
|
|
76
|
+
|
|
77
|
+
if (val === null) return `${op}.null`;
|
|
78
|
+
if (Array.isArray(val)) return `${op}.(${val.join(",")})`;
|
|
79
|
+
return `${op}.${val}`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// String — pass through (either plain equality value or PostgREST syntax)
|
|
83
|
+
return String(value);
|
|
84
|
+
}
|
|
85
|
+
|
|
32
86
|
export function buildQueryString(params?: FindParams): string {
|
|
33
87
|
if (!params) return "";
|
|
34
88
|
const parts: string[] = [];
|
|
@@ -41,13 +95,18 @@ export function buildQueryString(params?: FindParams): string {
|
|
|
41
95
|
parts.push(`orderBy=${encodeURIComponent(params.orderBy)}`);
|
|
42
96
|
}
|
|
43
97
|
|
|
98
|
+
if (params.searchString) {
|
|
99
|
+
parts.push(`searchString=${encodeURIComponent(params.searchString)}`);
|
|
100
|
+
}
|
|
101
|
+
|
|
44
102
|
if (params.include && params.include.length > 0) {
|
|
45
103
|
parts.push(`include=${encodeURIComponent(params.include.join(","))}`);
|
|
46
104
|
}
|
|
47
105
|
|
|
48
106
|
if (params.where) {
|
|
49
107
|
for (const [field, value] of Object.entries(params.where)) {
|
|
50
|
-
|
|
108
|
+
const normalized = normalizeWhereValue(value as WhereFieldValue);
|
|
109
|
+
parts.push(`${encodeURIComponent(field)}=${encodeURIComponent(normalized)}`);
|
|
51
110
|
}
|
|
52
111
|
}
|
|
53
112
|
|
|
@@ -55,7 +114,7 @@ export function buildQueryString(params?: FindParams): string {
|
|
|
55
114
|
}
|
|
56
115
|
|
|
57
116
|
export interface Transport {
|
|
58
|
-
request: <T =
|
|
117
|
+
request: <T = unknown>(path: string, init?: RequestInit) => Promise<T>;
|
|
59
118
|
setToken: (newToken: string | null) => void;
|
|
60
119
|
setAuthTokenGetter: (getter: () => Promise<string | null>) => void;
|
|
61
120
|
setOnUnauthorized: (handler: () => Promise<boolean>) => void;
|
|
@@ -77,13 +136,14 @@ export function createTransport(config: RebaseClientConfig): Transport {
|
|
|
77
136
|
return {
|
|
78
137
|
"Content-Type": "application/json",
|
|
79
138
|
...(activeToken ? { Authorization: `Bearer ${activeToken}` } : {}),
|
|
80
|
-
...((init?.headers as Record<string, string>) || {})
|
|
139
|
+
...((init?.headers as Record<string, string>) || {})
|
|
81
140
|
};
|
|
82
141
|
}
|
|
83
142
|
|
|
84
|
-
async function request<T =
|
|
85
|
-
const
|
|
86
|
-
|
|
143
|
+
async function request<T = unknown>(path: string, init?: RequestInit): Promise<T> {
|
|
144
|
+
const base = config.baseUrl ? config.baseUrl.replace(/\/$/, "") : "";
|
|
145
|
+
const url = base + apiPath + path;
|
|
146
|
+
|
|
87
147
|
let activeToken = token;
|
|
88
148
|
if (tokenGetter) {
|
|
89
149
|
try {
|
|
@@ -95,7 +155,7 @@ export function createTransport(config: RebaseClientConfig): Transport {
|
|
|
95
155
|
// Ignore error, fallback to static token if any
|
|
96
156
|
}
|
|
97
157
|
}
|
|
98
|
-
|
|
158
|
+
|
|
99
159
|
const headers = getHeaders(activeToken, init);
|
|
100
160
|
|
|
101
161
|
// If passing FormData, we MUST let fetch set the boundary, so remove Content-Type
|
|
@@ -103,11 +163,20 @@ export function createTransport(config: RebaseClientConfig): Transport {
|
|
|
103
163
|
delete (headers as Record<string, string>)["Content-Type"];
|
|
104
164
|
}
|
|
105
165
|
|
|
106
|
-
const res = await fetchFn(url, { ...init,
|
|
166
|
+
const res = await fetchFn(url, { ...init,
|
|
167
|
+
headers });
|
|
107
168
|
|
|
108
169
|
if (res.status === 204) return undefined as unknown as T;
|
|
109
170
|
|
|
110
|
-
const
|
|
171
|
+
const text = await res.text().catch(() => "");
|
|
172
|
+
let body: any = {};
|
|
173
|
+
if (text) {
|
|
174
|
+
try {
|
|
175
|
+
body = JSON.parse(text, rebaseReviver);
|
|
176
|
+
} catch (e) {
|
|
177
|
+
// If not valid JSON, fallback
|
|
178
|
+
}
|
|
179
|
+
}
|
|
111
180
|
|
|
112
181
|
if (res.status === 401 && onUnauthorizedHandler) {
|
|
113
182
|
const retried = await onUnauthorizedHandler();
|
|
@@ -119,18 +188,30 @@ export function createTransport(config: RebaseClientConfig): Transport {
|
|
|
119
188
|
if (fetched !== null && fetched !== undefined) {
|
|
120
189
|
retryToken = fetched;
|
|
121
190
|
}
|
|
122
|
-
} catch (e) {}
|
|
191
|
+
} catch (e) { /* ignore */ }
|
|
123
192
|
}
|
|
124
193
|
const retryHeaders = getHeaders(retryToken, init) as Record<string, string>;
|
|
125
|
-
const retryRes = await fetchFn(url, { ...init,
|
|
194
|
+
const retryRes = await fetchFn(url, { ...init,
|
|
195
|
+
headers: retryHeaders });
|
|
126
196
|
if (retryRes.status === 204) return undefined as unknown as T;
|
|
127
|
-
const
|
|
197
|
+
const retryText = await retryRes.text().catch(() => "");
|
|
198
|
+
let retryBody: any = {};
|
|
199
|
+
if (retryText) {
|
|
200
|
+
try {
|
|
201
|
+
retryBody = JSON.parse(retryText, rebaseReviver);
|
|
202
|
+
} catch (e) { /* ignore */ }
|
|
203
|
+
}
|
|
128
204
|
if (!retryRes.ok) {
|
|
205
|
+
let fallbackMessage = retryRes.statusText;
|
|
206
|
+
if (retryRes.status === 404 && !fallbackMessage) {
|
|
207
|
+
const method = init?.method || "GET";
|
|
208
|
+
fallbackMessage = `Endpoint not found (${method} ${path}). This usually means the collection is not registered on the backend, or the frontend API URL configuration (e.g. VITE_API_URL) is missing or pointing to the wrong host.`;
|
|
209
|
+
}
|
|
129
210
|
throw new RebaseApiError(
|
|
130
211
|
retryRes.status,
|
|
131
|
-
retryBody?.error?.message || retryBody?.message || retryRes.
|
|
212
|
+
retryBody?.error?.message || retryBody?.message || fallbackMessage || `Request failed with status ${retryRes.status}`,
|
|
132
213
|
retryBody?.error?.code || retryBody?.code,
|
|
133
|
-
retryBody?.error?.details || retryBody?.details
|
|
214
|
+
retryBody?.error?.details || retryBody?.details
|
|
134
215
|
);
|
|
135
216
|
}
|
|
136
217
|
return retryBody as T;
|
|
@@ -138,11 +219,16 @@ export function createTransport(config: RebaseClientConfig): Transport {
|
|
|
138
219
|
}
|
|
139
220
|
|
|
140
221
|
if (!res.ok) {
|
|
222
|
+
let fallbackMessage = res.statusText;
|
|
223
|
+
if (res.status === 404 && !fallbackMessage) {
|
|
224
|
+
const method = init?.method || "GET";
|
|
225
|
+
fallbackMessage = `Endpoint not found (${method} ${path}). This usually means the collection is not registered on the backend, or the frontend API URL configuration (e.g. VITE_API_URL) is missing or pointing to the wrong host.`;
|
|
226
|
+
}
|
|
141
227
|
throw new RebaseApiError(
|
|
142
228
|
res.status,
|
|
143
|
-
body?.error?.message || body?.message || res.
|
|
229
|
+
body?.error?.message || body?.message || fallbackMessage || `Request failed with status ${res.status}`,
|
|
144
230
|
body?.error?.code || body?.code,
|
|
145
|
-
body?.error?.details || body?.details
|
|
231
|
+
body?.error?.details || body?.details
|
|
146
232
|
);
|
|
147
233
|
}
|
|
148
234
|
|
|
@@ -154,7 +240,7 @@ export function createTransport(config: RebaseClientConfig): Transport {
|
|
|
154
240
|
setToken(newToken: string | null) { token = newToken || undefined; },
|
|
155
241
|
setAuthTokenGetter(getter: () => Promise<string | null>) { tokenGetter = getter; },
|
|
156
242
|
setOnUnauthorized(handler: () => Promise<boolean>) { onUnauthorizedHandler = handler; },
|
|
157
|
-
get baseUrl() { return config.baseUrl.replace(/\/$/, ""); },
|
|
243
|
+
get baseUrl() { return config.baseUrl ? config.baseUrl.replace(/\/$/, "") : ""; },
|
|
158
244
|
get apiPath() { return apiPath; },
|
|
159
245
|
get fetchFn() { return fetchFn; },
|
|
160
246
|
getHeaders: (init?: RequestInit) => getHeaders(token, init) as Record<string, string>,
|
|
@@ -165,7 +251,7 @@ export function createTransport(config: RebaseClientConfig): Transport {
|
|
|
165
251
|
if (fetched !== null && fetched !== undefined) {
|
|
166
252
|
return fetched;
|
|
167
253
|
}
|
|
168
|
-
} catch (e) {}
|
|
254
|
+
} catch (e) { /* ignore */ }
|
|
169
255
|
}
|
|
170
256
|
return token || null;
|
|
171
257
|
}
|
package/src/websocket.ts
CHANGED
|
@@ -9,8 +9,19 @@ import {
|
|
|
9
9
|
WebSocketErrorPayload,
|
|
10
10
|
CollectionUpdateMessage,
|
|
11
11
|
EntityUpdateMessage,
|
|
12
|
-
TableMetadata
|
|
12
|
+
TableMetadata,
|
|
13
|
+
BranchInfo
|
|
13
14
|
} from "@rebasepro/types";
|
|
15
|
+
import { rebaseReviver } from "./reviver";
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Rehydrate all serialised types inside an Entity's `values`.
|
|
19
|
+
* (Now obsolete as JSON.parse with rebaseReviver handles this globally,
|
|
20
|
+
* kept as pass-through for API compatibility)
|
|
21
|
+
*/
|
|
22
|
+
function rehydrateEntity<M extends Record<string, unknown>>(entity: Entity<M>): Entity<M> {
|
|
23
|
+
return entity;
|
|
24
|
+
}
|
|
14
25
|
|
|
15
26
|
/**
|
|
16
27
|
* Extract error message and code from a WebSocket message payload.
|
|
@@ -25,7 +36,8 @@ function extractMessageError(message: WebSocketMessage): { errorMessage: string;
|
|
|
25
36
|
const errorCode = typeof errPayload === "object"
|
|
26
37
|
? errPayload.code
|
|
27
38
|
: payload?.code;
|
|
28
|
-
return { errorMessage,
|
|
39
|
+
return { errorMessage,
|
|
40
|
+
errorCode };
|
|
29
41
|
}
|
|
30
42
|
|
|
31
43
|
export interface RebaseWebSocketConfig {
|
|
@@ -59,9 +71,9 @@ export class RebaseWebSocketClient {
|
|
|
59
71
|
onError?: (error: Error) => void
|
|
60
72
|
}>();
|
|
61
73
|
|
|
62
|
-
private listeners = new Map<string, Set<
|
|
74
|
+
private listeners = new Map<string, Set<(...args: unknown[]) => void>>();
|
|
63
75
|
|
|
64
|
-
public on(event: "connect" | "disconnect" | "reconnect" | "error", cb:
|
|
76
|
+
public on(event: "connect" | "disconnect" | "reconnect" | "error", cb: (...args: unknown[]) => void) {
|
|
65
77
|
if (!this.listeners.has(event)) {
|
|
66
78
|
this.listeners.set(event, new Set());
|
|
67
79
|
}
|
|
@@ -69,7 +81,7 @@ export class RebaseWebSocketClient {
|
|
|
69
81
|
return () => this.listeners.get(event)!.delete(cb);
|
|
70
82
|
}
|
|
71
83
|
|
|
72
|
-
private emit(event: string, ...args:
|
|
84
|
+
private emit(event: string, ...args: unknown[]) {
|
|
73
85
|
if (this.listeners.has(event)) {
|
|
74
86
|
this.listeners.get(event)!.forEach(cb => cb(...args));
|
|
75
87
|
}
|
|
@@ -105,7 +117,6 @@ export class RebaseWebSocketClient {
|
|
|
105
117
|
private backendToEntityKey = new Map<string, string>();
|
|
106
118
|
|
|
107
119
|
|
|
108
|
-
|
|
109
120
|
private pendingRequests = new Map<string, {
|
|
110
121
|
resolve: (p: unknown) => void;
|
|
111
122
|
reject: (p: Error) => void;
|
|
@@ -115,6 +126,7 @@ export class RebaseWebSocketClient {
|
|
|
115
126
|
private maxReconnectAttempts = 5;
|
|
116
127
|
private isConnected = false;
|
|
117
128
|
private messageQueue: Record<string, unknown>[] = [];
|
|
129
|
+
private reconnectTimeout: ReturnType<typeof setTimeout> | null = null;
|
|
118
130
|
|
|
119
131
|
private isAuthenticated = false;
|
|
120
132
|
private authPromise: Promise<void> | null = null;
|
|
@@ -124,7 +136,7 @@ export class RebaseWebSocketClient {
|
|
|
124
136
|
this.websocketUrl = config.websocketUrl;
|
|
125
137
|
this.getAuthToken = config.getAuthToken;
|
|
126
138
|
this.WebSocketConstructor = config.WebSocket || (typeof WebSocket !== "undefined" ? WebSocket : undefined);
|
|
127
|
-
|
|
139
|
+
|
|
128
140
|
if (!this.WebSocketConstructor) {
|
|
129
141
|
console.warn("WebSocket is not defined in this environment. Realtime subscriptions will not work unless you provide a WebSocket implementation in the config.");
|
|
130
142
|
} else {
|
|
@@ -180,11 +192,14 @@ export class RebaseWebSocketClient {
|
|
|
180
192
|
if (this.isConnected && !this.isAuthenticated && !this.authPromise) {
|
|
181
193
|
console.log("WebSocket auto-authenticating after token getter set");
|
|
182
194
|
this.getAuthToken().then(token => {
|
|
195
|
+
if (!this.ws) return; // Prevent memory leaks / actions after disconnect
|
|
183
196
|
if (token) {
|
|
184
|
-
this.authenticate(token).catch(e =>
|
|
197
|
+
this.authenticate(token).catch(e => {
|
|
198
|
+
if (this.ws) console.warn("WebSocket auto-auth failed:", e);
|
|
199
|
+
});
|
|
185
200
|
}
|
|
186
201
|
}).catch(e => {
|
|
187
|
-
console.warn("WebSocket auto-auth failed:", e);
|
|
202
|
+
if (this.ws) console.warn("WebSocket auto-auth failed:", e);
|
|
188
203
|
});
|
|
189
204
|
}
|
|
190
205
|
}
|
|
@@ -192,7 +207,15 @@ export class RebaseWebSocketClient {
|
|
|
192
207
|
public disconnect(): void {
|
|
193
208
|
this.isAuthenticated = false;
|
|
194
209
|
this.authPromise = null;
|
|
210
|
+
if (this.reconnectTimeout) {
|
|
211
|
+
clearTimeout(this.reconnectTimeout);
|
|
212
|
+
this.reconnectTimeout = null;
|
|
213
|
+
}
|
|
195
214
|
if (this.ws) {
|
|
215
|
+
this.ws.onclose = null; // Prevent reconnect on explicit disconnect
|
|
216
|
+
this.ws.onerror = null; // Prevent errors on explicit disconnect
|
|
217
|
+
this.ws.onopen = null;
|
|
218
|
+
this.ws.onmessage = null;
|
|
196
219
|
this.ws.close();
|
|
197
220
|
this.ws = null;
|
|
198
221
|
}
|
|
@@ -238,7 +261,7 @@ export class RebaseWebSocketClient {
|
|
|
238
261
|
|
|
239
262
|
this.ws!.onmessage = (event) => {
|
|
240
263
|
try {
|
|
241
|
-
const message = JSON.parse(event.data);
|
|
264
|
+
const message = JSON.parse(event.data, rebaseReviver);
|
|
242
265
|
this.handleWebSocketMessage(message);
|
|
243
266
|
} catch (error) {
|
|
244
267
|
console.error("Error parsing WebSocket message:", error);
|
|
@@ -297,7 +320,13 @@ export class RebaseWebSocketClient {
|
|
|
297
320
|
const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000);
|
|
298
321
|
|
|
299
322
|
console.log(`Attempting to reconnect in ${delay}ms (attempt ${this.reconnectAttempts})`);
|
|
300
|
-
|
|
323
|
+
|
|
324
|
+
if (this.reconnectTimeout) {
|
|
325
|
+
clearTimeout(this.reconnectTimeout);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
this.reconnectTimeout = setTimeout(() => {
|
|
329
|
+
this.reconnectTimeout = null;
|
|
301
330
|
this.initWebSocket();
|
|
302
331
|
}, delay);
|
|
303
332
|
}
|
|
@@ -332,7 +361,7 @@ export class RebaseWebSocketClient {
|
|
|
332
361
|
if (subscriptionKey) {
|
|
333
362
|
const collectionSub = this.collectionSubscriptions.get(subscriptionKey);
|
|
334
363
|
if (collectionSub) {
|
|
335
|
-
const incomingEntities = message.entities || [];
|
|
364
|
+
const incomingEntities = (message.entities || []).map((e: Entity) => rehydrateEntity(e));
|
|
336
365
|
|
|
337
366
|
// Structural merge: preserve cached entity references for entities
|
|
338
367
|
// whose values haven't changed. This prevents downstream React components
|
|
@@ -368,7 +397,7 @@ export class RebaseWebSocketClient {
|
|
|
368
397
|
if (subscriptionKey) {
|
|
369
398
|
const collectionSub = this.collectionSubscriptions.get(subscriptionKey);
|
|
370
399
|
if (collectionSub && collectionSub.isInitialDataReceived && collectionSub.latestData) {
|
|
371
|
-
const patchEntity = message.entity;
|
|
400
|
+
const patchEntity = message.entity ? rehydrateEntity(message.entity) : message.entity;
|
|
372
401
|
const patchEntityId = (message as unknown as { entityId: string }).entityId;
|
|
373
402
|
let updated: Entity[];
|
|
374
403
|
|
|
@@ -413,7 +442,7 @@ export class RebaseWebSocketClient {
|
|
|
413
442
|
if (subscriptionKey) {
|
|
414
443
|
const entitySub = this.entitySubscriptions.get(subscriptionKey);
|
|
415
444
|
if (entitySub) {
|
|
416
|
-
const entity = message.entity
|
|
445
|
+
const entity = message.entity ? rehydrateEntity(message.entity) : null;
|
|
417
446
|
// Cache the latest data with optimizations
|
|
418
447
|
entitySub.latestData = entity;
|
|
419
448
|
entitySub.lastUpdated = Date.now();
|
|
@@ -485,7 +514,7 @@ export class RebaseWebSocketClient {
|
|
|
485
514
|
}
|
|
486
515
|
}
|
|
487
516
|
|
|
488
|
-
private async ensureAuthenticated(retryCount
|
|
517
|
+
private async ensureAuthenticated(retryCount = 3): Promise<void> {
|
|
489
518
|
// If already authenticated or no token getter, skip
|
|
490
519
|
if (this.isAuthenticated || !this.getAuthToken) return;
|
|
491
520
|
|
|
@@ -612,31 +641,31 @@ export class RebaseWebSocketClient {
|
|
|
612
641
|
}
|
|
613
642
|
|
|
614
643
|
// Data source methods
|
|
615
|
-
async fetchCollection<M extends Record<string,
|
|
644
|
+
async fetchCollection<M extends Record<string, unknown>>(props: FetchCollectionProps<M>): Promise<Entity<M>[]> {
|
|
616
645
|
const response = await this.sendMessage({
|
|
617
646
|
type: "FETCH_COLLECTION",
|
|
618
647
|
payload: props
|
|
619
648
|
}) as { entities?: Entity<M>[] };
|
|
620
|
-
return response.entities || [];
|
|
649
|
+
return (response.entities || []).map(e => rehydrateEntity(e));
|
|
621
650
|
}
|
|
622
651
|
|
|
623
|
-
async fetchEntity<M extends Record<string,
|
|
652
|
+
async fetchEntity<M extends Record<string, unknown>>(props: FetchEntityProps<M>): Promise<Entity<M> | undefined> {
|
|
624
653
|
const response = await this.sendMessage({
|
|
625
654
|
type: "FETCH_ENTITY",
|
|
626
655
|
payload: props
|
|
627
656
|
}) as { entity?: Entity<M> };
|
|
628
|
-
return response.entity;
|
|
657
|
+
return response.entity ? rehydrateEntity(response.entity) : undefined;
|
|
629
658
|
}
|
|
630
659
|
|
|
631
|
-
async saveEntity<M extends Record<string,
|
|
660
|
+
async saveEntity<M extends Record<string, unknown>>(props: SaveEntityProps<M>): Promise<Entity<M>> {
|
|
632
661
|
const response = await this.sendMessage({
|
|
633
662
|
type: "SAVE_ENTITY",
|
|
634
663
|
payload: props
|
|
635
664
|
}) as { entity: Entity<M> };
|
|
636
|
-
return response.entity;
|
|
665
|
+
return rehydrateEntity(response.entity);
|
|
637
666
|
}
|
|
638
667
|
|
|
639
|
-
async deleteEntity<M extends Record<string,
|
|
668
|
+
async deleteEntity<M extends Record<string, unknown>>(props: DeleteEntityProps<M>): Promise<void> {
|
|
640
669
|
await this.sendMessage({
|
|
641
670
|
type: "DELETE_ENTITY",
|
|
642
671
|
payload: props
|
|
@@ -646,7 +675,8 @@ export class RebaseWebSocketClient {
|
|
|
646
675
|
async executeSql(sql: string, options?: { database?: string, role?: string }): Promise<Record<string, unknown>[]> {
|
|
647
676
|
const response = await this.sendMessage({
|
|
648
677
|
type: "EXECUTE_SQL",
|
|
649
|
-
payload: { sql,
|
|
678
|
+
payload: { sql,
|
|
679
|
+
options }
|
|
650
680
|
}) as { result?: Record<string, unknown>[] };
|
|
651
681
|
return response.result || [];
|
|
652
682
|
}
|
|
@@ -673,7 +703,7 @@ export class RebaseWebSocketClient {
|
|
|
673
703
|
return response.database;
|
|
674
704
|
}
|
|
675
705
|
|
|
676
|
-
async checkUniqueField(path: string, name: string, value:
|
|
706
|
+
async checkUniqueField(path: string, name: string, value: unknown, entityId?: string, collection?: EntityCollection): Promise<boolean> {
|
|
677
707
|
const response = await this.sendMessage({
|
|
678
708
|
type: "CHECK_UNIQUE_FIELD",
|
|
679
709
|
payload: {
|
|
@@ -687,7 +717,7 @@ export class RebaseWebSocketClient {
|
|
|
687
717
|
return response.isUnique;
|
|
688
718
|
}
|
|
689
719
|
|
|
690
|
-
async countEntities<M extends Record<string,
|
|
720
|
+
async countEntities<M extends Record<string, unknown>>(props: FetchCollectionProps<M>): Promise<number> {
|
|
691
721
|
const response = await this.sendMessage({
|
|
692
722
|
type: "COUNT_ENTITIES",
|
|
693
723
|
payload: props
|
|
@@ -708,8 +738,35 @@ export class RebaseWebSocketClient {
|
|
|
708
738
|
type: "FETCH_TABLE_METADATA",
|
|
709
739
|
payload: { tableName }
|
|
710
740
|
}) as { metadata?: TableMetadata };
|
|
711
|
-
|
|
712
|
-
return response.metadata || ({ columns: [],
|
|
741
|
+
|
|
742
|
+
return response.metadata || ({ columns: [],
|
|
743
|
+
foreignKeys: [],
|
|
744
|
+
junctions: [],
|
|
745
|
+
policies: [] } as TableMetadata);
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
async createBranch(name: string, options?: { source?: string }): Promise<BranchInfo> {
|
|
749
|
+
const response = await this.sendMessage({
|
|
750
|
+
type: "CREATE_BRANCH",
|
|
751
|
+
payload: { name,
|
|
752
|
+
options }
|
|
753
|
+
}) as { branch: BranchInfo };
|
|
754
|
+
return response.branch;
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
async deleteBranch(name: string): Promise<void> {
|
|
758
|
+
await this.sendMessage({
|
|
759
|
+
type: "DELETE_BRANCH",
|
|
760
|
+
payload: { name }
|
|
761
|
+
});
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
async listBranches(): Promise<BranchInfo[]> {
|
|
765
|
+
const response = await this.sendMessage({
|
|
766
|
+
type: "LIST_BRANCHES",
|
|
767
|
+
payload: {}
|
|
768
|
+
}) as { branches?: BranchInfo[] };
|
|
769
|
+
return response.branches || [];
|
|
713
770
|
}
|
|
714
771
|
|
|
715
772
|
/**
|
|
@@ -773,28 +830,28 @@ export class RebaseWebSocketClient {
|
|
|
773
830
|
|
|
774
831
|
private normalizeForComparison(val: unknown): unknown {
|
|
775
832
|
if (!val) return val;
|
|
776
|
-
|
|
833
|
+
|
|
777
834
|
if (Array.isArray(val)) {
|
|
778
835
|
return val.map(item => this.normalizeForComparison(item));
|
|
779
836
|
}
|
|
780
|
-
|
|
837
|
+
|
|
781
838
|
if (typeof val === "object") {
|
|
782
839
|
if (val instanceof Date) return val;
|
|
783
840
|
if (val instanceof RegExp) return val;
|
|
784
|
-
|
|
841
|
+
|
|
785
842
|
const obj = val as Record<string, unknown>;
|
|
786
843
|
if (obj.__type === "relation") {
|
|
787
844
|
const { data, ...rest } = obj;
|
|
788
845
|
return rest;
|
|
789
846
|
}
|
|
790
|
-
|
|
847
|
+
|
|
791
848
|
const result: Record<string, unknown> = {};
|
|
792
849
|
for (const [k, v] of Object.entries(obj)) {
|
|
793
850
|
result[k] = this.normalizeForComparison(v);
|
|
794
851
|
}
|
|
795
852
|
return result;
|
|
796
853
|
}
|
|
797
|
-
|
|
854
|
+
|
|
798
855
|
return val;
|
|
799
856
|
}
|
|
800
857
|
|
|
@@ -820,17 +877,18 @@ export class RebaseWebSocketClient {
|
|
|
820
877
|
if (cachedEntity.path === incomingEntity.path) {
|
|
821
878
|
const normCached = this.normalizeForComparison(cachedEntity.values) as Record<string, unknown>;
|
|
822
879
|
const normIncoming = this.normalizeForComparison(incomingEntity.values) as Record<string, unknown>;
|
|
823
|
-
|
|
880
|
+
|
|
824
881
|
if (this.deepEqual(normCached, normIncoming)) {
|
|
825
882
|
return cachedEntity;
|
|
826
883
|
} else {
|
|
827
|
-
// Deep debug: Why did it fail? Let's check which exact property differs
|
|
884
|
+
// Deep debug: Why did it fail? Let's check which exact property differs
|
|
828
885
|
// so the user can see it in their browser console if flashing still occurs.
|
|
829
886
|
const mismatches: Record<string, { cached: unknown, incoming: unknown }> = {};
|
|
830
887
|
const allKeys = new Set([...Object.keys(normCached), ...Object.keys(normIncoming)]);
|
|
831
888
|
for (const key of allKeys) {
|
|
832
889
|
if (!this.deepEqual(normCached[key], normIncoming[key])) {
|
|
833
|
-
mismatches[key] = { cached: normCached[key],
|
|
890
|
+
mismatches[key] = { cached: normCached[key],
|
|
891
|
+
incoming: normIncoming[key] };
|
|
834
892
|
}
|
|
835
893
|
}
|
|
836
894
|
console.log(`[RebaseWS] Row ${incomingEntity.id} refetch mismatch:\n`, JSON.stringify(mismatches, null, 2));
|
|
@@ -841,7 +899,7 @@ export class RebaseWebSocketClient {
|
|
|
841
899
|
}
|
|
842
900
|
|
|
843
901
|
// Subscription methods
|
|
844
|
-
listenCollection<M extends Record<string,
|
|
902
|
+
listenCollection<M extends Record<string, unknown>>(
|
|
845
903
|
props: FetchCollectionProps<M>,
|
|
846
904
|
onUpdate: (entities: Entity[]) => void,
|
|
847
905
|
onError?: (error: Error) => void
|
|
@@ -858,7 +916,8 @@ export class RebaseWebSocketClient {
|
|
|
858
916
|
onUpdate: (entities: Entity[]) => void;
|
|
859
917
|
onError?: (error: Error) => void;
|
|
860
918
|
}>;
|
|
861
|
-
callbackMap.set(callbackId, { onUpdate,
|
|
919
|
+
callbackMap.set(callbackId, { onUpdate,
|
|
920
|
+
onError });
|
|
862
921
|
|
|
863
922
|
// Immediately fire the callback with cached data if available
|
|
864
923
|
if (existingSubscription.latestData !== undefined && existingSubscription.isInitialDataReceived) {
|
|
@@ -895,7 +954,8 @@ export class RebaseWebSocketClient {
|
|
|
895
954
|
onUpdate: (entities: Entity[]) => void;
|
|
896
955
|
onError?: (error: Error) => void;
|
|
897
956
|
}>();
|
|
898
|
-
callbackMap.set(callbackId, { onUpdate,
|
|
957
|
+
callbackMap.set(callbackId, { onUpdate,
|
|
958
|
+
onError });
|
|
899
959
|
|
|
900
960
|
this.collectionSubscriptions.set(subscriptionKey, {
|
|
901
961
|
backendSubscriptionId,
|
|
@@ -937,7 +997,7 @@ export class RebaseWebSocketClient {
|
|
|
937
997
|
};
|
|
938
998
|
}
|
|
939
999
|
|
|
940
|
-
listenEntity<M extends Record<string,
|
|
1000
|
+
listenEntity<M extends Record<string, unknown>>(
|
|
941
1001
|
props: FetchEntityProps<M>,
|
|
942
1002
|
onUpdate: (entity: Entity | null) => void,
|
|
943
1003
|
onError?: (error: Error) => void
|
|
@@ -954,7 +1014,8 @@ export class RebaseWebSocketClient {
|
|
|
954
1014
|
onUpdate: (entity: Entity | null) => void;
|
|
955
1015
|
onError?: (error: Error) => void;
|
|
956
1016
|
}>;
|
|
957
|
-
callbackMap.set(callbackId, { onUpdate,
|
|
1017
|
+
callbackMap.set(callbackId, { onUpdate,
|
|
1018
|
+
onError });
|
|
958
1019
|
|
|
959
1020
|
// Immediately fire the callback with cached data if available
|
|
960
1021
|
if (existingSubscription.latestData !== undefined && existingSubscription.isInitialDataReceived) {
|
|
@@ -991,7 +1052,8 @@ export class RebaseWebSocketClient {
|
|
|
991
1052
|
onUpdate: (entity: Entity | null) => void;
|
|
992
1053
|
onError?: (error: Error) => void;
|
|
993
1054
|
}>();
|
|
994
|
-
callbackMap.set(callbackId, { onUpdate,
|
|
1055
|
+
callbackMap.set(callbackId, { onUpdate,
|
|
1056
|
+
onError });
|
|
995
1057
|
|
|
996
1058
|
this.entitySubscriptions.set(subscriptionKey, {
|
|
997
1059
|
backendSubscriptionId,
|
|
@@ -1099,7 +1161,7 @@ export class RebaseWebSocketClient {
|
|
|
1099
1161
|
// Use replacer function (not array) to sort keys at all levels for deterministic output
|
|
1100
1162
|
return JSON.stringify(key, (_, value) => {
|
|
1101
1163
|
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
1102
|
-
return Object.keys(value).sort().reduce((sorted: Record<string,
|
|
1164
|
+
return Object.keys(value).sort().reduce((sorted: Record<string, unknown>, k) => {
|
|
1103
1165
|
sorted[k] = value[k];
|
|
1104
1166
|
return sorted;
|
|
1105
1167
|
}, {});
|