@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
|
@@ -1,118 +1,117 @@
|
|
|
1
|
-
import { describe, it, expect, beforeEach, vi, afterEach } from "vitest"
|
|
2
|
-
import { QueryBuilder } from "../src/query.js"
|
|
3
|
-
import { QueryCache, buildCacheKey, identityFingerprint } from "../src/query-cache.js"
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
const
|
|
9
|
-
const
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
const
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
const
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
cache
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
})
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
"
|
|
67
|
-
|
|
68
|
-
"
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
//
|
|
74
|
-
//
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
expect(
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
expect(r2.
|
|
85
|
-
expect(
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
"
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
expect(
|
|
104
|
-
})
|
|
105
|
-
|
|
106
|
-
it("sends public directive when server and public", async () => {
|
|
107
|
-
fetchMock.mockResolvedValue(
|
|
108
|
-
new Response(JSON.stringify([]), { status: 200, headers: { "Content-Type": "application/json" } }),
|
|
109
|
-
)
|
|
110
|
-
|
|
111
|
-
await new QueryBuilder("http://localhost:9999", "/rest/v1/posts", {}, "*")
|
|
112
|
-
.cache({ ttl: 30_000, server: true, public: true })
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
})
|
|
1
|
+
import { describe, it, expect, beforeEach, vi, afterEach } from "vitest"
|
|
2
|
+
import { QueryBuilder } from "../src/query.js"
|
|
3
|
+
import { QueryCache, buildCacheKey, identityFingerprint } from "../src/query-cache.js"
|
|
4
|
+
import { fetchCall, fetchCalls, header, mockFetch } from "./support/fetch-mock.js"
|
|
5
|
+
|
|
6
|
+
describe("query-cache", () => {
|
|
7
|
+
it("identityFingerprint differs for different subs", () => {
|
|
8
|
+
const payloadA = btoa(JSON.stringify({ sub: "a", role: "authenticated" }))
|
|
9
|
+
const payloadB = btoa(JSON.stringify({ sub: "b", role: "authenticated" }))
|
|
10
|
+
const a = identityFingerprint({ Authorization: `Bearer x.${payloadA}.y` }, "user")
|
|
11
|
+
const b = identityFingerprint({ Authorization: `Bearer x.${payloadB}.y` }, "user")
|
|
12
|
+
expect(a).not.toBe(b)
|
|
13
|
+
})
|
|
14
|
+
|
|
15
|
+
it("identityFingerprint stable for same sub across token strings", () => {
|
|
16
|
+
const payload = btoa(JSON.stringify({ sub: "user-1", role: "authenticated" }))
|
|
17
|
+
const a = identityFingerprint({ Authorization: `Bearer aaa.${payload}.sig1` }, "user")
|
|
18
|
+
const b = identityFingerprint({ Authorization: `Bearer bbb.${payload}.sig2` }, "user")
|
|
19
|
+
expect(a).toBe(b)
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
it("public scope uses global fingerprint", () => {
|
|
23
|
+
expect(identityFingerprint({ Authorization: "Bearer x" }, "public")).toBe("global")
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
it("buildCacheKey is stable", () => {
|
|
27
|
+
const h = { Authorization: "Bearer x" }
|
|
28
|
+
const k1 = buildCacheKey("GET", "http://localhost/rest/v1/posts", h)
|
|
29
|
+
const k2 = buildCacheKey("GET", "http://localhost/rest/v1/posts", h)
|
|
30
|
+
expect(k1).toBe(k2)
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it("QueryCache expires entries", () => {
|
|
34
|
+
vi.useFakeTimers()
|
|
35
|
+
const cache = new QueryCache()
|
|
36
|
+
cache.set("k", { data: [{ id: 1 }], error: null, count: 1 }, 1000)
|
|
37
|
+
expect(cache.get("k")?.data).toEqual([{ id: 1 }])
|
|
38
|
+
vi.advanceTimersByTime(1001)
|
|
39
|
+
expect(cache.get("k")).toBeNull()
|
|
40
|
+
vi.useRealTimers()
|
|
41
|
+
})
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
describe("QueryBuilder.cache", () => {
|
|
45
|
+
const fetchMock = mockFetch()
|
|
46
|
+
|
|
47
|
+
beforeEach(() => {
|
|
48
|
+
fetchMock.mockReset()
|
|
49
|
+
vi.stubGlobal("fetch", fetchMock)
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
afterEach(() => {
|
|
53
|
+
vi.unstubAllGlobals()
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
it("returns cached result without second fetch", async () => {
|
|
57
|
+
fetchMock.mockResolvedValue(
|
|
58
|
+
new Response(JSON.stringify([{ id: 1 }]), {
|
|
59
|
+
status: 200,
|
|
60
|
+
headers: { "Content-Type": "application/json" },
|
|
61
|
+
}),
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
const cache = new QueryCache()
|
|
65
|
+
const qb = new QueryBuilder<{ id: number }>(
|
|
66
|
+
"http://localhost:9999",
|
|
67
|
+
"/rest/v1/posts",
|
|
68
|
+
{ Authorization: "Bearer anon" },
|
|
69
|
+
"*",
|
|
70
|
+
cache,
|
|
71
|
+
).cache({ ttl: 60_000 })
|
|
72
|
+
|
|
73
|
+
// Counted per table URL rather than across every request, because the client also fetches the
|
|
74
|
+
// project's column types once so it can keep bigInt, decimal and money columns exact. That
|
|
75
|
+
// request is cached per project and is not what this test is about.
|
|
76
|
+
const tableCalls = (): number =>
|
|
77
|
+
fetchCalls(fetchMock).filter(({ url }) => url.includes("/rest/v1/posts")).length
|
|
78
|
+
|
|
79
|
+
const r1 = await qb
|
|
80
|
+
expect(r1.data).toEqual([{ id: 1 }])
|
|
81
|
+
expect(tableCalls()).toBe(1)
|
|
82
|
+
|
|
83
|
+
const r2 = await qb
|
|
84
|
+
expect(r2.data).toEqual([{ id: 1 }])
|
|
85
|
+
expect(r2.meta?.cacheStatus).toBe("HIT")
|
|
86
|
+
expect(tableCalls()).toBe(1)
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
it("sends X-Supatype-Cache when server: true", async () => {
|
|
90
|
+
fetchMock.mockResolvedValue(
|
|
91
|
+
new Response(JSON.stringify([]), {
|
|
92
|
+
status: 200,
|
|
93
|
+
headers: {
|
|
94
|
+
"Content-Type": "application/json",
|
|
95
|
+
"X-Supatype-Cache-Status": "MISS",
|
|
96
|
+
},
|
|
97
|
+
}),
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
await new QueryBuilder("http://localhost:9999", "/rest/v1/posts", {}, "*")
|
|
101
|
+
.cache({ ttl: 30_000, server: true })
|
|
102
|
+
|
|
103
|
+
expect(header(fetchCall(fetchMock).init, "X-Supatype-Cache")).toBe("max-age=30")
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
it("sends public directive when server and public", async () => {
|
|
107
|
+
fetchMock.mockResolvedValue(
|
|
108
|
+
new Response(JSON.stringify([]), { status: 200, headers: { "Content-Type": "application/json" } }),
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
await new QueryBuilder("http://localhost:9999", "/rest/v1/posts", {}, "*")
|
|
112
|
+
.cache({ ttl: 30_000, server: true, public: true })
|
|
113
|
+
|
|
114
|
+
expect(header(fetchCall(fetchMock).init, "X-Supatype-Cache")).toBe("max-age=30, public")
|
|
115
|
+
})
|
|
116
|
+
})
|
|
118
117
|
|
package/tests/query.test.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { describe, it, expect, vi, beforeEach } from "vitest"
|
|
2
2
|
import { QueryBuilder, MutationBuilder, defaultQueryCache } from "../src/query.js"
|
|
3
|
+
import { fetchCall, fetchReturning, header, type FetchMock } from "./support/fetch-mock.js"
|
|
3
4
|
|
|
4
5
|
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
|
5
6
|
|
|
@@ -12,25 +13,17 @@ interface Post { id: string; title: string; status: string }
|
|
|
12
13
|
function mockFetch(
|
|
13
14
|
body: unknown,
|
|
14
15
|
opts: { ok?: boolean; status?: number; contentRange?: string } = {},
|
|
15
|
-
):
|
|
16
|
+
): FetchMock {
|
|
16
17
|
const { ok = true, status = ok ? 200 : 400, contentRange } = opts
|
|
17
|
-
return
|
|
18
|
-
ok,
|
|
19
|
-
status,
|
|
20
|
-
json: vi.fn().mockResolvedValue(body),
|
|
21
|
-
text: vi.fn().mockResolvedValue(JSON.stringify(body)),
|
|
22
|
-
headers: {
|
|
23
|
-
get: (key: string) => (key === "content-range" ? (contentRange ?? null) : null),
|
|
24
|
-
},
|
|
25
|
-
})
|
|
18
|
+
return fetchReturning(body, status, contentRange === undefined ? {} : { "Content-Range": contentRange })
|
|
26
19
|
}
|
|
27
20
|
|
|
28
|
-
function captureUrl(): { url: () => string; fetch:
|
|
21
|
+
function captureUrl(): { url: () => string; fetch: FetchMock } {
|
|
29
22
|
const fetch = mockFetch([])
|
|
30
23
|
vi.stubGlobal("fetch", fetch)
|
|
31
24
|
return {
|
|
32
25
|
fetch,
|
|
33
|
-
url: () => (fetch.
|
|
26
|
+
url: () => fetchCall(fetch).url,
|
|
34
27
|
}
|
|
35
28
|
}
|
|
36
29
|
|
|
@@ -126,6 +119,17 @@ describe("QueryBuilder: URL construction", () => {
|
|
|
126
119
|
expect(url()).toContain("nullsfirst")
|
|
127
120
|
})
|
|
128
121
|
|
|
122
|
+
// PostgREST reads only the first `order` parameter, so a second one sent separately was dropped
|
|
123
|
+
// without an error and the rows came back ordered by the first column alone.
|
|
124
|
+
it(".order() twice sends one comma-separated order parameter", async () => {
|
|
125
|
+
const { url } = captureUrl()
|
|
126
|
+
await new QueryBuilder<Post>(BASE, PATH, HEADERS)
|
|
127
|
+
.order("created_at", { ascending: false })
|
|
128
|
+
.order("id", { ascending: false })
|
|
129
|
+
const params = new URL(url()).searchParams
|
|
130
|
+
expect(params.getAll("order")).toEqual(["created_at.desc.nullslast,id.desc.nullslast"])
|
|
131
|
+
})
|
|
132
|
+
|
|
129
133
|
it(".limit() sets limit param", async () => {
|
|
130
134
|
const { url } = captureUrl()
|
|
131
135
|
await new QueryBuilder<Post>(BASE, PATH, HEADERS).limit(20)
|
|
@@ -136,8 +140,7 @@ describe("QueryBuilder: URL construction", () => {
|
|
|
136
140
|
const fetch = mockFetch([])
|
|
137
141
|
vi.stubGlobal("fetch", fetch)
|
|
138
142
|
await new QueryBuilder<Post>(BASE, PATH, HEADERS).range(10, 19)
|
|
139
|
-
|
|
140
|
-
expect((opts.headers as Record<string, string>)["Range"]).toBe("10-19")
|
|
143
|
+
expect(header(fetchCall(fetch).init, "Range")).toBe("10-19")
|
|
141
144
|
})
|
|
142
145
|
|
|
143
146
|
it("multiple chained filters all appear in URL", async () => {
|
|
@@ -166,8 +169,7 @@ describe("QueryBuilder: URL construction", () => {
|
|
|
166
169
|
await new QueryBuilder<Post>(BASE, PATH, HEADERS, "*", defaultQueryCache, undefined, {
|
|
167
170
|
count: "exact",
|
|
168
171
|
})
|
|
169
|
-
|
|
170
|
-
expect((opts.headers as Record<string, string>)["Prefer"]).toBe("count=exact")
|
|
172
|
+
expect(header(fetchCall(fetch).init, "Prefer")).toBe("count=exact")
|
|
171
173
|
})
|
|
172
174
|
|
|
173
175
|
it("select with head issues HEAD request and returns count only", async () => {
|
|
@@ -182,8 +184,7 @@ describe("QueryBuilder: URL construction", () => {
|
|
|
182
184
|
undefined,
|
|
183
185
|
{ count: "exact", head: true },
|
|
184
186
|
)
|
|
185
|
-
|
|
186
|
-
expect(opts.method).toBe("HEAD")
|
|
187
|
+
expect(fetchCall(fetch).init.method).toBe("HEAD")
|
|
187
188
|
expect(data).toBeNull()
|
|
188
189
|
expect(error).toBeNull()
|
|
189
190
|
expect(count).toBe(42)
|
|
@@ -231,8 +232,7 @@ describe("QueryBuilder.single()", () => {
|
|
|
231
232
|
const fetch = mockFetch({ id: "1", title: "Hello", status: "published" })
|
|
232
233
|
vi.stubGlobal("fetch", fetch)
|
|
233
234
|
await new QueryBuilder<Post>(BASE, PATH, HEADERS).single()
|
|
234
|
-
|
|
235
|
-
expect((opts.headers as Record<string, string>)["Accept"]).toContain("pgrst.object+json")
|
|
235
|
+
expect(header(fetchCall(fetch).init, "Accept")).toContain("pgrst.object+json")
|
|
236
236
|
})
|
|
237
237
|
|
|
238
238
|
it("returns single row", async () => {
|
|
@@ -271,9 +271,9 @@ describe("MutationBuilder: insert", () => {
|
|
|
271
271
|
const { data, error } = await new MutationBuilder<Post>(BASE, PATH, HEADERS, "POST", { title: "New", status: "draft" })
|
|
272
272
|
expect(error).toBeNull()
|
|
273
273
|
expect(data?.[0]?.id).toBe("1")
|
|
274
|
-
const
|
|
275
|
-
expect(
|
|
276
|
-
expect(
|
|
274
|
+
const { init } = fetchCall(fetch)
|
|
275
|
+
expect(init.method).toBe("POST")
|
|
276
|
+
expect(init.body).toContain("New")
|
|
277
277
|
})
|
|
278
278
|
|
|
279
279
|
it("returns error on non-ok", async () => {
|
|
@@ -291,8 +291,8 @@ describe("MutationBuilder: update / delete", () => {
|
|
|
291
291
|
const fetch = mockFetch([{ id: "1", title: "Updated", status: "published" }])
|
|
292
292
|
vi.stubGlobal("fetch", fetch)
|
|
293
293
|
await new MutationBuilder<Post>(BASE, PATH, HEADERS, "PATCH", { title: "Updated" }).eq("id", "1")
|
|
294
|
-
const
|
|
295
|
-
expect(
|
|
294
|
+
const { url, init } = fetchCall(fetch)
|
|
295
|
+
expect(init.method).toBe("PATCH")
|
|
296
296
|
expect(url).toContain("id=eq.1")
|
|
297
297
|
})
|
|
298
298
|
|
|
@@ -300,8 +300,8 @@ describe("MutationBuilder: update / delete", () => {
|
|
|
300
300
|
const fetch = mockFetch(null, { status: 204 })
|
|
301
301
|
vi.stubGlobal("fetch", fetch)
|
|
302
302
|
await new MutationBuilder<Post>(BASE, PATH, HEADERS, "DELETE").eq("id", "1")
|
|
303
|
-
const
|
|
304
|
-
expect(
|
|
303
|
+
const { url, init } = fetchCall(fetch)
|
|
304
|
+
expect(init.method).toBe("DELETE")
|
|
305
305
|
expect(url).toContain("id=eq.1")
|
|
306
306
|
})
|
|
307
307
|
|
|
@@ -316,8 +316,7 @@ describe("MutationBuilder: update / delete", () => {
|
|
|
316
316
|
const fetch = mockFetch([{ id: "1", title: "A", status: "draft" }])
|
|
317
317
|
vi.stubGlobal("fetch", fetch)
|
|
318
318
|
await new MutationBuilder<Post>(BASE, PATH, HEADERS, "POST", { id: "1", title: "A", status: "draft" }, { upsert: true })
|
|
319
|
-
|
|
320
|
-
expect((opts.headers as Record<string, string>)["Prefer"]).toContain("merge-duplicates")
|
|
319
|
+
expect(header(fetchCall(fetch).init, "Prefer")).toContain("merge-duplicates")
|
|
321
320
|
})
|
|
322
321
|
|
|
323
322
|
it("update().eq().select().maybeSingle() returns first row", async () => {
|
|
@@ -335,7 +334,6 @@ describe("MutationBuilder: update / delete", () => {
|
|
|
335
334
|
.maybeSingle()
|
|
336
335
|
expect(error).toBeNull()
|
|
337
336
|
expect(data).toEqual({ id: "1", title: "Updated", status: "published" })
|
|
338
|
-
|
|
339
|
-
expect(url).toContain("select=*")
|
|
337
|
+
expect(fetchCall(fetch).url).toContain("select=*")
|
|
340
338
|
})
|
|
341
339
|
})
|
|
@@ -11,14 +11,8 @@ import { RateLimitError } from "../src/errors.js"
|
|
|
11
11
|
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
|
12
12
|
|
|
13
13
|
function mockResponse(status: number, body: unknown = {}, headers?: Record<string, string>): Response {
|
|
14
|
-
const
|
|
15
|
-
return {
|
|
16
|
-
ok: status >= 200 && status < 300,
|
|
17
|
-
status,
|
|
18
|
-
json: vi.fn().mockResolvedValue(body),
|
|
19
|
-
headers: headersObj,
|
|
20
|
-
statusText: status === 429 ? "Too Many Requests" : "OK",
|
|
21
|
-
} as unknown as Response
|
|
14
|
+
const statusText = status === 429 ? "Too Many Requests" : "OK"
|
|
15
|
+
return new Response(JSON.stringify(body), { status, statusText, headers: { "Content-Type": "application/json", ...headers } })
|
|
22
16
|
}
|
|
23
17
|
|
|
24
18
|
// ─── Tests ───────────────────────────────────────────────────────────────────
|
|
@@ -126,9 +120,7 @@ describe("Task 91: SDK rate limit integration", () => {
|
|
|
126
120
|
expect.fail("Should have thrown RateLimitError")
|
|
127
121
|
} catch (err) {
|
|
128
122
|
expect(err).toBeInstanceOf(RateLimitError)
|
|
129
|
-
expect(
|
|
130
|
-
expect((err as RateLimitError).statusCode).toBe(429)
|
|
131
|
-
expect((err as RateLimitError).code).toBe("RATE_LIMITED")
|
|
123
|
+
expect(err).toMatchObject({ retryAfterSeconds: 2, statusCode: 429, code: "RATE_LIMITED" })
|
|
132
124
|
}
|
|
133
125
|
vi.useFakeTimers()
|
|
134
126
|
})
|
|
@@ -179,7 +171,7 @@ describe("Task 91: SDK rate limit integration", () => {
|
|
|
179
171
|
|
|
180
172
|
const res = await promise
|
|
181
173
|
expect(res.ok).toBe(true)
|
|
182
|
-
const data = await res.json()
|
|
174
|
+
const data: unknown = await res.json()
|
|
183
175
|
expect(data).toEqual(expectedData)
|
|
184
176
|
})
|
|
185
177
|
})
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A server reply is matched to the join that asked for it, not to whatever join on that channel
|
|
3
|
+
* name happens to be pending when it arrives.
|
|
4
|
+
*
|
|
5
|
+
* Replies used to be read by channel name alone. Two joins on one name close together (a rejoin
|
|
6
|
+
* after the joining handle leaves, or a leave followed at once by a new join) each got the other's
|
|
7
|
+
* answer: the first join's acknowledgement reported SUBSCRIBED for a second join the server went on
|
|
8
|
+
* to refuse, and the first join's refusal put a handle whose own join succeeded into CHANNEL_ERROR.
|
|
9
|
+
*
|
|
10
|
+
* The fake server here answers every frame in the order it was sent, as the real one does, and
|
|
11
|
+
* echoes the frame's `ref` when it carried one.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { describe, it, expect, beforeEach, afterEach } from "vitest"
|
|
15
|
+
import type { ChannelStatus } from "../src/realtime.js"
|
|
16
|
+
import { channelOf, sentFrames, simulateServerMessage } from "./helpers/mock-websocket.js"
|
|
17
|
+
import { createSocketSwapHarness, type SocketSwapHarness } from "./helpers/socket-swap.js"
|
|
18
|
+
|
|
19
|
+
const CHANNEL = "x"
|
|
20
|
+
const BAD_FILTER = "status=like.open"
|
|
21
|
+
|
|
22
|
+
let harness: SocketSwapHarness
|
|
23
|
+
let answered = 0
|
|
24
|
+
|
|
25
|
+
/** The server's reply to one subscribe or unsubscribe frame, with a join's ref when it had one. */
|
|
26
|
+
function replyTo(frame: Record<string, unknown>, echoRef: boolean): Record<string, unknown> {
|
|
27
|
+
const channel = channelOf(frame)
|
|
28
|
+
if (frame["type"] === "unsubscribe") return { type: "system", status: "ok", message: `unsubscribed from ${channel}` }
|
|
29
|
+
const ref = echoRef && typeof frame["ref"] === "string" ? { ref: frame["ref"] } : {}
|
|
30
|
+
const filter = frame["filter"]
|
|
31
|
+
const refused = typeof filter === "object" && filter !== null && "status" in filter
|
|
32
|
+
if (refused) return { type: "system", status: "error", message: `invalid filter ${BAD_FILTER}`, channel, ...ref }
|
|
33
|
+
return { type: "system", status: "ok", message: `subscribed to ${channel}`, ...ref }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Answer every join and leave sent since the last call, in the order they went out. */
|
|
37
|
+
function answerInOrder({ echoRef = true }: { echoRef?: boolean } = {}): void {
|
|
38
|
+
const pending = sentFrames(harness.socket())
|
|
39
|
+
.filter((frame) => frame["type"] === "subscribe" || frame["type"] === "unsubscribe")
|
|
40
|
+
.slice(answered)
|
|
41
|
+
answered += pending.length
|
|
42
|
+
for (const frame of pending) simulateServerMessage(harness.socket(), replyTo(frame, echoRef))
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
beforeEach(() => {
|
|
46
|
+
harness = createSocketSwapHarness()
|
|
47
|
+
answered = 0
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
afterEach(() => harness.restore())
|
|
51
|
+
|
|
52
|
+
describe("a rejoin sent before the join it replaces is answered", () => {
|
|
53
|
+
it("is not reported SUBSCRIBED by the earlier join's acknowledgement when it is itself refused", async () => {
|
|
54
|
+
const statuses: ChannelStatus[] = []
|
|
55
|
+
const a = harness.realtime.channel(CHANNEL).on("postgres_changes", { event: "*", table: "audit_log" }, () => {}).subscribe()
|
|
56
|
+
harness.realtime
|
|
57
|
+
.channel(CHANNEL)
|
|
58
|
+
.on("postgres_changes", { event: "*", table: "messages", filter: BAD_FILTER }, () => {})
|
|
59
|
+
.subscribe((s) => statuses.push(s))
|
|
60
|
+
await harness.settle()
|
|
61
|
+
|
|
62
|
+
// The first join is still unanswered when its handle leaves, so the channel joins again.
|
|
63
|
+
a.unsubscribe()
|
|
64
|
+
answerInOrder()
|
|
65
|
+
|
|
66
|
+
expect(statuses).toEqual(["SUBSCRIBING", "CHANNEL_ERROR"])
|
|
67
|
+
// Nothing on this channel is subscribed, so a handle arriving now is not told it is.
|
|
68
|
+
const late: ChannelStatus[] = []
|
|
69
|
+
harness.realtime.channel(CHANNEL).subscribe((s) => late.push(s))
|
|
70
|
+
expect(late).toEqual([])
|
|
71
|
+
})
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
describe("a join sent right after the channel was left", () => {
|
|
75
|
+
function join(filter: string | undefined, onStatus?: (status: ChannelStatus) => void): { unsubscribe(): void } {
|
|
76
|
+
return harness.realtime.channel(CHANNEL).on("postgres_changes", { event: "*", table: "t", filter }, () => {}).subscribe(onStatus)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function leaveThenJoin(firstFilter: string | undefined, secondFilter: string | undefined): Promise<ChannelStatus[]> {
|
|
80
|
+
// Another channel keeps the socket open across the leave.
|
|
81
|
+
harness.realtime.channel("keep").subscribe()
|
|
82
|
+
const first = join(firstFilter)
|
|
83
|
+
await harness.settle()
|
|
84
|
+
first.unsubscribe()
|
|
85
|
+
const statuses: ChannelStatus[] = []
|
|
86
|
+
join(secondFilter, (s) => statuses.push(s))
|
|
87
|
+
answerInOrder()
|
|
88
|
+
return statuses
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
it("is not put into CHANNEL_ERROR by the refusal of the join before it", async () => {
|
|
92
|
+
expect(await leaveThenJoin(BAD_FILTER, undefined)).toEqual(["SUBSCRIBED"])
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
it("is not reported SUBSCRIBED by the acknowledgement of the join before it", async () => {
|
|
96
|
+
expect(await leaveThenJoin(undefined, BAD_FILTER)).toEqual(["CHANNEL_ERROR"])
|
|
97
|
+
})
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
describe("a server that echoes no ref", () => {
|
|
101
|
+
it("still has its replies read by channel name, as before refs existed", async () => {
|
|
102
|
+
const statuses: ChannelStatus[] = []
|
|
103
|
+
harness.realtime.channel(CHANNEL).subscribe((s) => statuses.push(s))
|
|
104
|
+
await harness.settle()
|
|
105
|
+
|
|
106
|
+
const join = sentFrames(harness.socket()).find((frame) => frame["type"] === "subscribe")
|
|
107
|
+
expect(typeof join?.["ref"]).toBe("string")
|
|
108
|
+
answerInOrder({ echoRef: false })
|
|
109
|
+
|
|
110
|
+
expect(statuses).toEqual(["SUBSCRIBED"])
|
|
111
|
+
})
|
|
112
|
+
})
|
|
@@ -22,17 +22,15 @@ import {
|
|
|
22
22
|
const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 10))
|
|
23
23
|
|
|
24
24
|
let instances: MockWebSocketInstance[]
|
|
25
|
-
let originalWebSocket: typeof WebSocket
|
|
26
25
|
|
|
27
26
|
beforeEach(() => {
|
|
28
27
|
const mock = createMockWebSocketClass()
|
|
29
28
|
instances = mock.instances
|
|
30
|
-
|
|
31
|
-
globalThis.WebSocket = mock.MockWebSocket
|
|
29
|
+
vi.stubGlobal("WebSocket", mock.MockWebSocket)
|
|
32
30
|
})
|
|
33
31
|
|
|
34
32
|
afterEach(() => {
|
|
35
|
-
|
|
33
|
+
vi.unstubAllGlobals()
|
|
36
34
|
vi.restoreAllMocks()
|
|
37
35
|
})
|
|
38
36
|
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Presence counted from joins and leaves stays true across a socket swap.
|
|
3
|
+
*
|
|
4
|
+
* The server tells a channel's newcomer who is already there as joins, and it does so on every
|
|
5
|
+
* join, including the one each channel makes again on the socket that signing in opens. Leaves
|
|
6
|
+
* for the old socket's members never arrive (that socket is gone), so a page counting joins minus
|
|
7
|
+
* leaves read every member twice after signing in. The client now leaves, for its listeners,
|
|
8
|
+
* everyone it had been told about when the socket that told it goes away.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { describe, it, expect, beforeEach, afterEach } from "vitest"
|
|
12
|
+
import type { PresenceEntry } from "../src/realtime.js"
|
|
13
|
+
import { simulateServerMessage } from "./helpers/mock-websocket.js"
|
|
14
|
+
import { createSocketSwapHarness, type SocketSwapHarness } from "./helpers/socket-swap.js"
|
|
15
|
+
|
|
16
|
+
const CHANNEL = "lobby:lobby"
|
|
17
|
+
|
|
18
|
+
let harness: SocketSwapHarness
|
|
19
|
+
let here: number
|
|
20
|
+
let leaves: PresenceEntry[]
|
|
21
|
+
|
|
22
|
+
function newest(): SocketSwapHarness["sockets"][number] {
|
|
23
|
+
const socket = harness.sockets[harness.sockets.length - 1]
|
|
24
|
+
if (socket === undefined) throw new Error("no socket has been opened")
|
|
25
|
+
return socket
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function serverSays(joins: PresenceEntry[], left: PresenceEntry[] = []): void {
|
|
29
|
+
simulateServerMessage(newest(), { type: "presence", channel: CHANNEL, joins, leaves: left })
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
beforeEach(async () => {
|
|
33
|
+
harness = createSocketSwapHarness()
|
|
34
|
+
here = 0
|
|
35
|
+
leaves = []
|
|
36
|
+
const channel = harness.realtime.channel(CHANNEL)
|
|
37
|
+
channel.onPresence((event) => {
|
|
38
|
+
here += event.joins.length - event.leaves.length
|
|
39
|
+
leaves.push(...event.leaves)
|
|
40
|
+
})
|
|
41
|
+
channel.subscribe()
|
|
42
|
+
await harness.settle()
|
|
43
|
+
harness.ackJoins()
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
afterEach(() => harness.restore())
|
|
47
|
+
|
|
48
|
+
describe("presence across the socket swap on sign-in", () => {
|
|
49
|
+
it("counts each member once after the new socket's join sends the state again", async () => {
|
|
50
|
+
serverSays([{ user_id: "first" }, { user_id: "second" }])
|
|
51
|
+
expect(here).toBe(2)
|
|
52
|
+
|
|
53
|
+
await harness.signIn()
|
|
54
|
+
harness.ackJoins()
|
|
55
|
+
serverSays([{ user_id: "first" }, { user_id: "second" }])
|
|
56
|
+
|
|
57
|
+
expect(here).toBe(2)
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
it("leaves everyone it had been told about when the socket goes away", async () => {
|
|
61
|
+
serverSays([{ user_id: "first" }, { user_id: "second" }])
|
|
62
|
+
serverSays([], [{ user_id: "first" }])
|
|
63
|
+
|
|
64
|
+
await harness.signIn()
|
|
65
|
+
|
|
66
|
+
expect(here).toBe(0)
|
|
67
|
+
expect(leaves).toEqual([{ user_id: "first" }, { user_id: "second" }])
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
it("tells a channel nobody joined nothing when the socket goes away", () => {
|
|
71
|
+
harness.realtime.disconnect()
|
|
72
|
+
|
|
73
|
+
expect(leaves).toEqual([])
|
|
74
|
+
})
|
|
75
|
+
})
|
|
@@ -16,6 +16,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
|
|
|
16
16
|
import { RealtimeClient } from "../src/realtime.js"
|
|
17
17
|
import {
|
|
18
18
|
createMockWebSocketClass,
|
|
19
|
+
subscribedChannels,
|
|
19
20
|
tokenOf,
|
|
20
21
|
type MockWebSocketInstance,
|
|
21
22
|
} from "./helpers/mock-websocket.js"
|
|
@@ -128,10 +129,7 @@ describe("realtime authenticates as the session, not as anon", () => {
|
|
|
128
129
|
await settle()
|
|
129
130
|
|
|
130
131
|
const replacement = MockWS.instances[1]!
|
|
131
|
-
|
|
132
|
-
.map(([raw]) => JSON.parse(String(raw)) as { type: string; channel: string })
|
|
133
|
-
.filter((m) => m.type === "subscribe")
|
|
134
|
-
expect(subscribes.map((m) => m.channel)).toContain("public:task")
|
|
132
|
+
expect(subscribedChannels(replacement)).toContain("public:task")
|
|
135
133
|
})
|
|
136
134
|
|
|
137
135
|
it("reconnects when the identity changes while the first connect is still resolving its token", async () => {
|