@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
@@ -4,6 +4,7 @@
4
4
 
5
5
  import { describe, it, expect, vi, beforeEach } from "vitest"
6
6
  import { createClient } from "../src/index.js"
7
+ import { fetchCalls, header, jsonResponse, requestUrl } from "./support/fetch-mock.js"
7
8
 
8
9
  const BASE = "http://localhost:18473"
9
10
  const ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiJ9.test"
@@ -67,29 +68,18 @@ describe("createClient data plane auth", () => {
67
68
  }
68
69
  store.set("supatype.auth.session", JSON.stringify(expiredSession))
69
70
 
70
- const fetchSpy = vi.fn(async (url: string, init?: RequestInit) => {
71
- if (url.includes("/auth/v1/token")) {
72
- return {
73
- ok: true,
74
- status: 200,
75
- json: async () => ({
76
- access_token: freshAccess,
77
- refresh_token: "rotated-refresh",
78
- token_type: "bearer",
79
- expires_in: 3600,
80
- expires_at: Math.floor(Date.now() / 1000) + 3600,
81
- user: RAW_USER,
82
- }),
83
- headers: { get: (): string | null => null },
84
- }
85
- }
86
- return {
87
- ok: true,
88
- status: 200,
89
- json: async () => [{ id: "1", title: "Hello" }],
90
- text: async () => JSON.stringify([{ id: "1", title: "Hello" }]),
91
- headers: { get: (): string | null => null },
71
+ const fetchSpy = vi.fn<typeof fetch>(async (input) => {
72
+ if (requestUrl(input).includes("/auth/v1/token")) {
73
+ return jsonResponse({
74
+ access_token: freshAccess,
75
+ refresh_token: "rotated-refresh",
76
+ token_type: "bearer",
77
+ expires_in: 3600,
78
+ expires_at: Math.floor(Date.now() / 1000) + 3600,
79
+ user: RAW_USER,
80
+ })
92
81
  }
82
+ return jsonResponse([{ id: "1", title: "Hello" }])
93
83
  })
94
84
  vi.stubGlobal("fetch", fetchSpy)
95
85
 
@@ -99,14 +89,12 @@ describe("createClient data plane auth", () => {
99
89
  expect(error).toBeNull()
100
90
  expect(data).toEqual([{ id: "1", title: "Hello" }])
101
91
 
102
- const restCall = fetchSpy.mock.calls.find(([url]) =>
103
- String(url).includes("/rest/v1/post"),
104
- ) as [string, RequestInit] | undefined
92
+ const restCall = fetchCalls(fetchSpy).find(({ url }) => url.includes("/rest/v1/post"))
105
93
  expect(restCall).toBeDefined()
106
- expect((restCall![1].headers as Record<string, string>)["Authorization"]).toBe(
94
+ expect(header(restCall?.init ?? {}, "Authorization")).toBe(
107
95
  `Bearer ${freshAccess}`,
108
96
  )
109
- expect(fetchSpy.mock.calls.some(([url]) => String(url).includes(`${AUTH}/token`))).toBe(true)
97
+ expect(fetchCalls(fetchSpy).some(({ url }) => url.includes(`${AUTH}/token`))).toBe(true)
110
98
  })
111
99
 
112
100
  it("falls back to anon headers after refresh fails", async () => {
@@ -125,22 +113,11 @@ describe("createClient data plane auth", () => {
125
113
  }
126
114
  store.set("supatype.auth.session", JSON.stringify(expiredSession))
127
115
 
128
- const fetchSpy = vi.fn(async (url: string) => {
129
- if (url.includes("/auth/v1/token")) {
130
- return {
131
- ok: false,
132
- status: 400,
133
- json: async () => ({ error_description: "Invalid Refresh Token" }),
134
- headers: { get: (): string | null => null },
135
- }
136
- }
137
- return {
138
- ok: true,
139
- status: 200,
140
- json: async () => [{ id: "1", title: "Anon ok" }],
141
- text: async () => JSON.stringify([{ id: "1", title: "Anon ok" }]),
142
- headers: { get: (): string | null => null },
116
+ const fetchSpy = vi.fn<typeof fetch>(async (input) => {
117
+ if (requestUrl(input).includes("/auth/v1/token")) {
118
+ return jsonResponse({ error_description: "Invalid Refresh Token" }, 400)
143
119
  }
120
+ return jsonResponse([{ id: "1", title: "Anon ok" }])
144
121
  })
145
122
  vi.stubGlobal("fetch", fetchSpy)
146
123
 
@@ -150,10 +127,8 @@ describe("createClient data plane auth", () => {
150
127
  expect(error).toBeNull()
151
128
  expect(data).toEqual([{ id: "1", title: "Anon ok" }])
152
129
 
153
- const restCall = fetchSpy.mock.calls.find(([url]) =>
154
- String(url).includes("/rest/v1/post"),
155
- ) as [string, RequestInit] | undefined
156
- expect((restCall![1].headers as Record<string, string>)["Authorization"]).toBe(
130
+ const restCall = fetchCalls(fetchSpy).find(({ url }) => url.includes("/rest/v1/post"))
131
+ expect(header(restCall?.init ?? {}, "Authorization")).toBe(
157
132
  `Bearer ${ANON_KEY}`,
158
133
  )
159
134
  expect(store.get("supatype.auth.session")).toBeUndefined()
@@ -0,0 +1,118 @@
1
+ import { createHmac } from "node:crypto"
2
+ import { createServer, request, type IncomingMessage, type Server, type ServerResponse } from "node:http"
3
+ import type { AddressInfo } from "node:net"
4
+ import { afterAll, beforeAll, describe, expect, it } from "vitest"
5
+ import { createClient, forgetRegisteredDraftModels, registerDraftModels, type AnyDatabase } from "../src/index.js"
6
+
7
+ /**
8
+ * An editor's insert on a drafts model whose read rule hides unpublished records, against a real
9
+ * PostgREST and Postgres.
10
+ *
11
+ * The model is `posts` from the engine's `versioned_blog` fixture with the access rules of a real
12
+ * blog: read `published_at <= now()`, create and update for the `editor` role. The caller is an API
13
+ * editor (the `authenticated` role with `app_metadata.role = "editor"`) with no Studio membership, so
14
+ * nothing shows them every draft. A plain insert asking for the row back is refused for them with
15
+ * `42501`, since Postgres checks the returned row against the read rule before anything has made it
16
+ * visible to its author; the client's insert goes through `supatype.create_record` instead.
17
+ *
18
+ * Needs `SUPATYPE_DRAFTS_REST_URL` (PostgREST's root, exposing `public`, `draft` and `supatype`)
19
+ * and `SUPATYPE_DRAFTS_JWT_SECRET` (its JWT secret), with that schema pushed by the engine. Skips
20
+ * otherwise. PostgREST serves at its root, so a small proxy here strips `/rest/v1` as the gateway
21
+ * does.
22
+ */
23
+ const restUrl = process.env["SUPATYPE_DRAFTS_REST_URL"]
24
+ const jwtSecret = process.env["SUPATYPE_DRAFTS_JWT_SECRET"]
25
+ const EDITOR = "11111111-1111-1111-1111-111111111111"
26
+
27
+ /** An HS256 token carrying `claims`, signed as the auth server signs one. */
28
+ function token(claims: Record<string, unknown>): string {
29
+ const part = (value: object): string => Buffer.from(JSON.stringify(value)).toString("base64url")
30
+ const unsigned = `${part({ alg: "HS256", typ: "JWT" })}.${part({ ...claims, exp: Math.floor(Date.now() / 1000) + 600 })}`
31
+ return `${unsigned}.${createHmac("sha256", jwtSecret ?? "").update(unsigned).digest("base64url")}`
32
+ }
33
+
34
+ const ANON_KEY = (): string => token({ role: "anon" })
35
+ const EDITOR_SESSION = (): string => token({ sub: EDITOR, role: "authenticated", app_metadata: { role: "editor" } })
36
+
37
+ /** Forward `/rest/v1/<rest>` to PostgREST's `/<rest>`, as the gateway mounts it. */
38
+ function forward(upstream: URL) {
39
+ return (req: IncomingMessage, res: ServerResponse): void => {
40
+ const path = (req.url ?? "/").replace(/^\/rest\/v1/, "")
41
+ const out = request(new URL(path, upstream), { method: req.method, headers: { ...req.headers, host: upstream.host } }, (answer) => {
42
+ res.writeHead(answer.statusCode ?? 502, answer.headers)
43
+ answer.pipe(res)
44
+ })
45
+ out.on("error", () => res.writeHead(502).end())
46
+ req.pipe(out)
47
+ }
48
+ }
49
+
50
+ describe.skipIf(restUrl === undefined || jwtSecret === undefined)("an API editor's insert on a drafts model", () => {
51
+ let proxy: Server
52
+ let base = ""
53
+
54
+ beforeAll(async () => {
55
+ proxy = createServer(forward(new URL(restUrl ?? "")))
56
+ await new Promise<void>((resolve) => proxy.listen(0, "127.0.0.1", resolve))
57
+ const address: AddressInfo | string | null = proxy.address()
58
+ base = typeof address === "object" && address !== null ? `http://127.0.0.1:${address.port}` : ""
59
+ registerDraftModels({ version: 1, tables: { posts: { primaryKey: "id" } } })
60
+ })
61
+
62
+ afterAll(async () => {
63
+ forgetRegisteredDraftModels()
64
+ await new Promise<void>((resolve) => proxy.close(() => resolve()))
65
+ })
66
+
67
+ const editor = () =>
68
+ createClient<AnyDatabase>({ url: base, anonKey: ANON_KEY(), headers: { Authorization: `Bearer ${EDITOR_SESSION()}` } })
69
+ const reader = () => createClient<AnyDatabase>({ url: base, anonKey: ANON_KEY() })
70
+
71
+ it("creates the record and returns the row an insert returns", async () => {
72
+ const title = `Written by the client ${Date.now()}`
73
+ const { data, error } = await editor()
74
+ .from("posts")
75
+ .insert({ title, body: { en: "Hello" } })
76
+ .select()
77
+ .single()
78
+
79
+ expect(error).toBeNull()
80
+ expect(data).toMatchObject({ title, body: { en: "Hello" }, published_at: null })
81
+ expect(typeof data?.["id"]).toBe("string")
82
+ })
83
+
84
+ it("leaves the record an unpublished draft: its author reads it, the public does not", async () => {
85
+ const title = `Still a draft ${Date.now()}`
86
+ const { data } = await editor().from("posts").insert({ title }).select("id").single()
87
+ const id = String(data?.["id"])
88
+
89
+ const drafted = await editor().from("posts").draft().select("title").eq("id", id)
90
+ const publicly = await reader().from("posts").select("id").eq("id", id)
91
+ expect(drafted.data).toEqual([{ title }])
92
+ expect(publicly).toMatchObject({ data: [], error: null })
93
+ })
94
+
95
+ it("creates several records in one insert and returns them in the order sent", async () => {
96
+ const stamp = Date.now()
97
+ const titles = [`Batch first ${stamp}`, `Batch second ${stamp}`]
98
+ const { data, error } = await editor()
99
+ .from("posts")
100
+ .insert(titles.map((title) => ({ title, body: { en: title } })))
101
+ .select("title, body")
102
+
103
+ expect(error).toBeNull()
104
+ expect(data).toEqual(titles.map((title) => ({ title, body: { en: title } })))
105
+ })
106
+
107
+ it("creates none of them when one is refused", async () => {
108
+ const first = `Refused batch ${Date.now()}`
109
+ const { data, error } = await editor()
110
+ .from("posts")
111
+ .insert([{ title: first }, { title: null }])
112
+
113
+ expect(data).toBeNull()
114
+ expect(error).toMatchObject({ code: "23502" })
115
+ const drafted = await editor().from("posts").draft().select("title").eq("title", first)
116
+ expect(drafted).toMatchObject({ data: [], error: null })
117
+ })
118
+ })
@@ -0,0 +1,225 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
2
+ import { createClient, forgetRegisteredDraftModels, registerDraftModels, type AnyDatabase } from "../src/index.js"
3
+ import { runMutation } from "../src/bindings.js"
4
+ import { fetchCalls, header, jsonBody, jsonResponse, mockFetch, requestUrl, type FetchMock } from "./support/fetch-mock.js"
5
+
6
+ // An insert on a model that keeps drafts is created through `supatype.create_record` and read back
7
+ // from the draft view. A plain insert asking for the row back is refused there by a read rule that
8
+ // hides unpublished records (Postgres checks the returned row against it before anything has made
9
+ // the new row visible to its author), so these pin which request goes out, and that the caller gets
10
+ // the row an insert returns.
11
+
12
+ const BASE = "http://localhost:18473"
13
+ const ID = "7b1f115e-418d-4e92-91d0-f199ebd06e5e"
14
+ const ROW = { id: ID, title: "Mine", body: { en: "hi" }, published_at: null }
15
+ const CREATED = { record_id: ID, version: 1, status: "draft", created_at: "2026-10-18T10:00:00Z" }
16
+
17
+ /** PostgREST's answer to a plain insert asking for an unpublished row back, recorded from v14.18. */
18
+ const REFUSED = { code: "42501", details: null, hint: null, message: 'new row violates row-level security policy for table "posts"' }
19
+
20
+ /**
21
+ * Answers as the database does for an editor whose read rule hides unpublished records:
22
+ * `create_record` makes the record, the draft view reads it, and a plain insert asking for the row
23
+ * back is refused.
24
+ */
25
+ function draftsServer(): FetchMock {
26
+ return mockFetch((input, init) => {
27
+ const url = requestUrl(input)
28
+ if (url.endsWith("/rest/v1/rpc/create_record")) return Promise.resolve(jsonResponse(CREATED))
29
+ if (init?.method === "POST") return Promise.resolve(jsonResponse(REFUSED, 403))
30
+ return Promise.resolve(jsonResponse([ROW]))
31
+ })
32
+ }
33
+
34
+ const ID_A = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"
35
+ const ID_B = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"
36
+
37
+ /** Postgres's refusal of a record with no title, as PostgREST passes it on. */
38
+ const NOT_NULL = { code: "23502", details: null, hint: null, message: 'null value in column "title" violates not-null constraint' }
39
+
40
+ /**
41
+ * Answers `create_records` with two new records, and the draft view with their rows in the other
42
+ * order, as a database is free to: the client must put them back in the order they were sent.
43
+ */
44
+ function batchServer(): FetchMock {
45
+ return mockFetch((input) => {
46
+ const url = requestUrl(input)
47
+ if (url.endsWith("/rest/v1/rpc/create_records")) {
48
+ return Promise.resolve(jsonResponse([{ ...CREATED, record_id: ID_A }, { ...CREATED, record_id: ID_B }]))
49
+ }
50
+ return Promise.resolve(
51
+ jsonResponse([
52
+ { title: "B", __supatype_created_key: ID_B },
53
+ { title: "A", __supatype_created_key: ID_A },
54
+ ]),
55
+ )
56
+ })
57
+ }
58
+
59
+ function serve(fetch: FetchMock): FetchMock {
60
+ vi.stubGlobal("fetch", fetch)
61
+ return fetch
62
+ }
63
+
64
+ // Untyped, as a project whose schema the test fixtures do not describe.
65
+ const client = () => createClient<AnyDatabase>({ url: BASE, anonKey: "anon-key" })
66
+
67
+ describe("insert on a model that keeps drafts", () => {
68
+ beforeEach(() => registerDraftModels({ version: 1, tables: { posts: { primaryKey: "id" } } }))
69
+ afterEach(() => {
70
+ forgetRegisteredDraftModels()
71
+ vi.unstubAllGlobals()
72
+ })
73
+
74
+ it("creates the record through supatype.create_record", async () => {
75
+ const fetch = serve(draftsServer())
76
+ await client().from("posts").insert({ title: "Mine", body: { en: "hi" } })
77
+ const [create] = fetchCalls(fetch)
78
+ expect(create?.url).toBe(`${BASE}/rest/v1/rpc/create_record`)
79
+ expect(create?.init.method).toBe("POST")
80
+ expect(header(create?.init ?? {}, "Content-Profile")).toBe("supatype")
81
+ expect(jsonBody(create?.init ?? {})).toEqual({ model_table: "posts", data: { title: "Mine", body: { en: "hi" } } })
82
+ })
83
+
84
+ it("reads the new record back from the draft view, by its key, with the insert's select", async () => {
85
+ const fetch = serve(draftsServer())
86
+ await client().from("posts").insert({ title: "Mine" }).select("id, title")
87
+ const readBack = fetchCalls(fetch)[1]
88
+ const url = new URL(readBack?.url ?? "")
89
+ expect(url.pathname).toBe("/rest/v1/posts")
90
+ expect(url.searchParams.get("id")).toBe(`in.(${ID})`)
91
+ expect(url.searchParams.get("select")).toBe("id, title")
92
+ expect(header(readBack?.init ?? {}, "Accept-Profile")).toBe("draft")
93
+ })
94
+
95
+ it("returns the row as a plain insert would", async () => {
96
+ serve(draftsServer())
97
+ const { data, error, count } = await client().from("posts").insert({ title: "Mine" })
98
+ expect(error).toBeNull()
99
+ expect(data).toEqual([ROW])
100
+ expect(count).toBe(1)
101
+ })
102
+
103
+ it("answers single() with the one row", async () => {
104
+ serve(draftsServer())
105
+ const { data, error } = await client().from("posts").insert({ title: "Mine" }).select().single()
106
+ expect(error).toBeNull()
107
+ expect(data).toEqual(ROW)
108
+ })
109
+
110
+ it("treats a one-row array as one record", async () => {
111
+ const fetch = serve(draftsServer())
112
+ const { data } = await client().from("posts").insert([{ title: "Mine" }])
113
+ expect(fetchCalls(fetch)[0]?.url).toBe(`${BASE}/rest/v1/rpc/create_record`)
114
+ expect(jsonBody(fetchCalls(fetch)[0]?.init ?? {})["data"]).toEqual({ title: "Mine" })
115
+ expect(data).toEqual([ROW])
116
+ })
117
+
118
+ it("passes create_record's refusal through and reads nothing back", async () => {
119
+ const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse(REFUSED, 403))))
120
+ const { data, error } = await client().from("posts").insert({ title: "Mine" })
121
+ expect(data).toBeNull()
122
+ expect(error).toMatchObject({ code: "42501", status: 403 })
123
+ expect(fetchCalls(fetch)).toHaveLength(1)
124
+ })
125
+
126
+ it("creates several rows in one supatype.create_records call, which is all or nothing", async () => {
127
+ const fetch = serve(batchServer())
128
+ await client().from("posts").insert([{ title: "A" }, { title: "B" }])
129
+ const [create] = fetchCalls(fetch)
130
+ expect(create?.url).toBe(`${BASE}/rest/v1/rpc/create_records`)
131
+ expect(header(create?.init ?? {}, "Content-Profile")).toBe("supatype")
132
+ expect(jsonBody(create?.init ?? {})).toEqual({ model_table: "posts", data: [{ title: "A" }, { title: "B" }] })
133
+ })
134
+
135
+ it("reads several rows back by their keys, with the insert's select and a key to order them by", async () => {
136
+ const fetch = serve(batchServer())
137
+ await client().from("posts").insert([{ title: "A" }, { title: "B" }]).select("title")
138
+ const url = new URL(fetchCalls(fetch)[1]?.url ?? "")
139
+ expect(url.searchParams.get("id")).toBe(`in.(${ID_A},${ID_B})`)
140
+ expect(url.searchParams.get("select")).toBe("title,__supatype_created_key:id")
141
+ })
142
+
143
+ it("returns several rows in the order they were sent, as the select asked for them", async () => {
144
+ serve(batchServer())
145
+ const { data, error, count } = await client().from("posts").insert([{ title: "A" }, { title: "B" }]).select("title")
146
+ expect(error).toBeNull()
147
+ expect(data).toEqual([{ title: "A" }, { title: "B" }])
148
+ expect(count).toBe(2)
149
+ })
150
+
151
+ it("passes create_records' refusal through and reads nothing back", async () => {
152
+ const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse(NOT_NULL, 400))))
153
+ const { data, error } = await client().from("posts").insert([{ title: "A" }, { title: null }])
154
+ expect(data).toBeNull()
155
+ expect(error).toMatchObject({ code: "23502", status: 400 })
156
+ expect(fetchCalls(fetch)).toHaveLength(1)
157
+ })
158
+
159
+ it("leaves an empty insert a plain write, which creates nothing", async () => {
160
+ const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse([], 201))))
161
+ const { data } = await client().from("posts").insert([])
162
+ expect(fetchCalls(fetch).map((call) => call.url)).toEqual([`${BASE}/rest/v1/posts`])
163
+ expect(data).toEqual([])
164
+ })
165
+
166
+ it("hands the caller the gateway's hint when a plain write is refused", async () => {
167
+ const hint = "This model keeps drafts: create records with supatype.create_record."
168
+ serve(mockFetch(() => Promise.resolve(jsonResponse({ ...REFUSED, hint }, 403))))
169
+ const { error } = await client().from("posts").upsert({ title: "A" })
170
+ expect(error).toMatchObject({ code: "42501", status: 403, hint })
171
+ })
172
+
173
+ it("hands the caller the detail line naming a unique violation's columns, on a write and a call", async () => {
174
+ // Studio's Duplicate learns which copied value collided from this line; it was dropped.
175
+ const details = "Key (slug)=(intro) already exists."
176
+ const UNIQUE = { code: "23505", details, hint: null, message: 'duplicate key value violates unique constraint "posts_slug_key"' }
177
+ serve(mockFetch(() => Promise.resolve(jsonResponse(UNIQUE, 409))))
178
+ const write = await client().from("posts").upsert({ title: "A" })
179
+ const call = await client().rpc("create_record", { model_table: "posts", data: {} })
180
+ expect(write.error).toMatchObject({ code: "23505", details })
181
+ expect(call.error).toMatchObject({ code: "23505", details })
182
+ })
183
+
184
+ it("leaves upsert a plain write, since create_record cannot say what a conflict does", async () => {
185
+ const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse([ROW], 201))))
186
+ await client().from("posts").upsert({ id: ID, title: "Mine" })
187
+ expect(fetchCalls(fetch).map((call) => call.url)).toEqual([`${BASE}/rest/v1/posts`])
188
+ })
189
+
190
+ it("reaches the framework bindings, which insert through runMutation", async () => {
191
+ const fetch = serve(draftsServer())
192
+ const outcome = await runMutation(client(), "posts", "insert", { title: "Mine" })
193
+ expect(fetchCalls(fetch)[0]?.url).toBe(`${BASE}/rest/v1/rpc/create_record`)
194
+ expect(outcome.data).toEqual([ROW])
195
+ })
196
+ })
197
+
198
+ describe("insert on a model that keeps no drafts", () => {
199
+ afterEach(() => {
200
+ forgetRegisteredDraftModels()
201
+ vi.unstubAllGlobals()
202
+ })
203
+
204
+ it("is a plain insert asking for the row back", async () => {
205
+ registerDraftModels({ version: 1, tables: { posts: { primaryKey: "id" } } })
206
+ const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse([{ id: 1 }], 201))))
207
+ await client().from("tags").insert({ label: "news" })
208
+ const [only] = fetchCalls(fetch)
209
+ expect(only?.url).toBe(`${BASE}/rest/v1/tags`)
210
+ expect(header(only?.init ?? {}, "Prefer")).toContain("return=representation")
211
+ })
212
+
213
+ it("is a plain insert when nothing was registered, as for a client built without the generated file", async () => {
214
+ const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse([ROW], 201))))
215
+ await client().from("posts").insert({ title: "Mine" })
216
+ expect(fetchCalls(fetch).map((call) => call.url)).toEqual([`${BASE}/rest/v1/posts`])
217
+ })
218
+
219
+ it("ignores a document from a newer generator", async () => {
220
+ registerDraftModels({ version: 2, tables: { posts: { primaryKey: "id" } } })
221
+ const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse([ROW], 201))))
222
+ await client().from("posts").insert({ title: "Mine" })
223
+ expect(fetchCalls(fetch).map((call) => call.url)).toEqual([`${BASE}/rest/v1/posts`])
224
+ })
225
+ })