@supatype/client 0.3.1 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +28 -24
- package/.turbo/turbo-typecheck.log +2 -2
- package/dist/exact-response.d.ts +26 -0
- package/dist/exact-response.d.ts.map +1 -0
- package/dist/exact-response.js +51 -0
- package/dist/exact-response.js.map +1 -0
- package/dist/exact-values.d.ts +50 -0
- package/dist/exact-values.d.ts.map +1 -0
- package/dist/exact-values.js +254 -0
- package/dist/exact-values.js.map +1 -0
- package/dist/field-kinds-registry.d.ts +46 -0
- package/dist/field-kinds-registry.d.ts.map +1 -0
- package/dist/field-kinds-registry.js +51 -0
- package/dist/field-kinds-registry.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +18 -5
- package/dist/query.js.map +1 -1
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +19 -2
- package/dist/realtime.js.map +1 -1
- package/dist/types.d.ts +20 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +2 -2
- package/src/exact-response.ts +76 -0
- package/src/exact-values.ts +281 -0
- package/src/field-kinds-registry.ts +80 -0
- package/src/index.ts +12 -0
- package/src/query.ts +23 -5
- package/src/realtime.ts +29 -2
- package/src/types.ts +28 -0
- package/tests/data-plane-auth.test.ts +6 -4
- package/tests/draft-profile.test.ts +3 -0
- package/tests/exact-response.test.ts +95 -0
- package/tests/exact-values.test.ts +171 -0
- package/tests/field-kinds-registry.test.ts +80 -0
- package/tests/fixtures/models.ts +55 -0
- package/tests/identity-change.test.ts +5 -5
- package/tests/query-cache.test.ts +14 -8
- package/tests/query.test.ts +1 -0
- package/tests/realtime-exact-values.test.ts +161 -0
- package/tests/realtime-session-auth.test.ts +8 -8
- package/tests/tsconfig.json +9 -0
- package/tests/types.test.ts +40 -32
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What happens when the client is asked to read a value it was never told about.
|
|
3
|
+
*
|
|
4
|
+
* The kinds arrive from generated code, compiled into the same bundle as the app. So there are
|
|
5
|
+
* exactly two states worth distinguishing, and the design turns on telling them apart:
|
|
6
|
+
*
|
|
7
|
+
* nothing registered the project never generated, or the app imported `createClient` from the
|
|
8
|
+
* package instead of from `supatype/client`
|
|
9
|
+
* registered, unknown the column is new since the last push, or reached through an embed
|
|
10
|
+
*
|
|
11
|
+
* Neither is papered over. The previous design fell back to fetching PostgREST's OpenAPI document,
|
|
12
|
+
* which reconstructs the answer from the live database and therefore always succeeds, so the first
|
|
13
|
+
* state was indistinguishable from the second and could never be reported.
|
|
14
|
+
*/
|
|
15
|
+
import { describe, expect, it, beforeEach } from "vitest"
|
|
16
|
+
import { parseRowsExactly, tableFromPath } from "../src/exact-response.js"
|
|
17
|
+
import {
|
|
18
|
+
registerFieldKinds,
|
|
19
|
+
forgetRegisteredFieldKinds,
|
|
20
|
+
} from "../src/field-kinds-registry.js"
|
|
21
|
+
|
|
22
|
+
beforeEach(() => {
|
|
23
|
+
forgetRegisteredFieldKinds()
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
describe("tableFromPath", () => {
|
|
27
|
+
it("reads the table out of a PostgREST path", () => {
|
|
28
|
+
expect(tableFromPath("/rest/v1/job_post")).toBe("job_post")
|
|
29
|
+
expect(tableFromPath("/rest/v1/job_post?select=slug")).toBe("job_post")
|
|
30
|
+
})
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
describe("parseRowsExactly", () => {
|
|
34
|
+
it("returns a bigint column as a native bigint", () => {
|
|
35
|
+
registerFieldKinds({ version: 1, tables: { job_post: { views: "bigint" } } })
|
|
36
|
+
const out = parseRowsExactly('[{"slug":"a","views":9007199254740993}]', "job_post")
|
|
37
|
+
|
|
38
|
+
expect(out.ok).toBe(true)
|
|
39
|
+
expect(out.ok && (out.value as [{ views: bigint }])[0].views).toBe(9007199254740993n)
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
it("returns a numeric column as an exact string", () => {
|
|
43
|
+
registerFieldKinds({ version: 1, tables: { job_post: { equityPct: "numeric" } } })
|
|
44
|
+
const out = parseRowsExactly('[{"equityPct":0.20}]', "job_post")
|
|
45
|
+
|
|
46
|
+
expect(out.ok).toBe(true)
|
|
47
|
+
expect(out.ok && (out.value as [{ equityPct: string }])[0].equityPct).toBe("0.20")
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
it("leaves ordinary columns alone", () => {
|
|
51
|
+
registerFieldKinds({ version: 1, tables: { job_post: { views: "bigint" } } })
|
|
52
|
+
const out = parseRowsExactly('[{"hits":42,"rate":1.5,"title":"x"}]', "job_post")
|
|
53
|
+
|
|
54
|
+
expect(out.ok).toBe(true)
|
|
55
|
+
expect(out.ok && out.value).toEqual([{ hits: 42, rate: 1.5, title: "x" }])
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it("says the project has not generated when nothing is registered", () => {
|
|
59
|
+
const out = parseRowsExactly('[{"views":9007199254740993}]', "job_post")
|
|
60
|
+
|
|
61
|
+
expect(out.ok).toBe(false)
|
|
62
|
+
expect(!out.ok && out.columns).toEqual(["views"])
|
|
63
|
+
expect(!out.ok && out.message).toContain("supatype push")
|
|
64
|
+
expect(!out.ok && out.message).toContain('import { createClient } from "./supatype/client"')
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
it("says something different when the kinds are registered but the column is not", () => {
|
|
68
|
+
// Registered and unknown is a new column or an embed, not a missing setup step, and telling
|
|
69
|
+
// someone to run `push` when they already have would send them the wrong way.
|
|
70
|
+
registerFieldKinds({ version: 1, tables: { job_post: { views: "bigint" } } })
|
|
71
|
+
const out = parseRowsExactly('[{"author":{"views":9007199254740993}}]', "job_post")
|
|
72
|
+
|
|
73
|
+
expect(out.ok).toBe(false)
|
|
74
|
+
expect(!out.ok && out.message).toContain("embed")
|
|
75
|
+
expect(!out.ok && out.message).not.toContain('import { createClient }')
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
it("never returns a wrong number in place of an error", () => {
|
|
79
|
+
// The property that matters, in both states: a caller does not silently receive
|
|
80
|
+
// 9007199254740992 where the database holds 9007199254740993.
|
|
81
|
+
const unregistered = parseRowsExactly('[{"views":9007199254740993}]', "job_post")
|
|
82
|
+
expect(unregistered.ok).toBe(false)
|
|
83
|
+
|
|
84
|
+
registerFieldKinds({ version: 1, tables: { other: { x: "bigint" } } })
|
|
85
|
+
const wrongTable = parseRowsExactly('[{"views":9007199254740993}]', "job_post")
|
|
86
|
+
expect(wrongTable.ok).toBe(false)
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
it("does not complain about a project with nothing exact to protect", () => {
|
|
90
|
+
// Registered but empty: the schema simply has no bigInt, decimal or money column.
|
|
91
|
+
registerFieldKinds({ version: 1, tables: {} })
|
|
92
|
+
const out = parseRowsExactly('[{"hits":42}]', "job_post")
|
|
93
|
+
expect(out.ok).toBe(true)
|
|
94
|
+
})
|
|
95
|
+
})
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Exact-value columns surviving the trip through `JSON.parse`.
|
|
3
|
+
*
|
|
4
|
+
* Postgres holds 9007199254740993 and PostgREST puts those digits on the wire as an unquoted JSON
|
|
5
|
+
* number. `JSON.parse` returns 9007199254740992. The digits are correct right up until the client
|
|
6
|
+
* reads them, so the fix has to happen on the response text, before any parse.
|
|
7
|
+
*
|
|
8
|
+
* Both `money` and `decimal` are NUMERIC and both are declared `string` by the generator, so they
|
|
9
|
+
* share the `numeric` kind here. `bigInt` is declared `bigint` and becomes a native one.
|
|
10
|
+
*/
|
|
11
|
+
import { describe, expect, it } from "vitest"
|
|
12
|
+
import {
|
|
13
|
+
quoteExactNumbers,
|
|
14
|
+
coerceExactKinds,
|
|
15
|
+
findLossyNumbers,
|
|
16
|
+
stringifyWithBigInts,
|
|
17
|
+
type ExactFields,
|
|
18
|
+
} from "../src/exact-values.js"
|
|
19
|
+
|
|
20
|
+
const fields: ExactFields = { views: "bigint", price: "numeric", balance: "numeric" }
|
|
21
|
+
|
|
22
|
+
describe("quoteExactNumbers", () => {
|
|
23
|
+
it("keeps a bigint past 2^53 that JSON.parse would round", () => {
|
|
24
|
+
const body = '[{"views":9007199254740993}]'
|
|
25
|
+
// The failure this exists to prevent, stated as an assertion.
|
|
26
|
+
expect(JSON.parse(body)[0].views).toBe(9007199254740992)
|
|
27
|
+
|
|
28
|
+
const parsed = JSON.parse(quoteExactNumbers(body, fields)) as [{ views: string }]
|
|
29
|
+
expect(parsed[0].views).toBe("9007199254740993")
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
it("keeps a high-precision decimal", () => {
|
|
33
|
+
const body = '[{"price":12345678901234567890.1234}]'
|
|
34
|
+
const parsed = JSON.parse(quoteExactNumbers(body, fields)) as [{ price: string }]
|
|
35
|
+
expect(parsed[0].price).toBe("12345678901234567890.1234")
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
it("keeps trailing zeros on a money amount", () => {
|
|
39
|
+
// Not a value loss, but `19.0000` becoming `19` contradicts the declared `string` type.
|
|
40
|
+
const body = '[{"balance":19.0000}]'
|
|
41
|
+
const parsed = JSON.parse(quoteExactNumbers(body, fields)) as [{ balance: string }]
|
|
42
|
+
expect(parsed[0].balance).toBe("19.0000")
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
it("leaves columns that are not exact-value kinds alone", () => {
|
|
46
|
+
const body = '[{"hits":42,"rate":1.5}]'
|
|
47
|
+
expect(quoteExactNumbers(body, fields)).toBe(body)
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
it("leaves null alone", () => {
|
|
51
|
+
const body = '[{"views":null}]'
|
|
52
|
+
const parsed = JSON.parse(quoteExactNumbers(body, fields)) as [{ views: null }]
|
|
53
|
+
expect(parsed[0].views).toBeNull()
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
it("leaves a value that is already a string alone", () => {
|
|
57
|
+
const body = '[{"views":"9007199254740993"}]'
|
|
58
|
+
expect(quoteExactNumbers(body, fields)).toBe(body)
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
it("does not rewrite a field name that appears inside a string value", () => {
|
|
62
|
+
// The hazard that makes a regex wrong: this is prose, not a column.
|
|
63
|
+
const body = '[{"title":"the \\"views\\":123 column","hits":7}]'
|
|
64
|
+
expect(quoteExactNumbers(body, fields)).toBe(body)
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
it("handles negative and exponent literals", () => {
|
|
68
|
+
const body = '[{"views":-9007199254740993,"price":1.5e10}]'
|
|
69
|
+
const parsed = JSON.parse(quoteExactNumbers(body, fields)) as [{ views: string; price: string }]
|
|
70
|
+
expect(parsed[0].views).toBe("-9007199254740993")
|
|
71
|
+
expect(parsed[0].price).toBe("1.5e10")
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
it("handles a single-object response as well as an array", () => {
|
|
75
|
+
const body = '{"views":9007199254740993}'
|
|
76
|
+
const parsed = JSON.parse(quoteExactNumbers(body, fields)) as { views: string }
|
|
77
|
+
expect(parsed.views).toBe("9007199254740993")
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
it("does not touch an embedded resource", () => {
|
|
81
|
+
// An embedded table can have a same-named column of a different kind, and the select that
|
|
82
|
+
// produced it is not parsed here. Rewriting it would be a guess, so row level only.
|
|
83
|
+
const body = '[{"views":9007199254740993,"author":{"views":42}}]'
|
|
84
|
+
const out = quoteExactNumbers(body, fields)
|
|
85
|
+
expect(out).toContain('"views":"9007199254740993"')
|
|
86
|
+
expect(out).toContain('"author":{"views":42}')
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
it("is a no-op when no exact fields are known", () => {
|
|
90
|
+
const body = '[{"views":9007199254740993}]'
|
|
91
|
+
expect(quoteExactNumbers(body, {})).toBe(body)
|
|
92
|
+
})
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
describe("coerceExactKinds", () => {
|
|
96
|
+
it("turns a bigint column into a native bigint", () => {
|
|
97
|
+
const rows = [{ views: "9007199254740993", price: "19.0000" }]
|
|
98
|
+
const out = coerceExactKinds(rows, fields) as [{ views: bigint; price: string }]
|
|
99
|
+
expect(out[0].views).toBe(9007199254740993n)
|
|
100
|
+
expect(typeof out[0].views).toBe("bigint")
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
it("leaves numeric columns as exact strings", () => {
|
|
104
|
+
// `@supatype/types` declares Decimal and Money as `string`. There is no native exact decimal.
|
|
105
|
+
const rows = [{ price: "12345678901234567890.1234" }]
|
|
106
|
+
const out = coerceExactKinds(rows, fields) as [{ price: string }]
|
|
107
|
+
expect(out[0].price).toBe("12345678901234567890.1234")
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
it("leaves null alone", () => {
|
|
111
|
+
const out = coerceExactKinds([{ views: null }], fields) as [{ views: null }]
|
|
112
|
+
expect(out[0].views).toBeNull()
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
it("round-trips the full path, wire bytes to native bigint", () => {
|
|
116
|
+
const wire = '[{"views":9007199254740993,"balance":19.0000}]'
|
|
117
|
+
const rows = JSON.parse(quoteExactNumbers(wire, fields)) as unknown
|
|
118
|
+
const out = coerceExactKinds(rows, fields) as [{ views: bigint; balance: string }]
|
|
119
|
+
expect(out[0].views).toBe(9007199254740993n)
|
|
120
|
+
expect(out[0].balance).toBe("19.0000")
|
|
121
|
+
})
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
describe("findLossyNumbers", () => {
|
|
125
|
+
it("names a column whose literal will not survive the parse", () => {
|
|
126
|
+
// The safety net for when column metadata could not be loaded. Without it, a failed metadata
|
|
127
|
+
// fetch would quietly restore the corruption this module exists to remove.
|
|
128
|
+
expect(findLossyNumbers('[{"views":9007199254740993}]')).toEqual(["views"])
|
|
129
|
+
})
|
|
130
|
+
|
|
131
|
+
it("says nothing about numbers that round-trip exactly", () => {
|
|
132
|
+
expect(findLossyNumbers('[{"hits":42,"rate":1.5,"edge":9007199254740992}]')).toEqual([])
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
it("catches a decimal that loses digits", () => {
|
|
136
|
+
expect(findLossyNumbers('[{"price":12345678901234567890.1234}]')).toEqual(["price"])
|
|
137
|
+
})
|
|
138
|
+
|
|
139
|
+
it("does not flag trailing zeros, which lose no value", () => {
|
|
140
|
+
// `19.0000` parsing to `19` is a type-fidelity problem, not a wrong number, and throwing on it
|
|
141
|
+
// would break every project with a money column and no metadata.
|
|
142
|
+
expect(findLossyNumbers('[{"balance":19.0000}]')).toEqual([])
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
it("reports each affected column once", () => {
|
|
146
|
+
const body = '[{"views":9007199254740993},{"views":9007199254740995}]'
|
|
147
|
+
expect(findLossyNumbers(body)).toEqual(["views"])
|
|
148
|
+
})
|
|
149
|
+
|
|
150
|
+
it("ignores digits inside string values", () => {
|
|
151
|
+
expect(findLossyNumbers('[{"title":"id 9007199254740993 here"}]')).toEqual([])
|
|
152
|
+
})
|
|
153
|
+
})
|
|
154
|
+
|
|
155
|
+
describe("stringifyWithBigInts", () => {
|
|
156
|
+
it("serialises a bigint rather than throwing", () => {
|
|
157
|
+
// `JSON.stringify` throws on a bigint, so writing back a row that was just read would fail
|
|
158
|
+
// the moment the generated types started declaring bigint.
|
|
159
|
+
expect(() => JSON.stringify({ views: 1n })).toThrow(TypeError)
|
|
160
|
+
expect(stringifyWithBigInts({ views: 9007199254740993n })).toBe('{"views":"9007199254740993"}')
|
|
161
|
+
})
|
|
162
|
+
|
|
163
|
+
it("leaves everything else as JSON.stringify would", () => {
|
|
164
|
+
const body = { a: 1, b: "x", c: null, d: [1, 2], e: { f: true } }
|
|
165
|
+
expect(stringifyWithBigInts(body)).toBe(JSON.stringify(body))
|
|
166
|
+
})
|
|
167
|
+
|
|
168
|
+
it("handles a bigint nested in an array", () => {
|
|
169
|
+
expect(stringifyWithBigInts({ rows: [{ views: 1n }] })).toBe('{"rows":[{"views":"1"}]}')
|
|
170
|
+
})
|
|
171
|
+
})
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How the client learns which columns a JSON parser would destroy.
|
|
3
|
+
*
|
|
4
|
+
* The generated `supatype/client.ts` calls `registerFieldKinds` when it is imported, and an app
|
|
5
|
+
* imports `createClient` from there rather than from this package. So the kinds arrive by the same
|
|
6
|
+
* import that brings the client, compiled into the same bundle, with nothing fetched and nothing
|
|
7
|
+
* read from disk.
|
|
8
|
+
*
|
|
9
|
+
* This replaces reading `field-kinds.json` off the filesystem and falling back to PostgREST's
|
|
10
|
+
* OpenAPI document. The fallback always succeeded, which meant a project that had never generated
|
|
11
|
+
* looked identical to one that had, and the gap it papered over could never be reported.
|
|
12
|
+
*/
|
|
13
|
+
import { describe, expect, it, beforeEach } from "vitest"
|
|
14
|
+
import {
|
|
15
|
+
registerFieldKinds,
|
|
16
|
+
registeredFieldsFor,
|
|
17
|
+
fieldKindsAreRegistered,
|
|
18
|
+
forgetRegisteredFieldKinds,
|
|
19
|
+
} from "../src/field-kinds-registry.js"
|
|
20
|
+
|
|
21
|
+
const document = {
|
|
22
|
+
version: 1 as const,
|
|
23
|
+
tables: {
|
|
24
|
+
job_post: { views: "bigint" as const, equityPct: "numeric" as const },
|
|
25
|
+
landing_page: { price: "numeric" as const },
|
|
26
|
+
},
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
beforeEach(() => {
|
|
30
|
+
forgetRegisteredFieldKinds()
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
describe("registerFieldKinds", () => {
|
|
34
|
+
it("makes a table's exact columns available", () => {
|
|
35
|
+
registerFieldKinds(document)
|
|
36
|
+
expect(registeredFieldsFor("job_post")).toEqual({ views: "bigint", equityPct: "numeric" })
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it("reports nothing for a table the schema does not describe", () => {
|
|
40
|
+
registerFieldKinds(document)
|
|
41
|
+
expect(registeredFieldsFor("unknown_table")).toEqual({})
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
it("knows whether anything registered at all", () => {
|
|
45
|
+
// The distinction the OpenAPI fallback could never draw: a project that never generated is
|
|
46
|
+
// not the same as a project whose tables happen to have no exact columns.
|
|
47
|
+
expect(fieldKindsAreRegistered()).toBe(false)
|
|
48
|
+
registerFieldKinds(document)
|
|
49
|
+
expect(fieldKindsAreRegistered()).toBe(true)
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
it("counts an empty schema as registered", () => {
|
|
53
|
+
// A project with no bigInt, decimal or money column still generated. Treating it as absent
|
|
54
|
+
// would make the safety net shout at a project that has nothing to protect.
|
|
55
|
+
registerFieldKinds({ version: 1, tables: {} })
|
|
56
|
+
expect(fieldKindsAreRegistered()).toBe(true)
|
|
57
|
+
expect(registeredFieldsFor("anything")).toEqual({})
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
it("lets a later registration replace an earlier one", () => {
|
|
61
|
+
// Two clients against two projects in one process, which is ordinary in a monorepo.
|
|
62
|
+
registerFieldKinds(document)
|
|
63
|
+
registerFieldKinds({ version: 1, tables: { other: { total: "numeric" } } })
|
|
64
|
+
expect(registeredFieldsFor("other")).toEqual({ total: "numeric" })
|
|
65
|
+
expect(registeredFieldsFor("job_post")).toEqual({})
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
it("ignores a version it does not understand rather than guessing", () => {
|
|
69
|
+
registerFieldKinds({ version: 99, tables: { job_post: { views: "bigint" } } } as never)
|
|
70
|
+
expect(fieldKindsAreRegistered()).toBe(false)
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
it("drops kinds it does not recognise", () => {
|
|
74
|
+
registerFieldKinds({
|
|
75
|
+
version: 1,
|
|
76
|
+
tables: { job_post: { views: "bigint", weird: "quantum" } },
|
|
77
|
+
} as never)
|
|
78
|
+
expect(registeredFieldsFor("job_post")).toEqual({ views: "bigint" })
|
|
79
|
+
})
|
|
80
|
+
})
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The schema the test suite declares to `@supatype/client`.
|
|
3
|
+
*
|
|
4
|
+
* Module augmentation is global to a compilation. Once every test file shares one program, a
|
|
5
|
+
* `declare module` block written inside one of them applies to all of them, so a table declared in
|
|
6
|
+
* `types.test.ts` silently constrains `data-plane-auth.test.ts`. That is not a quirk to work
|
|
7
|
+
* around, it is what augmentation is: there is one `SupatypeModels`, and the suite has one schema.
|
|
8
|
+
*
|
|
9
|
+
* So it lives here, covering every table any test queries, rather than in whichever file happened
|
|
10
|
+
* to need it first.
|
|
11
|
+
*
|
|
12
|
+
* Declared with `type` rather than `interface` deliberately. An interface has no implicit index
|
|
13
|
+
* signature, so it does not satisfy `Record<string, unknown>` in `TableDef`, and a fixture written
|
|
14
|
+
* as an interface fails the `AnyDatabase` constraint. Generated output emits type aliases, so this
|
|
15
|
+
* matches what real projects have.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
export type Post = {
|
|
19
|
+
id: string
|
|
20
|
+
title: string
|
|
21
|
+
status: "draft" | "published"
|
|
22
|
+
user_id: string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export type PostInsert = {
|
|
26
|
+
title: string
|
|
27
|
+
status?: "draft" | "published" | undefined
|
|
28
|
+
user_id: string
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export type Comment = {
|
|
32
|
+
id: string
|
|
33
|
+
post_id: string
|
|
34
|
+
body: string
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Singular, and distinct from `posts`: several tests query it by that name. */
|
|
38
|
+
export type SinglePost = {
|
|
39
|
+
id: string
|
|
40
|
+
title: string
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export type Author = {
|
|
44
|
+
id: string
|
|
45
|
+
name: string
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
declare module "../../src/types.js" {
|
|
49
|
+
interface SupatypeModels {
|
|
50
|
+
posts: { Row: Post; Insert: PostInsert; Update: Partial<PostInsert> }
|
|
51
|
+
comments: { Row: Comment; Insert: Omit<Comment, "id">; Update: Partial<Comment> }
|
|
52
|
+
post: { Row: SinglePost; Insert: Omit<SinglePost, "id">; Update: Partial<SinglePost> }
|
|
53
|
+
authors: { Row: Author; Insert: Omit<Author, "id">; Update: Partial<Author> }
|
|
54
|
+
}
|
|
55
|
+
}
|
|
@@ -43,12 +43,12 @@ function sessionFor(userId: string, accessToken = "token"): Session {
|
|
|
43
43
|
id: userId,
|
|
44
44
|
email: `${userId}@example.com`,
|
|
45
45
|
role: "authenticated",
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
46
|
+
appMetadata: {},
|
|
47
|
+
userMetadata: {},
|
|
48
|
+
createdAt: "2024-01-01T00:00:00Z",
|
|
49
|
+
updatedAt: "2024-01-01T00:00:00Z",
|
|
50
50
|
},
|
|
51
|
-
}
|
|
51
|
+
}
|
|
52
52
|
}
|
|
53
53
|
|
|
54
54
|
describe("onIdentityChange", () => {
|
|
@@ -69,14 +69,20 @@ describe("QueryBuilder.cache", () => {
|
|
|
69
69
|
cache,
|
|
70
70
|
).cache({ ttl: 60_000 })
|
|
71
71
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
expect(
|
|
72
|
+
// Counted per table URL rather than across every request, because the client also fetches the
|
|
73
|
+
// project's column types once so it can keep bigInt, decimal and money columns exact. That
|
|
74
|
+
// request is cached per project and is not what this test is about.
|
|
75
|
+
const tableCalls = (): number =>
|
|
76
|
+
fetchMock.mock.calls.filter((call) => String(call[0]).includes("/rest/v1/posts")).length
|
|
77
|
+
|
|
78
|
+
const r1 = await qb
|
|
79
|
+
expect(r1.data).toEqual([{ id: 1 }])
|
|
80
|
+
expect(tableCalls()).toBe(1)
|
|
81
|
+
|
|
82
|
+
const r2 = await qb
|
|
83
|
+
expect(r2.data).toEqual([{ id: 1 }])
|
|
84
|
+
expect(r2.meta?.cacheStatus).toBe("HIT")
|
|
85
|
+
expect(tableCalls()).toBe(1)
|
|
80
86
|
})
|
|
81
87
|
|
|
82
88
|
it("sends X-Supatype-Cache when server: true", async () => {
|
package/tests/query.test.ts
CHANGED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The same row, read two ways, holding the same values.
|
|
3
|
+
*
|
|
4
|
+
* A row read over REST goes through `parseRowsExactly`, so a `bigInt` column arrives as a native
|
|
5
|
+
* bigint and a `decimal` as its exact string. The same row arriving over a subscription used to be
|
|
6
|
+
* a rounded number, because the realtime path had none of that: the service parsed the WAL with a
|
|
7
|
+
* plain `JSON.parse` and the client parsed the frame with another.
|
|
8
|
+
*
|
|
9
|
+
* The service now carries exact columns as strings and says which they are, reading the kinds from
|
|
10
|
+
* the database's own declared types. That is why the frames below name `exactColumns`, and why the
|
|
11
|
+
* client does not consult the local registry here: the frame is authoritative, so a project that
|
|
12
|
+
* never ran `supatype push` still reads the value correctly.
|
|
13
|
+
*/
|
|
14
|
+
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
|
|
15
|
+
import { RealtimeClient } from "../src/realtime.js"
|
|
16
|
+
import {
|
|
17
|
+
createMockWebSocketClass,
|
|
18
|
+
simulateServerMessage,
|
|
19
|
+
type MockWebSocketInstance,
|
|
20
|
+
} from "./helpers/mock-websocket.js"
|
|
21
|
+
|
|
22
|
+
const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 10))
|
|
23
|
+
|
|
24
|
+
let instances: MockWebSocketInstance[]
|
|
25
|
+
let originalWebSocket: typeof WebSocket
|
|
26
|
+
|
|
27
|
+
beforeEach(() => {
|
|
28
|
+
const mock = createMockWebSocketClass()
|
|
29
|
+
instances = mock.instances
|
|
30
|
+
originalWebSocket = globalThis.WebSocket
|
|
31
|
+
globalThis.WebSocket = mock.MockWebSocket
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
afterEach(() => {
|
|
35
|
+
globalThis.WebSocket = originalWebSocket
|
|
36
|
+
vi.restoreAllMocks()
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
/** Subscribe to a table, deliver one change frame, and hand back what the listener was given. */
|
|
40
|
+
async function deliver(frame: Record<string, unknown>): Promise<Record<string, unknown> | null> {
|
|
41
|
+
const client = new RealtimeClient("http://localhost:9999", { apikey: "anon" })
|
|
42
|
+
let seen: Record<string, unknown> | null = null
|
|
43
|
+
|
|
44
|
+
client
|
|
45
|
+
.channel("public:subscription")
|
|
46
|
+
.on("postgres_changes", { event: "INSERT" }, (payload) => {
|
|
47
|
+
seen = payload.new
|
|
48
|
+
})
|
|
49
|
+
.subscribe()
|
|
50
|
+
|
|
51
|
+
await settle()
|
|
52
|
+
const ws = instances[0]
|
|
53
|
+
if (!ws) throw new Error("no socket was opened")
|
|
54
|
+
simulateServerMessage(ws, frame)
|
|
55
|
+
await settle()
|
|
56
|
+
return seen
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** A change frame as the service now sends one: exact columns as strings, and named. */
|
|
60
|
+
function changeFrame(
|
|
61
|
+
row: Record<string, unknown>,
|
|
62
|
+
exactColumns?: Record<string, string>,
|
|
63
|
+
): Record<string, unknown> {
|
|
64
|
+
return {
|
|
65
|
+
type: "change",
|
|
66
|
+
channel: "public:subscription",
|
|
67
|
+
event: "INSERT",
|
|
68
|
+
payload: { old: null, new: row },
|
|
69
|
+
...(exactColumns ? { exactColumns } : {}),
|
|
70
|
+
timestamp: "2026-01-01T00:00:00Z",
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
describe("a change carrying exact columns", () => {
|
|
75
|
+
it("gives a bigint column a native bigint", async () => {
|
|
76
|
+
const row = await deliver(
|
|
77
|
+
changeFrame({ id: "a", externalId: "9007199254740993" }, { externalId: "bigint" }),
|
|
78
|
+
)
|
|
79
|
+
expect(row?.["externalId"]).toBe(9007199254740993n)
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
it("keeps the value a double would have rounded", async () => {
|
|
83
|
+
// The control that names the defect. It cannot be written as a numeric literal, because a
|
|
84
|
+
// literal of 9007199254740993 in this file is already 9007199254740992 by the time it runs:
|
|
85
|
+
// that is the whole problem. So the rounded value is derived, and the delivered one compared
|
|
86
|
+
// against it.
|
|
87
|
+
const rounded = BigInt(Number("9007199254740993"))
|
|
88
|
+
expect(rounded).toBe(9007199254740992n)
|
|
89
|
+
|
|
90
|
+
const row = await deliver(
|
|
91
|
+
changeFrame({ id: "a", externalId: "9007199254740993" }, { externalId: "bigint" }),
|
|
92
|
+
)
|
|
93
|
+
expect(row?.["externalId"]).not.toBe(rounded)
|
|
94
|
+
expect(String(row?.["externalId"])).toBe("9007199254740993")
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
it("leaves a numeric column as its exact string, scale and all", async () => {
|
|
98
|
+
// `@supatype/types` declares Decimal and Money as string, because JavaScript has no exact
|
|
99
|
+
// decimal. 10.00 and 10 are the same number and different values.
|
|
100
|
+
const row = await deliver(changeFrame({ unitAmount: "10.00" }, { unitAmount: "numeric" }))
|
|
101
|
+
expect(row?.["unitAmount"]).toBe("10.00")
|
|
102
|
+
})
|
|
103
|
+
|
|
104
|
+
it("touches nothing the frame did not name", async () => {
|
|
105
|
+
const row = await deliver(
|
|
106
|
+
changeFrame(
|
|
107
|
+
{ id: "a", quantity: 42, title: "unchanged", externalId: "12" },
|
|
108
|
+
{ externalId: "bigint" },
|
|
109
|
+
),
|
|
110
|
+
)
|
|
111
|
+
expect(row?.["quantity"]).toBe(42)
|
|
112
|
+
expect(row?.["title"]).toBe("unchanged")
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
it("coerces a small bigint too, because the database declared it one", async () => {
|
|
116
|
+
// Not decided by whether the value happens to be large: a column typed bigint reads as a
|
|
117
|
+
// bigint every time, or an application comparing against one is wrong half the time.
|
|
118
|
+
const row = await deliver(changeFrame({ externalId: "12" }, { externalId: "bigint" }))
|
|
119
|
+
expect(row?.["externalId"]).toBe(12n)
|
|
120
|
+
})
|
|
121
|
+
|
|
122
|
+
it("applies the same coercion to the old record of an update", async () => {
|
|
123
|
+
const client = new RealtimeClient("http://localhost:9999", { apikey: "anon" })
|
|
124
|
+
let old: Record<string, unknown> | null = null
|
|
125
|
+
client
|
|
126
|
+
.channel("public:subscription")
|
|
127
|
+
.on("postgres_changes", { event: "UPDATE" }, (payload) => {
|
|
128
|
+
old = payload.old
|
|
129
|
+
})
|
|
130
|
+
.subscribe()
|
|
131
|
+
await settle()
|
|
132
|
+
const ws = instances[0]
|
|
133
|
+
if (!ws) throw new Error("no socket was opened")
|
|
134
|
+
simulateServerMessage(ws, {
|
|
135
|
+
type: "change",
|
|
136
|
+
channel: "public:subscription",
|
|
137
|
+
event: "UPDATE",
|
|
138
|
+
payload: { old: { externalId: "9007199254740993" }, new: { externalId: "9007199254740995" } },
|
|
139
|
+
exactColumns: { externalId: "bigint" },
|
|
140
|
+
timestamp: "2026-01-01T00:00:00Z",
|
|
141
|
+
})
|
|
142
|
+
await settle()
|
|
143
|
+
expect(old?.["externalId"]).toBe(9007199254740993n)
|
|
144
|
+
})
|
|
145
|
+
})
|
|
146
|
+
|
|
147
|
+
describe("a change from a table with nothing exact", () => {
|
|
148
|
+
it("arrives unchanged when the frame names no exact columns", async () => {
|
|
149
|
+
// Which is most tables, and the frame carries no extra field for them at all.
|
|
150
|
+
const row = await deliver(changeFrame({ id: "a", views: 3, title: "hello" }))
|
|
151
|
+
expect(row).toEqual({ id: "a", views: 3, title: "hello" })
|
|
152
|
+
})
|
|
153
|
+
|
|
154
|
+
it("survives a frame from a service too old to send the field", async () => {
|
|
155
|
+
// An upgrade puts a new client in front of an old service. The values are already rounded by
|
|
156
|
+
// then and nothing here can recover them, but the payload must still be delivered.
|
|
157
|
+
const row = await deliver(changeFrame({ id: "a", externalId: 9007199254740992 }))
|
|
158
|
+
expect(row?.["id"]).toBe("a")
|
|
159
|
+
expect(row?.["externalId"]).toBe(9007199254740992)
|
|
160
|
+
})
|
|
161
|
+
})
|
|
@@ -51,12 +51,12 @@ function session(accessToken: string): Session {
|
|
|
51
51
|
id: "user-1",
|
|
52
52
|
email: "a@b.com",
|
|
53
53
|
role: "authenticated",
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
54
|
+
appMetadata: {},
|
|
55
|
+
userMetadata: {},
|
|
56
|
+
createdAt: "2024-01-01T00:00:00Z",
|
|
57
|
+
updatedAt: "2024-01-01T00:00:00Z",
|
|
58
58
|
},
|
|
59
|
-
}
|
|
59
|
+
}
|
|
60
60
|
}
|
|
61
61
|
|
|
62
62
|
describe("realtime authenticates as the session, not as anon", () => {
|
|
@@ -93,7 +93,7 @@ describe("realtime authenticates as the session, not as anon", () => {
|
|
|
93
93
|
|
|
94
94
|
it("opens the socket with the token the provider returns at connect time", async () => {
|
|
95
95
|
let token = "first"
|
|
96
|
-
const client = new RealtimeClient("ws://localhost:4000/realtime", () => bearerHeaders(token))
|
|
96
|
+
const client = new RealtimeClient("ws://localhost:4000/realtime", async () => bearerHeaders(token))
|
|
97
97
|
client.channel("public:task").subscribe()
|
|
98
98
|
await settle()
|
|
99
99
|
expect(tokenOf(MockWS.instances[0]!)).toBe("first")
|
|
@@ -107,7 +107,7 @@ describe("realtime authenticates as the session, not as anon", () => {
|
|
|
107
107
|
})
|
|
108
108
|
|
|
109
109
|
it("does not reconnect when the token has not changed", async () => {
|
|
110
|
-
const client = new RealtimeClient("ws://localhost:4000/realtime", () => bearerHeaders("same"))
|
|
110
|
+
const client = new RealtimeClient("ws://localhost:4000/realtime", async () => bearerHeaders("same"))
|
|
111
111
|
client.channel("public:task").subscribe()
|
|
112
112
|
await settle()
|
|
113
113
|
|
|
@@ -119,7 +119,7 @@ describe("realtime authenticates as the session, not as anon", () => {
|
|
|
119
119
|
|
|
120
120
|
it("re-subscribes every channel on the replacement socket", async () => {
|
|
121
121
|
let token = "before"
|
|
122
|
-
const client = new RealtimeClient("ws://localhost:4000/realtime", () => bearerHeaders(token))
|
|
122
|
+
const client = new RealtimeClient("ws://localhost:4000/realtime", async () => bearerHeaders(token))
|
|
123
123
|
client.channel("public:task").subscribe()
|
|
124
124
|
await settle()
|
|
125
125
|
|