@supatype/client 0.3.0 → 0.3.2

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 (74) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +28 -21
  3. package/.turbo/turbo-typecheck.log +2 -2
  4. package/dist/auth.d.ts +1 -1
  5. package/dist/auth.d.ts.map +1 -1
  6. package/dist/exact-response.d.ts +26 -0
  7. package/dist/exact-response.d.ts.map +1 -0
  8. package/dist/exact-response.js +51 -0
  9. package/dist/exact-response.js.map +1 -0
  10. package/dist/exact-values.d.ts +50 -0
  11. package/dist/exact-values.d.ts.map +1 -0
  12. package/dist/exact-values.js +254 -0
  13. package/dist/exact-values.js.map +1 -0
  14. package/dist/field-kinds-registry.d.ts +46 -0
  15. package/dist/field-kinds-registry.d.ts.map +1 -0
  16. package/dist/field-kinds-registry.js +51 -0
  17. package/dist/field-kinds-registry.js.map +1 -0
  18. package/dist/identity.d.ts +29 -0
  19. package/dist/identity.d.ts.map +1 -0
  20. package/dist/identity.js +30 -0
  21. package/dist/identity.js.map +1 -0
  22. package/dist/index.d.ts +17 -1
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +29 -1
  25. package/dist/index.js.map +1 -1
  26. package/dist/query-cache.d.ts +1 -1
  27. package/dist/query-cache.d.ts.map +1 -1
  28. package/dist/query-cache.js +2 -8
  29. package/dist/query-cache.js.map +1 -1
  30. package/dist/query.d.ts +13 -1
  31. package/dist/query.d.ts.map +1 -1
  32. package/dist/query.js +36 -7
  33. package/dist/query.js.map +1 -1
  34. package/dist/realtime.d.ts +61 -3
  35. package/dist/realtime.d.ts.map +1 -1
  36. package/dist/realtime.js +181 -24
  37. package/dist/realtime.js.map +1 -1
  38. package/dist/storage.d.ts +12 -0
  39. package/dist/storage.d.ts.map +1 -1
  40. package/dist/storage.js +17 -1
  41. package/dist/storage.js.map +1 -1
  42. package/dist/types.d.ts +20 -0
  43. package/dist/types.d.ts.map +1 -1
  44. package/dist/types.js.map +1 -1
  45. package/package.json +2 -2
  46. package/src/auth.ts +1 -1
  47. package/src/exact-response.ts +76 -0
  48. package/src/exact-values.ts +281 -0
  49. package/src/field-kinds-registry.ts +80 -0
  50. package/src/identity.ts +43 -0
  51. package/src/index.ts +54 -1
  52. package/src/query-cache.ts +3 -10
  53. package/src/query.ts +41 -7
  54. package/src/realtime.ts +195 -27
  55. package/src/storage.ts +17 -1
  56. package/src/types.ts +28 -0
  57. package/tests/data-plane-auth.test.ts +6 -4
  58. package/tests/draft-profile.test.ts +3 -0
  59. package/tests/exact-response.test.ts +95 -0
  60. package/tests/exact-values.test.ts +171 -0
  61. package/tests/field-kinds-registry.test.ts +80 -0
  62. package/tests/fixtures/models.ts +55 -0
  63. package/tests/helpers/mock-websocket.ts +70 -0
  64. package/tests/identity-change.test.ts +120 -0
  65. package/tests/query-cache.test.ts +14 -8
  66. package/tests/query.test.ts +1 -0
  67. package/tests/realtime-exact-values.test.ts +161 -0
  68. package/tests/realtime-multi-tenant-integration.test.ts +5 -50
  69. package/tests/realtime-session-auth.test.ts +177 -0
  70. package/tests/signed-url-absolute.test.ts +84 -0
  71. package/tests/subscribe-frame.test.ts +102 -0
  72. package/tests/tsconfig.json +9 -0
  73. package/tests/types.test.ts +40 -32
  74. package/tsconfig.tsbuildinfo +1 -1
package/src/query.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import type { QueryCache, QueryCacheOptions, CacheStatus } from "./query-cache.js"
2
2
  import { buildCacheKey, defaultQueryCache } from "./query-cache.js"
3
3
  import type { MaskedField, QueryResult, SelectQueryOptions, SupatypeError } from "./types.js"
4
+ import { parseRowsExactly, tableFromPath } from "./exact-response.js"
5
+ import { stringifyWithBigInts } from "./exact-values.js"
4
6
 
5
7
  const DEBUG_AUTH =
6
8
  (typeof process !== "undefined" && process.env["NEXT_PUBLIC_SUPATYPE_DEBUG_AUTH"] === "1") ||
@@ -64,13 +66,29 @@ function withMeta<T>(
64
66
  /** Resolves auth (and other) headers at request time so token refresh can run first. */
65
67
  export type HeadersProvider = () => Promise<Record<string, string>>
66
68
 
67
- function asHeadersProvider(
69
+ export function asHeadersProvider(
68
70
  headers: Record<string, string> | HeadersProvider,
69
71
  ): HeadersProvider {
70
72
  if (typeof headers === "function") return headers
71
73
  return () => Promise.resolve(headers)
72
74
  }
73
75
 
76
+ /**
77
+ * The caller's own token out of a header set: the session's bearer, else the apikey.
78
+ *
79
+ * One home for a rule three places had implemented separately. The realtime socket had the
80
+ * precedence the other way round, which is how it came to authenticate as anon on every
81
+ * connection: `apikey` is always set, so it never reached the Authorization header.
82
+ *
83
+ * Header names are matched in both casings because `config.headers` is caller-supplied and
84
+ * lowercase is just as valid over the wire.
85
+ */
86
+ export function bearerToken(headers: Record<string, string>): string {
87
+ const authorization = headers["Authorization"] ?? headers["authorization"] ?? ""
88
+ if (authorization.startsWith("Bearer ")) return authorization.slice("Bearer ".length)
89
+ return headers["apikey"] ?? headers["Apikey"] ?? ""
90
+ }
91
+
74
92
  async function fetchWithOptional401Retry(
75
93
  url: string,
76
94
  init: RequestInit,
@@ -133,7 +151,7 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
133
151
  }
134
152
  }
135
153
 
136
- /** Enable GET caching. Use `{ server: true }` to cache the response on the server too. */
154
+ /** Enable GET caching. Use `{ server: true }` for Valkey-backed server cache. */
137
155
  cache(options: QueryCacheOptions): this {
138
156
  this.cacheOptions = options
139
157
  return this
@@ -395,8 +413,17 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
395
413
  )
396
414
  }
397
415
 
398
- const json = await res.json() as TRow[]
399
- const result: QueryResult<TRow[]> = { data: json, error: null, count }
416
+ // Read from the text rather than `res.json()`: a bigInt, decimal or money column is already
417
+ // ruined by the time `JSON.parse` returns, and the digits are only recoverable from the body.
418
+ const parsed = parseRowsExactly(await res.text(), tableFromPath(this.path))
419
+ if (!parsed.ok) {
420
+ return withMeta<TRow[]>(
421
+ { data: null, error: { message: parsed.message, status: res.status }, count: null },
422
+ { cacheStatus, maskedFields },
423
+ )
424
+ }
425
+
426
+ const result: QueryResult<TRow[]> = { data: parsed.value as TRow[], error: null, count }
400
427
 
401
428
  if (this.cacheOptions) {
402
429
  const cacheKey = buildCacheKey("GET", url, await resolveRequestHeaders(), {
@@ -514,7 +541,9 @@ export class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
514
541
  })
515
542
  const init: RequestInit = {
516
543
  method: this.method,
517
- ...(this.body !== undefined && { body: JSON.stringify(this.body) }),
544
+ // Not `JSON.stringify`: it throws on a bigint, so reading a row with a bigInt column and
545
+ // writing it back would fail now that the generated types declare one.
546
+ ...(this.body !== undefined && { body: stringifyWithBigInts(this.body) }),
518
547
  }
519
548
  let res: Response
520
549
  try {
@@ -559,8 +588,13 @@ export class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
559
588
  return { data: [], error: null, count: 0 }
560
589
  }
561
590
 
562
- const json = await res.json() as TRow | TRow[]
563
- const data = Array.isArray(json) ? json : [json]
591
+ // The returned representation of what was just written, so it needs the same care as a read.
592
+ const parsed = parseRowsExactly(await res.text(), tableFromPath(this.path))
593
+ if (!parsed.ok) {
594
+ return { data: null, error: { message: parsed.message, status: res.status }, count: null }
595
+ }
596
+
597
+ const data = Array.isArray(parsed.value) ? (parsed.value as TRow[]) : [parsed.value as TRow]
564
598
  return { data, error: null, count: data.length }
565
599
  }
566
600
  }
package/src/realtime.ts CHANGED
@@ -1,3 +1,6 @@
1
+ import { asHeadersProvider, bearerToken, type HeadersProvider } from "./query.js"
2
+ import { coerceExactKinds, type ExactFields } from "./exact-values.js"
3
+
1
4
  export type RealtimeEvent = "INSERT" | "UPDATE" | "DELETE" | "*"
2
5
 
3
6
  export interface RealtimePayload<TRow> {
@@ -50,6 +53,21 @@ export interface PresenceEntry {
50
53
  [key: string]: unknown
51
54
  }
52
55
 
56
+ /**
57
+ * Turn the exact columns of one record into the types the generated schema declares.
58
+ *
59
+ * Shared with the REST path rather than reimplemented: `coerceExactKinds` is what turns a bigint
60
+ * string into a native bigint and leaves a numeric as its exact string, so a row read over a
61
+ * subscription and the same row read over REST hold equal values.
62
+ */
63
+ function coerceRecord(
64
+ record: Record<string, unknown> | null,
65
+ exact: ExactFields,
66
+ ): Record<string, unknown> | null {
67
+ if (record === null) return null
68
+ return coerceExactKinds(record, exact) as Record<string, unknown>
69
+ }
70
+
53
71
  // ─── Server message types (subset matching @supatype/realtime) ───────────────
54
72
 
55
73
  interface ServerChangeMessage {
@@ -57,6 +75,13 @@ interface ServerChangeMessage {
57
75
  channel: string
58
76
  event: "INSERT" | "UPDATE" | "DELETE"
59
77
  payload: { old: Record<string, unknown> | null; new: Record<string, unknown> | null }
78
+ /**
79
+ * Columns the service carried as exact strings, and the kind each one is.
80
+ *
81
+ * The service reads them from the database's own declared types, so this is authoritative in a
82
+ * way the local registry is not: a project that never generated still gets the right value.
83
+ */
84
+ exactColumns?: ExactFields
60
85
  timestamp: string
61
86
  }
62
87
 
@@ -86,18 +111,100 @@ type ServerMessage = ServerChangeMessage | ServerPresenceMessage | ServerBroadca
86
111
 
87
112
  export class RealtimeClient {
88
113
  private readonly url: string
89
- private readonly headers: Record<string, string>
114
+ private readonly getHeaders: HeadersProvider
90
115
  private ws: WebSocket | null = null
91
116
  private channels = new Map<string, ChannelState>()
92
117
  private reconnectTimer: ReturnType<typeof setTimeout> | null = null
93
118
  private reconnectAttempts = 0
94
119
  private maxReconnectAttempts = 10
95
120
  private baseReconnectDelay = 1000
96
-
97
- constructor(url: string, headers: Record<string, string>) {
121
+ /** The token the live socket was opened with, so an auth change can tell whether it still holds. */
122
+ private currentToken: string | undefined
123
+ /**
124
+ * The connect in flight, used as its own identity.
125
+ *
126
+ * A counter was tried first and produced a socket that never came back: abandoning an attempt
127
+ * bumped the counter but left this field set, so the replacement connect returned at the
128
+ * one-at-a-time guard, and the abandoned attempt then bailed on the counter. Nothing was
129
+ * connected and nothing was scheduled. Clearing this field both abandons an attempt and unblocks
130
+ * the next one, so the two cannot disagree.
131
+ */
132
+ private attempt: Promise<void> | null = null
133
+
134
+ /**
135
+ * `auth` is either a headers provider or a fixed set of headers: the same pair `QueryBuilder` and
136
+ * `MutationBuilder` accept, normalised by the same helper.
137
+ *
138
+ * The provider is what `createClient` passes, and it is why this takes two shapes. A fixed set of
139
+ * headers is read once at construction, so a socket opened before anybody signed in stayed anon
140
+ * for the life of the page: on a table that is not anon-readable it reported SUBSCRIBED and then
141
+ * delivered nothing, which is indistinguishable from a quiet table.
142
+ */
143
+ constructor(url: string, auth: Record<string, string> | HeadersProvider) {
98
144
  // Convert http(s) URL to ws(s) URL
99
145
  this.url = url.replace(/^http/, "ws")
100
- this.headers = headers
146
+ this.getHeaders = asHeadersProvider(auth)
147
+ }
148
+
149
+ /** The token this socket should authenticate with, or undefined when there is none. */
150
+ private async resolveToken(): Promise<string | undefined> {
151
+ const token = bearerToken(await this.getHeaders())
152
+ return token === "" ? undefined : token
153
+ }
154
+
155
+ /**
156
+ * Re-open the socket if the token it was opened with is no longer the current one.
157
+ *
158
+ * `createClient` calls this on every auth change. Without it the token preference above would
159
+ * still not be enough: every binding subscribes on mount, which is before the user has signed in,
160
+ * so the socket that matters is always one that was opened while signed out.
161
+ */
162
+ async reauthenticate(): Promise<void> {
163
+ if (this.ws === null && this.attempt === null) return
164
+ let token: string | undefined
165
+ try {
166
+ token = await this.resolveToken()
167
+ } catch {
168
+ return
169
+ }
170
+ if (token === this.currentToken) return
171
+ // Passed on rather than resolved a second time, so the socket opens with the token that
172
+ // justified opening it. Resolving twice left `currentToken` describing a token nobody checked.
173
+ this.cycleConnection(token)
174
+ }
175
+
176
+ /** Abandon the current socket and immediately open a replacement, keeping every channel. */
177
+ private cycleConnection(token: string | undefined): void {
178
+ this.abandonSocket("reauthenticating")
179
+ for (const state of this.channels.values()) {
180
+ state.subscribed = false
181
+ }
182
+ this.ensureConnection(token)
183
+ }
184
+
185
+ /**
186
+ * Drop the socket and any connect in flight, without deciding what happens next.
187
+ *
188
+ * Handlers are detached before closing, because `onclose` schedules a backoff reconnect that
189
+ * would otherwise race whatever the caller does instead.
190
+ */
191
+ private abandonSocket(reason: string): void {
192
+ this.attempt = null
193
+ if (this.reconnectTimer !== null) {
194
+ clearTimeout(this.reconnectTimer)
195
+ this.reconnectTimer = null
196
+ }
197
+ const old = this.ws
198
+ this.ws = null
199
+ this.currentToken = undefined
200
+ if (old !== null) {
201
+ old.onopen = null
202
+ old.onmessage = null
203
+ old.onclose = null
204
+ old.onerror = null
205
+ old.close(1000, reason)
206
+ }
207
+ this.reconnectAttempts = 0
101
208
  }
102
209
 
103
210
  channel<TRow = Record<string, unknown>>(name: string): ChannelSubscription<TRow> {
@@ -184,17 +291,16 @@ export class RealtimeClient {
184
291
  }
185
292
  }
186
293
 
187
- /** Disconnect the WebSocket entirely. */
294
+ /**
295
+ * Disconnect the WebSocket entirely.
296
+ *
297
+ * Shares `abandonSocket` with the re-authentication path, which is what stops an explicit
298
+ * disconnect from scheduling its own reconnect: the close handler is detached first. It also
299
+ * cancels a connect still waiting on its token, which would otherwise install a socket after the
300
+ * caller asked for none.
301
+ */
188
302
  disconnect(): void {
189
- if (this.reconnectTimer) {
190
- clearTimeout(this.reconnectTimer)
191
- this.reconnectTimer = null
192
- }
193
- if (this.ws) {
194
- this.ws.close(1000, "client disconnect")
195
- this.ws = null
196
- }
197
- this.reconnectAttempts = 0
303
+ this.abandonSocket("client disconnect")
198
304
  }
199
305
 
200
306
  // ─── Internal ──────────────────────────────────────────────────────────
@@ -215,18 +321,65 @@ export class RealtimeClient {
215
321
  return state
216
322
  }
217
323
 
218
- private ensureConnection(): void {
219
- if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)) {
220
- return
324
+ /** True while a socket exists and is usable. */
325
+ private isLive(): boolean {
326
+ if (this.ws === null) return false
327
+ return this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING
328
+ }
329
+
330
+ private ensureConnection(token?: string | undefined): void {
331
+ // One connect at a time: resolving the token is asynchronous, so two subscribes in the same
332
+ // tick would otherwise each open a socket and the second would orphan the first.
333
+ if (this.isLive() || this.attempt !== null) return
334
+
335
+ let attempt: Promise<void>
336
+ const isCurrent = (): boolean => this.attempt === attempt
337
+ // Started on a microtask so `this.attempt` is assigned before `openSocket` can ask whether it
338
+ // is still the current one. Called directly, the path that already has a token reaches that
339
+ // question with no await in front of it, compares against a handle nobody had stored yet, and
340
+ // abandons itself.
341
+ attempt = Promise.resolve().then(() => this.openSocket(isCurrent, token))
342
+ this.attempt = attempt
343
+ void attempt.finally(() => {
344
+ // Only if it is still ours. An attempt abandoned mid-flight must not clear the handle of the
345
+ // replacement that took its place.
346
+ if (this.attempt === attempt) this.attempt = null
347
+ })
348
+ }
349
+
350
+ /**
351
+ * Resolve a token, then open the socket with it.
352
+ *
353
+ * Split out of ensureConnection because the token is asynchronous: the session may have to be
354
+ * refreshed before it is known. `epoch` is read before the await so a socket abandoned in the
355
+ * meantime, by disconnect() or by reauthenticate(), does not install itself afterwards.
356
+ */
357
+ private async openSocket(
358
+ isCurrent: () => boolean,
359
+ known?: string | undefined,
360
+ ): Promise<void> {
361
+ let token = known
362
+ if (token === undefined) {
363
+ try {
364
+ token = await this.resolveToken()
365
+ } catch {
366
+ // A token that cannot be resolved is not a reason to open an unauthenticated socket: the
367
+ // server would accept it and deliver nothing, which reads as a broken table rather than a
368
+ // failed sign-in. Let the backoff try again.
369
+ if (isCurrent() && this.channels.size > 0) this.scheduleReconnect()
370
+ return
371
+ }
221
372
  }
373
+ // Abandoned while the token was resolving, by disconnect() or by a re-authentication that has
374
+ // already started its own attempt. Installing this socket now would orphan that one.
375
+ if (!isCurrent()) return
222
376
 
223
- // Build URL with token from apikey header
224
- const token = this.headers["apikey"] ?? this.headers["Authorization"]?.replace("Bearer ", "")
377
+ this.currentToken = token
225
378
  const wsUrl = token ? `${this.url}?token=${encodeURIComponent(token)}` : this.url
379
+ const ws = new WebSocket(wsUrl)
380
+ this.ws = ws
226
381
 
227
- this.ws = new WebSocket(wsUrl)
228
-
229
- this.ws.onopen = () => {
382
+ ws.onopen = () => {
230
383
  this.reconnectAttempts = 0
231
384
  // Re-subscribe all channels
232
385
  for (const state of this.channels.values()) {
@@ -236,7 +389,7 @@ export class RealtimeClient {
236
389
  }
237
390
  }
238
391
 
239
- this.ws.onmessage = (event) => {
392
+ ws.onmessage = (event) => {
240
393
  try {
241
394
  const msg = JSON.parse(String(event.data)) as ServerMessage
242
395
  this.handleServerMessage(msg)
@@ -245,7 +398,7 @@ export class RealtimeClient {
245
398
  }
246
399
  }
247
400
 
248
- this.ws.onclose = () => {
401
+ ws.onclose = () => {
249
402
  this.ws = null
250
403
  // Mark all channels as unsubscribed
251
404
  for (const state of this.channels.values()) {
@@ -257,7 +410,7 @@ export class RealtimeClient {
257
410
  }
258
411
  }
259
412
 
260
- this.ws.onerror = () => {
413
+ ws.onerror = () => {
261
414
  // onclose will fire after onerror
262
415
  }
263
416
  }
@@ -327,10 +480,14 @@ export class RealtimeClient {
327
480
  const schema = parts.length >= 2 ? parts[0]! : "public"
328
481
  const table = parts.length >= 2 ? parts[1]! : parts[0]!
329
482
 
483
+ // A bigint column arrives as a string and becomes a native bigint here, and a numeric stays
484
+ // the exact string `@supatype/types` declares for Decimal and Money. The same coercion the
485
+ // REST path uses, so a row read either way holds the same values.
486
+ const exact = msg.exactColumns ?? {}
330
487
  const payload: RealtimePayload<Record<string, unknown>> = {
331
488
  eventType: msg.event,
332
- new: msg.payload.new,
333
- old: msg.payload.old,
489
+ new: coerceRecord(msg.payload.new, exact),
490
+ old: coerceRecord(msg.payload.old, exact),
334
491
  schema,
335
492
  table,
336
493
  commitTimestamp: msg.timestamp,
@@ -379,10 +536,21 @@ export class RealtimeClient {
379
536
  }
380
537
  }
381
538
 
539
+ // `table` and `schema` travel with the subscription, rather than being inferred from the
540
+ // channel name at the other end.
541
+ //
542
+ // They were resolved here and then dropped, and the server falls back to reading the channel
543
+ // name as `schema:table`. So a subscription worked only when the channel happened to be named
544
+ // after its table, which is what `from(table).subscribe()` does. Anything else -- a channel
545
+ // called `lobby-chat` carrying `table: "chat_message"`, which is what `useSubscription` exists
546
+ // to let you write -- registered against a table no change can match. The socket reported
547
+ // SUBSCRIBED and delivered nothing, which is indistinguishable from a quiet table.
382
548
  this.sendMessage({
383
549
  type: "subscribe",
384
550
  channel: state.name,
385
551
  event: firstListener?.event ?? "*",
552
+ ...(firstListener?.table !== undefined && { table: firstListener.table }),
553
+ ...(firstListener?.schema !== undefined && { schema: firstListener.schema }),
386
554
  filter: Object.keys(filter).length > 0 ? filter : undefined,
387
555
  })
388
556
  }
package/src/storage.ts CHANGED
@@ -156,6 +156,22 @@ export class BucketClient {
156
156
  return { data: { publicUrl } }
157
157
  }
158
158
 
159
+ /**
160
+ * Resolve what the storage API returned against this client's base URL.
161
+ *
162
+ * `getPublicUrl` hands back something fetchable; this used to hand back the server's response
163
+ * verbatim, and the server answers with a path (`/object/sign/...`). So one of the two URL
164
+ * methods returned a URL and the other returned half of one, which fails at the caller as
165
+ * `TypeError: Failed to parse URL` rather than anywhere near here.
166
+ *
167
+ * Absolute answers are passed through untouched, so a deployment whose storage API returns a
168
+ * full URL (a CDN, a signed S3 link) is not mangled by being prefixed a second time.
169
+ */
170
+ private absoluteObjectUrl(value: string): string {
171
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) return value
172
+ return `${this.url.replace(/\/$/, "")}/${value.replace(/^\//, "")}`
173
+ }
174
+
159
175
  async createSignedUrl(
160
176
  path: string,
161
177
  expiresIn: number,
@@ -170,7 +186,7 @@ export class BucketClient {
170
186
  return { data: null, error: { message: String(err["message"] ?? err["error"] ?? "Failed to create signed URL"), status: res.status } }
171
187
  }
172
188
  const json = await res.json() as { signedURL: string }
173
- return { data: { signedUrl: json.signedURL }, error: null }
189
+ return { data: { signedUrl: this.absoluteObjectUrl(json.signedURL) }, error: null }
174
190
  }
175
191
 
176
192
  async createSignedUrls(
package/src/types.ts CHANGED
@@ -239,6 +239,34 @@ export type TableInsert<TTable extends keyof SupatypeModels & string> =
239
239
  : Record<string, unknown>
240
240
  : Record<string, unknown>
241
241
 
242
+ /**
243
+ * Row type for an augmented table name (from generated `supatype` output).
244
+ *
245
+ * Reach for this rather than indexing the generated database type by hand. Only `TableInsert`
246
+ * existed, so every consumer that wanted a row type wrote
247
+ * `Database["public"]["Tables"]["post"]["Row"]` instead, including our own examples in 23 places.
248
+ * That spelling names four internal structures to say one thing, and it breaks the moment any of
249
+ * them is renamed.
250
+ */
251
+ export type TableRow<TTable extends keyof SupatypeModels & string> =
252
+ [keyof SupatypeModels] extends [never]
253
+ ? Record<string, unknown>
254
+ : TTable extends keyof SupatypeModels
255
+ ? SupatypeModels[TTable] extends { Row: infer R }
256
+ ? R
257
+ : Record<string, unknown>
258
+ : Record<string, unknown>
259
+
260
+ /** Update payload for an augmented table name (from generated `supatype` output). */
261
+ export type TableUpdate<TTable extends keyof SupatypeModels & string> =
262
+ [keyof SupatypeModels] extends [never]
263
+ ? Record<string, unknown>
264
+ : TTable extends keyof SupatypeModels
265
+ ? SupatypeModels[TTable] extends { Update: infer U }
266
+ ? U
267
+ : Record<string, unknown>
268
+ : Record<string, unknown>
269
+
242
270
  type ModelDefFromAugmented<T> =
243
271
  T extends TableDef
244
272
  ? T
@@ -80,14 +80,15 @@ describe("createClient data plane auth", () => {
80
80
  expires_at: Math.floor(Date.now() / 1000) + 3600,
81
81
  user: RAW_USER,
82
82
  }),
83
- headers: { get: () => null },
83
+ headers: { get: (): string | null => null },
84
84
  }
85
85
  }
86
86
  return {
87
87
  ok: true,
88
88
  status: 200,
89
89
  json: async () => [{ id: "1", title: "Hello" }],
90
- headers: { get: () => null },
90
+ text: async () => JSON.stringify([{ id: "1", title: "Hello" }]),
91
+ headers: { get: (): string | null => null },
91
92
  }
92
93
  })
93
94
  vi.stubGlobal("fetch", fetchSpy)
@@ -130,14 +131,15 @@ describe("createClient data plane auth", () => {
130
131
  ok: false,
131
132
  status: 400,
132
133
  json: async () => ({ error_description: "Invalid Refresh Token" }),
133
- headers: { get: () => null },
134
+ headers: { get: (): string | null => null },
134
135
  }
135
136
  }
136
137
  return {
137
138
  ok: true,
138
139
  status: 200,
139
140
  json: async () => [{ id: "1", title: "Anon ok" }],
140
- headers: { get: () => null },
141
+ text: async () => JSON.stringify([{ id: "1", title: "Anon ok" }]),
142
+ headers: { get: (): string | null => null },
141
143
  }
142
144
  })
143
145
  vi.stubGlobal("fetch", fetchSpy)
@@ -18,6 +18,7 @@ function captureHeaders(): {
18
18
  ok: true,
19
19
  status: 200,
20
20
  json: vi.fn().mockResolvedValue([]),
21
+ text: vi.fn().mockResolvedValue("[]"),
21
22
  headers: { get: () => null },
22
23
  })
23
24
  vi.stubGlobal("fetch", fetch)
@@ -140,6 +141,7 @@ describe("a preview link as the client's credential", () => {
140
141
  ok: true,
141
142
  status: 200,
142
143
  json: () => Promise.resolve([]),
144
+ text: () => Promise.resolve("[]"),
143
145
  headers: { get: () => null },
144
146
  })
145
147
  })
@@ -252,6 +254,7 @@ describe("what storage sends as its credential", () => {
252
254
  ok: true,
253
255
  status: 200,
254
256
  json: vi.fn().mockResolvedValue([]),
257
+ text: vi.fn().mockResolvedValue("[]"),
255
258
  headers: { get: () => null },
256
259
  })
257
260
  vi.stubGlobal("fetch", fetchMock)
@@ -0,0 +1,95 @@
1
+ /**
2
+ * What happens when the client is asked to read a value it was never told about.
3
+ *
4
+ * The kinds arrive from generated code, compiled into the same bundle as the app. So there are
5
+ * exactly two states worth distinguishing, and the design turns on telling them apart:
6
+ *
7
+ * nothing registered the project never generated, or the app imported `createClient` from the
8
+ * package instead of from `supatype/client`
9
+ * registered, unknown the column is new since the last push, or reached through an embed
10
+ *
11
+ * Neither is papered over. The previous design fell back to fetching PostgREST's OpenAPI document,
12
+ * which reconstructs the answer from the live database and therefore always succeeds, so the first
13
+ * state was indistinguishable from the second and could never be reported.
14
+ */
15
+ import { describe, expect, it, beforeEach } from "vitest"
16
+ import { parseRowsExactly, tableFromPath } from "../src/exact-response.js"
17
+ import {
18
+ registerFieldKinds,
19
+ forgetRegisteredFieldKinds,
20
+ } from "../src/field-kinds-registry.js"
21
+
22
+ beforeEach(() => {
23
+ forgetRegisteredFieldKinds()
24
+ })
25
+
26
+ describe("tableFromPath", () => {
27
+ it("reads the table out of a PostgREST path", () => {
28
+ expect(tableFromPath("/rest/v1/job_post")).toBe("job_post")
29
+ expect(tableFromPath("/rest/v1/job_post?select=slug")).toBe("job_post")
30
+ })
31
+ })
32
+
33
+ describe("parseRowsExactly", () => {
34
+ it("returns a bigint column as a native bigint", () => {
35
+ registerFieldKinds({ version: 1, tables: { job_post: { views: "bigint" } } })
36
+ const out = parseRowsExactly('[{"slug":"a","views":9007199254740993}]', "job_post")
37
+
38
+ expect(out.ok).toBe(true)
39
+ expect(out.ok && (out.value as [{ views: bigint }])[0].views).toBe(9007199254740993n)
40
+ })
41
+
42
+ it("returns a numeric column as an exact string", () => {
43
+ registerFieldKinds({ version: 1, tables: { job_post: { equityPct: "numeric" } } })
44
+ const out = parseRowsExactly('[{"equityPct":0.20}]', "job_post")
45
+
46
+ expect(out.ok).toBe(true)
47
+ expect(out.ok && (out.value as [{ equityPct: string }])[0].equityPct).toBe("0.20")
48
+ })
49
+
50
+ it("leaves ordinary columns alone", () => {
51
+ registerFieldKinds({ version: 1, tables: { job_post: { views: "bigint" } } })
52
+ const out = parseRowsExactly('[{"hits":42,"rate":1.5,"title":"x"}]', "job_post")
53
+
54
+ expect(out.ok).toBe(true)
55
+ expect(out.ok && out.value).toEqual([{ hits: 42, rate: 1.5, title: "x" }])
56
+ })
57
+
58
+ it("says the project has not generated when nothing is registered", () => {
59
+ const out = parseRowsExactly('[{"views":9007199254740993}]', "job_post")
60
+
61
+ expect(out.ok).toBe(false)
62
+ expect(!out.ok && out.columns).toEqual(["views"])
63
+ expect(!out.ok && out.message).toContain("supatype push")
64
+ expect(!out.ok && out.message).toContain('import { createClient } from "./supatype/client"')
65
+ })
66
+
67
+ it("says something different when the kinds are registered but the column is not", () => {
68
+ // Registered and unknown is a new column or an embed, not a missing setup step, and telling
69
+ // someone to run `push` when they already have would send them the wrong way.
70
+ registerFieldKinds({ version: 1, tables: { job_post: { views: "bigint" } } })
71
+ const out = parseRowsExactly('[{"author":{"views":9007199254740993}}]', "job_post")
72
+
73
+ expect(out.ok).toBe(false)
74
+ expect(!out.ok && out.message).toContain("embed")
75
+ expect(!out.ok && out.message).not.toContain('import { createClient }')
76
+ })
77
+
78
+ it("never returns a wrong number in place of an error", () => {
79
+ // The property that matters, in both states: a caller does not silently receive
80
+ // 9007199254740992 where the database holds 9007199254740993.
81
+ const unregistered = parseRowsExactly('[{"views":9007199254740993}]', "job_post")
82
+ expect(unregistered.ok).toBe(false)
83
+
84
+ registerFieldKinds({ version: 1, tables: { other: { x: "bigint" } } })
85
+ const wrongTable = parseRowsExactly('[{"views":9007199254740993}]', "job_post")
86
+ expect(wrongTable.ok).toBe(false)
87
+ })
88
+
89
+ it("does not complain about a project with nothing exact to protect", () => {
90
+ // Registered but empty: the schema simply has no bigInt, decimal or money column.
91
+ registerFieldKinds({ version: 1, tables: {} })
92
+ const out = parseRowsExactly('[{"hits":42}]', "job_post")
93
+ expect(out.ok).toBe(true)
94
+ })
95
+ })