@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.
- package/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +69 -30
- package/.turbo/turbo-typecheck.log +2 -2
- package/LICENSE +1 -1
- package/dist/auth-redirect.d.ts +48 -0
- package/dist/auth-redirect.d.ts.map +1 -0
- package/dist/auth-redirect.js +70 -0
- package/dist/auth-redirect.js.map +1 -0
- package/dist/auth.d.ts +86 -4
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +383 -275
- package/dist/auth.js.map +1 -1
- package/dist/bindings.d.ts +16 -0
- package/dist/bindings.d.ts.map +1 -0
- package/dist/bindings.js +13 -0
- package/dist/bindings.js.map +1 -0
- package/dist/caller-types.d.ts +18 -0
- package/dist/caller-types.d.ts.map +1 -0
- package/dist/caller-types.js +22 -0
- package/dist/caller-types.js.map +1 -0
- package/dist/draft-create.d.ts +12 -0
- package/dist/draft-create.d.ts.map +1 -0
- package/dist/draft-create.js +47 -0
- package/dist/draft-create.js.map +1 -0
- package/dist/draft-models-registry.d.ts +27 -0
- package/dist/draft-models-registry.d.ts.map +1 -0
- package/dist/draft-models-registry.js +61 -0
- package/dist/draft-models-registry.js.map +1 -0
- package/dist/error-codes-doc.d.ts +1 -1
- package/dist/error-codes-doc.d.ts.map +1 -1
- package/dist/error-codes-doc.js +42 -34
- package/dist/error-codes-doc.js.map +1 -1
- package/dist/errors.d.ts +102 -60
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +69 -28
- package/dist/errors.js.map +1 -1
- package/dist/exact-response.d.ts.map +1 -1
- package/dist/exact-response.js +2 -1
- package/dist/exact-response.js.map +1 -1
- package/dist/exact-values.d.ts +2 -0
- package/dist/exact-values.d.ts.map +1 -1
- package/dist/exact-values.js +12 -10
- package/dist/exact-values.js.map +1 -1
- package/dist/fetch-with-retry.d.ts +21 -6
- package/dist/fetch-with-retry.d.ts.map +1 -1
- package/dist/fetch-with-retry.js +67 -53
- package/dist/fetch-with-retry.js.map +1 -1
- package/dist/field-kinds-registry.d.ts +11 -3
- package/dist/field-kinds-registry.d.ts.map +1 -1
- package/dist/field-kinds-registry.js +10 -6
- package/dist/field-kinds-registry.js.map +1 -1
- package/dist/filters.d.ts +51 -0
- package/dist/filters.d.ts.map +1 -0
- package/dist/filters.js +117 -0
- package/dist/filters.js.map +1 -0
- package/dist/generated-client.d.ts +7 -0
- package/dist/generated-client.d.ts.map +1 -0
- package/dist/generated-client.js +7 -0
- package/dist/generated-client.js.map +1 -0
- package/dist/graphql-document.d.ts +39 -0
- package/dist/graphql-document.d.ts.map +1 -0
- package/dist/graphql-document.js +228 -0
- package/dist/graphql-document.js.map +1 -0
- package/dist/graphql-json.d.ts +56 -0
- package/dist/graphql-json.d.ts.map +1 -0
- package/dist/graphql-json.js +220 -0
- package/dist/graphql-json.js.map +1 -0
- package/dist/graphql-transport.d.ts +28 -0
- package/dist/graphql-transport.d.ts.map +1 -0
- package/dist/graphql-transport.js +77 -0
- package/dist/graphql-transport.js.map +1 -0
- package/dist/index.d.ts +103 -40
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +170 -165
- package/dist/index.js.map +1 -1
- package/dist/json.d.ts +61 -0
- package/dist/json.d.ts.map +1 -0
- package/dist/json.js +83 -0
- package/dist/json.js.map +1 -0
- package/dist/jwt.d.ts +16 -0
- package/dist/jwt.d.ts.map +1 -0
- package/dist/jwt.js +37 -0
- package/dist/jwt.js.map +1 -0
- package/dist/live-preview.d.ts +23 -0
- package/dist/live-preview.d.ts.map +1 -0
- package/dist/live-preview.js +28 -0
- package/dist/live-preview.js.map +1 -0
- package/dist/mutation-request.d.ts +17 -0
- package/dist/mutation-request.d.ts.map +1 -0
- package/dist/mutation-request.js +41 -0
- package/dist/mutation-request.js.map +1 -0
- package/dist/preview.d.ts.map +1 -1
- package/dist/preview.js +8 -6
- package/dist/preview.js.map +1 -1
- package/dist/query-cache.d.ts.map +1 -1
- package/dist/query-cache.js +19 -13
- package/dist/query-cache.js.map +1 -1
- package/dist/query.d.ts +108 -29
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +294 -224
- package/dist/query.js.map +1 -1
- package/dist/realtime.d.ts +57 -2
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +300 -88
- package/dist/realtime.js.map +1 -1
- package/dist/select-types.d.ts +99 -0
- package/dist/select-types.d.ts.map +1 -0
- package/dist/select-types.js +2 -0
- package/dist/select-types.js.map +1 -0
- package/dist/storage.d.ts +81 -11
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +137 -38
- package/dist/storage.js.map +1 -1
- package/dist/table-subscription.d.ts +69 -0
- package/dist/table-subscription.d.ts.map +1 -0
- package/dist/table-subscription.js +93 -0
- package/dist/table-subscription.js.map +1 -0
- package/dist/types.d.ts +98 -5
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +6 -1
- package/dist/types.js.map +1 -1
- package/package.json +6 -2
- package/src/auth-redirect.ts +90 -0
- package/src/auth.ts +434 -281
- package/src/bindings.ts +22 -0
- package/src/caller-types.ts +27 -0
- package/src/draft-create.ts +51 -0
- package/src/draft-models-registry.ts +81 -0
- package/src/error-codes-doc.ts +44 -35
- package/src/errors.ts +72 -28
- package/src/exact-response.ts +2 -1
- package/src/exact-values.ts +16 -9
- package/src/fetch-with-retry.ts +80 -70
- package/src/field-kinds-registry.ts +22 -9
- package/src/filters.ts +133 -0
- package/src/generated-client.ts +6 -0
- package/src/graphql-document.ts +234 -0
- package/src/graphql-json.ts +243 -0
- package/src/graphql-transport.ts +97 -0
- package/src/index.ts +289 -208
- package/src/json.ts +117 -0
- package/src/jwt.ts +37 -0
- package/src/live-preview.ts +37 -0
- package/src/mutation-request.ts +66 -0
- package/src/preview.ts +9 -11
- package/src/query-cache.ts +19 -16
- package/src/query.ts +389 -270
- package/src/realtime.ts +333 -90
- package/src/select-types.ts +184 -0
- package/src/storage.ts +223 -44
- package/src/table-subscription.ts +160 -0
- package/src/types.ts +104 -5
- package/tests/auth-error-codes.test.ts +53 -0
- package/tests/auth-errors.test.ts +84 -0
- package/tests/auth-events.test.ts +136 -0
- package/tests/auth-url-session.test.ts +204 -0
- package/tests/auth.test.ts +187 -26
- package/tests/count.test.ts +60 -0
- package/tests/data-plane-auth.test.ts +21 -46
- package/tests/draft-insert.integration.test.ts +118 -0
- package/tests/draft-insert.test.ts +225 -0
- package/tests/draft-profile.test.ts +55 -84
- package/tests/draft-update.integration.test.ts +122 -0
- package/tests/draft-update.test.ts +174 -0
- package/tests/dynamic-headers.test.ts +45 -0
- package/tests/entry-points.test.ts +42 -0
- package/tests/exact-response.test.ts +4 -4
- package/tests/exact-values.test.ts +14 -25
- package/tests/field-kinds-registry.test.ts +3 -3
- package/tests/filters.test.ts +146 -0
- package/tests/graphql-json.test.ts +199 -0
- package/tests/helpers/mock-websocket.ts +44 -11
- package/tests/helpers/oauth-binding.ts +92 -0
- package/tests/helpers/signup-binding.ts +73 -0
- package/tests/helpers/socket-swap.ts +142 -0
- package/tests/mfa-totp-integration.test.ts +13 -20
- package/tests/postgrest-error-codes.test.ts +85 -0
- package/tests/query-cache.test.ts +116 -117
- package/tests/query.test.ts +29 -31
- package/tests/rate-limit-integration.test.ts +4 -12
- package/tests/realtime-ack-ref.test.ts +112 -0
- package/tests/realtime-exact-values.test.ts +2 -4
- package/tests/realtime-presence.test.ts +75 -0
- package/tests/realtime-session-auth.test.ts +2 -4
- package/tests/realtime-shared-channel.test.ts +209 -0
- package/tests/realtime-swap-status.test.ts +62 -0
- package/tests/retry-integration.test.ts +3 -8
- package/tests/retry-policy.test.ts +166 -0
- package/tests/rpc-resend.test.ts +24 -0
- package/tests/server-bodies.test.ts +187 -0
- package/tests/serverless.test.ts +2 -2
- package/tests/signed-url-absolute.test.ts +2 -5
- package/tests/storage-object-shape.test.ts +101 -0
- package/tests/storage-quota-integration.test.ts +7 -9
- package/tests/storage-reference-url.test.ts +51 -0
- package/tests/storage-upload-browser.test.ts +71 -0
- package/tests/storage-upload-limit-integration.test.ts +17 -31
- package/tests/storage-url-encoding.test.ts +52 -0
- package/tests/subscribe-frame.test.ts +5 -11
- package/tests/support/blob.ts +10 -0
- package/tests/support/fetch-mock.ts +64 -0
- package/tests/support/storage-object.ts +37 -0
- package/tests/table-subscribe.test.ts +41 -14
- package/tests/table-subscription.test.ts +105 -0
- package/tests/table-transport.test.ts +94 -0
- package/tests/tsconfig.json +1 -1
- package/tests/types.test.ts +153 -1
- package/tsconfig.json +1 -1
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest"
|
|
|
2
2
|
import { QueryBuilder } from "../src/query.js"
|
|
3
3
|
import { DRAFT_SCHEMA } from "../src/types.js"
|
|
4
4
|
import { createClient } from "../src/index.js"
|
|
5
|
+
import { fetchCall, fetchCalls, fetchReturning, header, jsonResponse, requestUrl } from "./support/fetch-mock.js"
|
|
5
6
|
|
|
6
7
|
// Reading a draft changes one thing about the request: which schema answers it. Same table name,
|
|
7
8
|
// same row type, one header. These tests pin that the header is actually sent, because a silently
|
|
@@ -10,25 +11,11 @@ import { createClient } from "../src/index.js"
|
|
|
10
11
|
const BASE = "http://localhost:18473"
|
|
11
12
|
const HEADERS: Record<string, string> = { apikey: "anon-key" }
|
|
12
13
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
fetch
|
|
16
|
-
} {
|
|
17
|
-
const fetch = vi.fn().mockResolvedValue({
|
|
18
|
-
ok: true,
|
|
19
|
-
status: 200,
|
|
20
|
-
json: vi.fn().mockResolvedValue([]),
|
|
21
|
-
text: vi.fn().mockResolvedValue("[]"),
|
|
22
|
-
headers: { get: () => null },
|
|
23
|
-
})
|
|
14
|
+
/** A fetch answering every request with no rows, and a reader for the first request's headers. */
|
|
15
|
+
function captureHeaders(): { header: (name: string) => string | null } {
|
|
16
|
+
const fetch = fetchReturning([])
|
|
24
17
|
vi.stubGlobal("fetch", fetch)
|
|
25
|
-
return {
|
|
26
|
-
fetch,
|
|
27
|
-
headers: () => {
|
|
28
|
-
const init = (fetch.mock.calls[0] as [string, { headers: Record<string, string> }])[1]
|
|
29
|
-
return init.headers
|
|
30
|
-
},
|
|
31
|
-
}
|
|
18
|
+
return { header: (name) => header(fetchCall(fetch).init, name) }
|
|
32
19
|
}
|
|
33
20
|
|
|
34
21
|
const SESSION_JWT =
|
|
@@ -44,20 +31,20 @@ describe("the draft profile", () => {
|
|
|
44
31
|
await new QueryBuilder(BASE, "/rest/v1/posts", HEADERS, "id", undefined, undefined, {
|
|
45
32
|
profile: DRAFT_SCHEMA,
|
|
46
33
|
})
|
|
47
|
-
expect(captured.
|
|
34
|
+
expect(captured.header("Accept-Profile")).toBe("draft")
|
|
48
35
|
})
|
|
49
36
|
|
|
50
37
|
it("is absent from an ordinary read, so published content is what a caller gets by default", async () => {
|
|
51
38
|
const captured = captureHeaders()
|
|
52
39
|
await new QueryBuilder(BASE, "/rest/v1/posts", HEADERS, "id")
|
|
53
|
-
expect(captured.
|
|
40
|
+
expect(captured.header("Accept-Profile")).toBeNull()
|
|
54
41
|
})
|
|
55
42
|
|
|
56
43
|
it("reaches the request through `from().draft().select()`", async () => {
|
|
57
44
|
const captured = captureHeaders()
|
|
58
45
|
const client = createClient({ url: BASE, anonKey: "anon-key" })
|
|
59
46
|
await client.from("posts").draft().select("id, title")
|
|
60
|
-
expect(captured.
|
|
47
|
+
expect(captured.header("Accept-Profile")).toBe("draft")
|
|
61
48
|
})
|
|
62
49
|
|
|
63
50
|
it("does not leak onto the next query from the same client", async () => {
|
|
@@ -67,12 +54,12 @@ describe("the draft profile", () => {
|
|
|
67
54
|
const client = createClient({ url: BASE, anonKey: "anon-key" })
|
|
68
55
|
const drafted = captureHeaders()
|
|
69
56
|
await client.from("posts").draft().select("id")
|
|
70
|
-
expect(drafted.
|
|
57
|
+
expect(drafted.header("Accept-Profile")).toBe("draft")
|
|
71
58
|
|
|
72
59
|
vi.restoreAllMocks()
|
|
73
60
|
const plain = captureHeaders()
|
|
74
61
|
await client.from("posts").select("id")
|
|
75
|
-
expect(plain.
|
|
62
|
+
expect(plain.header("Accept-Profile")).toBeNull()
|
|
76
63
|
})
|
|
77
64
|
|
|
78
65
|
it("leaves the count header alone, since a draft read can still be counted", async () => {
|
|
@@ -81,8 +68,8 @@ describe("the draft profile", () => {
|
|
|
81
68
|
profile: DRAFT_SCHEMA,
|
|
82
69
|
count: "exact",
|
|
83
70
|
})
|
|
84
|
-
expect(captured.
|
|
85
|
-
expect(captured.
|
|
71
|
+
expect(captured.header("Accept-Profile")).toBe("draft")
|
|
72
|
+
expect(captured.header("Prefer")).toBe("count=exact")
|
|
86
73
|
})
|
|
87
74
|
})
|
|
88
75
|
|
|
@@ -96,15 +83,15 @@ describe("calling a function outside the default schema", () => {
|
|
|
96
83
|
// mistake.
|
|
97
84
|
const captured = captureHeaders()
|
|
98
85
|
const client = createClient({ url: BASE, anonKey: "anon-key" })
|
|
99
|
-
await client.rpc("publish"
|
|
100
|
-
expect(captured.
|
|
86
|
+
await client.rpc("publish", { model_table: "posts" }, { schema: "supatype" })
|
|
87
|
+
expect(captured.header("Content-Profile")).toBe("supatype")
|
|
101
88
|
})
|
|
102
89
|
|
|
103
90
|
it("sends none for a function in the default schema", async () => {
|
|
104
91
|
const captured = captureHeaders()
|
|
105
92
|
const client = createClient({ url: BASE, anonKey: "anon-key" })
|
|
106
|
-
await client.rpc("calculate_shipping"
|
|
107
|
-
expect(captured.
|
|
93
|
+
await client.rpc("calculate_shipping", {})
|
|
94
|
+
expect(captured.header("Content-Profile")).toBeNull()
|
|
108
95
|
})
|
|
109
96
|
})
|
|
110
97
|
|
|
@@ -119,43 +106,32 @@ describe("a preview link as the client's credential", () => {
|
|
|
119
106
|
* these tests care about is on the *second* request, not the first.
|
|
120
107
|
*/
|
|
121
108
|
function previewFetch(exchange: { ok: boolean; token?: string; expiresAt?: string }): {
|
|
122
|
-
|
|
123
|
-
|
|
109
|
+
queryHeaders: () => string[]
|
|
110
|
+
queryHeader: (name: string) => string | null
|
|
124
111
|
exchanges: () => number
|
|
125
112
|
} {
|
|
126
|
-
const
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
json: () =>
|
|
132
|
-
Promise.resolve(
|
|
133
|
-
exchange.ok
|
|
134
|
-
? { token: exchange.token, expiresAt: exchange.expiresAt }
|
|
135
|
-
: { error: "gone" },
|
|
136
|
-
),
|
|
137
|
-
headers: { get: () => null },
|
|
138
|
-
})
|
|
113
|
+
const isExchange = (url: string): boolean => url.endsWith("/preview-links/resolve")
|
|
114
|
+
const fetchMock = vi.fn<typeof fetch>((input) => {
|
|
115
|
+
if (isExchange(requestUrl(input))) {
|
|
116
|
+
const body = exchange.ok ? { token: exchange.token, expiresAt: exchange.expiresAt } : { error: "gone" }
|
|
117
|
+
return Promise.resolve(jsonResponse(body, exchange.ok ? 200 : 404))
|
|
139
118
|
}
|
|
140
|
-
return Promise.resolve(
|
|
141
|
-
ok: true,
|
|
142
|
-
status: 200,
|
|
143
|
-
json: () => Promise.resolve([]),
|
|
144
|
-
text: () => Promise.resolve("[]"),
|
|
145
|
-
headers: { get: () => null },
|
|
146
|
-
})
|
|
119
|
+
return Promise.resolve(jsonResponse([]))
|
|
147
120
|
})
|
|
148
|
-
vi.stubGlobal("fetch",
|
|
149
|
-
const
|
|
150
|
-
|
|
121
|
+
vi.stubGlobal("fetch", fetchMock)
|
|
122
|
+
const queryInit = (): RequestInit => {
|
|
123
|
+
const call = fetchCalls(fetchMock).find(({ url }) => !isExchange(url))
|
|
124
|
+
if (call === undefined) throw new Error("no query was made")
|
|
125
|
+
return call.init
|
|
126
|
+
}
|
|
151
127
|
return {
|
|
152
|
-
|
|
153
|
-
exchanges: () => calls().filter(([url]) => url.endsWith("/preview-links/resolve")).length,
|
|
128
|
+
exchanges: () => fetchCalls(fetchMock).filter(({ url }) => isExchange(url)).length,
|
|
154
129
|
queryHeaders: () => {
|
|
155
|
-
const
|
|
156
|
-
|
|
157
|
-
return
|
|
130
|
+
const lines: string[] = []
|
|
131
|
+
new Headers(queryInit().headers).forEach((value, name) => lines.push(`${name}: ${value}`))
|
|
132
|
+
return lines
|
|
158
133
|
},
|
|
134
|
+
queryHeader: (name) => header(queryInit(), name),
|
|
159
135
|
}
|
|
160
136
|
}
|
|
161
137
|
|
|
@@ -165,7 +141,7 @@ describe("a preview link as the client's credential", () => {
|
|
|
165
141
|
const f = previewFetch({ ok: true, token: "exchanged.jwt", expiresAt: anHour() })
|
|
166
142
|
const client = createClient({ url: BASE, anonKey: "anon-key", previewCode: "pl_abc.secret" })
|
|
167
143
|
await client.from("posts").draft().select("id")
|
|
168
|
-
expect(f.
|
|
144
|
+
expect(f.queryHeader("Authorization")).toBe("Bearer exchanged.jwt")
|
|
169
145
|
})
|
|
170
146
|
|
|
171
147
|
it("never puts the code itself on the query", async () => {
|
|
@@ -181,7 +157,7 @@ describe("a preview link as the client's credential", () => {
|
|
|
181
157
|
const f = previewFetch({ ok: true, token: "exchanged.jwt", expiresAt: anHour() })
|
|
182
158
|
const client = createClient({ url: BASE, anonKey: "anon-key", previewCode: "pl_abc.secret" })
|
|
183
159
|
await client.from("posts").draft().select("id")
|
|
184
|
-
expect(f.
|
|
160
|
+
expect(f.queryHeader("apikey")).toBe("anon-key")
|
|
185
161
|
})
|
|
186
162
|
|
|
187
163
|
it("exchanges once for several queries in flight together", async () => {
|
|
@@ -235,13 +211,13 @@ describe("a preview link as the client's credential", () => {
|
|
|
235
211
|
const captured = captureHeaders()
|
|
236
212
|
const client = createClient({ url: BASE, anonKey: "anon-key" })
|
|
237
213
|
await client.from("posts").select("id")
|
|
238
|
-
expect(captured.
|
|
214
|
+
expect(captured.header("Authorization")).toBe("Bearer anon-key")
|
|
239
215
|
})
|
|
240
216
|
})
|
|
241
217
|
|
|
242
218
|
describe("what storage sends as its credential", () => {
|
|
243
|
-
// Storage was handed a plain headers object built when the client was constructed
|
|
244
|
-
// anybody
|
|
219
|
+
// Storage was handed a plain headers object built when the client was constructed, before
|
|
220
|
+
// anybody had signed in. Every storage request therefore carried the anon key for the life of the
|
|
245
221
|
// page: an app's per-user storage policies saw `anon` rather than the caller, and through Studio's
|
|
246
222
|
// proxy the request was refused outright, because an anon key carries no `sub` and the proxy
|
|
247
223
|
// requires one. The symptom was "Token missing subject claim" on a page that lists buckets.
|
|
@@ -249,19 +225,18 @@ describe("what storage sends as its credential", () => {
|
|
|
249
225
|
// Every other client on the object already resolved its headers per request. Storage was the one
|
|
250
226
|
// that did not.
|
|
251
227
|
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
headers: { get: () => null },
|
|
259
|
-
})
|
|
228
|
+
/** A fetch that knows the signed-in user and has no buckets, and the bucket request's headers. */
|
|
229
|
+
function captureHeaders(): { header: (name: string) => string | null } {
|
|
230
|
+
const isUser = (url: string): boolean => url.endsWith("/auth/v1/user")
|
|
231
|
+
const fetchMock = vi.fn<typeof fetch>((input) =>
|
|
232
|
+
Promise.resolve(jsonResponse(isUser(requestUrl(input)) ? { id: "u1", role: "authenticated" } : [])),
|
|
233
|
+
)
|
|
260
234
|
vi.stubGlobal("fetch", fetchMock)
|
|
261
235
|
return {
|
|
262
|
-
|
|
263
|
-
const call = fetchMock.
|
|
264
|
-
|
|
236
|
+
header: (name) => {
|
|
237
|
+
const call = fetchCalls(fetchMock).find(({ url }) => !isUser(url))
|
|
238
|
+
if (call === undefined) throw new Error("storage made no request")
|
|
239
|
+
return header(call.init, name)
|
|
265
240
|
},
|
|
266
241
|
}
|
|
267
242
|
}
|
|
@@ -271,22 +246,18 @@ describe("what storage sends as its credential", () => {
|
|
|
271
246
|
const client = createClient({ url: BASE, anonKey: "anon-key" })
|
|
272
247
|
// A session arriving after construction, which is the ordinary case: the client is built while
|
|
273
248
|
// the page loads and the person signs in afterwards.
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
refreshToken: "r",
|
|
277
|
-
expiresAt: Math.floor(Date.now() / 1000) + 3600,
|
|
278
|
-
user: { id: "u1" },
|
|
279
|
-
}
|
|
249
|
+
const { error } = await client.auth.setSession({ accessToken: SESSION_JWT, refreshToken: "r" })
|
|
250
|
+
expect(error).toBeNull()
|
|
280
251
|
|
|
281
252
|
await client.storage.listBuckets()
|
|
282
|
-
expect(captured.
|
|
253
|
+
expect(captured.header("Authorization")).toBe(`Bearer ${SESSION_JWT}`)
|
|
283
254
|
})
|
|
284
255
|
|
|
285
256
|
it("falls back to the anon key when nobody is signed in", async () => {
|
|
286
257
|
const captured = captureHeaders()
|
|
287
258
|
const client = createClient({ url: BASE, anonKey: "anon-key" })
|
|
288
259
|
await client.storage.listBuckets()
|
|
289
|
-
expect(captured.
|
|
260
|
+
expect(captured.header("Authorization")).toBe("Bearer anon-key")
|
|
290
261
|
})
|
|
291
262
|
|
|
292
263
|
it("uses the service role when the caller holds one", async () => {
|
|
@@ -294,6 +265,6 @@ describe("what storage sends as its credential", () => {
|
|
|
294
265
|
const captured = captureHeaders()
|
|
295
266
|
const client = createClient({ url: BASE, anonKey: "anon-key", serviceRoleKey: "service.jwt" })
|
|
296
267
|
await client.storage.listBuckets()
|
|
297
|
-
expect(captured.
|
|
268
|
+
expect(captured.header("Authorization")).toBe("Bearer service.jwt")
|
|
298
269
|
})
|
|
299
270
|
})
|
|
@@ -0,0 +1,122 @@
|
|
|
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 update on a drafts model, against a real PostgREST and Postgres.
|
|
9
|
+
*
|
|
10
|
+
* The same setup as `draft-insert.integration.test.ts`: `posts` from the engine's `versioned_blog`
|
|
11
|
+
* fixture with read `published_at <= now()` and create and update for the `editor` role, and an API
|
|
12
|
+
* editor with no Studio membership. The update saves a draft and the public keeps reading what was
|
|
13
|
+
* published, until the update asks to publish; a raw `PATCH` of the table is refused by the database.
|
|
14
|
+
*
|
|
15
|
+
* Needs `SUPATYPE_DRAFTS_REST_URL` and `SUPATYPE_DRAFTS_JWT_SECRET`, as that suite does. Skips
|
|
16
|
+
* otherwise.
|
|
17
|
+
*/
|
|
18
|
+
const restUrl = process.env["SUPATYPE_DRAFTS_REST_URL"]
|
|
19
|
+
const jwtSecret = process.env["SUPATYPE_DRAFTS_JWT_SECRET"]
|
|
20
|
+
const EDITOR = "11111111-1111-1111-1111-111111111111"
|
|
21
|
+
|
|
22
|
+
/** An HS256 token carrying `claims`, signed as the auth server signs one. */
|
|
23
|
+
function token(claims: Record<string, unknown>): string {
|
|
24
|
+
const part = (value: object): string => Buffer.from(JSON.stringify(value)).toString("base64url")
|
|
25
|
+
const unsigned = `${part({ alg: "HS256", typ: "JWT" })}.${part({ ...claims, exp: Math.floor(Date.now() / 1000) + 600 })}`
|
|
26
|
+
return `${unsigned}.${createHmac("sha256", jwtSecret ?? "").update(unsigned).digest("base64url")}`
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const ANON_KEY = (): string => token({ role: "anon" })
|
|
30
|
+
const EDITOR_SESSION = (): string => token({ sub: EDITOR, role: "authenticated", app_metadata: { role: "editor" } })
|
|
31
|
+
|
|
32
|
+
/** Forward `/rest/v1/<rest>` to PostgREST's `/<rest>`, as the gateway mounts it. */
|
|
33
|
+
function forward(upstream: URL) {
|
|
34
|
+
return (req: IncomingMessage, res: ServerResponse): void => {
|
|
35
|
+
const path = (req.url ?? "/").replace(/^\/rest\/v1/, "")
|
|
36
|
+
const out = request(new URL(path, upstream), { method: req.method, headers: { ...req.headers, host: upstream.host } }, (answer) => {
|
|
37
|
+
res.writeHead(answer.statusCode ?? 502, answer.headers)
|
|
38
|
+
answer.pipe(res)
|
|
39
|
+
})
|
|
40
|
+
out.on("error", () => res.writeHead(502).end())
|
|
41
|
+
req.pipe(out)
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
describe.skipIf(restUrl === undefined || jwtSecret === undefined)("an API editor's update on a drafts model", () => {
|
|
46
|
+
let proxy: Server
|
|
47
|
+
let base = ""
|
|
48
|
+
|
|
49
|
+
beforeAll(async () => {
|
|
50
|
+
proxy = createServer(forward(new URL(restUrl ?? "")))
|
|
51
|
+
await new Promise<void>((resolve) => proxy.listen(0, "127.0.0.1", resolve))
|
|
52
|
+
const address: AddressInfo | string | null = proxy.address()
|
|
53
|
+
base = typeof address === "object" && address !== null ? `http://127.0.0.1:${address.port}` : ""
|
|
54
|
+
registerDraftModels({ version: 1, tables: { posts: { primaryKey: "id" } } })
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
afterAll(async () => {
|
|
58
|
+
forgetRegisteredDraftModels()
|
|
59
|
+
await new Promise<void>((resolve) => proxy.close(() => resolve()))
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
const editor = () =>
|
|
63
|
+
createClient<AnyDatabase>({ url: base, anonKey: ANON_KEY(), headers: { Authorization: `Bearer ${EDITOR_SESSION()}` } })
|
|
64
|
+
const reader = () => createClient<AnyDatabase>({ url: base, anonKey: ANON_KEY() })
|
|
65
|
+
|
|
66
|
+
/** A post the editor has created and published, by its id. */
|
|
67
|
+
async function publishedPost(title: string): Promise<string> {
|
|
68
|
+
const { data } = await editor().from("posts").insert({ title }).select("id").single()
|
|
69
|
+
const id = String(data?.["id"])
|
|
70
|
+
const published = await editor().rpc("publish", { model_table: "posts", record_id: id }, { schema: "supatype" })
|
|
71
|
+
expect(published.error).toBeNull()
|
|
72
|
+
return id
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
it("saves a draft, returns it, and leaves what the public reads alone", async () => {
|
|
76
|
+
const stamp = Date.now()
|
|
77
|
+
const id = await publishedPost(`Published ${stamp}`)
|
|
78
|
+
|
|
79
|
+
const { data, error } = await editor().from("posts").update({ title: `Draft ${stamp}` }).eq("id", id).select("title")
|
|
80
|
+
|
|
81
|
+
expect(error).toBeNull()
|
|
82
|
+
expect(data).toEqual([{ title: `Draft ${stamp}` }])
|
|
83
|
+
const publicly = await reader().from("posts").select("title").eq("id", id)
|
|
84
|
+
expect(publicly).toMatchObject({ data: [{ title: `Published ${stamp}` }], error: null })
|
|
85
|
+
const drafted = await editor().from("posts").draft().select("title").eq("id", id)
|
|
86
|
+
expect(drafted.data).toEqual([{ title: `Draft ${stamp}` }])
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
it("publishes in the same call with { publish: true }, so the public reads the new version", async () => {
|
|
90
|
+
const stamp = Date.now()
|
|
91
|
+
const id = await publishedPost(`Before ${stamp}`)
|
|
92
|
+
|
|
93
|
+
const { error } = await editor().from("posts").update({ title: `After ${stamp}` }, { publish: true }).eq("id", id)
|
|
94
|
+
|
|
95
|
+
expect(error).toBeNull()
|
|
96
|
+
const publicly = await reader().from("posts").select("title").eq("id", id)
|
|
97
|
+
expect(publicly).toMatchObject({ data: [{ title: `After ${stamp}` }], error: null })
|
|
98
|
+
// Recorded as a version, which is what the draft view reads, and that version is the live one.
|
|
99
|
+
const newest = await editor().from("posts").draft().select("title").eq("id", id)
|
|
100
|
+
expect(newest.data).toEqual([{ title: `After ${stamp}` }])
|
|
101
|
+
const again = await editor().rpc("publish", { model_table: "posts", record_id: id }, { schema: "supatype" })
|
|
102
|
+
expect(again.error?.message).toContain("is already live")
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
it("is refused as a raw PATCH, naming drafts and publish", async () => {
|
|
106
|
+
const stamp = Date.now()
|
|
107
|
+
const id = await publishedPost(`Raw ${stamp}`)
|
|
108
|
+
|
|
109
|
+
const res = await fetch(`${base}/rest/v1/posts?id=eq.${id}`, {
|
|
110
|
+
method: "PATCH",
|
|
111
|
+
headers: { apikey: ANON_KEY(), Authorization: `Bearer ${EDITOR_SESSION()}`, "Content-Type": "application/json" },
|
|
112
|
+
body: JSON.stringify({ title: `Patched ${stamp}` }),
|
|
113
|
+
})
|
|
114
|
+
const refusal: unknown = await res.json()
|
|
115
|
+
|
|
116
|
+
expect(res.status).toBe(403)
|
|
117
|
+
expect(refusal).toMatchObject({ code: "42501" })
|
|
118
|
+
expect(JSON.stringify(refusal)).toContain("posts has drafts")
|
|
119
|
+
const publicly = await reader().from("posts").select("title").eq("id", id)
|
|
120
|
+
expect(publicly.data).toEqual([{ title: `Raw ${stamp}` }])
|
|
121
|
+
})
|
|
122
|
+
})
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, expectTypeOf, it, vi } from "vitest"
|
|
2
|
+
import { createClient, forgetRegisteredDraftModels, registerDraftModels, type AnyDatabase, type DraftUpdateOptions, type UpdateOptions } 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 update on a model that keeps drafts saves a new draft of each record it matches, through
|
|
7
|
+
// `supatype.save_drafts`, and leaves the live rows as they are: they change only when a version is
|
|
8
|
+
// published. `{ publish: true }` saves and publishes in the same call. These pin which requests go
|
|
9
|
+
// out and what the caller gets back.
|
|
10
|
+
|
|
11
|
+
const BASE = "http://localhost:18473"
|
|
12
|
+
const ID = "7b1f115e-418d-4e92-91d0-f199ebd06e5e"
|
|
13
|
+
const ID_B = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"
|
|
14
|
+
const DRAFT = { id: ID, title: "Edited", published_at: "2026-10-18T10:00:00Z" }
|
|
15
|
+
const SAVED = { record_id: ID, version: 2, status: "draft", created_at: "2026-10-22T08:00:00Z" }
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Answers as the database does for an editor: the table read names the matched records, `save_drafts`
|
|
19
|
+
* saves a version of each, and the draft view reads them back.
|
|
20
|
+
*/
|
|
21
|
+
function draftsServer(matched: readonly string[] = [ID]): FetchMock {
|
|
22
|
+
return mockFetch((input, init) => {
|
|
23
|
+
const url = new URL(requestUrl(input))
|
|
24
|
+
if (url.pathname.endsWith("/rpc/save_drafts")) {
|
|
25
|
+
return Promise.resolve(jsonResponse(matched.map((id) => ({ ...SAVED, record_id: id }))))
|
|
26
|
+
}
|
|
27
|
+
if (init?.method === "PATCH") return Promise.resolve(jsonResponse([{ ...DRAFT, title: "Live!" }]))
|
|
28
|
+
if (header(init ?? {}, "Accept-Profile") === "draft") return Promise.resolve(jsonResponse([DRAFT]))
|
|
29
|
+
return Promise.resolve(jsonResponse(matched.map((id) => ({ id }))))
|
|
30
|
+
})
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function serve(fetch: FetchMock): FetchMock {
|
|
34
|
+
vi.stubGlobal("fetch", fetch)
|
|
35
|
+
return fetch
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Untyped, as a project whose schema the test fixtures do not describe.
|
|
39
|
+
const client = () => createClient<AnyDatabase>({ url: BASE, anonKey: "anon-key" })
|
|
40
|
+
|
|
41
|
+
describe("update on a model that keeps drafts", () => {
|
|
42
|
+
beforeEach(() => registerDraftModels({ version: 1, tables: { posts: { primaryKey: "id" } } }))
|
|
43
|
+
afterEach(() => {
|
|
44
|
+
forgetRegisteredDraftModels()
|
|
45
|
+
vi.unstubAllGlobals()
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
it("reads the keys of the records its filters match, as the caller reads the table", async () => {
|
|
49
|
+
const fetch = serve(draftsServer())
|
|
50
|
+
await client().from("posts").update({ title: "Edited" }).eq("id", ID)
|
|
51
|
+
const [match] = fetchCalls(fetch)
|
|
52
|
+
const url = new URL(match?.url ?? "")
|
|
53
|
+
expect(match?.init.method).toBe("GET")
|
|
54
|
+
expect(url.pathname).toBe("/rest/v1/posts")
|
|
55
|
+
expect(url.searchParams.get("id")).toBe(`eq.${ID}`)
|
|
56
|
+
expect(url.searchParams.get("select")).toBe("id")
|
|
57
|
+
expect(header(match?.init ?? {}, "Accept-Profile")).toBeNull()
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
it("saves a draft of each through supatype.save_drafts and never patches the live row", async () => {
|
|
61
|
+
const fetch = serve(draftsServer([ID, ID_B]))
|
|
62
|
+
await client().from("posts").update({ title: "Edited" }).in("id", [ID, ID_B])
|
|
63
|
+
const calls = fetchCalls(fetch)
|
|
64
|
+
const save = calls[1]
|
|
65
|
+
expect(save?.url).toBe(`${BASE}/rest/v1/rpc/save_drafts`)
|
|
66
|
+
expect(save?.init.method).toBe("POST")
|
|
67
|
+
expect(header(save?.init ?? {}, "Content-Profile")).toBe("supatype")
|
|
68
|
+
expect(jsonBody(save?.init ?? {})).toEqual({
|
|
69
|
+
model_table: "posts",
|
|
70
|
+
record_ids: [ID, ID_B],
|
|
71
|
+
data: { title: "Edited" },
|
|
72
|
+
publish: false,
|
|
73
|
+
})
|
|
74
|
+
expect(calls.map((call) => call.init.method)).not.toContain("PATCH")
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
it("returns the draft rows, read back from the draft view with the update's select", async () => {
|
|
78
|
+
const fetch = serve(draftsServer())
|
|
79
|
+
const { data, error, count } = await client().from("posts").update({ title: "Edited" }).eq("id", ID).select("id, title")
|
|
80
|
+
const readBack = fetchCalls(fetch)[2]
|
|
81
|
+
const url = new URL(readBack?.url ?? "")
|
|
82
|
+
expect(url.searchParams.get("id")).toBe(`in.(${ID})`)
|
|
83
|
+
expect(url.searchParams.get("select")).toBe("id, title")
|
|
84
|
+
expect(header(readBack?.init ?? {}, "Accept-Profile")).toBe("draft")
|
|
85
|
+
expect(error).toBeNull()
|
|
86
|
+
expect(data).toEqual([DRAFT])
|
|
87
|
+
expect(count).toBe(1)
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
it("publishes in the same call with { publish: true }", async () => {
|
|
91
|
+
const fetch = serve(draftsServer())
|
|
92
|
+
const { error } = await client().from("posts").update({ title: "Edited" }, { publish: true }).eq("id", ID)
|
|
93
|
+
expect(error).toBeNull()
|
|
94
|
+
expect(jsonBody(fetchCalls(fetch)[1]?.init ?? {})["publish"]).toBe(true)
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
it("saves nothing when the filters match no record, as a PATCH that matches nothing", async () => {
|
|
98
|
+
const fetch = serve(draftsServer([]))
|
|
99
|
+
const { data, error, count } = await client().from("posts").update({ title: "Edited" }).eq("id", ID)
|
|
100
|
+
expect(fetchCalls(fetch)).toHaveLength(1)
|
|
101
|
+
expect({ data, error, count }).toEqual({ data: [], error: null, count: 0 })
|
|
102
|
+
})
|
|
103
|
+
|
|
104
|
+
it("passes save_drafts' refusal through and reads nothing back", async () => {
|
|
105
|
+
const refused = { code: "42501", details: null, hint: null, message: 'new row violates row-level security policy for table "posts_versions"' }
|
|
106
|
+
const fetch = serve(
|
|
107
|
+
mockFetch((input) =>
|
|
108
|
+
Promise.resolve(requestUrl(input).includes("/rpc/") ? jsonResponse(refused, 403) : jsonResponse([{ id: ID }])),
|
|
109
|
+
),
|
|
110
|
+
)
|
|
111
|
+
const { data, error } = await client().from("posts").update({ title: "Edited" }).eq("id", ID)
|
|
112
|
+
expect(data).toBeNull()
|
|
113
|
+
expect(error).toMatchObject({ code: "42501", status: 403 })
|
|
114
|
+
expect(fetchCalls(fetch)).toHaveLength(2)
|
|
115
|
+
})
|
|
116
|
+
|
|
117
|
+
it("reaches the framework bindings, which update through runMutation", async () => {
|
|
118
|
+
const fetch = serve(draftsServer())
|
|
119
|
+
const outcome = await runMutation(client(), "posts", "update", { title: "Edited" }, { id: ID }, { publish: true })
|
|
120
|
+
expect(fetchCalls(fetch)[1]?.url).toBe(`${BASE}/rest/v1/rpc/save_drafts`)
|
|
121
|
+
expect(jsonBody(fetchCalls(fetch)[1]?.init ?? {})["publish"]).toBe(true)
|
|
122
|
+
expect(outcome.data).toEqual([DRAFT])
|
|
123
|
+
})
|
|
124
|
+
})
|
|
125
|
+
|
|
126
|
+
describe("update on a model that keeps no drafts", () => {
|
|
127
|
+
afterEach(() => {
|
|
128
|
+
forgetRegisteredDraftModels()
|
|
129
|
+
vi.unstubAllGlobals()
|
|
130
|
+
})
|
|
131
|
+
|
|
132
|
+
it("is a plain PATCH asking for the rows back", async () => {
|
|
133
|
+
registerDraftModels({ version: 1, tables: { posts: { primaryKey: "id" } } })
|
|
134
|
+
const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse([{ id: 1, label: "news" }]))))
|
|
135
|
+
const { data } = await client().from("tags").update({ label: "news" }).eq("id", 1)
|
|
136
|
+
const [only] = fetchCalls(fetch)
|
|
137
|
+
expect(fetchCalls(fetch)).toHaveLength(1)
|
|
138
|
+
expect(only?.init.method).toBe("PATCH")
|
|
139
|
+
expect(only?.url).toBe(`${BASE}/rest/v1/tags?id=eq.1`)
|
|
140
|
+
expect(header(only?.init ?? {}, "Prefer")).toContain("return=representation")
|
|
141
|
+
expect(data).toEqual([{ id: 1, label: "news" }])
|
|
142
|
+
})
|
|
143
|
+
|
|
144
|
+
it("is a plain PATCH when nothing was registered, as for a client built without the generated file", async () => {
|
|
145
|
+
const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse([DRAFT]))))
|
|
146
|
+
await client().from("posts").update({ title: "Edited" }).eq("id", ID)
|
|
147
|
+
expect(fetchCalls(fetch).map((call) => call.init.method)).toEqual(["PATCH"])
|
|
148
|
+
})
|
|
149
|
+
|
|
150
|
+
it("refuses { publish: true } without sending anything, since there is nothing to publish", async () => {
|
|
151
|
+
const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse([]))))
|
|
152
|
+
const { data, error } = await client().from("tags").update({ label: "news" }, { publish: true }).eq("id", 1)
|
|
153
|
+
expect(fetchCalls(fetch)).toHaveLength(0)
|
|
154
|
+
expect(data).toBeNull()
|
|
155
|
+
expect(error?.message).toContain("keeps drafts")
|
|
156
|
+
expect(error?.message).toContain("./supatype/generated/client")
|
|
157
|
+
})
|
|
158
|
+
})
|
|
159
|
+
|
|
160
|
+
// Checked by `tsc -p tests/tsconfig.json`, not by vitest.
|
|
161
|
+
type Post = { Row: { id: string; title: string }; Insert: { title: string }; Update: { title?: string }; Drafts: true }
|
|
162
|
+
type Tag = { Row: { id: number; label: string }; Insert: { label: string }; Update: { label?: string } }
|
|
163
|
+
type Blog = { public: { Tables: { posts: Post; tags: Tag } } }
|
|
164
|
+
|
|
165
|
+
describe("the publish option's types", () => {
|
|
166
|
+
it("exists on a drafts model and not on any other", () => {
|
|
167
|
+
expectTypeOf<UpdateOptions<Post>>().toEqualTypeOf<DraftUpdateOptions>()
|
|
168
|
+
expectTypeOf<UpdateOptions<Tag>>().toBeNever()
|
|
169
|
+
const typed = createClient<Blog>({ url: BASE, anonKey: "anon-key" })
|
|
170
|
+
void typed.from("posts").update({ title: "x" }, { publish: true })
|
|
171
|
+
// @ts-expect-error a model with no drafts has nothing to publish
|
|
172
|
+
void typed.from("tags").update({ label: "x" }, { publish: true })
|
|
173
|
+
})
|
|
174
|
+
})
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `headers` may be a function, read on every request, so a header can change for the life of one
|
|
3
|
+
* client. Studio's acting-mode switch needs this: the mode a request asks for is chosen after the
|
|
4
|
+
* client exists, and rebuilding the client would drop its session and its sockets.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { afterEach, describe, expect, it, vi } from "vitest"
|
|
8
|
+
import { createClient } from "../src/index.js"
|
|
9
|
+
|
|
10
|
+
const BASE = "http://localhost:18474"
|
|
11
|
+
const ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiJ9.test"
|
|
12
|
+
|
|
13
|
+
afterEach(() => {
|
|
14
|
+
vi.unstubAllGlobals()
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
function captureRequests(): Headers[] {
|
|
18
|
+
const seen: Headers[] = []
|
|
19
|
+
vi.stubGlobal("fetch", async (_url: string, init?: RequestInit) => {
|
|
20
|
+
seen.push(new Headers(init?.headers))
|
|
21
|
+
return new Response("[]", { status: 200, headers: { "content-type": "application/json" } })
|
|
22
|
+
})
|
|
23
|
+
return seen
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
describe("headers", () => {
|
|
27
|
+
it("are read on every request when given as a function", async () => {
|
|
28
|
+
const seen = captureRequests()
|
|
29
|
+
let mode = "elevated"
|
|
30
|
+
const client = createClient({ url: BASE, anonKey: ANON_KEY, headers: () => ({ "X-Supatype-Acting-Mode": mode }) })
|
|
31
|
+
|
|
32
|
+
await client.from("posts").select()
|
|
33
|
+
mode = "self"
|
|
34
|
+
await client.from("posts").select()
|
|
35
|
+
|
|
36
|
+
expect(seen.map((h) => h.get("X-Supatype-Acting-Mode"))).toEqual(["elevated", "self"])
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it("are still sent when given as a plain object", async () => {
|
|
40
|
+
const seen = captureRequests()
|
|
41
|
+
const client = createClient({ url: BASE, anonKey: ANON_KEY, headers: { "X-Supatype-Environment": "staging" } })
|
|
42
|
+
await client.from("posts").select()
|
|
43
|
+
expect(seen[0]?.get("X-Supatype-Environment")).toBe("staging")
|
|
44
|
+
})
|
|
45
|
+
})
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The framework bindings' building blocks live on `@supatype/client/bindings`, not the main entry.
|
|
3
|
+
*
|
|
4
|
+
* `watchTable`, `runMutation` and their helpers exist so the bindings share one copy of the
|
|
5
|
+
* channel wiring and the mutation requests. On the main entry they read as API an app should call,
|
|
6
|
+
* and anything exported there is a promise to every app. The subpath keeps them available to the
|
|
7
|
+
* bindings without that.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { describe, it, expect } from "vitest"
|
|
11
|
+
import { readFileSync } from "node:fs"
|
|
12
|
+
import * as main from "../src/index.js"
|
|
13
|
+
import * as bindings from "../src/bindings.js"
|
|
14
|
+
|
|
15
|
+
const BINDING_EXPORTS = [
|
|
16
|
+
"watchTable",
|
|
17
|
+
"subscribeToTable",
|
|
18
|
+
"subscriptionViewOf",
|
|
19
|
+
"applyRowChange",
|
|
20
|
+
"isClientFor",
|
|
21
|
+
"isRowsOf",
|
|
22
|
+
"isCallerValue",
|
|
23
|
+
"runMutation",
|
|
24
|
+
"livePreviewMessage",
|
|
25
|
+
"previewMessageOf",
|
|
26
|
+
"originOf",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
describe("entry points", () => {
|
|
30
|
+
it("keeps the binding helpers off the main entry", () => {
|
|
31
|
+
for (const name of BINDING_EXPORTS) expect(main, name).not.toHaveProperty(name)
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
it("exports every binding helper from the bindings entry", () => {
|
|
35
|
+
for (const name of BINDING_EXPORTS) expect(bindings, name).toHaveProperty(name)
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
it("maps ./bindings in package.json to the built entry and its types", () => {
|
|
39
|
+
const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"))
|
|
40
|
+
expect(pkg).toHaveProperty(["exports", "./bindings"], { types: "./dist/bindings.d.ts", import: "./dist/bindings.js" })
|
|
41
|
+
})
|
|
42
|
+
})
|