@ultimabase/http 0.0.0-stage → 0.1.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 (47) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +4 -2
  3. package/dist/address.d.ts +9 -0
  4. package/dist/address.d.ts.map +1 -0
  5. package/dist/address.js +63 -0
  6. package/dist/app.d.ts +43 -0
  7. package/dist/app.d.ts.map +1 -0
  8. package/dist/app.js +200 -0
  9. package/dist/client.d.ts +9 -0
  10. package/dist/client.d.ts.map +1 -0
  11. package/dist/client.js +31 -0
  12. package/dist/index.d.ts +39 -0
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +89 -0
  15. package/dist/internal.d.ts +5 -0
  16. package/dist/internal.d.ts.map +1 -0
  17. package/dist/internal.js +2 -0
  18. package/dist/pages.d.ts +60 -0
  19. package/dist/pages.d.ts.map +1 -0
  20. package/dist/pages.js +124 -0
  21. package/dist/request.d.ts +5 -0
  22. package/dist/request.d.ts.map +1 -0
  23. package/dist/request.js +26 -0
  24. package/dist/server.d.ts +15 -0
  25. package/dist/server.d.ts.map +1 -0
  26. package/dist/server.js +73 -0
  27. package/dist/transport.d.ts +32 -0
  28. package/dist/transport.d.ts.map +1 -0
  29. package/dist/transport.js +55 -0
  30. package/dist/upgrade.d.ts +25 -0
  31. package/dist/upgrade.d.ts.map +1 -0
  32. package/dist/upgrade.js +63 -0
  33. package/dist/validate.d.ts +44 -0
  34. package/dist/validate.d.ts.map +1 -0
  35. package/dist/validate.js +36 -0
  36. package/package.json +44 -3
  37. package/src/address.ts +74 -0
  38. package/src/app.ts +263 -0
  39. package/src/client.ts +38 -0
  40. package/src/index.ts +133 -0
  41. package/src/internal.ts +29 -0
  42. package/src/pages.ts +200 -0
  43. package/src/request.ts +40 -0
  44. package/src/server.ts +90 -0
  45. package/src/transport.ts +84 -0
  46. package/src/upgrade.ts +105 -0
  47. package/src/validate.ts +96 -0
package/src/app.ts ADDED
@@ -0,0 +1,263 @@
1
+ // The Hono application `httpPlugin` serves (D-66, D-106): no caching, CORS,
2
+ // forms from other origins, the body limit, each request's caller, the
3
+ // routes, and errors as D-72 sends them.
4
+ import { randomUUID } from 'node:crypto'
5
+ import { STATUS_CODES } from 'node:http'
6
+ import type { Context } from 'hono'
7
+ import { Hono } from 'hono'
8
+ import { bodyLimit } from 'hono/body-limit'
9
+ import { cors } from 'hono/cors'
10
+ import { HTTPException } from 'hono/http-exception'
11
+ import type { ContentfulStatusCode } from 'hono/utils/http-status'
12
+ import { getPath } from 'hono/utils/url'
13
+ import type { Caller, ErrorCode, Logger } from 'ultimabase'
14
+ import { isLocalHost, PublicError } from 'ultimabase'
15
+ import { addresses, proxiesOf } from './address.ts'
16
+ import { hold } from './request.ts'
17
+
18
+ /**
19
+ * What a route's context holds: `c.var.caller` (D-106) and `c.var.address`,
20
+ * the client's, `''` when unknown (D-113, D-116).
21
+ */
22
+ export type HttpEnv = { Variables: { caller: Caller; address: string } }
23
+
24
+ /** Routes the application writes, read by `httpPlugin({ routes })`. */
25
+ export type Routes = Hono<HttpEnv>
26
+
27
+ /** Routes a plugin mounted; `bodyLimit: false` when they read their own body (D-153). */
28
+ export interface Mounted {
29
+ readonly routes: Routes
30
+ readonly bodyLimit: boolean
31
+ }
32
+
33
+ /** What `httpPlugin` takes (D-66, D-106). */
34
+ export interface HttpOptions {
35
+ /** Mounted at the root, in their order. */
36
+ readonly routes?: readonly Routes[]
37
+ /** The origins a browser may call from; local ones outside production. */
38
+ readonly cors?: readonly string[]
39
+ /** Then `PORT`, then 3000. */
40
+ readonly port?: number
41
+ /** In bytes; 1 MB by default. */
42
+ readonly bodyLimit?: number
43
+ /** In front of the server, which then reads the client's address from `X-Forwarded-For`; 0 by default (D-116). */
44
+ readonly proxies?: number
45
+ }
46
+
47
+ const statuses: ReadonlyMap<string, ContentfulStatusCode> = new Map<
48
+ ErrorCode,
49
+ ContentfulStatusCode
50
+ >([
51
+ ['ACCESS_DENIED', 403],
52
+ ['NOT_FOUND', 404],
53
+ ['VALIDATION_FAILED', 400],
54
+ ['UNIQUE_VIOLATION', 409],
55
+ ['RELATION_RESTRICTED', 409],
56
+ ['UNAUTHENTICATED', 401],
57
+ ['INVALID_CREDENTIALS', 401],
58
+ ['TOO_MANY_ATTEMPTS', 429],
59
+ ['INTERNAL', 500],
60
+ ])
61
+
62
+ /** Hono's way to refuse a request, with its status (D-108). */
63
+ function refused(error: HTTPException, c: Context): Response {
64
+ if (error.res !== undefined) return error.getResponse()
65
+ const name = STATUS_CODES[error.status]
66
+ const code =
67
+ name === undefined
68
+ ? `HTTP_${error.status}`
69
+ : name.toUpperCase().replaceAll(/[^A-Z0-9]+/g, '_')
70
+ const message = error.message === '' ? (name ?? code) : error.message
71
+ return c.json({ code, message }, error.status)
72
+ }
73
+
74
+ /** A `PublicError` as is; any other error masked, logged with its id. */
75
+ function failed(error: unknown, c: Context, logger: Logger): Response {
76
+ // The client left: its request failed, not the server (499, as nginx).
77
+ if (c.req.raw.signal.aborted) return new Response(null, { status: 499 })
78
+ if (error instanceof HTTPException) return refused(error, c)
79
+ if (error instanceof PublicError) {
80
+ const { code, message, details } = error
81
+ // An application's own code is a client error (D-72).
82
+ const status = statuses.get(code) ?? 400
83
+ // Its details say when to retry, in seconds (D-113).
84
+ if (
85
+ code === 'TOO_MANY_ATTEMPTS' &&
86
+ typeof details === 'object' &&
87
+ details !== null
88
+ ) {
89
+ const wait: unknown = Reflect.get(details, 'retryAfter')
90
+ if (typeof wait === 'number') c.header('retry-after', String(wait))
91
+ }
92
+ return details === undefined
93
+ ? c.json({ code, message }, status)
94
+ : c.json({ code, message, details }, status)
95
+ }
96
+ const correlationId = randomUUID()
97
+ logger.error({ correlationId, err: error }, 'A request failed.')
98
+ return c.json(
99
+ { code: 'INTERNAL', message: 'Internal error.', correlationId },
100
+ 500,
101
+ )
102
+ }
103
+
104
+ /** A local host over `http:`, on any port. */
105
+ function isLocal(origin: string): boolean {
106
+ if (!URL.canParse(origin)) return false
107
+ const { protocol, hostname } = new URL(origin)
108
+ return protocol === 'http:' && isLocalHost(hostname)
109
+ }
110
+
111
+ /**
112
+ * Whether a browser may call from `origin`, with its cookies: a listed one,
113
+ * or a local one outside production. Reads `NODE_ENV` once.
114
+ */
115
+ export function allowing(options: HttpOptions): (origin: string) => boolean {
116
+ const listed = options.cors ?? []
117
+ const local = process.env['NODE_ENV'] !== 'production'
118
+ return (origin) => listed.includes(origin) || (local && isLocal(origin))
119
+ }
120
+
121
+ const safe = new Set(['GET', 'HEAD', 'OPTIONS'])
122
+ /** What an HTML form sends, `text/plain` when it names none. */
123
+ const form =
124
+ /^(application\/x-www-form-urlencoded|multipart\/form-data|text\/plain)\b/i
125
+
126
+ /**
127
+ * Hono's path, with control characters left encoded: a route never matches
128
+ * one, and the development log cannot print one (D-108).
129
+ */
130
+ const pathOf = (request: Request): string =>
131
+ getPath(request).replaceAll(/[\p{Cc}\u2028\u2029]/gu, (char) =>
132
+ encodeURIComponent(char),
133
+ )
134
+
135
+ /**
136
+ * Reads `NODE_ENV` once, when the application starts. The application's
137
+ * routes come before those plugins mounted (D-107).
138
+ */
139
+ export function appOf(
140
+ options: HttpOptions,
141
+ mounted: readonly Mounted[],
142
+ identify: (request: Request) => Promise<Caller>,
143
+ logger: Logger,
144
+ ): Hono<HttpEnv> {
145
+ const local = process.env['NODE_ENV'] !== 'production'
146
+ const allows = allowing(options)
147
+ const maxSize = options.bodyLimit ?? 1024 * 1024
148
+ const addressOf = addresses(proxiesOf(options.proxies), logger)
149
+ const app = new Hono<HttpEnv>({ getPath: pathOf })
150
+ // A response may hold the caller's data: no cache keeps one, errors
151
+ // included, unless its route says otherwise (D-106).
152
+ app.use(async (c, next) => {
153
+ await next()
154
+ if (!c.res.headers.has('cache-control'))
155
+ c.header('cache-control', 'no-store')
156
+ })
157
+ // Each request once answered, outside production (D-108).
158
+ if (local) {
159
+ app.use(async (c, next) => {
160
+ const began = performance.now()
161
+ await next()
162
+ const ms = Math.round(performance.now() - began)
163
+ logger.info(`${c.req.method} ${c.req.path} ${c.res.status} ${ms}ms`)
164
+ })
165
+ }
166
+ // Hono's `onError` receives only an `Error`; any other value thrown ends
167
+ // here, answered as one.
168
+ app.use(async (c, next) => {
169
+ try {
170
+ await next()
171
+ } catch (error) {
172
+ c.res = failed(error, c, logger)
173
+ }
174
+ })
175
+ const allowed = (origin: string) => (allows(origin) ? origin : null)
176
+ // An allowed origin sends its cookies, as auth's session (D-112).
177
+ const preflight = cors({ origin: allowed, credentials: true })
178
+ app.use(async (c, next) => {
179
+ // Hono's `cors` answers every OPTIONS: a route's own runs, unless the
180
+ // request is a preflight.
181
+ const asked = c.req.header('access-control-request-method')
182
+ if (c.req.method !== 'OPTIONS' || asked !== undefined) {
183
+ return preflight(c, next)
184
+ }
185
+ await next()
186
+ const origin = allowed(c.req.header('origin') ?? '')
187
+ if (origin !== null) {
188
+ c.header('access-control-allow-origin', origin)
189
+ c.header('access-control-allow-credentials', 'true')
190
+ }
191
+ c.header('vary', 'Origin', { append: true })
192
+ })
193
+ // A browser sends a form to any site, with that site's cookies, and no
194
+ // CORS check stops it: a form from a browser, which names its origin or
195
+ // its site, or with cookies, comes from an allowed origin (D-106). Without
196
+ // cookies, another site's form would sign its visitor in to its own
197
+ // account. A webhook sends neither header, nor cookies.
198
+ app.use(async (c, next) => {
199
+ const origin = c.req.header('origin')
200
+ const site = c.req.header('sec-fetch-site')
201
+ if (
202
+ !safe.has(c.req.method) &&
203
+ form.test(c.req.header('content-type') ?? 'text/plain') &&
204
+ (c.req.header('cookie') !== undefined ||
205
+ origin !== undefined ||
206
+ site !== undefined) &&
207
+ site !== 'same-origin' &&
208
+ origin !== new URL(c.req.url).origin &&
209
+ allowed(origin ?? '') === null
210
+ ) {
211
+ throw new PublicError(
212
+ 'ACCESS_DENIED',
213
+ 'A form from another origin is refused.',
214
+ )
215
+ }
216
+ await next()
217
+ })
218
+ const limit = bodyLimit({
219
+ maxSize,
220
+ onError: (c) =>
221
+ c.json(
222
+ {
223
+ code: 'PAYLOAD_TOO_LARGE',
224
+ message: `The body is over ${maxSize} bytes.`,
225
+ },
226
+ 413,
227
+ ),
228
+ })
229
+ // The routes of the mounts that read their own body, by method: their
230
+ // `use` and `all` match any request, so they never lift the limit (D-153).
231
+ const unlimited = new Hono()
232
+ for (const mount of mounted.filter((each) => !each.bodyLimit)) {
233
+ for (const { method, path } of mount.routes.routes) {
234
+ if (method !== 'ALL') unlimited.on(method, path, (c) => c.body(null))
235
+ }
236
+ }
237
+ app.use(async (c, next) => {
238
+ const [matched] = unlimited.router.match(c.req.method, c.req.path)
239
+ if (matched.length > 0) await next()
240
+ else return limit(c, next)
241
+ })
242
+ app.use(async (c, next) => {
243
+ hold(c, await identify(c.req.raw), addressOf(c.env))
244
+ await next()
245
+ })
246
+ for (const routes of [
247
+ ...(options.routes ?? []),
248
+ ...mounted.map((mount) => mount.routes),
249
+ ]) {
250
+ app.route('/', routes)
251
+ }
252
+ app.notFound((c) =>
253
+ c.json(
254
+ {
255
+ code: 'NOT_FOUND',
256
+ message: `No route matches ${c.req.method} ${c.req.path}.`,
257
+ },
258
+ 404,
259
+ ),
260
+ )
261
+ app.onError((error, c) => failed(error, c, logger))
262
+ return app
263
+ }
package/src/client.ts ADDED
@@ -0,0 +1,38 @@
1
+ // A function's client over HTTP (D-113, D-115, D-116): the client's address, the
2
+ // request's cookies, and those its run sets, added to the route's response.
3
+ import type { Context } from 'hono'
4
+ import { generateCookie, getCookie } from 'hono/cookie'
5
+ import type { Client } from 'ultimabase'
6
+ import type { HttpEnv } from './app.ts'
7
+
8
+ /** The client of `c`'s request, and `sent`, which adds its cookies. */
9
+ export function clientOf(c: Context<HttpEnv>): {
10
+ readonly client: Client
11
+ readonly sent: (response: Response) => Response
12
+ } {
13
+ const cookies: string[] = []
14
+ return {
15
+ client: {
16
+ address: c.var.address,
17
+ cookies: {
18
+ get: (name) => getCookie(c, name),
19
+ set: (name, value, options) => {
20
+ cookies.push(generateCookie(name, value, options))
21
+ },
22
+ clear: (name, options) => {
23
+ cookies.push(generateCookie(name, '', { ...options, maxAge: 0 }))
24
+ },
25
+ },
26
+ },
27
+ // A route may return a Response Hono's `c.header` never reaches.
28
+ sent: (response) => {
29
+ if (cookies.length === 0) return response
30
+ const headers = new Headers(response.headers)
31
+ for (const cookie of cookies) headers.append('set-cookie', cookie)
32
+ return new Response(response.body, {
33
+ status: response.status,
34
+ headers,
35
+ })
36
+ },
37
+ }
38
+ }
package/src/index.ts ADDED
@@ -0,0 +1,133 @@
1
+ // `httpPlugin()` and `routes()` (D-106): a Node server for the application's
2
+ // Hono routes, each of which reads the caller as `c.var.caller`.
3
+ import type { Server } from 'node:http'
4
+ import type { Duplex } from 'node:stream'
5
+ import { Hono } from 'hono'
6
+ import type { Caller, PluginOf, PluginTypes } from 'ultimabase'
7
+ import { definePlugin } from 'ultimabase'
8
+ import manifest from '../package.json' with { type: 'json' }
9
+ import type { HttpEnv, HttpOptions, Mounted, Routes } from './app.ts'
10
+ import { addresses, proxiesOf } from './address.ts'
11
+ import { allowing, appOf } from './app.ts'
12
+ import { hold } from './request.ts'
13
+ import { closed, listening, portOf, serverOf } from './server.ts'
14
+ import type { Accept } from './upgrade.ts'
15
+ import { upgrading } from './upgrade.ts'
16
+
17
+ export type { HttpEnv, HttpOptions, Routes } from './app.ts'
18
+ export type { Accept, Upgrade } from './upgrade.ts'
19
+ export { clientOf } from './client.ts'
20
+ export type { StandardSchema } from './validate.ts'
21
+ export { validate } from './validate.ts'
22
+
23
+ /** What the HTTP plugin offers other plugins (D-107). */
24
+ export interface HttpApi {
25
+ /**
26
+ * Adds routes after the application's; call it from your `api`. With
27
+ * `bodyLimit: false`, they read their own body (D-153).
28
+ */
29
+ mount(routes: Routes, options?: { readonly bodyLimit?: false }): void
30
+ /**
31
+ * Takes the WebSocket upgrades of `path`, once their origin is one CORS
32
+ * allows; call it from your `api` (D-154).
33
+ */
34
+ upgrade(path: string, accept: Accept): void
35
+ /** Where the server listens, `http://localhost:3000`, once it started. */
36
+ url(): string
37
+ }
38
+
39
+ /** The HTTP plugin's types (D-57). */
40
+ export interface Http extends PluginTypes {
41
+ readonly name: 'http'
42
+ readonly appOptions: HttpOptions
43
+ readonly api: HttpApi
44
+ }
45
+
46
+ // Each running application's server and mounted routes, by the context its
47
+ // plugin received.
48
+ const servers = new WeakMap<object, Server>()
49
+ const mounts = new WeakMap<object, Mounted[]>()
50
+ const upgrades = new WeakMap<object, Map<string, Accept>>()
51
+ const taken = new WeakMap<object, ReadonlySet<Duplex>>()
52
+ const urls = new WeakMap<object, string>()
53
+
54
+ const http = definePlugin<Http>({
55
+ name: 'http',
56
+ manifest,
57
+ api: (context) => {
58
+ const mounted: Mounted[] = []
59
+ const accepts = new Map<string, Accept>()
60
+ mounts.set(context, mounted)
61
+ upgrades.set(context, accepts)
62
+ const building = (what: string) => {
63
+ if (mounts.has(context)) return
64
+ throw new Error(
65
+ `The HTTP server is running: ${what} from your plugin's api.`,
66
+ )
67
+ }
68
+ return {
69
+ mount: (routes, mountOptions) => {
70
+ building('mount routes')
71
+ mounted.push({ routes, bodyLimit: mountOptions?.bodyLimit ?? true })
72
+ },
73
+ upgrade: (path, accept) => {
74
+ building('take upgrades')
75
+ if (accepts.has(path)) {
76
+ throw new Error(`Two plugins take the upgrades of ${path}.`)
77
+ }
78
+ accepts.set(path, accept)
79
+ },
80
+ url: () => {
81
+ const url = urls.get(context)
82
+ if (url === undefined) {
83
+ throw new Error(
84
+ "The HTTP server is not running: read its url from your plugin's start.",
85
+ )
86
+ }
87
+ return url
88
+ },
89
+ }
90
+ },
91
+ start: async (context) => {
92
+ const { options, identify, logger } = context
93
+ const port = portOf(options.port)
94
+ const app = appOf(options, mounts.get(context) ?? [], identify, logger)
95
+ mounts.delete(context)
96
+ const server = serverOf(app.fetch)
97
+ const accepts = upgrades.get(context) ?? new Map<string, Accept>()
98
+ const addressOf = addresses(proxiesOf(options.proxies), logger)
99
+ taken.set(
100
+ context,
101
+ upgrading(server, accepts, allowing(options), addressOf, logger),
102
+ )
103
+ const bound = await listening(server, port)
104
+ servers.set(context, server)
105
+ const url = `http://localhost:${bound}`
106
+ urls.set(context, url)
107
+ logger.info(`Listening on ${url}.`)
108
+ },
109
+ // Stops accepting connections, then waits for running requests (D-59, D-106).
110
+ stop: async (context) => {
111
+ const { logger } = context
112
+ const server = servers.get(context)
113
+ if (server === undefined) return
114
+ servers.delete(context)
115
+ urls.delete(context)
116
+ await closed(server, logger, taken.get(context) ?? new Set())
117
+ },
118
+ })
119
+
120
+ /** The application's HTTP server (D-66, D-106). */
121
+ export const httpPlugin: PluginOf<Http> = http.plugin
122
+
123
+ const anonymous: Caller = { kind: 'anonymous' }
124
+
125
+ /**
126
+ * Routes whose context holds the request's caller, `c.var.caller`: the
127
+ * anonymous one when no application read it, as in `routes().request(…)`.
128
+ */
129
+ export const routes = (): Routes =>
130
+ new Hono<HttpEnv>().use(async (c, next) => {
131
+ if (!('caller' in c.var)) hold(c, anonymous, '')
132
+ await next()
133
+ })
@@ -0,0 +1,29 @@
1
+ // What the official transports share (D-139), kept off the documented
2
+ // surface: their pages, errors, names and JSON Schema reading.
3
+ export type {
4
+ Args,
5
+ At,
6
+ Change,
7
+ Limits,
8
+ Page,
9
+ Pagination,
10
+ Relay,
11
+ } from './pages.ts'
12
+ export {
13
+ applied,
14
+ connection,
15
+ pageArgs,
16
+ pageOf,
17
+ rowOf,
18
+ rowsOf,
19
+ } from './pages.ts'
20
+ export type { Node, Served } from './transport.ts'
21
+ export {
22
+ badInput,
23
+ isNode,
24
+ jsonSchemaOf,
25
+ plural,
26
+ readable,
27
+ readableVirtuals,
28
+ run,
29
+ } from './transport.ts'
package/src/pages.ts ADDED
@@ -0,0 +1,200 @@
1
+ // Pages (D-55, D-129): Relay arguments and `take`/`skip` as a kernel read,
2
+ // within the limits, and the rows read as a connection.
3
+ import type { Row } from 'ultimabase'
4
+ import { isRow } from 'ultimabase/internal'
5
+ import { badInput } from './transport.ts'
6
+
7
+ /** A list's arguments, as the client wrote them. */
8
+ export type Args = { readonly [key: string]: unknown }
9
+
10
+ /** Where an argument was written: `first`, or `include.posts.first`. */
11
+ export type At = (name: string) => string
12
+
13
+ /** A transport's `pagination` setting (D-55). */
14
+ export type Pagination = 'connection' | 'list'
15
+
16
+ /** A model's limits: the rows a list returns by default, and at most. */
17
+ export type Limits = {
18
+ readonly take: number
19
+ readonly maxTake: number
20
+ readonly model: { readonly name: string }
21
+ }
22
+
23
+ const encode = (id: string): string => Buffer.from(id).toString('base64url')
24
+
25
+ function decode(cursor: string, arg: string): string {
26
+ const id = Buffer.from(cursor, 'base64url').toString()
27
+ if (id === '' || encode(id) !== cursor) {
28
+ throw badInput(`${arg} is not a cursor this API returned.`)
29
+ }
30
+ return id
31
+ }
32
+
33
+ /** An `Int` argument; `null` is absent, as in GraphQL. */
34
+ function integer(args: Args, name: string, at: At): number | undefined {
35
+ const value = args[name]
36
+ if (value === undefined || value === null) return undefined
37
+ if (typeof value === 'number' && Number.isSafeInteger(value)) return value
38
+ throw badInput(`${at(name)} must be an integer.`)
39
+ }
40
+
41
+ /** A `String` argument; `null` is absent, as in GraphQL. */
42
+ function text(args: Args, name: string, at: At): string | undefined {
43
+ const value = args[name]
44
+ if (value === undefined || value === null) return undefined
45
+ if (typeof value === 'string') return value
46
+ throw badInput(`${at(name)} must be a string.`)
47
+ }
48
+
49
+ /** The rows asked for, within the model's limits unless Master asks. */
50
+ function size(
51
+ asked: number | undefined,
52
+ name: string,
53
+ limits: Limits,
54
+ master: boolean,
55
+ ): number | undefined {
56
+ if (asked !== undefined && asked < 0) {
57
+ throw badInput(`${name} cannot be negative.`)
58
+ }
59
+ if (master) return asked
60
+ if (asked !== undefined && asked > limits.maxTake) {
61
+ throw badInput(
62
+ `${name} is at most ${limits.maxTake} on ${limits.model.name}.`,
63
+ )
64
+ }
65
+ return asked ?? limits.take
66
+ }
67
+
68
+ /** A Relay page: the rows asked for and its direction. */
69
+ export type Relay = {
70
+ readonly size: number | undefined
71
+ readonly backward: boolean
72
+ }
73
+
74
+ /** A list's kernel read, and its Relay page unless `pagination: 'list'`. */
75
+ export type Page = { readonly read: Args; readonly relay: Relay | undefined }
76
+
77
+ /**
78
+ * One row more than asked tells whether another page follows. The cursor's
79
+ * row is included by the kernel, so `skip: 1` starts after it.
80
+ */
81
+ function relay(args: Args, limits: Limits, master: boolean, at: At): Page {
82
+ const after = text(args, 'after', at)
83
+ const before = text(args, 'before', at)
84
+ const first = integer(args, 'first', at)
85
+ const last = integer(args, 'last', at)
86
+ const backward = last !== undefined || before !== undefined
87
+ if (backward && (first !== undefined || after !== undefined)) {
88
+ throw badInput(
89
+ 'Page forward with first and after, or backward with last and before, not both.',
90
+ )
91
+ }
92
+ const rows = backward
93
+ ? size(last, at('last'), limits, master)
94
+ : size(first, at('first'), limits, master)
95
+ const cursor = backward ? before : after
96
+ const read: { [key: string]: unknown } = {}
97
+ if (rows !== undefined) read['take'] = backward ? -(rows + 1) : rows + 1
98
+ // Master's whole list, read backward from a cursor.
99
+ else if (backward) read['take'] = -Number.MAX_SAFE_INTEGER
100
+ if (cursor !== undefined) {
101
+ read['cursor'] = { id: decode(cursor, at(backward ? 'before' : 'after')) }
102
+ read['skip'] = 1
103
+ }
104
+ return { read, relay: { size: rows, backward } }
105
+ }
106
+
107
+ /** `take` and `skip` for `pagination: 'list'`. */
108
+ function list(args: Args, limits: Limits, master: boolean, at: At): Page {
109
+ const take = size(integer(args, 'take', at), at('take'), limits, master)
110
+ const skip = integer(args, 'skip', at)
111
+ const read = {
112
+ ...(take === undefined ? {} : { take }),
113
+ ...(skip === undefined ? {} : { skip }),
114
+ }
115
+ return { read, relay: undefined }
116
+ }
117
+
118
+ /** The page a list's arguments ask for. */
119
+ export const pageOf = (
120
+ pagination: Pagination,
121
+ limits: Limits,
122
+ args: Args,
123
+ master: boolean,
124
+ at: At = (name) => name,
125
+ ): Page =>
126
+ pagination === 'list'
127
+ ? list(args, limits, master, at)
128
+ : relay(args, limits, master, at)
129
+
130
+ /** The page arguments of each pagination. */
131
+ export const pageArgs = (pagination: Pagination): readonly string[] =>
132
+ pagination === 'list'
133
+ ? ['take', 'skip']
134
+ : ['first', 'after', 'last', 'before']
135
+
136
+ export type Connection<N> = {
137
+ readonly edges: readonly { readonly cursor: string; readonly node: N }[]
138
+ readonly pageInfo: {
139
+ readonly hasNextPage: boolean
140
+ readonly hasPreviousPage: boolean
141
+ readonly startCursor: string | null
142
+ readonly endCursor: string | null
143
+ }
144
+ }
145
+
146
+ /** The rows of a Relay read, without the one read to look ahead. */
147
+ export function connection<N>(
148
+ rows: readonly Row[],
149
+ page: Relay,
150
+ node: (row: Row) => N,
151
+ ): Connection<N> {
152
+ const more = page.size !== undefined && rows.length > page.size
153
+ const kept = more ? (page.backward ? rows.slice(1) : rows.slice(0, -1)) : rows
154
+ const edges = kept.map((row) => ({ cursor: encode(row.id), node: node(row) }))
155
+ return {
156
+ edges,
157
+ pageInfo: {
158
+ hasNextPage: more && !page.backward,
159
+ hasPreviousPage: more && page.backward,
160
+ startCursor: edges[0]?.cursor ?? null,
161
+ endCursor: edges.at(-1)?.cursor ?? null,
162
+ },
163
+ }
164
+ }
165
+
166
+ /** A row's relation as the kernel returned it. */
167
+ export function rowsOf(value: unknown): readonly Row[] {
168
+ return Array.isArray(value) ? value.filter(isRow) : []
169
+ }
170
+
171
+ export const rowOf = (value: unknown): Row | undefined =>
172
+ isRow(value) ? value : undefined
173
+
174
+ /** A live read's change (D-154): a row that left, or one placed after another. */
175
+ export type Change<R> =
176
+ | { readonly remove: string }
177
+ | { readonly upsert: R; readonly after: string | null }
178
+
179
+ /** `window` once a live read's `changes` are applied, in their order. */
180
+ export function applied<T extends { readonly id: string }, R>(
181
+ window: readonly T[],
182
+ changes: readonly Change<R>[],
183
+ kept: (upsert: R) => T,
184
+ ): T[] {
185
+ let rows = [...window]
186
+ for (const change of changes) {
187
+ if ('remove' in change) {
188
+ rows = rows.filter(({ id }) => id !== change.remove)
189
+ continue
190
+ }
191
+ const row = kept(change.upsert)
192
+ rows = rows.filter(({ id }) => id !== row.id)
193
+ const at =
194
+ change.after === null
195
+ ? 0
196
+ : rows.findIndex(({ id }) => id === change.after) + 1
197
+ rows.splice(at, 0, row)
198
+ }
199
+ return rows
200
+ }