@rebasepro/client 0.0.1-canary.4d4fb3e → 0.0.1-canary.ca2cb6e

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -1,40 +1,46 @@
1
1
  import { createTransport, RebaseClientConfig } from "./transport";
2
2
  import { createAuth, CreateAuthOptions } from "./auth";
3
3
  import { createAdmin, CreateAdminOptions } from "./admin";
4
+ import { createCron, CreateCronOptions } from "./cron";
4
5
  import { createCollectionClient, CollectionClient } from "./collection";
5
6
 
6
7
  export * from "./transport";
7
8
  export * from "./auth";
8
9
  export * from "./admin";
10
+ export * from "./cron";
9
11
  export * from "./collection";
10
12
  export * from "./websocket";
11
13
  export * from "./storage";
14
+ export * from "./reviver";
12
15
 
13
16
  export interface CreateRebaseClientOptions extends RebaseClientConfig {
14
17
  auth?: CreateAuthOptions;
15
18
  admin?: CreateAdminOptions;
19
+ cron?: CreateCronOptions;
16
20
  }
17
21
 
18
22
  import { RebaseWebSocketClient } from "./websocket";
19
23
  import { RebaseClient as BaseRebaseClient, RebaseData, CollectionAccessor, StorageSource } from "@rebasepro/types";
24
+ import { toSnakeCase } from "@rebasepro/utils";
20
25
 
21
- export type RebaseClient<DB = any> = BaseRebaseClient<DB> & {
26
+ export type RebaseClient<DB = Record<string, unknown>> = BaseRebaseClient<DB> & {
22
27
  setToken: (token: string | null) => void;
23
28
  setAuthTokenGetter: (getter: () => Promise<string | null>) => void;
24
29
  setOnUnauthorized: (handler: () => Promise<boolean>) => void;
25
30
  resolveToken: () => Promise<string | null>;
26
31
  auth: ReturnType<typeof createAuth>;
27
32
  admin: ReturnType<typeof createAdmin>;
33
+ cron: ReturnType<typeof createCron>;
28
34
  ws?: RebaseWebSocketClient;
29
35
  storage?: StorageSource;
30
- call: <T = any>(endpoint: string, payload?: any) => Promise<T>;
36
+ call: <T = unknown>(endpoint: string, payload?: unknown) => Promise<T>;
31
37
  data: RebaseData & {
32
38
  collection<K extends keyof DB>(slug: Extract<K, string>): CollectionClient<
33
- DB[K] extends { Row: infer R extends Record<string, any> } ? R : any
39
+ DB[K] extends { Row: infer R extends Record<string, unknown> } ? R : Record<string, unknown>
34
40
  >;
35
41
  } & {
36
42
  [K in keyof DB]: CollectionClient<
37
- DB[K] extends { Row: infer R extends Record<string, any> } ? R : any
43
+ DB[K] extends { Row: infer R extends Record<string, unknown> } ? R : Record<string, unknown>
38
44
  >;
39
45
  };
40
46
  };
@@ -45,17 +51,26 @@ import { createStorage } from "./storage";
45
51
  * Derive a WebSocket URL from an HTTP base URL.
46
52
  * `http://` → `ws://`, `https://` → `wss://`.
47
53
  */
48
- function deriveWebSocketUrl(baseUrl: string): string {
54
+ function deriveWebSocketUrl(baseUrl?: string): string {
55
+ if (!baseUrl) {
56
+ // If no baseUrl is provided, we can try to derive it from the window object if in browser
57
+ if (typeof window !== "undefined") {
58
+ const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
59
+ return `${protocol}//${window.location.host}`;
60
+ }
61
+ return "";
62
+ }
49
63
  return baseUrl
50
64
  .replace(/^https:\/\//, "wss://")
51
65
  .replace(/^http:\/\//, "ws://")
52
66
  .replace(/\/$/, "");
53
67
  }
54
68
 
55
- export function createRebaseClient<DB = any>(options: CreateRebaseClientOptions): RebaseClient<DB> {
69
+ export function createRebaseClient<DB = Record<string, unknown>>(options: CreateRebaseClientOptions): RebaseClient<DB> {
56
70
  const transport = createTransport(options);
57
71
  const auth = createAuth(transport, options.auth);
58
72
  const admin = createAdmin(transport, options.admin);
73
+ const cron = createCron(transport, options.cron);
59
74
  const storage = createStorage(transport);
60
75
 
61
76
  const resolvedWsUrl = options.websocketUrl ?? deriveWebSocketUrl(options.baseUrl);
@@ -82,28 +97,31 @@ export function createRebaseClient<DB = any>(options: CreateRebaseClientOptions)
82
97
  });
83
98
  }
84
99
 
85
- // Register transport callback for 401s after auth is instantiated
100
+ // Register transport callback for 401s after auth is instantiated.
101
+ // IMPORTANT: We must use transport.setOnUnauthorized() here — NOT set
102
+ // options.onUnauthorized — because the transport was already created above
103
+ // and captured the (undefined) value from the config closure.
86
104
  if (!options.onUnauthorized) {
87
- options.onUnauthorized = async () => {
105
+ transport.setOnUnauthorized(async () => {
88
106
  try {
89
107
  await auth.refreshSession();
90
108
  return true;
91
109
  } catch (e) {
92
110
  return false;
93
111
  }
94
- };
112
+ });
95
113
  }
96
114
 
97
- const collectionClients = new Map<string, CollectionClient<any>>();
115
+ const collectionClients = new Map<string, CollectionClient<Record<string, unknown>>>();
98
116
 
99
- function collection(slug: string): CollectionClient<any> {
117
+ function collection(slug: string): CollectionClient<Record<string, unknown>> {
100
118
  if (!collectionClients.has(slug)) {
101
119
  collectionClients.set(slug, createCollectionClient(transport, slug, ws));
102
120
  }
103
121
  return collectionClients.get(slug)!;
104
122
  }
105
123
 
106
- const dataTarget = { collection } as Record<string, any>;
124
+ const dataTarget = { collection } as Record<string, unknown>;
107
125
 
108
126
  const dataProxy = new Proxy(dataTarget, {
109
127
  get(_target, prop: string | symbol) {
@@ -112,7 +130,10 @@ export function createRebaseClient<DB = any>(options: CreateRebaseClientOptions)
112
130
  }
113
131
  if (typeof prop === "symbol") return undefined;
114
132
  if (typeof prop === "string" && prop !== "then" && prop !== "toJSON" && prop !== "$$typeof") {
115
- return collection(prop);
133
+ // Convert camelCase property names to snake_case slugs.
134
+ // e.g. `companyMembers` → `company_members`
135
+ const slug = toSnakeCase(prop);
136
+ return collection(slug);
116
137
  }
117
138
  return undefined;
118
139
  }
@@ -121,6 +142,7 @@ export function createRebaseClient<DB = any>(options: CreateRebaseClientOptions)
121
142
  const target = {
122
143
  auth,
123
144
  admin,
145
+ cron,
124
146
  storage,
125
147
  ws,
126
148
  setToken: transport.setToken,
@@ -129,7 +151,7 @@ export function createRebaseClient<DB = any>(options: CreateRebaseClientOptions)
129
151
  resolveToken: transport.resolveToken,
130
152
  baseUrl: transport.baseUrl,
131
153
  collection,
132
- call: async <T = any>(endpoint: string, payload?: any): Promise<T> => {
154
+ call: async <T = unknown>(endpoint: string, payload?: unknown): Promise<T> => {
133
155
  const prefix = endpoint.startsWith("/") ? "" : "/";
134
156
  const res = await transport.request<{ data: T }>(`${prefix}${endpoint}`, {
135
157
  method: "POST",
@@ -137,18 +159,9 @@ export function createRebaseClient<DB = any>(options: CreateRebaseClientOptions)
137
159
  });
138
160
  return res.data ?? (res as unknown as T);
139
161
  },
140
- data: dataProxy
162
+ data: dataProxy,
163
+ email: undefined
141
164
  } as unknown as RebaseClient<DB>;
142
165
 
143
- return new Proxy(target, {
144
- get(obj, prop: string | symbol) {
145
- if (prop in obj) {
146
- return (obj as Record<string, unknown>)[prop as string];
147
- }
148
- if (typeof prop === "string" && prop !== "then") {
149
- return collection(prop as Extract<keyof DB, string>);
150
- }
151
- return undefined;
152
- }
153
- }) as RebaseClient<DB>;
166
+ return target;
154
167
  }
@@ -1,5 +1,4 @@
1
- import { FindParams, Entity } from "@rebasepro/types";
2
- import { FindResponse } from "./transport";
1
+ import { FindParams, Entity, FindResponse } from "@rebasepro/types";
3
2
  import { CollectionClient } from "./collection";
4
3
 
5
4
  export type FilterOperator =
@@ -27,24 +26,24 @@ function mapOperator(op: FilterOperator): string {
27
26
  }
28
27
  }
29
28
 
30
- export class QueryBuilder<M extends Record<string, any> = any> {
29
+ export class QueryBuilder<M extends Record<string, unknown> = Record<string, unknown>> {
31
30
  private params: FindParams = { where: {} };
32
31
 
33
32
  constructor(private collection: CollectionClient<M>) {}
34
33
 
35
34
  /**
36
35
  * Add a filter condition to your query.
37
- * @example
36
+ * @example
38
37
  * client.collection('users').where('age', '>=', 18).find()
39
38
  */
40
- where(column: keyof M & string, operator: FilterOperator, value: any): this {
39
+ where(column: keyof M & string, operator: FilterOperator, value: unknown): this {
41
40
  if (!this.params.where) {
42
41
  this.params.where = {};
43
42
  }
44
43
 
45
44
  const mappedOp = mapOperator(operator);
46
45
  let formattedValue = value;
47
-
46
+
48
47
  // Handle arrays for in, nin, cs, csa
49
48
  if (Array.isArray(value) && ["in", "nin", "cs", "csa"].includes(mappedOp)) {
50
49
  formattedValue = `(${value.join(",")})`;
@@ -58,7 +57,7 @@ export class QueryBuilder<M extends Record<string, any> = any> {
58
57
 
59
58
  /**
60
59
  * Order the results by a specific column.
61
- * @example
60
+ * @example
62
61
  * client.collection('users').orderBy('createdAt', 'desc').find()
63
62
  */
64
63
  orderBy(column: keyof M & string, ascending: "asc" | "desc" = "asc"): this {
@@ -121,6 +120,6 @@ export class QueryBuilder<M extends Record<string, any> = any> {
121
120
  if (!this.collection.listen) {
122
121
  throw new Error("Listen is only available when RebaseClient is configured with a websocketUrl.");
123
122
  }
124
- return this.collection.listen(this.params, onUpdate as unknown as (data: { data: Entity<M>[]; meta: any }) => void, onError);
123
+ return this.collection.listen(this.params, onUpdate, onError);
125
124
  }
126
125
  }
package/src/reviver.ts ADDED
@@ -0,0 +1,39 @@
1
+ import { EntityReference, EntityRelation, GeoPoint, Vector, Entity } from "@rebasepro/types";
2
+
3
+ export function rebaseReviver(_key: string, value: unknown): unknown {
4
+ if (value && typeof value === "object" && "__type" in value) {
5
+ const record = value as Record<string, unknown>;
6
+ switch (record.__type) {
7
+ case "date":
8
+ case "Date": {
9
+ if (typeof record.value !== "string") {
10
+ return value;
11
+ }
12
+ const date = new Date(record.value);
13
+ return isNaN(date.getTime()) ? null : date;
14
+ }
15
+ case "reference":
16
+ case "EntityReference":
17
+ return new EntityReference({
18
+ id: String(record.id),
19
+ path: record.path as string,
20
+ driver: record.driver as string | undefined,
21
+ databaseId: record.databaseId as string | undefined
22
+ });
23
+ case "relation":
24
+ case "EntityRelation":
25
+ return new EntityRelation(
26
+ record.id as string | number,
27
+ record.path as string,
28
+ record.data as Entity | undefined
29
+ );
30
+ case "GeoPoint":
31
+ return new GeoPoint(record.latitude as number, record.longitude as number);
32
+ case "Vector":
33
+ return new Vector(record.value as number[]);
34
+ default:
35
+ return value;
36
+ }
37
+ }
38
+ return value;
39
+ }
package/src/storage.ts CHANGED
@@ -1,26 +1,24 @@
1
- import { StorageSource, UploadFileProps, UploadFileResult, DownloadConfig, StorageListResult } from "@rebasepro/types";
1
+ import { StorageSource, UploadFileProps, UploadFileResult, DownloadConfig, StorageListResult, DownloadMetadata } from "@rebasepro/types";
2
2
  import { Transport } from "./transport";
3
3
 
4
4
  export function createStorage(transport: Transport): StorageSource {
5
5
  const urlsCache = new Map<string, DownloadConfig>();
6
-
6
+
7
7
  // We expect the transport to point to /api, and storage endpoints handle /api/storage internally if they are relative?
8
8
  // Wait, useBackendStorageSource uses `${apiUrl}/api/storage` directly.
9
9
  // Transport has `.request` which hits `${config.baseUrl}${config.apiPath}${path}`.
10
10
  // Assuming `config.apiPath` is "/api", we just request(`/storage/upload`, ...).
11
11
 
12
- async function uploadFile({
12
+ async function putObject({
13
13
  file,
14
- fileName,
15
- path,
14
+ key,
16
15
  metadata,
17
16
  bucket
18
17
  }: UploadFileProps): Promise<UploadFileResult> {
19
18
  const formData = new FormData();
20
19
  formData.append("file", file);
21
20
 
22
- if (fileName) formData.append("fileName", fileName);
23
- if (path) formData.append("path", path);
21
+ if (key) formData.append("key", key);
24
22
  if (bucket) formData.append("bucket", bucket);
25
23
 
26
24
  if (metadata) {
@@ -40,7 +38,7 @@ export function createStorage(transport: Transport): StorageSource {
40
38
  method: "POST",
41
39
  body: formData,
42
40
  headers: {
43
- // transport.request merges headers, so to prevent it setting application/json we can delete it
41
+ // transport.request merges headers, so to prevent it setting application/json we can delete it
44
42
  // in transport if body is FormData, or we can explicitly set it to an empty string.
45
43
  // Let's rely on standard behaviour for now and adjust transport if it fails.
46
44
  }
@@ -49,15 +47,15 @@ export function createStorage(transport: Transport): StorageSource {
49
47
  return result.data;
50
48
  }
51
49
 
52
- async function getDownloadURL(
53
- pathOrUrl: string,
50
+ async function getSignedUrl(
51
+ keyOrUrl: string,
54
52
  bucket?: string
55
53
  ): Promise<DownloadConfig> {
56
- const cacheKey = bucket ? `${bucket}/${pathOrUrl}` : pathOrUrl;
54
+ const cacheKey = bucket ? `${bucket}/${keyOrUrl}` : keyOrUrl;
57
55
  const cached = urlsCache.get(cacheKey);
58
56
  if (cached) return cached;
59
57
 
60
- let filePath = pathOrUrl;
58
+ let filePath = keyOrUrl;
61
59
 
62
60
  if (filePath && (filePath.startsWith("local://") || filePath.startsWith("s3://"))) {
63
61
  filePath = filePath.substring(filePath.indexOf("://") + 3);
@@ -67,15 +65,16 @@ export function createStorage(transport: Transport): StorageSource {
67
65
  filePath = `${bucket}/${filePath}`;
68
66
  }
69
67
 
70
- if (!filePath || filePath.trim() === '' || filePath === '/') {
71
- return { url: null, fileNotFound: true };
68
+ if (!filePath || filePath.trim() === "" || filePath === "/") {
69
+ return { url: null,
70
+ fileNotFound: true };
72
71
  }
73
72
 
74
73
  try {
75
- const result = await transport.request<{ data: any }>(`/storage/metadata/${filePath}`);
76
-
74
+ const result = await transport.request<{ data: DownloadMetadata }>(`/storage/metadata/${filePath}`);
75
+
77
76
  const activeToken = await transport.resolveToken();
78
- const tokenQuery = activeToken ? `?token=${activeToken}` : '';
77
+ const tokenQuery = activeToken ? `?token=${activeToken}` : "";
79
78
 
80
79
  const downloadConfig: DownloadConfig = {
81
80
  url: `${transport.baseUrl}${transport.apiPath}/storage/file/${filePath}${tokenQuery}`,
@@ -85,18 +84,19 @@ export function createStorage(transport: Transport): StorageSource {
85
84
  urlsCache.set(cacheKey, downloadConfig);
86
85
  return downloadConfig;
87
86
  } catch (e: unknown) {
88
- if (e instanceof Error && 'status' in e && (e as { status: number }).status === 404) {
89
- return { url: null, fileNotFound: true };
87
+ if (e instanceof Error && "status" in e && (e as { status: number }).status === 404) {
88
+ return { url: null,
89
+ fileNotFound: true };
90
90
  }
91
91
  throw e;
92
92
  }
93
93
  }
94
94
 
95
- async function getFile(
96
- path: string,
95
+ async function getObject(
96
+ key: string,
97
97
  bucket?: string
98
98
  ): Promise<File | null> {
99
- let filePath = path;
99
+ let filePath = key;
100
100
 
101
101
  if (filePath && (filePath.startsWith("local://") || filePath.startsWith("s3://"))) {
102
102
  filePath = filePath.substring(filePath.indexOf("://") + 3);
@@ -106,13 +106,13 @@ export function createStorage(transport: Transport): StorageSource {
106
106
  filePath = `${bucket}/${filePath}`;
107
107
  }
108
108
 
109
- if (!filePath || filePath.trim() === '' || filePath === '/') {
109
+ if (!filePath || filePath.trim() === "" || filePath === "/") {
110
110
  return null;
111
111
  }
112
112
 
113
113
  // We must use plain fetch because transport.request expects JSON response, but here we want a Blob.
114
114
  const url = `${transport.baseUrl}${transport.apiPath}/storage/file/${filePath}`;
115
-
115
+
116
116
  // This is a bit manual, but necessary for blob handling
117
117
  const response = await transport.fetchFn(url, {
118
118
  headers: transport.getHeaders ? transport.getHeaders() : {}
@@ -126,11 +126,11 @@ export function createStorage(transport: Transport): StorageSource {
126
126
  return new File([blob], fileName, { type: blob.type });
127
127
  }
128
128
 
129
- async function deleteFile(
130
- path: string,
129
+ async function deleteObject(
130
+ key: string,
131
131
  bucket?: string
132
132
  ): Promise<void> {
133
- let filePath = path;
133
+ let filePath = key;
134
134
 
135
135
  if (filePath && (filePath.startsWith("local://") || filePath.startsWith("s3://"))) {
136
136
  filePath = filePath.substring(filePath.indexOf("://") + 3);
@@ -140,21 +140,21 @@ export function createStorage(transport: Transport): StorageSource {
140
140
  filePath = `${bucket}/${filePath}`;
141
141
  }
142
142
 
143
- if (!filePath || filePath.trim() === '' || filePath === '/') {
143
+ if (!filePath || filePath.trim() === "" || filePath === "/") {
144
144
  return;
145
145
  }
146
146
 
147
147
  try {
148
148
  await transport.request(`/storage/file/${filePath}`, { method: "DELETE" });
149
149
  } catch (e: unknown) {
150
- if (!(e instanceof Error && 'status' in e && (e as { status: number }).status === 404)) throw e;
150
+ if (!(e instanceof Error && "status" in e && (e as { status: number }).status === 404)) throw e;
151
151
  }
152
152
 
153
- urlsCache.delete(bucket ? `${bucket}/${path}` : path);
153
+ urlsCache.delete(bucket ? `${bucket}/${key}` : key);
154
154
  }
155
155
 
156
- async function list(
157
- path: string,
156
+ async function listObjects(
157
+ prefix: string,
158
158
  options?: {
159
159
  bucket?: string;
160
160
  maxResults?: number;
@@ -162,7 +162,7 @@ export function createStorage(transport: Transport): StorageSource {
162
162
  }
163
163
  ): Promise<StorageListResult> {
164
164
  const params = new URLSearchParams();
165
- if (path) params.set("path", path);
165
+ if (prefix) params.set("prefix", prefix);
166
166
  if (options?.bucket) params.set("bucket", options.bucket);
167
167
  if (options?.maxResults) params.set("maxResults", String(options.maxResults));
168
168
  if (options?.pageToken) params.set("pageToken", options.pageToken);
@@ -172,10 +172,10 @@ export function createStorage(transport: Transport): StorageSource {
172
172
  }
173
173
 
174
174
  return {
175
- uploadFile,
176
- getDownloadURL,
177
- getFile,
178
- deleteFile,
179
- list
175
+ putObject,
176
+ getSignedUrl,
177
+ getObject,
178
+ deleteObject,
179
+ listObjects
180
180
  };
181
181
  }