@supatype/client 0.1.0-alpha.6 → 0.1.0-alpha.8

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
@@ -5,7 +5,15 @@ import { RealtimeClient } from "./realtime.js"
5
5
  import { PostgrestError } from "./errors.js"
6
6
  import { createRetryFetch } from "./retry.js"
7
7
  import { warnIfServerlessDirectConnection } from "./fetch-with-retry.js"
8
- import type { AnyDatabase, FunctionDef, RpcResult, SupatypeClientConfig, SupatypeError } from "./types.js"
8
+ import type {
9
+ AnyDatabase,
10
+ AugmentedDatabase,
11
+ FunctionDef,
12
+ RpcResult,
13
+ SupatypeFunctions,
14
+ SupatypeClientConfig,
15
+ SupatypeError,
16
+ } from "./types.js"
9
17
 
10
18
  export type {
11
19
  User,
@@ -18,6 +26,11 @@ export type {
18
26
  SupatypeClientConfig,
19
27
  FunctionDef,
20
28
  TableDef,
29
+ TableInsert,
30
+ SupatypeModels,
31
+ SupatypeBuckets,
32
+ SupatypeFunctions,
33
+ AugmentedDatabase,
21
34
  } from "./types.js"
22
35
  export { AuthClient } from "./auth.js"
23
36
  export { QueryBuilder, MutationBuilder } from "./query.js"
@@ -119,6 +132,21 @@ export interface GlobalClient<TRow extends Record<string, unknown> = Record<stri
119
132
  update(data: Partial<TRow>): Promise<{ data: TRow | null; error: SupatypeError | null }>
120
133
  }
121
134
 
135
+ function jwtRole(token: string): string | null {
136
+ const parts = token.split(".")
137
+ if (parts.length !== 3) return null
138
+ try {
139
+ const payloadJson =
140
+ typeof atob === "function"
141
+ ? atob(parts[1] ?? "")
142
+ : Buffer.from(parts[1] ?? "", "base64").toString("utf-8")
143
+ const payload = JSON.parse(payloadJson) as Record<string, unknown>
144
+ return typeof payload["role"] === "string" ? payload["role"] : null
145
+ } catch {
146
+ return null
147
+ }
148
+ }
149
+
122
150
  /**
123
151
  * Helper type: extract function names from a database type.
124
152
  * Falls back to `string` when Functions is not defined.
@@ -156,6 +184,29 @@ type FunctionReturns<TDatabase extends AnyDatabase, TFn extends string> =
156
184
  : unknown
157
185
  : unknown
158
186
 
187
+ type EdgeFunctionNames =
188
+ [keyof SupatypeFunctions] extends [never]
189
+ ? string
190
+ : keyof SupatypeFunctions & string
191
+
192
+ type EdgeFunctionArgs<TFn extends string> =
193
+ [keyof SupatypeFunctions] extends [never]
194
+ ? unknown
195
+ : TFn extends keyof SupatypeFunctions
196
+ ? SupatypeFunctions[TFn] extends FunctionDef
197
+ ? SupatypeFunctions[TFn]["Args"]
198
+ : unknown
199
+ : unknown
200
+
201
+ type EdgeFunctionReturns<TFn extends string> =
202
+ [keyof SupatypeFunctions] extends [never]
203
+ ? unknown
204
+ : TFn extends keyof SupatypeFunctions
205
+ ? SupatypeFunctions[TFn] extends FunctionDef
206
+ ? SupatypeFunctions[TFn]["Returns"]
207
+ : unknown
208
+ : unknown
209
+
159
210
  // ─── Functions client ─────────────────────────────────────────────────────────
160
211
 
161
212
  export interface FunctionInvokeOptions {
@@ -189,10 +240,10 @@ class FunctionsClient {
189
240
  *
190
241
  * The current user's JWT is automatically included in the Authorization header.
191
242
  */
192
- async invoke<TResponse = unknown>(
193
- functionName: string,
194
- options?: FunctionInvokeOptions | undefined,
195
- ): Promise<{ data: TResponse | null; error: SupatypeError | null }> {
243
+ async invoke<TFn extends EdgeFunctionNames>(
244
+ functionName: TFn,
245
+ options?: (Omit<FunctionInvokeOptions, "body"> & { body?: EdgeFunctionArgs<TFn> | undefined }) | undefined,
246
+ ): Promise<{ data: EdgeFunctionReturns<TFn> | null; error: SupatypeError | null }> {
196
247
  const method = options?.method ?? "POST"
197
248
  const mergedHeaders: Record<string, string> = {
198
249
  ...this.headers,
@@ -228,13 +279,13 @@ class FunctionsClient {
228
279
 
229
280
  const contentType = res.headers.get("content-type") ?? ""
230
281
  if (contentType.includes("application/json")) {
231
- const data = await res.json() as TResponse
282
+ const data = await res.json() as EdgeFunctionReturns<TFn>
232
283
  return { data, error: null }
233
284
  }
234
285
 
235
286
  // Return text for non-JSON responses
236
287
  const text = await res.text()
237
- return { data: text as unknown as TResponse, error: null }
288
+ return { data: text as unknown as EdgeFunctionReturns<TFn>, error: null }
238
289
  } catch (e) {
239
290
  return {
240
291
  data: null,
@@ -244,7 +295,10 @@ class FunctionsClient {
244
295
  }
245
296
  }
246
297
 
247
- export interface SupatypeClient<TDatabase extends AnyDatabase = AnyDatabase> {
298
+ export interface SupatypeClient<TDatabase extends AnyDatabase = AugmentedDatabase> {
299
+ url: string
300
+ /** Service role key, if provided at construction time. Used by developer tools for admin API calls. */
301
+ serviceRoleKey: string | undefined
248
302
  from<TTable extends keyof TDatabase["public"]["Tables"] & string>(
249
303
  table: TTable,
250
304
  ): TableClient<TDatabase["public"]["Tables"][TTable]>
@@ -277,7 +331,7 @@ export interface SupatypeClient<TDatabase extends AnyDatabase = AnyDatabase> {
277
331
  ): Promise<RpcResult<FunctionReturns<TDatabase, TFn>>>
278
332
  }
279
333
 
280
- export function createClient<TDatabase extends AnyDatabase = AnyDatabase>(
334
+ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
281
335
  config: SupatypeClientConfig,
282
336
  ): SupatypeClient<TDatabase> {
283
337
  // Warn early if a direct Postgres URL is used in a serverless environment
@@ -285,6 +339,7 @@ export function createClient<TDatabase extends AnyDatabase = AnyDatabase>(
285
339
 
286
340
  const baseHeaders: Record<string, string> = {
287
341
  apikey: config.anonKey,
342
+ Authorization: `Bearer ${config.anonKey}`,
288
343
  "Content-Type": "application/json",
289
344
  }
290
345
 
@@ -294,19 +349,52 @@ export function createClient<TDatabase extends AnyDatabase = AnyDatabase>(
294
349
  timeout: config.timeout,
295
350
  })
296
351
 
297
- const auth = new AuthClient(`${config.url}/auth/v1`, baseHeaders)
298
- const storage = new StorageClient(`${config.url}/storage/v1`, baseHeaders)
352
+ const auth = new AuthClient(`${config.url}/auth/v1`, baseHeaders, {
353
+ initialSession: config.initialSession,
354
+ persistSession: config.auth?.persistSession,
355
+ storageKey: config.auth?.storageKey,
356
+ cookiePrefix: config.auth?.cookiePrefix,
357
+ })
358
+ // Storage admin operations (listBuckets, createBucket, etc.) require service_role.
359
+ // When a service role key is provided (developer tools like Studio), use it for
360
+ // storage so admin calls are authorised; otherwise fall back to the anon headers.
361
+ const storageHeaders: Record<string, string> = config.serviceRoleKey
362
+ ? {
363
+ apikey: config.serviceRoleKey,
364
+ Authorization: `Bearer ${config.serviceRoleKey}`,
365
+ "Content-Type": "application/json",
366
+ }
367
+ : baseHeaders
368
+ const storage = new StorageClient(`${config.url}/storage/v1`, storageHeaders)
299
369
  const realtime = new RealtimeClient(`${config.url}/realtime/v1`, baseHeaders)
300
370
  const functions = new FunctionsClient(config.url, baseHeaders, doFetch)
301
371
 
302
372
  const getAuthHeaders = (): Record<string, string> => {
303
- // The auth headers are merged dynamically so callers pick up fresh JWTs
304
- // after sign-in. Internal reference to auth._setSession isn't exposed;
305
- // instead we read currentSession via a closure.
373
+ // Studio and other admin tools pass serviceRoleKey — use it for table/RPC/GraphQL
374
+ // so supatype_admin RLS policies and bypass rules apply (anon would fail).
375
+ if (config.serviceRoleKey) {
376
+ return {
377
+ apikey: config.serviceRoleKey,
378
+ Authorization: `Bearer ${config.serviceRoleKey}`,
379
+ "Content-Type": "application/json",
380
+ }
381
+ }
382
+ const token = auth.currentAccessToken
383
+ if (token !== null) {
384
+ const role = jwtRole(token)
385
+ // Guardrail: malformed sessions can carry a JWT with empty role, which
386
+ // PostgREST rejects ("role \"\" does not exist"). Fall back to anon.
387
+ if (role !== null && role.trim().length > 0) {
388
+ return { ...baseHeaders, Authorization: `Bearer ${token}` }
389
+ }
390
+ }
306
391
  return baseHeaders
307
392
  }
308
393
 
309
394
  return {
395
+ url: config.url,
396
+ serviceRoleKey: config.serviceRoleKey,
397
+
310
398
  from<TTable extends keyof TDatabase["public"]["Tables"] & string>(
311
399
  table: TTable,
312
400
  ): TableClient<TDatabase["public"]["Tables"][TTable]> {
@@ -349,13 +437,25 @@ export function createClient<TDatabase extends AnyDatabase = AnyDatabase>(
349
437
  try {
350
438
  res = await doFetch(`${config.url}/graphql/v1`, {
351
439
  method: "POST",
352
- headers: baseHeaders,
440
+ headers: getAuthHeaders(),
353
441
  body: JSON.stringify(body),
354
442
  })
355
443
  } catch (e) {
356
444
  return { data: null, error: { message: e instanceof Error ? e.message : "Network error" } }
357
445
  }
358
- const json = await res.json() as Record<string, unknown>
446
+ let json: Record<string, unknown>
447
+ try {
448
+ json = await res.json() as Record<string, unknown>
449
+ } catch {
450
+ return { data: null, error: { message: `GraphQL endpoint returned a non-JSON response (HTTP ${res.status} ${res.statusText})` } }
451
+ }
452
+ if (!res.ok) {
453
+ const message =
454
+ typeof json["message"] === "string" ? json["message"]
455
+ : typeof json["error"] === "string" ? json["error"]
456
+ : `GraphQL request failed (HTTP ${res.status})`
457
+ return { data: json["data"] ?? null, error: { message, status: res.status } }
458
+ }
359
459
  if (json["errors"] !== undefined) {
360
460
  const errors = json["errors"] as Array<{ message: string }>
361
461
  return { data: json["data"] ?? null, error: { message: (errors[0]?.message ?? "GraphQL error") } }
package/src/query.ts CHANGED
@@ -1,5 +1,27 @@
1
1
  import type { QueryResult, SupatypeError } from "./types.js"
2
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
+
3
25
  // ─── QueryBuilder ─────────────────────────────────────────────────────────────
4
26
 
5
27
  export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
@@ -78,6 +100,11 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
78
100
  return this
79
101
  }
80
102
 
103
+ not(column: string, op: string, value: unknown): this {
104
+ this.params.append(column, `not.${op}.${String(value)}`)
105
+ return this
106
+ }
107
+
81
108
  contains(column: string, value: unknown): this {
82
109
  this.params.append(column, `cs.${JSON.stringify(value)}`)
83
110
  return this
@@ -164,6 +191,15 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
164
191
 
165
192
  if (!res.ok) {
166
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
+ }
167
203
  return {
168
204
  data: null,
169
205
  error: {
@@ -227,6 +263,11 @@ export class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
227
263
  return this
228
264
  }
229
265
 
266
+ in(column: string, values: unknown[]): this {
267
+ this.params.append(column, `in.(${values.map(String).join(",")})`)
268
+ return this
269
+ }
270
+
230
271
  then<R1 = QueryResult<TRow[]>, R2 = never>(
231
272
  onfulfilled?: ((value: QueryResult<TRow[]>) => R1 | PromiseLike<R1>) | null | undefined,
232
273
  onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null | undefined,
@@ -254,6 +295,16 @@ export class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
254
295
 
255
296
  if (!res.ok) {
256
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
+ }
257
308
  return {
258
309
  data: null,
259
310
  error: {
package/src/storage.ts CHANGED
@@ -19,6 +19,16 @@ export interface TransformOptions {
19
19
  resize?: "cover" | "contain" | "fill" | "inside" | "outside" | undefined
20
20
  }
21
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
+
22
32
  export class StorageClient {
23
33
  private readonly url: string
24
34
  private readonly headers: Record<string, string>
@@ -31,6 +41,47 @@ export class StorageClient {
31
41
  from(bucket: string): BucketClient {
32
42
  return new BucketClient(this.url, bucket, this.headers)
33
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
+ }
34
85
  }
35
86
 
36
87
  export class BucketClient {
@@ -49,9 +100,10 @@ export class BucketClient {
49
100
  file: Blob | File | ArrayBuffer,
50
101
  options?: { contentType?: string | undefined; upsert?: boolean | undefined } | undefined,
51
102
  ): Promise<{ data: { path: string } | null; error: SupatypeError | null }> {
103
+ const inferredType = file instanceof File && file.type ? file.type : "application/octet-stream"
52
104
  const headers: Record<string, string> = {
53
105
  ...this.headers,
54
- "Content-Type": options?.contentType ?? "application/octet-stream",
106
+ "Content-Type": options?.contentType ?? inferredType,
55
107
  }
56
108
  if (options?.upsert === true) {
57
109
  headers["x-upsert"] = "true"
@@ -63,7 +115,7 @@ export class BucketClient {
63
115
  })
64
116
  if (!res.ok) {
65
117
  const err = await res.json().catch(() => ({ message: "Upload failed" })) as Record<string, unknown>
66
- return { data: null, error: { message: String(err["message"] ?? "Upload failed"), status: res.status } }
118
+ return { data: null, error: { message: String(err["message"] ?? err["error"] ?? "Upload failed"), status: res.status } }
67
119
  }
68
120
  return { data: { path }, error: null }
69
121
  }
@@ -76,7 +128,7 @@ export class BucketClient {
76
128
  const res = await fetch(url, { headers: this.headers })
77
129
  if (!res.ok) {
78
130
  const err = await res.json().catch(() => ({ message: "Download failed" })) as Record<string, unknown>
79
- return { data: null, error: { message: String(err["message"] ?? "Download failed"), status: res.status } }
131
+ return { data: null, error: { message: String(err["message"] ?? err["error"] ?? "Download failed"), status: res.status } }
80
132
  }
81
133
  const blob = await res.blob()
82
134
  return { data: blob, error: null }
@@ -101,7 +153,7 @@ export class BucketClient {
101
153
  })
102
154
  if (!res.ok) {
103
155
  const err = await res.json().catch(() => ({ message: "Failed to create signed URL" })) as Record<string, unknown>
104
- return { data: null, error: { message: String(err["message"] ?? "Failed to create signed URL"), status: res.status } }
156
+ return { data: null, error: { message: String(err["message"] ?? err["error"] ?? "Failed to create signed URL"), status: res.status } }
105
157
  }
106
158
  const json = await res.json() as { signedURL: string }
107
159
  return { data: { signedUrl: json.signedURL }, error: null }
@@ -131,7 +183,7 @@ export class BucketClient {
131
183
  })
132
184
  if (!res.ok) {
133
185
  const err = await res.json().catch(() => ({ message: "Delete failed" })) as Record<string, unknown>
134
- return { data: null, error: { message: String(err["message"] ?? "Delete failed"), status: res.status } }
186
+ return { data: null, error: { message: String(err["message"] ?? err["error"] ?? "Delete failed"), status: res.status } }
135
187
  }
136
188
  const json = await res.json() as StorageObject[]
137
189
  return { data: json, error: null }
@@ -153,7 +205,7 @@ export class BucketClient {
153
205
  })
154
206
  if (!res.ok) {
155
207
  const err = await res.json().catch(() => ({ message: "List failed" })) as Record<string, unknown>
156
- return { data: null, error: { message: String(err["message"] ?? "List failed"), status: res.status } }
208
+ return { data: null, error: { message: String(err["message"] ?? err["error"] ?? "List failed"), status: res.status } }
157
209
  }
158
210
  const json = await res.json() as StorageObject[]
159
211
  return { data: json, error: null }
package/src/types.ts CHANGED
@@ -26,6 +26,7 @@ export interface User {
26
26
  email?: string | undefined
27
27
  phone?: string | undefined
28
28
  role?: string | undefined
29
+ isAnonymous?: boolean | undefined
29
30
  appMetadata: Record<string, unknown>
30
31
  userMetadata: Record<string, unknown>
31
32
  identities?: UserIdentity[] | undefined
@@ -138,10 +139,71 @@ export interface RpcResult<TData> {
138
139
 
139
140
  export interface TableDef {
140
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
+ */
141
146
  Insert: Record<string, unknown>
142
147
  Update: Record<string, unknown>
143
148
  }
144
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
+
145
207
  /**
146
208
  * Describes the shape of a Postgres function for typed `.rpc()` calls.
147
209
  * Generated by the Supatype engine from detected Postgres functions.
@@ -161,15 +223,27 @@ export interface AnyDatabase {
161
223
  // ─── Client config ────────────────────────────────────────────────────────────
162
224
 
163
225
  export interface SupatypeClientConfig {
164
- /** Base URL of the Supatype gateway (e.g. http://localhost:8000) */
226
+ /** Base URL of the Supatype gateway (e.g. http://localhost:18473) */
165
227
  url: string
166
228
  /** Anon JWT key */
167
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
168
236
  auth?: {
169
237
  /** Persist session across page reloads (browser only). Default: true */
170
238
  persistSession?: boolean | undefined
171
239
  /** localStorage key to use for session storage. Default: "supatype.auth.session" */
172
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
173
247
  } | undefined
174
248
  /**
175
249
  * Disable automatic retry for transient errors.
@@ -181,4 +255,10 @@ export interface SupatypeClientConfig {
181
255
  * Applied to every HTTP request made by the client.
182
256
  */
183
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
184
264
  }
@@ -89,6 +89,75 @@ describe("AuthClient.signUp()", () => {
89
89
  })
90
90
  })
91
91
 
92
+ describe("AuthClient.signInAnonymously()", () => {
93
+ beforeEach(() => vi.restoreAllMocks())
94
+
95
+ const ANON_USER = {
96
+ ...RAW_USER,
97
+ email: undefined,
98
+ is_anonymous: true,
99
+ }
100
+
101
+ const ANON_TOKEN_RESPONSE = {
102
+ ...TOKEN_RESPONSE,
103
+ user: ANON_USER,
104
+ }
105
+
106
+ it("sends POST to /signup with no email or password", async () => {
107
+ const fetch = mockFetch(ANON_TOKEN_RESPONSE)
108
+ vi.stubGlobal("fetch", fetch)
109
+
110
+ const { error } = await freshClient().signInAnonymously()
111
+
112
+ expect(error).toBeNull()
113
+ expect(fetch).toHaveBeenCalledWith(
114
+ `${GOTRUE_URL}/signup`,
115
+ expect.objectContaining({ method: "POST" }),
116
+ )
117
+ const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
118
+ const body = JSON.parse(opts.body as string) as Record<string, unknown>
119
+ expect(body["email"]).toBeUndefined()
120
+ expect(body["password"]).toBeUndefined()
121
+ })
122
+
123
+ it("includes optional user metadata and captcha token", async () => {
124
+ const fetch = mockFetch(ANON_TOKEN_RESPONSE)
125
+ vi.stubGlobal("fetch", fetch)
126
+
127
+ await freshClient().signInAnonymously({
128
+ options: { data: { guest: true }, captchaToken: "captcha-123" },
129
+ })
130
+
131
+ const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
132
+ const body = JSON.parse(opts.body as string) as Record<string, unknown>
133
+ expect(body["data"]).toEqual({ guest: true })
134
+ expect(body["gotrue_meta_security"]).toEqual({ captcha_token: "captcha-123" })
135
+ })
136
+
137
+ it("parses isAnonymous from response", async () => {
138
+ vi.stubGlobal("fetch", mockFetch(ANON_TOKEN_RESPONSE))
139
+
140
+ const { data, error } = await freshClient().signInAnonymously()
141
+
142
+ expect(error).toBeNull()
143
+ expect(data.user?.isAnonymous).toBe(true)
144
+ expect(data.session?.accessToken).toBe("access-token-123")
145
+ })
146
+
147
+ it("returns error when anonymous sign-ins are disabled", async () => {
148
+ vi.stubGlobal(
149
+ "fetch",
150
+ mockFetch({ msg: "Anonymous sign-ins are disabled" }, false, 422),
151
+ )
152
+
153
+ const { data, error } = await freshClient().signInAnonymously()
154
+
155
+ expect(data.session).toBeNull()
156
+ expect(error?.message).toBe("Anonymous sign-ins are disabled")
157
+ expect(error?.status).toBe(422)
158
+ })
159
+ })
160
+
92
161
  describe("AuthClient.signInWithPassword()", () => {
93
162
  beforeEach(() => vi.restoreAllMocks())
94
163
 
@@ -3,7 +3,7 @@ import { QueryBuilder, MutationBuilder } from "../src/query.js"
3
3
 
4
4
  // ─── Helpers ─────────────────────────────────────────────────────────────────
5
5
 
6
- const BASE = "http://localhost:8000"
6
+ const BASE = "http://localhost:18473"
7
7
  const PATH = "/rest/v1/posts"
8
8
  const HEADERS: Record<string, string> = { apikey: "anon-key", "Content-Type": "application/json" }
9
9
 
@@ -9,7 +9,7 @@ import { StorageClient } from "../src/storage.js"
9
9
 
10
10
  // ─── Helpers ─────────────────────────────────────────────────────────────────
11
11
 
12
- const STORAGE_URL = "http://localhost:8000/storage/v1"
12
+ const STORAGE_URL = "http://localhost:18473/storage/v1"
13
13
  const HEADERS = { apikey: "test-anon-key", Authorization: "Bearer test-token" }
14
14
 
15
15
  function freshClient(): StorageClient {
@@ -9,7 +9,7 @@ import { StorageClient } from "../src/storage.js"
9
9
 
10
10
  // ─── Helpers ─────────────────────────────────────────────────────────────────
11
11
 
12
- const STORAGE_URL = "http://localhost:8000/storage/v1"
12
+ const STORAGE_URL = "http://localhost:18473/storage/v1"
13
13
  const HEADERS = { apikey: "test-anon-key", Authorization: "Bearer test-token" }
14
14
 
15
15
  function freshClient(): StorageClient {
@@ -37,11 +37,25 @@ interface TestDB {
37
37
  }
38
38
  }
39
39
 
40
- const client = createClient<TestDB>({ url: "http://localhost:8000", anonKey: "test" })
40
+ const client = createClient<TestDB>({ url: "http://localhost:18473", anonKey: "test" })
41
+
42
+ declare module "../src/types.js" {
43
+ interface SupatypeModels {
44
+ posts: { Row: Post; Insert: PostInsert; Update: Partial<PostInsert> }
45
+ comments: { Row: Comment; Insert: Omit<Comment, "id">; Update: Partial<Comment> }
46
+ }
47
+ }
48
+
49
+ const augmentedClient = createClient({ url: "http://localhost:18473", anonKey: "test" })
41
50
 
42
51
  // ─── from() ───────────────────────────────────────────────────────────────────
43
52
 
44
53
  describe("createClient type inference", () => {
54
+ it("from() infers augmented table types without call-site generics", () => {
55
+ const q = augmentedClient.from("posts").select()
56
+ expectTypeOf(q).toMatchTypeOf<QueryBuilder<Post>>()
57
+ })
58
+
45
59
  it("from() .select() returns QueryBuilder typed to the table's Row", () => {
46
60
  const q = client.from("posts").select()
47
61
  expectTypeOf(q).toMatchTypeOf<QueryBuilder<Post>>()