@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/collection.ts CHANGED
@@ -1,20 +1,68 @@
1
- import { Transport, FindParams, FindResponse, buildQueryString } from "./transport";
1
+ import { Transport, FindParams, buildQueryString } from "./transport";
2
2
  import { RebaseWebSocketClient } from "./websocket";
3
- import { Entity, FilterValues, WhereFilterOp, CollectionAccessor } from "@rebasepro/types";
3
+ import { Entity, FilterValues, WhereFilterOp, CollectionAccessor, WhereFieldValue, FindResponse } from "@rebasepro/types";
4
4
 
5
5
  import { FilterOperator, QueryBuilder } from "./query_builder";
6
6
 
7
- function parseWhereFilter(where?: Record<string, string>): FilterValues<any> | undefined {
7
+ function parseWhereFilter(where?: Record<string, WhereFieldValue>): FilterValues<string> | undefined {
8
8
  if (!where) return undefined;
9
9
  const filters: Record<string, [WhereFilterOp, unknown]> = {};
10
- for (const [key, value] of Object.entries(where)) {
10
+ for (const [key, rawValue] of Object.entries(where)) {
11
+ // Handle null → equality
12
+ if (rawValue === null) {
13
+ filters[key] = ["==", null];
14
+ continue;
15
+ }
16
+
17
+ // Handle boolean → equality
18
+ if (typeof rawValue === "boolean") {
19
+ filters[key] = ["==", rawValue];
20
+ continue;
21
+ }
22
+
23
+ // Handle number → equality
24
+ if (typeof rawValue === "number") {
25
+ filters[key] = ["==", rawValue];
26
+ continue;
27
+ }
28
+
29
+ // Handle tuple: [operator, value]
30
+ if (Array.isArray(rawValue) && rawValue.length === 2) {
31
+ const [rawOp, val] = rawValue;
32
+ const OP_TO_FILTER: Record<string, WhereFilterOp> = {
33
+ "eq": "==",
34
+ "neq": "!=",
35
+ "gt": ">",
36
+ "gte": ">=",
37
+ "lt": "<",
38
+ "lte": "<=",
39
+ "==": "==",
40
+ "!=": "!=",
41
+ ">": ">",
42
+ ">=": ">=",
43
+ "<": "<",
44
+ "<=": "<=",
45
+ "in": "in",
46
+ "nin": "not-in",
47
+ "not-in": "not-in",
48
+ "cs": "array-contains",
49
+ "csa": "array-contains-any",
50
+ "array-contains": "array-contains",
51
+ "array-contains-any": "array-contains-any"
52
+ };
53
+ filters[key] = [OP_TO_FILTER[rawOp] ?? "==", val];
54
+ continue;
55
+ }
56
+
57
+ // Handle string (original PostgREST format)
58
+ const value = String(rawValue);
11
59
  const dotIndex = value.indexOf(".");
12
60
  if (dotIndex > 0) {
13
61
  const opStr = value.substring(0, dotIndex);
14
62
  const valStr = value.substring(dotIndex + 1);
15
63
  let op: WhereFilterOp = "==";
16
- let val: any = valStr;
17
-
64
+ let val: string | number | boolean | null | string[] = valStr;
65
+
18
66
  switch (opStr) {
19
67
  case "eq": op = "=="; break;
20
68
  case "neq": op = "!="; break;
@@ -22,22 +70,22 @@ function parseWhereFilter(where?: Record<string, string>): FilterValues<any> | u
22
70
  case "gte": op = ">="; break;
23
71
  case "lt": op = "<"; break;
24
72
  case "lte": op = "<="; break;
25
- case "in":
73
+ case "in":
26
74
  op = "in";
27
- val = valStr.startsWith("(") && valStr.endsWith(")")
75
+ val = valStr.startsWith("(") && valStr.endsWith(")")
28
76
  ? valStr.slice(1, -1).split(",").map(v => v.trim())
29
77
  : valStr.split(",");
30
78
  break;
31
- case "nin":
79
+ case "nin":
32
80
  op = "not-in";
33
- val = valStr.startsWith("(") && valStr.endsWith(")")
81
+ val = valStr.startsWith("(") && valStr.endsWith(")")
34
82
  ? valStr.slice(1, -1).split(",").map(v => v.trim())
35
83
  : valStr.split(",");
36
84
  break;
37
85
  case "cs": op = "array-contains"; break;
38
- case "csa":
86
+ case "csa":
39
87
  op = "array-contains-any";
40
- val = valStr.startsWith("(") && valStr.endsWith(")")
88
+ val = valStr.startsWith("(") && valStr.endsWith(")")
41
89
  ? valStr.slice(1, -1).split(",").map(v => v.trim())
42
90
  : valStr.split(",");
43
91
  break;
@@ -47,8 +95,8 @@ function parseWhereFilter(where?: Record<string, string>): FilterValues<any> | u
47
95
  if (val === "true") val = true;
48
96
  else if (val === "false") val = false;
49
97
  else if (val === "null") val = null;
50
- else if (typeof val === "string" && /^[0-9]+(\.[0-9]+)?$/.test(val)) val = Number(val);
51
-
98
+ else if (typeof val === "string" && /^[0-9]+(\.[0-9]+)?$/.test(val) && key !== "id" && !key.endsWith("_id")) val = Number(val);
99
+
52
100
  filters[key] = [op, val];
53
101
  } else {
54
102
  filters[key] = ["==", value];
@@ -63,9 +111,9 @@ function parseWhereFilter(where?: Record<string, string>): FilterValues<any> | u
63
111
  * The `id` is kept inside `values` as well, since collection properties
64
112
  * may define an `isId` field that the form binds to `formex.values`.
65
113
  */
66
- function rowToEntity<M extends Record<string, any>>(row: Record<string, any>, slug: string): Entity<M> {
114
+ function rowToEntity<M extends Record<string, unknown>>(row: Record<string, unknown>, slug: string): Entity<M> {
67
115
  return {
68
- id: row.id,
116
+ id: row.id as string | number,
69
117
  path: slug,
70
118
  values: row as M
71
119
  };
@@ -77,9 +125,9 @@ function rowToEntity<M extends Record<string, any>>(row: Record<string, any>, sl
77
125
  *
78
126
  * Additionally it exposes fluent query builder methods like `.where()`, `.orderBy()`.
79
127
  */
80
- export interface CollectionClient<M extends Record<string, any> = any> extends CollectionAccessor<M> {
128
+ export interface CollectionClient<M extends Record<string, unknown> = Record<string, unknown>> extends CollectionAccessor<M> {
81
129
  // Fluent Query Builder
82
- where(column: keyof M & string, operator: FilterOperator, value: any): QueryBuilder<M>;
130
+ where(column: keyof M & string, operator: FilterOperator, value: unknown): QueryBuilder<M>;
83
131
  orderBy(column: keyof M & string, ascending?: "asc" | "desc"): QueryBuilder<M>;
84
132
  limit(count: number): QueryBuilder<M>;
85
133
  offset(count: number): QueryBuilder<M>;
@@ -87,21 +135,21 @@ export interface CollectionClient<M extends Record<string, any> = any> extends C
87
135
  include(...relations: string[]): QueryBuilder<M>;
88
136
  }
89
137
 
90
- export function createCollectionClient<M extends Record<string, any> = any>(transport: Transport, slug: string, ws?: RebaseWebSocketClient): CollectionClient<M> {
138
+ export function createCollectionClient<M extends Record<string, unknown> = Record<string, unknown>>(transport: Transport, slug: string, ws?: RebaseWebSocketClient): CollectionClient<M> {
91
139
  const basePath = `/data/${slug}`;
92
140
 
93
- return {
94
- async find(params?: FindParams) {
141
+ const client: CollectionClient<M> = {
142
+ async find(params?: FindParams): Promise<FindResponse<M>> {
95
143
  const qs = buildQueryString(params);
96
- const raw = await transport.request<{ data: Record<string, any>[]; meta: any }>(basePath + qs, { method: "GET" });
144
+ const raw = await transport.request<{ data: Record<string, unknown>[]; meta: FindResponse<M>["meta"] }>(basePath + qs, { method: "GET" });
97
145
  return {
98
- data: (raw.data || []).map((row: Record<string, any>) => rowToEntity<M>(row, slug)),
146
+ data: (raw.data || []).map((row: Record<string, unknown>) => rowToEntity<M>(row, slug)),
99
147
  meta: raw.meta
100
148
  };
101
149
  },
102
150
 
103
151
  async findById(id: string | number) {
104
- const raw = await transport.request<Record<string, any>>(`${basePath}/${encodeURIComponent(String(id))}`, { method: "GET" });
152
+ const raw = await transport.request<Record<string, unknown>>(`${basePath}/${encodeURIComponent(String(id))}`, { method: "GET" });
105
153
  if (!raw) return undefined;
106
154
  return rowToEntity<M>(raw, slug);
107
155
  },
@@ -111,88 +159,91 @@ export function createCollectionClient<M extends Record<string, any> = any>(tran
111
159
  if (id !== undefined) {
112
160
  body.id = id;
113
161
  }
114
- const raw = await transport.request<Record<string, any>>(basePath, {
162
+ const raw = await transport.request<Record<string, unknown>>(basePath, {
115
163
  method: "POST",
116
- body: JSON.stringify(body),
164
+ body: JSON.stringify(body)
117
165
  });
118
166
  return rowToEntity<M>(raw, slug);
119
167
  },
120
168
 
121
169
  async update(id: string | number, data: Partial<M>) {
122
- const raw = await transport.request<Record<string, any>>(`${basePath}/${encodeURIComponent(String(id))}`, {
170
+ const raw = await transport.request<Record<string, unknown>>(`${basePath}/${encodeURIComponent(String(id))}`, {
123
171
  method: "PUT",
124
- body: JSON.stringify(data),
172
+ body: JSON.stringify(data)
125
173
  });
126
174
  return rowToEntity<M>(raw, slug);
127
175
  },
128
176
 
129
177
  async delete(id: string | number) {
130
178
  return transport.request<void>(`${basePath}/${encodeURIComponent(String(id))}`, {
131
- method: "DELETE",
179
+ method: "DELETE"
132
180
  });
133
181
  },
134
182
 
135
- ...(ws && {
136
- listen(params: FindParams | undefined, onUpdate: (data: { data: Entity<M>[]; meta: any }) => void, onError?: (error: Error) => void) {
137
- return ws.listenCollection(
138
- {
139
- path: slug,
140
- filter: parseWhereFilter(params?.where),
141
- limit: params?.limit,
142
- startAfter: params?.offset ? String(params.offset) : undefined,
143
- orderBy: params?.orderBy?.split(":")[0],
144
- order: params?.orderBy?.split(":")[1] as "asc" | "desc",
145
- searchString: params?.searchString
146
- },
147
- (entities: Entity[]) => {
148
- const requestedLimit = params?.limit || 20;
149
- onUpdate({
150
- data: entities as Entity<M>[],
151
- meta: {
152
- total: entities.length,
153
- limit: requestedLimit,
154
- offset: params?.offset || 0,
155
- hasMore: entities.length >= requestedLimit
156
- }
157
- });
158
- },
159
- onError
160
- );
161
- },
162
-
163
- listenById(id: string | number, onUpdate: (data: Entity<M> | undefined) => void, onError?: (error: Error) => void) {
164
- return ws.listenEntity(
165
- { path: slug, entityId: String(id) },
166
- (entity: Entity | null) => {
167
- if (entity) {
168
- onUpdate(entity as Entity<M>);
169
- } else {
170
- onUpdate(undefined);
171
- }
172
- },
173
- onError
174
- );
175
- }
176
- }),
177
-
178
183
  // Fluent builder instantiation
179
- where(column: keyof M & string, operator: FilterOperator, value: any) {
180
- return new QueryBuilder<M>(this as unknown as CollectionClient<M>).where(column, operator, value);
184
+ where(column: keyof M & string, operator: FilterOperator, value: unknown) {
185
+ return new QueryBuilder<M>(client).where(column, operator, value);
181
186
  },
182
187
  orderBy(column: keyof M & string, ascending?: "asc" | "desc") {
183
- return new QueryBuilder<M>(this as unknown as CollectionClient<M>).orderBy(column, ascending);
188
+ return new QueryBuilder<M>(client).orderBy(column, ascending);
184
189
  },
185
190
  limit(count: number) {
186
- return new QueryBuilder<M>(this as unknown as CollectionClient<M>).limit(count);
191
+ return new QueryBuilder<M>(client).limit(count);
187
192
  },
188
193
  offset(count: number) {
189
- return new QueryBuilder<M>(this as unknown as CollectionClient<M>).offset(count);
194
+ return new QueryBuilder<M>(client).offset(count);
190
195
  },
191
196
  search(searchString: string) {
192
- return new QueryBuilder<M>(this as unknown as CollectionClient<M>).search(searchString);
197
+ return new QueryBuilder<M>(client).search(searchString);
193
198
  },
194
199
  include(...relations: string[]) {
195
- return new QueryBuilder<M>(this as unknown as CollectionClient<M>).include(...relations);
200
+ return new QueryBuilder<M>(client).include(...relations);
196
201
  }
197
202
  };
203
+
204
+ if (ws) {
205
+ client.listen = (params: FindParams | undefined, onUpdate: (response: FindResponse<M>) => void, onError?: (error: Error) => void) => {
206
+ return ws.listenCollection(
207
+ {
208
+ path: slug,
209
+ filter: parseWhereFilter(params?.where),
210
+ limit: params?.limit,
211
+ startAfter: params?.offset ? String(params.offset) : undefined,
212
+ orderBy: params?.orderBy?.split(":")[0],
213
+ order: params?.orderBy?.split(":")[1] as "asc" | "desc",
214
+ searchString: params?.searchString
215
+ },
216
+ (entities: Entity[]) => {
217
+ const requestedLimit = params?.limit || 20;
218
+ onUpdate({
219
+ data: entities as Entity<M>[],
220
+ meta: {
221
+ total: entities.length,
222
+ limit: requestedLimit,
223
+ offset: params?.offset || 0,
224
+ hasMore: entities.length >= requestedLimit
225
+ }
226
+ });
227
+ },
228
+ onError
229
+ );
230
+ };
231
+
232
+ client.listenById = (id: string | number, onUpdate: (data: Entity<M> | undefined) => void, onError?: (error: Error) => void) => {
233
+ return ws.listenEntity(
234
+ { path: slug,
235
+ entityId: String(id) },
236
+ (entity: Entity | null) => {
237
+ if (entity) {
238
+ onUpdate(entity as Entity<M>);
239
+ } else {
240
+ onUpdate(undefined);
241
+ }
242
+ },
243
+ onError
244
+ );
245
+ };
246
+ }
247
+
248
+ return client;
198
249
  }
@@ -0,0 +1,164 @@
1
+ import { describe, it, expect, jest, beforeEach } from "@jest/globals";
2
+ import { createCron } from "./cron";
3
+ import type { Transport } from "./transport";
4
+
5
+ // ─── Mock Transport ─────────────────────────────────────────────────
6
+
7
+ function createMockTransport() {
8
+ const requestMock = jest.fn() as unknown as jest.MockedFunction<Transport["request"]>;
9
+
10
+ return {
11
+ request: requestMock,
12
+ setToken: jest.fn(),
13
+ setAuthTokenGetter: jest.fn(),
14
+ setOnUnauthorized: jest.fn(),
15
+ get baseUrl() { return "http://test"; },
16
+ get apiPath() { return "/api"; },
17
+ get fetchFn() { return globalThis.fetch; },
18
+ getHeaders: () => ({}),
19
+ resolveToken: async () => null
20
+ };
21
+ }
22
+
23
+ // ─── Tests ──────────────────────────────────────────────────────────
24
+
25
+ describe("createCron", () => {
26
+ let transport: ReturnType<typeof createMockTransport>;
27
+
28
+ beforeEach(() => {
29
+ transport = createMockTransport();
30
+ });
31
+
32
+ describe("listJobs", () => {
33
+ it("calls GET /cron", async () => {
34
+ transport.request.mockResolvedValue({ jobs: [] });
35
+ const cron = createCron(transport);
36
+
37
+ const result = await cron.listJobs();
38
+
39
+ expect(transport.request).toHaveBeenCalledWith("/cron", { method: "GET" });
40
+ expect(result).toEqual({ jobs: [] });
41
+ });
42
+ });
43
+
44
+ describe("getJob", () => {
45
+ it("calls GET /cron/:id with encoded ID", async () => {
46
+ transport.request.mockResolvedValue({ job: { id: "my-job" } });
47
+ const cron = createCron(transport);
48
+
49
+ await cron.getJob("my-job");
50
+
51
+ expect(transport.request).toHaveBeenCalledWith("/cron/my-job", { method: "GET" });
52
+ });
53
+
54
+ it("encodes special characters in job ID", async () => {
55
+ transport.request.mockResolvedValue({ job: {} });
56
+ const cron = createCron(transport);
57
+
58
+ await cron.getJob("job with spaces");
59
+
60
+ expect(transport.request).toHaveBeenCalledWith(
61
+ "/cron/job%20with%20spaces",
62
+ { method: "GET" }
63
+ );
64
+ });
65
+ });
66
+
67
+ describe("triggerJob", () => {
68
+ it("calls POST /cron/:id/trigger", async () => {
69
+ transport.request.mockResolvedValue({ log: {},
70
+ job: {} });
71
+ const cron = createCron(transport);
72
+
73
+ await cron.triggerJob("my-job");
74
+
75
+ expect(transport.request).toHaveBeenCalledWith(
76
+ "/cron/my-job/trigger",
77
+ { method: "POST" }
78
+ );
79
+ });
80
+ });
81
+
82
+ describe("getJobLogs", () => {
83
+ it("calls GET /cron/:id/logs without limit", async () => {
84
+ transport.request.mockResolvedValue({ logs: [] });
85
+ const cron = createCron(transport);
86
+
87
+ await cron.getJobLogs("my-job");
88
+
89
+ expect(transport.request).toHaveBeenCalledWith(
90
+ "/cron/my-job/logs",
91
+ { method: "GET" }
92
+ );
93
+ });
94
+
95
+ it("appends limit query param when provided", async () => {
96
+ transport.request.mockResolvedValue({ logs: [] });
97
+ const cron = createCron(transport);
98
+
99
+ await cron.getJobLogs("my-job", { limit: 5 });
100
+
101
+ expect(transport.request).toHaveBeenCalledWith(
102
+ "/cron/my-job/logs?limit=5",
103
+ { method: "GET" }
104
+ );
105
+ });
106
+ });
107
+
108
+ describe("toggleJob", () => {
109
+ it("calls PUT /cron/:id with enabled=true", async () => {
110
+ transport.request.mockResolvedValue({ job: {} });
111
+ const cron = createCron(transport);
112
+
113
+ await cron.toggleJob("my-job", true);
114
+
115
+ expect(transport.request).toHaveBeenCalledWith(
116
+ "/cron/my-job",
117
+ {
118
+ method: "PUT",
119
+ body: JSON.stringify({ enabled: true })
120
+ }
121
+ );
122
+ });
123
+
124
+ it("calls PUT /cron/:id with enabled=false", async () => {
125
+ transport.request.mockResolvedValue({ job: {} });
126
+ const cron = createCron(transport);
127
+
128
+ await cron.toggleJob("my-job", false);
129
+
130
+ expect(transport.request).toHaveBeenCalledWith(
131
+ "/cron/my-job",
132
+ {
133
+ method: "PUT",
134
+ body: JSON.stringify({ enabled: false })
135
+ }
136
+ );
137
+ });
138
+ });
139
+
140
+ describe("custom cronPath", () => {
141
+ it("uses custom path prefix", async () => {
142
+ transport.request.mockResolvedValue({ jobs: [] });
143
+ const cron = createCron(transport, { cronPath: "/admin/scheduled" });
144
+
145
+ await cron.listJobs();
146
+
147
+ expect(transport.request).toHaveBeenCalledWith(
148
+ "/admin/scheduled",
149
+ { method: "GET" }
150
+ );
151
+ });
152
+
153
+ it("custom path applies to all methods", async () => {
154
+ transport.request.mockResolvedValue({});
155
+ const cron = createCron(transport, { cronPath: "/v2/cron" });
156
+
157
+ await cron.getJob("x");
158
+ expect(transport.request).toHaveBeenCalledWith("/v2/cron/x", { method: "GET" });
159
+
160
+ await cron.triggerJob("x");
161
+ expect(transport.request).toHaveBeenCalledWith("/v2/cron/x/trigger", { method: "POST" });
162
+ });
163
+ });
164
+ });
package/src/cron.ts ADDED
@@ -0,0 +1,62 @@
1
+ import { Transport } from "./transport";
2
+ import type { CronJobStatus, CronJobLogEntry } from "@rebasepro/types";
3
+
4
+ export interface CreateCronOptions {
5
+ cronPath?: string;
6
+ }
7
+
8
+ export function createCron(transport: Transport, options?: CreateCronOptions) {
9
+ const cronPath = options?.cronPath || "/cron";
10
+
11
+ async function listJobs(): Promise<{ jobs: CronJobStatus[] }> {
12
+ return transport.request<{ jobs: CronJobStatus[] }>(cronPath, { method: "GET" });
13
+ }
14
+
15
+ async function getJob(jobId: string): Promise<{ job: CronJobStatus }> {
16
+ return transport.request<{ job: CronJobStatus }>(
17
+ cronPath + "/" + encodeURIComponent(jobId),
18
+ { method: "GET" }
19
+ );
20
+ }
21
+
22
+ async function triggerJob(jobId: string): Promise<{ log: CronJobLogEntry; job: CronJobStatus }> {
23
+ return transport.request<{ log: CronJobLogEntry; job: CronJobStatus }>(
24
+ cronPath + "/" + encodeURIComponent(jobId) + "/trigger",
25
+ { method: "POST" }
26
+ );
27
+ }
28
+
29
+ async function getJobLogs(
30
+ jobId: string,
31
+ options?: { limit?: number }
32
+ ): Promise<{ logs: CronJobLogEntry[] }> {
33
+ const params = new URLSearchParams();
34
+ if (options?.limit !== undefined) params.set("limit", String(options.limit));
35
+ const qs = params.toString();
36
+ return transport.request<{ logs: CronJobLogEntry[] }>(
37
+ cronPath + "/" + encodeURIComponent(jobId) + "/logs" + (qs ? "?" + qs : ""),
38
+ { method: "GET" }
39
+ );
40
+ }
41
+
42
+ async function toggleJob(
43
+ jobId: string,
44
+ enabled: boolean
45
+ ): Promise<{ job: CronJobStatus }> {
46
+ return transport.request<{ job: CronJobStatus }>(
47
+ cronPath + "/" + encodeURIComponent(jobId),
48
+ {
49
+ method: "PUT",
50
+ body: JSON.stringify({ enabled })
51
+ }
52
+ );
53
+ }
54
+
55
+ return {
56
+ listJobs,
57
+ getJob,
58
+ triggerJob,
59
+ getJobLogs,
60
+ toggleJob
61
+ };
62
+ }