@supatype/client 0.1.0-alpha.6

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 +7 -0
  3. package/.turbo/turbo-typecheck.log +4 -0
  4. package/dist/auth.d.ts +243 -0
  5. package/dist/auth.d.ts.map +1 -0
  6. package/dist/auth.js +560 -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 +137 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +225 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/query.d.ts +53 -0
  25. package/dist/query.d.ts.map +1 -0
  26. package/dist/query.js +216 -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 +79 -0
  41. package/dist/storage.d.ts.map +1 -0
  42. package/dist/storage.js +130 -0
  43. package/dist/storage.js.map +1 -0
  44. package/dist/types.d.ts +141 -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 +713 -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 +418 -0
  54. package/src/query.ts +280 -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 +182 -0
  59. package/src/types.ts +184 -0
  60. package/tests/auth.test.ts +282 -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 +123 -0
  70. package/tsconfig.json +11 -0
  71. package/tsconfig.tsbuildinfo +1 -0
package/src/retry.ts ADDED
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Retry configuration module.
3
+ *
4
+ * Re-exports the core fetchWithRetry and provides a factory that binds
5
+ * client-level retry/timeout options so callers don't repeat them.
6
+ */
7
+
8
+ import { fetchWithRetry, type FetchOptions } from "./fetch-with-retry.js"
9
+
10
+ export type { FetchOptions } from "./fetch-with-retry.js"
11
+
12
+ export interface RetryConfig {
13
+ /** Disable automatic retry. When false, no retries are attempted. */
14
+ retry?: boolean | undefined
15
+ /** Request timeout in milliseconds. Default: 30000. */
16
+ timeout?: number | undefined
17
+ }
18
+
19
+ /**
20
+ * Create a fetch function pre-configured with client-level retry/timeout.
21
+ *
22
+ * ```ts
23
+ * const doFetch = createRetryFetch({ retry: true, timeout: 10000 })
24
+ * const res = await doFetch('https://api.example.com/data', { method: 'GET' })
25
+ * ```
26
+ */
27
+ export function createRetryFetch(config: RetryConfig) {
28
+ return (url: string, init?: RequestInit & Partial<FetchOptions>): Promise<Response> => {
29
+ return fetchWithRetry(url, {
30
+ ...init,
31
+ retry: init?.retry ?? config.retry,
32
+ timeout: init?.timeout ?? config.timeout,
33
+ })
34
+ }
35
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Serverless connection documentation — Gap Appendices task 84
3
+ *
4
+ * Code-accessible documentation for connection modes.
5
+ * Rendered in Studio's getting-started view and available to CLI help output.
6
+ */
7
+
8
+ export interface ConnectionModeDoc {
9
+ /** Short label for this mode. */
10
+ label: string
11
+ /** When to use this mode (environment/context). */
12
+ recommended: string
13
+ /** Whether this mode is safe in serverless contexts. */
14
+ serverlessSafe: boolean
15
+ /** How it handles connection pooling. */
16
+ pooling: string
17
+ /** Brief description. */
18
+ description: string
19
+ /** Example code snippet (TypeScript). */
20
+ example: string
21
+ }
22
+
23
+ /**
24
+ * Documents the two primary ways to connect to a Supatype project,
25
+ * with clear guidance on serverless vs. long-lived server environments.
26
+ */
27
+ export const CONNECTION_MODES: readonly ConnectionModeDoc[] = [
28
+ {
29
+ label: "Supatype SDK (via PostgREST)",
30
+ recommended: "Serverless environments: Next.js API routes, Vercel Edge Functions, AWS Lambda, Cloudflare Workers, Deno Deploy",
31
+ serverlessSafe: true,
32
+ pooling: "PostgREST maintains a persistent connection pool to Postgres. Each SDK request is an HTTP call that reuses an existing database connection from the pool.",
33
+ description:
34
+ "Use the Supatype SDK in serverless environments. PostgREST handles connection pooling for you. " +
35
+ "Each serverless invocation makes an HTTP request to PostgREST, which maps it to a pre-established " +
36
+ "database connection. This avoids the connection-per-invocation problem entirely.",
37
+ example: [
38
+ 'import { createClient } from "@supatype/client"',
39
+ "",
40
+ "const client = createClient(process.env.SUPATYPE_URL!, process.env.SUPATYPE_ANON_KEY!)",
41
+ "",
42
+ "// Safe in serverless — each call is an HTTP request, not a new DB connection",
43
+ "const users = await client.from(\"users\").select()",
44
+ ].join("\n"),
45
+ },
46
+ {
47
+ label: "Direct database connection",
48
+ recommended: "Long-lived servers: Express/Fastify/Hono on a VM or container, background workers, migration scripts, CLI tools",
49
+ serverlessSafe: false,
50
+ pooling: "Each new connection opens a TCP socket to Postgres. In serverless, each invocation creates a new connection that is never reused, exhausting the connection pool within seconds under load.",
51
+ description:
52
+ "Do NOT use direct database connections from serverless environments. " +
53
+ "Each invocation opens a new connection, which will exhaust your connection pool " +
54
+ "within seconds under load. Direct connections are only appropriate for long-lived " +
55
+ "server processes that open a connection once and reuse it across many requests.",
56
+ example: [
57
+ '// ONLY for long-lived servers — NOT for serverless',
58
+ 'import pg from "pg"',
59
+ "",
60
+ "const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL })",
61
+ "",
62
+ "// Connection is reused across requests in a long-lived process",
63
+ "const result = await pool.query(\"SELECT * FROM users\")",
64
+ ].join("\n"),
65
+ },
66
+ ] as const
67
+
68
+ /**
69
+ * A short, actionable warning suitable for display in Studio banners,
70
+ * CLI output, and getting-started guides.
71
+ */
72
+ export const SERVERLESS_CONNECTION_WARNING =
73
+ "Use the Supatype SDK (via PostgREST) in serverless environments (Next.js API routes, " +
74
+ "Vercel Edge Functions, AWS Lambda). PostgREST handles connection pooling for you. " +
75
+ "Do NOT use direct database connections from serverless — each invocation opens a new " +
76
+ "connection, which will exhaust your connection pool within seconds under load."
77
+
78
+ /**
79
+ * Structured FAQ entries for the connection modes documentation.
80
+ */
81
+ export const CONNECTION_FAQ: ReadonlyArray<{ question: string; answer: string }> = [
82
+ {
83
+ question: "Can I use Prisma/Drizzle/Knex in serverless?",
84
+ answer:
85
+ "These ORMs require a direct database connection. In serverless, use the Supatype SDK instead. " +
86
+ "If you must use an ORM, deploy it on a long-lived server (container, VM) or use a connection " +
87
+ "pooler like PgBouncer in transaction mode.",
88
+ },
89
+ {
90
+ question: "What about Edge Functions?",
91
+ answer:
92
+ "Edge Functions (Vercel Edge, Cloudflare Workers) are serverless. Use the Supatype SDK. " +
93
+ "Direct TCP connections are not available in most edge runtimes anyway.",
94
+ },
95
+ {
96
+ question: "How many connections does PostgREST use?",
97
+ answer:
98
+ "PostgREST maintains a configurable pool (default: 10 connections). All incoming HTTP requests " +
99
+ "share this pool, so even thousands of concurrent SDK requests only use 10 database connections.",
100
+ },
101
+ {
102
+ question: "When should I use a direct connection?",
103
+ answer:
104
+ "Use direct connections for: migration scripts, long-lived API servers (Express, Fastify), " +
105
+ "background job processors, and CLI tooling. These processes start once and reuse connections.",
106
+ },
107
+ ]
package/src/storage.ts ADDED
@@ -0,0 +1,182 @@
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 class StorageClient {
23
+ private readonly url: string
24
+ private readonly headers: Record<string, string>
25
+
26
+ constructor(url: string, headers: Record<string, string>) {
27
+ this.url = url
28
+ this.headers = headers
29
+ }
30
+
31
+ from(bucket: string): BucketClient {
32
+ return new BucketClient(this.url, bucket, this.headers)
33
+ }
34
+ }
35
+
36
+ export class BucketClient {
37
+ private readonly url: string
38
+ private readonly bucket: string
39
+ private readonly headers: Record<string, string>
40
+
41
+ constructor(url: string, bucket: string, headers: Record<string, string>) {
42
+ this.url = url
43
+ this.bucket = bucket
44
+ this.headers = headers
45
+ }
46
+
47
+ async upload(
48
+ path: string,
49
+ file: Blob | File | ArrayBuffer,
50
+ options?: { contentType?: string | undefined; upsert?: boolean | undefined } | undefined,
51
+ ): Promise<{ data: { path: string } | null; error: SupatypeError | null }> {
52
+ const headers: Record<string, string> = {
53
+ ...this.headers,
54
+ "Content-Type": options?.contentType ?? "application/octet-stream",
55
+ }
56
+ if (options?.upsert === true) {
57
+ headers["x-upsert"] = "true"
58
+ }
59
+ const res = await fetch(`${this.url}/object/${this.bucket}/${path}`, {
60
+ method: "POST",
61
+ headers,
62
+ body: file,
63
+ })
64
+ if (!res.ok) {
65
+ 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 } }
67
+ }
68
+ return { data: { path }, error: null }
69
+ }
70
+
71
+ async download(
72
+ path: string,
73
+ options?: { transform?: TransformOptions | undefined } | undefined,
74
+ ): Promise<{ data: Blob | null; error: SupatypeError | null }> {
75
+ const url = this.buildObjectUrl("authenticated", path, options?.transform)
76
+ const res = await fetch(url, { headers: this.headers })
77
+ if (!res.ok) {
78
+ 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 } }
80
+ }
81
+ const blob = await res.blob()
82
+ return { data: blob, error: null }
83
+ }
84
+
85
+ getPublicUrl(
86
+ path: string,
87
+ options?: { transform?: TransformOptions | undefined } | undefined,
88
+ ): { data: { publicUrl: string } } {
89
+ const publicUrl = this.buildObjectUrl("public", path, options?.transform)
90
+ return { data: { publicUrl } }
91
+ }
92
+
93
+ async createSignedUrl(
94
+ path: string,
95
+ expiresIn: number,
96
+ ): Promise<{ data: { signedUrl: string } | null; error: SupatypeError | null }> {
97
+ const res = await fetch(`${this.url}/object/sign/${this.bucket}/${path}`, {
98
+ method: "POST",
99
+ headers: { ...this.headers, "Content-Type": "application/json" },
100
+ body: JSON.stringify({ expiresIn }),
101
+ })
102
+ if (!res.ok) {
103
+ 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 } }
105
+ }
106
+ const json = await res.json() as { signedURL: string }
107
+ return { data: { signedUrl: json.signedURL }, error: null }
108
+ }
109
+
110
+ async createSignedUrls(
111
+ paths: string[],
112
+ expiresIn: number,
113
+ ): Promise<{ data: { path: string; signedUrl: string; error: string | null }[] | null; error: SupatypeError | null }> {
114
+ const results = await Promise.all(
115
+ paths.map(async (path) => {
116
+ const result = await this.createSignedUrl(path, expiresIn)
117
+ if (result.error) {
118
+ return { path, signedUrl: "", error: result.error.message }
119
+ }
120
+ return { path, signedUrl: result.data!.signedUrl, error: null }
121
+ }),
122
+ )
123
+ return { data: results, error: null }
124
+ }
125
+
126
+ async remove(paths: string[]): Promise<{ data: StorageObject[] | null; error: SupatypeError | null }> {
127
+ const res = await fetch(`${this.url}/object/${this.bucket}`, {
128
+ method: "DELETE",
129
+ headers: { ...this.headers, "Content-Type": "application/json" },
130
+ body: JSON.stringify({ prefixes: paths }),
131
+ })
132
+ if (!res.ok) {
133
+ 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 } }
135
+ }
136
+ const json = await res.json() as StorageObject[]
137
+ return { data: json, error: null }
138
+ }
139
+
140
+ async list(
141
+ prefix?: string | undefined,
142
+ options?: { limit?: number | undefined; offset?: number | undefined } | undefined,
143
+ ): Promise<{ data: StorageObject[] | null; error: SupatypeError | null }> {
144
+ const body: Record<string, unknown> = {
145
+ ...(prefix !== undefined && { prefix }),
146
+ ...(options?.limit !== undefined && { limit: options.limit }),
147
+ ...(options?.offset !== undefined && { offset: options.offset }),
148
+ }
149
+ const res = await fetch(`${this.url}/object/list/${this.bucket}`, {
150
+ method: "POST",
151
+ headers: { ...this.headers, "Content-Type": "application/json" },
152
+ body: JSON.stringify(body),
153
+ })
154
+ if (!res.ok) {
155
+ 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 } }
157
+ }
158
+ const json = await res.json() as StorageObject[]
159
+ return { data: json, error: null }
160
+ }
161
+
162
+ // ─── Internal ───────────────────────────────────────────────────────────────
163
+
164
+ private buildObjectUrl(
165
+ access: "public" | "authenticated",
166
+ path: string,
167
+ transform?: TransformOptions | undefined,
168
+ ): string {
169
+ let url = `${this.url}/object/${access}/${this.bucket}/${path}`
170
+ if (transform) {
171
+ const params = new URLSearchParams()
172
+ if (transform.width !== undefined) params.set("width", String(transform.width))
173
+ if (transform.height !== undefined) params.set("height", String(transform.height))
174
+ if (transform.format !== undefined) params.set("format", transform.format)
175
+ if (transform.quality !== undefined) params.set("quality", String(transform.quality))
176
+ if (transform.resize !== undefined) params.set("resize", transform.resize)
177
+ const qs = params.toString()
178
+ if (qs) url += `?${qs}`
179
+ }
180
+ return url
181
+ }
182
+ }
package/src/types.ts ADDED
@@ -0,0 +1,184 @@
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
+ appMetadata: Record<string, unknown>
30
+ userMetadata: Record<string, unknown>
31
+ identities?: UserIdentity[] | undefined
32
+ factors?: Factor[] | undefined
33
+ createdAt: string
34
+ updatedAt: string
35
+ }
36
+
37
+ export interface Session {
38
+ accessToken: string
39
+ tokenType: string
40
+ expiresIn: number
41
+ expiresAt?: number | undefined
42
+ refreshToken: string
43
+ user: User
44
+ }
45
+
46
+ export type AuthChangeEvent =
47
+ | "SIGNED_IN"
48
+ | "SIGNED_OUT"
49
+ | "TOKEN_REFRESHED"
50
+ | "USER_UPDATED"
51
+ | "PASSWORD_RECOVERY"
52
+ | "MFA_CHALLENGE_VERIFIED"
53
+
54
+ // ─── MFA types ──────────────────────────────────────────────────────────────
55
+
56
+ export interface AuthMFAEnrollResponse {
57
+ /** The MFA factor ID */
58
+ id: string
59
+ /** Factor type: totp, phone, or webauthn */
60
+ type: string
61
+ /** Friendly name for the factor */
62
+ friendlyName: string
63
+ /** TOTP-specific data (only present for totp factor type) */
64
+ totp?: {
65
+ /** QR code SVG string */
66
+ qrCode: string
67
+ /** TOTP secret */
68
+ secret: string
69
+ /** TOTP URI for manual entry */
70
+ uri: string
71
+ } | undefined
72
+ /** Phone number (only present for phone factor type) */
73
+ phone?: string | undefined
74
+ }
75
+
76
+ export interface AuthMFAChallengeResponse {
77
+ /** The challenge ID */
78
+ id: string
79
+ /** Factor type */
80
+ type: string
81
+ /** Challenge expiry timestamp (Unix epoch seconds) */
82
+ expiresAt: number
83
+ }
84
+
85
+ export interface AuthMFAVerifyResponse {
86
+ /** Access token */
87
+ accessToken: string
88
+ tokenType: string
89
+ expiresIn: number
90
+ expiresAt?: number | undefined
91
+ refreshToken: string
92
+ user: User
93
+ }
94
+
95
+ export interface AuthMFAListFactorsResponse {
96
+ /** All factors including unverified */
97
+ all: Factor[]
98
+ /** Only verified TOTP factors */
99
+ totp: Factor[]
100
+ /** Only verified phone factors */
101
+ phone: Factor[]
102
+ }
103
+
104
+ export type OtpType =
105
+ | "signup"
106
+ | "magiclink"
107
+ | "recovery"
108
+ | "invite"
109
+ | "email_change"
110
+ | "sms"
111
+ | "phone_change"
112
+ | "email"
113
+
114
+ // ─── Error type ───────────────────────────────────────────────────────────────
115
+
116
+ export interface SupatypeError {
117
+ message: string
118
+ status?: number | undefined
119
+ code?: string | undefined
120
+ }
121
+
122
+ // ─── Query result ─────────────────────────────────────────────────────────────
123
+
124
+ export interface QueryResult<TData> {
125
+ data: TData | null
126
+ error: SupatypeError | null
127
+ count: number | null
128
+ }
129
+
130
+ // ─── RPC result ──────────────────────────────────────────────────────────────
131
+
132
+ export interface RpcResult<TData> {
133
+ data: TData | null
134
+ error: SupatypeError | null
135
+ }
136
+
137
+ // ─── Database generic ─────────────────────────────────────────────────────────
138
+
139
+ export interface TableDef {
140
+ Row: Record<string, unknown>
141
+ Insert: Record<string, unknown>
142
+ Update: Record<string, unknown>
143
+ }
144
+
145
+ /**
146
+ * Describes the shape of a Postgres function for typed `.rpc()` calls.
147
+ * Generated by the Supatype engine from detected Postgres functions.
148
+ */
149
+ export interface FunctionDef {
150
+ Args: Record<string, unknown>
151
+ Returns: unknown
152
+ }
153
+
154
+ export interface AnyDatabase {
155
+ public: {
156
+ Tables: Record<string, TableDef>
157
+ Functions?: Record<string, FunctionDef> | undefined
158
+ }
159
+ }
160
+
161
+ // ─── Client config ────────────────────────────────────────────────────────────
162
+
163
+ export interface SupatypeClientConfig {
164
+ /** Base URL of the Supatype gateway (e.g. http://localhost:8000) */
165
+ url: string
166
+ /** Anon JWT key */
167
+ anonKey: string
168
+ auth?: {
169
+ /** Persist session across page reloads (browser only). Default: true */
170
+ persistSession?: boolean | undefined
171
+ /** localStorage key to use for session storage. Default: "supatype.auth.session" */
172
+ storageKey?: string | undefined
173
+ } | undefined
174
+ /**
175
+ * Disable automatic retry for transient errors.
176
+ * Default: true (retries enabled).
177
+ */
178
+ retry?: boolean | undefined
179
+ /**
180
+ * Request timeout in milliseconds. Default: 30000 (30 seconds).
181
+ * Applied to every HTTP request made by the client.
182
+ */
183
+ timeout?: number | undefined
184
+ }