@supatype/client 0.1.0-alpha.10

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.
Files changed (71) hide show
  1. package/.turbo/turbo-build.log +4 -0
  2. package/.turbo/turbo-test.log +23 -0
  3. package/.turbo/turbo-typecheck.log +4 -0
  4. package/dist/auth.d.ts +279 -0
  5. package/dist/auth.d.ts.map +1 -0
  6. package/dist/auth.js +848 -0
  7. package/dist/auth.js.map +1 -0
  8. package/dist/error-codes-doc.d.ts +31 -0
  9. package/dist/error-codes-doc.d.ts.map +1 -0
  10. package/dist/error-codes-doc.js +294 -0
  11. package/dist/error-codes-doc.js.map +1 -0
  12. package/dist/errors.d.ts +197 -0
  13. package/dist/errors.d.ts.map +1 -0
  14. package/dist/errors.js +162 -0
  15. package/dist/errors.js.map +1 -0
  16. package/dist/fetch-with-retry.d.ts +49 -0
  17. package/dist/fetch-with-retry.d.ts.map +1 -0
  18. package/dist/fetch-with-retry.js +150 -0
  19. package/dist/fetch-with-retry.js.map +1 -0
  20. package/dist/index.d.ts +151 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +285 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/query.d.ts +55 -0
  25. package/dist/query.d.ts.map +1 -0
  26. package/dist/query.js +264 -0
  27. package/dist/query.js.map +1 -0
  28. package/dist/realtime.d.ts +69 -0
  29. package/dist/realtime.d.ts.map +1 -0
  30. package/dist/realtime.js +279 -0
  31. package/dist/realtime.js.map +1 -0
  32. package/dist/retry.d.ts +24 -0
  33. package/dist/retry.d.ts.map +1 -0
  34. package/dist/retry.js +25 -0
  35. package/dist/retry.js.map +1 -0
  36. package/dist/serverless-docs.d.ts +38 -0
  37. package/dist/serverless-docs.d.ts.map +1 -0
  38. package/dist/serverless-docs.js +83 -0
  39. package/dist/serverless-docs.js.map +1 -0
  40. package/dist/storage.d.ts +102 -0
  41. package/dist/storage.d.ts.map +1 -0
  42. package/dist/storage.js +169 -0
  43. package/dist/storage.js.map +1 -0
  44. package/dist/types.d.ts +212 -0
  45. package/dist/types.d.ts.map +1 -0
  46. package/dist/types.js +3 -0
  47. package/dist/types.js.map +1 -0
  48. package/package.json +26 -0
  49. package/src/auth.ts +1024 -0
  50. package/src/error-codes-doc.ts +315 -0
  51. package/src/errors.ts +201 -0
  52. package/src/fetch-with-retry.ts +200 -0
  53. package/src/index.ts +518 -0
  54. package/src/query.ts +331 -0
  55. package/src/realtime.ts +418 -0
  56. package/src/retry.ts +35 -0
  57. package/src/serverless-docs.ts +107 -0
  58. package/src/storage.ts +234 -0
  59. package/src/types.ts +264 -0
  60. package/tests/auth.test.ts +351 -0
  61. package/tests/mfa-totp-integration.test.ts +359 -0
  62. package/tests/query.test.ts +286 -0
  63. package/tests/rate-limit-integration.test.ts +185 -0
  64. package/tests/realtime-multi-tenant-integration.test.ts +372 -0
  65. package/tests/retry-integration.test.ts +212 -0
  66. package/tests/serverless.test.ts +115 -0
  67. package/tests/storage-quota-integration.test.ts +189 -0
  68. package/tests/storage-upload-limit-integration.test.ts +185 -0
  69. package/tests/types.test.ts +137 -0
  70. package/tsconfig.json +11 -0
  71. package/tsconfig.tsbuildinfo +1 -0
package/src/query.ts ADDED
@@ -0,0 +1,331 @@
1
+ import type { QueryResult, SupatypeError } from "./types.js"
2
+
3
+ const DEBUG_AUTH =
4
+ (typeof process !== "undefined" && process.env["NEXT_PUBLIC_SUPATYPE_DEBUG_AUTH"] === "1") ||
5
+ (typeof process !== "undefined" && process.env["SUPATYPE_DEBUG_AUTH"] === "1")
6
+
7
+ function decodeJwtRoleFromAuthHeader(headers: Record<string, string>): string | null {
8
+ const auth = headers["Authorization"] ?? headers["authorization"]
9
+ if (auth === undefined || !auth.startsWith("Bearer ")) return null
10
+ const token = auth.slice("Bearer ".length)
11
+ const parts = token.split(".")
12
+ if (parts.length !== 3) return null
13
+ try {
14
+ const payloadJson =
15
+ typeof atob === "function"
16
+ ? atob(parts[1] ?? "")
17
+ : Buffer.from(parts[1] ?? "", "base64").toString("utf-8")
18
+ const payload = JSON.parse(payloadJson) as Record<string, unknown>
19
+ return typeof payload["role"] === "string" ? payload["role"] : null
20
+ } catch {
21
+ return null
22
+ }
23
+ }
24
+
25
+ // ─── QueryBuilder ─────────────────────────────────────────────────────────────
26
+
27
+ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
28
+ private readonly baseUrl: string
29
+ private readonly path: string
30
+ private readonly headers: Record<string, string>
31
+ private readonly params: URLSearchParams
32
+
33
+ constructor(
34
+ baseUrl: string,
35
+ path: string,
36
+ headers: Record<string, string>,
37
+ columns?: string | undefined,
38
+ ) {
39
+ this.baseUrl = baseUrl
40
+ this.path = path
41
+ this.headers = { ...headers }
42
+ this.params = new URLSearchParams()
43
+ if (columns !== undefined) {
44
+ this.params.set("select", columns)
45
+ }
46
+ }
47
+
48
+ select(columns: string): this {
49
+ this.params.set("select", columns)
50
+ return this
51
+ }
52
+
53
+ eq(column: string, value: unknown): this {
54
+ this.params.append(column, `eq.${String(value)}`)
55
+ return this
56
+ }
57
+
58
+ neq(column: string, value: unknown): this {
59
+ this.params.append(column, `neq.${String(value)}`)
60
+ return this
61
+ }
62
+
63
+ gt(column: string, value: unknown): this {
64
+ this.params.append(column, `gt.${String(value)}`)
65
+ return this
66
+ }
67
+
68
+ gte(column: string, value: unknown): this {
69
+ this.params.append(column, `gte.${String(value)}`)
70
+ return this
71
+ }
72
+
73
+ lt(column: string, value: unknown): this {
74
+ this.params.append(column, `lt.${String(value)}`)
75
+ return this
76
+ }
77
+
78
+ lte(column: string, value: unknown): this {
79
+ this.params.append(column, `lte.${String(value)}`)
80
+ return this
81
+ }
82
+
83
+ like(column: string, pattern: string): this {
84
+ this.params.append(column, `like.${pattern}`)
85
+ return this
86
+ }
87
+
88
+ ilike(column: string, pattern: string): this {
89
+ this.params.append(column, `ilike.${pattern}`)
90
+ return this
91
+ }
92
+
93
+ in(column: string, values: unknown[]): this {
94
+ this.params.append(column, `in.(${values.map(String).join(",")})`)
95
+ return this
96
+ }
97
+
98
+ is(column: string, value: null | boolean): this {
99
+ this.params.append(column, `is.${String(value)}`)
100
+ return this
101
+ }
102
+
103
+ not(column: string, op: string, value: unknown): this {
104
+ this.params.append(column, `not.${op}.${String(value)}`)
105
+ return this
106
+ }
107
+
108
+ contains(column: string, value: unknown): this {
109
+ this.params.append(column, `cs.${JSON.stringify(value)}`)
110
+ return this
111
+ }
112
+
113
+ containedBy(column: string, value: unknown): this {
114
+ this.params.append(column, `cd.${JSON.stringify(value)}`)
115
+ return this
116
+ }
117
+
118
+ order(
119
+ column: string,
120
+ opts?: { ascending?: boolean | undefined; nullsFirst?: boolean | undefined } | undefined,
121
+ ): this {
122
+ const dir = opts?.ascending === false ? "desc" : "asc"
123
+ const nulls = opts?.nullsFirst === true ? "nullsfirst" : "nullslast"
124
+ this.params.append("order", `${column}.${dir}.${nulls}`)
125
+ return this
126
+ }
127
+
128
+ limit(count: number): this {
129
+ this.params.set("limit", String(count))
130
+ return this
131
+ }
132
+
133
+ /** Set the locale for resolving localized fields. */
134
+ locale(code: string): this {
135
+ this.headers["Accept-Language"] = code
136
+ return this
137
+ }
138
+
139
+ range(from: number, to: number): this {
140
+ this.headers["Range"] = `${from}-${to}`
141
+ this.headers["Range-Unit"] = "items"
142
+ return this
143
+ }
144
+
145
+ /** Return a single row (errors if none or many found). */
146
+ async single(): Promise<QueryResult<TRow>> {
147
+ const headers = {
148
+ ...this.headers,
149
+ Accept: "application/vnd.pgrst.object+json",
150
+ }
151
+ const { data, error } = await this._fetch(headers)
152
+ if (error !== null) return { data: null, error, count: null }
153
+ return { data: data as unknown as TRow, error: null, count: 1 }
154
+ }
155
+
156
+ /** Return a single row or null (errors if many found). */
157
+ async maybeSingle(): Promise<QueryResult<TRow | null>> {
158
+ const { data, error, count } = await this._fetch(this.headers)
159
+ if (error !== null) return { data: null, error, count: null }
160
+ const rows = data as TRow[]
161
+ const row = rows.length > 0 ? (rows[0] ?? null) : null
162
+ return { data: row, error: null, count }
163
+ }
164
+
165
+ then<R1 = QueryResult<TRow[]>, R2 = never>(
166
+ onfulfilled?: ((value: QueryResult<TRow[]>) => R1 | PromiseLike<R1>) | null | undefined,
167
+ onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null | undefined,
168
+ ): PromiseLike<R1 | R2> {
169
+ return this._fetch(this.headers).then(onfulfilled, onrejected)
170
+ }
171
+
172
+ private async _fetch(headers: Record<string, string>): Promise<QueryResult<TRow[]>> {
173
+ const qs = this.params.toString()
174
+ const url = `${this.baseUrl}${this.path}${qs ? `?${qs}` : ""}`
175
+ let res: Response
176
+ try {
177
+ res = await fetch(url, { headers })
178
+ } catch (e) {
179
+ return {
180
+ data: null,
181
+ error: { message: e instanceof Error ? e.message : "Network error" },
182
+ count: null,
183
+ }
184
+ }
185
+
186
+ const contentRange = res.headers.get("content-range")
187
+ const count =
188
+ contentRange !== null
189
+ ? parseInt(contentRange.split("/")[1] ?? "0", 10)
190
+ : null
191
+
192
+ if (!res.ok) {
193
+ const err = await res.json().catch(() => ({ message: "Error" })) as Record<string, unknown>
194
+ if (DEBUG_AUTH) {
195
+ console.log("[supatype:query] request failed", {
196
+ url,
197
+ status: res.status,
198
+ role: decodeJwtRoleFromAuthHeader(headers),
199
+ message: String(err["message"] ?? err["hint"] ?? "Request failed"),
200
+ code: typeof err["code"] === "string" ? err["code"] : null,
201
+ })
202
+ }
203
+ return {
204
+ data: null,
205
+ error: {
206
+ message: String(err["message"] ?? err["hint"] ?? "Request failed"),
207
+ status: res.status,
208
+ ...(err["code"] !== undefined && { code: String(err["code"]) }),
209
+ },
210
+ count: null,
211
+ }
212
+ }
213
+
214
+ const json = await res.json() as TRow[]
215
+ return { data: json, error: null, count }
216
+ }
217
+ }
218
+
219
+ // ─── MutationBuilder ──────────────────────────────────────────────────────────
220
+
221
+ type HttpMethod = "POST" | "PATCH" | "DELETE"
222
+
223
+ export class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
224
+ private readonly baseUrl: string
225
+ private readonly path: string
226
+ private readonly headers: Record<string, string>
227
+ private readonly method: HttpMethod
228
+ private readonly body: unknown
229
+ private readonly params: URLSearchParams
230
+
231
+ constructor(
232
+ baseUrl: string,
233
+ path: string,
234
+ headers: Record<string, string>,
235
+ method: HttpMethod,
236
+ body?: unknown,
237
+ opts?: { upsert?: boolean | undefined } | undefined,
238
+ ) {
239
+ this.baseUrl = baseUrl
240
+ this.path = path
241
+ this.headers = { ...headers }
242
+ this.method = method
243
+ this.body = body
244
+ this.params = new URLSearchParams()
245
+
246
+ if (opts?.upsert === true) {
247
+ this.headers["Prefer"] = "resolution=merge-duplicates"
248
+ }
249
+
250
+ // Return inserted/updated rows
251
+ if (method !== "DELETE") {
252
+ this.headers["Prefer"] = (this.headers["Prefer"] ?? "") + ",return=representation"
253
+ }
254
+ }
255
+
256
+ eq(column: string, value: unknown): this {
257
+ this.params.append(column, `eq.${String(value)}`)
258
+ return this
259
+ }
260
+
261
+ neq(column: string, value: unknown): this {
262
+ this.params.append(column, `neq.${String(value)}`)
263
+ return this
264
+ }
265
+
266
+ in(column: string, values: unknown[]): this {
267
+ this.params.append(column, `in.(${values.map(String).join(",")})`)
268
+ return this
269
+ }
270
+
271
+ then<R1 = QueryResult<TRow[]>, R2 = never>(
272
+ onfulfilled?: ((value: QueryResult<TRow[]>) => R1 | PromiseLike<R1>) | null | undefined,
273
+ onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null | undefined,
274
+ ): PromiseLike<R1 | R2> {
275
+ return this._execute().then(onfulfilled, onrejected)
276
+ }
277
+
278
+ private async _execute(): Promise<QueryResult<TRow[]>> {
279
+ const qs = this.params.toString()
280
+ const url = `${this.baseUrl}${this.path}${qs ? `?${qs}` : ""}`
281
+ let res: Response
282
+ try {
283
+ res = await fetch(url, {
284
+ method: this.method,
285
+ headers: this.headers,
286
+ ...(this.body !== undefined && { body: JSON.stringify(this.body) }),
287
+ })
288
+ } catch (e) {
289
+ return {
290
+ data: null,
291
+ error: { message: e instanceof Error ? e.message : "Network error" },
292
+ count: null,
293
+ }
294
+ }
295
+
296
+ if (!res.ok) {
297
+ const err = await res.json().catch(() => ({ message: "Error" })) as Record<string, unknown>
298
+ if (DEBUG_AUTH) {
299
+ console.log("[supatype:mutation] request failed", {
300
+ url,
301
+ method: this.method,
302
+ status: res.status,
303
+ role: decodeJwtRoleFromAuthHeader(this.headers),
304
+ message: String(err["message"] ?? err["hint"] ?? "Request failed"),
305
+ code: typeof err["code"] === "string" ? err["code"] : null,
306
+ })
307
+ }
308
+ return {
309
+ data: null,
310
+ error: {
311
+ message: String(err["message"] ?? err["hint"] ?? "Request failed"),
312
+ status: res.status,
313
+ ...(err["code"] !== undefined && { code: String(err["code"]) }),
314
+ },
315
+ count: null,
316
+ }
317
+ }
318
+
319
+ if (res.status === 204) {
320
+ return { data: [], error: null, count: 0 }
321
+ }
322
+
323
+ const json = await res.json() as TRow | TRow[]
324
+ const data = Array.isArray(json) ? json : [json]
325
+ return { data, error: null, count: data.length }
326
+ }
327
+ }
328
+
329
+ // ─── StorageError ─────────────────────────────────────────────────────────────
330
+
331
+ export type { SupatypeError }