@rebasepro/client 0.4.0 → 0.6.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.
package/dist/index.umd.js CHANGED
@@ -1,2428 +1,2162 @@
1
1
  (function(global, factory) {
2
- typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("@rebasepro/types"), require("@rebasepro/common"), require("@rebasepro/utils")) : typeof define === "function" && define.amd ? define(["exports", "@rebasepro/types", "@rebasepro/common", "@rebasepro/utils"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global["Rebase Client"] = {}, global.types, global.common, global.utils));
3
- })(this, function(exports2, types, common, utils) {
4
- "use strict";
5
- function rebaseReviver(_key, value) {
6
- if (value && typeof value === "object" && "__type" in value) {
7
- const record = value;
8
- switch (record.__type) {
9
- case "date":
10
- case "Date": {
11
- if (typeof record.value !== "string") {
12
- return value;
13
- }
14
- const date = new Date(record.value);
15
- return isNaN(date.getTime()) ? null : date;
16
- }
17
- case "reference":
18
- case "EntityReference":
19
- return new types.EntityReference({
20
- id: String(record.id),
21
- path: record.path,
22
- driver: record.driver,
23
- databaseId: record.databaseId
24
- });
25
- case "relation":
26
- case "EntityRelation":
27
- return new types.EntityRelation(
28
- record.id,
29
- record.path,
30
- record.data
31
- );
32
- case "GeoPoint":
33
- return new types.GeoPoint(record.latitude, record.longitude);
34
- case "Vector":
35
- return new types.Vector(record.value);
36
- default:
37
- return value;
38
- }
39
- }
40
- return value;
41
- }
42
- class RebaseApiError extends Error {
43
- status;
44
- code;
45
- details;
46
- constructor(status, message, code, details) {
47
- super(message);
48
- this.name = "RebaseApiError";
49
- this.status = status;
50
- this.code = code;
51
- this.details = details;
52
- }
53
- }
54
- const OP_MAP = {
55
- "==": "eq",
56
- "!=": "neq",
57
- ">": "gt",
58
- ">=": "gte",
59
- "<": "lt",
60
- "<=": "lte",
61
- "not-in": "nin",
62
- "array-contains": "cs",
63
- "array-contains-any": "csa"
64
- };
65
- function normalizeWhereValue(value) {
66
- if (value === null) return "eq.null";
67
- if (typeof value === "boolean") return `eq.${value}`;
68
- if (typeof value === "number") return String(value);
69
- if (Array.isArray(value)) {
70
- const conditions = Array.isArray(value[0]) ? value : [value];
71
- const [rawOp, val] = conditions[0] || [];
72
- if (rawOp) {
73
- const op = OP_MAP[rawOp] ?? rawOp;
74
- if (val === null) return `${op}.null`;
75
- if (Array.isArray(val)) return `${op}.(${val.join(",")})`;
76
- return `${op}.${val}`;
77
- }
78
- }
79
- return String(value);
80
- }
81
- function serializeLogicalCondition(cond) {
82
- if ("type" in cond) {
83
- const sub = cond.conditions.map(serializeLogicalCondition).join(",");
84
- return `${cond.type}(${sub})`;
85
- } else {
86
- const op = OP_MAP[cond.operator] ?? cond.operator;
87
- let formattedValue = cond.value;
88
- if (Array.isArray(cond.value)) {
89
- formattedValue = `(${cond.value.join(",")})`;
90
- } else if (cond.value === null) {
91
- formattedValue = "null";
92
- }
93
- return `${cond.column}.${op}.${formattedValue}`;
94
- }
95
- }
96
- function buildQueryString(params) {
97
- if (!params) return "";
98
- const parts = [];
99
- if (params.limit != null) parts.push(`limit=${params.limit}`);
100
- if (params.offset != null) parts.push(`offset=${params.offset}`);
101
- if (params.page != null) parts.push(`page=${params.page}`);
102
- if (params.orderBy) {
103
- parts.push(`orderBy=${encodeURIComponent(params.orderBy)}`);
104
- }
105
- if (params.searchString) {
106
- parts.push(`searchString=${encodeURIComponent(params.searchString)}`);
107
- }
108
- if (params.include && params.include.length > 0) {
109
- parts.push(`include=${encodeURIComponent(params.include.join(","))}`);
110
- }
111
- if (params.logical) {
112
- const root = params.logical;
113
- const serialized = root.conditions.map(serializeLogicalCondition).join(",");
114
- parts.push(`${root.type}=${encodeURIComponent(`(${serialized})`)}`);
115
- }
116
- if (params.where) {
117
- for (const [field, value] of Object.entries(params.where)) {
118
- if (Array.isArray(value) && value.length > 0 && Array.isArray(value[0])) {
119
- for (const subVal of value) {
120
- const normalized = normalizeWhereValue(subVal);
121
- parts.push(`${encodeURIComponent(field)}=${encodeURIComponent(normalized)}`);
122
- }
123
- } else {
124
- const normalized = normalizeWhereValue(value);
125
- parts.push(`${encodeURIComponent(field)}=${encodeURIComponent(normalized)}`);
126
- }
127
- }
128
- }
129
- return parts.length > 0 ? "?" + parts.join("&") : "";
130
- }
131
- function createTransport(config) {
132
- const fetchFn = config.fetch || globalThis.fetch;
133
- const apiPath = config.apiPath || "/api";
134
- let token = config.token;
135
- let tokenGetter;
136
- let onUnauthorizedHandler = config.onUnauthorized;
137
- function getHeaders(activeToken, init) {
138
- return {
139
- "Content-Type": "application/json",
140
- ...activeToken ? { Authorization: `Bearer ${activeToken}` } : {},
141
- ...init?.headers || {}
142
- };
143
- }
144
- async function request(path, init) {
145
- const base = config.baseUrl ? config.baseUrl.replace(/\/$/, "") : "";
146
- const url = base + apiPath + path;
147
- let activeToken = token;
148
- if (tokenGetter) {
149
- try {
150
- const fetched = await tokenGetter();
151
- if (fetched !== null && fetched !== void 0) {
152
- activeToken = fetched;
153
- }
154
- } catch (e) {
155
- }
156
- }
157
- const headers = getHeaders(activeToken, init);
158
- if (init?.body instanceof FormData) {
159
- delete headers["Content-Type"];
160
- }
161
- const res = await fetchFn(url, {
162
- ...init,
163
- headers
164
- });
165
- if (res.status === 204) return void 0;
166
- const text = await res.text().catch(() => "");
167
- let body = {};
168
- if (text) {
169
- try {
170
- body = JSON.parse(text, rebaseReviver);
171
- } catch (e) {
172
- }
173
- }
174
- const getErrorField = (obj, field) => {
175
- const err = obj?.error;
176
- if (err && typeof err === "object" && err !== null && field in err) {
177
- return err[field];
178
- }
179
- return obj?.[field];
180
- };
181
- if (res.status === 401 && onUnauthorizedHandler) {
182
- const retried = await onUnauthorizedHandler();
183
- if (retried) {
184
- let retryToken = token;
185
- if (tokenGetter) {
186
- try {
187
- const fetched = await tokenGetter();
188
- if (fetched !== null && fetched !== void 0) {
189
- retryToken = fetched;
190
- }
191
- } catch (e) {
192
- }
193
- }
194
- const retryHeaders = getHeaders(retryToken, init);
195
- const retryRes = await fetchFn(url, {
196
- ...init,
197
- headers: retryHeaders
198
- });
199
- if (retryRes.status === 204) return void 0;
200
- const retryText = await retryRes.text().catch(() => "");
201
- let retryBody = {};
202
- if (retryText) {
203
- try {
204
- retryBody = JSON.parse(retryText, rebaseReviver);
205
- } catch (e) {
206
- }
207
- }
208
- if (!retryRes.ok) {
209
- let fallbackMessage = retryRes.statusText;
210
- if (retryRes.status === 404 && !fallbackMessage) {
211
- const method = init?.method || "GET";
212
- 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.`;
213
- }
214
- throw new RebaseApiError(
215
- retryRes.status,
216
- String(getErrorField(retryBody, "message") || fallbackMessage || `Request failed with status ${retryRes.status}`),
217
- getErrorField(retryBody, "code"),
218
- getErrorField(retryBody, "details")
219
- );
220
- }
221
- return retryBody;
222
- }
223
- }
224
- if (!res.ok) {
225
- let fallbackMessage = res.statusText;
226
- if (res.status === 404 && !fallbackMessage) {
227
- const method = init?.method || "GET";
228
- 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.`;
229
- }
230
- throw new RebaseApiError(
231
- res.status,
232
- String(getErrorField(body, "message") || fallbackMessage || `Request failed with status ${res.status}`),
233
- getErrorField(body, "code"),
234
- getErrorField(body, "details")
235
- );
236
- }
237
- return body;
238
- }
239
- return {
240
- request,
241
- setToken(newToken) {
242
- token = newToken || void 0;
243
- },
244
- setAuthTokenGetter(getter) {
245
- tokenGetter = getter;
246
- },
247
- setOnUnauthorized(handler) {
248
- onUnauthorizedHandler = handler;
249
- },
250
- get baseUrl() {
251
- return config.baseUrl ? config.baseUrl.replace(/\/$/, "") : "";
252
- },
253
- get apiPath() {
254
- return apiPath;
255
- },
256
- get fetchFn() {
257
- return fetchFn;
258
- },
259
- getHeaders: (init) => getHeaders(token, init),
260
- resolveToken: async () => {
261
- if (tokenGetter) {
262
- try {
263
- const fetched = await tokenGetter();
264
- if (fetched !== null && fetched !== void 0) {
265
- return fetched;
266
- }
267
- } catch (e) {
268
- }
269
- }
270
- return token || null;
271
- }
272
- };
273
- }
274
- function createMemoryStorage() {
275
- const store = {};
276
- return {
277
- getItem(key) {
278
- return store[key] ?? null;
279
- },
280
- setItem(key, value) {
281
- store[key] = value;
282
- },
283
- removeItem(key) {
284
- delete store[key];
285
- }
286
- };
287
- }
288
- function detectStorage() {
289
- try {
290
- if (typeof localStorage !== "undefined") {
291
- localStorage.setItem("__rebase_test__", "1");
292
- localStorage.removeItem("__rebase_test__");
293
- return localStorage;
294
- }
295
- } catch (e) {
296
- }
297
- return createMemoryStorage();
298
- }
299
- function createAuth(transport, options) {
300
- const opts = options || {};
301
- const storage = opts.storage || detectStorage();
302
- const authPath = opts.authPath || "/auth";
303
- const autoRefresh = opts.autoRefresh !== false;
304
- const persistSession = opts.persistSession !== false;
305
- const STORAGE_KEY = "rebase_auth";
306
- const REFRESH_BUFFER_MS = 12e4;
307
- let currentSession = null;
308
- const listeners = /* @__PURE__ */ new Set();
309
- let refreshTimeout = null;
310
- function authUrl(endpoint) {
311
- return transport.baseUrl + transport.apiPath + authPath + endpoint;
312
- }
313
- function getFetch() {
314
- return transport.fetchFn || globalThis.fetch;
315
- }
316
- function throwApiError(status, body, statusText) {
317
- throw new RebaseApiError(
318
- status,
319
- body?.error?.message || body?.message || statusText,
320
- body?.error?.code || body?.code,
321
- body?.error?.details || body?.details
322
- );
323
- }
324
- function emit(event, session) {
325
- for (const fn of listeners) {
326
- try {
327
- fn(event, session);
328
- } catch (e) {
329
- }
330
- }
331
- }
332
- function saveSession(session) {
333
- if (!persistSession) return;
334
- try {
335
- storage.setItem(STORAGE_KEY, JSON.stringify(session));
336
- } catch (e) {
337
- }
338
- }
339
- function clearStoredSession() {
340
- try {
341
- storage.removeItem(STORAGE_KEY);
342
- } catch (e) {
343
- }
344
- }
345
- function loadStoredSession() {
346
- try {
347
- const raw = storage.getItem(STORAGE_KEY);
348
- if (raw) return JSON.parse(raw);
349
- } catch (e) {
350
- }
351
- return null;
352
- }
353
- function scheduleRefresh(expiresAt) {
354
- if (refreshTimeout) clearTimeout(refreshTimeout);
355
- if (!autoRefresh) return;
356
- const delay = expiresAt - REFRESH_BUFFER_MS - Date.now();
357
- if (delay <= 0) {
358
- refreshSession().catch(() => signOut());
359
- return;
360
- }
361
- refreshTimeout = setTimeout(async () => {
362
- try {
363
- await refreshSession();
364
- } catch (e) {
365
- signOut();
366
- }
367
- }, delay);
368
- }
369
- function handleAuthResponse(data, event) {
370
- const session = {
371
- accessToken: data.tokens.accessToken,
372
- refreshToken: data.tokens.refreshToken,
373
- expiresAt: data.tokens.accessTokenExpiresAt,
374
- user: data.user
375
- };
376
- currentSession = session;
377
- saveSession(session);
378
- transport.setToken(session.accessToken);
379
- scheduleRefresh(session.expiresAt);
380
- emit(event, session);
381
- return session;
382
- }
383
- async function signInWithEmail(email, password) {
384
- const fetchFn = getFetch();
385
- const res = await fetchFn(authUrl("/login"), {
386
- method: "POST",
387
- headers: { "Content-Type": "application/json" },
388
- body: JSON.stringify({
389
- email,
390
- password
391
- })
392
- });
393
- const body = await res.json().catch(() => ({}));
394
- if (!res.ok) throwApiError(res.status, body, res.statusText);
395
- const session = handleAuthResponse(body, "SIGNED_IN");
396
- return {
397
- user: session.user,
398
- accessToken: session.accessToken,
399
- refreshToken: session.refreshToken
400
- };
401
- }
402
- async function signUp(email, password, displayName) {
403
- const fetchFn = getFetch();
404
- const payload = {
405
- email,
406
- password
407
- };
408
- if (displayName !== void 0) payload.displayName = displayName;
409
- const res = await fetchFn(authUrl("/register"), {
410
- method: "POST",
411
- headers: { "Content-Type": "application/json" },
412
- body: JSON.stringify(payload)
413
- });
414
- const body = await res.json().catch(() => ({}));
415
- if (!res.ok) throwApiError(res.status, body, res.statusText);
416
- const session = handleAuthResponse(body, "SIGNED_IN");
417
- return {
418
- user: session.user,
419
- accessToken: session.accessToken,
420
- refreshToken: session.refreshToken
421
- };
422
- }
423
- async function signInWithGoogle(payload) {
424
- const fetchFn = getFetch();
425
- const res = await fetchFn(authUrl("/google"), {
426
- method: "POST",
427
- headers: { "Content-Type": "application/json" },
428
- body: JSON.stringify(payload)
429
- });
430
- const responseBody = await res.json().catch(() => ({}));
431
- if (!res.ok) throwApiError(res.status, responseBody, res.statusText);
432
- const session = handleAuthResponse(responseBody, "SIGNED_IN");
433
- return { user: session.user, accessToken: session.accessToken, refreshToken: session.refreshToken };
434
- }
435
- async function signInWithLinkedin(code, redirectUri) {
436
- const fetchFn = getFetch();
437
- const res = await fetchFn(authUrl("/linkedin"), {
438
- method: "POST",
439
- headers: { "Content-Type": "application/json" },
440
- body: JSON.stringify({
441
- code,
442
- redirectUri
443
- })
444
- });
445
- const body = await res.json().catch(() => ({}));
446
- if (!res.ok) throwApiError(res.status, body, res.statusText);
447
- const session = handleAuthResponse(body, "SIGNED_IN");
448
- return {
449
- user: session.user,
450
- accessToken: session.accessToken,
451
- refreshToken: session.refreshToken
452
- };
453
- }
454
- async function signInWithOAuth(providerId, payload) {
455
- const fetchFn = getFetch();
456
- const res = await fetchFn(authUrl(`/${providerId}`), {
457
- method: "POST",
458
- headers: { "Content-Type": "application/json" },
459
- body: JSON.stringify(payload)
460
- });
461
- const body = await res.json().catch(() => ({}));
462
- if (!res.ok) throwApiError(res.status, body, res.statusText);
463
- const session = handleAuthResponse(body, "SIGNED_IN");
464
- return {
465
- user: session.user,
466
- accessToken: session.accessToken,
467
- refreshToken: session.refreshToken
468
- };
469
- }
470
- async function signInWithGitHub(code, redirectUri) {
471
- return signInWithOAuth("github", {
472
- code,
473
- redirectUri
474
- });
475
- }
476
- async function signInWithMicrosoft(code, redirectUri) {
477
- return signInWithOAuth("microsoft", {
478
- code,
479
- redirectUri
480
- });
481
- }
482
- async function signInWithApple(code, redirectUri, user) {
483
- return signInWithOAuth("apple", {
484
- code,
485
- redirectUri,
486
- user
487
- });
488
- }
489
- async function signInWithFacebook(code, redirectUri) {
490
- return signInWithOAuth("facebook", {
491
- code,
492
- redirectUri
493
- });
494
- }
495
- async function signInWithTwitter(code, redirectUri, codeVerifier) {
496
- return signInWithOAuth("twitter", {
497
- code,
498
- redirectUri,
499
- codeVerifier
500
- });
501
- }
502
- async function signInWithDiscord(code, redirectUri) {
503
- return signInWithOAuth("discord", {
504
- code,
505
- redirectUri
506
- });
507
- }
508
- async function signInWithGitLab(code, redirectUri) {
509
- return signInWithOAuth("gitlab", {
510
- code,
511
- redirectUri
512
- });
513
- }
514
- async function signInWithBitbucket(code, redirectUri) {
515
- return signInWithOAuth("bitbucket", {
516
- code,
517
- redirectUri
518
- });
519
- }
520
- async function signInWithSlack(code, redirectUri) {
521
- return signInWithOAuth("slack", {
522
- code,
523
- redirectUri
524
- });
525
- }
526
- async function signInWithSpotify(code, redirectUri) {
527
- return signInWithOAuth("spotify", {
528
- code,
529
- redirectUri
530
- });
531
- }
532
- async function signOut() {
533
- const fetchFn = getFetch();
534
- try {
535
- if (currentSession?.refreshToken) {
536
- await fetchFn(authUrl("/logout"), {
537
- method: "POST",
538
- headers: { "Content-Type": "application/json" },
539
- body: JSON.stringify({ refreshToken: currentSession.refreshToken })
540
- });
541
- }
542
- } catch (e) {
543
- }
544
- currentSession = null;
545
- clearStoredSession();
546
- if (refreshTimeout) {
547
- clearTimeout(refreshTimeout);
548
- refreshTimeout = null;
549
- }
550
- transport.setToken(null);
551
- emit("SIGNED_OUT", null);
552
- }
553
- async function refreshSession() {
554
- if (!currentSession?.refreshToken) {
555
- throw new Error("No active session to refresh");
556
- }
557
- const fetchFn = getFetch();
558
- const res = await fetchFn(authUrl("/refresh"), {
559
- method: "POST",
560
- headers: { "Content-Type": "application/json" },
561
- body: JSON.stringify({ refreshToken: currentSession.refreshToken })
562
- });
563
- const body = await res.json().catch(() => ({}));
564
- if (!res.ok) throwApiError(res.status, body, res.statusText);
565
- const session = {
566
- accessToken: body.tokens.accessToken,
567
- refreshToken: body.tokens.refreshToken,
568
- expiresAt: body.tokens.accessTokenExpiresAt,
569
- user: currentSession.user
570
- };
571
- currentSession = session;
572
- saveSession(session);
573
- transport.setToken(session.accessToken);
574
- scheduleRefresh(session.expiresAt);
575
- emit("TOKEN_REFRESHED", session);
576
- return session;
577
- }
578
- async function getUser() {
579
- const data = await transport.request(authPath + "/me", { method: "GET" });
580
- return data.user;
581
- }
582
- async function updateUser(updates) {
583
- const data = await transport.request(authPath + "/me", {
584
- method: "PATCH",
585
- body: JSON.stringify(updates)
586
- });
587
- if (currentSession) {
588
- currentSession = {
589
- ...currentSession,
590
- user: data.user
591
- };
592
- saveSession(currentSession);
593
- emit("USER_UPDATED", currentSession);
594
- }
595
- return data.user;
596
- }
597
- async function resetPasswordForEmail(email) {
598
- const fetchFn = getFetch();
599
- const res = await fetchFn(authUrl("/forgot-password"), {
600
- method: "POST",
601
- headers: { "Content-Type": "application/json" },
602
- body: JSON.stringify({ email })
603
- });
604
- const body = await res.json().catch(() => ({}));
605
- if (!res.ok) throwApiError(res.status, body, res.statusText);
606
- return body;
607
- }
608
- async function resetPassword(token, password) {
609
- const fetchFn = getFetch();
610
- const res = await fetchFn(authUrl("/reset-password"), {
611
- method: "POST",
612
- headers: { "Content-Type": "application/json" },
613
- body: JSON.stringify({
614
- token,
615
- password
616
- })
617
- });
618
- const body = await res.json().catch(() => ({}));
619
- if (!res.ok) throwApiError(res.status, body, res.statusText);
620
- return body;
621
- }
622
- async function changePassword(oldPassword, newPassword) {
623
- return transport.request(authPath + "/change-password", {
624
- method: "POST",
625
- body: JSON.stringify({
626
- oldPassword,
627
- newPassword
628
- })
629
- });
630
- }
631
- async function sendVerificationEmail() {
632
- return transport.request(authPath + "/send-verification", {
633
- method: "POST"
634
- });
635
- }
636
- async function verifyEmail(token) {
637
- const fetchFn = getFetch();
638
- const res = await fetchFn(authUrl("/verify-email?token=" + encodeURIComponent(token)), {
639
- method: "GET",
640
- headers: { "Content-Type": "application/json" }
641
- });
642
- const body = await res.json().catch(() => ({}));
643
- if (!res.ok) throwApiError(res.status, body, res.statusText);
644
- return body;
645
- }
646
- async function getSessions() {
647
- const data = await transport.request(authPath + "/sessions", { method: "GET" });
648
- return data.sessions;
649
- }
650
- async function revokeSession(sessionId) {
651
- return transport.request(authPath + "/sessions/" + encodeURIComponent(sessionId), {
652
- method: "DELETE"
653
- });
654
- }
655
- async function revokeAllSessions() {
656
- const result = await transport.request(authPath + "/sessions", {
657
- method: "DELETE"
658
- });
659
- currentSession = null;
660
- clearStoredSession();
661
- if (refreshTimeout) {
662
- clearTimeout(refreshTimeout);
663
- refreshTimeout = null;
664
- }
665
- transport.setToken(null);
666
- emit("SIGNED_OUT", null);
667
- return result;
668
- }
669
- async function getAuthConfig() {
670
- const fetchFn = getFetch();
671
- const res = await fetchFn(authUrl("/config"), {
672
- method: "GET",
673
- headers: { "Content-Type": "application/json" }
674
- });
675
- const body = await res.json().catch(() => ({}));
676
- if (!res.ok) throwApiError(res.status, body, res.statusText);
677
- return body;
678
- }
679
- function getSession() {
680
- return currentSession;
681
- }
682
- function onAuthStateChange(callback) {
683
- listeners.add(callback);
684
- return () => listeners.delete(callback);
685
- }
686
- if (persistSession) {
687
- const stored = loadStoredSession();
688
- if (stored && stored.accessToken && stored.refreshToken) {
689
- if (stored.expiresAt > Date.now()) {
690
- currentSession = stored;
691
- transport.setToken(stored.accessToken);
692
- scheduleRefresh(stored.expiresAt);
693
- } else if (stored.refreshToken) {
694
- currentSession = stored;
695
- refreshSession().catch(() => {
696
- currentSession = null;
697
- clearStoredSession();
698
- transport.setToken(null);
699
- });
700
- }
701
- }
702
- }
703
- return {
704
- signInWithEmail,
705
- signUp,
706
- signInWithGoogle,
707
- signInWithLinkedin,
708
- signInWithOAuth,
709
- signInWithGitHub,
710
- signInWithMicrosoft,
711
- signInWithApple,
712
- signInWithFacebook,
713
- signInWithTwitter,
714
- signInWithDiscord,
715
- signInWithGitLab,
716
- signInWithBitbucket,
717
- signInWithSlack,
718
- signInWithSpotify,
719
- signOut,
720
- refreshSession,
721
- getUser,
722
- updateUser,
723
- resetPasswordForEmail,
724
- resetPassword,
725
- changePassword,
726
- sendVerificationEmail,
727
- verifyEmail,
728
- getSessions,
729
- revokeSession,
730
- revokeAllSessions,
731
- getAuthConfig,
732
- getSession,
733
- onAuthStateChange
734
- };
735
- }
736
- function createCookieStorage(options = {}) {
737
- const defaultOptions = {
738
- path: "/",
739
- sameSite: "Lax",
740
- ...options
741
- };
742
- return {
743
- getItem(key) {
744
- if (typeof document === "undefined") return null;
745
- const nameEQ = encodeURIComponent(key) + "=";
746
- const ca = document.cookie.split(";");
747
- for (let i = 0; i < ca.length; i++) {
748
- let c = ca[i];
749
- while (c.charAt(0) === " ") c = c.substring(1, c.length);
750
- if (c.indexOf(nameEQ) === 0) {
751
- return decodeURIComponent(c.substring(nameEQ.length, c.length));
752
- }
753
- }
754
- return null;
755
- },
756
- setItem(key, value) {
757
- if (typeof document === "undefined") return;
758
- let cookieStr = `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
759
- if (defaultOptions.path) {
760
- cookieStr += `; path=${defaultOptions.path}`;
761
- }
762
- if (defaultOptions.domain) {
763
- cookieStr += `; domain=${defaultOptions.domain}`;
764
- }
765
- if (defaultOptions.maxAge !== void 0) {
766
- cookieStr += `; max-age=${defaultOptions.maxAge}`;
767
- } else {
768
- cookieStr += `; max-age=${365 * 24 * 60 * 60}`;
769
- }
770
- if (defaultOptions.secure) {
771
- cookieStr += "; secure";
772
- }
773
- if (defaultOptions.sameSite) {
774
- cookieStr += `; samesite=${defaultOptions.sameSite}`;
775
- }
776
- document.cookie = cookieStr;
777
- },
778
- removeItem(key) {
779
- if (typeof document === "undefined") return;
780
- let cookieStr = `${encodeURIComponent(key)}=; path=${defaultOptions.path || "/"}; max-age=-1`;
781
- if (defaultOptions.domain) {
782
- cookieStr += `; domain=${defaultOptions.domain}`;
783
- }
784
- document.cookie = cookieStr;
785
- }
786
- };
787
- }
788
- function createAdmin(transport, options) {
789
- const opts = options || {};
790
- const adminPath = opts.adminPath || "/admin";
791
- async function listUsers() {
792
- return transport.request(adminPath + "/users", { method: "GET" });
793
- }
794
- async function listUsersPaginated(options2) {
795
- const params = new URLSearchParams();
796
- if (options2?.limit !== void 0) params.set("limit", String(options2.limit));
797
- if (options2?.offset !== void 0) params.set("offset", String(options2.offset));
798
- if (options2?.search) params.set("search", options2.search);
799
- if (options2?.orderBy) params.set("orderBy", options2.orderBy);
800
- if (options2?.orderDir) params.set("orderDir", options2.orderDir);
801
- const qs = params.toString();
802
- return transport.request(
803
- adminPath + "/users" + (qs ? "?" + qs : ""),
804
- { method: "GET" }
805
- );
806
- }
807
- async function getUser(userId) {
808
- return transport.request(adminPath + "/users/" + encodeURIComponent(userId), { method: "GET" });
809
- }
810
- async function createUser(data) {
811
- return transport.request(adminPath + "/users", {
812
- method: "POST",
813
- body: JSON.stringify(data)
814
- });
815
- }
816
- async function updateUser(userId, data) {
817
- return transport.request(adminPath + "/users/" + encodeURIComponent(userId), {
818
- method: "PUT",
819
- body: JSON.stringify(data)
820
- });
821
- }
822
- async function deleteUser(userId) {
823
- return transport.request(adminPath + "/users/" + encodeURIComponent(userId), {
824
- method: "DELETE"
825
- });
826
- }
827
- async function bootstrap() {
828
- return transport.request(adminPath + "/bootstrap", {
829
- method: "POST"
830
- });
831
- }
832
- return {
833
- listUsers,
834
- listUsersPaginated,
835
- getUser,
836
- createUser,
837
- updateUser,
838
- deleteUser,
839
- bootstrap
840
- };
841
- }
842
- function createCron(transport, options) {
843
- const cronPath = options?.cronPath || "/cron";
844
- async function listJobs() {
845
- return transport.request(cronPath, { method: "GET" });
846
- }
847
- async function getJob(jobId) {
848
- return transport.request(
849
- cronPath + "/" + encodeURIComponent(jobId),
850
- { method: "GET" }
851
- );
852
- }
853
- async function triggerJob(jobId) {
854
- return transport.request(
855
- cronPath + "/" + encodeURIComponent(jobId) + "/trigger",
856
- { method: "POST" }
857
- );
858
- }
859
- async function getJobLogs(jobId, options2) {
860
- const params = new URLSearchParams();
861
- if (options2?.limit !== void 0) params.set("limit", String(options2.limit));
862
- const qs = params.toString();
863
- return transport.request(
864
- cronPath + "/" + encodeURIComponent(jobId) + "/logs" + (qs ? "?" + qs : ""),
865
- { method: "GET" }
866
- );
867
- }
868
- async function toggleJob(jobId, enabled) {
869
- return transport.request(
870
- cronPath + "/" + encodeURIComponent(jobId),
871
- {
872
- method: "PUT",
873
- body: JSON.stringify({ enabled })
874
- }
875
- );
876
- }
877
- return {
878
- listJobs,
879
- getJob,
880
- triggerJob,
881
- getJobLogs,
882
- toggleJob
883
- };
884
- }
885
- function parseWhereFilter(where) {
886
- if (!where) return void 0;
887
- const filters = {};
888
- const OP_TO_FILTER = {
889
- "eq": "==",
890
- "neq": "!=",
891
- "gt": ">",
892
- "gte": ">=",
893
- "lt": "<",
894
- "lte": "<=",
895
- "==": "==",
896
- "!=": "!=",
897
- ">": ">",
898
- ">=": ">=",
899
- "<": "<",
900
- "<=": "<=",
901
- "in": "in",
902
- "nin": "not-in",
903
- "not-in": "not-in",
904
- "cs": "array-contains",
905
- "csa": "array-contains-any",
906
- "array-contains": "array-contains",
907
- "array-contains-any": "array-contains-any"
908
- };
909
- const parseSingle = (rawValue, fieldKey) => {
910
- if (rawValue === null) return ["==", null];
911
- if (typeof rawValue === "boolean") return ["==", rawValue];
912
- if (typeof rawValue === "number") return ["==", rawValue];
913
- if (Array.isArray(rawValue) && rawValue.length === 2 && typeof rawValue[0] === "string") {
914
- const [rawOp, val] = rawValue;
915
- return [OP_TO_FILTER[rawOp] ?? "==", val];
916
- }
917
- const value = String(rawValue);
918
- const dotIndex = value.indexOf(".");
919
- if (dotIndex > 0) {
920
- const opStr = value.substring(0, dotIndex);
921
- const valStr = value.substring(dotIndex + 1);
922
- let op = "==";
923
- let val = valStr;
924
- switch (opStr) {
925
- case "eq":
926
- op = "==";
927
- break;
928
- case "neq":
929
- op = "!=";
930
- break;
931
- case "gt":
932
- op = ">";
933
- break;
934
- case "gte":
935
- op = ">=";
936
- break;
937
- case "lt":
938
- op = "<";
939
- break;
940
- case "lte":
941
- op = "<=";
942
- break;
943
- case "in":
944
- op = "in";
945
- val = valStr.startsWith("(") && valStr.endsWith(")") ? valStr.slice(1, -1).split(",").map((v) => v.trim()) : valStr.split(",");
946
- break;
947
- case "nin":
948
- op = "not-in";
949
- val = valStr.startsWith("(") && valStr.endsWith(")") ? valStr.slice(1, -1).split(",").map((v) => v.trim()) : valStr.split(",");
950
- break;
951
- case "cs":
952
- op = "array-contains";
953
- break;
954
- case "csa":
955
- op = "array-contains-any";
956
- val = valStr.startsWith("(") && valStr.endsWith(")") ? valStr.slice(1, -1).split(",").map((v) => v.trim()) : valStr.split(",");
957
- break;
958
- default:
959
- op = "==";
960
- val = value;
961
- }
962
- if (val === "true") val = true;
963
- else if (val === "false") val = false;
964
- else if (val === "null") val = null;
965
- else if (typeof val === "string" && /^[0-9]+(\.[0-9]+)?$/.test(val) && fieldKey !== "id" && !fieldKey.endsWith("_id")) val = Number(val);
966
- return [op, val];
967
- } else {
968
- return ["==", value];
969
- }
970
- };
971
- for (const [key, rawValue] of Object.entries(where)) {
972
- if (Array.isArray(rawValue) && rawValue.length > 0 && Array.isArray(rawValue[0])) {
973
- filters[key] = rawValue.map((r) => parseSingle(r, key));
974
- } else {
975
- filters[key] = parseSingle(rawValue, key);
976
- }
977
- }
978
- return filters;
979
- }
980
- function rowToEntity(row, slug) {
981
- return {
982
- id: row.id,
983
- path: slug,
984
- values: row
985
- };
986
- }
987
- function createCollectionClient(transport, slug, ws) {
988
- const basePath = `/data/${slug}`;
989
- const client = {
990
- async find(params) {
991
- const qs = buildQueryString(params);
992
- const raw = await transport.request(basePath + qs, { method: "GET" });
993
- return {
994
- data: (raw.data || []).map((row) => rowToEntity(row, slug)),
995
- meta: raw.meta
996
- };
997
- },
998
- async findById(id) {
999
- try {
1000
- const raw = await transport.request(`${basePath}/${encodeURIComponent(String(id))}`, { method: "GET" });
1001
- if (!raw) return void 0;
1002
- return rowToEntity(raw, slug);
1003
- } catch (err) {
1004
- if (err instanceof RebaseApiError && err.status === 404) {
1005
- return void 0;
1006
- }
1007
- throw err;
1008
- }
1009
- },
1010
- async create(data, id) {
1011
- const body = { ...data };
1012
- if (id !== void 0) {
1013
- body.id = id;
1014
- }
1015
- const raw = await transport.request(basePath, {
1016
- method: "POST",
1017
- body: JSON.stringify(body)
1018
- });
1019
- return rowToEntity(raw, slug);
1020
- },
1021
- async update(id, data) {
1022
- const raw = await transport.request(`${basePath}/${encodeURIComponent(String(id))}`, {
1023
- method: "PUT",
1024
- body: JSON.stringify(data)
1025
- });
1026
- return rowToEntity(raw, slug);
1027
- },
1028
- async delete(id) {
1029
- return transport.request(`${basePath}/${encodeURIComponent(String(id))}`, {
1030
- method: "DELETE"
1031
- });
1032
- },
1033
- async count(params) {
1034
- const countParams = {
1035
- ...params,
1036
- limit: void 0,
1037
- offset: void 0
1038
- };
1039
- const qs = buildQueryString(countParams);
1040
- const raw = await transport.request(basePath + "/count" + qs, { method: "GET" });
1041
- return raw.count ?? 0;
1042
- },
1043
- // Fluent builder instantiation
1044
- where(columnOrCondition, operator, value) {
1045
- const builder = new common.QueryBuilder(client);
1046
- if (typeof columnOrCondition === "object") {
1047
- return builder.where(columnOrCondition);
1048
- }
1049
- return builder.where(columnOrCondition, operator, value);
1050
- },
1051
- orderBy(column, ascending) {
1052
- return new common.QueryBuilder(client).orderBy(column, ascending);
1053
- },
1054
- limit(count) {
1055
- return new common.QueryBuilder(client).limit(count);
1056
- },
1057
- offset(count) {
1058
- return new common.QueryBuilder(client).offset(count);
1059
- },
1060
- search(searchString) {
1061
- return new common.QueryBuilder(client).search(searchString);
1062
- },
1063
- include(...relations) {
1064
- return new common.QueryBuilder(client).include(...relations);
1065
- }
1066
- };
1067
- if (ws) {
1068
- client.listen = (params, onUpdate, onError) => {
1069
- return ws.listenCollection(
1070
- {
1071
- path: slug,
1072
- filter: parseWhereFilter(params?.where),
1073
- limit: params?.limit,
1074
- startAfter: params?.offset ? String(params.offset) : void 0,
1075
- orderBy: params?.orderBy?.split(":")[0],
1076
- order: params?.orderBy?.split(":")[1],
1077
- searchString: params?.searchString
1078
- },
1079
- (entities) => {
1080
- const requestedLimit = params?.limit || 20;
1081
- onUpdate({
1082
- data: entities,
1083
- meta: {
1084
- total: entities.length,
1085
- limit: requestedLimit,
1086
- offset: params?.offset || 0,
1087
- hasMore: entities.length >= requestedLimit
1088
- }
1089
- });
1090
- },
1091
- onError
1092
- );
1093
- };
1094
- client.listenById = (id, onUpdate, onError) => {
1095
- return ws.listenEntity(
1096
- {
1097
- path: slug,
1098
- entityId: String(id)
1099
- },
1100
- (entity) => {
1101
- if (entity) {
1102
- onUpdate(entity);
1103
- } else {
1104
- onUpdate(void 0);
1105
- }
1106
- },
1107
- onError
1108
- );
1109
- };
1110
- }
1111
- return client;
1112
- }
1113
- function createFunctionsClient(transport) {
1114
- return {
1115
- async invoke(name, payload, options) {
1116
- const method = options?.method ?? "POST";
1117
- const subPath = options?.path ? `/${options.path.replace(/^\//, "")}` : "";
1118
- const routePath = `/functions/${encodeURIComponent(name)}${subPath}`;
1119
- const init = { method };
1120
- if (payload !== void 0 && method !== "GET") {
1121
- init.body = JSON.stringify(payload);
1122
- }
1123
- if (options?.headers) {
1124
- init.headers = options.headers;
1125
- }
1126
- return transport.request(routePath, init);
1127
- }
1128
- };
1129
- }
1130
- function rehydrateEntity(entity) {
1131
- return entity;
1132
- }
1133
- function extractMessageError(message) {
1134
- const payload = message.payload;
1135
- const errPayload = payload?.error;
1136
- const errorMessage = typeof errPayload === "object" ? errPayload.message : payload?.message || (typeof errPayload === "string" ? errPayload : void 0) || message.error || "Unknown error";
1137
- const errorCode = typeof errPayload === "object" ? errPayload.code : payload?.code;
1138
- return {
1139
- errorMessage,
1140
- errorCode
1141
- };
1142
- }
1143
- class ApiError extends Error {
1144
- code;
1145
- error;
1146
- constructor(message, error, code) {
1147
- super(message);
1148
- this.name = "ApiError";
1149
- this.code = code;
1150
- this.error = error;
1151
- }
1152
- }
1153
- class RebaseWebSocketClient {
1154
- websocketUrl;
1155
- ws = null;
1156
- getAuthToken;
1157
- subscriptions = /* @__PURE__ */ new Map();
1158
- listeners = /* @__PURE__ */ new Map();
1159
- on(event, cb) {
1160
- if (!this.listeners.has(event)) {
1161
- this.listeners.set(event, /* @__PURE__ */ new Set());
1162
- }
1163
- this.listeners.get(event).add(cb);
1164
- return () => this.listeners.get(event).delete(cb);
1165
- }
1166
- emit(event, ...args) {
1167
- if (this.listeners.has(event)) {
1168
- this.listeners.get(event).forEach((cb) => cb(...args));
1169
- }
1170
- }
1171
- // New: Subscription deduplication management with optimizations
1172
- collectionSubscriptions = /* @__PURE__ */ new Map();
1173
- entitySubscriptions = /* @__PURE__ */ new Map();
1174
- // Maps to quickly find subscription by backend subscription ID
1175
- backendToCollectionKey = /* @__PURE__ */ new Map();
1176
- backendToEntityKey = /* @__PURE__ */ new Map();
1177
- pendingRequests = /* @__PURE__ */ new Map();
1178
- reconnectAttempts = 0;
1179
- maxReconnectAttempts = 5;
1180
- isConnected = false;
1181
- messageQueue = [];
1182
- reconnectTimeout = null;
1183
- isAuthenticated = false;
1184
- authPromise = null;
1185
- WebSocketConstructor;
1186
- onUnauthorized;
1187
- refreshInProgress = null;
1188
- constructor(config) {
1189
- this.websocketUrl = config.websocketUrl;
1190
- this.getAuthToken = config.getAuthToken;
1191
- this.onUnauthorized = config.onUnauthorized;
1192
- this.WebSocketConstructor = config.WebSocket || (typeof WebSocket !== "undefined" ? WebSocket : void 0);
1193
- if (!this.WebSocketConstructor) {
1194
- console.warn("WebSocket is not defined in this environment. Realtime subscriptions will not work unless you provide a WebSocket implementation in the config.");
1195
- } else {
1196
- this.initWebSocket();
1197
- }
1198
- }
1199
- /**
1200
- * Authenticate the WebSocket connection
1201
- */
1202
- async authenticate(token) {
1203
- return new Promise((resolve, reject) => {
1204
- const requestId = `auth_${Date.now()}`;
1205
- const timeout = setTimeout(() => {
1206
- this.pendingRequests.delete(requestId);
1207
- this.authPromise = null;
1208
- reject(new Error("Authentication timeout"));
1209
- }, 3e4);
1210
- this.pendingRequests.set(requestId, {
1211
- resolve: () => {
1212
- clearTimeout(timeout);
1213
- this.isAuthenticated = true;
1214
- resolve();
1215
- },
1216
- reject: (error) => {
1217
- clearTimeout(timeout);
1218
- reject(error);
1219
- }
1220
- });
1221
- const message = {
1222
- type: "AUTHENTICATE",
1223
- requestId,
1224
- payload: { token }
1225
- };
1226
- if (!this.isConnected || !this.ws) {
1227
- this.messageQueue.unshift(message);
1228
- } else {
1229
- this.ws.send(JSON.stringify(message));
1230
- }
1231
- });
1232
- }
1233
- /**
1234
- * Set the auth token getter function
1235
- */
1236
- setAuthTokenGetter(getAuthToken) {
1237
- this.getAuthToken = getAuthToken;
1238
- if (this.isConnected && !this.isAuthenticated && !this.authPromise) {
1239
- console.debug("WebSocket auto-authenticating after token getter set");
1240
- this.getAuthToken().then((token) => {
1241
- if (!this.ws) return;
1242
- if (token) {
1243
- this.authenticate(token).catch((e) => {
1244
- if (this.ws) console.debug("WebSocket auto-auth skipped:", e?.message || e);
1245
- });
1246
- }
1247
- }).catch((e) => {
1248
- if (this.ws) console.debug("WebSocket auto-auth skipped:", e?.message || e);
1249
- });
1250
- }
1251
- }
1252
- disconnect() {
1253
- this.isAuthenticated = false;
1254
- this.authPromise = null;
1255
- if (this.reconnectTimeout) {
1256
- clearTimeout(this.reconnectTimeout);
1257
- this.reconnectTimeout = null;
1258
- }
1259
- if (this.ws) {
1260
- this.ws.onclose = null;
1261
- this.ws.onerror = null;
1262
- this.ws.onopen = null;
1263
- this.ws.onmessage = null;
1264
- this.ws.close();
1265
- this.ws = null;
1266
- }
1267
- }
1268
- // Initialize WebSocket connection
1269
- initWebSocket() {
1270
- if (!this.WebSocketConstructor) return;
1271
- if (this.ws?.readyState === this.WebSocketConstructor.OPEN) return;
1272
- try {
1273
- this.ws = new this.WebSocketConstructor(this.websocketUrl);
1274
- this.ws.onopen = async () => {
1275
- console.debug("Connected to PostgreSQL backend");
1276
- const wasReconnect = this.reconnectAttempts > 0;
1277
- this.isConnected = true;
1278
- this.reconnectAttempts = 0;
1279
- if (this.getAuthToken && !this.isAuthenticated) {
1280
- try {
1281
- const token = await this.getAuthToken();
1282
- if (token) {
1283
- await this.authenticate(token);
1284
- console.debug("WebSocket auto-authenticated");
1285
- }
1286
- } catch (error) {
1287
- console.debug("WebSocket connected without auth:", error?.message || error);
1288
- }
1289
- }
1290
- this.emit(wasReconnect ? "reconnect" : "connect");
1291
- this.processMessageQueue();
1292
- if (wasReconnect) {
1293
- this.resubscribeAll();
1294
- }
1295
- };
1296
- this.ws.onmessage = (event) => {
1297
- try {
1298
- const message = JSON.parse(event.data, rebaseReviver);
1299
- this.handleWebSocketMessage(message);
1300
- } catch (error) {
1301
- console.error("Error parsing WebSocket message:", error);
1302
- }
1303
- };
1304
- this.ws.onclose = () => {
1305
- console.debug("Disconnected from PostgreSQL backend");
1306
- this.isConnected = false;
1307
- this.isAuthenticated = false;
1308
- this.authPromise = null;
1309
- this.emit("disconnect");
1310
- for (const [reqId, request] of this.pendingRequests.entries()) {
1311
- if (reqId.startsWith("auth_")) {
1312
- request.reject(new Error("Connection closed during authentication"));
1313
- } else if (request.message) {
1314
- request.message._queuedResolve = request.resolve;
1315
- request.message._queuedReject = request.reject;
1316
- this.messageQueue.push(request.message);
1317
- } else {
1318
- request.reject(new ApiError("Connection closed", "Connection closed"));
1319
- }
1320
- this.pendingRequests.delete(reqId);
1321
- }
1322
- this.attemptReconnect();
1323
- };
1324
- this.ws.onerror = (error) => {
1325
- console.error("WebSocket error:", error);
1326
- this.isConnected = false;
1327
- this.emit("error", error);
1328
- };
1329
- } catch (error) {
1330
- console.error("Failed to initialize WebSocket:", error);
1331
- this.attemptReconnect();
1332
- }
1333
- }
1334
- processMessageQueue() {
1335
- while (this.messageQueue.length > 0 && this.isConnected) {
1336
- const message = this.messageQueue.shift();
1337
- if (message) this.sendMessage(message);
1338
- }
1339
- }
1340
- attemptReconnect() {
1341
- if (this.reconnectAttempts >= this.maxReconnectAttempts) {
1342
- console.error("Max reconnection attempts reached");
1343
- return;
1344
- }
1345
- this.reconnectAttempts++;
1346
- const delay = Math.min(1e3 * Math.pow(2, this.reconnectAttempts), 3e4);
1347
- console.debug(`Attempting to reconnect in ${delay}ms (attempt ${this.reconnectAttempts})`);
1348
- if (this.reconnectTimeout) {
1349
- clearTimeout(this.reconnectTimeout);
1350
- }
1351
- this.reconnectTimeout = setTimeout(() => {
1352
- this.reconnectTimeout = null;
1353
- this.initWebSocket();
1354
- }, delay);
1355
- }
1356
- isAuthError(message) {
1357
- if (message.type === "AUTH_ERROR") return true;
1358
- const { errorMessage, errorCode } = extractMessageError(message);
1359
- if (errorCode === "UNAUTHORIZED" || errorCode === "JWT_EXPIRED" || errorCode === "AUTH_ERROR") return true;
1360
- const lowerMessage = errorMessage.toLowerCase();
1361
- return lowerMessage.includes("unauthorized") || lowerMessage.includes("token expired") || lowerMessage.includes("token is expired") || lowerMessage.includes("invalid token") || lowerMessage.includes("session expired") || lowerMessage.includes("auth error");
1362
- }
1363
- async handleAuthFailure() {
1364
- if (this.refreshInProgress) {
1365
- return this.refreshInProgress;
1366
- }
1367
- this.refreshInProgress = (async () => {
1368
- this.isAuthenticated = false;
1369
- this.authPromise = null;
1370
- if (this.onUnauthorized) {
1371
- try {
1372
- const refreshed = await this.onUnauthorized();
1373
- if (refreshed && this.getAuthToken) {
1374
- const token = await this.getAuthToken();
1375
- if (token) {
1376
- await this.authenticate(token);
1377
- return true;
1378
- }
1379
- }
1380
- } catch (error) {
1381
- console.error("WebSocket auth refresh failed:", error);
1382
- }
1383
- }
1384
- return false;
1385
- })();
1386
- try {
1387
- return await this.refreshInProgress;
1388
- } finally {
1389
- this.refreshInProgress = null;
1390
- }
1391
- }
1392
- handleWebSocketMessage(message) {
1393
- const {
1394
- type,
1395
- requestId,
1396
- subscriptionId
1397
- } = message;
1398
- if (requestId && this.pendingRequests.has(requestId)) {
1399
- const pendingReq = this.pendingRequests.get(requestId);
1400
- if (type === "ERROR" || type === "AUTH_ERROR" || message.error) {
1401
- if (this.isAuthError(message)) {
1402
- this.pendingRequests.delete(requestId);
1403
- this.handleAuthFailure().then((refreshed) => {
1404
- if (refreshed && pendingReq.message) {
1405
- this.doSendMessage(pendingReq.message, pendingReq.resolve, pendingReq.reject).catch(pendingReq.reject);
1406
- } else {
1407
- const { errorMessage, errorCode } = extractMessageError(message);
1408
- pendingReq.reject(new ApiError(errorMessage, errorMessage, errorCode));
1409
- }
1410
- }).catch((err) => {
1411
- pendingReq.reject(err);
1412
- });
1413
- } else {
1414
- this.pendingRequests.delete(requestId);
1415
- const { errorMessage, errorCode } = extractMessageError(message);
1416
- pendingReq.reject(new ApiError(errorMessage, errorMessage, errorCode));
1417
- }
1418
- } else {
1419
- this.pendingRequests.delete(requestId);
1420
- pendingReq.resolve(message.payload || message);
1421
- }
1422
- return;
1423
- }
1424
- if (subscriptionId && type === "collection_update") {
1425
- const subscriptionKey = this.backendToCollectionKey.get(subscriptionId);
1426
- if (subscriptionKey) {
1427
- const collectionSub = this.collectionSubscriptions.get(subscriptionKey);
1428
- if (collectionSub) {
1429
- const incomingEntities = (message.entities || []).map((e) => rehydrateEntity(e));
1430
- const entities = this.mergeEntities(collectionSub.latestData, incomingEntities);
1431
- collectionSub.latestData = entities;
1432
- collectionSub.lastUpdated = Date.now();
1433
- collectionSub.isInitialDataReceived = true;
1434
- collectionSub.callbacks.forEach((callback) => {
1435
- try {
1436
- callback.onUpdate(entities);
1437
- } catch (error) {
1438
- console.error("Error in collection subscription callback:", error);
1439
- if (callback.onError) {
1440
- callback.onError(error instanceof Error ? error : new Error(String(error)));
1441
- }
1442
- }
1443
- });
1444
- return;
1445
- }
1446
- }
1447
- }
1448
- if (subscriptionId && type === "collection_entity_patch") {
1449
- const subscriptionKey = this.backendToCollectionKey.get(subscriptionId);
1450
- if (subscriptionKey) {
1451
- const collectionSub = this.collectionSubscriptions.get(subscriptionKey);
1452
- if (collectionSub && collectionSub.isInitialDataReceived && collectionSub.latestData) {
1453
- const patchEntity = message.entity ? rehydrateEntity(message.entity) : message.entity;
1454
- const patchEntityId = message.entityId;
1455
- let updated;
1456
- if (patchEntity === null || patchEntity === void 0) {
1457
- updated = collectionSub.latestData.filter((e) => String(e.id) !== String(patchEntityId));
1458
- } else {
1459
- const idx = collectionSub.latestData.findIndex((e) => String(e.id) === String(patchEntity.id));
1460
- if (idx >= 0) {
1461
- updated = [...collectionSub.latestData];
1462
- updated[idx] = patchEntity;
1463
- } else {
1464
- updated = [patchEntity, ...collectionSub.latestData];
1465
- }
1466
- }
1467
- collectionSub.latestData = updated;
1468
- collectionSub.lastUpdated = Date.now();
1469
- collectionSub.callbacks.forEach((callback) => {
1470
- try {
1471
- callback.onUpdate(updated);
1472
- } catch (error) {
1473
- console.error("Error in collection patch callback:", error);
1474
- if (callback.onError) {
1475
- callback.onError(error instanceof Error ? error : new Error(String(error)));
1476
- }
1477
- }
1478
- });
1479
- return;
1480
- }
1481
- }
1482
- }
1483
- if (subscriptionId && type === "entity_update") {
1484
- const subscriptionKey = this.backendToEntityKey.get(subscriptionId);
1485
- if (subscriptionKey) {
1486
- const entitySub = this.entitySubscriptions.get(subscriptionKey);
1487
- if (entitySub) {
1488
- const entity = message.entity ? rehydrateEntity(message.entity) : null;
1489
- entitySub.latestData = entity;
1490
- entitySub.lastUpdated = Date.now();
1491
- entitySub.isInitialDataReceived = true;
1492
- entitySub.callbacks.forEach((callback) => {
1493
- try {
1494
- callback.onUpdate(entity);
1495
- } catch (error) {
1496
- console.error("Error in entity subscription callback:", error);
1497
- if (callback.onError) {
1498
- callback.onError(error instanceof Error ? error : new Error(String(error)));
1499
- }
1500
- }
1501
- });
1502
- return;
1503
- }
1504
- }
1505
- }
1506
- if (subscriptionId && (type === "ERROR" || message.error)) {
1507
- const collectionKey = this.backendToCollectionKey.get(subscriptionId);
1508
- if (collectionKey) {
1509
- const collectionSub = this.collectionSubscriptions.get(collectionKey);
1510
- if (collectionSub) {
1511
- if (this.isAuthError(message)) {
1512
- this.handleAuthFailure().then((refreshed) => {
1513
- if (refreshed) {
1514
- const oldBackendId = collectionSub.backendSubscriptionId;
1515
- const newBackendId = `collection_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
1516
- collectionSub.backendSubscriptionId = newBackendId;
1517
- this.backendToCollectionKey.delete(oldBackendId);
1518
- this.backendToCollectionKey.set(newBackendId, collectionKey);
1519
- this.sendMessage({
1520
- type: "subscribe_collection",
1521
- payload: {
1522
- ...collectionSub.props,
1523
- subscriptionId: newBackendId
1524
- }
1525
- }).catch((error2) => {
1526
- console.error("[WS] Failed to re-subscribe collection after auth refresh:", collectionKey, error2);
1527
- collectionSub.callbacks.forEach((callback) => {
1528
- if (callback.onError) callback.onError(error2);
1529
- });
1530
- });
1531
- } else {
1532
- const { errorMessage: errorMessage2, errorCode: errorCode2 } = extractMessageError(message);
1533
- const error2 = new ApiError(errorMessage2, errorMessage2, errorCode2);
1534
- collectionSub.callbacks.forEach((callback) => {
1535
- if (callback.onError) callback.onError(error2);
1536
- });
1537
- }
1538
- }).catch((err) => {
1539
- collectionSub.callbacks.forEach((callback) => {
1540
- if (callback.onError) callback.onError(err);
1541
- });
1542
- });
1543
- return;
1544
- }
1545
- const { errorMessage, errorCode } = extractMessageError(message);
1546
- const error = new ApiError(errorMessage, errorMessage, errorCode);
1547
- collectionSub.callbacks.forEach((callback) => {
1548
- if (callback.onError) {
1549
- callback.onError(error);
1550
- }
1551
- });
1552
- return;
1553
- }
1554
- }
1555
- const entityKey = this.backendToEntityKey.get(subscriptionId);
1556
- if (entityKey) {
1557
- const entitySub = this.entitySubscriptions.get(entityKey);
1558
- if (entitySub) {
1559
- if (this.isAuthError(message)) {
1560
- this.handleAuthFailure().then((refreshed) => {
1561
- if (refreshed) {
1562
- const oldBackendId = entitySub.backendSubscriptionId;
1563
- const newBackendId = `entity_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
1564
- entitySub.backendSubscriptionId = newBackendId;
1565
- this.backendToEntityKey.delete(oldBackendId);
1566
- this.backendToEntityKey.set(newBackendId, entityKey);
1567
- this.sendMessage({
1568
- type: "subscribe_entity",
1569
- payload: {
1570
- ...entitySub.props,
1571
- subscriptionId: newBackendId
1572
- }
1573
- }).catch((error2) => {
1574
- console.error("[WS] Failed to re-subscribe entity after auth refresh:", entityKey, error2);
1575
- entitySub.callbacks.forEach((callback) => {
1576
- if (callback.onError) callback.onError(error2);
1577
- });
1578
- });
1579
- } else {
1580
- const { errorMessage: errorMessage2, errorCode: errorCode2 } = extractMessageError(message);
1581
- const error2 = new ApiError(errorMessage2, errorMessage2, errorCode2);
1582
- entitySub.callbacks.forEach((callback) => {
1583
- if (callback.onError) callback.onError(error2);
1584
- });
1585
- }
1586
- }).catch((err) => {
1587
- entitySub.callbacks.forEach((callback) => {
1588
- if (callback.onError) callback.onError(err);
1589
- });
1590
- });
1591
- return;
1592
- }
1593
- const { errorMessage, errorCode } = extractMessageError(message);
1594
- const error = new ApiError(errorMessage, errorMessage, errorCode);
1595
- entitySub.callbacks.forEach((callback) => {
1596
- if (callback.onError) {
1597
- callback.onError(error);
1598
- }
1599
- });
1600
- return;
1601
- }
1602
- }
1603
- }
1604
- if (subscriptionId && this.subscriptions.has(subscriptionId)) {
1605
- const callback = this.subscriptions.get(subscriptionId);
1606
- if (!callback) {
1607
- throw new Error(`Subscription callback not found for subscriptionId: ${subscriptionId}`);
1608
- }
1609
- if (message.type === "ERROR" || message.error) {
1610
- if (callback.onError) {
1611
- const { errorMessage, errorCode } = extractMessageError(message);
1612
- callback.onError(new ApiError(errorMessage, errorMessage, errorCode));
1613
- }
1614
- } else {
1615
- callback.onUpdate(message);
1616
- }
1617
- }
1618
- }
1619
- async ensureAuthenticated(retryCount = 3) {
1620
- if (this.isAuthenticated || !this.getAuthToken) return;
1621
- if (this.authPromise) {
1622
- await this.authPromise;
1623
- return;
1624
- }
1625
- let lastError = null;
1626
- for (let attempt = 0; attempt < retryCount; attempt++) {
1627
- try {
1628
- const token = await this.getAuthToken();
1629
- if (!token) throw new Error("user not logged in");
1630
- this.authPromise = this.authenticate(token);
1631
- await this.authPromise;
1632
- this.authPromise = null;
1633
- console.debug("WebSocket authenticated on demand");
1634
- return;
1635
- } catch (error) {
1636
- this.authPromise = null;
1637
- lastError = error;
1638
- const errMsg = error instanceof Error ? error.message : String(error);
1639
- if (errMsg.includes("not logged in") || errMsg.includes("Session expired")) {
1640
- console.warn("WebSocket auth failed: user not logged in");
1641
- throw error;
1642
- }
1643
- if (errMsg.includes("still loading")) {
1644
- if (attempt < retryCount - 1) {
1645
- const delay = Math.min(500 * (attempt + 1), 2e3);
1646
- await new Promise((resolve) => setTimeout(resolve, delay));
1647
- continue;
1648
- }
1649
- }
1650
- if (attempt < retryCount - 1) {
1651
- const delay = Math.min(1e3 * (attempt + 1), 3e3);
1652
- console.debug(`WebSocket auth attempt ${attempt + 1} failed, retrying in ${delay}ms...`);
1653
- await new Promise((resolve) => setTimeout(resolve, delay));
1654
- }
1655
- }
1656
- }
1657
- console.warn("WebSocket on-demand auth failed after retries:", lastError);
1658
- throw lastError;
1659
- }
1660
- /**
1661
- * Force re-authentication (call after token refresh)
1662
- */
1663
- async reauthenticate() {
1664
- if (!this.getAuthToken) return;
1665
- this.isAuthenticated = false;
1666
- try {
1667
- const token = await this.getAuthToken();
1668
- await this.authenticate(token);
1669
- console.debug("WebSocket reauthenticated successfully");
1670
- } catch (error) {
1671
- console.error("WebSocket reauthentication failed:", error);
1672
- throw error;
1673
- }
1674
- }
1675
- sendMessage(message) {
1676
- const queuedMsg = message;
1677
- if (queuedMsg._queuedResolve && queuedMsg._queuedReject) {
1678
- return this.doSendMessage(message, queuedMsg._queuedResolve, queuedMsg._queuedReject);
1679
- }
1680
- if (!this.isConnected || !this.ws) {
1681
- return new Promise((resolve, reject) => {
1682
- const queueable = message;
1683
- queueable._queuedResolve = resolve;
1684
- queueable._queuedReject = reject;
1685
- this.messageQueue.push(message);
1686
- });
1687
- }
1688
- return new Promise((resolve, reject) => {
1689
- this.doSendMessage(message, resolve, reject);
1690
- });
1691
- }
1692
- async doSendMessage(message, resolve, reject) {
1693
- if (message.type !== "AUTHENTICATE" && this.getAuthToken && !this.isAuthenticated) {
1694
- try {
1695
- await this.ensureAuthenticated();
1696
- } catch (error) {
1697
- const errorMessage = error instanceof Error ? error.message : "Authentication required";
1698
- reject(new ApiError(errorMessage, errorMessage));
1699
- return;
1700
- }
1701
- }
1702
- const requestId = message.requestId || `req_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
1703
- message.requestId = requestId;
1704
- if (!this.pendingRequests.has(requestId)) {
1705
- this.pendingRequests.set(requestId, {
1706
- resolve,
1707
- reject,
1708
- message
1709
- });
1710
- }
1711
- try {
1712
- this.ws.send(JSON.stringify(message));
1713
- } catch (error) {
1714
- this.pendingRequests.delete(requestId);
1715
- reject(new ApiError("Failed to send message", error instanceof Error ? error.message : "Unknown error"));
1716
- }
1717
- }
1718
- // Data source methods
1719
- async fetchCollection(props) {
1720
- const response = await this.sendMessage({
1721
- type: "FETCH_COLLECTION",
1722
- payload: props
1723
- });
1724
- return (response.entities || []).map((e) => rehydrateEntity(e));
1725
- }
1726
- async fetchEntity(props) {
1727
- const response = await this.sendMessage({
1728
- type: "FETCH_ENTITY",
1729
- payload: props
1730
- });
1731
- return response.entity ? rehydrateEntity(response.entity) : void 0;
1732
- }
1733
- async saveEntity(props) {
1734
- const response = await this.sendMessage({
1735
- type: "SAVE_ENTITY",
1736
- payload: props
1737
- });
1738
- return rehydrateEntity(response.entity);
1739
- }
1740
- async deleteEntity(props) {
1741
- await this.sendMessage({
1742
- type: "DELETE_ENTITY",
1743
- payload: props
1744
- });
1745
- }
1746
- async executeSql(sql, options) {
1747
- const response = await this.sendMessage({
1748
- type: "EXECUTE_SQL",
1749
- payload: {
1750
- sql,
1751
- options
1752
- }
1753
- });
1754
- return response.result || [];
1755
- }
1756
- async fetchAvailableDatabases() {
1757
- const response = await this.sendMessage({
1758
- type: "FETCH_DATABASES",
1759
- payload: {}
1760
- });
1761
- return response.databases || [];
1762
- }
1763
- async fetchAvailableRoles() {
1764
- const response = await this.sendMessage({
1765
- type: "FETCH_ROLES"
1766
- });
1767
- return response.roles || [];
1768
- }
1769
- async fetchCurrentDatabase() {
1770
- const response = await this.sendMessage({
1771
- type: "FETCH_CURRENT_DATABASE"
1772
- });
1773
- return response.database;
1774
- }
1775
- async checkUniqueField(path, name, value, entityId, collection) {
1776
- const response = await this.sendMessage({
1777
- type: "CHECK_UNIQUE_FIELD",
1778
- payload: {
1779
- path,
1780
- name,
1781
- value,
1782
- entityId,
1783
- collection
1784
- }
1785
- });
1786
- return response.isUnique;
1787
- }
1788
- async countEntities(props) {
1789
- const response = await this.sendMessage({
1790
- type: "COUNT_ENTITIES",
1791
- payload: props
1792
- });
1793
- return response.count;
1794
- }
1795
- async fetchUnmappedTables(mappedPaths) {
1796
- const response = await this.sendMessage({
1797
- type: "FETCH_UNMAPPED_TABLES",
1798
- payload: { mappedPaths }
1799
- });
1800
- return response.tables || [];
1801
- }
1802
- async fetchTableMetadata(tableName) {
1803
- const response = await this.sendMessage({
1804
- type: "FETCH_TABLE_METADATA",
1805
- payload: { tableName }
1806
- });
1807
- return response.metadata || {
1808
- columns: [],
1809
- foreignKeys: [],
1810
- junctions: [],
1811
- policies: []
1812
- };
1813
- }
1814
- async createBranch(name, options) {
1815
- const response = await this.sendMessage({
1816
- type: "CREATE_BRANCH",
1817
- payload: {
1818
- name,
1819
- options
1820
- }
1821
- });
1822
- return response.branch;
1823
- }
1824
- async deleteBranch(name) {
1825
- await this.sendMessage({
1826
- type: "DELETE_BRANCH",
1827
- payload: { name }
1828
- });
1829
- }
1830
- async listBranches() {
1831
- const response = await this.sendMessage({
1832
- type: "LIST_BRANCHES",
1833
- payload: {}
1834
- });
1835
- return response.branches || [];
1836
- }
1837
- /**
1838
- * Recursively compare two values for structural equality.
1839
- * Handles primitives, null, undefined, Date, RegExp, arrays, and plain objects.
1840
- */
1841
- deepEqual(a, b) {
1842
- if (a === b) return true;
1843
- if (a === null || b === null || a === void 0 || b === void 0) return false;
1844
- if (typeof a !== typeof b) return false;
1845
- if (typeof a !== "object") return false;
1846
- if (a instanceof Date && b instanceof Date) {
1847
- return a.getTime() === b.getTime();
1848
- }
1849
- if (a instanceof Date || b instanceof Date) return false;
1850
- if (a instanceof RegExp && b instanceof RegExp) {
1851
- return a.source === b.source && a.flags === b.flags;
1852
- }
1853
- if (a instanceof RegExp || b instanceof RegExp) return false;
1854
- const aIsArray = Array.isArray(a);
1855
- const bIsArray = Array.isArray(b);
1856
- if (aIsArray !== bIsArray) return false;
1857
- if (aIsArray && bIsArray) {
1858
- if (a.length !== b.length) return false;
1859
- for (let i = 0; i < a.length; i++) {
1860
- if (!this.deepEqual(a[i], b[i])) return false;
1861
- }
1862
- return true;
1863
- }
1864
- const aObj = a;
1865
- const bObj = b;
1866
- const aKeys = Object.keys(aObj);
1867
- const bKeys = Object.keys(bObj);
1868
- if (aKeys.length !== bKeys.length) return false;
1869
- for (const key of aKeys) {
1870
- if (!Object.prototype.hasOwnProperty.call(bObj, key)) return false;
1871
- if (!this.deepEqual(aObj[key], bObj[key])) return false;
1872
- }
1873
- return true;
1874
- }
1875
- normalizeForComparison(val) {
1876
- if (!val) return val;
1877
- if (Array.isArray(val)) {
1878
- return val.map((item) => this.normalizeForComparison(item));
1879
- }
1880
- if (typeof val === "object") {
1881
- if (val instanceof Date) return val;
1882
- if (val instanceof RegExp) return val;
1883
- const obj = val;
1884
- if (obj.__type === "relation") {
1885
- const { data, ...rest } = obj;
1886
- return rest;
1887
- }
1888
- const result = {};
1889
- for (const [k, v] of Object.entries(obj)) {
1890
- result[k] = this.normalizeForComparison(v);
1891
- }
1892
- return result;
1893
- }
1894
- return val;
1895
- }
1896
- /**
1897
- * Merge incoming entities with cached data, preserving cached references
1898
- * for entities whose values haven't changed. This avoids unnecessary
1899
- * React re-renders when the server refetches all entities but most
1900
- * haven't actually changed.
1901
- */
1902
- mergeEntities(cached, incoming) {
1903
- if (!cached || cached.length === 0) return incoming;
1904
- const cachedById = /* @__PURE__ */ new Map();
1905
- for (const entity of cached) {
1906
- cachedById.set(entity.id, entity);
1907
- }
1908
- return incoming.map((incomingEntity) => {
1909
- const cachedEntity = cachedById.get(incomingEntity.id);
1910
- if (!cachedEntity) return incomingEntity;
1911
- if (cachedEntity.path === incomingEntity.path) {
1912
- const normCached = this.normalizeForComparison(cachedEntity.values);
1913
- const normIncoming = this.normalizeForComparison(incomingEntity.values);
1914
- if (this.deepEqual(normCached, normIncoming)) {
1915
- return cachedEntity;
1916
- } else {
1917
- const mismatches = {};
1918
- const allKeys = /* @__PURE__ */ new Set([...Object.keys(normCached), ...Object.keys(normIncoming)]);
1919
- for (const key of allKeys) {
1920
- if (!this.deepEqual(normCached[key], normIncoming[key])) {
1921
- mismatches[key] = {
1922
- cached: normCached[key],
1923
- incoming: normIncoming[key]
1924
- };
1925
- }
1926
- }
1927
- console.debug(`[RebaseWS] Row ${incomingEntity.id} refetch mismatch:
1928
- `, JSON.stringify(mismatches, null, 2));
1929
- }
1930
- }
1931
- return incomingEntity;
1932
- });
1933
- }
1934
- // Subscription methods
1935
- listenCollection(props, onUpdate, onError) {
1936
- const subscriptionKey = this.createCollectionSubscriptionKey(props);
1937
- const callbackId = `callback_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
1938
- const existingSubscription = this.collectionSubscriptions.get(subscriptionKey);
1939
- if (existingSubscription) {
1940
- const callbackMap2 = existingSubscription.callbacks;
1941
- callbackMap2.set(callbackId, {
1942
- onUpdate,
1943
- onError
1944
- });
1945
- if (existingSubscription.latestData !== void 0 && existingSubscription.isInitialDataReceived) {
1946
- try {
1947
- onUpdate(existingSubscription.latestData);
1948
- } catch (error) {
1949
- console.error("Error in collection subscription callback:", error);
1950
- if (onError) {
1951
- onError(error instanceof Error ? error : new Error(String(error)));
1952
- }
1953
- }
1954
- }
1955
- return () => {
1956
- callbackMap2.delete(callbackId);
1957
- if (callbackMap2.size === 0) {
1958
- this.collectionSubscriptions.delete(subscriptionKey);
1959
- this.backendToCollectionKey.delete(existingSubscription.backendSubscriptionId);
1960
- if (this.isConnected && this.ws) {
1961
- this.sendMessage({
1962
- type: "unsubscribe",
1963
- payload: { subscriptionId: existingSubscription.backendSubscriptionId }
1964
- }).catch(console.error);
1965
- }
1966
- }
1967
- };
1968
- }
1969
- const backendSubscriptionId = `collection_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
1970
- const callbackMap = /* @__PURE__ */ new Map();
1971
- callbackMap.set(callbackId, {
1972
- onUpdate,
1973
- onError
1974
- });
1975
- this.collectionSubscriptions.set(subscriptionKey, {
1976
- backendSubscriptionId,
1977
- callbacks: callbackMap,
1978
- props
1979
- });
1980
- this.backendToCollectionKey.set(backendSubscriptionId, subscriptionKey);
1981
- this.sendMessage({
1982
- type: "subscribe_collection",
1983
- payload: {
1984
- ...props,
1985
- subscriptionId: backendSubscriptionId
1986
- }
1987
- }).catch((error) => {
1988
- if (onError) onError(error);
1989
- });
1990
- return () => {
1991
- const subscription = this.collectionSubscriptions.get(subscriptionKey);
1992
- if (subscription) {
1993
- const callbacks = subscription.callbacks;
1994
- callbacks.delete(callbackId);
1995
- if (callbacks.size === 0) {
1996
- this.collectionSubscriptions.delete(subscriptionKey);
1997
- this.backendToCollectionKey.delete(subscription.backendSubscriptionId);
1998
- if (this.isConnected && this.ws) {
1999
- this.sendMessage({
2000
- type: "unsubscribe",
2001
- payload: { subscriptionId: subscription.backendSubscriptionId }
2002
- }).catch(console.error);
2003
- }
2004
- }
2005
- }
2006
- };
2007
- }
2008
- listenEntity(props, onUpdate, onError) {
2009
- const subscriptionKey = this.createEntitySubscriptionKey(props);
2010
- const callbackId = `callback_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
2011
- const existingSubscription = this.entitySubscriptions.get(subscriptionKey);
2012
- if (existingSubscription) {
2013
- const callbackMap2 = existingSubscription.callbacks;
2014
- callbackMap2.set(callbackId, {
2015
- onUpdate,
2016
- onError
2017
- });
2018
- if (existingSubscription.latestData !== void 0 && existingSubscription.isInitialDataReceived) {
2019
- try {
2020
- onUpdate(existingSubscription.latestData);
2021
- } catch (error) {
2022
- console.error("Error in entity subscription callback:", error);
2023
- if (onError) {
2024
- onError(error instanceof Error ? error : new Error(String(error)));
2025
- }
2026
- }
2027
- }
2028
- return () => {
2029
- callbackMap2.delete(callbackId);
2030
- if (callbackMap2.size === 0) {
2031
- this.entitySubscriptions.delete(subscriptionKey);
2032
- this.backendToEntityKey.delete(existingSubscription.backendSubscriptionId);
2033
- if (this.isConnected && this.ws) {
2034
- this.sendMessage({
2035
- type: "unsubscribe",
2036
- payload: { subscriptionId: existingSubscription.backendSubscriptionId }
2037
- }).catch(console.error);
2038
- }
2039
- }
2040
- };
2041
- }
2042
- const backendSubscriptionId = `entity_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
2043
- const callbackMap = /* @__PURE__ */ new Map();
2044
- callbackMap.set(callbackId, {
2045
- onUpdate,
2046
- onError
2047
- });
2048
- this.entitySubscriptions.set(subscriptionKey, {
2049
- backendSubscriptionId,
2050
- callbacks: callbackMap,
2051
- props
2052
- });
2053
- this.backendToEntityKey.set(backendSubscriptionId, subscriptionKey);
2054
- this.sendMessage({
2055
- type: "subscribe_entity",
2056
- payload: {
2057
- ...props,
2058
- subscriptionId: backendSubscriptionId
2059
- }
2060
- }).catch((error) => {
2061
- if (onError) onError(error);
2062
- });
2063
- return () => {
2064
- const subscription = this.entitySubscriptions.get(subscriptionKey);
2065
- if (subscription) {
2066
- const callbacks = subscription.callbacks;
2067
- callbacks.delete(callbackId);
2068
- if (callbacks.size === 0) {
2069
- this.entitySubscriptions.delete(subscriptionKey);
2070
- this.backendToEntityKey.delete(subscription.backendSubscriptionId);
2071
- if (this.isConnected && this.ws) {
2072
- this.sendMessage({
2073
- type: "unsubscribe",
2074
- payload: { subscriptionId: subscription.backendSubscriptionId }
2075
- }).catch(console.error);
2076
- }
2077
- }
2078
- }
2079
- };
2080
- }
2081
- /**
2082
- * Re-send all active subscriptions to the backend after a reconnect.
2083
- * The server wipes subscription state when a client disconnects, so
2084
- * we need to re-register everything to resume receiving updates.
2085
- */
2086
- resubscribeAll() {
2087
- console.debug(`[WS] Re-subscribing: ${this.collectionSubscriptions.size} collection(s), ${this.entitySubscriptions.size} entity(ies)`);
2088
- for (const [key, sub] of this.collectionSubscriptions.entries()) {
2089
- const oldBackendId = sub.backendSubscriptionId;
2090
- const newBackendId = `collection_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
2091
- sub.backendSubscriptionId = newBackendId;
2092
- this.backendToCollectionKey.delete(oldBackendId);
2093
- this.backendToCollectionKey.set(newBackendId, key);
2094
- this.sendMessage({
2095
- type: "subscribe_collection",
2096
- payload: {
2097
- ...sub.props,
2098
- subscriptionId: newBackendId
2099
- }
2100
- }).catch((error) => {
2101
- console.error("[WS] Failed to re-subscribe collection:", key, error);
2102
- });
2103
- }
2104
- for (const [key, sub] of this.entitySubscriptions.entries()) {
2105
- const oldBackendId = sub.backendSubscriptionId;
2106
- const newBackendId = `entity_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
2107
- sub.backendSubscriptionId = newBackendId;
2108
- this.backendToEntityKey.delete(oldBackendId);
2109
- this.backendToEntityKey.set(newBackendId, key);
2110
- this.sendMessage({
2111
- type: "subscribe_entity",
2112
- payload: {
2113
- ...sub.props,
2114
- subscriptionId: newBackendId
2115
- }
2116
- }).catch((error) => {
2117
- console.error("[WS] Failed to re-subscribe entity:", key, error);
2118
- });
2119
- }
2120
- }
2121
- createCollectionSubscriptionKey(props) {
2122
- const key = {
2123
- path: props.path,
2124
- filter: props.filter,
2125
- limit: props.limit,
2126
- startAfter: props.startAfter,
2127
- orderBy: props.orderBy,
2128
- order: props.order,
2129
- searchString: props.searchString,
2130
- collection: props.collection?.name
2131
- };
2132
- return JSON.stringify(key, (_, value) => {
2133
- if (value && typeof value === "object" && !Array.isArray(value)) {
2134
- return Object.keys(value).sort().reduce((sorted, k) => {
2135
- sorted[k] = value[k];
2136
- return sorted;
2137
- }, {});
2138
- }
2139
- return value;
2140
- });
2141
- }
2142
- createEntitySubscriptionKey(props) {
2143
- return `${props.path}|${props.entityId}`;
2144
- }
2145
- }
2146
- function createStorage(transport) {
2147
- const urlsCache = /* @__PURE__ */ new Map();
2148
- async function putObject({
2149
- file,
2150
- key,
2151
- metadata,
2152
- bucket
2153
- }) {
2154
- const formData = new FormData();
2155
- formData.append("file", file);
2156
- if (key) formData.append("key", key);
2157
- if (bucket) formData.append("bucket", bucket);
2158
- if (metadata) {
2159
- for (const [key2, value] of Object.entries(metadata)) {
2160
- if (value !== void 0 && value !== null) {
2161
- formData.append(
2162
- `metadata_${key2}`,
2163
- typeof value === "string" ? value : JSON.stringify(value)
2164
- );
2165
- }
2166
- }
2167
- }
2168
- const result = await transport.request("/storage/upload", {
2169
- method: "POST",
2170
- body: formData,
2171
- headers: {
2172
- // transport.request merges headers, so to prevent it setting application/json we can delete it
2173
- // in transport if body is FormData, or we can explicitly set it to an empty string.
2174
- // Let's rely on standard behaviour for now and adjust transport if it fails.
2175
- }
2176
- });
2177
- return result.data;
2178
- }
2179
- async function getSignedUrl(keyOrUrl, bucket) {
2180
- const cacheKey = bucket ? `${bucket}/${keyOrUrl}` : keyOrUrl;
2181
- const cached = urlsCache.get(cacheKey);
2182
- if (cached) return cached;
2183
- let filePath = keyOrUrl;
2184
- if (filePath && (filePath.startsWith("local://") || filePath.startsWith("s3://"))) {
2185
- filePath = filePath.substring(filePath.indexOf("://") + 3);
2186
- }
2187
- if (bucket && filePath && !filePath.startsWith(bucket)) {
2188
- filePath = `${bucket}/${filePath}`;
2189
- }
2190
- if (!filePath || filePath.trim() === "" || filePath === "/") {
2191
- return {
2192
- url: null,
2193
- fileNotFound: true
2194
- };
2195
- }
2196
- try {
2197
- const result = await transport.request(`/storage/metadata/${filePath}`);
2198
- const activeToken = await transport.resolveToken();
2199
- const tokenQuery = activeToken ? `?token=${activeToken}` : "";
2200
- const downloadConfig = {
2201
- url: `${transport.baseUrl}${transport.apiPath}/storage/file/${filePath}${tokenQuery}`,
2202
- metadata: result.data
2203
- };
2204
- urlsCache.set(cacheKey, downloadConfig);
2205
- return downloadConfig;
2206
- } catch (e) {
2207
- if (e instanceof Error && "status" in e && e.status === 404) {
2208
- return {
2209
- url: null,
2210
- fileNotFound: true
2211
- };
2212
- }
2213
- throw e;
2214
- }
2215
- }
2216
- async function getObject(key, bucket) {
2217
- let filePath = key;
2218
- if (filePath && (filePath.startsWith("local://") || filePath.startsWith("s3://"))) {
2219
- filePath = filePath.substring(filePath.indexOf("://") + 3);
2220
- }
2221
- if (bucket && filePath && !filePath.startsWith(bucket)) {
2222
- filePath = `${bucket}/${filePath}`;
2223
- }
2224
- if (!filePath || filePath.trim() === "" || filePath === "/") {
2225
- return null;
2226
- }
2227
- const url = `${transport.baseUrl}${transport.apiPath}/storage/file/${filePath}`;
2228
- const response = await transport.fetchFn(url, {
2229
- headers: transport.getHeaders ? transport.getHeaders() : {}
2230
- });
2231
- if (response.status === 404) return null;
2232
- if (!response.ok) throw new Error("Failed to get file");
2233
- const blob = await response.blob();
2234
- const fileName = filePath.split("/").pop() || "file";
2235
- return new File([blob], fileName, { type: blob.type });
2236
- }
2237
- async function deleteObject(key, bucket) {
2238
- let filePath = key;
2239
- if (filePath && (filePath.startsWith("local://") || filePath.startsWith("s3://"))) {
2240
- filePath = filePath.substring(filePath.indexOf("://") + 3);
2241
- }
2242
- if (bucket && filePath && !filePath.startsWith(bucket)) {
2243
- filePath = `${bucket}/${filePath}`;
2244
- }
2245
- if (!filePath || filePath.trim() === "" || filePath === "/") {
2246
- return;
2247
- }
2248
- try {
2249
- await transport.request(`/storage/file/${filePath}`, { method: "DELETE" });
2250
- } catch (e) {
2251
- if (!(e instanceof Error && "status" in e && e.status === 404)) throw e;
2252
- }
2253
- urlsCache.delete(bucket ? `${bucket}/${key}` : key);
2254
- }
2255
- async function listObjects(prefix, options) {
2256
- const params = new URLSearchParams();
2257
- if (prefix) params.set("prefix", prefix);
2258
- if (options?.bucket) params.set("bucket", options.bucket);
2259
- if (options?.maxResults) params.set("maxResults", String(options.maxResults));
2260
- if (options?.pageToken) params.set("pageToken", options.pageToken);
2261
- const result = await transport.request(`/storage/list?${params.toString()}`);
2262
- return result.data;
2263
- }
2264
- return {
2265
- putObject,
2266
- getSignedUrl,
2267
- getObject,
2268
- deleteObject,
2269
- listObjects
2270
- };
2271
- }
2272
- function deriveWebSocketUrl(baseUrl) {
2273
- if (typeof window !== "undefined") {
2274
- let absoluteUrl = "";
2275
- if (!baseUrl) {
2276
- absoluteUrl = window.location.origin;
2277
- } else if (/^https?:\/\//i.test(baseUrl) || /^wss?:\/\//i.test(baseUrl)) {
2278
- absoluteUrl = baseUrl;
2279
- } else {
2280
- try {
2281
- absoluteUrl = new URL(baseUrl, window.location.href).origin;
2282
- } catch {
2283
- absoluteUrl = window.location.origin;
2284
- }
2285
- }
2286
- const protocol = absoluteUrl.startsWith("https:") || absoluteUrl.startsWith("wss:") ? "wss:" : "ws:";
2287
- return absoluteUrl.replace(/^https?:\/\//i, `${protocol}//`).replace(/^wss?:\/\//i, `${protocol}//`).replace(/\/$/, "");
2288
- }
2289
- if (!baseUrl) return "";
2290
- if (!/^https?:\/\//i.test(baseUrl) && !/^wss?:\/\//i.test(baseUrl)) {
2291
- return "";
2292
- }
2293
- return baseUrl.replace(/^https?:\/\//i, (match) => match.toLowerCase() === "https://" ? "wss://" : "ws://").replace(/\/$/, "");
2294
- }
2295
- function createRebaseClient(options) {
2296
- const transport = createTransport(options);
2297
- const auth = createAuth(transport, options.auth);
2298
- const admin = createAdmin(transport, options.admin);
2299
- const cron = createCron(transport, options.cron);
2300
- const storage = createStorage(transport);
2301
- const functions = createFunctionsClient(transport);
2302
- const resolvedWsUrl = options.websocketUrl ?? deriveWebSocketUrl(options.baseUrl);
2303
- let ws;
2304
- if (resolvedWsUrl) {
2305
- const wsOnUnauthorized = options.onUnauthorized || (async () => {
2306
- try {
2307
- await auth.refreshSession();
2308
- return true;
2309
- } catch (e) {
2310
- return false;
2311
- }
2312
- });
2313
- ws = new RebaseWebSocketClient({
2314
- websocketUrl: resolvedWsUrl,
2315
- getAuthToken: async () => {
2316
- let session = auth.getSession();
2317
- if (session && session.expiresAt <= Date.now() + 1e4) {
2318
- try {
2319
- session = await auth.refreshSession();
2320
- } catch (e) {
2321
- }
2322
- }
2323
- return session?.accessToken || options.token || "";
2324
- },
2325
- onUnauthorized: wsOnUnauthorized
2326
- });
2327
- auth.onAuthStateChange((event, session) => {
2328
- if (!ws) return;
2329
- if (event === "SIGNED_OUT") {
2330
- ws.disconnect();
2331
- } else if (event === "SIGNED_IN" || event === "TOKEN_REFRESHED") {
2332
- if (session?.accessToken) {
2333
- ws.authenticate(session.accessToken).catch(console.warn);
2334
- }
2335
- }
2336
- });
2337
- }
2338
- if (!options.onUnauthorized) {
2339
- transport.setOnUnauthorized(async () => {
2340
- try {
2341
- await auth.refreshSession();
2342
- return true;
2343
- } catch (e) {
2344
- return false;
2345
- }
2346
- });
2347
- }
2348
- const collectionClients = /* @__PURE__ */ new Map();
2349
- function collection(slug) {
2350
- if (!collectionClients.has(slug)) {
2351
- collectionClients.set(slug, createCollectionClient(transport, slug, ws));
2352
- }
2353
- return collectionClients.get(slug);
2354
- }
2355
- const dataTarget = { collection };
2356
- const dataProxy = new Proxy(dataTarget, {
2357
- get(_target, prop) {
2358
- if (prop === "collection") {
2359
- return collection;
2360
- }
2361
- if (typeof prop === "symbol") return void 0;
2362
- if (typeof prop === "string" && prop !== "then" && prop !== "toJSON" && prop !== "$$typeof") {
2363
- const slug = utils.toSnakeCase(prop);
2364
- return collection(slug);
2365
- }
2366
- return void 0;
2367
- }
2368
- });
2369
- const target = {
2370
- auth,
2371
- admin,
2372
- cron,
2373
- functions,
2374
- storage,
2375
- ws,
2376
- setToken: transport.setToken,
2377
- setAuthTokenGetter: transport.setAuthTokenGetter,
2378
- setOnUnauthorized: transport.setOnUnauthorized,
2379
- resolveToken: transport.resolveToken,
2380
- baseUrl: transport.baseUrl,
2381
- collection,
2382
- call: async (endpoint, payload) => {
2383
- const prefix = endpoint.startsWith("/") ? "" : "/";
2384
- const res = await transport.request(`${prefix}${endpoint}`, {
2385
- method: "POST",
2386
- body: payload ? JSON.stringify(payload) : void 0
2387
- });
2388
- return res.data ?? res;
2389
- },
2390
- data: dataProxy,
2391
- email: void 0
2392
- };
2393
- return target;
2394
- }
2395
- Object.defineProperty(exports2, "QueryBuilder", {
2396
- enumerable: true,
2397
- get: () => common.QueryBuilder
2398
- });
2399
- Object.defineProperty(exports2, "and", {
2400
- enumerable: true,
2401
- get: () => common.and
2402
- });
2403
- Object.defineProperty(exports2, "cond", {
2404
- enumerable: true,
2405
- get: () => common.cond
2406
- });
2407
- Object.defineProperty(exports2, "or", {
2408
- enumerable: true,
2409
- get: () => common.or
2410
- });
2411
- exports2.ApiError = ApiError;
2412
- exports2.RebaseApiError = RebaseApiError;
2413
- exports2.RebaseWebSocketClient = RebaseWebSocketClient;
2414
- exports2.buildQueryString = buildQueryString;
2415
- exports2.createAdmin = createAdmin;
2416
- exports2.createAuth = createAuth;
2417
- exports2.createCollectionClient = createCollectionClient;
2418
- exports2.createCookieStorage = createCookieStorage;
2419
- exports2.createCron = createCron;
2420
- exports2.createFunctionsClient = createFunctionsClient;
2421
- exports2.createMemoryStorage = createMemoryStorage;
2422
- exports2.createRebaseClient = createRebaseClient;
2423
- exports2.createStorage = createStorage;
2424
- exports2.createTransport = createTransport;
2425
- exports2.rebaseReviver = rebaseReviver;
2426
- Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
2
+ typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("@rebasepro/types"), require("@rebasepro/common"), require("@rebasepro/utils")) : typeof define === "function" && define.amd ? define([
3
+ "exports",
4
+ "@rebasepro/types",
5
+ "@rebasepro/common",
6
+ "@rebasepro/utils"
7
+ ], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global["Rebase Client"] = {}, global._rebasepro_types, global._rebasepro_common, global._rebasepro_utils));
8
+ })(this, function(exports, _rebasepro_types, _rebasepro_common, _rebasepro_utils) {
9
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
10
+ //#region src/reviver.ts
11
+ function rebaseReviver(_key, value) {
12
+ if (value && typeof value === "object" && "__type" in value) {
13
+ const record = value;
14
+ switch (record.__type) {
15
+ case "date":
16
+ case "Date": {
17
+ if (typeof record.value !== "string") return value;
18
+ const date = new Date(record.value);
19
+ return isNaN(date.getTime()) ? null : date;
20
+ }
21
+ case "reference":
22
+ case "EntityReference": return new _rebasepro_types.EntityReference({
23
+ id: String(record.id),
24
+ path: record.path,
25
+ driver: record.driver,
26
+ databaseId: record.databaseId
27
+ });
28
+ case "relation":
29
+ case "EntityRelation": return new _rebasepro_types.EntityRelation(record.id, record.path, record.data);
30
+ case "GeoPoint": return new _rebasepro_types.GeoPoint(record.latitude, record.longitude);
31
+ case "Vector": return new _rebasepro_types.Vector(record.value);
32
+ default: return value;
33
+ }
34
+ }
35
+ return value;
36
+ }
37
+ //#endregion
38
+ //#region src/transport.ts
39
+ var RebaseApiError = class extends Error {
40
+ status;
41
+ code;
42
+ details;
43
+ constructor(status, message, code, details) {
44
+ super(message);
45
+ this.name = "RebaseApiError";
46
+ this.status = status;
47
+ this.code = code;
48
+ this.details = details;
49
+ }
50
+ };
51
+ /**
52
+ * Maps a short operator alias to the PostgREST-style short code.
53
+ */
54
+ var OP_MAP = {
55
+ "==": "eq",
56
+ "!=": "neq",
57
+ ">": "gt",
58
+ ">=": "gte",
59
+ "<": "lt",
60
+ "<=": "lte",
61
+ "not-in": "nin",
62
+ "array-contains": "cs",
63
+ "array-contains-any": "csa"
64
+ };
65
+ /**
66
+ * Normalise a single `WhereFieldValue` into the PostgREST query-string
67
+ * representation the backend expects.
68
+ *
69
+ * Supports:
70
+ * - `null` → `"eq.null"`
71
+ * - `true`/`false` → `"eq.true"` / `"eq.false"`
72
+ * - `42` → `"42"` (plain equality)
73
+ * - `"active"` → `"active"` (plain equality, backward-compat)
74
+ * - `"gte.18"` → `"gte.18"` (pass-through PostgREST string)
75
+ * - `[">=", 18]` → `"gte.18"` (tuple syntax)
76
+ * - `["in", [1,2]]` → `"in.(1,2)"` (tuple with array value)
77
+ * - `["!=", null]` → `"neq.null"`
78
+ */
79
+ function normalizeWhereValue(value) {
80
+ if (value === null) return "eq.null";
81
+ if (typeof value === "boolean") return `eq.${value}`;
82
+ if (typeof value === "number") return String(value);
83
+ if (Array.isArray(value)) {
84
+ const [rawOp, val] = (Array.isArray(value[0]) ? value : [value])[0] || [];
85
+ if (rawOp) {
86
+ const op = OP_MAP[rawOp] ?? rawOp;
87
+ if (val === null) return `${op}.null`;
88
+ if (Array.isArray(val)) return `${op}.(${val.join(",")})`;
89
+ return `${op}.${val}`;
90
+ }
91
+ }
92
+ return String(value);
93
+ }
94
+ function serializeLogicalCondition(cond) {
95
+ if ("type" in cond) {
96
+ const sub = cond.conditions.map(serializeLogicalCondition).join(",");
97
+ return `${cond.type}(${sub})`;
98
+ } else {
99
+ const op = OP_MAP[cond.operator] ?? cond.operator;
100
+ let formattedValue = cond.value;
101
+ if (Array.isArray(cond.value)) formattedValue = `(${cond.value.join(",")})`;
102
+ else if (cond.value === null) formattedValue = "null";
103
+ return `${cond.column}.${op}.${formattedValue}`;
104
+ }
105
+ }
106
+ function buildQueryString(params) {
107
+ if (!params) return "";
108
+ const parts = [];
109
+ if (params.limit != null) parts.push(`limit=${params.limit}`);
110
+ if (params.offset != null) parts.push(`offset=${params.offset}`);
111
+ if (params.page != null) parts.push(`page=${params.page}`);
112
+ if (params.orderBy) parts.push(`orderBy=${encodeURIComponent(params.orderBy)}`);
113
+ if (params.searchString) parts.push(`searchString=${encodeURIComponent(params.searchString)}`);
114
+ if (params.include && params.include.length > 0) parts.push(`include=${encodeURIComponent(params.include.join(","))}`);
115
+ if (params.logical) {
116
+ const root = params.logical;
117
+ const serialized = root.conditions.map(serializeLogicalCondition).join(",");
118
+ parts.push(`${root.type}=${encodeURIComponent(`(${serialized})`)}`);
119
+ }
120
+ if (params.where) for (const [field, value] of Object.entries(params.where)) if (Array.isArray(value) && value.length > 0 && Array.isArray(value[0])) for (const subVal of value) {
121
+ const normalized = normalizeWhereValue(subVal);
122
+ parts.push(`${encodeURIComponent(field)}=${encodeURIComponent(normalized)}`);
123
+ }
124
+ else {
125
+ const normalized = normalizeWhereValue(value);
126
+ parts.push(`${encodeURIComponent(field)}=${encodeURIComponent(normalized)}`);
127
+ }
128
+ return parts.length > 0 ? "?" + parts.join("&") : "";
129
+ }
130
+ function createTransport(config) {
131
+ const fetchFn = config.fetch || globalThis.fetch;
132
+ const apiPath = config.apiPath || "/api";
133
+ let token = config.token;
134
+ let tokenGetter;
135
+ let onUnauthorizedHandler = config.onUnauthorized;
136
+ function getHeaders(activeToken, init) {
137
+ return {
138
+ "Content-Type": "application/json",
139
+ ...activeToken ? { Authorization: `Bearer ${activeToken}` } : {},
140
+ ...init?.headers || {}
141
+ };
142
+ }
143
+ async function request(path, init) {
144
+ const url = (config.baseUrl ? config.baseUrl.replace(/\/$/, "") : "") + apiPath + path;
145
+ let activeToken = token;
146
+ if (tokenGetter) try {
147
+ const fetched = await tokenGetter();
148
+ if (fetched !== null && fetched !== void 0) activeToken = fetched;
149
+ } catch (e) {}
150
+ const headers = getHeaders(activeToken, init);
151
+ if (init?.body instanceof FormData) delete headers["Content-Type"];
152
+ const res = await fetchFn(url, {
153
+ ...init,
154
+ headers
155
+ });
156
+ if (res.status === 204) return void 0;
157
+ const text = await res.text().catch(() => "");
158
+ let body = {};
159
+ if (text) try {
160
+ body = JSON.parse(text, rebaseReviver);
161
+ } catch (e) {}
162
+ const getErrorField = (obj, field) => {
163
+ const err = obj?.error;
164
+ if (err && typeof err === "object" && err !== null && field in err) return err[field];
165
+ return obj?.[field];
166
+ };
167
+ if (res.status === 401 && onUnauthorizedHandler) {
168
+ if (await onUnauthorizedHandler()) {
169
+ let retryToken = token;
170
+ if (tokenGetter) try {
171
+ const fetched = await tokenGetter();
172
+ if (fetched !== null && fetched !== void 0) retryToken = fetched;
173
+ } catch (e) {}
174
+ const retryHeaders = getHeaders(retryToken, init);
175
+ const retryRes = await fetchFn(url, {
176
+ ...init,
177
+ headers: retryHeaders
178
+ });
179
+ if (retryRes.status === 204) return void 0;
180
+ const retryText = await retryRes.text().catch(() => "");
181
+ let retryBody = {};
182
+ if (retryText) try {
183
+ retryBody = JSON.parse(retryText, rebaseReviver);
184
+ } catch (e) {}
185
+ if (!retryRes.ok) {
186
+ let fallbackMessage = retryRes.statusText;
187
+ if (retryRes.status === 404 && !fallbackMessage) fallbackMessage = `Endpoint not found (${init?.method || "GET"} ${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.`;
188
+ throw new RebaseApiError(retryRes.status, String(getErrorField(retryBody, "message") || fallbackMessage || `Request failed with status ${retryRes.status}`), getErrorField(retryBody, "code"), getErrorField(retryBody, "details"));
189
+ }
190
+ return retryBody;
191
+ }
192
+ }
193
+ if (!res.ok) {
194
+ let fallbackMessage = res.statusText;
195
+ if (res.status === 404 && !fallbackMessage) fallbackMessage = `Endpoint not found (${init?.method || "GET"} ${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.`;
196
+ throw new RebaseApiError(res.status, String(getErrorField(body, "message") || fallbackMessage || `Request failed with status ${res.status}`), getErrorField(body, "code"), getErrorField(body, "details"));
197
+ }
198
+ return body;
199
+ }
200
+ return {
201
+ request,
202
+ setToken(newToken) {
203
+ token = newToken || void 0;
204
+ },
205
+ setAuthTokenGetter(getter) {
206
+ tokenGetter = getter;
207
+ },
208
+ setOnUnauthorized(handler) {
209
+ onUnauthorizedHandler = handler;
210
+ },
211
+ get baseUrl() {
212
+ return config.baseUrl ? config.baseUrl.replace(/\/$/, "") : "";
213
+ },
214
+ get apiPath() {
215
+ return apiPath;
216
+ },
217
+ get fetchFn() {
218
+ return fetchFn;
219
+ },
220
+ getHeaders: (init) => getHeaders(token, init),
221
+ resolveToken: async () => {
222
+ if (tokenGetter) try {
223
+ const fetched = await tokenGetter();
224
+ if (fetched !== null && fetched !== void 0) return fetched;
225
+ } catch (e) {}
226
+ return token || null;
227
+ }
228
+ };
229
+ }
230
+ //#endregion
231
+ //#region src/auth.ts
232
+ function createMemoryStorage() {
233
+ const store = {};
234
+ return {
235
+ getItem(key) {
236
+ return store[key] ?? null;
237
+ },
238
+ setItem(key, value) {
239
+ store[key] = value;
240
+ },
241
+ removeItem(key) {
242
+ delete store[key];
243
+ }
244
+ };
245
+ }
246
+ function detectStorage() {
247
+ try {
248
+ if (typeof localStorage !== "undefined") {
249
+ localStorage.setItem("__rebase_test__", "1");
250
+ localStorage.removeItem("__rebase_test__");
251
+ return localStorage;
252
+ }
253
+ } catch (e) {}
254
+ return createMemoryStorage();
255
+ }
256
+ function createAuth(transport, options) {
257
+ const opts = options || {};
258
+ const storage = opts.storage || detectStorage();
259
+ const authPath = opts.authPath || "/auth";
260
+ const autoRefresh = opts.autoRefresh !== false;
261
+ const persistSession = opts.persistSession !== false;
262
+ const STORAGE_KEY = "rebase_auth";
263
+ const REFRESH_BUFFER_MS = 12e4;
264
+ let currentSession = null;
265
+ const listeners = /* @__PURE__ */ new Set();
266
+ let refreshTimeout = null;
267
+ function authUrl(endpoint) {
268
+ return transport.baseUrl + transport.apiPath + authPath + endpoint;
269
+ }
270
+ function getFetch() {
271
+ return transport.fetchFn || globalThis.fetch;
272
+ }
273
+ function throwApiError(status, body, statusText) {
274
+ throw new RebaseApiError(status, body?.error?.message || body?.message || statusText, body?.error?.code || body?.code, body?.error?.details || body?.details);
275
+ }
276
+ function emit(event, session) {
277
+ for (const fn of listeners) try {
278
+ fn(event, session);
279
+ } catch (e) {}
280
+ }
281
+ function saveSession(session) {
282
+ if (!persistSession) return;
283
+ try {
284
+ storage.setItem(STORAGE_KEY, JSON.stringify(session));
285
+ } catch (e) {}
286
+ }
287
+ function clearStoredSession() {
288
+ try {
289
+ storage.removeItem(STORAGE_KEY);
290
+ } catch (e) {}
291
+ }
292
+ function loadStoredSession() {
293
+ try {
294
+ const raw = storage.getItem(STORAGE_KEY);
295
+ if (raw) return JSON.parse(raw);
296
+ } catch (e) {}
297
+ return null;
298
+ }
299
+ function scheduleRefresh(expiresAt) {
300
+ if (refreshTimeout) clearTimeout(refreshTimeout);
301
+ if (!autoRefresh) return;
302
+ const delay = expiresAt - REFRESH_BUFFER_MS - Date.now();
303
+ if (delay <= 0) {
304
+ refreshSession().catch(() => signOut());
305
+ return;
306
+ }
307
+ refreshTimeout = setTimeout(async () => {
308
+ try {
309
+ await refreshSession();
310
+ } catch (e) {
311
+ signOut();
312
+ }
313
+ }, delay);
314
+ }
315
+ function handleAuthResponse(data, event) {
316
+ const session = {
317
+ accessToken: data.tokens.accessToken,
318
+ refreshToken: data.tokens.refreshToken,
319
+ expiresAt: data.tokens.accessTokenExpiresAt,
320
+ user: data.user
321
+ };
322
+ currentSession = session;
323
+ saveSession(session);
324
+ transport.setToken(session.accessToken);
325
+ scheduleRefresh(session.expiresAt);
326
+ emit(event || "SIGNED_IN", session);
327
+ return session;
328
+ }
329
+ async function signInWithEmail(email, password) {
330
+ const res = await getFetch()(authUrl("/login"), {
331
+ method: "POST",
332
+ headers: { "Content-Type": "application/json" },
333
+ body: JSON.stringify({
334
+ email,
335
+ password
336
+ })
337
+ });
338
+ const body = await res.json().catch(() => ({}));
339
+ if (!res.ok) throwApiError(res.status, body, res.statusText);
340
+ const session = handleAuthResponse(body, "SIGNED_IN");
341
+ return {
342
+ user: session.user,
343
+ accessToken: session.accessToken,
344
+ refreshToken: session.refreshToken
345
+ };
346
+ }
347
+ async function signUp(email, password, displayName) {
348
+ const fetchFn = getFetch();
349
+ const payload = {
350
+ email,
351
+ password
352
+ };
353
+ if (displayName !== void 0) payload.displayName = displayName;
354
+ const res = await fetchFn(authUrl("/register"), {
355
+ method: "POST",
356
+ headers: { "Content-Type": "application/json" },
357
+ body: JSON.stringify(payload)
358
+ });
359
+ const body = await res.json().catch(() => ({}));
360
+ if (!res.ok) throwApiError(res.status, body, res.statusText);
361
+ const session = handleAuthResponse(body, "SIGNED_IN");
362
+ return {
363
+ user: session.user,
364
+ accessToken: session.accessToken,
365
+ refreshToken: session.refreshToken
366
+ };
367
+ }
368
+ /**
369
+ * Sign in with Google.
370
+ *
371
+ * Supports three invocation styles:
372
+ * - `signInWithGoogle({ idToken })` — ID-token flow (One Tap / Sign In button)
373
+ * - `signInWithGoogle({ accessToken })` — Access-token flow (popup)
374
+ * - `signInWithGoogle({ code, redirectUri })` — Authorization code flow (most secure)
375
+ */
376
+ async function signInWithGoogle(payload) {
377
+ const res = await getFetch()(authUrl("/google"), {
378
+ method: "POST",
379
+ headers: { "Content-Type": "application/json" },
380
+ body: JSON.stringify(payload)
381
+ });
382
+ const responseBody = await res.json().catch(() => ({}));
383
+ if (!res.ok) throwApiError(res.status, responseBody, res.statusText);
384
+ const session = handleAuthResponse(responseBody, "SIGNED_IN");
385
+ return {
386
+ user: session.user,
387
+ accessToken: session.accessToken,
388
+ refreshToken: session.refreshToken
389
+ };
390
+ }
391
+ async function signInWithLinkedin(code, redirectUri) {
392
+ const res = await getFetch()(authUrl("/linkedin"), {
393
+ method: "POST",
394
+ headers: { "Content-Type": "application/json" },
395
+ body: JSON.stringify({
396
+ code,
397
+ redirectUri
398
+ })
399
+ });
400
+ const body = await res.json().catch(() => ({}));
401
+ if (!res.ok) throwApiError(res.status, body, res.statusText);
402
+ const session = handleAuthResponse(body, "SIGNED_IN");
403
+ return {
404
+ user: session.user,
405
+ accessToken: session.accessToken,
406
+ refreshToken: session.refreshToken
407
+ };
408
+ }
409
+ /**
410
+ * Generic OAuth sign-in. Posts the given payload to `/auth/{providerId}`.
411
+ * Use this for any provider registered on the backend.
412
+ */
413
+ async function signInWithOAuth(providerId, payload) {
414
+ const res = await getFetch()(authUrl(`/${providerId}`), {
415
+ method: "POST",
416
+ headers: { "Content-Type": "application/json" },
417
+ body: JSON.stringify(payload)
418
+ });
419
+ const body = await res.json().catch(() => ({}));
420
+ if (!res.ok) throwApiError(res.status, body, res.statusText);
421
+ const session = handleAuthResponse(body, "SIGNED_IN");
422
+ return {
423
+ user: session.user,
424
+ accessToken: session.accessToken,
425
+ refreshToken: session.refreshToken
426
+ };
427
+ }
428
+ async function signInWithGitHub(code, redirectUri) {
429
+ return signInWithOAuth("github", {
430
+ code,
431
+ redirectUri
432
+ });
433
+ }
434
+ async function signInWithMicrosoft(code, redirectUri) {
435
+ return signInWithOAuth("microsoft", {
436
+ code,
437
+ redirectUri
438
+ });
439
+ }
440
+ async function signInWithApple(code, redirectUri, user) {
441
+ return signInWithOAuth("apple", {
442
+ code,
443
+ redirectUri,
444
+ user
445
+ });
446
+ }
447
+ async function signInWithFacebook(code, redirectUri) {
448
+ return signInWithOAuth("facebook", {
449
+ code,
450
+ redirectUri
451
+ });
452
+ }
453
+ async function signInWithTwitter(code, redirectUri, codeVerifier) {
454
+ return signInWithOAuth("twitter", {
455
+ code,
456
+ redirectUri,
457
+ codeVerifier
458
+ });
459
+ }
460
+ async function signInWithDiscord(code, redirectUri) {
461
+ return signInWithOAuth("discord", {
462
+ code,
463
+ redirectUri
464
+ });
465
+ }
466
+ async function signInWithGitLab(code, redirectUri) {
467
+ return signInWithOAuth("gitlab", {
468
+ code,
469
+ redirectUri
470
+ });
471
+ }
472
+ async function signInWithBitbucket(code, redirectUri) {
473
+ return signInWithOAuth("bitbucket", {
474
+ code,
475
+ redirectUri
476
+ });
477
+ }
478
+ async function signInWithSlack(code, redirectUri) {
479
+ return signInWithOAuth("slack", {
480
+ code,
481
+ redirectUri
482
+ });
483
+ }
484
+ async function signInWithSpotify(code, redirectUri) {
485
+ return signInWithOAuth("spotify", {
486
+ code,
487
+ redirectUri
488
+ });
489
+ }
490
+ async function signOut() {
491
+ const fetchFn = getFetch();
492
+ try {
493
+ if (currentSession?.refreshToken) await fetchFn(authUrl("/logout"), {
494
+ method: "POST",
495
+ headers: { "Content-Type": "application/json" },
496
+ body: JSON.stringify({ refreshToken: currentSession.refreshToken })
497
+ });
498
+ } catch (e) {}
499
+ currentSession = null;
500
+ clearStoredSession();
501
+ if (refreshTimeout) {
502
+ clearTimeout(refreshTimeout);
503
+ refreshTimeout = null;
504
+ }
505
+ transport.setToken(null);
506
+ emit("SIGNED_OUT", null);
507
+ }
508
+ async function refreshSession() {
509
+ if (!currentSession?.refreshToken) throw new Error("No active session to refresh");
510
+ const res = await getFetch()(authUrl("/refresh"), {
511
+ method: "POST",
512
+ headers: { "Content-Type": "application/json" },
513
+ body: JSON.stringify({ refreshToken: currentSession.refreshToken })
514
+ });
515
+ const body = await res.json().catch(() => ({}));
516
+ if (!res.ok) throwApiError(res.status, body, res.statusText);
517
+ const session = {
518
+ accessToken: body.tokens.accessToken,
519
+ refreshToken: body.tokens.refreshToken,
520
+ expiresAt: body.tokens.accessTokenExpiresAt,
521
+ user: currentSession.user
522
+ };
523
+ currentSession = session;
524
+ saveSession(session);
525
+ transport.setToken(session.accessToken);
526
+ scheduleRefresh(session.expiresAt);
527
+ emit("TOKEN_REFRESHED", session);
528
+ return session;
529
+ }
530
+ async function getUser() {
531
+ return (await transport.request(authPath + "/me", { method: "GET" })).user;
532
+ }
533
+ async function updateUser(updates) {
534
+ const data = await transport.request(authPath + "/me", {
535
+ method: "PATCH",
536
+ body: JSON.stringify(updates)
537
+ });
538
+ if (currentSession) {
539
+ currentSession = {
540
+ ...currentSession,
541
+ user: data.user
542
+ };
543
+ saveSession(currentSession);
544
+ emit("USER_UPDATED", currentSession);
545
+ }
546
+ return data.user;
547
+ }
548
+ async function resetPasswordForEmail(email) {
549
+ const res = await getFetch()(authUrl("/forgot-password"), {
550
+ method: "POST",
551
+ headers: { "Content-Type": "application/json" },
552
+ body: JSON.stringify({ email })
553
+ });
554
+ const body = await res.json().catch(() => ({}));
555
+ if (!res.ok) throwApiError(res.status, body, res.statusText);
556
+ return body;
557
+ }
558
+ async function resetPassword(token, password) {
559
+ const res = await getFetch()(authUrl("/reset-password"), {
560
+ method: "POST",
561
+ headers: { "Content-Type": "application/json" },
562
+ body: JSON.stringify({
563
+ token,
564
+ password
565
+ })
566
+ });
567
+ const body = await res.json().catch(() => ({}));
568
+ if (!res.ok) throwApiError(res.status, body, res.statusText);
569
+ return body;
570
+ }
571
+ async function changePassword(oldPassword, newPassword) {
572
+ return transport.request(authPath + "/change-password", {
573
+ method: "POST",
574
+ body: JSON.stringify({
575
+ oldPassword,
576
+ newPassword
577
+ })
578
+ });
579
+ }
580
+ async function sendVerificationEmail() {
581
+ return transport.request(authPath + "/send-verification", { method: "POST" });
582
+ }
583
+ async function verifyEmail(token) {
584
+ const res = await getFetch()(authUrl("/verify-email?token=" + encodeURIComponent(token)), {
585
+ method: "GET",
586
+ headers: { "Content-Type": "application/json" }
587
+ });
588
+ const body = await res.json().catch(() => ({}));
589
+ if (!res.ok) throwApiError(res.status, body, res.statusText);
590
+ return body;
591
+ }
592
+ async function getSessions() {
593
+ return (await transport.request(authPath + "/sessions", { method: "GET" })).sessions;
594
+ }
595
+ async function revokeSession(sessionId) {
596
+ return transport.request(authPath + "/sessions/" + encodeURIComponent(sessionId), { method: "DELETE" });
597
+ }
598
+ async function revokeAllSessions() {
599
+ const result = await transport.request(authPath + "/sessions", { method: "DELETE" });
600
+ currentSession = null;
601
+ clearStoredSession();
602
+ if (refreshTimeout) {
603
+ clearTimeout(refreshTimeout);
604
+ refreshTimeout = null;
605
+ }
606
+ transport.setToken(null);
607
+ emit("SIGNED_OUT", null);
608
+ return result;
609
+ }
610
+ async function getAuthConfig() {
611
+ const res = await getFetch()(authUrl("/config"), {
612
+ method: "GET",
613
+ headers: { "Content-Type": "application/json" }
614
+ });
615
+ const body = await res.json().catch(() => ({}));
616
+ if (!res.ok) throwApiError(res.status, body, res.statusText);
617
+ return body;
618
+ }
619
+ function getSession() {
620
+ return currentSession;
621
+ }
622
+ function onAuthStateChange(callback) {
623
+ listeners.add(callback);
624
+ return () => listeners.delete(callback);
625
+ }
626
+ if (persistSession) {
627
+ const stored = loadStoredSession();
628
+ if (stored && stored.accessToken && stored.refreshToken) {
629
+ if (stored.expiresAt > Date.now()) {
630
+ currentSession = stored;
631
+ transport.setToken(stored.accessToken);
632
+ scheduleRefresh(stored.expiresAt);
633
+ } else if (stored.refreshToken) {
634
+ currentSession = stored;
635
+ refreshSession().catch(() => {
636
+ currentSession = null;
637
+ clearStoredSession();
638
+ transport.setToken(null);
639
+ });
640
+ }
641
+ }
642
+ }
643
+ return {
644
+ signInWithEmail,
645
+ signUp,
646
+ signInWithGoogle,
647
+ signInWithLinkedin,
648
+ signInWithOAuth,
649
+ signInWithGitHub,
650
+ signInWithMicrosoft,
651
+ signInWithApple,
652
+ signInWithFacebook,
653
+ signInWithTwitter,
654
+ signInWithDiscord,
655
+ signInWithGitLab,
656
+ signInWithBitbucket,
657
+ signInWithSlack,
658
+ signInWithSpotify,
659
+ signOut,
660
+ refreshSession,
661
+ getUser,
662
+ updateUser,
663
+ resetPasswordForEmail,
664
+ resetPassword,
665
+ changePassword,
666
+ sendVerificationEmail,
667
+ verifyEmail,
668
+ getSessions,
669
+ revokeSession,
670
+ revokeAllSessions,
671
+ getAuthConfig,
672
+ getSession,
673
+ onAuthStateChange
674
+ };
675
+ }
676
+ function createCookieStorage(options = {}) {
677
+ const defaultOptions = {
678
+ path: "/",
679
+ sameSite: "Lax",
680
+ ...options
681
+ };
682
+ return {
683
+ getItem(key) {
684
+ if (typeof document === "undefined") return null;
685
+ const nameEQ = encodeURIComponent(key) + "=";
686
+ const ca = document.cookie.split(";");
687
+ for (let i = 0; i < ca.length; i++) {
688
+ let c = ca[i];
689
+ while (c.charAt(0) === " ") c = c.substring(1, c.length);
690
+ if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
691
+ }
692
+ return null;
693
+ },
694
+ setItem(key, value) {
695
+ if (typeof document === "undefined") return;
696
+ let cookieStr = `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
697
+ if (defaultOptions.path) cookieStr += `; path=${defaultOptions.path}`;
698
+ if (defaultOptions.domain) cookieStr += `; domain=${defaultOptions.domain}`;
699
+ if (defaultOptions.maxAge !== void 0) cookieStr += `; max-age=${defaultOptions.maxAge}`;
700
+ else cookieStr += `; max-age=${365 * 24 * 60 * 60}`;
701
+ if (defaultOptions.secure) cookieStr += "; secure";
702
+ if (defaultOptions.sameSite) cookieStr += `; samesite=${defaultOptions.sameSite}`;
703
+ document.cookie = cookieStr;
704
+ },
705
+ removeItem(key) {
706
+ if (typeof document === "undefined") return;
707
+ let cookieStr = `${encodeURIComponent(key)}=; path=${defaultOptions.path || "/"}; max-age=-1`;
708
+ if (defaultOptions.domain) cookieStr += `; domain=${defaultOptions.domain}`;
709
+ document.cookie = cookieStr;
710
+ }
711
+ };
712
+ }
713
+ //#endregion
714
+ //#region src/admin.ts
715
+ function createAdmin(transport, options) {
716
+ const adminPath = (options || {}).adminPath || "/admin";
717
+ async function listUsers() {
718
+ return transport.request(adminPath + "/users", { method: "GET" });
719
+ }
720
+ async function listUsersPaginated(options) {
721
+ const params = new URLSearchParams();
722
+ if (options?.limit !== void 0) params.set("limit", String(options.limit));
723
+ if (options?.offset !== void 0) params.set("offset", String(options.offset));
724
+ if (options?.search) params.set("search", options.search);
725
+ if (options?.orderBy) params.set("orderBy", options.orderBy);
726
+ if (options?.orderDir) params.set("orderDir", options.orderDir);
727
+ const qs = params.toString();
728
+ return transport.request(adminPath + "/users" + (qs ? "?" + qs : ""), { method: "GET" });
729
+ }
730
+ async function getUser(userId) {
731
+ return transport.request(adminPath + "/users/" + encodeURIComponent(userId), { method: "GET" });
732
+ }
733
+ async function createUser(data) {
734
+ return transport.request(adminPath + "/users", {
735
+ method: "POST",
736
+ body: JSON.stringify(data)
737
+ });
738
+ }
739
+ async function updateUser(userId, data) {
740
+ return transport.request(adminPath + "/users/" + encodeURIComponent(userId), {
741
+ method: "PUT",
742
+ body: JSON.stringify(data)
743
+ });
744
+ }
745
+ async function deleteUser(userId) {
746
+ return transport.request(adminPath + "/users/" + encodeURIComponent(userId), { method: "DELETE" });
747
+ }
748
+ async function bootstrap() {
749
+ return transport.request(adminPath + "/bootstrap", { method: "POST" });
750
+ }
751
+ return {
752
+ listUsers,
753
+ listUsersPaginated,
754
+ getUser,
755
+ createUser,
756
+ updateUser,
757
+ deleteUser,
758
+ bootstrap
759
+ };
760
+ }
761
+ //#endregion
762
+ //#region src/cron.ts
763
+ function createCron(transport, options) {
764
+ const cronPath = options?.cronPath || "/cron";
765
+ async function listJobs() {
766
+ return transport.request(cronPath, { method: "GET" });
767
+ }
768
+ async function getJob(jobId) {
769
+ return transport.request(cronPath + "/" + encodeURIComponent(jobId), { method: "GET" });
770
+ }
771
+ async function triggerJob(jobId) {
772
+ return transport.request(cronPath + "/" + encodeURIComponent(jobId) + "/trigger", { method: "POST" });
773
+ }
774
+ async function getJobLogs(jobId, options) {
775
+ const params = new URLSearchParams();
776
+ if (options?.limit !== void 0) params.set("limit", String(options.limit));
777
+ const qs = params.toString();
778
+ return transport.request(cronPath + "/" + encodeURIComponent(jobId) + "/logs" + (qs ? "?" + qs : ""), { method: "GET" });
779
+ }
780
+ async function toggleJob(jobId, enabled) {
781
+ return transport.request(cronPath + "/" + encodeURIComponent(jobId), {
782
+ method: "PUT",
783
+ body: JSON.stringify({ enabled })
784
+ });
785
+ }
786
+ return {
787
+ listJobs,
788
+ getJob,
789
+ triggerJob,
790
+ getJobLogs,
791
+ toggleJob
792
+ };
793
+ }
794
+ //#endregion
795
+ //#region src/collection.ts
796
+ function parseWhereFilter(where) {
797
+ if (!where) return void 0;
798
+ const filters = {};
799
+ const OP_TO_FILTER = {
800
+ "eq": "==",
801
+ "neq": "!=",
802
+ "gt": ">",
803
+ "gte": ">=",
804
+ "lt": "<",
805
+ "lte": "<=",
806
+ "==": "==",
807
+ "!=": "!=",
808
+ ">": ">",
809
+ ">=": ">=",
810
+ "<": "<",
811
+ "<=": "<=",
812
+ "in": "in",
813
+ "nin": "not-in",
814
+ "not-in": "not-in",
815
+ "cs": "array-contains",
816
+ "csa": "array-contains-any",
817
+ "array-contains": "array-contains",
818
+ "array-contains-any": "array-contains-any"
819
+ };
820
+ const parseSingle = (rawValue, fieldKey) => {
821
+ if (rawValue === null) return ["==", null];
822
+ if (typeof rawValue === "boolean") return ["==", rawValue];
823
+ if (typeof rawValue === "number") return ["==", rawValue];
824
+ if (Array.isArray(rawValue) && rawValue.length === 2 && typeof rawValue[0] === "string") {
825
+ const [rawOp, val] = rawValue;
826
+ return [OP_TO_FILTER[rawOp] ?? "==", val];
827
+ }
828
+ const value = String(rawValue);
829
+ const dotIndex = value.indexOf(".");
830
+ if (dotIndex > 0) {
831
+ const opStr = value.substring(0, dotIndex);
832
+ const valStr = value.substring(dotIndex + 1);
833
+ let op = "==";
834
+ let val = valStr;
835
+ switch (opStr) {
836
+ case "eq":
837
+ op = "==";
838
+ break;
839
+ case "neq":
840
+ op = "!=";
841
+ break;
842
+ case "gt":
843
+ op = ">";
844
+ break;
845
+ case "gte":
846
+ op = ">=";
847
+ break;
848
+ case "lt":
849
+ op = "<";
850
+ break;
851
+ case "lte":
852
+ op = "<=";
853
+ break;
854
+ case "in":
855
+ op = "in";
856
+ val = valStr.startsWith("(") && valStr.endsWith(")") ? valStr.slice(1, -1).split(",").map((v) => v.trim()) : valStr.split(",");
857
+ break;
858
+ case "nin":
859
+ op = "not-in";
860
+ val = valStr.startsWith("(") && valStr.endsWith(")") ? valStr.slice(1, -1).split(",").map((v) => v.trim()) : valStr.split(",");
861
+ break;
862
+ case "cs":
863
+ op = "array-contains";
864
+ break;
865
+ case "csa":
866
+ op = "array-contains-any";
867
+ val = valStr.startsWith("(") && valStr.endsWith(")") ? valStr.slice(1, -1).split(",").map((v) => v.trim()) : valStr.split(",");
868
+ break;
869
+ default:
870
+ op = "==";
871
+ val = value;
872
+ }
873
+ if (val === "true") val = true;
874
+ else if (val === "false") val = false;
875
+ else if (val === "null") val = null;
876
+ else if (typeof val === "string" && /^[0-9]+(\.[0-9]+)?$/.test(val) && fieldKey !== "id" && !fieldKey.endsWith("_id")) val = Number(val);
877
+ return [op, val];
878
+ } else return ["==", value];
879
+ };
880
+ for (const [key, rawValue] of Object.entries(where)) if (Array.isArray(rawValue) && rawValue.length > 0 && Array.isArray(rawValue[0])) filters[key] = rawValue.map((r) => parseSingle(r, key));
881
+ else filters[key] = parseSingle(rawValue, key);
882
+ return filters;
883
+ }
884
+ /**
885
+ * Wrap a flat row (returned by the REST API as `{ id, ...fields }`) into
886
+ * a proper `Entity<M>` structure expected by the core framework.
887
+ * The `id` is kept inside `values` as well, since collection properties
888
+ * may define an `isId` field that the form binds to `formex.values`.
889
+ */
890
+ function rowToEntity(row, slug) {
891
+ return {
892
+ id: row.id,
893
+ path: slug,
894
+ values: row
895
+ };
896
+ }
897
+ function createCollectionClient(transport, slug, ws) {
898
+ const basePath = `/data/${slug}`;
899
+ const client = {
900
+ async find(params) {
901
+ const qs = buildQueryString(params);
902
+ const raw = await transport.request(basePath + qs, { method: "GET" });
903
+ return {
904
+ data: (raw.data || []).map((row) => rowToEntity(row, slug)),
905
+ meta: raw.meta
906
+ };
907
+ },
908
+ async findById(id) {
909
+ try {
910
+ const raw = await transport.request(`${basePath}/${encodeURIComponent(String(id))}`, { method: "GET" });
911
+ if (!raw) return void 0;
912
+ return rowToEntity(raw, slug);
913
+ } catch (err) {
914
+ if (err instanceof RebaseApiError && err.status === 404) return;
915
+ throw err;
916
+ }
917
+ },
918
+ async create(data, id) {
919
+ const body = { ...data };
920
+ if (id !== void 0) body.id = id;
921
+ return rowToEntity(await transport.request(basePath, {
922
+ method: "POST",
923
+ body: JSON.stringify(body)
924
+ }), slug);
925
+ },
926
+ async update(id, data) {
927
+ return rowToEntity(await transport.request(`${basePath}/${encodeURIComponent(String(id))}`, {
928
+ method: "PUT",
929
+ body: JSON.stringify(data)
930
+ }), slug);
931
+ },
932
+ async delete(id) {
933
+ return transport.request(`${basePath}/${encodeURIComponent(String(id))}`, { method: "DELETE" });
934
+ },
935
+ async count(params) {
936
+ const qs = buildQueryString({
937
+ ...params,
938
+ limit: void 0,
939
+ offset: void 0
940
+ });
941
+ return (await transport.request(basePath + "/count" + qs, { method: "GET" })).count ?? 0;
942
+ },
943
+ where(columnOrCondition, operator, value) {
944
+ const builder = new _rebasepro_common.QueryBuilder(client);
945
+ if (typeof columnOrCondition === "object") return builder.where(columnOrCondition);
946
+ return builder.where(columnOrCondition, operator, value);
947
+ },
948
+ orderBy(column, ascending) {
949
+ return new _rebasepro_common.QueryBuilder(client).orderBy(column, ascending);
950
+ },
951
+ limit(count) {
952
+ return new _rebasepro_common.QueryBuilder(client).limit(count);
953
+ },
954
+ offset(count) {
955
+ return new _rebasepro_common.QueryBuilder(client).offset(count);
956
+ },
957
+ search(searchString) {
958
+ return new _rebasepro_common.QueryBuilder(client).search(searchString);
959
+ },
960
+ include(...relations) {
961
+ return new _rebasepro_common.QueryBuilder(client).include(...relations);
962
+ }
963
+ };
964
+ if (ws) {
965
+ client.listen = (params, onUpdate, onError) => {
966
+ return ws.listenCollection({
967
+ path: slug,
968
+ filter: parseWhereFilter(params?.where),
969
+ limit: params?.limit,
970
+ startAfter: params?.offset ? String(params.offset) : void 0,
971
+ orderBy: params?.orderBy?.split(":")[0],
972
+ order: params?.orderBy?.split(":")[1],
973
+ searchString: params?.searchString
974
+ }, (entities) => {
975
+ const requestedLimit = params?.limit || 20;
976
+ onUpdate({
977
+ data: entities,
978
+ meta: {
979
+ total: entities.length,
980
+ limit: requestedLimit,
981
+ offset: params?.offset || 0,
982
+ hasMore: entities.length >= requestedLimit
983
+ }
984
+ });
985
+ }, onError);
986
+ };
987
+ client.listenById = (id, onUpdate, onError) => {
988
+ return ws.listenEntity({
989
+ path: slug,
990
+ entityId: String(id)
991
+ }, (entity) => {
992
+ if (entity) onUpdate(entity);
993
+ else onUpdate(void 0);
994
+ }, onError);
995
+ };
996
+ }
997
+ return client;
998
+ }
999
+ //#endregion
1000
+ //#region src/functions.ts
1001
+ /**
1002
+ * Create a `FunctionsClient` backed by the given transport.
1003
+ *
1004
+ * The transport already handles:
1005
+ * - Base URL resolution
1006
+ * - JWT injection via `Authorization: Bearer`
1007
+ * - 401 retry / `onUnauthorized` flow
1008
+ * - Consistent error throwing via `RebaseApiError`
1009
+ *
1010
+ * @internal
1011
+ */
1012
+ function createFunctionsClient(transport) {
1013
+ return { async invoke(name, payload, options) {
1014
+ const method = options?.method ?? "POST";
1015
+ const subPath = options?.path ? `/${options.path.replace(/^\//, "")}` : "";
1016
+ const routePath = `/functions/${encodeURIComponent(name)}${subPath}`;
1017
+ const init = { method };
1018
+ if (payload !== void 0 && method !== "GET") init.body = JSON.stringify(payload);
1019
+ if (options?.headers) init.headers = options.headers;
1020
+ return transport.request(routePath, init);
1021
+ } };
1022
+ }
1023
+ //#endregion
1024
+ //#region src/storage.ts
1025
+ function createStorage(transport) {
1026
+ const urlsCache = /* @__PURE__ */ new Map();
1027
+ async function putObject({ file, key, metadata, bucket }) {
1028
+ const formData = new FormData();
1029
+ formData.append("file", file);
1030
+ if (key) formData.append("key", key);
1031
+ if (bucket) formData.append("bucket", bucket);
1032
+ if (metadata) {
1033
+ for (const [key, value] of Object.entries(metadata)) if (value !== void 0 && value !== null) formData.append(`metadata_${key}`, typeof value === "string" ? value : JSON.stringify(value));
1034
+ }
1035
+ return (await transport.request("/storage/upload", {
1036
+ method: "POST",
1037
+ body: formData,
1038
+ headers: {}
1039
+ })).data;
1040
+ }
1041
+ async function getSignedUrl(keyOrUrl, bucket) {
1042
+ const cacheKey = bucket ? `${bucket}/${keyOrUrl}` : keyOrUrl;
1043
+ const cached = urlsCache.get(cacheKey);
1044
+ if (cached) return cached;
1045
+ let filePath = keyOrUrl;
1046
+ if (filePath && (filePath.startsWith("local://") || filePath.startsWith("s3://"))) filePath = filePath.substring(filePath.indexOf("://") + 3);
1047
+ if (bucket && filePath && !filePath.startsWith(bucket)) filePath = `${bucket}/${filePath}`;
1048
+ if (!filePath || filePath.trim() === "" || filePath === "/") return {
1049
+ url: null,
1050
+ fileNotFound: true
1051
+ };
1052
+ try {
1053
+ const result = await transport.request(`/storage/metadata/${filePath}`);
1054
+ const activeToken = await transport.resolveToken();
1055
+ const tokenQuery = activeToken ? `?token=${activeToken}` : "";
1056
+ const downloadConfig = {
1057
+ url: `${transport.baseUrl}${transport.apiPath}/storage/file/${filePath}${tokenQuery}`,
1058
+ metadata: result.data
1059
+ };
1060
+ urlsCache.set(cacheKey, downloadConfig);
1061
+ return downloadConfig;
1062
+ } catch (e) {
1063
+ if (e instanceof Error && "status" in e && e.status === 404) return {
1064
+ url: null,
1065
+ fileNotFound: true
1066
+ };
1067
+ throw e;
1068
+ }
1069
+ }
1070
+ async function getObject(key, bucket) {
1071
+ let filePath = key;
1072
+ if (filePath && (filePath.startsWith("local://") || filePath.startsWith("s3://"))) filePath = filePath.substring(filePath.indexOf("://") + 3);
1073
+ if (bucket && filePath && !filePath.startsWith(bucket)) filePath = `${bucket}/${filePath}`;
1074
+ if (!filePath || filePath.trim() === "" || filePath === "/") return null;
1075
+ const url = `${transport.baseUrl}${transport.apiPath}/storage/file/${filePath}`;
1076
+ const response = await transport.fetchFn(url, { headers: transport.getHeaders ? transport.getHeaders() : {} });
1077
+ if (response.status === 404) return null;
1078
+ if (!response.ok) throw new Error("Failed to get file");
1079
+ const blob = await response.blob();
1080
+ const fileName = filePath.split("/").pop() || "file";
1081
+ return new File([blob], fileName, { type: blob.type });
1082
+ }
1083
+ async function deleteObject(key, bucket) {
1084
+ let filePath = key;
1085
+ if (filePath && (filePath.startsWith("local://") || filePath.startsWith("s3://"))) filePath = filePath.substring(filePath.indexOf("://") + 3);
1086
+ if (bucket && filePath && !filePath.startsWith(bucket)) filePath = `${bucket}/${filePath}`;
1087
+ if (!filePath || filePath.trim() === "" || filePath === "/") return;
1088
+ try {
1089
+ await transport.request(`/storage/file/${filePath}`, { method: "DELETE" });
1090
+ } catch (e) {
1091
+ if (!(e instanceof Error && "status" in e && e.status === 404)) throw e;
1092
+ }
1093
+ urlsCache.delete(bucket ? `${bucket}/${key}` : key);
1094
+ }
1095
+ async function listObjects(prefix, options) {
1096
+ const params = new URLSearchParams();
1097
+ if (prefix) params.set("prefix", prefix);
1098
+ if (options?.bucket) params.set("bucket", options.bucket);
1099
+ if (options?.maxResults) params.set("maxResults", String(options.maxResults));
1100
+ if (options?.pageToken) params.set("pageToken", options.pageToken);
1101
+ return (await transport.request(`/storage/list?${params.toString()}`)).data;
1102
+ }
1103
+ return {
1104
+ putObject,
1105
+ getSignedUrl,
1106
+ getObject,
1107
+ deleteObject,
1108
+ listObjects
1109
+ };
1110
+ }
1111
+ //#endregion
1112
+ //#region src/websocket.ts
1113
+ /**
1114
+ * Extract error message and code from a WebSocket message payload.
1115
+ * Handles both `{ error: string }` and `{ error: { message, code } }` shapes.
1116
+ */
1117
+ function extractMessageError(message) {
1118
+ const payload = message.payload;
1119
+ const errPayload = payload?.error;
1120
+ return {
1121
+ errorMessage: typeof errPayload === "object" ? errPayload.message : payload?.message || (typeof errPayload === "string" ? errPayload : void 0) || message.error || "Unknown error",
1122
+ errorCode: typeof errPayload === "object" ? errPayload.code : payload?.code
1123
+ };
1124
+ }
1125
+ var ApiError = class extends Error {
1126
+ code;
1127
+ error;
1128
+ constructor(message, error, code) {
1129
+ super(message);
1130
+ this.name = "ApiError";
1131
+ this.code = code;
1132
+ this.error = error;
1133
+ }
1134
+ };
1135
+ var RebaseWebSocketClient = class {
1136
+ websocketUrl;
1137
+ ws = null;
1138
+ getAuthToken;
1139
+ subscriptions = /* @__PURE__ */ new Map();
1140
+ listeners = /* @__PURE__ */ new Map();
1141
+ on(event, cb) {
1142
+ if (!this.listeners.has(event)) this.listeners.set(event, /* @__PURE__ */ new Set());
1143
+ this.listeners.get(event).add(cb);
1144
+ return () => this.listeners.get(event).delete(cb);
1145
+ }
1146
+ emit(event, ...args) {
1147
+ if (this.listeners.has(event)) this.listeners.get(event).forEach((cb) => cb(...args));
1148
+ }
1149
+ collectionSubscriptions = /* @__PURE__ */ new Map();
1150
+ entitySubscriptions = /* @__PURE__ */ new Map();
1151
+ backendToCollectionKey = /* @__PURE__ */ new Map();
1152
+ backendToEntityKey = /* @__PURE__ */ new Map();
1153
+ pendingRequests = /* @__PURE__ */ new Map();
1154
+ reconnectAttempts = 0;
1155
+ maxReconnectAttempts = 5;
1156
+ isConnected = false;
1157
+ messageQueue = [];
1158
+ requestTimeoutMs = 3e4;
1159
+ reconnectTimeout = null;
1160
+ isAuthenticated = false;
1161
+ authPromise = null;
1162
+ WebSocketConstructor;
1163
+ onUnauthorized;
1164
+ refreshInProgress = null;
1165
+ constructor(config) {
1166
+ this.websocketUrl = config.websocketUrl;
1167
+ this.getAuthToken = config.getAuthToken;
1168
+ this.onUnauthorized = config.onUnauthorized;
1169
+ this.WebSocketConstructor = config.WebSocket || (typeof WebSocket !== "undefined" ? WebSocket : void 0);
1170
+ if (!this.WebSocketConstructor) console.warn("WebSocket is not defined in this environment. Realtime subscriptions will not work unless you provide a WebSocket implementation in the config.");
1171
+ else this.initWebSocket();
1172
+ }
1173
+ /**
1174
+ * Authenticate the WebSocket connection
1175
+ */
1176
+ async authenticate(token) {
1177
+ return new Promise((resolve, reject) => {
1178
+ const requestId = `auth_${Date.now()}`;
1179
+ const timeout = setTimeout(() => {
1180
+ this.pendingRequests.delete(requestId);
1181
+ this.authPromise = null;
1182
+ reject(/* @__PURE__ */ new Error("Authentication timeout"));
1183
+ }, 3e4);
1184
+ this.pendingRequests.set(requestId, {
1185
+ resolve: () => {
1186
+ clearTimeout(timeout);
1187
+ this.isAuthenticated = true;
1188
+ resolve();
1189
+ },
1190
+ reject: (error) => {
1191
+ clearTimeout(timeout);
1192
+ reject(error);
1193
+ }
1194
+ });
1195
+ const message = {
1196
+ type: "AUTHENTICATE",
1197
+ requestId,
1198
+ payload: { token }
1199
+ };
1200
+ if (!this.isConnected || !this.ws) this.messageQueue.unshift(message);
1201
+ else this.ws.send(JSON.stringify(message));
1202
+ });
1203
+ }
1204
+ /**
1205
+ * Set the auth token getter function
1206
+ */
1207
+ setAuthTokenGetter(getAuthToken) {
1208
+ this.getAuthToken = getAuthToken;
1209
+ if (this.isConnected && !this.isAuthenticated && !this.authPromise) {
1210
+ console.debug("WebSocket auto-authenticating after token getter set");
1211
+ this.getAuthToken().then((token) => {
1212
+ if (!this.ws) return;
1213
+ if (token) this.authenticate(token).catch((e) => {
1214
+ if (this.ws) console.debug("WebSocket auto-auth skipped:", e?.message || e);
1215
+ });
1216
+ }).catch((e) => {
1217
+ if (this.ws) console.debug("WebSocket auto-auth skipped:", e?.message || e);
1218
+ });
1219
+ }
1220
+ }
1221
+ disconnect() {
1222
+ this.isAuthenticated = false;
1223
+ this.authPromise = null;
1224
+ if (this.reconnectTimeout) {
1225
+ clearTimeout(this.reconnectTimeout);
1226
+ this.reconnectTimeout = null;
1227
+ }
1228
+ if (this.ws) {
1229
+ this.ws.onclose = null;
1230
+ this.ws.onerror = null;
1231
+ this.ws.onopen = null;
1232
+ this.ws.onmessage = null;
1233
+ this.ws.close();
1234
+ this.ws = null;
1235
+ }
1236
+ }
1237
+ initWebSocket() {
1238
+ if (!this.WebSocketConstructor) return;
1239
+ if (this.ws?.readyState === this.WebSocketConstructor.OPEN) return;
1240
+ if (this.ws) {
1241
+ this.ws.onclose = null;
1242
+ this.ws.close();
1243
+ this.ws = null;
1244
+ }
1245
+ try {
1246
+ this.ws = new this.WebSocketConstructor(this.websocketUrl);
1247
+ this.ws.onopen = async () => {
1248
+ console.debug("Connected to PostgreSQL backend");
1249
+ const wasReconnect = this.reconnectAttempts > 0;
1250
+ this.isConnected = true;
1251
+ this.reconnectAttempts = 0;
1252
+ if (this.getAuthToken && !this.isAuthenticated) try {
1253
+ const token = await this.getAuthToken();
1254
+ if (token) {
1255
+ await this.authenticate(token);
1256
+ console.debug("WebSocket auto-authenticated");
1257
+ }
1258
+ } catch (error) {
1259
+ console.debug("WebSocket connected without auth:", error?.message || error);
1260
+ }
1261
+ this.emit(wasReconnect ? "reconnect" : "connect");
1262
+ this.processMessageQueue();
1263
+ if (wasReconnect) this.resubscribeAll();
1264
+ };
1265
+ this.ws.onmessage = (event) => {
1266
+ try {
1267
+ const message = JSON.parse(event.data, rebaseReviver);
1268
+ this.handleWebSocketMessage(message);
1269
+ } catch (error) {
1270
+ console.error("Error parsing WebSocket message:", error);
1271
+ }
1272
+ };
1273
+ this.ws.onclose = () => {
1274
+ console.debug("Disconnected from PostgreSQL backend");
1275
+ this.isConnected = false;
1276
+ this.isAuthenticated = false;
1277
+ this.authPromise = null;
1278
+ this.emit("disconnect");
1279
+ for (const [reqId, request] of this.pendingRequests.entries()) {
1280
+ if (reqId.startsWith("auth_")) request.reject(/* @__PURE__ */ new Error("Connection closed during authentication"));
1281
+ else if (request.message) {
1282
+ request.message._queuedResolve = request.resolve;
1283
+ request.message._queuedReject = request.reject;
1284
+ this.messageQueue.push(request.message);
1285
+ } else request.reject(new ApiError("Connection closed", "Connection closed"));
1286
+ this.pendingRequests.delete(reqId);
1287
+ }
1288
+ this.attemptReconnect();
1289
+ };
1290
+ this.ws.onerror = (error) => {
1291
+ console.error("WebSocket error:", error);
1292
+ this.isConnected = false;
1293
+ this.emit("error", error);
1294
+ };
1295
+ } catch (error) {
1296
+ console.error("Failed to initialize WebSocket:", error);
1297
+ this.attemptReconnect();
1298
+ }
1299
+ }
1300
+ processMessageQueue() {
1301
+ while (this.messageQueue.length > 0 && this.isConnected) {
1302
+ const message = this.messageQueue.shift();
1303
+ if (message) this.sendMessage(message);
1304
+ }
1305
+ }
1306
+ attemptReconnect() {
1307
+ if (this.reconnectAttempts >= this.maxReconnectAttempts) {
1308
+ console.error("Max reconnection attempts reached");
1309
+ return;
1310
+ }
1311
+ this.reconnectAttempts++;
1312
+ const delay = Math.min(1e3 * Math.pow(2, this.reconnectAttempts), 3e4);
1313
+ console.debug(`Attempting to reconnect in ${delay}ms (attempt ${this.reconnectAttempts})`);
1314
+ if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
1315
+ this.reconnectTimeout = setTimeout(() => {
1316
+ this.reconnectTimeout = null;
1317
+ this.initWebSocket();
1318
+ }, delay);
1319
+ }
1320
+ isAuthError(message) {
1321
+ if (message.type === "AUTH_ERROR") return true;
1322
+ const { errorMessage, errorCode } = extractMessageError(message);
1323
+ if (errorCode === "UNAUTHORIZED" || errorCode === "JWT_EXPIRED" || errorCode === "AUTH_ERROR") return true;
1324
+ const lowerMessage = errorMessage.toLowerCase();
1325
+ return lowerMessage.includes("unauthorized") || lowerMessage.includes("token expired") || lowerMessage.includes("token is expired") || lowerMessage.includes("invalid token") || lowerMessage.includes("session expired") || lowerMessage.includes("auth error");
1326
+ }
1327
+ async handleAuthFailure() {
1328
+ if (this.refreshInProgress) return this.refreshInProgress;
1329
+ this.refreshInProgress = (async () => {
1330
+ this.isAuthenticated = false;
1331
+ this.authPromise = null;
1332
+ if (this.onUnauthorized) try {
1333
+ if (await this.onUnauthorized() && this.getAuthToken) {
1334
+ const token = await this.getAuthToken();
1335
+ if (token) {
1336
+ await this.authenticate(token);
1337
+ return true;
1338
+ }
1339
+ }
1340
+ } catch (error) {
1341
+ console.error("WebSocket auth refresh failed:", error);
1342
+ }
1343
+ return false;
1344
+ })();
1345
+ try {
1346
+ return await this.refreshInProgress;
1347
+ } finally {
1348
+ this.refreshInProgress = null;
1349
+ }
1350
+ }
1351
+ /**
1352
+ * Shared logic for re-subscribing a collection or entity subscription
1353
+ * after an auth error is resolved by refreshing credentials.
1354
+ */
1355
+ resubscribeAfterAuthRefresh(message, subscription, subscriptionKey, idPrefix, backendKeyMap, messageType) {
1356
+ this.handleAuthFailure().then((refreshed) => {
1357
+ if (refreshed) {
1358
+ const oldBackendId = subscription.backendSubscriptionId;
1359
+ const newBackendId = `${idPrefix}_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
1360
+ subscription.backendSubscriptionId = newBackendId;
1361
+ backendKeyMap.delete(oldBackendId);
1362
+ backendKeyMap.set(newBackendId, subscriptionKey);
1363
+ this.sendMessage({
1364
+ type: messageType,
1365
+ payload: {
1366
+ ...subscription.props,
1367
+ subscriptionId: newBackendId
1368
+ }
1369
+ }).catch((error) => {
1370
+ console.error(`[WS] Failed to re-subscribe ${idPrefix} after auth refresh:`, subscriptionKey, error);
1371
+ subscription.callbacks.forEach((callback) => {
1372
+ if (callback.onError) callback.onError(error);
1373
+ });
1374
+ });
1375
+ } else {
1376
+ const { errorMessage, errorCode } = extractMessageError(message);
1377
+ const error = new ApiError(errorMessage, errorMessage, errorCode);
1378
+ subscription.callbacks.forEach((callback) => {
1379
+ if (callback.onError) callback.onError(error);
1380
+ });
1381
+ }
1382
+ }).catch((err) => {
1383
+ subscription.callbacks.forEach((callback) => {
1384
+ if (callback.onError) callback.onError(err);
1385
+ });
1386
+ });
1387
+ }
1388
+ handleWebSocketMessage(message) {
1389
+ const { type, requestId, subscriptionId } = message;
1390
+ if (requestId && this.pendingRequests.has(requestId)) {
1391
+ const pendingReq = this.pendingRequests.get(requestId);
1392
+ if (type === "ERROR" || type === "AUTH_ERROR" || message.error) if (this.isAuthError(message)) {
1393
+ this.pendingRequests.delete(requestId);
1394
+ this.handleAuthFailure().then((refreshed) => {
1395
+ if (refreshed && pendingReq.message) this.doSendMessage(pendingReq.message, pendingReq.resolve, pendingReq.reject).catch(pendingReq.reject);
1396
+ else {
1397
+ const { errorMessage, errorCode } = extractMessageError(message);
1398
+ pendingReq.reject(new ApiError(errorMessage, errorMessage, errorCode));
1399
+ }
1400
+ }).catch((err) => {
1401
+ pendingReq.reject(err);
1402
+ });
1403
+ } else {
1404
+ this.pendingRequests.delete(requestId);
1405
+ const { errorMessage, errorCode } = extractMessageError(message);
1406
+ pendingReq.reject(new ApiError(errorMessage, errorMessage, errorCode));
1407
+ }
1408
+ else {
1409
+ this.pendingRequests.delete(requestId);
1410
+ pendingReq.resolve(message.payload || message);
1411
+ }
1412
+ return;
1413
+ }
1414
+ if (subscriptionId && type === "collection_update") {
1415
+ const subscriptionKey = this.backendToCollectionKey.get(subscriptionId);
1416
+ if (subscriptionKey) {
1417
+ const collectionSub = this.collectionSubscriptions.get(subscriptionKey);
1418
+ if (collectionSub) {
1419
+ const incomingEntities = message.entities || [];
1420
+ const entities = this.mergeEntities(collectionSub.latestData, incomingEntities);
1421
+ collectionSub.latestData = entities;
1422
+ collectionSub.lastUpdated = Date.now();
1423
+ collectionSub.isInitialDataReceived = true;
1424
+ collectionSub.callbacks.forEach((callback) => {
1425
+ try {
1426
+ callback.onUpdate(entities);
1427
+ } catch (error) {
1428
+ console.error("Error in collection subscription callback:", error);
1429
+ if (callback.onError) callback.onError(error instanceof Error ? error : new Error(String(error)));
1430
+ }
1431
+ });
1432
+ return;
1433
+ }
1434
+ }
1435
+ }
1436
+ if (subscriptionId && type === "collection_entity_patch") {
1437
+ const subscriptionKey = this.backendToCollectionKey.get(subscriptionId);
1438
+ if (subscriptionKey) {
1439
+ const collectionSub = this.collectionSubscriptions.get(subscriptionKey);
1440
+ if (collectionSub && collectionSub.isInitialDataReceived && collectionSub.latestData) {
1441
+ const patchEntity = message.entity ?? null;
1442
+ const patchEntityId = message.entityId;
1443
+ let updated;
1444
+ if (patchEntity === null || patchEntity === void 0) updated = collectionSub.latestData.filter((e) => String(e.id) !== String(patchEntityId));
1445
+ else {
1446
+ const idx = collectionSub.latestData.findIndex((e) => String(e.id) === String(patchEntity.id));
1447
+ if (idx >= 0) {
1448
+ updated = [...collectionSub.latestData];
1449
+ updated[idx] = patchEntity;
1450
+ } else updated = [patchEntity, ...collectionSub.latestData];
1451
+ }
1452
+ collectionSub.latestData = updated;
1453
+ collectionSub.lastUpdated = Date.now();
1454
+ collectionSub.callbacks.forEach((callback) => {
1455
+ try {
1456
+ callback.onUpdate(updated);
1457
+ } catch (error) {
1458
+ console.error("Error in collection patch callback:", error);
1459
+ if (callback.onError) callback.onError(error instanceof Error ? error : new Error(String(error)));
1460
+ }
1461
+ });
1462
+ return;
1463
+ }
1464
+ }
1465
+ }
1466
+ if (subscriptionId && type === "entity_update") {
1467
+ const subscriptionKey = this.backendToEntityKey.get(subscriptionId);
1468
+ if (subscriptionKey) {
1469
+ const entitySub = this.entitySubscriptions.get(subscriptionKey);
1470
+ if (entitySub) {
1471
+ const entity = message.entity ?? null;
1472
+ entitySub.latestData = entity;
1473
+ entitySub.lastUpdated = Date.now();
1474
+ entitySub.isInitialDataReceived = true;
1475
+ entitySub.callbacks.forEach((callback) => {
1476
+ try {
1477
+ callback.onUpdate(entity);
1478
+ } catch (error) {
1479
+ console.error("Error in entity subscription callback:", error);
1480
+ if (callback.onError) callback.onError(error instanceof Error ? error : new Error(String(error)));
1481
+ }
1482
+ });
1483
+ return;
1484
+ }
1485
+ }
1486
+ }
1487
+ if (subscriptionId && (type === "ERROR" || message.error)) {
1488
+ const collectionKey = this.backendToCollectionKey.get(subscriptionId);
1489
+ if (collectionKey) {
1490
+ const collectionSub = this.collectionSubscriptions.get(collectionKey);
1491
+ if (collectionSub) {
1492
+ if (this.isAuthError(message)) {
1493
+ this.resubscribeAfterAuthRefresh(message, collectionSub, collectionKey, "collection", this.backendToCollectionKey, "subscribe_collection");
1494
+ return;
1495
+ }
1496
+ const { errorMessage, errorCode } = extractMessageError(message);
1497
+ const error = new ApiError(errorMessage, errorMessage, errorCode);
1498
+ collectionSub.callbacks.forEach((callback) => {
1499
+ if (callback.onError) callback.onError(error);
1500
+ });
1501
+ return;
1502
+ }
1503
+ }
1504
+ const entityKey = this.backendToEntityKey.get(subscriptionId);
1505
+ if (entityKey) {
1506
+ const entitySub = this.entitySubscriptions.get(entityKey);
1507
+ if (entitySub) {
1508
+ if (this.isAuthError(message)) {
1509
+ this.resubscribeAfterAuthRefresh(message, entitySub, entityKey, "entity", this.backendToEntityKey, "subscribe_entity");
1510
+ return;
1511
+ }
1512
+ const { errorMessage, errorCode } = extractMessageError(message);
1513
+ const error = new ApiError(errorMessage, errorMessage, errorCode);
1514
+ entitySub.callbacks.forEach((callback) => {
1515
+ if (callback.onError) callback.onError(error);
1516
+ });
1517
+ return;
1518
+ }
1519
+ }
1520
+ }
1521
+ if (subscriptionId && this.subscriptions.has(subscriptionId)) {
1522
+ const callback = this.subscriptions.get(subscriptionId);
1523
+ if (!callback) throw new Error(`Subscription callback not found for subscriptionId: ${subscriptionId}`);
1524
+ if (message.type === "ERROR" || message.error) {
1525
+ if (callback.onError) {
1526
+ const { errorMessage, errorCode } = extractMessageError(message);
1527
+ callback.onError(new ApiError(errorMessage, errorMessage, errorCode));
1528
+ }
1529
+ } else callback.onUpdate(message);
1530
+ }
1531
+ }
1532
+ async ensureAuthenticated(retryCount = 3) {
1533
+ if (this.isAuthenticated || !this.getAuthToken) return;
1534
+ if (this.authPromise) {
1535
+ await this.authPromise;
1536
+ return;
1537
+ }
1538
+ let lastError = null;
1539
+ for (let attempt = 0; attempt < retryCount; attempt++) try {
1540
+ const token = await this.getAuthToken();
1541
+ if (!token) throw new Error("user not logged in");
1542
+ this.authPromise = this.authenticate(token);
1543
+ await this.authPromise;
1544
+ this.authPromise = null;
1545
+ console.debug("WebSocket authenticated on demand");
1546
+ return;
1547
+ } catch (error) {
1548
+ this.authPromise = null;
1549
+ lastError = error;
1550
+ const errMsg = error instanceof Error ? error.message : String(error);
1551
+ if (errMsg.includes("not logged in") || errMsg.includes("Session expired")) {
1552
+ console.warn("WebSocket auth failed: user not logged in");
1553
+ throw error;
1554
+ }
1555
+ if (errMsg.includes("still loading")) {
1556
+ if (attempt < retryCount - 1) {
1557
+ const delay = Math.min(500 * (attempt + 1), 2e3);
1558
+ await new Promise((resolve) => setTimeout(resolve, delay));
1559
+ continue;
1560
+ }
1561
+ }
1562
+ if (attempt < retryCount - 1) {
1563
+ const delay = Math.min(1e3 * (attempt + 1), 3e3);
1564
+ console.debug(`WebSocket auth attempt ${attempt + 1} failed, retrying in ${delay}ms...`);
1565
+ await new Promise((resolve) => setTimeout(resolve, delay));
1566
+ }
1567
+ }
1568
+ console.warn("WebSocket on-demand auth failed after retries:", lastError);
1569
+ throw lastError;
1570
+ }
1571
+ async reauthenticate() {
1572
+ if (!this.getAuthToken) return;
1573
+ this.isAuthenticated = false;
1574
+ try {
1575
+ const token = await this.getAuthToken();
1576
+ if (!token) throw new Error("user not logged in");
1577
+ await this.authenticate(token);
1578
+ console.debug("WebSocket reauthenticated successfully");
1579
+ } catch (error) {
1580
+ console.error("WebSocket reauthentication failed:", error);
1581
+ throw error;
1582
+ }
1583
+ }
1584
+ sendMessage(message) {
1585
+ const queuedMsg = message;
1586
+ if (queuedMsg._queuedResolve && queuedMsg._queuedReject) return this.doSendMessage(message, queuedMsg._queuedResolve, queuedMsg._queuedReject);
1587
+ if (!this.isConnected || !this.ws) return new Promise((resolve, reject) => {
1588
+ const queueable = message;
1589
+ queueable._queuedResolve = resolve;
1590
+ queueable._queuedReject = reject;
1591
+ this.messageQueue.push(message);
1592
+ });
1593
+ return new Promise((resolve, reject) => {
1594
+ this.doSendMessage(message, resolve, reject);
1595
+ });
1596
+ }
1597
+ async doSendMessage(message, resolve, reject) {
1598
+ if (message.type !== "AUTHENTICATE" && this.getAuthToken && !this.isAuthenticated) try {
1599
+ await this.ensureAuthenticated();
1600
+ } catch (error) {
1601
+ const errorMessage = error instanceof Error ? error.message : "Authentication required";
1602
+ reject(new ApiError(errorMessage, errorMessage));
1603
+ return;
1604
+ }
1605
+ const requestId = message.requestId || `req_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
1606
+ message.requestId = requestId;
1607
+ const expectsResponse = ![
1608
+ "subscribe_collection",
1609
+ "subscribe_entity",
1610
+ "unsubscribe",
1611
+ "join_channel",
1612
+ "leave_channel",
1613
+ "broadcast",
1614
+ "presence_track",
1615
+ "presence_untrack",
1616
+ "presence_state"
1617
+ ].includes(message.type);
1618
+ if (expectsResponse && !this.pendingRequests.has(requestId)) {
1619
+ const timeoutHandle = setTimeout(() => {
1620
+ if (this.pendingRequests.has(requestId)) {
1621
+ this.pendingRequests.delete(requestId);
1622
+ reject(new ApiError("Request timed out", "Request timed out"));
1623
+ }
1624
+ }, this.requestTimeoutMs);
1625
+ this.pendingRequests.set(requestId, {
1626
+ resolve: (value) => {
1627
+ clearTimeout(timeoutHandle);
1628
+ resolve(value);
1629
+ },
1630
+ reject: (error) => {
1631
+ clearTimeout(timeoutHandle);
1632
+ reject(error);
1633
+ },
1634
+ message
1635
+ });
1636
+ }
1637
+ try {
1638
+ this.ws.send(JSON.stringify(message));
1639
+ if (!expectsResponse) resolve(void 0);
1640
+ } catch (error) {
1641
+ if (expectsResponse) this.pendingRequests.delete(requestId);
1642
+ reject(new ApiError("Failed to send message", error instanceof Error ? error.message : "Unknown error"));
1643
+ }
1644
+ }
1645
+ async fetchCollection(props) {
1646
+ return (await this.sendMessage({
1647
+ type: "FETCH_COLLECTION",
1648
+ payload: props
1649
+ })).entities || [];
1650
+ }
1651
+ async fetchEntity(props) {
1652
+ return (await this.sendMessage({
1653
+ type: "FETCH_ENTITY",
1654
+ payload: props
1655
+ })).entity ?? void 0;
1656
+ }
1657
+ async saveEntity(props) {
1658
+ return (await this.sendMessage({
1659
+ type: "SAVE_ENTITY",
1660
+ payload: props
1661
+ })).entity;
1662
+ }
1663
+ async deleteEntity(props) {
1664
+ await this.sendMessage({
1665
+ type: "DELETE_ENTITY",
1666
+ payload: props
1667
+ });
1668
+ }
1669
+ async executeSql(sql, options) {
1670
+ return (await this.sendMessage({
1671
+ type: "EXECUTE_SQL",
1672
+ payload: {
1673
+ sql,
1674
+ options
1675
+ }
1676
+ })).result || [];
1677
+ }
1678
+ async fetchAvailableDatabases() {
1679
+ return (await this.sendMessage({
1680
+ type: "FETCH_DATABASES",
1681
+ payload: {}
1682
+ })).databases || [];
1683
+ }
1684
+ async fetchAvailableRoles() {
1685
+ return (await this.sendMessage({ type: "FETCH_ROLES" })).roles || [];
1686
+ }
1687
+ async fetchCurrentDatabase() {
1688
+ return (await this.sendMessage({ type: "FETCH_CURRENT_DATABASE" })).database;
1689
+ }
1690
+ async checkUniqueField(path, name, value, entityId, collection) {
1691
+ return (await this.sendMessage({
1692
+ type: "CHECK_UNIQUE_FIELD",
1693
+ payload: {
1694
+ path,
1695
+ name,
1696
+ value,
1697
+ entityId,
1698
+ collection
1699
+ }
1700
+ })).isUnique;
1701
+ }
1702
+ async countEntities(props) {
1703
+ return (await this.sendMessage({
1704
+ type: "COUNT_ENTITIES",
1705
+ payload: props
1706
+ })).count;
1707
+ }
1708
+ async fetchUnmappedTables(mappedPaths) {
1709
+ return (await this.sendMessage({
1710
+ type: "FETCH_UNMAPPED_TABLES",
1711
+ payload: { mappedPaths }
1712
+ })).tables || [];
1713
+ }
1714
+ async fetchTableMetadata(tableName) {
1715
+ return (await this.sendMessage({
1716
+ type: "FETCH_TABLE_METADATA",
1717
+ payload: { tableName }
1718
+ })).metadata || {
1719
+ columns: [],
1720
+ foreignKeys: [],
1721
+ junctions: [],
1722
+ policies: []
1723
+ };
1724
+ }
1725
+ async createBranch(name, options) {
1726
+ return (await this.sendMessage({
1727
+ type: "CREATE_BRANCH",
1728
+ payload: {
1729
+ name,
1730
+ options
1731
+ }
1732
+ })).branch;
1733
+ }
1734
+ async deleteBranch(name) {
1735
+ await this.sendMessage({
1736
+ type: "DELETE_BRANCH",
1737
+ payload: { name }
1738
+ });
1739
+ }
1740
+ async listBranches() {
1741
+ return (await this.sendMessage({
1742
+ type: "LIST_BRANCHES",
1743
+ payload: {}
1744
+ })).branches || [];
1745
+ }
1746
+ /**
1747
+ * Recursively compare two values for structural equality.
1748
+ * Handles primitives, null, undefined, Date, RegExp, arrays, and plain objects.
1749
+ */
1750
+ deepEqual(a, b) {
1751
+ if (a === b) return true;
1752
+ if (a === null || b === null || a === void 0 || b === void 0) return false;
1753
+ if (typeof a !== typeof b) return false;
1754
+ if (typeof a !== "object") return false;
1755
+ if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
1756
+ if (a instanceof Date || b instanceof Date) return false;
1757
+ if (a instanceof RegExp && b instanceof RegExp) return a.source === b.source && a.flags === b.flags;
1758
+ if (a instanceof RegExp || b instanceof RegExp) return false;
1759
+ const aIsArray = Array.isArray(a);
1760
+ const bIsArray = Array.isArray(b);
1761
+ if (aIsArray !== bIsArray) return false;
1762
+ if (aIsArray && bIsArray) {
1763
+ if (a.length !== b.length) return false;
1764
+ for (let i = 0; i < a.length; i++) if (!this.deepEqual(a[i], b[i])) return false;
1765
+ return true;
1766
+ }
1767
+ const aObj = a;
1768
+ const bObj = b;
1769
+ const aKeys = Object.keys(aObj);
1770
+ const bKeys = Object.keys(bObj);
1771
+ if (aKeys.length !== bKeys.length) return false;
1772
+ for (const key of aKeys) {
1773
+ if (!Object.prototype.hasOwnProperty.call(bObj, key)) return false;
1774
+ if (!this.deepEqual(aObj[key], bObj[key])) return false;
1775
+ }
1776
+ return true;
1777
+ }
1778
+ normalizeForComparison(val) {
1779
+ if (!val) return val;
1780
+ if (Array.isArray(val)) return val.map((item) => this.normalizeForComparison(item));
1781
+ if (typeof val === "object") {
1782
+ if (val instanceof Date) return val;
1783
+ if (val instanceof RegExp) return val;
1784
+ const obj = val;
1785
+ if (obj.__type === "relation") {
1786
+ const { data, ...rest } = obj;
1787
+ return rest;
1788
+ }
1789
+ const result = {};
1790
+ for (const [k, v] of Object.entries(obj)) result[k] = this.normalizeForComparison(v);
1791
+ return result;
1792
+ }
1793
+ return val;
1794
+ }
1795
+ /**
1796
+ * Merge incoming entities with cached data, preserving cached references
1797
+ * for entities whose values haven't changed. This avoids unnecessary
1798
+ * React re-renders when the server refetches all entities but most
1799
+ * haven't actually changed.
1800
+ */
1801
+ mergeEntities(cached, incoming) {
1802
+ if (!cached || cached.length === 0) return incoming;
1803
+ const cachedById = /* @__PURE__ */ new Map();
1804
+ for (const entity of cached) cachedById.set(entity.id, entity);
1805
+ return incoming.map((incomingEntity) => {
1806
+ const cachedEntity = cachedById.get(incomingEntity.id);
1807
+ if (!cachedEntity) return incomingEntity;
1808
+ if (cachedEntity.path === incomingEntity.path) {
1809
+ const normCached = this.normalizeForComparison(cachedEntity.values);
1810
+ const normIncoming = this.normalizeForComparison(incomingEntity.values);
1811
+ if (this.deepEqual(normCached, normIncoming)) return cachedEntity;
1812
+ else {
1813
+ const mismatches = {};
1814
+ const allKeys = new Set([...Object.keys(normCached), ...Object.keys(normIncoming)]);
1815
+ for (const key of allKeys) if (!this.deepEqual(normCached[key], normIncoming[key])) mismatches[key] = {
1816
+ cached: normCached[key],
1817
+ incoming: normIncoming[key]
1818
+ };
1819
+ console.debug(`[RebaseWS] Row ${incomingEntity.id} refetch mismatch:\n`, JSON.stringify(mismatches, null, 2));
1820
+ }
1821
+ }
1822
+ return incomingEntity;
1823
+ });
1824
+ }
1825
+ listenCollection(props, onUpdate, onError) {
1826
+ const subscriptionKey = this.createCollectionSubscriptionKey(props);
1827
+ const callbackId = `callback_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
1828
+ const existingSubscription = this.collectionSubscriptions.get(subscriptionKey);
1829
+ if (existingSubscription) {
1830
+ const callbackMap = existingSubscription.callbacks;
1831
+ callbackMap.set(callbackId, {
1832
+ onUpdate,
1833
+ onError
1834
+ });
1835
+ if (existingSubscription.latestData !== void 0 && existingSubscription.isInitialDataReceived) try {
1836
+ onUpdate(existingSubscription.latestData);
1837
+ } catch (error) {
1838
+ console.error("Error in collection subscription callback:", error);
1839
+ if (onError) onError(error instanceof Error ? error : new Error(String(error)));
1840
+ }
1841
+ return () => {
1842
+ callbackMap.delete(callbackId);
1843
+ if (callbackMap.size === 0) {
1844
+ this.collectionSubscriptions.delete(subscriptionKey);
1845
+ this.backendToCollectionKey.delete(existingSubscription.backendSubscriptionId);
1846
+ if (this.isConnected && this.ws) this.sendMessage({
1847
+ type: "unsubscribe",
1848
+ payload: { subscriptionId: existingSubscription.backendSubscriptionId }
1849
+ }).catch(console.error);
1850
+ }
1851
+ };
1852
+ }
1853
+ const backendSubscriptionId = `collection_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
1854
+ const callbackMap = /* @__PURE__ */ new Map();
1855
+ callbackMap.set(callbackId, {
1856
+ onUpdate,
1857
+ onError
1858
+ });
1859
+ this.collectionSubscriptions.set(subscriptionKey, {
1860
+ backendSubscriptionId,
1861
+ callbacks: callbackMap,
1862
+ props
1863
+ });
1864
+ this.backendToCollectionKey.set(backendSubscriptionId, subscriptionKey);
1865
+ this.sendMessage({
1866
+ type: "subscribe_collection",
1867
+ payload: {
1868
+ ...props,
1869
+ subscriptionId: backendSubscriptionId
1870
+ }
1871
+ }).catch((error) => {
1872
+ if (onError) onError(error);
1873
+ });
1874
+ return () => {
1875
+ const subscription = this.collectionSubscriptions.get(subscriptionKey);
1876
+ if (subscription) {
1877
+ const callbacks = subscription.callbacks;
1878
+ callbacks.delete(callbackId);
1879
+ if (callbacks.size === 0) {
1880
+ this.collectionSubscriptions.delete(subscriptionKey);
1881
+ this.backendToCollectionKey.delete(subscription.backendSubscriptionId);
1882
+ if (this.isConnected && this.ws) this.sendMessage({
1883
+ type: "unsubscribe",
1884
+ payload: { subscriptionId: subscription.backendSubscriptionId }
1885
+ }).catch(console.error);
1886
+ }
1887
+ }
1888
+ };
1889
+ }
1890
+ listenEntity(props, onUpdate, onError) {
1891
+ const subscriptionKey = this.createEntitySubscriptionKey(props);
1892
+ const callbackId = `callback_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
1893
+ const existingSubscription = this.entitySubscriptions.get(subscriptionKey);
1894
+ if (existingSubscription) {
1895
+ const callbackMap = existingSubscription.callbacks;
1896
+ callbackMap.set(callbackId, {
1897
+ onUpdate,
1898
+ onError
1899
+ });
1900
+ if (existingSubscription.latestData !== void 0 && existingSubscription.isInitialDataReceived) try {
1901
+ onUpdate(existingSubscription.latestData);
1902
+ } catch (error) {
1903
+ console.error("Error in entity subscription callback:", error);
1904
+ if (onError) onError(error instanceof Error ? error : new Error(String(error)));
1905
+ }
1906
+ return () => {
1907
+ callbackMap.delete(callbackId);
1908
+ if (callbackMap.size === 0) {
1909
+ this.entitySubscriptions.delete(subscriptionKey);
1910
+ this.backendToEntityKey.delete(existingSubscription.backendSubscriptionId);
1911
+ if (this.isConnected && this.ws) this.sendMessage({
1912
+ type: "unsubscribe",
1913
+ payload: { subscriptionId: existingSubscription.backendSubscriptionId }
1914
+ }).catch(console.error);
1915
+ }
1916
+ };
1917
+ }
1918
+ const backendSubscriptionId = `entity_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
1919
+ const callbackMap = /* @__PURE__ */ new Map();
1920
+ callbackMap.set(callbackId, {
1921
+ onUpdate,
1922
+ onError
1923
+ });
1924
+ this.entitySubscriptions.set(subscriptionKey, {
1925
+ backendSubscriptionId,
1926
+ callbacks: callbackMap,
1927
+ props
1928
+ });
1929
+ this.backendToEntityKey.set(backendSubscriptionId, subscriptionKey);
1930
+ this.sendMessage({
1931
+ type: "subscribe_entity",
1932
+ payload: {
1933
+ ...props,
1934
+ subscriptionId: backendSubscriptionId
1935
+ }
1936
+ }).catch((error) => {
1937
+ if (onError) onError(error);
1938
+ });
1939
+ return () => {
1940
+ const subscription = this.entitySubscriptions.get(subscriptionKey);
1941
+ if (subscription) {
1942
+ const callbacks = subscription.callbacks;
1943
+ callbacks.delete(callbackId);
1944
+ if (callbacks.size === 0) {
1945
+ this.entitySubscriptions.delete(subscriptionKey);
1946
+ this.backendToEntityKey.delete(subscription.backendSubscriptionId);
1947
+ if (this.isConnected && this.ws) this.sendMessage({
1948
+ type: "unsubscribe",
1949
+ payload: { subscriptionId: subscription.backendSubscriptionId }
1950
+ }).catch(console.error);
1951
+ }
1952
+ }
1953
+ };
1954
+ }
1955
+ /**
1956
+ * Re-send all active subscriptions to the backend after a reconnect.
1957
+ * The server wipes subscription state when a client disconnects, so
1958
+ * we need to re-register everything to resume receiving updates.
1959
+ */
1960
+ resubscribeAll() {
1961
+ console.debug(`[WS] Re-subscribing: ${this.collectionSubscriptions.size} collection(s), ${this.entitySubscriptions.size} entity(ies)`);
1962
+ for (const [key, sub] of this.collectionSubscriptions.entries()) {
1963
+ const oldBackendId = sub.backendSubscriptionId;
1964
+ const newBackendId = `collection_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
1965
+ sub.backendSubscriptionId = newBackendId;
1966
+ this.backendToCollectionKey.delete(oldBackendId);
1967
+ this.backendToCollectionKey.set(newBackendId, key);
1968
+ this.sendMessage({
1969
+ type: "subscribe_collection",
1970
+ payload: {
1971
+ ...sub.props,
1972
+ subscriptionId: newBackendId
1973
+ }
1974
+ }).catch((error) => {
1975
+ console.error("[WS] Failed to re-subscribe collection:", key, error);
1976
+ });
1977
+ }
1978
+ for (const [key, sub] of this.entitySubscriptions.entries()) {
1979
+ const oldBackendId = sub.backendSubscriptionId;
1980
+ const newBackendId = `entity_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
1981
+ sub.backendSubscriptionId = newBackendId;
1982
+ this.backendToEntityKey.delete(oldBackendId);
1983
+ this.backendToEntityKey.set(newBackendId, key);
1984
+ this.sendMessage({
1985
+ type: "subscribe_entity",
1986
+ payload: {
1987
+ ...sub.props,
1988
+ subscriptionId: newBackendId
1989
+ }
1990
+ }).catch((error) => {
1991
+ console.error("[WS] Failed to re-subscribe entity:", key, error);
1992
+ });
1993
+ }
1994
+ }
1995
+ createCollectionSubscriptionKey(props) {
1996
+ const key = {
1997
+ path: props.path,
1998
+ filter: props.filter,
1999
+ limit: props.limit,
2000
+ startAfter: props.startAfter,
2001
+ orderBy: props.orderBy,
2002
+ order: props.order,
2003
+ searchString: props.searchString,
2004
+ collection: props.collection?.name
2005
+ };
2006
+ return JSON.stringify(key, (_, value) => {
2007
+ if (value && typeof value === "object" && !Array.isArray(value)) return Object.keys(value).sort().reduce((sorted, k) => {
2008
+ sorted[k] = value[k];
2009
+ return sorted;
2010
+ }, {});
2011
+ return value;
2012
+ });
2013
+ }
2014
+ createEntitySubscriptionKey(props) {
2015
+ return `${props.path}|${props.entityId}`;
2016
+ }
2017
+ };
2018
+ //#endregion
2019
+ //#region src/index.ts
2020
+ /**
2021
+ * Derive a WebSocket URL from an HTTP base URL.
2022
+ * `http://` `ws://`, `https://` → `wss://`.
2023
+ */
2024
+ function deriveWebSocketUrl(baseUrl) {
2025
+ if (typeof window !== "undefined") {
2026
+ let absoluteUrl = "";
2027
+ if (!baseUrl) absoluteUrl = window.location.origin;
2028
+ else if (/^https?:\/\//i.test(baseUrl) || /^wss?:\/\//i.test(baseUrl)) absoluteUrl = baseUrl;
2029
+ else try {
2030
+ absoluteUrl = new URL(baseUrl, window.location.href).origin;
2031
+ } catch {
2032
+ absoluteUrl = window.location.origin;
2033
+ }
2034
+ const protocol = absoluteUrl.startsWith("https:") || absoluteUrl.startsWith("wss:") ? "wss:" : "ws:";
2035
+ return absoluteUrl.replace(/^https?:\/\//i, `${protocol}//`).replace(/^wss?:\/\//i, `${protocol}//`).replace(/\/$/, "");
2036
+ }
2037
+ if (!baseUrl) return "";
2038
+ if (!/^https?:\/\//i.test(baseUrl) && !/^wss?:\/\//i.test(baseUrl)) return "";
2039
+ return baseUrl.replace(/^https?:\/\//i, (match) => match.toLowerCase() === "https://" ? "wss://" : "ws://").replace(/\/$/, "");
2040
+ }
2041
+ function createRebaseClient(options) {
2042
+ const transport = createTransport(options);
2043
+ const auth = createAuth(transport, options.auth);
2044
+ const admin = createAdmin(transport, options.admin);
2045
+ const cron = createCron(transport, options.cron);
2046
+ const storage = createStorage(transport);
2047
+ const functions = createFunctionsClient(transport);
2048
+ const resolvedWsUrl = options.websocketUrl ?? deriveWebSocketUrl(options.baseUrl);
2049
+ let ws;
2050
+ if (resolvedWsUrl) {
2051
+ ws = new RebaseWebSocketClient({
2052
+ websocketUrl: resolvedWsUrl,
2053
+ getAuthToken: async () => {
2054
+ let session = auth.getSession();
2055
+ if (session && session.expiresAt <= Date.now() + 1e4) try {
2056
+ session = await auth.refreshSession();
2057
+ } catch (e) {}
2058
+ return session?.accessToken || options.token || "";
2059
+ },
2060
+ onUnauthorized: options.onUnauthorized || (async () => {
2061
+ try {
2062
+ await auth.refreshSession();
2063
+ return true;
2064
+ } catch (e) {
2065
+ return false;
2066
+ }
2067
+ })
2068
+ });
2069
+ auth.onAuthStateChange((event, session) => {
2070
+ if (!ws) return;
2071
+ if (event === "SIGNED_OUT") ws.disconnect();
2072
+ else if (event === "SIGNED_IN" || event === "TOKEN_REFRESHED") {
2073
+ if (session?.accessToken) ws.authenticate(session.accessToken).catch(console.warn);
2074
+ }
2075
+ });
2076
+ }
2077
+ if (!options.onUnauthorized) transport.setOnUnauthorized(async () => {
2078
+ try {
2079
+ await auth.refreshSession();
2080
+ return true;
2081
+ } catch (e) {
2082
+ return false;
2083
+ }
2084
+ });
2085
+ const collectionClients = /* @__PURE__ */ new Map();
2086
+ function collection(slug) {
2087
+ if (!collectionClients.has(slug)) collectionClients.set(slug, createCollectionClient(transport, slug, ws));
2088
+ return collectionClients.get(slug);
2089
+ }
2090
+ const dataProxy = new Proxy({ collection }, { get(_target, prop) {
2091
+ if (prop === "collection") return collection;
2092
+ if (typeof prop === "symbol") return void 0;
2093
+ if (typeof prop === "string" && prop !== "then" && prop !== "toJSON" && prop !== "$$typeof") return collection((0, _rebasepro_utils.toSnakeCase)(prop));
2094
+ } });
2095
+ return {
2096
+ auth,
2097
+ admin,
2098
+ cron,
2099
+ functions,
2100
+ storage,
2101
+ ws,
2102
+ setToken: transport.setToken,
2103
+ setAuthTokenGetter: transport.setAuthTokenGetter,
2104
+ setOnUnauthorized: transport.setOnUnauthorized,
2105
+ resolveToken: transport.resolveToken,
2106
+ baseUrl: transport.baseUrl,
2107
+ collection,
2108
+ call: async (endpoint, payload) => {
2109
+ const prefix = endpoint.startsWith("/") ? "" : "/";
2110
+ const res = await transport.request(`${prefix}${endpoint}`, {
2111
+ method: "POST",
2112
+ body: payload ? JSON.stringify(payload) : void 0
2113
+ });
2114
+ return res.data ?? res;
2115
+ },
2116
+ data: dataProxy,
2117
+ email: void 0
2118
+ };
2119
+ }
2120
+ //#endregion
2121
+ exports.ApiError = ApiError;
2122
+ Object.defineProperty(exports, "QueryBuilder", {
2123
+ enumerable: true,
2124
+ get: function() {
2125
+ return _rebasepro_common.QueryBuilder;
2126
+ }
2127
+ });
2128
+ exports.RebaseApiError = RebaseApiError;
2129
+ exports.RebaseWebSocketClient = RebaseWebSocketClient;
2130
+ Object.defineProperty(exports, "and", {
2131
+ enumerable: true,
2132
+ get: function() {
2133
+ return _rebasepro_common.and;
2134
+ }
2135
+ });
2136
+ exports.buildQueryString = buildQueryString;
2137
+ Object.defineProperty(exports, "cond", {
2138
+ enumerable: true,
2139
+ get: function() {
2140
+ return _rebasepro_common.cond;
2141
+ }
2142
+ });
2143
+ exports.createAdmin = createAdmin;
2144
+ exports.createAuth = createAuth;
2145
+ exports.createCollectionClient = createCollectionClient;
2146
+ exports.createCookieStorage = createCookieStorage;
2147
+ exports.createCron = createCron;
2148
+ exports.createFunctionsClient = createFunctionsClient;
2149
+ exports.createMemoryStorage = createMemoryStorage;
2150
+ exports.createRebaseClient = createRebaseClient;
2151
+ exports.createStorage = createStorage;
2152
+ exports.createTransport = createTransport;
2153
+ Object.defineProperty(exports, "or", {
2154
+ enumerable: true,
2155
+ get: function() {
2156
+ return _rebasepro_common.or;
2157
+ }
2158
+ });
2159
+ exports.rebaseReviver = rebaseReviver;
2427
2160
  });
2428
- //# sourceMappingURL=index.umd.js.map
2161
+
2162
+ //# sourceMappingURL=index.umd.js.map