@ember-lattice/server 0.0.0-stage → 1.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.
@@ -0,0 +1,157 @@
1
+ import type { CellChange, CellRef, CellStyle, CellValue, RangeRef, SheetOp } from '@ember-lattice/formula';
2
+ export declare const COLLAB_VERSION = 1;
3
+ export declare const COLLAB_LIMITS: {
4
+ /** Ops in one submit. */
5
+ maxOps: number;
6
+ /** IDs in one insert or delete. */
7
+ maxIds: number;
8
+ /** Characters in a text value, a formula or a name ref (the Excel cell limit). */
9
+ maxText: number;
10
+ /** Characters in a number format, a style color or a user name. */
11
+ maxShort: number;
12
+ /** Characters in an ID (doc, client, op, sheet, row or column). */
13
+ maxId: number;
14
+ };
15
+ /**
16
+ * An op on the wire: a `SheetOp` (the engine ops), or a model op that the engine does not see.
17
+ * `freeze` keeps the counts of frozen rows and columns; 0 and 0 removes the panes.
18
+ */
19
+ export type CollabOp = SheetOp | {
20
+ type: 'setNote';
21
+ sheet: string;
22
+ row: string;
23
+ col: string;
24
+ note: string | null;
25
+ } | {
26
+ type: 'freeze';
27
+ sheet: string;
28
+ rows: number;
29
+ cols: number;
30
+ };
31
+ /** A cell, a selection or a cell in edit mode, as presence. */
32
+ export interface Presence {
33
+ cursor: CellRef | null;
34
+ selection: RangeRef | null;
35
+ /** The cell that the user edits now: a soft lock hint for the other users. */
36
+ editing: CellRef | null;
37
+ }
38
+ export type ClientMessage =
39
+ /** Opens a doc. `sinceSeq` null asks for a snapshot; a number asks for the ops after it. */
40
+ {
41
+ v: 1;
42
+ type: 'join';
43
+ docId: string;
44
+ clientId: string;
45
+ sinceSeq: number | null;
46
+ name?: string;
47
+ } | {
48
+ v: 1;
49
+ type: 'submit';
50
+ docId: string;
51
+ clientId: string;
52
+ opId: string;
53
+ baseSeq: number;
54
+ ops: CollabOp[];
55
+ } | ({
56
+ v: 1;
57
+ type: 'presence';
58
+ docId: string;
59
+ } & Presence);
60
+ /** A doc as the server sends it: the `WorkbookDoc` form, with the computed values. */
61
+ export interface CollabCell {
62
+ row: string;
63
+ col: string;
64
+ value?: CellValue;
65
+ formula?: string;
66
+ computed?: CellValue;
67
+ format?: string;
68
+ style?: string;
69
+ note?: string;
70
+ }
71
+ export interface CollabArea {
72
+ start: {
73
+ row: string;
74
+ col: string;
75
+ };
76
+ end: {
77
+ row: string;
78
+ col: string;
79
+ };
80
+ }
81
+ export interface CollabDoc {
82
+ sheets: {
83
+ id: string;
84
+ name: string;
85
+ rows: string[];
86
+ cols: string[];
87
+ cells: CollabCell[];
88
+ merges?: CollabArea[];
89
+ /** Not there when no row and no column is frozen. */
90
+ frozen?: {
91
+ rows: number;
92
+ cols: number;
93
+ };
94
+ }[];
95
+ names?: {
96
+ name: string;
97
+ ref: string;
98
+ }[];
99
+ styles?: Record<string, CellStyle>;
100
+ }
101
+ export type ServerMessage = {
102
+ v: 1;
103
+ type: 'snapshot';
104
+ docId: string;
105
+ seq: number;
106
+ doc: CollabDoc;
107
+ }
108
+ /** The ops as the server applied them, to every client (the sender too). */
109
+ | {
110
+ v: 1;
111
+ type: 'ops';
112
+ docId: string;
113
+ seq: number;
114
+ clientId: string;
115
+ opId: string;
116
+ ops: CollabOp[];
117
+ changes: CellChange[];
118
+ }
119
+ /** A submit that the server sequenced before (a resend after a reconnect). */
120
+ | {
121
+ v: 1;
122
+ type: 'ack';
123
+ docId: string;
124
+ opId: string;
125
+ seq: number;
126
+ }
127
+ /** The server applied no op of the submit. `opId` is null when the message did not parse. */
128
+ | {
129
+ v: 1;
130
+ type: 'reject';
131
+ docId: string;
132
+ opId: string | null;
133
+ reason: string;
134
+ } | ({
135
+ v: 1;
136
+ type: 'presence';
137
+ docId: string;
138
+ clientId: string;
139
+ name: string;
140
+ } & Presence) | {
141
+ v: 1;
142
+ type: 'leave';
143
+ docId: string;
144
+ clientId: string;
145
+ };
146
+ export type ParseResult = {
147
+ ok: true;
148
+ message: ClientMessage;
149
+ } | {
150
+ ok: false;
151
+ error: string;
152
+ };
153
+ /**
154
+ * Checks a client message. This is the trust boundary of the collab server. It never throws.
155
+ * On success it gives a fresh copy that holds only known keys.
156
+ */
157
+ export declare function parseClientMessage(input: unknown): ParseResult;
@@ -0,0 +1,3 @@
1
+ export { createRowsHandler } from './rows';
2
+ export type { Dialect, RowsHandlerOptions } from './rows';
3
+ export * from './collab/index';
package/dist/index.js ADDED
@@ -0,0 +1,417 @@
1
+ import { isArray, isNull, isNumber, isBoolean, isString, isSafeInteger } from './chunk-WHFTIPTN.js';
2
+ export { COLLAB_LIMITS, COLLAB_VERSION, attachSocket, createDocServer, createMemoryStore, parseClientMessage } from './chunk-WHFTIPTN.js';
3
+ import { sql } from 'kysely';
4
+ import { parseRowsRequest, ProtocolValidationError, LIMITS, aggregateKey, GROUP_COUNT_KEY, TREE_PATH_SEPARATOR } from '@ember-lattice/protocol';
5
+
6
+ var OUTER = sql.id("$to");
7
+ var IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
8
+ var RESERVED = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
9
+ var and = (xs) => xs.length ? sql`(${sql.join(xs, sql` and `)})` : sql`1 = 1`;
10
+ var or = (xs) => xs.length ? sql`(${sql.join(xs, sql` or `)})` : sql`1 = 0`;
11
+ var comma = (xs) => sql.join(xs);
12
+ function utcIso(v) {
13
+ return new Date(Date.parse(/T[^Z+-]*$/.test(v) ? `${v}Z` : v)).toISOString();
14
+ }
15
+ function scalarOk(t, v) {
16
+ if (isNull(v)) return true;
17
+ if (t === "number") return isNumber(v) && Number.isFinite(v);
18
+ if (t === "boolean") return isBoolean(v);
19
+ return isString(v) && (t === "string" || !Number.isNaN(Date.parse(v)));
20
+ }
21
+ function createRowsHandler(options) {
22
+ const { db, dialect } = options;
23
+ for (const c of options.columns) {
24
+ if (!IDENTIFIER.test(c.name) || RESERVED.has(c.name))
25
+ throw new Error(`lattice: bad column name "${c.name}"`);
26
+ }
27
+ if (!options.columns.some((c) => c.name === options.key))
28
+ throw new Error(`lattice: the key "${options.key}" is not in the allow-list`);
29
+ const treeColumns = options.columns.filter((c) => c.parent === true || c.path === true);
30
+ const treeColumn = treeColumns[0];
31
+ const keyType = options.columns.find((c) => c.name === options.key).type;
32
+ if (treeColumns.length > 1 || treeColumn?.parent === true && treeColumn.type !== keyType || treeColumn?.path === true && treeColumn.type !== "string")
33
+ throw new Error(
34
+ "lattice: tree data needs one parent column of the key type, or one string path column"
35
+ );
36
+ const allowList = options.columns.map((c) => ({ ...c, key: c.name === options.key }));
37
+ const types = new Map(allowList.map((c) => [c.name, c.type]));
38
+ const type = (c) => types.get(c);
39
+ const searchColumns = allowList.filter((c) => c.search === true && c.type === "string");
40
+ const table = sql.table(options.table);
41
+ const pg = dialect === "postgres";
42
+ const mysql = dialect === "mysql";
43
+ const run = async (q) => (await q.execute(db)).rows;
44
+ const dateExpr = (x) => pg ? sql`cast(${x} as timestamptz)` : mysql ? x : sql`julianday(${x})`;
45
+ const param = (v) => {
46
+ if (isBoolean(v)) return pg ? sql`${v}` : sql`${Number(v)}`;
47
+ if (pg && isNumber(v) && !isSafeInteger(v)) return sql`cast(${v} as double precision)`;
48
+ return sql`${v}`;
49
+ };
50
+ const dateParam = (v) => {
51
+ const iso = utcIso(v);
52
+ return dateExpr(sql`${mysql ? iso.replace("T", " ").replace("Z", "") : iso}`);
53
+ };
54
+ const decode = (t, v) => {
55
+ if (v === null || v === void 0) return null;
56
+ if (t === "number") return Number(v);
57
+ if (t === "boolean") return Boolean(Number(v));
58
+ return v;
59
+ };
60
+ const id = (c) => sql.id(c);
61
+ const ord = (c) => {
62
+ if (type(c) !== "string") return id(c);
63
+ if (pg) return sql`${id(c)} collate "C"`;
64
+ return mysql ? sql`${id(c)} collate utf8mb4_bin` : sql`${id(c)} collate binary`;
65
+ };
66
+ const orderItem = (k) => {
67
+ const dir = k.dir === "desc" ? sql`desc` : sql`asc`;
68
+ const e = ord(k.column);
69
+ if (mysql) return sql`(${e} is null) ${k.nulls === "first" ? sql`desc` : sql`asc`}, ${e} ${dir}`;
70
+ return sql`${e} ${dir} ${k.nulls === "first" ? sql`nulls first` : sql`nulls last`}`;
71
+ };
72
+ const orderBy = (keys) => comma(keys.map(orderItem));
73
+ const flip = (k) => ({
74
+ ...k,
75
+ dir: k.dir === "asc" ? "desc" : "asc",
76
+ nulls: k.nulls === "first" ? "last" : "first"
77
+ });
78
+ const like = (c, pattern) => mysql ? sql`lower(${id(c)}) like ${pattern}` : sql`lower(${id(c)}) like ${pattern} escape '\\'`;
79
+ const esc = (v) => String(v).toLowerCase().replace(/[\\%_]/g, "\\$&");
80
+ const where = (node) => {
81
+ if (node.op === "and") return and(node.nodes.map(where));
82
+ if (node.op === "or") return or(node.nodes.map(where));
83
+ if (node.op === "not") return sql`not ${where(node.node)}`;
84
+ return leaf(node);
85
+ };
86
+ const leaf = (node) => {
87
+ const c = node.column;
88
+ const t = type(c);
89
+ const blank = t === "string" ? sql`(${id(c)} is null or ${id(c)} = '')` : sql`(${id(c)} is null)`;
90
+ const lhs = t === "date" ? dateExpr(id(c)) : ord(c);
91
+ const p = (v) => t === "date" && isString(v) ? dateParam(v) : param(v);
92
+ switch (node.op) {
93
+ case "blank":
94
+ return blank;
95
+ case "notBlank":
96
+ return sql`not ${blank}`;
97
+ case "contains":
98
+ return like(c, sql`${`%${esc(node.value)}%`}`);
99
+ case "startsWith":
100
+ return like(c, sql`${`${esc(node.value)}%`}`);
101
+ case "endsWith":
102
+ return like(c, sql`${`%${esc(node.value)}`}`);
103
+ case "eq":
104
+ return sql`${lhs} = ${p(node.value)}`;
105
+ case "ne":
106
+ return sql`${lhs} <> ${p(node.value)}`;
107
+ case "lt":
108
+ return sql`${lhs} < ${p(node.value)}`;
109
+ case "lte":
110
+ return sql`${lhs} <= ${p(node.value)}`;
111
+ case "gt":
112
+ return sql`${lhs} > ${p(node.value)}`;
113
+ case "gte":
114
+ return sql`${lhs} >= ${p(node.value)}`;
115
+ case "in":
116
+ return sql`${lhs} in (${comma(node.value.map(p))})`;
117
+ case "notIn":
118
+ return sql`${lhs} not in (${comma(node.value.map(p))})`;
119
+ case "between":
120
+ return sql`(${lhs} between ${p(node.value[0])} and ${p(node.value[1])})`;
121
+ case "inRange":
122
+ return sql`(${lhs} >= ${p(node.value[0])} and ${lhs} < ${p(node.value[1])})`;
123
+ }
124
+ };
125
+ const same = (c, v) => v === null ? sql`${id(c)} is null` : leaf({ column: c, op: "eq", value: v });
126
+ const keyset = (keys, at, after) => {
127
+ const branches = keys.map((k, i) => {
128
+ const e = ord(k.column);
129
+ const v = at[i] ?? null;
130
+ const nullsAhead = k.nulls === "last" === after;
131
+ let step;
132
+ if (v === null) step = nullsAhead ? void 0 : sql`${e} is not null`;
133
+ else {
134
+ const gt = k.dir === "asc" === after;
135
+ const cmp = gt ? sql`${e} > ${param(v)}` : sql`${e} < ${param(v)}`;
136
+ step = nullsAhead && !k.notNull ? sql`(${cmp} or ${e} is null)` : cmp;
137
+ }
138
+ return step && and([...keys.slice(0, i).map((p, j) => equal(p, at[j] ?? null)), step]);
139
+ });
140
+ return or(branches.filter((b) => b !== void 0));
141
+ };
142
+ const equal = (k, v) => v === null ? sql`${ord(k.column)} is null` : sql`${ord(k.column)} = ${param(v)}`;
143
+ const aggregates = (leafKeys) => {
144
+ const windows = [];
145
+ const input = (c) => (
146
+ // Postgres has no min or max on boolean.
147
+ pg && type(c) === "boolean" ? sql`cast(${id(c)} as integer)` : id(c)
148
+ );
149
+ const agg = (a, partition, cond) => {
150
+ let fn;
151
+ let x;
152
+ if (a.fn === "first" || a.fn === "last") {
153
+ const alias = sql.id(`$w${windows.length}`);
154
+ const over = sql`over (${partition.length ? sql`partition by ${comma(partition.map(ord))} ` : sql``}order by ${orderBy(leafKeys)} rows between unbounded preceding and unbounded following)`;
155
+ const value = input(a.column);
156
+ windows.push(
157
+ a.fn === "first" ? sql`first_value(${value}) ${over} as ${alias}` : sql`last_value(${value}) ${over} as ${alias}`
158
+ );
159
+ fn = (v) => sql`min(${v})`;
160
+ x = alias;
161
+ } else {
162
+ x = a.fn === "min" || a.fn === "max" ? type(a.column) === "string" ? ord(a.column) : input(a.column) : id(a.column);
163
+ fn = {
164
+ sum: (v) => sql`sum(${v})`,
165
+ avg: (v) => sql`avg(${v})`,
166
+ min: (v) => sql`min(${v})`,
167
+ max: (v) => sql`max(${v})`,
168
+ count: (v) => sql`count(${v})`
169
+ }[a.fn];
170
+ }
171
+ if (!cond) return fn(x);
172
+ return pg ? sql`${fn(x)} filter (where ${cond})` : fn(sql`case when ${cond} then ${x} end`);
173
+ };
174
+ const decodeAgg = (a, v) => decode(a.fn === "sum" || a.fn === "avg" || a.fn === "count" ? "number" : type(a.column), v);
175
+ const from = (scope) => sql`(select *${windows.length ? sql`, ${comma(windows)}` : sql``} from ${table} where ${scope}) as s`;
176
+ return { agg, decodeAgg, from };
177
+ };
178
+ return async (input) => {
179
+ const parsed = parseRowsRequest(input, allowList);
180
+ if (!parsed.ok) throw new ProtocolValidationError(parsed.errors);
181
+ const req = parsed.value;
182
+ const { by, keys } = req.group;
183
+ const conds = [];
184
+ if (req.filter) conds.push(where(req.filter));
185
+ if (req.search) {
186
+ const pattern = sql`${`%${esc(req.search)}%`}`;
187
+ conds.push(or(searchColumns.map((c) => like(c.name, pattern))));
188
+ }
189
+ keys.forEach((k, i) => conds.push(same(by[i], k)));
190
+ const matchScope = and(conds);
191
+ const tree = req.tree ? treeLevel(req.tree.keys) : void 0;
192
+ if (tree) conds.push(tree.level);
193
+ const scope = and(conds);
194
+ const sortKey = (column, dir, nulls) => ({
195
+ column,
196
+ type: type(column),
197
+ dir,
198
+ nulls: nulls ?? "last",
199
+ notNull: column === options.key
200
+ });
201
+ const leafKeys = [
202
+ ...req.sort.map((s) => sortKey(s.column, s.dir, s.nulls)),
203
+ sortKey(options.key, "asc")
204
+ ];
205
+ const A = aggregates(leafKeys);
206
+ let pivotColumns;
207
+ let pivotCells = () => ({ sql: [], read: () => [] });
208
+ if (req.pivot) {
209
+ const pivot = req.pivot;
210
+ const pkeys = pivot.by.map((c) => sortKey(c, "asc"));
211
+ const combos = (await run(
212
+ sql`select ${comma(pivot.by.map((c, i) => sql`${ord(c)} as ${sql.id(`$p${i}`)}`))} from ${table} where ${scope} group by ${comma(pivot.by.map(ord))} order by ${orderBy(pkeys)} limit ${LIMITS.maxPivotValues + 1}`
213
+ )).map((r) => pivot.by.map((c, i) => decode(type(c), r[`$p${i}`])));
214
+ if (combos.length > LIMITS.maxPivotValues) {
215
+ const message = `more than ${LIMITS.maxPivotValues} distinct pivot values`;
216
+ throw new ProtocolValidationError([{ path: "pivot", code: "pivot_too_wide", message }]);
217
+ }
218
+ const field = (k, v) => JSON.stringify([...k, aggregateKey(v)]);
219
+ pivotColumns = combos.flatMap(
220
+ (k) => pivot.values.map((v) => ({ field: field(k, v), keys: k, value: aggregateKey(v) }))
221
+ );
222
+ pivotCells = (partition) => {
223
+ const cells = combos.flatMap(
224
+ (k) => pivot.values.map((v) => ({
225
+ name: field(k, v),
226
+ v,
227
+ sql: A.agg(
228
+ v,
229
+ [...partition, ...pivot.by],
230
+ and(pivot.by.map((c, i) => same(c, k[i] ?? null)))
231
+ )
232
+ }))
233
+ );
234
+ return {
235
+ sql: cells.map((c, i) => sql`${c.sql} as ${sql.id(`$v${i}`)}`),
236
+ read: (r) => cells.map((c, i) => [c.name, A.decodeAgg(c.v, r[`$v${i}`])])
237
+ };
238
+ };
239
+ }
240
+ const aggCols = (partition) => {
241
+ const list = req.aggregate.map((a) => A.agg(a, partition));
242
+ return {
243
+ sql: list.map((x, i) => sql`${x} as ${sql.id(`$a${i}`)}`),
244
+ read: (r) => req.aggregate.map(
245
+ (a, i) => [aggregateKey(a), A.decodeAgg(a, r[`$a${i}`])]
246
+ )
247
+ };
248
+ };
249
+ const res = { rows: [] };
250
+ if (keys.length >= by.length && req.pivot) {
251
+ const t = aggCols([]);
252
+ const p = pivotCells([]);
253
+ const r = (await run(
254
+ sql`select ${comma([...t.sql, sql`count(*) as ${sql.id("$n")}`, ...p.sql])} from ${A.from(scope)}`
255
+ ))[0];
256
+ const row = Object.fromEntries([
257
+ ...t.read(r),
258
+ [GROUP_COUNT_KEY, Number(r["$n"])],
259
+ ...p.read(r)
260
+ ]);
261
+ pageOne(res, req, row);
262
+ } else {
263
+ let page;
264
+ if (keys.length < by.length) {
265
+ const col = by[keys.length];
266
+ const s = req.sort.find((x) => x.column === col);
267
+ const k = sortKey(col, s?.dir ?? "asc", s?.nulls);
268
+ k.notNull = false;
269
+ const t = aggCols([col]);
270
+ const p = pivotCells([col]);
271
+ const select = (extra) => sql`select ${comma([sql`${ord(col)} as ${sql.id("$k0")}`, ...t.sql, sql`count(*) as ${sql.id("$n")}`, ...p.sql])} from ${A.from(scope)} where ${extra} group by ${ord(col)}`;
272
+ page = await paged(
273
+ req,
274
+ [k],
275
+ select,
276
+ (extra) => sql`select count(*) as ${sql.id("$n")} from (select ${ord(col)} as ${sql.id("$k0")} from ${table} where ${and([scope, extra])} group by ${ord(col)}) as q`,
277
+ (r) => Object.fromEntries([
278
+ [col, decode(k.type, r["$k0"])],
279
+ ...t.read(r),
280
+ [GROUP_COUNT_KEY, Number(r["$n"])],
281
+ ...p.read(r)
282
+ ])
283
+ );
284
+ } else {
285
+ const names = req.columns ? [.../* @__PURE__ */ new Set([options.key, ...req.columns])] : allowList.map((c) => c.name);
286
+ const cols = [
287
+ ...names.map((n, i) => sql`${id(n)} as ${sql.id(`$c${i}`)}`),
288
+ ...leafKeys.map((k, i) => sql`${id(k.column)} as ${sql.id(`$k${i}`)}`),
289
+ ...tree ? [sql`${tree.children(matchScope)} as ${sql.id("$t")}`] : []
290
+ ];
291
+ const from = tree ? sql`${table} as ${OUTER}` : table;
292
+ page = await paged(
293
+ req,
294
+ leafKeys,
295
+ (extra) => sql`select ${comma(cols)} from ${from} where ${and([scope, extra])}`,
296
+ (extra) => sql`select count(*) as ${sql.id("$n")} from ${table} where ${and([scope, extra])}`,
297
+ (r) => Object.fromEntries([
298
+ ...names.map((n, i) => [n, decode(type(n), r[`$c${i}`])]),
299
+ ...tree ? [[GROUP_COUNT_KEY, Number(r["$t"])]] : []
300
+ ])
301
+ );
302
+ }
303
+ Object.assign(res, page);
304
+ }
305
+ if (pivotColumns) res.pivotColumns = pivotColumns;
306
+ if (req.aggregate.length > 0) {
307
+ const t = aggCols([]);
308
+ const r = await run(sql`select ${comma(t.sql)} from ${A.from(scope)}`);
309
+ res.total = Object.fromEntries(t.read(r[0]));
310
+ }
311
+ return res;
312
+ };
313
+ function treeLevel(keys) {
314
+ const col = treeColumn;
315
+ const key = id(options.key);
316
+ const outerKey = sql`${OUTER}.${key}`;
317
+ const inner = sql.id("$tc");
318
+ if (col.parent === true) {
319
+ const parent = id(col.name);
320
+ const is = (e, v) => v === null ? sql`${e} is null` : sql`${e} = ${param(v)}`;
321
+ const chain = keys.map(
322
+ (k, i) => sql`exists (select 1 from ${table} as ${inner} where ${is(sql`${inner}.${key}`, k)} and ${is(sql`${inner}.${parent}`, i ? keys[i - 1] : null)})`
323
+ );
324
+ return {
325
+ level: and([...chain, is(parent, keys.length ? keys[keys.length - 1] : null)]),
326
+ children: (match) => sql`(select count(*) from ${table} as ${inner} where ${and([match, sql`${inner}.${parent} = ${outerKey}`])})`
327
+ };
328
+ }
329
+ const path = id(col.name);
330
+ const prefix = keys.map((k) => `${String(k)}${TREE_PATH_SEPARATOR}`).join("");
331
+ const keyText = mysql ? sql`cast(${outerKey} as char)` : sql`cast(${outerKey} as text)`;
332
+ const childPath = mysql ? sql`concat(${prefix}, ${keyText})` : sql`(${prefix} || ${keyText})`;
333
+ return {
334
+ level: sql`${path} = ${prefix.slice(0, -1)}`,
335
+ children: (match) => sql`(select count(*) from ${table} as ${inner} where ${and([match, sql`${inner}.${path} = ${childPath}`])})`
336
+ };
337
+ }
338
+ async function paged(req, keys, select, count, toRow) {
339
+ const countAll = async () => Number((await run(count(sql`1 = 1`)))[0]["$n"]);
340
+ const tuple = (r) => keys.map((k, i) => decode(k.type, r[`$k${i}`]));
341
+ const range = req.range;
342
+ if ("start" in range) {
343
+ const size = range.end - range.start;
344
+ const raw2 = await run(
345
+ sql`${select(sql`1 = 1`)} order by ${orderBy(keys)} limit ${size + 1} offset ${range.start}`
346
+ );
347
+ const rows2 = raw2.slice(0, size).map(toRow);
348
+ const out2 = { rows: rows2 };
349
+ if (raw2.length <= size) {
350
+ out2.count = rows2.length > 0 ? range.start + rows2.length : range.start === 0 ? 0 : await countAll();
351
+ } else if (req.count === true) out2.count = await countAll();
352
+ return out2;
353
+ }
354
+ const after = range.before === void 0;
355
+ const cursor = range.after ?? range.before;
356
+ const at = cursor === void 0 ? void 0 : decodeCursor(cursor, keys, after);
357
+ const dirKeys = after ? keys : keys.map(flip);
358
+ const extra = at === void 0 ? sql`1 = 1` : keyset(keys, at, after);
359
+ const raw = await run(
360
+ sql`${select(extra)} order by ${orderBy(dirKeys)} limit ${range.limit + 1}`
361
+ );
362
+ const more = raw.length > range.limit;
363
+ const got = raw.slice(0, range.limit);
364
+ if (!after) got.reverse();
365
+ const rows = got.map(toRow);
366
+ const otherSide = async () => at !== void 0 && (await run(
367
+ sql`${select(or([keyset(keys, at, !after), and(keys.map((k, i) => equal(k, at[i] ?? null)))]))} limit 1`
368
+ )).length > 0;
369
+ const c = {};
370
+ let last;
371
+ if (rows.length === 0) last = after ? true : !await otherSide();
372
+ else if (after) {
373
+ last = !more;
374
+ if (more) c.next = JSON.stringify(tuple(got[got.length - 1]));
375
+ if (await otherSide()) c.prev = JSON.stringify(tuple(got[0]));
376
+ } else {
377
+ last = !await otherSide();
378
+ if (!last) c.next = JSON.stringify(tuple(got[got.length - 1]));
379
+ if (more) c.prev = JSON.stringify(tuple(got[0]));
380
+ }
381
+ const out = { rows, cursor: c };
382
+ if (last || req.count === true) out.count = await countAll();
383
+ return out;
384
+ }
385
+ function decodeCursor(cursor, keys, after) {
386
+ const bad = () => new ProtocolValidationError([
387
+ { path: `range.${after ? "after" : "before"}`, code: "bad_cursor", message: "bad cursor" }
388
+ ]);
389
+ let v;
390
+ try {
391
+ v = JSON.parse(cursor);
392
+ } catch {
393
+ throw bad();
394
+ }
395
+ if (!isArray(v) || v.length !== keys.length || !v.every((x, i) => scalarOk(keys[i].type, x)))
396
+ throw bad();
397
+ if (v.some((x, i) => x === null && keys[i].notNull)) throw bad();
398
+ return v;
399
+ }
400
+ function pageOne(res, req, row) {
401
+ const range = req.range;
402
+ if ("start" in range) {
403
+ res.rows = range.start < 1 && range.end > 0 ? [row] : [];
404
+ if (req.count === true || range.end >= 1) res.count = 1;
405
+ return;
406
+ }
407
+ const cursor = range.after ?? range.before;
408
+ if (cursor !== void 0) decodeCursor(cursor, [], range.before === void 0);
409
+ res.rows = cursor === void 0 ? [row] : [];
410
+ res.cursor = {};
411
+ if (req.count === true || range.before === void 0) res.count = 1;
412
+ }
413
+ }
414
+
415
+ export { createRowsHandler };
416
+ //# sourceMappingURL=index.js.map
417
+ //# sourceMappingURL=index.js.map