@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/storage.ts ADDED
@@ -0,0 +1,234 @@
1
+ import type { SupatypeError } from "./types.js"
2
+
3
+ export interface StorageObject {
4
+ id: string
5
+ name: string
6
+ bucket_id: string
7
+ owner?: string | undefined
8
+ created_at: string
9
+ updated_at: string
10
+ last_accessed_at: string
11
+ metadata?: Record<string, unknown> | undefined
12
+ }
13
+
14
+ export interface TransformOptions {
15
+ width?: number | undefined
16
+ height?: number | undefined
17
+ format?: "webp" | "avif" | "png" | "jpeg" | undefined
18
+ quality?: number | undefined
19
+ resize?: "cover" | "contain" | "fill" | "inside" | "outside" | undefined
20
+ }
21
+
22
+ export interface StorageBucketMeta {
23
+ id: string
24
+ name: string
25
+ public: boolean
26
+ file_size_limit: number | null
27
+ allowed_mime_types: string[] | null
28
+ created_at: string
29
+ updated_at: string
30
+ }
31
+
32
+ export class StorageClient {
33
+ private readonly url: string
34
+ private readonly headers: Record<string, string>
35
+
36
+ constructor(url: string, headers: Record<string, string>) {
37
+ this.url = url
38
+ this.headers = headers
39
+ }
40
+
41
+ from(bucket: string): BucketClient {
42
+ return new BucketClient(this.url, bucket, this.headers)
43
+ }
44
+
45
+ async listBuckets(): Promise<{ data: StorageBucketMeta[] | null; error: SupatypeError | null }> {
46
+ try {
47
+ const res = await fetch(`${this.url}/bucket`, { headers: this.headers })
48
+ if (!res.ok) {
49
+ const err = await res.json().catch(() => ({ message: "Error" })) as { message?: string }
50
+ return { data: null, error: { message: err.message ?? "Failed to list buckets" } }
51
+ }
52
+ const data = await res.json() as StorageBucketMeta[]
53
+ return { data, error: null }
54
+ } catch (e) {
55
+ return { data: null, error: { message: e instanceof Error ? e.message : "Network error" } }
56
+ }
57
+ }
58
+
59
+ async createBucket(
60
+ name: string,
61
+ options?: { public?: boolean | undefined; fileSizeLimit?: number | undefined; allowedMimeTypes?: string[] | undefined } | undefined,
62
+ ): Promise<{ data: { name: string } | null; error: SupatypeError | null }> {
63
+ try {
64
+ const body: Record<string, unknown> = {
65
+ id: name,
66
+ name,
67
+ ...(options?.public !== undefined && { public: options.public }),
68
+ ...(options?.fileSizeLimit !== undefined && { file_size_limit: options.fileSizeLimit }),
69
+ ...(options?.allowedMimeTypes !== undefined && { allowed_mime_types: options.allowedMimeTypes }),
70
+ }
71
+ const res = await fetch(`${this.url}/bucket`, {
72
+ method: "POST",
73
+ headers: { ...this.headers, "Content-Type": "application/json" },
74
+ body: JSON.stringify(body),
75
+ })
76
+ if (!res.ok) {
77
+ const err = await res.json().catch(() => ({ message: "Error" })) as { message?: string }
78
+ return { data: null, error: { message: err.message ?? "Failed to create bucket" } }
79
+ }
80
+ return { data: { name }, error: null }
81
+ } catch (e) {
82
+ return { data: null, error: { message: e instanceof Error ? e.message : "Network error" } }
83
+ }
84
+ }
85
+ }
86
+
87
+ export class BucketClient {
88
+ private readonly url: string
89
+ private readonly bucket: string
90
+ private readonly headers: Record<string, string>
91
+
92
+ constructor(url: string, bucket: string, headers: Record<string, string>) {
93
+ this.url = url
94
+ this.bucket = bucket
95
+ this.headers = headers
96
+ }
97
+
98
+ async upload(
99
+ path: string,
100
+ file: Blob | File | ArrayBuffer,
101
+ options?: { contentType?: string | undefined; upsert?: boolean | undefined } | undefined,
102
+ ): Promise<{ data: { path: string } | null; error: SupatypeError | null }> {
103
+ const inferredType = file instanceof File && file.type ? file.type : "application/octet-stream"
104
+ const headers: Record<string, string> = {
105
+ ...this.headers,
106
+ "Content-Type": options?.contentType ?? inferredType,
107
+ }
108
+ if (options?.upsert === true) {
109
+ headers["x-upsert"] = "true"
110
+ }
111
+ const res = await fetch(`${this.url}/object/${this.bucket}/${path}`, {
112
+ method: "POST",
113
+ headers,
114
+ body: file,
115
+ })
116
+ if (!res.ok) {
117
+ const err = await res.json().catch(() => ({ message: "Upload failed" })) as Record<string, unknown>
118
+ return { data: null, error: { message: String(err["message"] ?? err["error"] ?? "Upload failed"), status: res.status } }
119
+ }
120
+ return { data: { path }, error: null }
121
+ }
122
+
123
+ async download(
124
+ path: string,
125
+ options?: { transform?: TransformOptions | undefined } | undefined,
126
+ ): Promise<{ data: Blob | null; error: SupatypeError | null }> {
127
+ const url = this.buildObjectUrl("authenticated", path, options?.transform)
128
+ const res = await fetch(url, { headers: this.headers })
129
+ if (!res.ok) {
130
+ const err = await res.json().catch(() => ({ message: "Download failed" })) as Record<string, unknown>
131
+ return { data: null, error: { message: String(err["message"] ?? err["error"] ?? "Download failed"), status: res.status } }
132
+ }
133
+ const blob = await res.blob()
134
+ return { data: blob, error: null }
135
+ }
136
+
137
+ getPublicUrl(
138
+ path: string,
139
+ options?: { transform?: TransformOptions | undefined } | undefined,
140
+ ): { data: { publicUrl: string } } {
141
+ const publicUrl = this.buildObjectUrl("public", path, options?.transform)
142
+ return { data: { publicUrl } }
143
+ }
144
+
145
+ async createSignedUrl(
146
+ path: string,
147
+ expiresIn: number,
148
+ ): Promise<{ data: { signedUrl: string } | null; error: SupatypeError | null }> {
149
+ const res = await fetch(`${this.url}/object/sign/${this.bucket}/${path}`, {
150
+ method: "POST",
151
+ headers: { ...this.headers, "Content-Type": "application/json" },
152
+ body: JSON.stringify({ expiresIn }),
153
+ })
154
+ if (!res.ok) {
155
+ const err = await res.json().catch(() => ({ message: "Failed to create signed URL" })) as Record<string, unknown>
156
+ return { data: null, error: { message: String(err["message"] ?? err["error"] ?? "Failed to create signed URL"), status: res.status } }
157
+ }
158
+ const json = await res.json() as { signedURL: string }
159
+ return { data: { signedUrl: json.signedURL }, error: null }
160
+ }
161
+
162
+ async createSignedUrls(
163
+ paths: string[],
164
+ expiresIn: number,
165
+ ): Promise<{ data: { path: string; signedUrl: string; error: string | null }[] | null; error: SupatypeError | null }> {
166
+ const results = await Promise.all(
167
+ paths.map(async (path) => {
168
+ const result = await this.createSignedUrl(path, expiresIn)
169
+ if (result.error) {
170
+ return { path, signedUrl: "", error: result.error.message }
171
+ }
172
+ return { path, signedUrl: result.data!.signedUrl, error: null }
173
+ }),
174
+ )
175
+ return { data: results, error: null }
176
+ }
177
+
178
+ async remove(paths: string[]): Promise<{ data: StorageObject[] | null; error: SupatypeError | null }> {
179
+ const res = await fetch(`${this.url}/object/${this.bucket}`, {
180
+ method: "DELETE",
181
+ headers: { ...this.headers, "Content-Type": "application/json" },
182
+ body: JSON.stringify({ prefixes: paths }),
183
+ })
184
+ if (!res.ok) {
185
+ const err = await res.json().catch(() => ({ message: "Delete failed" })) as Record<string, unknown>
186
+ return { data: null, error: { message: String(err["message"] ?? err["error"] ?? "Delete failed"), status: res.status } }
187
+ }
188
+ const json = await res.json() as StorageObject[]
189
+ return { data: json, error: null }
190
+ }
191
+
192
+ async list(
193
+ prefix?: string | undefined,
194
+ options?: { limit?: number | undefined; offset?: number | undefined } | undefined,
195
+ ): Promise<{ data: StorageObject[] | null; error: SupatypeError | null }> {
196
+ const body: Record<string, unknown> = {
197
+ ...(prefix !== undefined && { prefix }),
198
+ ...(options?.limit !== undefined && { limit: options.limit }),
199
+ ...(options?.offset !== undefined && { offset: options.offset }),
200
+ }
201
+ const res = await fetch(`${this.url}/object/list/${this.bucket}`, {
202
+ method: "POST",
203
+ headers: { ...this.headers, "Content-Type": "application/json" },
204
+ body: JSON.stringify(body),
205
+ })
206
+ if (!res.ok) {
207
+ const err = await res.json().catch(() => ({ message: "List failed" })) as Record<string, unknown>
208
+ return { data: null, error: { message: String(err["message"] ?? err["error"] ?? "List failed"), status: res.status } }
209
+ }
210
+ const json = await res.json() as StorageObject[]
211
+ return { data: json, error: null }
212
+ }
213
+
214
+ // ─── Internal ───────────────────────────────────────────────────────────────
215
+
216
+ private buildObjectUrl(
217
+ access: "public" | "authenticated",
218
+ path: string,
219
+ transform?: TransformOptions | undefined,
220
+ ): string {
221
+ let url = `${this.url}/object/${access}/${this.bucket}/${path}`
222
+ if (transform) {
223
+ const params = new URLSearchParams()
224
+ if (transform.width !== undefined) params.set("width", String(transform.width))
225
+ if (transform.height !== undefined) params.set("height", String(transform.height))
226
+ if (transform.format !== undefined) params.set("format", transform.format)
227
+ if (transform.quality !== undefined) params.set("quality", String(transform.quality))
228
+ if (transform.resize !== undefined) params.set("resize", transform.resize)
229
+ const qs = params.toString()
230
+ if (qs) url += `?${qs}`
231
+ }
232
+ return url
233
+ }
234
+ }
package/src/types.ts ADDED
@@ -0,0 +1,264 @@
1
+ // ─── Auth types ───────────────────────────────────────────────────────────────
2
+
3
+ export interface UserIdentity {
4
+ id: string
5
+ userId: string
6
+ identityData: Record<string, unknown>
7
+ identityId: string
8
+ provider: string
9
+ createdAt: string
10
+ updatedAt: string
11
+ lastSignInAt?: string | undefined
12
+ }
13
+
14
+ export interface Factor {
15
+ id: string
16
+ friendlyName?: string | undefined
17
+ factorType: "totp" | "phone" | "webauthn"
18
+ status: "verified" | "unverified"
19
+ createdAt: string
20
+ updatedAt: string
21
+ phone?: string | undefined
22
+ }
23
+
24
+ export interface User {
25
+ id: string
26
+ email?: string | undefined
27
+ phone?: string | undefined
28
+ role?: string | undefined
29
+ isAnonymous?: boolean | undefined
30
+ appMetadata: Record<string, unknown>
31
+ userMetadata: Record<string, unknown>
32
+ identities?: UserIdentity[] | undefined
33
+ factors?: Factor[] | undefined
34
+ createdAt: string
35
+ updatedAt: string
36
+ }
37
+
38
+ export interface Session {
39
+ accessToken: string
40
+ tokenType: string
41
+ expiresIn: number
42
+ expiresAt?: number | undefined
43
+ refreshToken: string
44
+ user: User
45
+ }
46
+
47
+ export type AuthChangeEvent =
48
+ | "SIGNED_IN"
49
+ | "SIGNED_OUT"
50
+ | "TOKEN_REFRESHED"
51
+ | "USER_UPDATED"
52
+ | "PASSWORD_RECOVERY"
53
+ | "MFA_CHALLENGE_VERIFIED"
54
+
55
+ // ─── MFA types ──────────────────────────────────────────────────────────────
56
+
57
+ export interface AuthMFAEnrollResponse {
58
+ /** The MFA factor ID */
59
+ id: string
60
+ /** Factor type: totp, phone, or webauthn */
61
+ type: string
62
+ /** Friendly name for the factor */
63
+ friendlyName: string
64
+ /** TOTP-specific data (only present for totp factor type) */
65
+ totp?: {
66
+ /** QR code SVG string */
67
+ qrCode: string
68
+ /** TOTP secret */
69
+ secret: string
70
+ /** TOTP URI for manual entry */
71
+ uri: string
72
+ } | undefined
73
+ /** Phone number (only present for phone factor type) */
74
+ phone?: string | undefined
75
+ }
76
+
77
+ export interface AuthMFAChallengeResponse {
78
+ /** The challenge ID */
79
+ id: string
80
+ /** Factor type */
81
+ type: string
82
+ /** Challenge expiry timestamp (Unix epoch seconds) */
83
+ expiresAt: number
84
+ }
85
+
86
+ export interface AuthMFAVerifyResponse {
87
+ /** Access token */
88
+ accessToken: string
89
+ tokenType: string
90
+ expiresIn: number
91
+ expiresAt?: number | undefined
92
+ refreshToken: string
93
+ user: User
94
+ }
95
+
96
+ export interface AuthMFAListFactorsResponse {
97
+ /** All factors including unverified */
98
+ all: Factor[]
99
+ /** Only verified TOTP factors */
100
+ totp: Factor[]
101
+ /** Only verified phone factors */
102
+ phone: Factor[]
103
+ }
104
+
105
+ export type OtpType =
106
+ | "signup"
107
+ | "magiclink"
108
+ | "recovery"
109
+ | "invite"
110
+ | "email_change"
111
+ | "sms"
112
+ | "phone_change"
113
+ | "email"
114
+
115
+ // ─── Error type ───────────────────────────────────────────────────────────────
116
+
117
+ export interface SupatypeError {
118
+ message: string
119
+ status?: number | undefined
120
+ code?: string | undefined
121
+ }
122
+
123
+ // ─── Query result ─────────────────────────────────────────────────────────────
124
+
125
+ export interface QueryResult<TData> {
126
+ data: TData | null
127
+ error: SupatypeError | null
128
+ count: number | null
129
+ }
130
+
131
+ // ─── RPC result ──────────────────────────────────────────────────────────────
132
+
133
+ export interface RpcResult<TData> {
134
+ data: TData | null
135
+ error: SupatypeError | null
136
+ }
137
+
138
+ // ─── Database generic ─────────────────────────────────────────────────────────
139
+
140
+ export interface TableDef {
141
+ Row: Record<string, unknown>
142
+ /**
143
+ * Columns the database fills (`gen_random_uuid()`, `now()`, sequences, etc.)
144
+ * are optional here even when required on {@link TableDef.Row}.
145
+ */
146
+ Insert: Record<string, unknown>
147
+ Update: Record<string, unknown>
148
+ }
149
+
150
+ /**
151
+ * Module augmentation anchors used by generated `supatype` types output.
152
+ *
153
+ * Example generated output:
154
+ * declare module "@supatype/client" {
155
+ * interface SupatypeModels {
156
+ * post: { Row: PostRow; Insert: PostInsert; Update: PostUpdate }
157
+ * }
158
+ * }
159
+ */
160
+ export interface SupatypeModels {}
161
+ export interface SupatypeBuckets {}
162
+ export interface SupatypeFunctions {}
163
+
164
+ /**
165
+ * Insert payload for an augmented table name (from generated `supatype` output).
166
+ *
167
+ * For inserts from plain objects, prefer this over re-stating column unions.
168
+ */
169
+ export type TableInsert<TTable extends keyof SupatypeModels & string> =
170
+ [keyof SupatypeModels] extends [never]
171
+ ? Record<string, unknown>
172
+ : TTable extends keyof SupatypeModels
173
+ ? SupatypeModels[TTable] extends { Insert: infer I }
174
+ ? I
175
+ : Record<string, unknown>
176
+ : Record<string, unknown>
177
+
178
+ type ModelDefFromAugmented<T> =
179
+ T extends TableDef
180
+ ? T
181
+ : T extends Record<string, unknown>
182
+ ? { Row: T; Insert: Partial<T>; Update: Partial<T> }
183
+ : TableDef
184
+
185
+ export type AugmentedTables =
186
+ [keyof SupatypeModels] extends [never]
187
+ ? Record<string, TableDef>
188
+ : {
189
+ [K in keyof SupatypeModels & string]: ModelDefFromAugmented<SupatypeModels[K]>
190
+ }
191
+
192
+ export type AugmentedFunctions =
193
+ [keyof SupatypeFunctions] extends [never]
194
+ ? Record<string, FunctionDef>
195
+ : {
196
+ [K in keyof SupatypeFunctions & string]:
197
+ SupatypeFunctions[K] extends FunctionDef ? SupatypeFunctions[K] : FunctionDef
198
+ }
199
+
200
+ export interface AugmentedDatabase {
201
+ public: {
202
+ Tables: AugmentedTables
203
+ Functions?: AugmentedFunctions | undefined
204
+ }
205
+ }
206
+
207
+ /**
208
+ * Describes the shape of a Postgres function for typed `.rpc()` calls.
209
+ * Generated by the Supatype engine from detected Postgres functions.
210
+ */
211
+ export interface FunctionDef {
212
+ Args: Record<string, unknown>
213
+ Returns: unknown
214
+ }
215
+
216
+ export interface AnyDatabase {
217
+ public: {
218
+ Tables: Record<string, TableDef>
219
+ Functions?: Record<string, FunctionDef> | undefined
220
+ }
221
+ }
222
+
223
+ // ─── Client config ────────────────────────────────────────────────────────────
224
+
225
+ export interface SupatypeClientConfig {
226
+ /** Base URL of the Supatype gateway (e.g. http://localhost:18473) */
227
+ url: string
228
+ /** Anon JWT key */
229
+ anonKey: string
230
+ /**
231
+ * Service role key — bypasses row-level security.
232
+ * Only set this in trusted server-side or developer-tool contexts.
233
+ * Never expose to end-user clients.
234
+ */
235
+ serviceRoleKey?: string | undefined
236
+ auth?: {
237
+ /** Persist session across page reloads (browser only). Default: true */
238
+ persistSession?: boolean | undefined
239
+ /** localStorage key to use for session storage. Default: "supatype.auth.session" */
240
+ storageKey?: string | undefined
241
+ /**
242
+ * Cookie prefix used for browser-written auth cookie.
243
+ * `@supatype/ssr` reads `<prefix>-auth-token` (and `<prefix>-*-auth-token` forms).
244
+ * Default: `"st"`.
245
+ */
246
+ cookiePrefix?: string | undefined
247
+ } | undefined
248
+ /**
249
+ * Disable automatic retry for transient errors.
250
+ * Default: true (retries enabled).
251
+ */
252
+ retry?: boolean | undefined
253
+ /**
254
+ * Request timeout in milliseconds. Default: 30000 (30 seconds).
255
+ * Applied to every HTTP request made by the client.
256
+ */
257
+ timeout?: number | undefined
258
+ /**
259
+ * Pre-load a session at construction time (SSR use case).
260
+ * Used by `@supatype/ssr` to inject a cookie-parsed session into the client
261
+ * before any requests are made.
262
+ */
263
+ initialSession?: Session | undefined
264
+ }