query-builder-prisma 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.
package/dist/index.cjs ADDED
@@ -0,0 +1,636 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ DIALECT_CAPABILITIES: () => DIALECT_CAPABILITIES,
24
+ NoResultError: () => NoResultError,
25
+ QueryBuilder: () => QueryBuilder,
26
+ configureQueryBuilder: () => configureQueryBuilder,
27
+ detectDialect: () => detectDialect,
28
+ registerDialect: () => registerDialect,
29
+ resetDialectConfig: () => resetDialectConfig,
30
+ resolveDialect: () => resolveDialect,
31
+ setDialectDetector: () => setDialectDetector
32
+ });
33
+ module.exports = __toCommonJS(index_exports);
34
+
35
+ // src/core/conditions.ts
36
+ var DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
37
+ function isSafeKey(key) {
38
+ return !DANGEROUS_KEYS.has(key);
39
+ }
40
+ function stripUndefined(obj) {
41
+ const result = {};
42
+ for (const [key, value] of Object.entries(obj)) {
43
+ if (value !== void 0 && isSafeKey(key)) {
44
+ result[key] = value;
45
+ }
46
+ }
47
+ return result;
48
+ }
49
+ function deepStripUndefined(obj) {
50
+ const result = {};
51
+ for (const [key, value] of Object.entries(obj)) {
52
+ if (value === void 0 || !isSafeKey(key)) {
53
+ continue;
54
+ }
55
+ result[key] = isDeepStrippable(value) ? deepStripUndefined(value) : Array.isArray(value) ? value.map((item) => isDeepStrippable(item) ? deepStripUndefined(item) : item) : value;
56
+ }
57
+ return result;
58
+ }
59
+ function isDeepStrippable(value) {
60
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
61
+ return false;
62
+ }
63
+ const proto = Object.getPrototypeOf(value);
64
+ return proto === Object.prototype || proto === null;
65
+ }
66
+ function isPlainObject(value) {
67
+ return typeof value === "object" && value !== null && !Array.isArray(value);
68
+ }
69
+ function expandDotPath(path, leaf) {
70
+ const keys = path.split(".").filter((key) => key.length > 0);
71
+ if (keys.length === 0 || keys.some((key) => !isSafeKey(key))) {
72
+ return {};
73
+ }
74
+ let current = leaf;
75
+ for (let i = keys.length - 1; i >= 0; i--) {
76
+ const key = keys[i];
77
+ if (key === void 0) {
78
+ continue;
79
+ }
80
+ current = { [key]: current };
81
+ }
82
+ return current;
83
+ }
84
+ function combineAnd(conditions, customWhere) {
85
+ const all = isPlainObject(customWhere) ? [customWhere, ...conditions] : [...conditions];
86
+ if (all.length === 0) {
87
+ return void 0;
88
+ }
89
+ if (all.length === 1) {
90
+ return all[0];
91
+ }
92
+ return { AND: all };
93
+ }
94
+
95
+ // src/core/pagination.ts
96
+ var DEFAULT_PAGE_SIZE = 10;
97
+ var MAX_PAGE_SIZE = 1e3;
98
+ var MAX_SKIP = 1e5;
99
+ function clampLimit(limit) {
100
+ if (!Number.isFinite(limit)) {
101
+ return DEFAULT_PAGE_SIZE;
102
+ }
103
+ return Math.min(Math.max(1, Math.floor(limit)), MAX_PAGE_SIZE);
104
+ }
105
+ function clampPage(page) {
106
+ if (!Number.isFinite(page)) {
107
+ return 1;
108
+ }
109
+ return Math.max(1, Math.floor(page));
110
+ }
111
+ function toOffsetArgs(page, limit) {
112
+ const safePage = clampPage(page);
113
+ const safeLimit = clampLimit(limit);
114
+ const skip = Math.min((safePage - 1) * safeLimit, MAX_SKIP);
115
+ return { take: safeLimit, skip, page: safePage, limit: safeLimit };
116
+ }
117
+ function buildPaginationMeta(total, page, limit) {
118
+ const safeLimit = clampLimit(limit);
119
+ const safePage = clampPage(page);
120
+ return {
121
+ page: safePage,
122
+ limit: safeLimit,
123
+ total,
124
+ totalPage: Math.ceil(total / safeLimit)
125
+ };
126
+ }
127
+ function serializeCursorValue(value) {
128
+ return value instanceof Date ? value.toISOString() : String(value);
129
+ }
130
+ function toCursorArgs(plan) {
131
+ const sign = plan.direction === "backward" ? -1 : 1;
132
+ const take = sign * (clampLimit(plan.limit ?? DEFAULT_PAGE_SIZE) + 1);
133
+ if (plan.cursor === void 0) {
134
+ return { take };
135
+ }
136
+ return {
137
+ take,
138
+ cursor: { [plan.cursorField]: plan.cursor },
139
+ skip: 1
140
+ };
141
+ }
142
+ function buildCursorPage(rows, info) {
143
+ const { limit, direction, cursorField, hadCursor, exactFlags } = info;
144
+ const safeLimit = clampLimit(limit);
145
+ const hasExtra = rows.length > safeLimit;
146
+ const pageRows = hasExtra ? rows.slice(0, safeLimit) : rows;
147
+ const ordered = direction === "backward" ? [...pageRows].reverse() : pageRows;
148
+ const hasRows = rows.length > 0;
149
+ const hasNextPage = exactFlags?.hasNextPage ?? (direction === "forward" ? hasExtra : hadCursor && hasRows);
150
+ const hasPrevPage = exactFlags?.hasPrevPage ?? (direction === "backward" ? hasExtra : hadCursor && hasRows);
151
+ const first = ordered[0];
152
+ const last = ordered[ordered.length - 1];
153
+ return {
154
+ data: ordered,
155
+ meta: {
156
+ limit: safeLimit,
157
+ nextCursor: hasNextPage && last !== void 0 ? serializeCursorValue(last[cursorField]) : null,
158
+ prevCursor: hasPrevPage && first !== void 0 ? serializeCursorValue(first[cursorField]) : null,
159
+ hasNextPage,
160
+ hasPrevPage
161
+ }
162
+ };
163
+ }
164
+
165
+ // src/dialects/capabilities.ts
166
+ var DIALECT_CAPABILITIES = {
167
+ postgresql: { caseInsensitiveMode: true, caseInsensitiveCollation: false },
168
+ cockroachdb: { caseInsensitiveMode: true, caseInsensitiveCollation: false },
169
+ mysql: { caseInsensitiveMode: false, caseInsensitiveCollation: true },
170
+ mariadb: { caseInsensitiveMode: false, caseInsensitiveCollation: true },
171
+ sqlite: { caseInsensitiveMode: false, caseInsensitiveCollation: false },
172
+ sqlserver: { caseInsensitiveMode: false, caseInsensitiveCollation: true },
173
+ mongodb: { caseInsensitiveMode: true, caseInsensitiveCollation: false },
174
+ /**
175
+ * Fallback used when no dialect is configured/detected. Only emits arguments
176
+ * that are valid on EVERY Prisma-supported database.
177
+ */
178
+ universal: { caseInsensitiveMode: false, caseInsensitiveCollation: false }
179
+ };
180
+
181
+ // src/dialects/detect.ts
182
+ function detectDialect() {
183
+ return void 0;
184
+ }
185
+
186
+ // src/dialects/registry.ts
187
+ var STATE_KEY = /* @__PURE__ */ Symbol.for("query-builder-prisma.dialect-state");
188
+ function state() {
189
+ const host = globalThis;
190
+ return host[STATE_KEY] ??= {
191
+ registry: new Map(Object.entries(DIALECT_CAPABILITIES)),
192
+ globalDialect: void 0,
193
+ detector: void 0
194
+ };
195
+ }
196
+ function registerDialect(name, capabilities) {
197
+ state().registry.set(name, capabilities);
198
+ }
199
+ function configureQueryBuilder(options) {
200
+ state().globalDialect = options.dialect;
201
+ }
202
+ function setDialectDetector(detector) {
203
+ state().detector = detector;
204
+ }
205
+ function resolveDialect(explicit) {
206
+ const s = state();
207
+ const requested = explicit ?? s.globalDialect ?? s.detector?.() ?? detectDialect() ?? "universal";
208
+ const capabilities = s.registry.get(requested);
209
+ return capabilities ? { name: requested, capabilities } : { name: "universal", capabilities: DIALECT_CAPABILITIES.universal };
210
+ }
211
+ function resetDialectConfig() {
212
+ const s = state();
213
+ s.globalDialect = void 0;
214
+ s.detector = void 0;
215
+ }
216
+
217
+ // src/core/query-builder.ts
218
+ var NoResultError = class extends Error {
219
+ constructor() {
220
+ super("Query returned no rows");
221
+ this.name = "NoResultError";
222
+ }
223
+ };
224
+ var QueryBuilder = class {
225
+ delegate;
226
+ dialect;
227
+ strictNumbers;
228
+ andConditions = [];
229
+ customArgs = {};
230
+ /**
231
+ * The `initialArgs` seed `where` plus every `.custom({ where })`, AND-merged.
232
+ * Kept out of `customArgs` so a later `.custom({ where })` merges with the
233
+ * seed instead of replacing it (audit F2 — the seed carries safety filters).
234
+ */
235
+ customWhere;
236
+ orderByArg;
237
+ selectArg;
238
+ includeArg;
239
+ page;
240
+ limit;
241
+ cursorActive = false;
242
+ cursor;
243
+ cursorLimit;
244
+ cursorDirection = "forward";
245
+ cursorField = "id";
246
+ cursorStrict = false;
247
+ /**
248
+ * @param delegate - The Prisma delegate to query (e.g. `prisma.user`).
249
+ * @param options - Optional seed args, a dialect override, or `strictNumbers`.
250
+ */
251
+ constructor(delegate, options) {
252
+ this.delegate = delegate;
253
+ this.dialect = options?.dialect;
254
+ this.strictNumbers = options?.strictNumbers ?? false;
255
+ if (options?.initialArgs) {
256
+ const { where, ...rest } = options.initialArgs;
257
+ this.customArgs = { ...rest };
258
+ this.customWhere = where;
259
+ }
260
+ }
261
+ /**
262
+ * Case-insensitive `contains` across the provided string fields. No condition
263
+ * is added when `searchText` is empty or whitespace-only (audit G7).
264
+ *
265
+ * Dialect-aware: adds `mode: 'insensitive'` only where Prisma accepts it (see
266
+ * `caseInsensitiveMode` in `src/dialects/capabilities.ts`); everywhere else
267
+ * the bare `contains` relies on the database's collation, and where that is
268
+ * ASCII-only matching stays case-sensitive — Prisma offers no alternative
269
+ * there.
270
+ */
271
+ search(params) {
272
+ const text = params.searchText?.trim();
273
+ const fields = params.fields;
274
+ if (text && fields.length > 0) {
275
+ const { capabilities } = resolveDialect(this.dialect);
276
+ this.andConditions.push({
277
+ OR: fields.map((field) => {
278
+ const match = { contains: text };
279
+ if (capabilities.caseInsensitiveMode) {
280
+ match.mode = "insensitive";
281
+ }
282
+ return { [field]: match };
283
+ })
284
+ });
285
+ }
286
+ return this;
287
+ }
288
+ /**
289
+ * Adds an equality/operator filter. Accepts a partial Prisma `where` object;
290
+ * `undefined` values are ignored so optional query params are safe to pass.
291
+ */
292
+ filter(filters) {
293
+ const cleaned = stripUndefined(filters);
294
+ if (Object.keys(cleaned).length > 0) {
295
+ this.andConditions.push(cleaned);
296
+ }
297
+ return this;
298
+ }
299
+ /**
300
+ * Adds `gte`/`lte` range conditions. Keys may be dot-paths to reach relations
301
+ * or nested objects (e.g. `'avatar.size'`). Bounds left `undefined` are
302
+ * skipped; a field is only added when at least one bound is present.
303
+ */
304
+ range(ranges) {
305
+ for (const [path, bound] of Object.entries(ranges)) {
306
+ const condition = {};
307
+ if (bound.from !== void 0) {
308
+ condition.gte = bound.from;
309
+ }
310
+ if (bound.to !== void 0) {
311
+ condition.lte = bound.to;
312
+ }
313
+ if (Object.keys(condition).length > 0) {
314
+ const expanded = expandDotPath(path, condition);
315
+ if (Object.keys(expanded).length > 0) {
316
+ this.andConditions.push(expanded);
317
+ }
318
+ }
319
+ }
320
+ return this;
321
+ }
322
+ /** Adds an arbitrary, fully-typed Prisma `where` condition. */
323
+ where(condition) {
324
+ const cleaned = stripUndefined(condition);
325
+ if (Object.keys(cleaned).length > 0) {
326
+ this.andConditions.push(cleaned);
327
+ }
328
+ return this;
329
+ }
330
+ /**
331
+ * Sets `orderBy` from a single key. No-op when `sortBy` is not provided.
332
+ * Dot paths expand like `.range()` (`'avatar.size'` → `{ avatar: { size } }`,
333
+ * audit F6). For multi-key or nested relation sorts use {@link orderBy}.
334
+ */
335
+ sortBy(params) {
336
+ const { sortBy, sortOrder = "desc" } = params;
337
+ if (sortBy) {
338
+ const expanded = expandDotPath(sortBy, sortOrder);
339
+ if (Object.keys(expanded).length > 0) {
340
+ this.orderByArg = expanded;
341
+ }
342
+ }
343
+ return this;
344
+ }
345
+ /**
346
+ * Sets `orderBy` verbatim from the full Prisma shape: arrays for multi-key
347
+ * sorts, nested relation order objects. `.sortBy()` remains the single-key
348
+ * convenience — the latest of the two calls wins (audit G1).
349
+ */
350
+ orderBy(order) {
351
+ this.orderByArg = order;
352
+ return this;
353
+ }
354
+ /** Configures `skip`/`take` from a 1-based page number and page size. */
355
+ paginate(params) {
356
+ this.assertPage(params.page);
357
+ this.assertLimit(params.limit);
358
+ this.page = params.page ?? 1;
359
+ this.limit = params.limit ?? DEFAULT_PAGE_SIZE;
360
+ return this;
361
+ }
362
+ /**
363
+ * Configures cursor-based ("seek") pagination. Use {@link executeWithCursor}
364
+ * to run the query and obtain `next`/`prev` cursors.
365
+ *
366
+ * - `cursor` is the value of `cursorField` from the edge row of the previous
367
+ * page (omit it for the first page). Strings, numbers and Dates are
368
+ * accepted; Dates serialize to ISO-8601 in the returned cursors (audit F4).
369
+ * - `direction` walks `'forward'` (next) or `'backward'` (previous).
370
+ * - `cursorField` is the unique, sequential column to seek on (default `id`).
371
+ * Pair it with a matching {@link sortBy} for stable ordering.
372
+ * - `strict` spends one extra 1-row probe query to make `hasNextPage` /
373
+ * `hasPrevPage` exact instead of optimistic (audit F10).
374
+ *
375
+ * Takes precedence over {@link paginate} when both are set.
376
+ */
377
+ cursorPaginate(params) {
378
+ this.assertLimit(params.limit);
379
+ this.cursorActive = true;
380
+ this.cursor = params.cursor;
381
+ this.cursorLimit = params.limit;
382
+ this.cursorDirection = params.direction ?? "forward";
383
+ this.cursorField = params.cursorField ?? "id";
384
+ this.cursorStrict = params.strict ?? false;
385
+ return this;
386
+ }
387
+ /**
388
+ * Projects fields with Prisma `select`. The result type of `execute()` is
389
+ * narrowed to exactly the selected shape. Clears any active `.include()`.
390
+ */
391
+ select(select) {
392
+ this.selectArg = select;
393
+ this.includeArg = void 0;
394
+ return this;
395
+ }
396
+ /**
397
+ * Eager-loads relations with Prisma `include`. The result type of `execute()`
398
+ * is widened with the included relations. Clears any active `.select()`.
399
+ */
400
+ include(include) {
401
+ this.includeArg = include;
402
+ this.selectArg = void 0;
403
+ return this;
404
+ }
405
+ /**
406
+ * Merges raw `findMany` args, e.g. `cursor`, `distinct` or a custom `where`.
407
+ * Values that are `undefined` are stripped at any depth, so
408
+ * `custom({ distinct: undefined })` cannot overwrite an earlier value
409
+ * (audit F15). A custom `where` is AND-ed with the `initialArgs` seed and any
410
+ * previous custom `where` — it never replaces them (audit F2). Successive
411
+ * custom `where`s may nest `{ AND: [...] }` groups; Prisma treats that
412
+ * identically.
413
+ */
414
+ custom(args) {
415
+ const { where, ...rest } = args;
416
+ this.customArgs = { ...this.customArgs, ...deepStripUndefined(rest) };
417
+ if (where !== void 0) {
418
+ const cleaned = isPlainObject(where) ? deepStripUndefined(where) : where;
419
+ const hasKeys = !isPlainObject(cleaned) || Object.keys(cleaned).length > 0;
420
+ if (hasKeys) {
421
+ this.customWhere = combineAnd([cleaned], this.customWhere);
422
+ }
423
+ }
424
+ return this;
425
+ }
426
+ /** The fully assembled `findMany` args. Useful for debugging or reuse. */
427
+ buildArgs() {
428
+ const args = { ...this.customArgs };
429
+ const where = this.buildWhere();
430
+ if (where) {
431
+ args.where = where;
432
+ }
433
+ if (this.orderByArg) {
434
+ args.orderBy = this.orderByArg;
435
+ }
436
+ if (this.selectArg) {
437
+ args.select = this.selectArg;
438
+ }
439
+ if (this.includeArg) {
440
+ args.include = this.includeArg;
441
+ }
442
+ if (this.cursorActive) {
443
+ const cursorArgs = toCursorArgs({
444
+ cursor: this.cursor,
445
+ limit: this.cursorLimit,
446
+ direction: this.cursorDirection,
447
+ cursorField: this.cursorField
448
+ });
449
+ args.take = cursorArgs.take;
450
+ if (cursorArgs.cursor) {
451
+ args.cursor = cursorArgs.cursor;
452
+ }
453
+ if (cursorArgs.skip !== void 0) {
454
+ args.skip = cursorArgs.skip;
455
+ }
456
+ } else if (this.limit !== void 0) {
457
+ const page = this.page ?? 1;
458
+ this.assertSkipCap(page, this.limit);
459
+ const offset = toOffsetArgs(page, this.limit);
460
+ args.take = offset.take;
461
+ args.skip = offset.skip;
462
+ }
463
+ return args;
464
+ }
465
+ /**
466
+ * Executes the query and returns the rows, typed from `.select()`/`.include()`.
467
+ *
468
+ * Tip: for 100% Prisma-native inference you can always run the passthrough
469
+ * `prisma.user.findMany(qb.buildArgs())` — same args, Prisma's own overloads.
470
+ */
471
+ async execute() {
472
+ const findMany = this.delegate.findMany.bind(this.delegate);
473
+ const data = await findMany(this.buildArgs());
474
+ return data;
475
+ }
476
+ /** Executes the query and returns the first row, or `null` when none matched. */
477
+ async first() {
478
+ const args = { ...this.buildArgs() };
479
+ args.take = 1;
480
+ delete args.skip;
481
+ delete args.cursor;
482
+ const findMany = this.delegate.findMany.bind(this.delegate);
483
+ const rows = await findMany(args);
484
+ const row = rows[0];
485
+ return row ?? null;
486
+ }
487
+ /** Like {@link first}, but throws {@link NoResultError} when nothing matched. */
488
+ async firstOrThrow() {
489
+ const row = await this.first();
490
+ if (row === null) {
491
+ throw new NoResultError();
492
+ }
493
+ return row;
494
+ }
495
+ /** Counts rows matching the current filters (ignores pagination/projection). */
496
+ async count() {
497
+ const where = this.buildWhere();
498
+ const countFn = this.delegate.count.bind(this.delegate);
499
+ return countFn(where ? { where } : {});
500
+ }
501
+ /**
502
+ * Executes the query and returns the rows plus offset pagination metadata.
503
+ * When no pagination was configured, defaults to page 1, limit 10 so `meta`
504
+ * always describes the data actually returned. `count` and `findMany` run in
505
+ * parallel.
506
+ *
507
+ * Pass `{ includeTotal: false }` to skip the `COUNT` query entirely — `meta`
508
+ * then carries `total: null` / `totalPage: null` (audit G3).
509
+ *
510
+ * Throws when cursor pagination is configured — offset meta cannot describe a
511
+ * seek query, and the cursor over-fetch row would leak into `data` (audit F1).
512
+ * Use {@link executeWithCursor} instead.
513
+ */
514
+ async executeWithMeta(opts) {
515
+ if (this.cursorActive) {
516
+ throw new Error(
517
+ "executeWithMeta() is offset-mode only: this builder has cursor pagination configured via cursorPaginate(). Use executeWithCursor() instead."
518
+ );
519
+ }
520
+ if (this.limit === void 0) {
521
+ this.paginate({ page: 1, limit: DEFAULT_PAGE_SIZE });
522
+ }
523
+ this.assertSkipCap(this.page ?? 1, this.limit ?? DEFAULT_PAGE_SIZE);
524
+ const offset = toOffsetArgs(this.page ?? 1, this.limit ?? DEFAULT_PAGE_SIZE);
525
+ if (opts?.includeTotal === false) {
526
+ const data2 = await this.execute();
527
+ return {
528
+ meta: { page: offset.page, limit: offset.limit, total: null, totalPage: null },
529
+ data: data2
530
+ };
531
+ }
532
+ const [total, data] = await Promise.all([this.count(), this.execute()]);
533
+ return {
534
+ meta: buildPaginationMeta(total, offset.page, offset.limit),
535
+ data
536
+ };
537
+ }
538
+ /**
539
+ * Executes a cursor-paginated query (see {@link cursorPaginate}) and returns
540
+ * the page rows plus `next`/`prev` cursors. Rows are always returned in the
541
+ * configured sort order, regardless of pagination `direction`.
542
+ *
543
+ * Throws when a `.select()` projection drops `cursorField` — the page cursors
544
+ * are derived from that field and would come out as `undefined` (audit F5).
545
+ */
546
+ async executeWithCursor() {
547
+ if (!this.cursorActive) {
548
+ this.cursorPaginate({});
549
+ }
550
+ this.assertCursorFieldProjected();
551
+ const limit = this.cursorLimit ?? DEFAULT_PAGE_SIZE;
552
+ const hadCursor = this.cursor !== void 0;
553
+ const findMany = this.delegate.findMany.bind(this.delegate);
554
+ const rows = await findMany(this.buildArgs());
555
+ let exactFlags;
556
+ if (this.cursorStrict && hadCursor) {
557
+ const probeArgs = {
558
+ take: this.cursorDirection === "forward" ? -1 : 1,
559
+ cursor: { [this.cursorField]: this.cursor },
560
+ skip: 1
561
+ };
562
+ const where = this.buildWhere();
563
+ if (where) {
564
+ probeArgs.where = where;
565
+ }
566
+ if (this.orderByArg) {
567
+ probeArgs.orderBy = this.orderByArg;
568
+ }
569
+ const probe = await findMany(probeArgs);
570
+ const hasEdgeRow = probe.length > 0;
571
+ exactFlags = this.cursorDirection === "forward" ? { hasPrevPage: hasEdgeRow } : { hasNextPage: hasEdgeRow };
572
+ }
573
+ const { data, meta } = buildCursorPage(rows, {
574
+ limit,
575
+ direction: this.cursorDirection,
576
+ cursorField: this.cursorField,
577
+ hadCursor,
578
+ exactFlags
579
+ });
580
+ return { meta, data };
581
+ }
582
+ /** strictNumbers: out-of-range limits throw instead of clamping (audit F12). */
583
+ assertLimit(limit) {
584
+ if (!this.strictNumbers || limit === void 0) {
585
+ return;
586
+ }
587
+ if (!Number.isFinite(limit) || limit < 1 || limit > MAX_PAGE_SIZE) {
588
+ throw new Error(`strictNumbers: limit ${String(limit)} is outside [1, ${MAX_PAGE_SIZE}].`);
589
+ }
590
+ }
591
+ assertPage(page) {
592
+ if (!this.strictNumbers || page === void 0) {
593
+ return;
594
+ }
595
+ if (!Number.isFinite(page) || page < 1) {
596
+ throw new Error(`strictNumbers: page ${String(page)} must be a finite number >= 1.`);
597
+ }
598
+ }
599
+ /** strictNumbers: a computed skip beyond MAX_SKIP throws (audit F18). */
600
+ assertSkipCap(page, limit) {
601
+ if (!this.strictNumbers) {
602
+ return;
603
+ }
604
+ const skip = (clampPage(page) - 1) * clampLimit(limit);
605
+ if (skip > MAX_SKIP) {
606
+ throw new Error(
607
+ `strictNumbers: computed skip ${String(skip)} exceeds the ${String(MAX_SKIP)} cap \u2014 use cursor pagination for deep pages.`
608
+ );
609
+ }
610
+ }
611
+ /** A projection without the cursor field would derive cursors from `undefined` (audit F5). */
612
+ assertCursorFieldProjected() {
613
+ const select = this.selectArg ?? this.customArgs.select;
614
+ if (select && !select[this.cursorField]) {
615
+ throw new Error(
616
+ `executeWithCursor(): the projection drops cursorField "${this.cursorField}", so page cursors would be built from undefined. Keep the field in .select() or remove the projection.`
617
+ );
618
+ }
619
+ }
620
+ buildWhere() {
621
+ return combineAnd(this.andConditions, this.customWhere);
622
+ }
623
+ };
624
+ // Annotate the CommonJS export names for ESM import in node:
625
+ 0 && (module.exports = {
626
+ DIALECT_CAPABILITIES,
627
+ NoResultError,
628
+ QueryBuilder,
629
+ configureQueryBuilder,
630
+ detectDialect,
631
+ registerDialect,
632
+ resetDialectConfig,
633
+ resolveDialect,
634
+ setDialectDetector
635
+ });
636
+ //# sourceMappingURL=index.cjs.map