@supatype/client 0.3.6 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +58 -31
  3. package/.turbo/turbo-typecheck.log +2 -2
  4. package/LICENSE +1 -1
  5. package/dist/auth-redirect.d.ts +48 -0
  6. package/dist/auth-redirect.d.ts.map +1 -0
  7. package/dist/auth-redirect.js +70 -0
  8. package/dist/auth-redirect.js.map +1 -0
  9. package/dist/auth.d.ts +78 -4
  10. package/dist/auth.d.ts.map +1 -1
  11. package/dist/auth.js +373 -274
  12. package/dist/auth.js.map +1 -1
  13. package/dist/bindings.d.ts +16 -0
  14. package/dist/bindings.d.ts.map +1 -0
  15. package/dist/bindings.js +13 -0
  16. package/dist/bindings.js.map +1 -0
  17. package/dist/caller-types.d.ts +18 -0
  18. package/dist/caller-types.d.ts.map +1 -0
  19. package/dist/caller-types.js +22 -0
  20. package/dist/caller-types.js.map +1 -0
  21. package/dist/draft-create.d.ts +12 -0
  22. package/dist/draft-create.d.ts.map +1 -0
  23. package/dist/draft-create.js +47 -0
  24. package/dist/draft-create.js.map +1 -0
  25. package/dist/draft-models-registry.d.ts +27 -0
  26. package/dist/draft-models-registry.d.ts.map +1 -0
  27. package/dist/draft-models-registry.js +61 -0
  28. package/dist/draft-models-registry.js.map +1 -0
  29. package/dist/error-codes-doc.d.ts +1 -1
  30. package/dist/error-codes-doc.d.ts.map +1 -1
  31. package/dist/error-codes-doc.js +42 -34
  32. package/dist/error-codes-doc.js.map +1 -1
  33. package/dist/errors.d.ts +102 -60
  34. package/dist/errors.d.ts.map +1 -1
  35. package/dist/errors.js +69 -28
  36. package/dist/errors.js.map +1 -1
  37. package/dist/exact-response.d.ts.map +1 -1
  38. package/dist/exact-response.js +2 -1
  39. package/dist/exact-response.js.map +1 -1
  40. package/dist/exact-values.d.ts +2 -0
  41. package/dist/exact-values.d.ts.map +1 -1
  42. package/dist/exact-values.js +12 -10
  43. package/dist/exact-values.js.map +1 -1
  44. package/dist/fetch-with-retry.d.ts +21 -6
  45. package/dist/fetch-with-retry.d.ts.map +1 -1
  46. package/dist/fetch-with-retry.js +67 -53
  47. package/dist/fetch-with-retry.js.map +1 -1
  48. package/dist/field-kinds-registry.d.ts +11 -3
  49. package/dist/field-kinds-registry.d.ts.map +1 -1
  50. package/dist/field-kinds-registry.js +10 -6
  51. package/dist/field-kinds-registry.js.map +1 -1
  52. package/dist/filters.d.ts +51 -0
  53. package/dist/filters.d.ts.map +1 -0
  54. package/dist/filters.js +117 -0
  55. package/dist/filters.js.map +1 -0
  56. package/dist/generated-client.d.ts +7 -0
  57. package/dist/generated-client.d.ts.map +1 -0
  58. package/dist/generated-client.js +7 -0
  59. package/dist/generated-client.js.map +1 -0
  60. package/dist/graphql-document.d.ts +39 -0
  61. package/dist/graphql-document.d.ts.map +1 -0
  62. package/dist/graphql-document.js +228 -0
  63. package/dist/graphql-document.js.map +1 -0
  64. package/dist/graphql-json.d.ts +56 -0
  65. package/dist/graphql-json.d.ts.map +1 -0
  66. package/dist/graphql-json.js +220 -0
  67. package/dist/graphql-json.js.map +1 -0
  68. package/dist/graphql-transport.d.ts +28 -0
  69. package/dist/graphql-transport.d.ts.map +1 -0
  70. package/dist/graphql-transport.js +77 -0
  71. package/dist/graphql-transport.js.map +1 -0
  72. package/dist/index.d.ts +103 -40
  73. package/dist/index.d.ts.map +1 -1
  74. package/dist/index.js +153 -157
  75. package/dist/index.js.map +1 -1
  76. package/dist/json.d.ts +61 -0
  77. package/dist/json.d.ts.map +1 -0
  78. package/dist/json.js +83 -0
  79. package/dist/json.js.map +1 -0
  80. package/dist/jwt.d.ts +16 -0
  81. package/dist/jwt.d.ts.map +1 -0
  82. package/dist/jwt.js +37 -0
  83. package/dist/jwt.js.map +1 -0
  84. package/dist/live-preview.d.ts +23 -0
  85. package/dist/live-preview.d.ts.map +1 -0
  86. package/dist/live-preview.js +28 -0
  87. package/dist/live-preview.js.map +1 -0
  88. package/dist/mutation-request.d.ts +17 -0
  89. package/dist/mutation-request.d.ts.map +1 -0
  90. package/dist/mutation-request.js +41 -0
  91. package/dist/mutation-request.js.map +1 -0
  92. package/dist/preview.d.ts.map +1 -1
  93. package/dist/preview.js +8 -6
  94. package/dist/preview.js.map +1 -1
  95. package/dist/query-cache.d.ts.map +1 -1
  96. package/dist/query-cache.js +19 -13
  97. package/dist/query-cache.js.map +1 -1
  98. package/dist/query.d.ts +108 -29
  99. package/dist/query.d.ts.map +1 -1
  100. package/dist/query.js +294 -224
  101. package/dist/query.js.map +1 -1
  102. package/dist/realtime.d.ts +20 -2
  103. package/dist/realtime.d.ts.map +1 -1
  104. package/dist/realtime.js +105 -12
  105. package/dist/realtime.js.map +1 -1
  106. package/dist/select-types.d.ts +99 -0
  107. package/dist/select-types.d.ts.map +1 -0
  108. package/dist/select-types.js +2 -0
  109. package/dist/select-types.js.map +1 -0
  110. package/dist/storage.d.ts +81 -11
  111. package/dist/storage.d.ts.map +1 -1
  112. package/dist/storage.js +129 -37
  113. package/dist/storage.js.map +1 -1
  114. package/dist/table-subscription.d.ts +69 -0
  115. package/dist/table-subscription.d.ts.map +1 -0
  116. package/dist/table-subscription.js +93 -0
  117. package/dist/table-subscription.js.map +1 -0
  118. package/dist/types.d.ts +84 -5
  119. package/dist/types.d.ts.map +1 -1
  120. package/dist/types.js +6 -1
  121. package/dist/types.js.map +1 -1
  122. package/package.json +6 -2
  123. package/src/auth-redirect.ts +90 -0
  124. package/src/auth.ts +421 -280
  125. package/src/bindings.ts +22 -0
  126. package/src/caller-types.ts +27 -0
  127. package/src/draft-create.ts +51 -0
  128. package/src/draft-models-registry.ts +81 -0
  129. package/src/error-codes-doc.ts +44 -35
  130. package/src/errors.ts +72 -28
  131. package/src/exact-response.ts +2 -1
  132. package/src/exact-values.ts +16 -9
  133. package/src/fetch-with-retry.ts +80 -70
  134. package/src/field-kinds-registry.ts +22 -9
  135. package/src/filters.ts +133 -0
  136. package/src/generated-client.ts +6 -0
  137. package/src/graphql-document.ts +234 -0
  138. package/src/graphql-json.ts +243 -0
  139. package/src/graphql-transport.ts +97 -0
  140. package/src/index.ts +272 -201
  141. package/src/json.ts +117 -0
  142. package/src/jwt.ts +37 -0
  143. package/src/live-preview.ts +37 -0
  144. package/src/mutation-request.ts +66 -0
  145. package/src/preview.ts +9 -11
  146. package/src/query-cache.ts +19 -16
  147. package/src/query.ts +389 -270
  148. package/src/realtime.ts +116 -13
  149. package/src/select-types.ts +184 -0
  150. package/src/storage.ts +214 -43
  151. package/src/table-subscription.ts +160 -0
  152. package/src/types.ts +90 -5
  153. package/tests/auth-error-codes.test.ts +53 -0
  154. package/tests/auth-errors.test.ts +84 -0
  155. package/tests/auth-events.test.ts +136 -0
  156. package/tests/auth-url-session.test.ts +204 -0
  157. package/tests/auth.test.ts +122 -26
  158. package/tests/count.test.ts +60 -0
  159. package/tests/data-plane-auth.test.ts +21 -46
  160. package/tests/draft-insert.integration.test.ts +118 -0
  161. package/tests/draft-insert.test.ts +225 -0
  162. package/tests/draft-profile.test.ts +55 -84
  163. package/tests/draft-update.integration.test.ts +122 -0
  164. package/tests/draft-update.test.ts +174 -0
  165. package/tests/dynamic-headers.test.ts +45 -0
  166. package/tests/entry-points.test.ts +42 -0
  167. package/tests/exact-response.test.ts +4 -4
  168. package/tests/exact-values.test.ts +14 -25
  169. package/tests/field-kinds-registry.test.ts +3 -3
  170. package/tests/filters.test.ts +146 -0
  171. package/tests/graphql-json.test.ts +199 -0
  172. package/tests/helpers/mock-websocket.ts +44 -11
  173. package/tests/helpers/oauth-binding.ts +92 -0
  174. package/tests/helpers/signup-binding.ts +73 -0
  175. package/tests/helpers/socket-swap.ts +139 -0
  176. package/tests/mfa-totp-integration.test.ts +13 -20
  177. package/tests/postgrest-error-codes.test.ts +85 -0
  178. package/tests/query-cache.test.ts +116 -117
  179. package/tests/query.test.ts +29 -31
  180. package/tests/rate-limit-integration.test.ts +4 -12
  181. package/tests/realtime-exact-values.test.ts +2 -4
  182. package/tests/realtime-presence.test.ts +75 -0
  183. package/tests/realtime-session-auth.test.ts +2 -4
  184. package/tests/realtime-swap-status.test.ts +62 -0
  185. package/tests/retry-integration.test.ts +3 -8
  186. package/tests/retry-policy.test.ts +166 -0
  187. package/tests/rpc-resend.test.ts +24 -0
  188. package/tests/server-bodies.test.ts +139 -0
  189. package/tests/serverless.test.ts +2 -2
  190. package/tests/signed-url-absolute.test.ts +2 -5
  191. package/tests/storage-object-shape.test.ts +101 -0
  192. package/tests/storage-quota-integration.test.ts +3 -2
  193. package/tests/storage-reference-url.test.ts +51 -0
  194. package/tests/storage-upload-browser.test.ts +71 -0
  195. package/tests/storage-upload-limit-integration.test.ts +12 -22
  196. package/tests/subscribe-frame.test.ts +5 -11
  197. package/tests/support/fetch-mock.ts +64 -0
  198. package/tests/support/storage-object.ts +37 -0
  199. package/tests/table-subscribe.test.ts +13 -13
  200. package/tests/table-subscription.test.ts +105 -0
  201. package/tests/table-transport.test.ts +94 -0
  202. package/tests/tsconfig.json +1 -1
  203. package/tests/types.test.ts +153 -1
  204. package/tsconfig.json +1 -1
  205. package/tsconfig.tsbuildinfo +1 -1
package/src/query.ts CHANGED
@@ -1,29 +1,41 @@
1
1
  import type { QueryCache, QueryCacheOptions, CacheStatus } from "./query-cache.js"
2
2
  import { buildCacheKey, defaultQueryCache } from "./query-cache.js"
3
- import type { MaskedField, QueryResult, SelectQueryOptions, SupatypeError } from "./types.js"
3
+ import type { MaskedField, QueryResult, SelectQueryOptions, SupatypeError, TableDef } from "./types.js"
4
+ import { DRAFT_SCHEMA, PUBLISHING_SCHEMA } from "./types.js"
5
+ import { createCall, createdKeys, inCreatedOrder, readBackColumns } from "./draft-create.js"
6
+ import type { SelectRow } from "./select-types.js"
4
7
  import { parseRowsExactly, tableFromPath } from "./exact-response.js"
5
8
  import { stringifyWithBigInts } from "./exact-values.js"
9
+ import { FilterBuilder } from "./filters.js"
10
+ import { PostgrestErrorCodes, transportFailure } from "./errors.js"
11
+ import { plainFetch, type FetchOptions, type RequestTransport } from "./fetch-with-retry.js"
12
+ import { isJsonObject, isOneOf, readJsonObject, refusalText } from "./json.js"
13
+ import { bearerRole } from "./jwt.js"
6
14
 
7
15
  const DEBUG_AUTH =
8
16
  (typeof process !== "undefined" && process.env["NEXT_PUBLIC_SUPATYPE_DEBUG_AUTH"] === "1") ||
9
17
  (typeof process !== "undefined" && process.env["SUPATYPE_DEBUG_AUTH"] === "1")
10
18
 
11
- function decodeJwtRoleFromAuthHeader(headers: Record<string, string>): string | null {
12
- const auth = headers["Authorization"] ?? headers["authorization"]
13
- if (auth === undefined || !auth.startsWith("Bearer ")) return null
14
- const token = auth.slice("Bearer ".length)
15
- const parts = token.split(".")
16
- if (parts.length !== 3) return null
17
- try {
18
- const payloadJson =
19
- typeof atob === "function"
20
- ? atob(parts[1] ?? "")
21
- : Buffer.from(parts[1] ?? "", "base64").toString("utf-8")
22
- const payload = JSON.parse(payloadJson) as Record<string, unknown>
23
- return typeof payload["role"] === "string" ? payload["role"] : null
24
- } catch {
25
- return null
26
- }
19
+ /**
20
+ * The boundary between a parsed body and the row type the caller declared for the table.
21
+ *
22
+ * PostgREST answers a table read or write with JSON objects, which is what is checked. That each
23
+ * object holds `TRow`'s columns is the generated schema's claim about the database, or the
24
+ * caller's own for `select<TResult>()`, which nothing on the client can check.
25
+ */
26
+ function isCallerRow<TRow>(value: unknown): value is TRow {
27
+ return isJsonObject(value)
28
+ }
29
+
30
+ /** The rows a body holds: an array of objects, or one object (the single-object Accept). */
31
+ function callerRows<TRow>(value: unknown): TRow[] | null {
32
+ if (Array.isArray(value)) return value.every(isCallerRow<TRow>) ? value : null
33
+ return isCallerRow<TRow>(value) ? [value] : null
34
+ }
35
+
36
+ /** The body was JSON but not rows: PostgREST does not answer a table request that way. */
37
+ function notRows(status: number): SupatypeError {
38
+ return { message: `Unexpected response body: expected rows (HTTP ${status})`, status }
27
39
  }
28
40
 
29
41
  /**
@@ -47,6 +59,73 @@ export function parseMaskedFields(header: string | null): MaskedField[] | undefi
47
59
  return fields.length > 0 ? fields : undefined
48
60
  }
49
61
 
62
+ /**
63
+ * `.single()` answered without exactly one row, worded as PostgREST 14 words it, so a caller sees
64
+ * the same error whether PostgREST refused the request or the client found the rows wrong.
65
+ */
66
+ function notOneRow(): SupatypeError {
67
+ return { message: "Cannot coerce the result to a single JSON object", code: PostgrestErrorCodes.NOT_FOUND }
68
+ }
69
+
70
+ /**
71
+ * The error a refused request answered with, for a read and a write alike.
72
+ *
73
+ * One function for both because they drifted: the write path dropped `field`, and a field
74
+ * validator only ever runs on a write, so the column it named never reached the caller.
75
+ */
76
+ function refusal(err: Record<string, unknown>, status: number): SupatypeError {
77
+ return {
78
+ message: refusalText(err) ?? String(err["hint"] ?? "Request failed"),
79
+ status,
80
+ ...(err["code"] !== undefined && { code: String(err["code"]) }),
81
+ // A field validator's refusal names the column it refused. Kept whole rather than folded into
82
+ // the message, so a form can mark the input.
83
+ ...(typeof err["field"] === "string" && { field: err["field"] }),
84
+ ...(typeof err["hint"] === "string" && err["hint"] !== "" && { hint: err["hint"] }),
85
+ ...(typeof err["details"] === "string" && err["details"] !== "" && { details: err["details"] }),
86
+ }
87
+ }
88
+
89
+ /** The refusal a failed request answered with, logged with `context` when auth debugging is on. */
90
+ async function readRefusal(
91
+ res: Response,
92
+ label: string,
93
+ context: () => Promise<Record<string, unknown>>,
94
+ ): Promise<SupatypeError> {
95
+ const err = await readJsonObject(res, { message: "Error" })
96
+ if (DEBUG_AUTH) {
97
+ console.log(label, {
98
+ ...(await context()),
99
+ status: res.status,
100
+ message: String(err["message"] ?? err["hint"] ?? "Request failed"),
101
+ code: typeof err["code"] === "string" ? err["code"] : null,
102
+ })
103
+ }
104
+ return refusal(err, res.status)
105
+ }
106
+
107
+ /**
108
+ * The rows a successful body holds.
109
+ *
110
+ * Read from the text rather than `res.json()`: a bigInt, decimal or money column is already ruined
111
+ * by the time `JSON.parse` returns, and the digits are only recoverable from the body.
112
+ */
113
+ function readRows<TRow>(body: string, path: string, status: number, count: number | null): QueryResult<TRow[]> {
114
+ const parsed = parseRowsExactly(body, tableFromPath(path))
115
+ if (!parsed.ok) return { data: null, error: { message: parsed.message, status }, count: null }
116
+ const rows = callerRows<TRow>(parsed.value)
117
+ if (rows === null) return { data: null, error: notRows(status), count: null }
118
+ return { data: rows, error: null, count }
119
+ }
120
+
121
+ const isServerCacheStatus = isOneOf(["HIT", "MISS", "BYPASS"])
122
+
123
+ /** What the server said of its cache, else MISS for a cached read, else nothing. */
124
+ function cacheStatusOf(header: string | null, cached: boolean): CacheStatus {
125
+ if (isServerCacheStatus(header)) return header
126
+ return cached ? "MISS" : undefined
127
+ }
128
+
50
129
  function withMeta<T>(
51
130
  result: QueryResult<T>,
52
131
  meta: { cacheStatus?: CacheStatus; maskedFields?: MaskedField[] | undefined },
@@ -89,31 +168,49 @@ export function bearerToken(headers: Record<string, string>): string {
89
168
  return headers["apikey"] ?? headers["Apikey"] ?? ""
90
169
  }
91
170
 
92
- async function fetchWithOptional401Retry(
171
+ // `createClient` passes its retrying fetch, so `config.timeout` and `config.retry` reach table reads
172
+ // and writes as they reach every other request. A builder constructed directly, without one, sends
173
+ // with plain `fetch` as it always has.
174
+ export type { RequestTransport }
175
+
176
+ /** Send once; on a 401, let the session refresh and send again with freshly resolved headers. */
177
+ export async function fetchWithOptional401Retry(
178
+ send: RequestTransport,
93
179
  url: string,
94
- init: RequestInit,
180
+ init: RequestInit & FetchOptions,
95
181
  resolveHeaders: () => Promise<Record<string, string>>,
96
182
  onUnauthorized?: (() => Promise<void>) | undefined,
97
183
  ): Promise<Response> {
98
184
  let headers = await resolveHeaders()
99
- let res = await fetch(url, { ...init, headers })
185
+ let res = await send(url, { ...init, headers })
100
186
  if (res.status === 401 && onUnauthorized !== undefined) {
101
187
  await onUnauthorized()
102
188
  headers = await resolveHeaders()
103
- res = await fetch(url, { ...init, headers })
189
+ res = await send(url, { ...init, headers })
104
190
  }
105
191
  return res
106
192
  }
107
193
 
194
+ /**
195
+ * The total from PostgREST's `Content-Range: <range>/<total>`, or null when there is none.
196
+ *
197
+ * PostgREST sends the header on every read, and the total is `*` unless the request asked for a
198
+ * count with `Prefer: count=...`. Reading `*` as a number gave `NaN` on every ordinary query.
199
+ */
200
+ export function parseContentRangeTotal(header: string | null): number | null {
201
+ const total = header?.split("/")[1]
202
+ return total !== undefined && /^\d+$/.test(total) ? Number(total) : null
203
+ }
204
+
108
205
  // ─── QueryBuilder ─────────────────────────────────────────────────────────────
109
206
 
110
- export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
207
+ export class QueryBuilder<TRow> extends FilterBuilder implements PromiseLike<QueryResult<TRow[]>> {
111
208
  private readonly baseUrl: string
112
209
  private readonly path: string
113
210
  private readonly getHeaders: HeadersProvider
114
211
  private readonly onUnauthorized: (() => Promise<void>) | undefined
212
+ private readonly send: RequestTransport
115
213
  private readonly extraHeaders: Record<string, string>
116
- private readonly params: URLSearchParams
117
214
  private readonly queryCache: QueryCache
118
215
  private cacheOptions: QueryCacheOptions | undefined
119
216
  private readonly countMode: SelectQueryOptions["count"]
@@ -127,13 +224,15 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
127
224
  queryCache: QueryCache = defaultQueryCache,
128
225
  onUnauthorized?: (() => Promise<void>) | undefined,
129
226
  selectOptions?: SelectQueryOptions | undefined,
227
+ transport: RequestTransport = plainFetch,
130
228
  ) {
229
+ super()
131
230
  this.baseUrl = baseUrl
132
231
  this.path = path
133
232
  this.getHeaders = asHeadersProvider(headers)
134
233
  this.onUnauthorized = onUnauthorized
234
+ this.send = transport
135
235
  this.extraHeaders = {}
136
- this.params = new URLSearchParams()
137
236
  this.queryCache = queryCache
138
237
  this.countMode = selectOptions?.count
139
238
  this.head = selectOptions?.head === true
@@ -162,84 +261,17 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
162
261
  return this
163
262
  }
164
263
 
165
- eq(column: string, value: unknown): this {
166
- this.params.append(column, `eq.${String(value)}`)
167
- return this
168
- }
169
-
170
- neq(column: string, value: unknown): this {
171
- this.params.append(column, `neq.${String(value)}`)
172
- return this
173
- }
174
-
175
- gt(column: string, value: unknown): this {
176
- this.params.append(column, `gt.${String(value)}`)
177
- return this
178
- }
179
-
180
- gte(column: string, value: unknown): this {
181
- this.params.append(column, `gte.${String(value)}`)
182
- return this
183
- }
184
-
185
- lt(column: string, value: unknown): this {
186
- this.params.append(column, `lt.${String(value)}`)
187
- return this
188
- }
189
-
190
- lte(column: string, value: unknown): this {
191
- this.params.append(column, `lte.${String(value)}`)
192
- return this
193
- }
194
-
195
- like(column: string, pattern: string): this {
196
- this.params.append(column, `like.${pattern}`)
197
- return this
198
- }
199
-
200
- ilike(column: string, pattern: string): this {
201
- this.params.append(column, `ilike.${pattern}`)
202
- return this
203
- }
204
-
205
- in(column: string, values: unknown[]): this {
206
- this.params.append(column, `in.(${values.map(String).join(",")})`)
207
- return this
208
- }
209
-
210
- is(column: string, value: null | boolean): this {
211
- this.params.append(column, `is.${String(value)}`)
212
- return this
213
- }
214
-
215
- not(column: string, op: string, value: unknown): this {
216
- this.params.append(column, `not.${op}.${String(value)}`)
217
- return this
218
- }
219
-
220
- contains(column: string, value: unknown): this {
221
- this.params.append(column, `cs.${JSON.stringify(value)}`)
222
- return this
223
- }
224
-
225
- containedBy(column: string, value: unknown): this {
226
- this.params.append(column, `cd.${JSON.stringify(value)}`)
227
- return this
228
- }
229
-
230
- /** PostgREST OR filter: pass conditions in PostgREST syntax, e.g. `"status.eq.active,owner_id.eq.123"`. */
231
- or(filters: string): this {
232
- this.params.append("or", `(${filters})`)
233
- return this
234
- }
235
-
236
264
  order(
237
265
  column: string,
238
266
  opts?: { ascending?: boolean | undefined; nullsFirst?: boolean | undefined } | undefined,
239
267
  ): this {
240
268
  const dir = opts?.ascending === false ? "desc" : "asc"
241
269
  const nulls = opts?.nullsFirst === true ? "nullsfirst" : "nullslast"
242
- this.params.append("order", `${column}.${dir}.${nulls}`)
270
+ // One parameter, comma-separated: PostgREST reads only the first `order`, so appending a second
271
+ // dropped every column after the first without an error.
272
+ const term = `${column}.${dir}.${nulls}`
273
+ const prior = this.params.get("order")
274
+ this.params.set("order", prior === null ? term : `${prior},${term}`)
243
275
  return this
244
276
  }
245
277
 
@@ -266,12 +298,13 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
266
298
  Accept: "application/vnd.pgrst.object+json",
267
299
  })
268
300
  if (error !== null) return { data: null, error, count: null, ...(meta && { meta }) }
269
- // Some proxies drop Accept and return a one-element array, unwrap.
270
- const row = (Array.isArray(data) ? data[0] : data) as TRow | undefined
301
+ // The single-object body and a one-element array (from a proxy that dropped Accept) both
302
+ // arrive here as rows: `callerRows` reads either.
303
+ const row = data === null ? null : data[0]
271
304
  if (row === undefined) {
272
305
  return {
273
306
  data: null,
274
- error: { message: "JSON object requested, multiple (or no) rows returned", code: "PGRST116" },
307
+ error: notOneRow(),
275
308
  count: null,
276
309
  ...(meta && { meta }),
277
310
  }
@@ -283,8 +316,7 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
283
316
  async maybeSingle(): Promise<QueryResult<TRow | null>> {
284
317
  const { data, error, count, meta } = await this._fetch({})
285
318
  if (error !== null) return { data: null, error, count: null, ...(meta && { meta }) }
286
- const rows = data as TRow[]
287
- const row = rows.length > 0 ? (rows[0] ?? null) : null
319
+ const row = data?.[0] ?? null
288
320
  return { data: row, error: null, count, ...(meta && { meta }) }
289
321
  }
290
322
 
@@ -329,127 +361,142 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
329
361
  const mergedExtra = this.mergePreferHeader(this.extraHeaders, fetchHeaders)
330
362
  const url = this.buildRequestUrl()
331
363
  const method = this.head ? "HEAD" : "GET"
332
- const resolveRequestHeaders = async (): Promise<Record<string, string>> => {
333
- const authHeaders = await this.getHeaders()
334
- return this.applyServerCacheHeader({ ...authHeaders, ...mergedExtra })
335
- }
364
+ const resolveRequestHeaders = async (): Promise<Record<string, string>> =>
365
+ this.applyServerCacheHeader({ ...(await this.getHeaders()), ...mergedExtra })
336
366
 
337
- if (this.cacheOptions && !this.head) {
338
- const requestHeaders = await resolveRequestHeaders()
339
- const cacheKey = buildCacheKey("GET", url, requestHeaders, {
340
- partition: this.cacheOptions.key,
341
- public: this.cacheOptions.public,
342
- })
343
- const cached = this.queryCache.get<TRow[]>(cacheKey)
344
- if (cached) {
345
- return withMeta(cached, { cacheStatus: "HIT" })
346
- }
347
- }
367
+ const cached = await this.cachedResult(url, resolveRequestHeaders)
368
+ if (cached) return withMeta(cached, { cacheStatus: "HIT" })
348
369
 
349
370
  let res: Response
350
371
  try {
351
- res = await fetchWithOptional401Retry(
352
- url,
353
- { method },
354
- resolveRequestHeaders,
355
- this.onUnauthorized,
356
- )
372
+ res = await fetchWithOptional401Retry(this.send, url, { method }, resolveRequestHeaders, this.onUnauthorized)
357
373
  } catch (e) {
358
- return {
359
- data: null,
360
- error: { message: e instanceof Error ? e.message : "Network error" },
361
- count: null,
362
- }
374
+ return { data: null, error: transportFailure(e), count: null }
363
375
  }
364
376
 
365
- const contentRange = res.headers.get("content-range")
366
- const count =
367
- contentRange !== null
368
- ? parseInt(contentRange.split("/")[1] ?? "0", 10)
369
- : null
370
-
371
- const maskedFields = parseMaskedFields(res.headers.get("X-Supatype-Masked-Fields"))
372
- const serverCacheStatus = res.headers.get("X-Supatype-Cache-Status") as CacheStatus | null
373
- const cacheStatus: CacheStatus =
374
- serverCacheStatus === "HIT" || serverCacheStatus === "MISS" || serverCacheStatus === "BYPASS"
375
- ? serverCacheStatus
376
- : this.cacheOptions
377
- ? "MISS"
378
- : undefined
377
+ const result = await this.readResult(res, method, url, resolveRequestHeaders)
378
+ await this.remember(url, resolveRequestHeaders, result)
379
+ return withMeta(result, {
380
+ cacheStatus: cacheStatusOf(res.headers.get("X-Supatype-Cache-Status"), this.cacheOptions !== undefined),
381
+ maskedFields: parseMaskedFields(res.headers.get("X-Supatype-Masked-Fields")),
382
+ })
383
+ }
379
384
 
385
+ /** The cached result for this read, when it is cached and the cache holds one. */
386
+ private async cachedResult(
387
+ url: string,
388
+ resolveRequestHeaders: () => Promise<Record<string, string>>,
389
+ ): Promise<QueryResult<TRow[]> | null> {
390
+ if (!this.cacheOptions || this.head) return null
391
+ return this.queryCache.get<TRow[]>(await this.cacheKey(url, this.cacheOptions, resolveRequestHeaders))
392
+ }
393
+
394
+ /** Cache a read's rows, when this read is cached and it returned rows. */
395
+ private async remember(
396
+ url: string,
397
+ resolveRequestHeaders: () => Promise<Record<string, string>>,
398
+ result: QueryResult<TRow[]>,
399
+ ): Promise<void> {
400
+ if (!this.cacheOptions || result.error !== null || result.data === null) return
401
+ const key = await this.cacheKey(url, this.cacheOptions, resolveRequestHeaders)
402
+ this.queryCache.set(key, result, this.cacheOptions.ttl)
403
+ }
404
+
405
+ /** What the response says: a refusal, no body (HEAD or 204), or the rows. */
406
+ private async readResult(
407
+ res: Response,
408
+ method: "GET" | "HEAD",
409
+ url: string,
410
+ resolveRequestHeaders: () => Promise<Record<string, string>>,
411
+ ): Promise<QueryResult<TRow[]>> {
380
412
  if (!res.ok) {
381
- const err = await res.json().catch(() => ({ message: "Error" })) as Record<string, unknown>
382
- const debugHeaders = await resolveRequestHeaders()
383
- if (DEBUG_AUTH) {
384
- console.log("[supatype:query] request failed", {
385
- url,
386
- status: res.status,
387
- role: decodeJwtRoleFromAuthHeader(debugHeaders),
388
- message: String(err["message"] ?? err["hint"] ?? "Request failed"),
389
- code: typeof err["code"] === "string" ? err["code"] : null,
390
- })
391
- }
392
- return withMeta<TRow[]>(
393
- {
394
- data: null,
395
- error: {
396
- message: String(err["message"] ?? err["hint"] ?? "Request failed"),
397
- status: res.status,
398
- ...(err["code"] !== undefined && { code: String(err["code"]) }),
399
- // A field validator's refusal names the column it refused. Kept whole rather than
400
- // folded into the message, so a form can mark the input.
401
- ...(typeof err["field"] === "string" && { field: err["field"] }),
402
- },
403
- count: null,
404
- },
405
- { cacheStatus, maskedFields },
406
- )
407
- }
408
-
409
- if (method === "HEAD" || res.status === 204) {
410
- return withMeta<TRow[]>(
411
- { data: null, error: null, count },
412
- { cacheStatus, maskedFields },
413
- )
413
+ const error = await readRefusal(res, "[supatype:query] request failed", async () => ({
414
+ url,
415
+ role: bearerRole(await resolveRequestHeaders()),
416
+ }))
417
+ return { data: null, error, count: null }
414
418
  }
419
+ const count = parseContentRangeTotal(res.headers.get("content-range"))
420
+ if (method === "HEAD" || res.status === 204) return { data: null, error: null, count }
421
+ return readRows<TRow>(await res.text(), this.path, res.status, count)
422
+ }
423
+
424
+ private async cacheKey(
425
+ url: string,
426
+ options: QueryCacheOptions,
427
+ resolveRequestHeaders: () => Promise<Record<string, string>>,
428
+ ): Promise<string> {
429
+ return buildCacheKey("GET", url, await resolveRequestHeaders(), {
430
+ partition: options.key,
431
+ public: options.public,
432
+ })
433
+ }
434
+ }
415
435
 
416
- // Read from the text rather than `res.json()`: a bigInt, decimal or money column is already
417
- // ruined by the time `JSON.parse` returns, and the digits are only recoverable from the body.
418
- const parsed = parseRowsExactly(await res.text(), tableFromPath(this.path))
419
- if (!parsed.ok) {
420
- return withMeta<TRow[]>(
421
- { data: null, error: { message: parsed.message, status: res.status }, count: null },
422
- { cacheStatus, maskedFields },
423
- )
424
- }
436
+ // ─── MutationBuilder ──────────────────────────────────────────────────────────
425
437
 
426
- const result: QueryResult<TRow[]> = { data: parsed.value as TRow[], error: null, count }
438
+ type HttpMethod = "POST" | "PATCH" | "DELETE"
427
439
 
428
- if (this.cacheOptions) {
429
- const cacheKey = buildCacheKey("GET", url, await resolveRequestHeaders(), {
430
- partition: this.cacheOptions.key,
431
- public: this.cacheOptions.public,
432
- })
433
- this.queryCache.set(cacheKey, result, this.cacheOptions.ttl)
434
- }
440
+ /**
441
+ * An insert sent through `supatype.create_record` (one row) or `supatype.create_records` (several,
442
+ * all or none) rather than as a plain `POST`: the table, which keeps drafts, and the key its new
443
+ * records are read back by.
444
+ *
445
+ * Why at all: a new record on a drafts model is unpublished, and when the model's read rule hides
446
+ * unpublished rows Postgres refuses an insert that asks for the row back, since it checks the
447
+ * returned row against that rule before anything has made it visible to its author.
448
+ * `create_record` inserts without reading back and writes version 1, after which the author sees it.
449
+ */
450
+ export interface DraftCreate {
451
+ readonly table: string
452
+ readonly primaryKey: string
453
+ }
435
454
 
436
- return withMeta(result, { cacheStatus, maskedFields })
437
- }
455
+ /**
456
+ * An update sent through `supatype.save_drafts` rather than as a plain `PATCH`: the table, which
457
+ * keeps drafts, its key, and whether to publish the new drafts in the same call.
458
+ *
459
+ * Why at all: on a drafts model the live row changes only by publishing, and the database refuses
460
+ * a direct update of it from the API roles.
461
+ */
462
+ export interface DraftEdit extends DraftCreate {
463
+ readonly publish: boolean
438
464
  }
439
465
 
440
- // ─── MutationBuilder ──────────────────────────────────────────────────────────
466
+ /** How a write is made beyond its method and body. */
467
+ export interface MutationOptions {
468
+ upsert?: boolean | undefined
469
+ /** Create the records through `create_record` or `create_records`, for an insert on a drafts model. */
470
+ createThrough?: DraftCreate | undefined
471
+ /** Save a draft of each matched record through `save_drafts`, for an update on a drafts model. */
472
+ editThrough?: DraftEdit | undefined
473
+ /** Send nothing and answer with this: the write asks for something its table cannot do. */
474
+ refusal?: SupatypeError | undefined
475
+ }
441
476
 
442
- type HttpMethod = "POST" | "PATCH" | "DELETE"
477
+ /**
478
+ * The rows a write hands back for `select(columns)`.
479
+ *
480
+ * Read from the string, as `TableClient.select` does, when the builder knows the tables it was
481
+ * written against. A builder constructed by hand knows only its row, so there it stays the row.
482
+ */
483
+ type ReturnedRow<TRow, TTables, TName extends string, TColumns extends string> =
484
+ [TTables] extends [Record<string, TableDef>] ? SelectRow<TTables, TName, TColumns> : TRow
443
485
 
444
- export class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
486
+ export class MutationBuilder<TRow, TTables = unknown, TName extends string = string>
487
+ extends FilterBuilder
488
+ implements PromiseLike<QueryResult<TRow[]>> {
445
489
  private readonly baseUrl: string
446
490
  private readonly path: string
447
491
  private readonly getHeaders: HeadersProvider
448
492
  private readonly onUnauthorized: (() => Promise<void>) | undefined
493
+ private readonly send: RequestTransport
449
494
  private readonly extraHeaders: Record<string, string>
450
495
  private readonly method: HttpMethod
451
496
  private readonly body: unknown
452
- private readonly params: URLSearchParams
497
+ private readonly createThrough: DraftCreate | undefined
498
+ private readonly editThrough: DraftEdit | undefined
499
+ private readonly refusal: SupatypeError | undefined
453
500
 
454
501
  constructor(
455
502
  baseUrl: string,
@@ -457,46 +504,51 @@ export class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
457
504
  headers: Record<string, string> | HeadersProvider,
458
505
  method: HttpMethod,
459
506
  body?: unknown,
460
- opts?: { upsert?: boolean | undefined } | undefined,
507
+ opts?: MutationOptions | undefined,
461
508
  onUnauthorized?: (() => Promise<void>) | undefined,
509
+ transport: RequestTransport = plainFetch,
462
510
  ) {
511
+ super()
463
512
  this.baseUrl = baseUrl
464
513
  this.path = path
465
514
  this.getHeaders = asHeadersProvider(headers)
466
515
  this.onUnauthorized = onUnauthorized
516
+ this.send = transport
467
517
  this.extraHeaders = {}
468
518
  this.method = method
469
519
  this.body = body
470
- this.params = new URLSearchParams()
471
-
472
- if (opts?.upsert === true) {
473
- this.extraHeaders["Prefer"] = "resolution=merge-duplicates"
474
- }
520
+ this.createThrough = opts?.createThrough
521
+ this.editThrough = opts?.editThrough
522
+ this.refusal = opts?.refusal
475
523
 
524
+ if (opts?.upsert === true) this.prefer("resolution=merge-duplicates")
476
525
  // Return inserted/updated rows
477
- if (method !== "DELETE") {
478
- this.extraHeaders["Prefer"] = (this.extraHeaders["Prefer"] ?? "") + ",return=representation"
479
- }
480
- }
481
-
482
- eq(column: string, value: unknown): this {
483
- this.params.append(column, `eq.${String(value)}`)
484
- return this
485
- }
486
-
487
- neq(column: string, value: unknown): this {
488
- this.params.append(column, `neq.${String(value)}`)
489
- return this
490
- }
491
-
492
- in(column: string, values: unknown[]): this {
493
- this.params.append(column, `in.(${values.map(String).join(",")})`)
494
- return this
495
- }
496
-
497
- /** Limit returned columns on the mutation response (requires `return=representation`). */
498
- select(columns?: string): this {
526
+ if (method !== "DELETE") this.prefer("return=representation")
527
+ }
528
+
529
+ private prefer(preference: string): void {
530
+ const current = this.extraHeaders["Prefer"]
531
+ if (current?.split(",").includes(preference) === true) return
532
+ this.extraHeaders["Prefer"] = current === undefined ? preference : `${current},${preference}`
533
+ }
534
+
535
+ /**
536
+ * Return the written rows, limited to `columns`.
537
+ *
538
+ * Asks for the representation too, which a delete does not by default: without it PostgREST
539
+ * answers 204 and `delete().select()` returned no rows although it had deleted some.
540
+ */
541
+ select<TColumns extends string = "*">(
542
+ columns?: TColumns | undefined,
543
+ ): MutationBuilder<ReturnedRow<TRow, TTables, TName, TColumns>, TTables, TName>
544
+ /** Return the written rows typed as `TResult`, for a shape the select string cannot describe. */
545
+ select<TResult>(columns?: string | undefined): MutationBuilder<TResult, TTables, TName>
546
+ // The same request, now described as returning the selected shape rather than the whole row. The
547
+ // overloads above say which shape; the row type is the caller's claim, checked by nothing at
548
+ // runtime, so the builder itself is returned rather than a copy that would split the request.
549
+ select(columns?: string | undefined): MutationBuilder<unknown, TTables, TName> {
499
550
  this.params.set("select", columns ?? "*")
551
+ this.prefer("return=representation")
500
552
  return this
501
553
  }
502
554
 
@@ -505,11 +557,11 @@ export class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
505
557
  Accept: "application/vnd.pgrst.object+json",
506
558
  })
507
559
  if (error !== null) return { data: null, error, count: null, ...(meta && { meta }) }
508
- const row = data !== null && data.length > 0 ? (data[0] as TRow) : null
560
+ const row = data?.[0] ?? null
509
561
  if (row === null) {
510
562
  return {
511
563
  data: null,
512
- error: { message: "JSON object requested, multiple (or no) rows returned" },
564
+ error: notOneRow(),
513
565
  count: null,
514
566
  ...(meta && { meta }),
515
567
  }
@@ -531,7 +583,20 @@ export class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
531
583
  return this._execute().then(onfulfilled, onrejected)
532
584
  }
533
585
 
586
+ /** POST, PATCH and DELETE: the transport applies the timeout and never retries them. */
587
+ private requestInit(): RequestInit {
588
+ return {
589
+ method: this.method,
590
+ // Not `JSON.stringify`: it throws on a bigint, so reading a row with a bigInt column and
591
+ // writing it back would fail now that the generated types declare one.
592
+ ...(this.body !== undefined && { body: stringifyWithBigInts(this.body) }),
593
+ }
594
+ }
595
+
534
596
  private async _execute(fetchHeaders: Record<string, string> = {}): Promise<QueryResult<TRow[]>> {
597
+ if (this.refusal !== undefined) return { data: null, error: this.refusal, count: null }
598
+ if (this.createThrough !== undefined) return this.createDraftRecords(this.createThrough)
599
+ if (this.editThrough !== undefined) return this.saveDraftRecords(this.editThrough)
535
600
  const qs = this.params.toString()
536
601
  const url = `${this.baseUrl}${this.path}${qs ? `?${qs}` : ""}`
537
602
  const resolveRequestHeaders = async (): Promise<Record<string, string>> => ({
@@ -539,49 +604,20 @@ export class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
539
604
  ...this.extraHeaders,
540
605
  ...fetchHeaders,
541
606
  })
542
- const init: RequestInit = {
543
- method: this.method,
544
- // Not `JSON.stringify`: it throws on a bigint, so reading a row with a bigInt column and
545
- // writing it back would fail now that the generated types declare one.
546
- ...(this.body !== undefined && { body: stringifyWithBigInts(this.body) }),
547
- }
548
607
  let res: Response
549
608
  try {
550
- res = await fetchWithOptional401Retry(
551
- url,
552
- init,
553
- resolveRequestHeaders,
554
- this.onUnauthorized,
555
- )
609
+ res = await fetchWithOptional401Retry(this.send, url, this.requestInit(), resolveRequestHeaders, this.onUnauthorized)
556
610
  } catch (e) {
557
- return {
558
- data: null,
559
- error: { message: e instanceof Error ? e.message : "Network error" },
560
- count: null,
561
- }
611
+ return { data: null, error: transportFailure(e), count: null }
562
612
  }
563
613
 
564
614
  if (!res.ok) {
565
- const err = await res.json().catch(() => ({ message: "Error" })) as Record<string, unknown>
566
- if (DEBUG_AUTH) {
567
- console.log("[supatype:mutation] request failed", {
568
- url,
569
- method: this.method,
570
- status: res.status,
571
- role: decodeJwtRoleFromAuthHeader(await resolveRequestHeaders()),
572
- message: String(err["message"] ?? err["hint"] ?? "Request failed"),
573
- code: typeof err["code"] === "string" ? err["code"] : null,
574
- })
575
- }
576
- return {
577
- data: null,
578
- error: {
579
- message: String(err["message"] ?? err["hint"] ?? "Request failed"),
580
- status: res.status,
581
- ...(err["code"] !== undefined && { code: String(err["code"]) }),
582
- },
583
- count: null,
584
- }
615
+ const error = await readRefusal(res, "[supatype:mutation] request failed", async () => ({
616
+ url,
617
+ method: this.method,
618
+ role: bearerRole(await resolveRequestHeaders()),
619
+ }))
620
+ return { data: null, error, count: null }
585
621
  }
586
622
 
587
623
  if (res.status === 204) {
@@ -589,13 +625,96 @@ export class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
589
625
  }
590
626
 
591
627
  // The returned representation of what was just written, so it needs the same care as a read.
592
- const parsed = parseRowsExactly(await res.text(), tableFromPath(this.path))
593
- if (!parsed.ok) {
594
- return { data: null, error: { message: parsed.message, status: res.status }, count: null }
628
+ const result = readRows<TRow>(await res.text(), this.path, res.status, null)
629
+ return result.data === null ? result : { ...result, count: result.data.length }
630
+ }
631
+
632
+ /**
633
+ * Create the records as their first drafts, then read them back as an insert returns them.
634
+ *
635
+ * Read from the draft view, which has the table's row type: the live row of a new record holds no
636
+ * locale yet, so reading the table would hand back empty translations for what was just written.
637
+ * The select string applies as it would to the insert's own answer, and several rows come back in
638
+ * the order they were sent.
639
+ */
640
+ private async createDraftRecords(target: DraftCreate): Promise<QueryResult<TRow[]>> {
641
+ const { fn, data } = createCall(this.body)
642
+ const keys = await this.callPublishing(fn, { model_table: target.table, data })
643
+ if (!Array.isArray(keys)) return { data: null, error: keys, count: null }
644
+ return this.readDrafts(target, keys)
645
+ }
646
+
647
+ /**
648
+ * Save a draft of each record the filters match, publishing it too when asked, then read the
649
+ * drafts back as an update returns its rows. The live rows are left to publishing.
650
+ *
651
+ * The records are the ones the caller reads in the table under the update's filters, as a `PATCH`
652
+ * would match them, and `save_drafts` saves all of them or none.
653
+ */
654
+ private async saveDraftRecords(target: DraftEdit): Promise<QueryResult<TRow[]>> {
655
+ const matched = await this.matchedKeys(target.primaryKey)
656
+ if (!Array.isArray(matched)) return { data: null, error: matched, count: null }
657
+ // A `PATCH` that matches nothing answers no rows, and so does this, having saved nothing.
658
+ if (matched.length === 0) return { data: [], error: null, count: 0 }
659
+ const body = { model_table: target.table, record_ids: matched, data: this.body, publish: target.publish }
660
+ const keys = await this.callPublishing("save_drafts", body)
661
+ if (!Array.isArray(keys)) return { data: null, error: keys, count: null }
662
+ return this.readDrafts(target, keys)
663
+ }
664
+
665
+ /** The keys of the rows this write's filters match, read from the table as the caller. */
666
+ private async matchedKeys(primaryKey: string): Promise<string[] | SupatypeError> {
667
+ const params = new URLSearchParams(this.params)
668
+ params.set("select", primaryKey)
669
+ const url = `${this.baseUrl}${this.path}?${params.toString()}`
670
+ let res: Response
671
+ try {
672
+ res = await fetchWithOptional401Retry(this.send, url, { method: "GET" }, this.getHeaders, this.onUnauthorized)
673
+ } catch (e) {
674
+ return transportFailure(e)
595
675
  }
596
-
597
- const data = Array.isArray(parsed.value) ? (parsed.value as TRow[]) : [parsed.value as TRow]
598
- return { data, error: null, count: data.length }
676
+ if (!res.ok) return readRefusal(res, "[supatype:mutation] reading the records to draft failed", async () => ({ url }))
677
+ const rows = readRows<Record<string, unknown>>(await res.text(), this.path, res.status, null)
678
+ if (rows.data === null) return rows.error ?? notRows(res.status)
679
+ return rows.data.map((row) => String(row[primaryKey]))
680
+ }
681
+
682
+ /** `keys`' newest drafts, from the draft view, with this write's select and in the order given. */
683
+ private async readDrafts(target: DraftCreate, keys: string[]): Promise<QueryResult<TRow[]>> {
684
+ const select = readBackColumns(this.params.get("select"), target.primaryKey, keys.length)
685
+ const result = await new QueryBuilder<Record<string, unknown>>(
686
+ this.baseUrl,
687
+ this.path,
688
+ this.getHeaders,
689
+ select,
690
+ defaultQueryCache,
691
+ this.onUnauthorized,
692
+ { profile: DRAFT_SCHEMA },
693
+ this.send,
694
+ ).in(target.primaryKey, keys)
695
+ if (result.data === null) return { ...result, data: null }
696
+ const rows = callerRows<TRow>(inCreatedOrder(result.data, keys)) ?? []
697
+ return { ...result, data: rows, count: rows.length }
698
+ }
699
+
700
+ /** Call the publishing function `fn` with `body`: the record keys it answers with, in order, or why not. */
701
+ private async callPublishing(fn: string, body: Record<string, unknown>): Promise<string[] | SupatypeError> {
702
+ const url = `${this.baseUrl}/rest/v1/rpc/${fn}`
703
+ const init = { method: "POST", body: stringifyWithBigInts(body) }
704
+ const resolveRequestHeaders = async (): Promise<Record<string, string>> => ({
705
+ ...(await this.getHeaders()),
706
+ "Content-Profile": PUBLISHING_SCHEMA,
707
+ })
708
+ let res: Response
709
+ try {
710
+ res = await fetchWithOptional401Retry(this.send, url, init, resolveRequestHeaders, this.onUnauthorized)
711
+ } catch (e) {
712
+ return transportFailure(e)
713
+ }
714
+ const table = body["model_table"]
715
+ if (!res.ok) return readRefusal(res, `[supatype:mutation] ${fn} failed`, async () => ({ url, table }))
716
+ const answer: unknown = await res.json().catch(() => null)
717
+ return createdKeys(answer) ?? { message: `${fn} answered without the record ids`, status: res.status }
599
718
  }
600
719
  }
601
720