@supatype/client 0.3.1 → 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 (50) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +28 -24
  3. package/.turbo/turbo-typecheck.log +2 -2
  4. package/dist/exact-response.d.ts +26 -0
  5. package/dist/exact-response.d.ts.map +1 -0
  6. package/dist/exact-response.js +51 -0
  7. package/dist/exact-response.js.map +1 -0
  8. package/dist/exact-values.d.ts +50 -0
  9. package/dist/exact-values.d.ts.map +1 -0
  10. package/dist/exact-values.js +254 -0
  11. package/dist/exact-values.js.map +1 -0
  12. package/dist/field-kinds-registry.d.ts +46 -0
  13. package/dist/field-kinds-registry.d.ts.map +1 -0
  14. package/dist/field-kinds-registry.js +51 -0
  15. package/dist/field-kinds-registry.js.map +1 -0
  16. package/dist/index.d.ts +2 -1
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +4 -0
  19. package/dist/index.js.map +1 -1
  20. package/dist/query.d.ts.map +1 -1
  21. package/dist/query.js +18 -5
  22. package/dist/query.js.map +1 -1
  23. package/dist/realtime.d.ts.map +1 -1
  24. package/dist/realtime.js +19 -2
  25. package/dist/realtime.js.map +1 -1
  26. package/dist/types.d.ts +20 -0
  27. package/dist/types.d.ts.map +1 -1
  28. package/dist/types.js.map +1 -1
  29. package/package.json +2 -2
  30. package/src/exact-response.ts +76 -0
  31. package/src/exact-values.ts +281 -0
  32. package/src/field-kinds-registry.ts +80 -0
  33. package/src/index.ts +12 -0
  34. package/src/query.ts +23 -5
  35. package/src/realtime.ts +29 -2
  36. package/src/types.ts +28 -0
  37. package/tests/data-plane-auth.test.ts +6 -4
  38. package/tests/draft-profile.test.ts +3 -0
  39. package/tests/exact-response.test.ts +95 -0
  40. package/tests/exact-values.test.ts +171 -0
  41. package/tests/field-kinds-registry.test.ts +80 -0
  42. package/tests/fixtures/models.ts +55 -0
  43. package/tests/identity-change.test.ts +5 -5
  44. package/tests/query-cache.test.ts +14 -8
  45. package/tests/query.test.ts +1 -0
  46. package/tests/realtime-exact-values.test.ts +161 -0
  47. package/tests/realtime-session-auth.test.ts +8 -8
  48. package/tests/tsconfig.json +9 -0
  49. package/tests/types.test.ts +40 -32
  50. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,281 @@
1
+ /**
2
+ * Keeping exact-value columns intact across `JSON.parse`.
3
+ *
4
+ * `bigInt`, `decimal` and `money` name values no binary float holds. Postgres stores them exactly
5
+ * and PostgREST writes the correct digits on the wire, as unquoted JSON numbers. `JSON.parse` then
6
+ * reads each one into an IEEE-754 double, and 9007199254740993 comes back as 9007199254740992.
7
+ *
8
+ * Nothing after the parse can recover the digits, so the repair has to happen on the response text
9
+ * while they are still there: quote the value, let `JSON.parse` produce a string, and convert from
10
+ * that. This also makes runtime agree with the generated types, which declare `bigint` for BIGINT
11
+ * and `string` for the two NUMERIC kinds, matching `@supatype/types`.
12
+ *
13
+ * Deliberately not implemented with `JSON.parse`'s source-accessing reviver: that is recent enough
14
+ * that a runtime without it would silently fall back to corruption, which is the failure this
15
+ * module exists to remove.
16
+ */
17
+
18
+ /** The two shapes a column can need. `numeric` covers both `decimal` and `money`. */
19
+ export type ExactKind = "bigint" | "numeric"
20
+
21
+ /** Column name to kind, for the table being read. */
22
+ export type ExactFields = Readonly<Record<string, ExactKind>>
23
+
24
+ const WHITESPACE = new Set([" ", "\t", "\n", "\r"])
25
+ const QUOTE = '"'
26
+
27
+ /** A numeric literal found as the value of a key, with where it sits in the text. */
28
+ type KeyedNumber = {
29
+ readonly key: string
30
+ readonly depth: number
31
+ readonly start: number
32
+ readonly end: number
33
+ }
34
+
35
+ /**
36
+ * Walk the JSON text and report every numeric literal that is the value of a key.
37
+ *
38
+ * One scanner rather than one per caller, because the hard part is shared: tracking string state
39
+ * so a key name written inside a string value is not mistaken for a column.
40
+ */
41
+ function forEachKeyedNumber(body: string, visit: (found: KeyedNumber) => void): void {
42
+ let i = 0
43
+ let depth = 0
44
+ let pendingKey: string | null = null
45
+
46
+ while (i < body.length) {
47
+ const ch = body[i] as string
48
+
49
+ if (ch === QUOTE) {
50
+ const end = endOfString(body, i)
51
+ const raw = body.slice(i, end)
52
+ i = end
53
+ pendingKey = nextMeaningfulChar(body, i) === ":" ? readKey(raw) : null
54
+ continue
55
+ }
56
+
57
+ if (ch === "{" || ch === "[") {
58
+ depth += 1
59
+ i += 1
60
+ continue
61
+ }
62
+
63
+ if (ch === "}" || ch === "]") {
64
+ depth -= 1
65
+ i += 1
66
+ continue
67
+ }
68
+
69
+ if (ch === ":") {
70
+ i += 1
71
+ while (i < body.length && WHITESPACE.has(body[i] as string)) i += 1
72
+ const key = pendingKey
73
+ pendingKey = null
74
+ if (key !== null) {
75
+ const end = endOfNumber(body, i)
76
+ if (end > i) {
77
+ visit({ key, depth, start: i, end })
78
+ i = end
79
+ }
80
+ }
81
+ continue
82
+ }
83
+
84
+ i += 1
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Quote the numeric literals belonging to exact-value columns, so the digits survive the parse.
90
+ *
91
+ * Returns `body` unchanged when there is nothing to do, so the common request pays a scan and no
92
+ * string building.
93
+ */
94
+ export function quoteExactNumbers(body: string, fields: ExactFields): string {
95
+ if (Object.keys(fields).length === 0) return body
96
+
97
+ // A list response nests rows one level deeper than a single-object response. Columns are only
98
+ // rewritten at row level: an embedded resource can carry a same-named column of another kind,
99
+ // and the select that produced it is not parsed here, so rewriting it would be a guess.
100
+ const rowDepth = firstMeaningfulChar(body) === "[" ? 2 : 1
101
+
102
+ const spans: KeyedNumber[] = []
103
+ forEachKeyedNumber(body, (found) => {
104
+ if (found.depth === rowDepth && fields[found.key] !== undefined) spans.push(found)
105
+ })
106
+ if (spans.length === 0) return body
107
+
108
+ let out = ""
109
+ let cursor = 0
110
+ for (const span of spans) {
111
+ // The literal, verbatim. Trailing zeros and exponents are part of what was sent.
112
+ const literal = body.slice(span.start, span.end)
113
+ out += body.slice(cursor, span.start)
114
+ out += JSON.stringify(literal)
115
+ cursor = span.end
116
+ }
117
+ return out + body.slice(cursor)
118
+ }
119
+
120
+ /**
121
+ * The columns whose literals will not survive `JSON.parse`.
122
+ *
123
+ * The safety net for when column metadata could not be loaded. Without it a failed metadata fetch
124
+ * would quietly restore the corruption this module exists to remove. Reports at any depth, since
125
+ * over-reporting here costs a clear error and under-reporting costs a wrong number.
126
+ */
127
+ export function findLossyNumbers(body: string): string[] {
128
+ const names: string[] = []
129
+ const seen = new Set<string>()
130
+ forEachKeyedNumber(body, (found) => {
131
+ if (seen.has(found.key)) return
132
+ if (!isLossy(body.slice(found.start, found.end))) return
133
+ seen.add(found.key)
134
+ names.push(found.key)
135
+ })
136
+ return names
137
+ }
138
+
139
+ /**
140
+ * Convert the quoted values to the types the generated `database.ts` declares.
141
+ *
142
+ * `bigint` columns become native bigints. `numeric` columns stay exact strings, because JavaScript
143
+ * has no native exact decimal, which is why `@supatype/types` declares Decimal and Money `string`.
144
+ */
145
+ export function coerceExactKinds(value: unknown, fields: ExactFields): unknown {
146
+ if (Object.keys(fields).length === 0) return value
147
+ if (Array.isArray(value)) return value.map((row) => coerceRow(row, fields))
148
+ return coerceRow(value, fields)
149
+ }
150
+
151
+ /**
152
+ * `JSON.stringify` that does not throw on a bigint.
153
+ *
154
+ * Reading a row and writing it back would otherwise fail the moment the generated types started
155
+ * declaring `bigint`, because `JSON.stringify` refuses to serialise one.
156
+ */
157
+ export function stringifyWithBigInts(value: unknown): string {
158
+ return JSON.stringify(value, (_key, item: unknown) =>
159
+ typeof item === "bigint" ? item.toString() : item,
160
+ )
161
+ }
162
+
163
+ function coerceRow(row: unknown, fields: ExactFields): unknown {
164
+ if (row === null || typeof row !== "object" || Array.isArray(row)) return row
165
+
166
+ const source = row as Record<string, unknown>
167
+ let copy: Record<string, unknown> | null = null
168
+
169
+ for (const [name, kind] of Object.entries(fields)) {
170
+ if (kind !== "bigint") continue
171
+ const current = source[name]
172
+ if (typeof current !== "string") continue
173
+ copy ??= { ...source }
174
+ copy[name] = BigInt(current)
175
+ }
176
+
177
+ return copy ?? row
178
+ }
179
+
180
+ /** Whether parsing this literal as a double changes the value it names. */
181
+ function isLossy(literal: string): boolean {
182
+ const asNumber = Number(literal)
183
+ if (!Number.isFinite(asNumber)) return true
184
+ // Compared as values rather than as text, so `19.0000` arriving as `19` is not called a loss.
185
+ // It is a type-fidelity problem, and throwing on it would break every project with a money
186
+ // column whose metadata failed to load.
187
+ return normalizeDecimal(literal) !== normalizeDecimal(String(asNumber))
188
+ }
189
+
190
+ /** A literal rewritten as a plain decimal with no exponent and no insignificant zeros. */
191
+ function normalizeDecimal(literal: string): string {
192
+ const parts = /^(-?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(literal)
193
+ if (parts === null) return literal
194
+
195
+ const sign = parts[1] ?? ""
196
+ const exponent = parts[4] !== undefined ? Number(parts[4]) : 0
197
+ const integerPart = parts[2] ?? ""
198
+ const fractionPart = parts[3] ?? ""
199
+
200
+ let digits = integerPart + fractionPart
201
+ let pointAt = integerPart.length + exponent
202
+
203
+ if (pointAt <= 0) {
204
+ digits = "0".repeat(1 - pointAt) + digits
205
+ pointAt = 1
206
+ }
207
+ if (pointAt >= digits.length) {
208
+ digits += "0".repeat(pointAt - digits.length)
209
+ }
210
+
211
+ const head = digits.slice(0, pointAt).replace(/^0+(?=\d)/, "")
212
+ const tail = digits.slice(pointAt).replace(/0+$/, "")
213
+ const magnitude = tail === "" ? head : head + "." + tail
214
+
215
+ return /^0(\.0*)?$/.test(magnitude) ? "0" : sign + magnitude
216
+ }
217
+
218
+ function firstMeaningfulChar(body: string): string | undefined {
219
+ return nextMeaningfulChar(body, 0)
220
+ }
221
+
222
+ function nextMeaningfulChar(body: string, from: number): string | undefined {
223
+ for (let i = from; i < body.length; i += 1) {
224
+ const ch = body[i] as string
225
+ if (!WHITESPACE.has(ch)) return ch
226
+ }
227
+ return undefined
228
+ }
229
+
230
+ /** Index just past the closing quote of the string starting at `start`. */
231
+ function endOfString(body: string, start: number): number {
232
+ let i = start + 1
233
+ while (i < body.length) {
234
+ const ch = body[i]
235
+ if (ch === "\\") {
236
+ i += 2
237
+ continue
238
+ }
239
+ if (ch === QUOTE) return i + 1
240
+ i += 1
241
+ }
242
+ return i
243
+ }
244
+
245
+ /** The key a raw JSON string token names, with escapes resolved. */
246
+ function readKey(raw: string): string | null {
247
+ try {
248
+ const parsed: unknown = JSON.parse(raw)
249
+ return typeof parsed === "string" ? parsed : null
250
+ } catch {
251
+ return null
252
+ }
253
+ }
254
+
255
+ /** Index just past the JSON number starting at `from`, or `from` when one does not start there. */
256
+ function endOfNumber(body: string, from: number): number {
257
+ let i = from
258
+ if (body[i] === "-") i += 1
259
+ const digitsStart = i
260
+ while (i < body.length && isDigit(body[i] as string)) i += 1
261
+ if (i === digitsStart) return from
262
+
263
+ if (body[i] === ".") {
264
+ i += 1
265
+ while (i < body.length && isDigit(body[i] as string)) i += 1
266
+ }
267
+
268
+ if (body[i] === "e" || body[i] === "E") {
269
+ let j = i + 1
270
+ if (body[j] === "+" || body[j] === "-") j += 1
271
+ const expStart = j
272
+ while (j < body.length && isDigit(body[j] as string)) j += 1
273
+ if (j > expStart) i = j
274
+ }
275
+
276
+ return i
277
+ }
278
+
279
+ function isDigit(ch: string): boolean {
280
+ return ch >= "0" && ch <= "9"
281
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Which columns hold values a JSON parser would destroy, told to the client by generated code.
3
+ *
4
+ * `supatype push` writes `supatype/client.ts` into the project. That file calls
5
+ * {@link registerFieldKinds} at import time and re-exports `createClient`, so an app writes
6
+ *
7
+ * import { createClient } from "./supatype/client"
8
+ *
9
+ * and the kinds arrive by the same import that brings the client. They are compiled into the same
10
+ * bundle, so there is nothing to fetch, nothing to read from disk, and nothing that can be stale
11
+ * relative to the code that shipped.
12
+ *
13
+ * This replaced reading the kinds off the filesystem with a fetch of PostgREST's OpenAPI document
14
+ * as a fallback. That fallback reconstructed the answer from the live database, so it always
15
+ * succeeded, which meant a project that had never generated was indistinguishable from one that
16
+ * had. The gap could not be reported because nothing could detect it. Here, absence is a fact:
17
+ * {@link fieldKindsAreRegistered} is false, and the caller can say so.
18
+ */
19
+ import type { ExactFields, ExactKind } from "./exact-values.js"
20
+
21
+ /** Table name to its exact-value columns. */
22
+ export type ExactFieldsByTable = Readonly<Record<string, ExactFields>>
23
+
24
+ /** The shape the generated file passes. Versioned so an older client declines a newer one. */
25
+ export type FieldKindsDocument = {
26
+ readonly version: 1
27
+ readonly tables: Readonly<Record<string, Readonly<Record<string, ExactKind>>>>
28
+ }
29
+
30
+ const SUPPORTED_VERSION = 1
31
+ const NO_FIELDS: ExactFields = {}
32
+
33
+ // Module level, and deliberately not per client. Server-side rendering builds a client per
34
+ // request, and the schema does not change between them.
35
+ let registered: ExactFieldsByTable | null = null
36
+
37
+ /**
38
+ * Record a project's exact-value columns. Called by generated code, not by hand.
39
+ *
40
+ * A document whose version this client does not understand is ignored rather than guessed at: a
41
+ * newer shape read by older rules is how a client starts converting the wrong columns.
42
+ */
43
+ export function registerFieldKinds(document: FieldKindsDocument): void {
44
+ if (document === null || typeof document !== "object") return
45
+ if (document.version !== SUPPORTED_VERSION) return
46
+ if (document.tables === null || typeof document.tables !== "object") return
47
+
48
+ const tables: Record<string, ExactFields> = {}
49
+ for (const [table, columns] of Object.entries(document.tables)) {
50
+ if (columns === null || typeof columns !== "object") continue
51
+ const fields: Record<string, ExactKind> = {}
52
+ for (const [column, kind] of Object.entries(columns)) {
53
+ if (kind === "bigint" || kind === "numeric") fields[column] = kind
54
+ }
55
+ if (Object.keys(fields).length > 0) tables[table] = fields
56
+ }
57
+
58
+ registered = tables
59
+ }
60
+
61
+ /** The exact-value columns of one table, or none when the table has any. */
62
+ export function registeredFieldsFor(table: string): ExactFields {
63
+ return registered?.[table] ?? NO_FIELDS
64
+ }
65
+
66
+ /**
67
+ * Whether generated code has registered anything at all.
68
+ *
69
+ * Distinct from a table having no exact columns. A project with no `bigInt`, `decimal` or `money`
70
+ * anywhere still generated, and shouting at it would be wrong; a project that never generated is
71
+ * the case worth reporting.
72
+ */
73
+ export function fieldKindsAreRegistered(): boolean {
74
+ return registered !== null
75
+ }
76
+
77
+ /** Forget what was registered. For tests, and for a process that switches projects. */
78
+ export function forgetRegisteredFieldKinds(): void {
79
+ registered = null
80
+ }
package/src/index.ts CHANGED
@@ -39,6 +39,8 @@ export type {
39
39
  SelectQueryOptions,
40
40
  TableDef,
41
41
  TableInsert,
42
+ TableRow,
43
+ TableUpdate,
42
44
  SupatypeModels,
43
45
  SupatypeBuckets,
44
46
  SupatypeFunctions,
@@ -75,6 +77,16 @@ export type { StorageObject, TransformOptions } from "./storage.js"
75
77
  export { RealtimeClient } from "./realtime.js"
76
78
  export type { RealtimeEvent, RealtimePayload, ChannelStatus, PresenceEntry } from "./realtime.js"
77
79
  export * from "./errors.js"
80
+
81
+ // Called by the generated `supatype/client.ts`, which is how a project tells the client which
82
+ // columns hold values a JSON parser would destroy. Exported because generated code imports it;
83
+ // applications do not call it.
84
+ export {
85
+ registerFieldKinds,
86
+ fieldKindsAreRegistered,
87
+ forgetRegisteredFieldKinds,
88
+ type FieldKindsDocument,
89
+ } from "./field-kinds-registry.js"
78
90
  export { fetchWithRetry, detectServerlessEnvironment, warnIfServerlessDirectConnection } from "./fetch-with-retry.js"
79
91
  export type { FetchOptions, ServerlessDetectionResult } from "./fetch-with-retry.js"
80
92
  export { createRetryFetch } from "./retry.js"
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") ||
@@ -411,8 +413,17 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
411
413
  )
412
414
  }
413
415
 
414
- const json = await res.json() as TRow[]
415
- 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 }
416
427
 
417
428
  if (this.cacheOptions) {
418
429
  const cacheKey = buildCacheKey("GET", url, await resolveRequestHeaders(), {
@@ -530,7 +541,9 @@ export class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
530
541
  })
531
542
  const init: RequestInit = {
532
543
  method: this.method,
533
- ...(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) }),
534
547
  }
535
548
  let res: Response
536
549
  try {
@@ -575,8 +588,13 @@ export class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
575
588
  return { data: [], error: null, count: 0 }
576
589
  }
577
590
 
578
- const json = await res.json() as TRow | TRow[]
579
- 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]
580
598
  return { data, error: null, count: data.length }
581
599
  }
582
600
  }
package/src/realtime.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { asHeadersProvider, bearerToken, type HeadersProvider } from "./query.js"
2
+ import { coerceExactKinds, type ExactFields } from "./exact-values.js"
2
3
 
3
4
  export type RealtimeEvent = "INSERT" | "UPDATE" | "DELETE" | "*"
4
5
 
@@ -52,6 +53,21 @@ export interface PresenceEntry {
52
53
  [key: string]: unknown
53
54
  }
54
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
+
55
71
  // ─── Server message types (subset matching @supatype/realtime) ───────────────
56
72
 
57
73
  interface ServerChangeMessage {
@@ -59,6 +75,13 @@ interface ServerChangeMessage {
59
75
  channel: string
60
76
  event: "INSERT" | "UPDATE" | "DELETE"
61
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
62
85
  timestamp: string
63
86
  }
64
87
 
@@ -457,10 +480,14 @@ export class RealtimeClient {
457
480
  const schema = parts.length >= 2 ? parts[0]! : "public"
458
481
  const table = parts.length >= 2 ? parts[1]! : parts[0]!
459
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 ?? {}
460
487
  const payload: RealtimePayload<Record<string, unknown>> = {
461
488
  eventType: msg.event,
462
- new: msg.payload.new,
463
- old: msg.payload.old,
489
+ new: coerceRecord(msg.payload.new, exact),
490
+ old: coerceRecord(msg.payload.old, exact),
464
491
  schema,
465
492
  table,
466
493
  commitTimestamp: msg.timestamp,
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)