@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
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Reading a response body without losing the columns a double cannot hold.
3
+ *
4
+ * Joins the two halves: the registry says which columns are exact-value kinds, `exact-values` keeps
5
+ * their digits intact across the parse. Kept apart from both so neither has to know about the
6
+ * other, and so the decision about what to do when the kinds are unknown lives in one place.
7
+ */
8
+ import {
9
+ coerceExactKinds,
10
+ findLossyNumbers,
11
+ quoteExactNumbers,
12
+ type ExactFields,
13
+ } from "./exact-values.js"
14
+ import { fieldKindsAreRegistered, registeredFieldsFor } from "./field-kinds-registry.js"
15
+
16
+ /**
17
+ * Either the parsed rows, or the reason they could not be read without corrupting something.
18
+ *
19
+ * A result rather than an exception, because every other failure in this client is reported
20
+ * through `QueryResult.error` and a lone throw from the parse path would be the odd one out.
21
+ */
22
+ export type ExactParse =
23
+ | { readonly ok: true; readonly value: unknown }
24
+ | { readonly ok: false; readonly message: string; readonly columns: readonly string[] }
25
+
26
+ /** The table a PostgREST path names, for looking its columns up. */
27
+ export function tableFromPath(path: string): string {
28
+ const withoutPrefix = path.replace(/^\/rest\/v1\//, "")
29
+ const [table] = withoutPrefix.split("?")
30
+ return table ?? withoutPrefix
31
+ }
32
+
33
+ /**
34
+ * Parse a response body, keeping exact-value columns exact.
35
+ *
36
+ * When a numeric literal would lose its value and the column is not one the generated code
37
+ * described, this reports a failure rather than returning a wrong number. There is deliberately no
38
+ * fallback to asking the database: reconstructing the answer always succeeds, which would make a
39
+ * project that never generated indistinguishable from one that did.
40
+ */
41
+ export function parseRowsExactly(body: string, table: string): ExactParse {
42
+ const fields: ExactFields = registeredFieldsFor(table)
43
+ const rewritten = quoteExactNumbers(body, fields)
44
+
45
+ // Anything still lossy is a column nothing described: the known ones are strings by now.
46
+ const stranded = findLossyNumbers(rewritten)
47
+ if (stranded.length === 0) {
48
+ return { ok: true, value: coerceExactKinds(JSON.parse(rewritten), fields) }
49
+ }
50
+
51
+ return { ok: false, columns: stranded, message: describe(table, stranded) }
52
+ }
53
+
54
+ function describe(table: string, columns: readonly string[]): string {
55
+ const named = columns.join(", ")
56
+ const which = columns.length === 1 ? "column" : "columns"
57
+
58
+ if (!fieldKindsAreRegistered()) {
59
+ return (
60
+ `The ${which} ${named} on ${table} returned a value that JavaScript cannot hold exactly, and ` +
61
+ `this project's generated types have not been loaded, so Supatype does not know which ` +
62
+ `columns to keep exact. Run \`supatype push\` and import the client from the generated file:` +
63
+ `\n\n import { createClient } from "./supatype/client"\n\n` +
64
+ `Reading it as a number would have silently changed the value, so it has not guessed.`
65
+ )
66
+ }
67
+
68
+ return (
69
+ `The ${which} ${named} on ${table} returned a value that JavaScript cannot hold exactly, and ` +
70
+ `the generated types do not describe it as one Supatype knows how to keep exact, so it has ` +
71
+ `not guessed. The usual cause is an embedded resource: a column reached through an embed is ` +
72
+ `left alone, because the select that produced it is not parsed here. Selecting it directly ` +
73
+ `rather than through an embed returns it exactly. If the column is new, \`supatype push\` ` +
74
+ `regenerates the types.`
75
+ )
76
+ }
@@ -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
+ }
@@ -0,0 +1,43 @@
1
+ import type { AuthListener } from "./auth.js"
2
+
3
+ /**
4
+ * The part of `AuthClient` this needs.
5
+ *
6
+ * Structural rather than the class itself so a caller, and a test, can supply anything that emits
7
+ * auth changes without constructing a whole client. The callback is `AuthListener`, the same type
8
+ * the real `onAuthStateChange` takes, so the stand-in cannot drift from what it stands in for.
9
+ */
10
+ export interface IdentitySource {
11
+ onAuthStateChange(callback: AuthListener): {
12
+ data: { subscription: { unsubscribe(): void } }
13
+ }
14
+ }
15
+
16
+ /**
17
+ * Call `onChange` whenever the signed-in identity changes, and not otherwise.
18
+ *
19
+ * `onAuthStateChange` also fires once at registration and again on every token refresh. A data hook
20
+ * subscribed to it raw would refetch on a timer for as long as the page stayed open, and would
21
+ * refetch once more immediately after the fetch it already makes on mount. This narrows the stream
22
+ * to the only transition that changes what a query is allowed to read: a different user, or none.
23
+ *
24
+ * Returns the unsubscribe function, so a caller can hand it straight to its own teardown hook.
25
+ */
26
+ export function onIdentityChange(auth: IdentitySource, onChange: () => void): () => void {
27
+ // `undefined` until the registration emission has established the baseline, so that emission is
28
+ // not itself read as a change.
29
+ let known: string | null | undefined
30
+ const { data } = auth.onAuthStateChange((_event, session) => {
31
+ const userId = session?.user.id ?? null
32
+ if (known === undefined) {
33
+ known = userId
34
+ return
35
+ }
36
+ if (userId === known) return
37
+ known = userId
38
+ onChange()
39
+ })
40
+ return () => {
41
+ data.subscription.unsubscribe()
42
+ }
43
+ }
package/src/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { AuthClient } from "./auth.js"
2
+ import { onIdentityChange } from "./identity.js"
2
3
  import { PreviewCredential } from "./preview.js"
3
4
  import { QueryBuilder, MutationBuilder, type HeadersProvider } from "./query.js"
4
5
  import { defaultQueryCache, type QueryCache } from "./query-cache.js"
@@ -38,6 +39,8 @@ export type {
38
39
  SelectQueryOptions,
39
40
  TableDef,
40
41
  TableInsert,
42
+ TableRow,
43
+ TableUpdate,
41
44
  SupatypeModels,
42
45
  SupatypeBuckets,
43
46
  SupatypeFunctions,
@@ -49,8 +52,24 @@ export {
49
52
  PKCE_METHOD_S256,
50
53
  } from "./pkce.js"
51
54
  export { DRAFT_SCHEMA } from "./types.js"
55
+
56
+ /**
57
+ * A client whose database type the holder does not know.
58
+ *
59
+ * What every framework binding's context, provider or injection key is typed at. A context is one
60
+ * value shared by many consumers, so it cannot be generic, and at the `AugmentedDatabase` default
61
+ * it rejected `createClient<Database>(...)`, the client every real project builds. `AnyDatabase` is
62
+ * the constraint every generated database satisfies, so the typed client goes in unchanged and each
63
+ * binding's `useSupatype<TDatabase>()` narrows it on the way back out.
64
+ *
65
+ * Named here rather than spelled out in four packages so the decision has one home. It is also not
66
+ * `any`: that widening is one TypeScript already allows, so `any` bought nothing and cost every
67
+ * consumer its checking.
68
+ */
69
+ export type AnyClient = SupatypeClient<AnyDatabase>
52
70
  export type { QueryCacheOptions, CacheStatus } from "./query-cache.js"
53
71
  export { AuthClient } from "./auth.js"
72
+ export { onIdentityChange, type IdentitySource } from "./identity.js"
54
73
  export { QueryBuilder, MutationBuilder, type HeadersProvider } from "./query.js"
55
74
  export { QueryCache, defaultQueryCache } from "./query-cache.js"
56
75
  export { StorageClient, BucketClient } from "./storage.js"
@@ -58,6 +77,16 @@ export type { StorageObject, TransformOptions } from "./storage.js"
58
77
  export { RealtimeClient } from "./realtime.js"
59
78
  export type { RealtimeEvent, RealtimePayload, ChannelStatus, PresenceEntry } from "./realtime.js"
60
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"
61
90
  export { fetchWithRetry, detectServerlessEnvironment, warnIfServerlessDirectConnection } from "./fetch-with-retry.js"
62
91
  export type { FetchOptions, ServerlessDetectionResult } from "./fetch-with-retry.js"
63
92
  export { createRetryFetch } from "./retry.js"
@@ -504,7 +533,6 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
504
533
  cookiePrefix: config.auth?.cookiePrefix,
505
534
  storage: config.auth?.storage,
506
535
  })
507
- const realtime = new RealtimeClient(`${config.url}/realtime/v1`, baseHeaders)
508
536
  const queryCache = config.queryCache ?? defaultQueryCache
509
537
 
510
538
  const getAuthHeaders = async (): Promise<Record<string, string>> => {
@@ -547,12 +575,37 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
547
575
  // because an anon key carries no `sub` and the proxy requires one.
548
576
  const storage = new StorageClient(`${config.url}/storage/v1`, getAuthHeaders)
549
577
 
578
+ // The same provider the other sub-clients get, not `baseHeaders`.
579
+ //
580
+ // `baseHeaders` is built once and never mutated, so handing it over pinned every socket to the
581
+ // anon key for the life of the page. Realtime enforces RLS, so on a table that is not
582
+ // anon-readable the socket reported SUBSCRIBED and delivered nothing, which is exactly the
583
+ // failure the storage note above describes.
584
+ const realtime = new RealtimeClient(`${config.url}/realtime/v1`, getAuthHeaders)
585
+
550
586
  const onUnauthorized = config.serviceRoleKey
551
587
  ? undefined
552
588
  : (): Promise<void> => auth.ensureValidSession()
553
589
 
554
590
  const functions = new FunctionsClient(config.url, getAuthHeaders, doFetch, onUnauthorized)
555
591
 
592
+ // Signing in has to reach an already-open socket.
593
+ //
594
+ // Every binding subscribes when its component mounts, which is before the user has signed in, so
595
+ // the socket that matters is always one opened while signed out. Resolving the token per
596
+ // connection is not enough on its own; something has to tell the connection it is now stale.
597
+ //
598
+ // `onIdentityChange`, not `onAuthStateChange`: a refreshed token is a different string for the
599
+ // same person, and reconnecting on it would close and re-open the socket once an hour for the
600
+ // life of the tab, losing every change committed in the gap. That is the silent miss this whole
601
+ // change exists to remove, so it must not be reintroduced by the fix.
602
+ //
603
+ // The subscription is never torn down. The listener is held by `auth` and closes over `realtime`,
604
+ // both owned by this client, so the cycle is collected whole when the client is dropped.
605
+ onIdentityChange(auth, () => {
606
+ void realtime.reauthenticate()
607
+ })
608
+
556
609
  return {
557
610
  url: config.url,
558
611
  serviceRoleKey: config.serviceRoleKey,
@@ -1,10 +1,11 @@
1
1
  import type { QueryResult } from "./types.js"
2
2
  import { sha256Hex } from "./sha256-hex.js"
3
+ import { bearerToken } from "./query.js"
3
4
 
4
5
  export interface QueryCacheOptions {
5
6
  /** Client-side TTL in milliseconds. */
6
7
  ttl: number
7
- /** When true, send `X-Supatype-Cache: max-age=N` so the server caches the response too. */
8
+ /** When true, send `X-Supatype-Cache: max-age=N` for server-side Valkey caching. */
8
9
  server?: boolean | undefined
9
10
  /** When true (with server), request shared public cache scope when allowed for the table. */
10
11
  public?: boolean | undefined
@@ -26,14 +27,6 @@ interface JwtPayload {
26
27
  role?: string
27
28
  }
28
29
 
29
- function bearerOrApikey(headers: Record<string, string>): string {
30
- const auth = headers["Authorization"] ?? headers["authorization"] ?? ""
31
- if (auth.startsWith("Bearer ")) {
32
- return auth.slice("Bearer ".length)
33
- }
34
- return headers["apikey"] ?? headers["Apikey"] ?? ""
35
- }
36
-
37
30
  function parseJwtPayload(token: string): JwtPayload | null {
38
31
  const parts = token.split(".")
39
32
  if (parts.length !== 3) return null
@@ -51,7 +44,7 @@ export function identityFingerprint(
51
44
  scope: "public" | "user",
52
45
  ): string {
53
46
  if (scope === "public") return "global"
54
- const token = bearerOrApikey(headers)
47
+ const token = bearerToken(headers)
55
48
  if (!token) return "anon"
56
49
  const claims = parseJwtPayload(token)
57
50
  const role = claims?.role?.trim() || "authenticated"