@supatype/client 0.3.6 → 0.8.0

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 (209) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +69 -30
  3. package/.turbo/turbo-typecheck.log +2 -2
  4. package/LICENSE +1 -1
  5. package/dist/auth-redirect.d.ts +48 -0
  6. package/dist/auth-redirect.d.ts.map +1 -0
  7. package/dist/auth-redirect.js +70 -0
  8. package/dist/auth-redirect.js.map +1 -0
  9. package/dist/auth.d.ts +86 -4
  10. package/dist/auth.d.ts.map +1 -1
  11. package/dist/auth.js +383 -275
  12. package/dist/auth.js.map +1 -1
  13. package/dist/bindings.d.ts +16 -0
  14. package/dist/bindings.d.ts.map +1 -0
  15. package/dist/bindings.js +13 -0
  16. package/dist/bindings.js.map +1 -0
  17. package/dist/caller-types.d.ts +18 -0
  18. package/dist/caller-types.d.ts.map +1 -0
  19. package/dist/caller-types.js +22 -0
  20. package/dist/caller-types.js.map +1 -0
  21. package/dist/draft-create.d.ts +12 -0
  22. package/dist/draft-create.d.ts.map +1 -0
  23. package/dist/draft-create.js +47 -0
  24. package/dist/draft-create.js.map +1 -0
  25. package/dist/draft-models-registry.d.ts +27 -0
  26. package/dist/draft-models-registry.d.ts.map +1 -0
  27. package/dist/draft-models-registry.js +61 -0
  28. package/dist/draft-models-registry.js.map +1 -0
  29. package/dist/error-codes-doc.d.ts +1 -1
  30. package/dist/error-codes-doc.d.ts.map +1 -1
  31. package/dist/error-codes-doc.js +42 -34
  32. package/dist/error-codes-doc.js.map +1 -1
  33. package/dist/errors.d.ts +102 -60
  34. package/dist/errors.d.ts.map +1 -1
  35. package/dist/errors.js +69 -28
  36. package/dist/errors.js.map +1 -1
  37. package/dist/exact-response.d.ts.map +1 -1
  38. package/dist/exact-response.js +2 -1
  39. package/dist/exact-response.js.map +1 -1
  40. package/dist/exact-values.d.ts +2 -0
  41. package/dist/exact-values.d.ts.map +1 -1
  42. package/dist/exact-values.js +12 -10
  43. package/dist/exact-values.js.map +1 -1
  44. package/dist/fetch-with-retry.d.ts +21 -6
  45. package/dist/fetch-with-retry.d.ts.map +1 -1
  46. package/dist/fetch-with-retry.js +67 -53
  47. package/dist/fetch-with-retry.js.map +1 -1
  48. package/dist/field-kinds-registry.d.ts +11 -3
  49. package/dist/field-kinds-registry.d.ts.map +1 -1
  50. package/dist/field-kinds-registry.js +10 -6
  51. package/dist/field-kinds-registry.js.map +1 -1
  52. package/dist/filters.d.ts +51 -0
  53. package/dist/filters.d.ts.map +1 -0
  54. package/dist/filters.js +117 -0
  55. package/dist/filters.js.map +1 -0
  56. package/dist/generated-client.d.ts +7 -0
  57. package/dist/generated-client.d.ts.map +1 -0
  58. package/dist/generated-client.js +7 -0
  59. package/dist/generated-client.js.map +1 -0
  60. package/dist/graphql-document.d.ts +39 -0
  61. package/dist/graphql-document.d.ts.map +1 -0
  62. package/dist/graphql-document.js +228 -0
  63. package/dist/graphql-document.js.map +1 -0
  64. package/dist/graphql-json.d.ts +56 -0
  65. package/dist/graphql-json.d.ts.map +1 -0
  66. package/dist/graphql-json.js +220 -0
  67. package/dist/graphql-json.js.map +1 -0
  68. package/dist/graphql-transport.d.ts +28 -0
  69. package/dist/graphql-transport.d.ts.map +1 -0
  70. package/dist/graphql-transport.js +77 -0
  71. package/dist/graphql-transport.js.map +1 -0
  72. package/dist/index.d.ts +103 -40
  73. package/dist/index.d.ts.map +1 -1
  74. package/dist/index.js +170 -165
  75. package/dist/index.js.map +1 -1
  76. package/dist/json.d.ts +61 -0
  77. package/dist/json.d.ts.map +1 -0
  78. package/dist/json.js +83 -0
  79. package/dist/json.js.map +1 -0
  80. package/dist/jwt.d.ts +16 -0
  81. package/dist/jwt.d.ts.map +1 -0
  82. package/dist/jwt.js +37 -0
  83. package/dist/jwt.js.map +1 -0
  84. package/dist/live-preview.d.ts +23 -0
  85. package/dist/live-preview.d.ts.map +1 -0
  86. package/dist/live-preview.js +28 -0
  87. package/dist/live-preview.js.map +1 -0
  88. package/dist/mutation-request.d.ts +17 -0
  89. package/dist/mutation-request.d.ts.map +1 -0
  90. package/dist/mutation-request.js +41 -0
  91. package/dist/mutation-request.js.map +1 -0
  92. package/dist/preview.d.ts.map +1 -1
  93. package/dist/preview.js +8 -6
  94. package/dist/preview.js.map +1 -1
  95. package/dist/query-cache.d.ts.map +1 -1
  96. package/dist/query-cache.js +19 -13
  97. package/dist/query-cache.js.map +1 -1
  98. package/dist/query.d.ts +108 -29
  99. package/dist/query.d.ts.map +1 -1
  100. package/dist/query.js +294 -224
  101. package/dist/query.js.map +1 -1
  102. package/dist/realtime.d.ts +57 -2
  103. package/dist/realtime.d.ts.map +1 -1
  104. package/dist/realtime.js +300 -88
  105. package/dist/realtime.js.map +1 -1
  106. package/dist/select-types.d.ts +99 -0
  107. package/dist/select-types.d.ts.map +1 -0
  108. package/dist/select-types.js +2 -0
  109. package/dist/select-types.js.map +1 -0
  110. package/dist/storage.d.ts +81 -11
  111. package/dist/storage.d.ts.map +1 -1
  112. package/dist/storage.js +137 -38
  113. package/dist/storage.js.map +1 -1
  114. package/dist/table-subscription.d.ts +69 -0
  115. package/dist/table-subscription.d.ts.map +1 -0
  116. package/dist/table-subscription.js +93 -0
  117. package/dist/table-subscription.js.map +1 -0
  118. package/dist/types.d.ts +98 -5
  119. package/dist/types.d.ts.map +1 -1
  120. package/dist/types.js +6 -1
  121. package/dist/types.js.map +1 -1
  122. package/package.json +6 -2
  123. package/src/auth-redirect.ts +90 -0
  124. package/src/auth.ts +434 -281
  125. package/src/bindings.ts +22 -0
  126. package/src/caller-types.ts +27 -0
  127. package/src/draft-create.ts +51 -0
  128. package/src/draft-models-registry.ts +81 -0
  129. package/src/error-codes-doc.ts +44 -35
  130. package/src/errors.ts +72 -28
  131. package/src/exact-response.ts +2 -1
  132. package/src/exact-values.ts +16 -9
  133. package/src/fetch-with-retry.ts +80 -70
  134. package/src/field-kinds-registry.ts +22 -9
  135. package/src/filters.ts +133 -0
  136. package/src/generated-client.ts +6 -0
  137. package/src/graphql-document.ts +234 -0
  138. package/src/graphql-json.ts +243 -0
  139. package/src/graphql-transport.ts +97 -0
  140. package/src/index.ts +289 -208
  141. package/src/json.ts +117 -0
  142. package/src/jwt.ts +37 -0
  143. package/src/live-preview.ts +37 -0
  144. package/src/mutation-request.ts +66 -0
  145. package/src/preview.ts +9 -11
  146. package/src/query-cache.ts +19 -16
  147. package/src/query.ts +389 -270
  148. package/src/realtime.ts +333 -90
  149. package/src/select-types.ts +184 -0
  150. package/src/storage.ts +223 -44
  151. package/src/table-subscription.ts +160 -0
  152. package/src/types.ts +104 -5
  153. package/tests/auth-error-codes.test.ts +53 -0
  154. package/tests/auth-errors.test.ts +84 -0
  155. package/tests/auth-events.test.ts +136 -0
  156. package/tests/auth-url-session.test.ts +204 -0
  157. package/tests/auth.test.ts +187 -26
  158. package/tests/count.test.ts +60 -0
  159. package/tests/data-plane-auth.test.ts +21 -46
  160. package/tests/draft-insert.integration.test.ts +118 -0
  161. package/tests/draft-insert.test.ts +225 -0
  162. package/tests/draft-profile.test.ts +55 -84
  163. package/tests/draft-update.integration.test.ts +122 -0
  164. package/tests/draft-update.test.ts +174 -0
  165. package/tests/dynamic-headers.test.ts +45 -0
  166. package/tests/entry-points.test.ts +42 -0
  167. package/tests/exact-response.test.ts +4 -4
  168. package/tests/exact-values.test.ts +14 -25
  169. package/tests/field-kinds-registry.test.ts +3 -3
  170. package/tests/filters.test.ts +146 -0
  171. package/tests/graphql-json.test.ts +199 -0
  172. package/tests/helpers/mock-websocket.ts +44 -11
  173. package/tests/helpers/oauth-binding.ts +92 -0
  174. package/tests/helpers/signup-binding.ts +73 -0
  175. package/tests/helpers/socket-swap.ts +142 -0
  176. package/tests/mfa-totp-integration.test.ts +13 -20
  177. package/tests/postgrest-error-codes.test.ts +85 -0
  178. package/tests/query-cache.test.ts +116 -117
  179. package/tests/query.test.ts +29 -31
  180. package/tests/rate-limit-integration.test.ts +4 -12
  181. package/tests/realtime-ack-ref.test.ts +112 -0
  182. package/tests/realtime-exact-values.test.ts +2 -4
  183. package/tests/realtime-presence.test.ts +75 -0
  184. package/tests/realtime-session-auth.test.ts +2 -4
  185. package/tests/realtime-shared-channel.test.ts +209 -0
  186. package/tests/realtime-swap-status.test.ts +62 -0
  187. package/tests/retry-integration.test.ts +3 -8
  188. package/tests/retry-policy.test.ts +166 -0
  189. package/tests/rpc-resend.test.ts +24 -0
  190. package/tests/server-bodies.test.ts +187 -0
  191. package/tests/serverless.test.ts +2 -2
  192. package/tests/signed-url-absolute.test.ts +2 -5
  193. package/tests/storage-object-shape.test.ts +101 -0
  194. package/tests/storage-quota-integration.test.ts +7 -9
  195. package/tests/storage-reference-url.test.ts +51 -0
  196. package/tests/storage-upload-browser.test.ts +71 -0
  197. package/tests/storage-upload-limit-integration.test.ts +17 -31
  198. package/tests/storage-url-encoding.test.ts +52 -0
  199. package/tests/subscribe-frame.test.ts +5 -11
  200. package/tests/support/blob.ts +10 -0
  201. package/tests/support/fetch-mock.ts +64 -0
  202. package/tests/support/storage-object.ts +37 -0
  203. package/tests/table-subscribe.test.ts +41 -14
  204. package/tests/table-subscription.test.ts +105 -0
  205. package/tests/table-transport.test.ts +94 -0
  206. package/tests/tsconfig.json +1 -1
  207. package/tests/types.test.ts +153 -1
  208. package/tsconfig.json +1 -1
  209. package/tsconfig.tsbuildinfo +1 -1
@@ -5,7 +5,7 @@
5
5
  * exactly two states worth distinguishing, and the design turns on telling them apart:
6
6
  *
7
7
  * nothing registered the project never generated, or the app imported `createClient` from the
8
- * package instead of from `supatype/client`
8
+ * package instead of from `supatype/generated/client`
9
9
  * registered, unknown the column is new since the last push, or reached through an embed
10
10
  *
11
11
  * Neither is papered over. The previous design fell back to fetching PostgREST's OpenAPI document,
@@ -36,7 +36,7 @@ describe("parseRowsExactly", () => {
36
36
  const out = parseRowsExactly('[{"slug":"a","views":9007199254740993}]', "job_post")
37
37
 
38
38
  expect(out.ok).toBe(true)
39
- expect(out.ok && (out.value as [{ views: bigint }])[0].views).toBe(9007199254740993n)
39
+ expect(out.ok && out.value).toEqual([{ slug: "a", views: 9007199254740993n }])
40
40
  })
41
41
 
42
42
  it("returns a numeric column as an exact string", () => {
@@ -44,7 +44,7 @@ describe("parseRowsExactly", () => {
44
44
  const out = parseRowsExactly('[{"equityPct":0.20}]', "job_post")
45
45
 
46
46
  expect(out.ok).toBe(true)
47
- expect(out.ok && (out.value as [{ equityPct: string }])[0].equityPct).toBe("0.20")
47
+ expect(out.ok && out.value).toEqual([{ equityPct: "0.20" }])
48
48
  })
49
49
 
50
50
  it("leaves ordinary columns alone", () => {
@@ -61,7 +61,7 @@ describe("parseRowsExactly", () => {
61
61
  expect(out.ok).toBe(false)
62
62
  expect(!out.ok && out.columns).toEqual(["views"])
63
63
  expect(!out.ok && out.message).toContain("supatype push")
64
- expect(!out.ok && out.message).toContain('import { createClient } from "./supatype/client"')
64
+ expect(!out.ok && out.message).toContain('import { createClient } from "./supatype/generated/client"')
65
65
  })
66
66
 
67
67
  it("says something different when the kinds are registered but the column is not", () => {
@@ -23,23 +23,21 @@ describe("quoteExactNumbers", () => {
23
23
  it("keeps a bigint past 2^53 that JSON.parse would round", () => {
24
24
  const body = '[{"views":9007199254740993}]'
25
25
  // The failure this exists to prevent, stated as an assertion.
26
- expect(JSON.parse(body)[0].views).toBe(9007199254740992)
26
+ const lossy = JSON.parse(body)
27
+ expect(lossy).toEqual([{ views: 9007199254740992 }])
27
28
 
28
- const parsed = JSON.parse(quoteExactNumbers(body, fields)) as [{ views: string }]
29
- expect(parsed[0].views).toBe("9007199254740993")
29
+ expect(JSON.parse(quoteExactNumbers(body, fields))).toEqual([{ views: "9007199254740993" }])
30
30
  })
31
31
 
32
32
  it("keeps a high-precision decimal", () => {
33
33
  const body = '[{"price":12345678901234567890.1234}]'
34
- const parsed = JSON.parse(quoteExactNumbers(body, fields)) as [{ price: string }]
35
- expect(parsed[0].price).toBe("12345678901234567890.1234")
34
+ expect(JSON.parse(quoteExactNumbers(body, fields))).toEqual([{ price: "12345678901234567890.1234" }])
36
35
  })
37
36
 
38
37
  it("keeps trailing zeros on a money amount", () => {
39
38
  // Not a value loss, but `19.0000` becoming `19` contradicts the declared `string` type.
40
39
  const body = '[{"balance":19.0000}]'
41
- const parsed = JSON.parse(quoteExactNumbers(body, fields)) as [{ balance: string }]
42
- expect(parsed[0].balance).toBe("19.0000")
40
+ expect(JSON.parse(quoteExactNumbers(body, fields))).toEqual([{ balance: "19.0000" }])
43
41
  })
44
42
 
45
43
  it("leaves columns that are not exact-value kinds alone", () => {
@@ -49,8 +47,7 @@ describe("quoteExactNumbers", () => {
49
47
 
50
48
  it("leaves null alone", () => {
51
49
  const body = '[{"views":null}]'
52
- const parsed = JSON.parse(quoteExactNumbers(body, fields)) as [{ views: null }]
53
- expect(parsed[0].views).toBeNull()
50
+ expect(JSON.parse(quoteExactNumbers(body, fields))).toEqual([{ views: null }])
54
51
  })
55
52
 
56
53
  it("leaves a value that is already a string alone", () => {
@@ -66,15 +63,12 @@ describe("quoteExactNumbers", () => {
66
63
 
67
64
  it("handles negative and exponent literals", () => {
68
65
  const body = '[{"views":-9007199254740993,"price":1.5e10}]'
69
- const parsed = JSON.parse(quoteExactNumbers(body, fields)) as [{ views: string; price: string }]
70
- expect(parsed[0].views).toBe("-9007199254740993")
71
- expect(parsed[0].price).toBe("1.5e10")
66
+ expect(JSON.parse(quoteExactNumbers(body, fields))).toEqual([{ views: "-9007199254740993", price: "1.5e10" }])
72
67
  })
73
68
 
74
69
  it("handles a single-object response as well as an array", () => {
75
70
  const body = '{"views":9007199254740993}'
76
- const parsed = JSON.parse(quoteExactNumbers(body, fields)) as { views: string }
77
- expect(parsed.views).toBe("9007199254740993")
71
+ expect(JSON.parse(quoteExactNumbers(body, fields))).toEqual({ views: "9007199254740993" })
78
72
  })
79
73
 
80
74
  it("does not touch an embedded resource", () => {
@@ -95,29 +89,24 @@ describe("quoteExactNumbers", () => {
95
89
  describe("coerceExactKinds", () => {
96
90
  it("turns a bigint column into a native bigint", () => {
97
91
  const rows = [{ views: "9007199254740993", price: "19.0000" }]
98
- const out = coerceExactKinds(rows, fields) as [{ views: bigint; price: string }]
99
- expect(out[0].views).toBe(9007199254740993n)
100
- expect(typeof out[0].views).toBe("bigint")
92
+ // `toEqual` compares with Object.is, so the string "9007199254740993" would not pass.
93
+ expect(coerceExactKinds(rows, fields)).toEqual([{ views: 9007199254740993n, price: "19.0000" }])
101
94
  })
102
95
 
103
96
  it("leaves numeric columns as exact strings", () => {
104
97
  // `@supatype/types` declares Decimal and Money as `string`. There is no native exact decimal.
105
98
  const rows = [{ price: "12345678901234567890.1234" }]
106
- const out = coerceExactKinds(rows, fields) as [{ price: string }]
107
- expect(out[0].price).toBe("12345678901234567890.1234")
99
+ expect(coerceExactKinds(rows, fields)).toEqual([{ price: "12345678901234567890.1234" }])
108
100
  })
109
101
 
110
102
  it("leaves null alone", () => {
111
- const out = coerceExactKinds([{ views: null }], fields) as [{ views: null }]
112
- expect(out[0].views).toBeNull()
103
+ expect(coerceExactKinds([{ views: null }], fields)).toEqual([{ views: null }])
113
104
  })
114
105
 
115
106
  it("round-trips the full path, wire bytes to native bigint", () => {
116
107
  const wire = '[{"views":9007199254740993,"balance":19.0000}]'
117
- const rows = JSON.parse(quoteExactNumbers(wire, fields)) as unknown
118
- const out = coerceExactKinds(rows, fields) as [{ views: bigint; balance: string }]
119
- expect(out[0].views).toBe(9007199254740993n)
120
- expect(out[0].balance).toBe("19.0000")
108
+ const rows = JSON.parse(quoteExactNumbers(wire, fields))
109
+ expect(coerceExactKinds(rows, fields)).toEqual([{ views: 9007199254740993n, balance: "19.0000" }])
121
110
  })
122
111
  })
123
112
 
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * How the client learns which columns a JSON parser would destroy.
3
3
  *
4
- * The generated `supatype/client.ts` calls `registerFieldKinds` when it is imported, and an app
4
+ * The generated `supatype/generated/client.ts` calls `registerFieldKinds` when it is imported, and an app
5
5
  * imports `createClient` from there rather than from this package. So the kinds arrive by the same
6
6
  * import that brings the client, compiled into the same bundle, with nothing fetched and nothing
7
7
  * read from disk.
@@ -66,7 +66,7 @@ describe("registerFieldKinds", () => {
66
66
  })
67
67
 
68
68
  it("ignores a version it does not understand rather than guessing", () => {
69
- registerFieldKinds({ version: 99, tables: { job_post: { views: "bigint" } } } as never)
69
+ registerFieldKinds({ version: 99, tables: { job_post: { views: "bigint" } } })
70
70
  expect(fieldKindsAreRegistered()).toBe(false)
71
71
  })
72
72
 
@@ -74,7 +74,7 @@ describe("registerFieldKinds", () => {
74
74
  registerFieldKinds({
75
75
  version: 1,
76
76
  tables: { job_post: { views: "bigint", weird: "quantum" } },
77
- } as never)
77
+ })
78
78
  expect(registeredFieldsFor("job_post")).toEqual({ views: "bigint" })
79
79
  })
80
80
  })
@@ -0,0 +1,146 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest"
2
+ import { QueryBuilder, MutationBuilder } from "../src/query.js"
3
+ import { fetchCall, fetchReturning, header, type FetchMock } from "./support/fetch-mock.js"
4
+
5
+ const BASE = "http://localhost:18473"
6
+ const PATH = "/rest/v1/posts"
7
+ const HEADERS: Record<string, string> = { apikey: "anon-key", "Content-Type": "application/json" }
8
+
9
+ interface Post { id: string; title: string; tags: string[]; meta: Record<string, unknown> }
10
+
11
+ function stubFetch(): FetchMock {
12
+ const fetch = fetchReturning([])
13
+ vi.stubGlobal("fetch", fetch)
14
+ return fetch
15
+ }
16
+
17
+ /** The filters exactly as PostgREST will read them, after URL decoding. */
18
+ function sentFilters(fetch: FetchMock): string[] {
19
+ return [...new URL(fetchCall(fetch).url).searchParams.entries()].map(([key, value]) => `${key}=${value}`)
20
+ }
21
+
22
+ describe("contains / containedBy: PostgREST operand syntax", () => {
23
+ beforeEach(() => vi.restoreAllMocks())
24
+
25
+ it("an array becomes a Postgres array literal, not JSON", async () => {
26
+ const fetch = stubFetch()
27
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS).contains("tags", ["a", "b"])
28
+ expect(sentFilters(fetch)).toEqual(["tags=cs.{a,b}"])
29
+ })
30
+
31
+ it("array elements PostgreSQL would split or misread are quoted and escaped", async () => {
32
+ const fetch = stubFetch()
33
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS).containedBy("tags", [
34
+ "plain",
35
+ "a,b",
36
+ "with space",
37
+ 'say "hi"',
38
+ "back\\slash",
39
+ "{brace}",
40
+ "",
41
+ "null",
42
+ 7,
43
+ null,
44
+ ])
45
+ expect(sentFilters(fetch)).toEqual([
46
+ 'tags=cd.{plain,"a,b","with space","say \\"hi\\"","back\\\\slash","{brace}","","null",7,NULL}',
47
+ ])
48
+ })
49
+
50
+ it("an object becomes JSON, for jsonb columns", async () => {
51
+ const fetch = stubFetch()
52
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS).contains("meta", { tier: "gold" })
53
+ expect(sentFilters(fetch)).toEqual(['meta=cs.{"tier":"gold"}'])
54
+ })
55
+
56
+ it("a string is sent as written, for range types and hand-written literals", async () => {
57
+ const fetch = stubFetch()
58
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS).containedBy("during", "[2026-01-01,2026-02-01)")
59
+ expect(sentFilters(fetch)).toEqual(["during=cd.[2026-01-01,2026-02-01)"])
60
+ })
61
+ })
62
+
63
+ describe("in(): values PostgREST would split are quoted", () => {
64
+ beforeEach(() => vi.restoreAllMocks())
65
+
66
+ it("quotes a value holding a comma or parenthesis", async () => {
67
+ const fetch = stubFetch()
68
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS).in("title", ["a,b", "c(d)", "plain", 3])
69
+ expect(sentFilters(fetch)).toEqual(['title=in.("a,b","c(d)",plain,3)'])
70
+ })
71
+ })
72
+
73
+ describe("MutationBuilder: the same filter set as QueryBuilder", () => {
74
+ beforeEach(() => vi.restoreAllMocks())
75
+
76
+ it("update can filter with every query operator", async () => {
77
+ const fetch = stubFetch()
78
+ await new MutationBuilder<Post>(BASE, PATH, HEADERS, "PATCH", { title: "x" })
79
+ .gt("views", 1)
80
+ .gte("likes", 2)
81
+ .lt("rank", 3)
82
+ .lte("score", 4)
83
+ .like("title", "%a%")
84
+ .ilike("body", "%B%")
85
+ .is("deleted_at", null)
86
+ .not("status", "eq", "draft")
87
+ .or("owner.eq.1,owner.eq.2")
88
+ .contains("tags", ["a"])
89
+ .containedBy("meta", { k: 1 })
90
+ .match({ author: "ann", lang: "en" })
91
+ expect(sentFilters(fetch)).toEqual([
92
+ "views=gt.1",
93
+ "likes=gte.2",
94
+ "rank=lt.3",
95
+ "score=lte.4",
96
+ "title=like.%a%",
97
+ "body=ilike.%B%",
98
+ "deleted_at=is.null",
99
+ "status=not.eq.draft",
100
+ "or=(owner.eq.1,owner.eq.2)",
101
+ "tags=cs.{a}",
102
+ 'meta=cd.{"k":1}',
103
+ "author=eq.ann",
104
+ "lang=eq.en",
105
+ ])
106
+ })
107
+
108
+ it("delete can filter with a range and a pattern", async () => {
109
+ const fetch = stubFetch()
110
+ await new MutationBuilder<Post>(BASE, PATH, HEADERS, "DELETE").lt("created_at", "2026-01-01").ilike("title", "tmp%")
111
+ expect(fetchCall(fetch).init.method).toBe("DELETE")
112
+ expect(sentFilters(fetch)).toEqual(["created_at=lt.2026-01-01", "title=ilike.tmp%"])
113
+ })
114
+
115
+ it("query and mutation produce identical filters for the same chain", async () => {
116
+ const queryFetch = stubFetch()
117
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS).eq("a", 1).neq("b", 2).in("c", [3, 4]).match({ d: 5 })
118
+ const query = sentFilters(queryFetch)
119
+ vi.restoreAllMocks()
120
+ const mutationFetch = stubFetch()
121
+ await new MutationBuilder<Post>(BASE, PATH, HEADERS, "DELETE").eq("a", 1).neq("b", 2).in("c", [3, 4]).match({ d: 5 })
122
+ expect(sentFilters(mutationFetch)).toEqual(query)
123
+ })
124
+ })
125
+
126
+ describe("MutationBuilder: delete().select() returns the deleted rows", () => {
127
+ beforeEach(() => vi.restoreAllMocks())
128
+
129
+ it("asks PostgREST for the representation once select() is called", async () => {
130
+ const fetch = stubFetch()
131
+ await new MutationBuilder<Post>(BASE, PATH, HEADERS, "DELETE").eq("id", "1").select("id")
132
+ expect(header(fetchCall(fetch).init, "Prefer")).toBe("return=representation")
133
+ })
134
+
135
+ it("a plain delete still asks for no body", async () => {
136
+ const fetch = stubFetch()
137
+ await new MutationBuilder<Post>(BASE, PATH, HEADERS, "DELETE").eq("id", "1")
138
+ expect(header(fetchCall(fetch).init, "Prefer")).toBeNull()
139
+ })
140
+
141
+ it("an upsert keeps both preferences, without a stray comma", async () => {
142
+ const fetch = stubFetch()
143
+ await new MutationBuilder<Post>(BASE, PATH, HEADERS, "POST", { id: "1" }, { upsert: true }).select("id")
144
+ expect(header(fetchCall(fetch).init, "Prefer")).toBe("resolution=merge-duplicates,return=representation")
145
+ })
146
+ })
@@ -0,0 +1,199 @@
1
+ /**
2
+ * pg_graphql types every json and jsonb column as its `JSON` scalar, which it serializes as a string.
3
+ * A rich text, blocks or json field therefore arrives as `"{\"root\":...}"`, and an app would have to
4
+ * know which fields to `JSON.parse`. The client knows instead: it reads the schema's field types once
5
+ * and decodes exactly the response keys whose field is a `JSON` scalar, following the query through
6
+ * aliases, fragments, nested relations and lists. A key it cannot place stays as returned.
7
+ */
8
+ import { beforeEach, describe, expect, it, vi } from "vitest"
9
+ import { createClient, decodeGraphqlJsonFields, readGraphqlSchema } from "../src/index.js"
10
+ import { fetchCalls, jsonBody, jsonResponse, mockFetch, type FetchMock } from "./support/fetch-mock.js"
11
+
12
+ type TypeRef = { kind: string; name: string | null; ofType: TypeRef | null }
13
+
14
+ const named = (kind: string, name: string): TypeRef => ({ kind, name, ofType: null })
15
+ const nonNull = (type: TypeRef): TypeRef => ({ kind: "NON_NULL", name: null, ofType: type })
16
+ const list = (type: TypeRef): TypeRef => ({ kind: "LIST", name: null, ofType: type })
17
+ const object = (name: string): TypeRef => named("OBJECT", name)
18
+ const JSON_TYPE = named("SCALAR", "JSON")
19
+ const STRING = named("SCALAR", "String")
20
+
21
+ function objectType(name: string, fields: Record<string, TypeRef>, kind = "OBJECT"): Record<string, unknown> {
22
+ return { name, kind, fields: Object.entries(fields).map(([field, type]) => ({ name: field, type })) }
23
+ }
24
+
25
+ /** The shape pg_graphql gives a `talk` table with a `speaker` relation, trimmed to what the tests use. */
26
+ const INTROSPECTION = {
27
+ data: {
28
+ __schema: {
29
+ queryType: { name: "Query" },
30
+ mutationType: { name: "Mutation" },
31
+ types: [
32
+ objectType("Query", { talkCollection: object("TalkConnection"), node: named("INTERFACE", "Node") }),
33
+ objectType("Mutation", { insertIntoTalkCollection: object("TalkInsertResponse") }),
34
+ objectType("TalkInsertResponse", { records: nonNull(list(nonNull(object("Talk")))) }),
35
+ objectType("TalkConnection", { edges: nonNull(list(nonNull(object("TalkEdge")))) }),
36
+ objectType("TalkEdge", { node: nonNull(object("Talk")) }),
37
+ objectType("Talk", {
38
+ nodeId: nonNull(named("SCALAR", "ID")),
39
+ title: STRING,
40
+ abstract: JSON_TYPE,
41
+ body: JSON_TYPE,
42
+ tags: list(JSON_TYPE),
43
+ speaker: object("Speaker"),
44
+ }),
45
+ objectType("Speaker", { name: STRING, bio: JSON_TYPE, talkCollection: object("TalkConnection") }),
46
+ objectType("Node", { nodeId: nonNull(named("SCALAR", "ID")) }, "INTERFACE"),
47
+ { name: "JSON", kind: "SCALAR", fields: null },
48
+ { name: "String", kind: "SCALAR", fields: null },
49
+ ],
50
+ },
51
+ },
52
+ }
53
+
54
+ const ABSTRACT = { root: { type: "root", children: [{ type: "paragraph", children: [] }] } }
55
+ const BLOCKS = [{ type: "quote", data: { text: "Ship it" } }]
56
+ const BIO = { en: { root: { type: "root", children: [] } } }
57
+ const encoded = (value: unknown): string => JSON.stringify(value)
58
+
59
+ let introspect: () => Response
60
+ let answer: unknown
61
+
62
+ /** A GraphQL endpoint: the schema for an introspection query, `answer` for anything else. */
63
+ function serve(): FetchMock {
64
+ const fetch = mockFetch((_input, init) => {
65
+ const query = jsonBody(init ?? {})["query"]
66
+ const isIntrospection = typeof query === "string" && query.includes("__schema")
67
+ return Promise.resolve(isIntrospection ? introspect() : jsonResponse({ data: answer }))
68
+ })
69
+ vi.stubGlobal("fetch", fetch)
70
+ return fetch
71
+ }
72
+
73
+ const client = () => createClient({ url: "http://api.test", anonKey: "anon", auth: { persistSession: false } })
74
+
75
+ beforeEach(() => {
76
+ vi.restoreAllMocks()
77
+ introspect = () => jsonResponse(INTROSPECTION)
78
+ })
79
+
80
+ describe("graphql: JSON scalar fields come back as values, not strings", () => {
81
+ it("decodes a rich text field", async () => {
82
+ serve()
83
+ answer = { talkCollection: { edges: [{ node: { title: "Keynote", abstract: encoded(ABSTRACT) } }] } }
84
+ const { data, error } = await client().graphql("{ talkCollection { edges { node { title abstract } } } }")
85
+ expect(error).toBeNull()
86
+ expect(data).toEqual({ talkCollection: { edges: [{ node: { title: "Keynote", abstract: ABSTRACT } }] } })
87
+ })
88
+
89
+ it("follows an alias to the field it names, and leaves a text field aliased to a JSON field's name alone", async () => {
90
+ serve()
91
+ answer = { talkCollection: { edges: [{ node: { summary: encoded(ABSTRACT), abstract: "{\"looks\":\"like json\"}" } }] } }
92
+ const { data } = await client().graphql("{ talkCollection { edges { node { summary: abstract abstract: title } } } }")
93
+ expect(data).toEqual({ talkCollection: { edges: [{ node: { summary: ABSTRACT, abstract: "{\"looks\":\"like json\"}" } }] } })
94
+ })
95
+
96
+ it("decodes fields selected through a named fragment and an inline fragment on an interface", async () => {
97
+ serve()
98
+ answer = { node: { nodeId: "WyJ0YWxrIl0=", abstract: encoded(ABSTRACT), body: encoded(BLOCKS) } }
99
+ const query = `query Read($id: ID!) { node(nodeId: $id) { nodeId ...TalkBody ... on Talk { abstract } } }
100
+ fragment TalkBody on Talk { body }`
101
+ const { data } = await client().graphql(query, { id: "WyJ0YWxrIl0=" })
102
+ expect(data).toEqual({ node: { nodeId: "WyJ0YWxrIl0=", abstract: ABSTRACT, body: BLOCKS } })
103
+ })
104
+
105
+ it("decodes inside a nested relation's list, and every item of a list of JSON", async () => {
106
+ serve()
107
+ const talk = { abstract: encoded(ABSTRACT), tags: [encoded({ a: 1 }), encoded("plain")] }
108
+ answer = { talkCollection: { edges: [{ node: { speaker: { bio: encoded(BIO), talkCollection: { edges: [{ node: talk }] } } } }] } }
109
+ const query = "{ talkCollection { edges { node { speaker { bio talkCollection { edges { node { abstract tags } } } } } } } }"
110
+ const { data } = await client().graphql(query)
111
+ const inner = { edges: [{ node: { abstract: ABSTRACT, tags: [{ a: 1 }, "plain"] } }] }
112
+ expect(data).toEqual({ talkCollection: { edges: [{ node: { speaker: { bio: BIO, talkCollection: inner } } }] } })
113
+ })
114
+
115
+ it("decodes the records a mutation returns", async () => {
116
+ serve()
117
+ answer = { insertIntoTalkCollection: { records: [{ abstract: encoded(ABSTRACT) }] } }
118
+ const { data } = await client().graphql("mutation { insertIntoTalkCollection(objects: [{title: \"a } b\"}]) { records { abstract } } }")
119
+ expect(data).toEqual({ insertIntoTalkCollection: { records: [{ abstract: ABSTRACT }] } })
120
+ })
121
+
122
+ it("reads past comments, block strings, arguments and directives", async () => {
123
+ serve()
124
+ answer = { talkCollection: { edges: [{ node: { abstract: encoded(ABSTRACT) } }] } }
125
+ const query = `# a comment { with a brace
126
+ query ($skip: Boolean = false) {
127
+ talkCollection(filter: { title: { eq: """a } "quoted" { b""" } }) @cached {
128
+ edges { node { abstract @skip(if: $skip) } }
129
+ }
130
+ }`
131
+ const { data } = await client().graphql(query)
132
+ expect(data).toEqual({ talkCollection: { edges: [{ node: { abstract: ABSTRACT } }] } })
133
+ })
134
+ })
135
+
136
+ describe("graphql: a field the client cannot place stays as returned", () => {
137
+ it("leaves the answer alone when the schema cannot be read", async () => {
138
+ serve()
139
+ introspect = () => jsonResponse({ message: "introspection is off" }, 403)
140
+ answer = { talkCollection: { edges: [{ node: { abstract: encoded(ABSTRACT) } }] } }
141
+ const { data, error } = await client().graphql("{ talkCollection { edges { node { abstract } } } }")
142
+ expect(error).toBeNull()
143
+ expect(data).toEqual(answer)
144
+ })
145
+
146
+ it("leaves a field the schema does not have, and reads the schema again on the next call", async () => {
147
+ const fetch = serve()
148
+ answer = { talkCollection: { edges: [{ node: { addedSincePush: encoded({ a: 1 }) } }] } }
149
+ const c = client()
150
+ const { data } = await c.graphql("{ talkCollection { edges { node { addedSincePush } } } }")
151
+ expect(data).toEqual(answer)
152
+ await c.graphql("{ talkCollection { edges { node { addedSincePush } } } }")
153
+ expect(introspections(fetch)).toBe(2)
154
+ })
155
+
156
+ it("leaves a document with more than one operation, since the server picks which runs", async () => {
157
+ serve()
158
+ answer = { talkCollection: { edges: [{ node: { abstract: encoded(ABSTRACT) } }] } }
159
+ const { data } = await client().graphql("query A { talkCollection { edges { node { abstract } } } } query B { __typename }")
160
+ expect(data).toEqual(answer)
161
+ })
162
+
163
+ it("leaves a string that is not JSON", () => {
164
+ const schema = readGraphqlSchema(INTROSPECTION.data)
165
+ if (schema === null) throw new Error("the fixture schema did not read")
166
+ const raw = { talkCollection: { edges: [{ node: { abstract: "not json" } }] } }
167
+ const decoded = decodeGraphqlJsonFields("{ talkCollection { edges { node { abstract } } } }", raw, schema)
168
+ expect(decoded).toEqual({ data: raw, schemaIsStale: false })
169
+ })
170
+ })
171
+
172
+ describe("graphql: the schema is read once, after the query", () => {
173
+ it("sends the query first and introspects once across calls", async () => {
174
+ const fetch = serve()
175
+ answer = { talkCollection: { edges: [{ node: { abstract: encoded(ABSTRACT) } }] } }
176
+ const c = client()
177
+ await c.graphql("{ talkCollection { edges { node { abstract } } } }")
178
+ await c.graphql("{ talkCollection { edges { node { abstract } } } }")
179
+ expect(introspections(fetch)).toBe(1)
180
+ expect(queryOf(fetch, 0)).not.toContain("__schema")
181
+ })
182
+
183
+ it("does not introspect for an answer with no strings in it", async () => {
184
+ const fetch = serve()
185
+ answer = { talkCollection: { edges: [] } }
186
+ await client().graphql("{ talkCollection { edges { node { abstract } } } }")
187
+ expect(introspections(fetch)).toBe(0)
188
+ })
189
+ })
190
+
191
+ function queryOf(fetch: FetchMock, n: number): string {
192
+ const call = fetchCalls(fetch)[n]
193
+ const query = call === undefined ? undefined : jsonBody(call.init)["query"]
194
+ return typeof query === "string" ? query : ""
195
+ }
196
+
197
+ function introspections(fetch: FetchMock): number {
198
+ return fetchCalls(fetch).filter((_, n) => queryOf(fetch, n).includes("__schema")).length
199
+ }
@@ -1,4 +1,5 @@
1
- import { vi } from "vitest"
1
+ import { vi, type Mock } from "vitest"
2
+ import { isJsonObject } from "../../src/json.js"
2
3
 
3
4
  /**
4
5
  * A stand-in WebSocket for the realtime suites.
@@ -17,17 +18,26 @@ export interface MockWebSocketInstance {
17
18
  onclose: ((event: CloseEvent) => void) | null
18
19
  onmessage: ((event: MessageEvent) => void) | null
19
20
  onerror: ((event: Event) => void) | null
20
- send: ReturnType<typeof vi.fn>
21
- close: ReturnType<typeof vi.fn>
21
+ /** The client only ever sends JSON text. */
22
+ send: Mock<(data: string) => void>
23
+ close: Mock<() => void>
24
+ }
25
+
26
+ /** What the realtime client uses of the WebSocket constructor: `new` and the ready states. */
27
+ export interface MockWebSocketClass {
28
+ new (url: string): MockWebSocketInstance
29
+ readonly OPEN: number
30
+ readonly CONNECTING: number
31
+ readonly CLOSED: number
22
32
  }
23
33
 
24
34
  export function createMockWebSocketClass(): {
25
- MockWebSocket: typeof WebSocket
35
+ MockWebSocket: MockWebSocketClass
26
36
  instances: MockWebSocketInstance[]
27
37
  } {
28
38
  const instances: MockWebSocketInstance[] = []
29
39
 
30
- class MockWebSocket {
40
+ class MockWebSocket implements MockWebSocketInstance {
31
41
  static OPEN = 1
32
42
  static CONNECTING = 0
33
43
  static CLOSED = 3
@@ -38,22 +48,22 @@ export function createMockWebSocketClass(): {
38
48
  onclose: ((event: CloseEvent) => void) | null = null
39
49
  onmessage: ((event: MessageEvent) => void) | null = null
40
50
  onerror: ((event: Event) => void) | null = null
41
- send = vi.fn()
42
- close = vi.fn()
51
+ send = vi.fn<(data: string) => void>()
52
+ close = vi.fn<() => void>()
43
53
 
44
54
  constructor(url: string) {
45
55
  this.url = url
46
- instances.push(this as unknown as MockWebSocketInstance)
56
+ instances.push(this)
47
57
 
48
58
  // Auto-open after a microtask
49
59
  queueMicrotask(() => {
50
60
  this.readyState = 1 // OPEN
51
- this.onopen?.({} as Event)
61
+ this.onopen?.(new Event("open"))
52
62
  })
53
63
  }
54
64
  }
55
65
 
56
- return { MockWebSocket: MockWebSocket as unknown as typeof WebSocket, instances }
66
+ return { MockWebSocket, instances }
57
67
  }
58
68
 
59
69
  /** Simulate a server message arriving on a WebSocket instance. */
@@ -61,10 +71,33 @@ export function simulateServerMessage(
61
71
  ws: MockWebSocketInstance,
62
72
  msg: Record<string, unknown>,
63
73
  ): void {
64
- ws.onmessage?.({ data: JSON.stringify(msg) } as MessageEvent)
74
+ ws.onmessage?.(new MessageEvent("message", { data: JSON.stringify(msg) }))
65
75
  }
66
76
 
67
77
  /** The token a socket was opened with, read back out of its URL. */
68
78
  export function tokenOf(ws: MockWebSocketInstance): string | null {
69
79
  return new URL(ws.url.replace(/^ws/, "http")).searchParams.get("token")
70
80
  }
81
+
82
+ /** Every frame the client sent on a socket, parsed. A frame that is not a JSON object fails the test. */
83
+ export function sentFrames(ws: MockWebSocketInstance): Array<Record<string, unknown>> {
84
+ return ws.send.mock.calls.map(([raw]) => {
85
+ const frame = JSON.parse(raw)
86
+ if (!isJsonObject(frame)) throw new Error(`the client sent a frame that is not a JSON object: ${raw}`)
87
+ return frame
88
+ })
89
+ }
90
+
91
+ /** The channels a socket was asked to join, in the order the subscribe frames went out. */
92
+ export function subscribedChannels(ws: MockWebSocketInstance): string[] {
93
+ return sentFrames(ws)
94
+ .filter((frame) => frame["type"] === "subscribe")
95
+ .map(channelOf)
96
+ }
97
+
98
+ /** The channel a frame names. Fails the test when it names none. */
99
+ export function channelOf(frame: Record<string, unknown> | undefined): string {
100
+ const channel = frame?.["channel"]
101
+ if (typeof channel !== "string") throw new Error(`the frame names no channel: ${JSON.stringify(frame)}`)
102
+ return channel
103
+ }