uql-orm 0.112.1 → 0.113.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 (83) hide show
  1. package/README.md +1 -1
  2. package/dist/browser/http/httpTransport.d.ts +29 -0
  3. package/dist/browser/http/httpTransport.js +59 -0
  4. package/dist/browser/http/index.d.ts +1 -2
  5. package/dist/browser/http/index.js +1 -2
  6. package/dist/browser/index.d.ts +1 -0
  7. package/dist/browser/querier/clientQuerier.d.ts +7 -0
  8. package/dist/browser/querier/clientQuerier.js +43 -0
  9. package/dist/browser/querier/index.d.ts +2 -1
  10. package/dist/browser/querier/index.js +2 -1
  11. package/dist/browser/querier/queryOptions.d.ts +23 -0
  12. package/dist/browser/querier/queryOptions.js +35 -0
  13. package/dist/browser/type/clientQuerier.d.ts +10 -11
  14. package/dist/browser/type/index.d.ts +1 -1
  15. package/dist/browser/type/index.js +1 -1
  16. package/dist/browser/type/transport.d.ts +13 -0
  17. package/dist/dialect/abstractDialect.d.ts +2 -2
  18. package/dist/express/index.d.ts +1 -1
  19. package/dist/express/index.js +1 -1
  20. package/dist/express/router.d.ts +8 -0
  21. package/dist/express/router.js +50 -0
  22. package/dist/http/api.d.ts +36 -0
  23. package/dist/http/api.js +136 -0
  24. package/dist/http/apiCall.d.ts +59 -0
  25. package/dist/http/apiCall.js +52 -0
  26. package/dist/http/errors.d.ts +20 -0
  27. package/dist/http/errors.js +27 -0
  28. package/dist/http/exposure.d.ts +54 -0
  29. package/dist/http/exposure.js +171 -0
  30. package/dist/http/handler.d.ts +23 -88
  31. package/dist/http/handler.js +42 -158
  32. package/dist/http/index.d.ts +8 -4
  33. package/dist/http/index.js +6 -3
  34. package/dist/http/route.d.ts +34 -0
  35. package/dist/http/route.js +82 -0
  36. package/dist/http/wireCall.d.ts +115 -0
  37. package/dist/http/wireCall.js +126 -0
  38. package/dist/http/wireQuery.d.ts +8 -0
  39. package/dist/http/wireQuery.js +51 -0
  40. package/dist/http/wireRow.d.ts +4 -2
  41. package/dist/http/wireRow.js +15 -2
  42. package/dist/index.d.ts +1 -1
  43. package/dist/index.js +1 -1
  44. package/dist/mongodb/mongoDialect.d.ts +6 -6
  45. package/dist/mongodb/mongodbQuerier.d.ts +8 -8
  46. package/dist/nestjs/uqlContextInterceptor.d.ts +3 -3
  47. package/dist/nestjs/uqlContextInterceptor.js +7 -7
  48. package/dist/nestjs/uqlModule.d.ts +5 -11
  49. package/dist/nestjs/uqlModule.js +10 -15
  50. package/dist/querier/abstractQuerier.d.ts +8 -8
  51. package/dist/querier/abstractQuerier.js +15 -8
  52. package/dist/querier/abstractSqlQuerier.d.ts +8 -8
  53. package/dist/querier/keyset.d.ts +15 -0
  54. package/dist/querier/keyset.js +16 -11
  55. package/dist/type/column.d.ts +4 -1
  56. package/dist/type/querier.d.ts +2 -2
  57. package/dist/type/query.d.ts +18 -4
  58. package/dist/type/universalQuerier.d.ts +16 -16
  59. package/dist/type/wire.d.ts +1 -31
  60. package/dist/util/dialect.util.d.ts +9 -9
  61. package/dist/util/dialect.util.js +18 -10
  62. package/dist/util/field.util.d.ts +4 -1
  63. package/dist/util/field.util.js +5 -2
  64. package/dist/util/uqlError.d.ts +27 -1
  65. package/dist/util/uqlError.js +43 -0
  66. package/package.json +1 -1
  67. package/skills/uql-orm/SKILL.md +4 -2
  68. package/dist/browser/http/bus.d.ts +0 -3
  69. package/dist/browser/http/bus.js +0 -12
  70. package/dist/browser/http/http.d.ts +0 -20
  71. package/dist/browser/http/http.js +0 -67
  72. package/dist/browser/querier/httpQuerier.d.ts +0 -46
  73. package/dist/browser/querier/httpQuerier.js +0 -70
  74. package/dist/browser/type/request.d.ts +0 -27
  75. package/dist/express/querierMiddleware.d.ts +0 -11
  76. package/dist/express/querierMiddleware.js +0 -39
  77. package/dist/http/contract.d.ts +0 -113
  78. package/dist/http/contract.js +0 -83
  79. package/dist/http/fetchHandler.d.ts +0 -13
  80. package/dist/http/fetchHandler.js +0 -63
  81. package/dist/http/query.d.ts +0 -26
  82. package/dist/http/query.js +0 -119
  83. /package/dist/browser/type/{request.js → transport.js} +0 -0
@@ -1,9 +1,11 @@
1
1
  import type { EntityMeta } from '../type/index.js';
2
- import type { WireAnswer } from './contract.js';
2
+ import type { WireAnswer } from './wireCall.js';
3
3
  /** `data` as JSON is to carry it, by what its route `answers`; the client reads it back by {@link readWireData}. */
4
4
  export declare function writeWireData<E>(meta: EntityMeta<E>, data: unknown, answers: WireAnswer): unknown;
5
- /** `data` JSON carried, a response or a write's body, read back as the entity holds it by what it `answers`. */
5
+ /** `data` JSON carried, a response, read back as the entity holds it by what it `answers`. */
6
6
  export declare function readWireData<E>(meta: EntityMeta<E>, data: unknown, answers: WireAnswer): unknown;
7
+ /** A write's payload JSON carried, a row, a list of rows or an update's changes, read back as the entity holds it. */
8
+ export declare function readWirePayload<E>(meta: EntityMeta<E>, payload: unknown): unknown;
7
9
  /**
8
10
  * `query` with each value it compares a field with read back as the entity holds it, its `$populate` and `$count`
9
11
  * relations' included: JSON carried each date and `bigint` as text, which an engine would compare as text.
@@ -21,16 +21,21 @@ const received = (field) => {
21
21
  }
22
22
  };
23
23
  }
24
- return columnFamily(type) === 'date' ? (text) => decodeDate(String(text)) : undefined;
24
+ // A transport carrying a `Date` as one (superjson) hands it over read already.
25
+ return columnFamily(type) === 'date' ? (text) => (text instanceof Date ? text : decodeDate(String(text))) : undefined;
25
26
  };
26
27
  /** `data` as JSON is to carry it, by what its route `answers`; the client reads it back by {@link readWireData}. */
27
28
  export function writeWireData(meta, data, answers) {
28
29
  return across(meta, data, answers, SENDING);
29
30
  }
30
- /** `data` JSON carried, a response or a write's body, read back as the entity holds it by what it `answers`. */
31
+ /** `data` JSON carried, a response, read back as the entity holds it by what it `answers`. */
31
32
  export function readWireData(meta, data, answers) {
32
33
  return across(meta, data, answers, RECEIVING);
33
34
  }
35
+ /** A write's payload JSON carried, a row, a list of rows or an update's changes, read back as the entity holds it. */
36
+ export function readWirePayload(meta, payload) {
37
+ return convert(meta, payload, RECEIVING);
38
+ }
34
39
  /**
35
40
  * `query` with each value it compares a field with read back as the entity holds it, its `$populate` and `$count`
36
41
  * relations' included: JSON carried each date and `bigint` as text, which an engine would compare as text.
@@ -59,6 +64,14 @@ function across(meta, data, answers, way) {
59
64
  return data;
60
65
  case 'rows':
61
66
  return convert(meta, data, way);
67
+ case 'rowsAndCount': {
68
+ if (!Array.isArray(data)) {
69
+ return data;
70
+ }
71
+ const [rows, count] = data;
72
+ const converted = convert(meta, rows, way);
73
+ return converted === rows ? data : [converted, count];
74
+ }
62
75
  case 'page': {
63
76
  if (!isPlainObject(data)) {
64
77
  return data;
package/dist/index.d.ts CHANGED
@@ -12,4 +12,4 @@ export { sortOf } from './util/query.util.js';
12
12
  export { DefaultLogger } from './util/logger.js';
13
13
  export { aliasOf, currentDate, currentTime, currentTimestamp, refs, sql, tableOf, uuid, uuidv7 } from './util/sql.js';
14
14
  export { deleteFrom, insertInto, refuse, type TriggerUpsert, updateTable, upsertInto } from './util/triggerWrite.js';
15
- export { type QueryErrorKind, UqlError, UqlOptimisticLockError, UqlSecurityError, UqlUsageError, } from './util/uqlError.js';
15
+ export { type QueryErrorKind, UqlError, type UqlErrorOptions, type UqlErrorPath, UqlOptimisticLockError, UqlRequestError, UqlSecurityError, UqlUsageError, } from './util/uqlError.js';
package/dist/index.js CHANGED
@@ -11,4 +11,4 @@ export { sortOf } from './util/query.util.js';
11
11
  export { DefaultLogger } from './util/logger.js';
12
12
  export { aliasOf, currentDate, currentTime, currentTimestamp, refs, sql, tableOf, uuid, uuidv7 } from './util/sql.js';
13
13
  export { deleteFrom, insertInto, refuse, updateTable, upsertInto } from './util/triggerWrite.js';
14
- export { UqlError, UqlOptimisticLockError, UqlSecurityError, UqlUsageError, } from './util/uqlError.js';
14
+ export { UqlError, UqlOptimisticLockError, UqlRequestError, UqlSecurityError, UqlUsageError, } from './util/uqlError.js';
@@ -1,6 +1,6 @@
1
1
  import { type Document, type Filter, type Sort } from 'mongodb';
2
2
  import { AbstractDialect } from '../dialect/abstractDialect.js';
3
- import type { DialectFeatures, EntityData, EntityMeta, Query, QueryAggregate, QueryOptions, QueryPager, QuerySelectValue, QuerySortMap, QueryWhere, AbstractType } from '../type/index.js';
3
+ import type { DialectFeatures, EntityData, EntityMeta, Query, QueryAggregate, StatementOptions, QueryPager, QuerySelectValue, QuerySortMap, QueryWhere, AbstractType } from '../type/index.js';
4
4
  import { type CallbackKey } from '../util/index.js';
5
5
  /** How a read runs: its pipeline, or the ordering of the `find` cursor where one expresses it. */
6
6
  export type MongoRead = {
@@ -25,14 +25,14 @@ export declare class MongoDialect extends AbstractDialect {
25
25
  * the document does not use.
26
26
  */
27
27
  columnOf<E>(meta: EntityMeta<E>, key: string): string;
28
- where<E extends Document>(entity: AbstractType<E>, where?: QueryWhere<E>, opts?: QueryOptions): Filter<E>;
28
+ where<E extends Document>(entity: AbstractType<E>, where?: QueryWhere<E>, opts?: StatementOptions): Filter<E>;
29
29
  /**
30
30
  * The stages every pipeline starts with: the `$lookup` each relation condition needs, into a temporary
31
31
  * field so `$or` keeps its meaning, the `$match` reading them, and the temporaries taken back out. Each
32
32
  * relation aggregate the `$where` or `fields` reads is left on the document, once, under its column.
33
33
  * `lookup` keeps the temporaries used, so a later lookup neither repeats nor reuses one.
34
34
  */
35
- matchStages<E extends Document>(entity: AbstractType<E>, where?: QueryWhere<E>, opts?: QueryOptions, fields?: readonly string[], lookup?: Lookup): MongoAggregationPipelineEntry<Document>[];
35
+ matchStages<E extends Document>(entity: AbstractType<E>, where?: QueryWhere<E>, opts?: StatementOptions, fields?: readonly string[], lookup?: Lookup): MongoAggregationPipelineEntry<Document>[];
36
36
  /**
37
37
  * Renders a `$where` tree without applying entity filters (used for same-scope group-operator
38
38
  * recursion). A relation, or a relation aggregate, needs `$lookup` stages, so it is only accepted
@@ -161,7 +161,7 @@ export declare class MongoDialect extends AbstractDialect {
161
161
  * How a read runs, its ordering and aggregates read once for both the routing and the run: the one place
162
162
  * deciding how a read is scored and ranked, a root vector search through Atlas.
163
163
  */
164
- readPlan<E extends Document>(entity: AbstractType<E>, q: Query<E>, opts?: QueryOptions): MongoRead;
164
+ readPlan<E extends Document>(entity: AbstractType<E>, q: Query<E>, opts?: StatementOptions): MongoRead;
165
165
  /**
166
166
  * Whether a read needs stages a `find` cursor cannot express: a lookup to populate, count, filter or
167
167
  * order by a relation, one to build a relation aggregate, and the grouping `$distinct` is.
@@ -173,7 +173,7 @@ export declare class MongoDialect extends AbstractDialect {
173
173
  */
174
174
  private vectorSearchPipeline;
175
175
  /** A read as a pipeline, whether or not a `find` cursor would express it. */
176
- aggregationPipeline<E extends Document>(entity: AbstractType<E>, q: Query<E>, opts?: QueryOptions): MongoAggregationPipelineEntry<Document>[];
176
+ aggregationPipeline<E extends Document>(entity: AbstractType<E>, q: Query<E>, opts?: StatementOptions): MongoAggregationPipelineEntry<Document>[];
177
177
  /** The pipeline of a read no `$vectorSearch` enters, given its ordering, aggregates and vector score. */
178
178
  private scanPipeline;
179
179
  /** A vector search's exact distance, by its metric, as a score to rank by: its `$project`, else a temporary field. */
@@ -242,7 +242,7 @@ export declare class MongoDialect extends AbstractDialect {
242
242
  /**
243
243
  * Build MongoDB aggregation pipeline stages from a QueryAggregate.
244
244
  */
245
- buildAggregateStages<E extends Document>(entity: AbstractType<E>, q: QueryAggregate<E>, opts?: QueryOptions): MongoAggregationPipelineEntry<Document>[];
245
+ buildAggregateStages<E extends Document>(entity: AbstractType<E>, q: QueryAggregate<E>, opts?: StatementOptions): MongoAggregationPipelineEntry<Document>[];
246
246
  /**
247
247
  * Resolve parsed group entries into the `_id` keys and accumulators of a `$group` stage, and the
248
248
  * `columns` its `$project` reads each result from: a group key out of `_id`, a DISTINCT set by its
@@ -1,7 +1,7 @@
1
1
  import type { ClientSession, Document, MongoClient } from 'mongodb';
2
2
  import type { UpsertedId } from '../querier/abstractQuerier.js';
3
3
  import { AbstractQuerier } from '../querier/index.js';
4
- import type { EntityData, ExtraOptions, Query, QueryAggregate, QueryUpsert, QueryPage, QueryOptions, QuerySearch, RawRow, TransactionOptions, Type, UpdatePayload } from '../type/index.js';
4
+ import type { EntityData, ExtraOptions, Query, QueryAggregate, QueryUpsert, QueryPage, StatementOptions, QuerySearch, RawRow, TransactionOptions, Type, UpdatePayload } from '../type/index.js';
5
5
  import type { MongoDialect } from './mongoDialect.js';
6
6
  import type { MongoQuerier } from './mongoQuerier.js';
7
7
  export declare class MongodbQuerier extends AbstractQuerier implements MongoQuerier {
@@ -13,8 +13,8 @@ export declare class MongodbQuerier extends AbstractQuerier implements MongoQuer
13
13
  constructor(dialect: MongoDialect, conn: MongoClient, extra?: ExtraOptions);
14
14
  /** Runs `task` on the open transaction's session, if any, after everything queued before it, timed as `label`. */
15
15
  private execute;
16
- protected internalFindMany<E extends Document>(entity: Type<E>, q: Query<E>, opts?: QueryOptions): Promise<E[]>;
17
- protected internalFindManyStream<E extends Document>(entity: Type<E>, q: Query<E>, opts?: QueryOptions): AsyncGenerator<E, void, unknown>;
16
+ protected internalFindMany<E extends Document>(entity: Type<E>, q: Query<E>, opts?: StatementOptions): Promise<E[]>;
17
+ protected internalFindManyStream<E extends Document>(entity: Type<E>, q: Query<E>, opts?: StatementOptions): AsyncGenerator<E, void, unknown>;
18
18
  /**
19
19
  * The cursor a read runs on: the aggregation pipeline for a clause only a stage can express - a
20
20
  * lookup, a grouping, a vector search - and the plain `find` cursor for everything else. One routing
@@ -24,22 +24,22 @@ export declare class MongodbQuerier extends AbstractQuerier implements MongoQuer
24
24
  private buildScalarProjection;
25
25
  /** Build a MongoDB FindCursor with filter, projection, skip, and limit from the query, ordered by `sort`. */
26
26
  private buildFindCursor;
27
- protected internalAggregate<E extends Document>(entity: Type<E>, q: QueryAggregate<E>, opts?: QueryOptions): Promise<RawRow[]>;
27
+ protected internalAggregate<E extends Document>(entity: Type<E>, q: QueryAggregate<E>, opts?: StatementOptions): Promise<RawRow[]>;
28
28
  /**
29
29
  * A `$required` relation drops parents that have no match, and `$distinct` collapses them, so both
30
30
  * totals have to be taken after the stage that does it - which only the read pipeline builds. Every
31
31
  * other query counts through {@link internalCount}, which needs no pipeline of its own.
32
32
  */
33
- protected internalFindManyAndCount<E extends Document>(entity: Type<E>, q: Query<E>, opts?: QueryOptions): Promise<[E[], number]>;
33
+ protected internalFindManyAndCount<E extends Document>(entity: Type<E>, q: Query<E>, opts?: StatementOptions): Promise<[E[], number]>;
34
34
  /** The pipeline `countDocuments` runs, spelled out so a relation condition gets its lookups and a page its stages. */
35
- protected internalCount<E extends Document>(entity: Type<E>, q: QueryPage<E>, opts?: QueryOptions): Promise<number>;
35
+ protected internalCount<E extends Document>(entity: Type<E>, q: QueryPage<E>, opts?: StatementOptions): Promise<number>;
36
36
  /**
37
37
  * The collection's metadata count, which the driver exposes as its own call and which takes no
38
38
  * filter - the reason {@link UniversalQuerier.estimatedCount} takes none either.
39
39
  */
40
40
  estimatedCount<E extends Document>(entity: Type<E>): Promise<number>;
41
41
  internalInsertMany<E extends Document>(entity: Type<E>, rows: EntityData<E>[]): Promise<void>;
42
- internalUpdateMany<E extends Document>(entity: Type<E>, qm: QuerySearch<E>, payload: UpdatePayload<E>, opts?: QueryOptions): Promise<number>;
42
+ internalUpdateMany<E extends Document>(entity: Type<E>, qm: QuerySearch<E>, payload: UpdatePayload<E>, opts?: StatementOptions): Promise<number>;
43
43
  /** The filter and update of an update of the documents matching `where` with `payload`, its `onUpdate` fills included. */
44
44
  private updateOperation;
45
45
  /**
@@ -49,7 +49,7 @@ export declare class MongodbQuerier extends AbstractQuerier implements MongoQuer
49
49
  */
50
50
  private upsertUpdate;
51
51
  protected internalUpsertMany<E extends Document>(entity: Type<E>, q: QueryUpsert<E>, payload: E[]): Promise<(UpsertedId<E> | undefined)[]>;
52
- protected internalDeleteMany<E extends Document>(entity: Type<E>, qm: QuerySearch<E>, opts?: QueryOptions): Promise<number>;
52
+ protected internalDeleteMany<E extends Document>(entity: Type<E>, qm: QuerySearch<E>, opts?: StatementOptions): Promise<number>;
53
53
  get hasOpenTransaction(): boolean;
54
54
  /** Every read and write goes through here, which makes it where a released querier is caught. */
55
55
  collection<E extends Document>(entity: Type<E>): import("mongodb").Collection<E>;
@@ -4,10 +4,10 @@ import type { UqlContext } from '../type/index.js';
4
4
  /**
5
5
  * Runs each request inside `withContext`, so parameterized/`security` filters (multi-tenancy, RLS)
6
6
  * are scoped automatically for every query in the request - including relations, cascades, and the
7
- * queries a transaction runs. Wired for you by {@link UqlModule.forRoot} when you pass `getContext`.
7
+ * queries a transaction runs. Wired for you by {@link UqlModule.forRoot} when you pass `contextOf`.
8
8
  */
9
9
  export declare class UqlContextInterceptor<Req = unknown> implements NestInterceptor {
10
- private readonly getContext;
11
- constructor(getContext: (request: Req) => UqlContext | undefined);
10
+ private readonly contextOf;
11
+ constructor(contextOf: (request: Req) => UqlContext | undefined | Promise<UqlContext | undefined>);
12
12
  intercept(execContext: ExecutionContext, next: CallHandler): Observable<unknown>;
13
13
  }
@@ -33,12 +33,12 @@ var __runInitializers = (this && this.__runInitializers) || function (thisArg, i
33
33
  return useValue ? value : void 0;
34
34
  };
35
35
  import { Injectable } from '@nestjs/common';
36
- import { Observable } from 'rxjs';
36
+ import { from, Observable, switchMap } from 'rxjs';
37
37
  import { withContext } from '../context/context.js';
38
38
  /**
39
39
  * Runs each request inside `withContext`, so parameterized/`security` filters (multi-tenancy, RLS)
40
40
  * are scoped automatically for every query in the request - including relations, cascades, and the
41
- * queries a transaction runs. Wired for you by {@link UqlModule.forRoot} when you pass `getContext`.
41
+ * queries a transaction runs. Wired for you by {@link UqlModule.forRoot} when you pass `contextOf`.
42
42
  */
43
43
  let UqlContextInterceptor = (() => {
44
44
  let _classDecorators = [Injectable()];
@@ -54,14 +54,14 @@ let UqlContextInterceptor = (() => {
54
54
  if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
55
55
  __runInitializers(_classThis, _classExtraInitializers);
56
56
  }
57
- getContext;
58
- constructor(getContext) {
59
- this.getContext = getContext;
57
+ contextOf;
58
+ constructor(contextOf) {
59
+ this.contextOf = contextOf;
60
60
  }
61
61
  intercept(execContext, next) {
62
- const context = this.getContext(execContext.switchToHttp().getRequest()) ?? {};
62
+ return from(Promise.resolve(this.contextOf(execContext.switchToHttp().getRequest()))).pipe(
63
63
  // Subscribe inside the context so the handler's async chain (and its queries) inherit it.
64
- return new Observable((subscriber) => withContext(context, () => next.handle().subscribe(subscriber)));
64
+ switchMap((context) => new Observable((subscriber) => withContext(context ?? {}, () => next.handle().subscribe(subscriber)))));
65
65
  }
66
66
  };
67
67
  return UqlContextInterceptor = _classThis;
@@ -1,11 +1,6 @@
1
1
  import { type DynamicModule, type FactoryProvider } from '@nestjs/common';
2
2
  import type { QuerierPool, UqlContext } from '../type/index.js';
3
- /**
4
- * Injection token for the configured {@link QuerierPool} - for injecting into your own
5
- * providers. UQL's own machinery (`getQuerier`, `querierMiddleware`, `createFetchHandler`) reads
6
- * the default pool set by {@link UqlModule.forRoot}, not this token, so overriding the provider
7
- * does not redirect UQL internals.
8
- */
3
+ /** Injection token for the configured {@link QuerierPool}: for your own providers, and the `pool` of a `createApi`. */
9
4
  export declare const UQL_QUERIER_POOL: unique symbol;
10
5
  /** Shared by {@link UqlModuleOptions} and {@link UqlModuleAsyncOptions}. */
11
6
  type UqlModuleCommon<Req> = {
@@ -17,7 +12,7 @@ type UqlModuleCommon<Req> = {
17
12
  * `security` filters (multi-tenancy, RLS) are scoped automatically. Derive tenant/auth from a
18
13
  * verified source (session, JWT) - never trust the client.
19
14
  */
20
- readonly getContext?: (request: Req) => UqlContext | undefined;
15
+ readonly contextOf?: (request: Req) => UqlContext | undefined | Promise<UqlContext | undefined>;
21
16
  };
22
17
  export type UqlModuleOptions<Req = unknown> = UqlModuleCommon<Req> & {
23
18
  readonly pool: QuerierPool;
@@ -33,14 +28,13 @@ export type UqlModuleAsyncOptions<Req = unknown> = UqlModuleCommon<Req> & {
33
28
  /**
34
29
  * NestJS integration: provides the pool via DI under {@link UQL_QUERIER_POOL}, optionally scopes
35
30
  * every request to a {@link UqlContext} (multi-tenancy), and ends the pool on application shutdown.
36
- * Inject the pool where you need it, `querierMiddleware`/`createFetchHandler` included: those take
37
- * it as an option rather than reading a process-wide default.
31
+ * Inject the pool where you need it, a `createApi` included, which takes it as an option.
38
32
  */
39
33
  export declare class UqlModule {
40
34
  /** Configure with an already-built pool. */
41
- static forRoot<Req = unknown>({ pool, global, getContext }: UqlModuleOptions<Req>): DynamicModule;
35
+ static forRoot<Req = unknown>({ pool, global, contextOf }: UqlModuleOptions<Req>): DynamicModule;
42
36
  /** Configure with a pool built asynchronously from injected providers (e.g. `ConfigService`). */
43
- static forRootAsync<Req = unknown>({ imports, useFactory, inject, global, getContext, }: UqlModuleAsyncOptions<Req>): DynamicModule;
37
+ static forRootAsync<Req = unknown>({ imports, useFactory, inject, global, contextOf, }: UqlModuleAsyncOptions<Req>): DynamicModule;
44
38
  private static build;
45
39
  }
46
40
  export {};
@@ -35,12 +35,7 @@ var __runInitializers = (this && this.__runInitializers) || function (thisArg, i
35
35
  import { Module, } from '@nestjs/common';
36
36
  import { APP_INTERCEPTOR } from '@nestjs/core';
37
37
  import { UqlContextInterceptor } from './uqlContextInterceptor.js';
38
- /**
39
- * Injection token for the configured {@link QuerierPool} - for injecting into your own
40
- * providers. UQL's own machinery (`getQuerier`, `querierMiddleware`, `createFetchHandler`) reads
41
- * the default pool set by {@link UqlModule.forRoot}, not this token, so overriding the provider
42
- * does not redirect UQL internals.
43
- */
38
+ /** Injection token for the configured {@link QuerierPool}: for your own providers, and the `pool` of a `createApi`. */
44
39
  export const UQL_QUERIER_POOL = Symbol('UQL_QUERIER_POOL');
45
40
  /**
46
41
  * Ends the pool this module was configured with when Nest shuts down: a provider built by `useFactory`,
@@ -58,9 +53,9 @@ class UqlPoolLifecycle {
58
53
  /**
59
54
  * NestJS integration: provides the pool via DI under {@link UQL_QUERIER_POOL}, optionally scopes
60
55
  * every request to a {@link UqlContext} (multi-tenancy), and ends the pool on application shutdown.
61
- * Inject the pool where you need it, `querierMiddleware`/`createFetchHandler` included: those take
62
- * it as an option rather than reading a process-wide default.
56
+ * Inject the pool where you need it, a `createApi` included, which takes it as an option.
63
57
  */
58
+ // NestJS needs a decorated class as the module token; the shutdown hook lives on its own provider.
64
59
  let UqlModule = (() => {
65
60
  let _classDecorators = [Module({})];
66
61
  let _classDescriptor;
@@ -76,19 +71,19 @@ let UqlModule = (() => {
76
71
  __runInitializers(_classThis, _classExtraInitializers);
77
72
  }
78
73
  /** Configure with an already-built pool. */
79
- static forRoot({ pool, global = true, getContext }) {
80
- return UqlModule.build(global, { provide: UQL_QUERIER_POOL, useValue: pool }, getContext);
74
+ static forRoot({ pool, global = true, contextOf }) {
75
+ return UqlModule.build(global, { provide: UQL_QUERIER_POOL, useValue: pool }, contextOf);
81
76
  }
82
77
  /** Configure with a pool built asynchronously from injected providers (e.g. `ConfigService`). */
83
- static forRootAsync({ imports, useFactory, inject = [], global = true, getContext, }) {
78
+ static forRootAsync({ imports, useFactory, inject = [], global = true, contextOf, }) {
84
79
  const poolProvider = {
85
80
  provide: UQL_QUERIER_POOL,
86
81
  useFactory,
87
82
  inject,
88
83
  };
89
- return UqlModule.build(global, poolProvider, getContext, imports);
84
+ return UqlModule.build(global, poolProvider, contextOf, imports);
90
85
  }
91
- static build(global, poolProvider, getContext, imports) {
86
+ static build(global, poolProvider, contextOf, imports) {
92
87
  const providers = [
93
88
  poolProvider,
94
89
  {
@@ -97,9 +92,9 @@ let UqlModule = (() => {
97
92
  inject: [UQL_QUERIER_POOL],
98
93
  },
99
94
  ];
100
- if (getContext) {
95
+ if (contextOf) {
101
96
  // Scope every request to its context so multi-tenancy / security filters apply automatically.
102
- providers.push({ provide: APP_INTERCEPTOR, useValue: new UqlContextInterceptor(getContext) });
97
+ providers.push({ provide: APP_INTERCEPTOR, useValue: new UqlContextInterceptor(contextOf) });
103
98
  }
104
99
  return { module: UqlModule, global, imports, providers, exports: [UQL_QUERIER_POOL] };
105
100
  }
@@ -1,13 +1,13 @@
1
1
  import type { AbstractDialect } from '../dialect/abstractDialect.js';
2
- import type { BooleanLike, CursorPage, Captured, EntityData, EntityId, EntityWrite, EntityMeta, ExtraOptions, FieldKey, Querier, Query, QueryAggregate, QueryAggregateResult, QueryConflictKeys, QueryUpsert, QueryFilter, QueryFindResult, QueryKeyset, QueryOne, QueryOptions, QueryPage, QuerySearch, SavepointCommand, TransactionOptions, Type, UpdatePayload, UpdateWrite, WriteResults, WriteOptions, PrimaryKey, WrittenId, RawRow, ReportedWrite } from '../type/index.js';
2
+ import type { BooleanLike, CursorPage, Captured, EntityData, EntityId, EntityWrite, EntityMeta, ExtraOptions, FieldKey, Querier, Query, QueryAggregate, QueryAggregateResult, QueryConflictKeys, QueryUpsert, QueryFilter, QueryFindResult, QueryKeyset, QueryOne, QueryOptions, StatementOptions, QueryPage, QuerySearch, SavepointCommand, TransactionOptions, Type, UpdatePayload, UpdateWrite, WriteResults, WriteOptions, PrimaryKey, WrittenId, RawRow, ReportedWrite } from '../type/index.js';
3
3
  import { LoggerWrapper } from '../util/index.js';
4
4
  import { type TransactionScope } from './transaction.js';
5
5
  /** What an upsert reports of a row: the value a driver answers for a lone key, or the key the read back names. */
6
6
  export type UpsertedId<E> = PrimaryKey | WrittenId<E>;
7
7
  /** Each write as one statement reporting the rows it wrote with the fields `keys` names. */
8
8
  export type ReportingWrites = {
9
- update<E extends object>(entity: Type<E>, q: QuerySearch<E>, payload: UpdatePayload<E>, opts: QueryOptions, keys: readonly FieldKey<E>[]): Promise<E[]>;
10
- delete<E extends object>(entity: Type<E>, q: QuerySearch<E>, opts: QueryOptions, keys: readonly FieldKey<E>[]): Promise<E[]>;
9
+ update<E extends object>(entity: Type<E>, q: QuerySearch<E>, payload: UpdatePayload<E>, opts: StatementOptions, keys: readonly FieldKey<E>[]): Promise<E[]>;
10
+ delete<E extends object>(entity: Type<E>, q: QuerySearch<E>, opts: StatementOptions, keys: readonly FieldKey<E>[]): Promise<E[]>;
11
11
  /** Inserts `rows`, reporting each in their order and placing its key on it, as `internalInsertMany` does. */
12
12
  insert<E extends object>(entity: Type<E>, rows: EntityData<E>[], keys: readonly FieldKey<E>[]): Promise<E[]>;
13
13
  /** The rows of `payload` the upsert writes, in its order, `undefined` for one it kept. */
@@ -56,7 +56,7 @@ export declare abstract class AbstractQuerier implements Querier {
56
56
  * The rows matching `q`, each populated relation and `$count` read with them in the same statement
57
57
  * or pipeline. [The design](../../../../architecture/relations-in-one-statement.md).
58
58
  */
59
- protected abstract internalFindMany<E extends object>(entity: Type<E>, q: Query<E>, opts?: QueryOptions): Promise<E[]>;
59
+ protected abstract internalFindMany<E extends object>(entity: Type<E>, q: Query<E>, opts?: StatementOptions): Promise<E[]>;
60
60
  /**
61
61
  * Stream records with the relations and counts `findMany` reads, the entity passed first or as `$entity`.
62
62
  * `afterLoad` runs on each row as it arrives, and the querier runs nothing else until the loop ends.
@@ -73,7 +73,7 @@ export declare abstract class AbstractQuerier implements Querier {
73
73
  * which a loop awaiting it never finishes, so `serialize` refuses one meanwhile, and `release` closes the stream.
74
74
  */
75
75
  private holdWhileReading;
76
- protected abstract internalFindManyStream<E extends object>(entity: Type<E>, q: Query<E>, opts?: QueryOptions): AsyncIterable<E>;
76
+ protected abstract internalFindManyStream<E extends object>(entity: Type<E>, q: Query<E>, opts?: StatementOptions): AsyncIterable<E>;
77
77
  /** Find many records and count every match, the entity passed first or as the query's `$entity`. */
78
78
  findManyAndCount<E extends object, const Q extends Query<E> & {
79
79
  $entity: Type<E>;
@@ -85,7 +85,7 @@ export declare abstract class AbstractQuerier implements Querier {
85
85
  * The page and how many rows the filter matched beyond it. Two statements here, which is what a
86
86
  * backend with no way to answer both at once is left with; SQL overrides it to answer from one.
87
87
  */
88
- protected internalFindManyAndCount<E extends object>(entity: Type<E>, q: Query<E>, opts?: QueryOptions): Promise<[E[], number]>;
88
+ protected internalFindManyAndCount<E extends object>(entity: Type<E>, q: Query<E>, opts?: StatementOptions): Promise<[E[], number]>;
89
89
  /** Read a page of records from a cursor, the entity passed first or as the query's `$entity`. */
90
90
  findManyPage<E extends object, const Q extends QueryKeyset<E> & {
91
91
  $entity: Type<E>;
@@ -213,7 +213,7 @@ export declare abstract class AbstractQuerier implements Querier {
213
213
  /** How the engine writes rows of `meta` and reports them in one statement, or `undefined` where `write` reads them. */
214
214
  protected reportingWrites<E>(_meta: EntityMeta<E>, _write: ReportedWrite): ReportingWrites | undefined;
215
215
  /** Runs one UPDATE over `q`, which names its rows by id wherever {@link updateMany} settled them. */
216
- protected abstract internalUpdateMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, payload: UpdatePayload<E>, opts?: QueryOptions): Promise<number>;
216
+ protected abstract internalUpdateMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, payload: UpdatePayload<E>, opts?: StatementOptions): Promise<number>;
217
217
  restoreOneById<E extends object>(entity: Type<E>, id: EntityId<E>): Promise<number>;
218
218
  restoreMany<E extends object>(q: QuerySearch<E> & {
219
219
  $entity: Type<E>;
@@ -268,7 +268,7 @@ export declare abstract class AbstractQuerier implements Querier {
268
268
  /** Deletes the rows `q` matches, or the ones `read` holds, reading them first where a hook, cascade or page needs them. */
269
269
  private deleteRows;
270
270
  /** Runs one DELETE (or soft-delete stamp) over `q`, which names its rows by id wherever {@link deleteMany} settled them. */
271
- protected abstract internalDeleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, opts?: QueryOptions): Promise<number>;
271
+ protected abstract internalDeleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, opts?: StatementOptions): Promise<number>;
272
272
  saveOne<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, payload: EntityWrite<E>, opts?: WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['inserted']>;
273
273
  saveMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, payload: readonly EntityWrite<E>[], opts?: WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['inserted'][]>;
274
274
  /**
@@ -81,7 +81,7 @@ function writtenIds(meta, rows) {
81
81
  */
82
82
  function upsertsByReading(meta, q, rows) {
83
83
  return (meta.version !== undefined ||
84
- securityConditions(meta).length > 0 ||
84
+ securityConditions(meta, ['read', 'insert', 'update']).length > 0 ||
85
85
  writesRelations(meta, q.$update ? [...rows, q.$update] : rows));
86
86
  }
87
87
  /**
@@ -171,6 +171,11 @@ async function runCallbacks(callbacks) {
171
171
  await callback();
172
172
  }
173
173
  }
174
+ /**
175
+ * What an upsert or a restore reads and updates rows with: soft-deleted ones too, since a key holds across both, held
176
+ * to the `security` filters an update is.
177
+ */
178
+ const UPDATING_DELETED = { ...withDeleted(), access: 'update' };
174
179
  const STREAM_HOLDS_QUERIER = 'a stream is reading on this querier: run the statement after its loop, or on another querier';
175
180
  /** Base class for all database queriers. */
176
181
  export class AbstractQuerier {
@@ -439,10 +444,11 @@ export class AbstractQuerier {
439
444
  async updateWhere(entity, q, payload, opts) {
440
445
  assertNamesRows(entity, 'updateMany', q, opts);
441
446
  const meta = getMeta(entity);
442
- const { returning, ...rest } = opts ?? {};
447
+ const { returning, ...given } = opts ?? {};
448
+ const rest = { ...given, access: 'update' };
443
449
  const keys = returnedKeys(meta, returning);
444
450
  if (!keys) {
445
- return this.updateMatching(entity, q, payload, opts);
451
+ return this.updateMatching(entity, q, payload, rest);
446
452
  }
447
453
  const reportingWrites = this.reportingWrites(meta, 'update');
448
454
  const reporting = (row) => reportingWrites && this.updatesByFilter(entity, q, row) ? reportingWrites : undefined;
@@ -600,7 +606,7 @@ export class AbstractQuerier {
600
606
  const $where = whereWith(meta.softDelete, { $ne: null }, q.$where);
601
607
  // No version: a restore only undoes the stamp a delete left, which takes none either, and two of
602
608
  // them racing agree on the result anyway. A lock is for content, and a restore writes none.
603
- return this.hooked(entity, 'Update', [{ [meta.softDelete]: null }], ([row]) => this.updateRows(entity, { ...q, $where }, row, withDeleted(), undefined));
609
+ return this.hooked(entity, 'Update', [{ [meta.softDelete]: null }], ([row]) => this.updateRows(entity, { ...q, $where }, row, UPDATING_DELETED, undefined));
604
610
  }
605
611
  async upsertOne(...args) {
606
612
  const [entity, q, payload, opts] = payloadArgs(args);
@@ -677,7 +683,7 @@ export class AbstractQuerier {
677
683
  const assigned = foundRowAssigned(meta, q, row);
678
684
  if (assigned) {
679
685
  const $where = q.$where ? whereAnd(whereIds(meta, id), [q.$where]) : whereIds(meta, id);
680
- await this.updateRows(entity, { $where }, assigned, withDeleted(), meta.version).catch((error) => {
686
+ await this.updateRows(entity, { $where }, assigned, UPDATING_DELETED, meta.version).catch((error) => {
681
687
  // Still at its version, so its `$where` excluded it: kept, as an unversioned row is.
682
688
  if (q.$where && error instanceof UqlOptimisticLockError && error.actual === error.expected) {
683
689
  return 0;
@@ -707,10 +713,11 @@ export class AbstractQuerier {
707
713
  async deleteWhere(entity, q, opts) {
708
714
  assertNamesRows(entity, 'deleteMany', q, opts);
709
715
  const meta = getMeta(entity);
710
- const { returning, ...rest } = opts ?? {};
716
+ const { returning, ...given } = opts ?? {};
717
+ const rest = { ...given, access: 'delete' };
711
718
  const keys = returnedKeys(meta, returning);
712
719
  if (!keys) {
713
- return this.deleteRows(entity, q, opts);
720
+ return this.deleteRows(entity, q, rest);
714
721
  }
715
722
  const read = [...keys, ...meta.ids];
716
723
  // A soft delete stamps the rows, which a `RETURNING` would report stamped rather than as they were.
@@ -1126,7 +1133,7 @@ export class AbstractQuerier {
1126
1133
  const distinct = [...new Map(named.map((row) => [rowKey(row, keys), row])).values()];
1127
1134
  const byConflict = new Map();
1128
1135
  for (const q of this.keyedReads(keys, distinct, [...new Set([...select, ...keys])])) {
1129
- for (const row of await this.readForWrite(entity, q, withDeleted())) {
1136
+ for (const row of await this.readForWrite(entity, q, UPDATING_DELETED)) {
1130
1137
  const key = rowKey(row, keys);
1131
1138
  byConflict.set(key, byConflict.has(key) ? undefined : row);
1132
1139
  }
@@ -1,5 +1,5 @@
1
1
  import type { AbstractSqlDialect } from '../dialect/index.js';
2
- import type { EntityData, EntityMeta, ExtraOptions, Query, QueryAggregate, QueryUpsert, QueryPage, QueryOptions, QuerySearch, QueryUpdateResult, RawRow, SavepointCommand, SqlQuerier, SqlStatement, Type, TransactionOptions, UpdatePayload, ReportedWrite } from '../type/index.js';
2
+ import type { EntityData, EntityMeta, ExtraOptions, Query, QueryAggregate, QueryUpsert, QueryPage, StatementOptions, QuerySearch, QueryUpdateResult, RawRow, SavepointCommand, SqlQuerier, SqlStatement, Type, TransactionOptions, UpdatePayload, ReportedWrite } from '../type/index.js';
3
3
  import type { SqlExecution } from '../util/sql.util.js';
4
4
  import { AbstractQuerier, type UpsertedId, type ReportingWrites } from './abstractQuerier.js';
5
5
  /** A statement as it is sent: its SQL and the values it binds. */
@@ -60,7 +60,7 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
60
60
  private vectorTuning;
61
61
  /** Whether `tuning` applies only inside a transaction, as a `SET LOCAL` does: a read opens one, or joins the open one. */
62
62
  private tunedInTransaction;
63
- protected internalFindMany<E extends object>(entity: Type<E>, q: Query<E>, opts?: QueryOptions): Promise<E[]>;
63
+ protected internalFindMany<E extends object>(entity: Type<E>, q: Query<E>, opts?: StatementOptions): Promise<E[]>;
64
64
  /** Every row `q` matches past its page, deduplicated where it reads `$distinct`. */
65
65
  private countUnpaged;
66
66
  /**
@@ -68,7 +68,7 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
68
68
  * an empty page. A window counts before `DISTINCT`, and the Postgres family refuses one beside a `$lock`,
69
69
  * so those count apart.
70
70
  */
71
- protected internalFindManyAndCount<E extends object>(entity: Type<E>, q: Query<E>, opts?: QueryOptions): Promise<[E[], number]>;
71
+ protected internalFindManyAndCount<E extends object>(entity: Type<E>, q: Query<E>, opts?: StatementOptions): Promise<[E[], number]>;
72
72
  /**
73
73
  * The rows a read of `entity` matches, each as its statement reads it, the vector search's tuning leading it, in a
74
74
  * transaction of its own where the tuning needs one and none is open.
@@ -86,7 +86,7 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
86
86
  * and connects on its own, its values going as the context holds them, each normalized as it was bound. Tuning
87
87
  * that needs a transaction is refused outside one, which would otherwise stay open for the whole loop.
88
88
  */
89
- protected internalFindManyStream<E extends object>(entity: Type<E>, q: Query<E>, opts?: QueryOptions): AsyncGenerator<Awaited<E>, void, unknown>;
89
+ protected internalFindManyStream<E extends object>(entity: Type<E>, q: Query<E>, opts?: StatementOptions): AsyncGenerator<Awaited<E>, void, unknown>;
90
90
  /**
91
91
  * A read's rows one at a time: paged through a server-side cursor where the engine has one, read whole
92
92
  * where it has none. A driver that streams on its own overrides this; a Node `Readable` it hands back
@@ -99,9 +99,9 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
99
99
  * as 0; no row is 0 too, since a catalog that does not know the table answers with none.
100
100
  */
101
101
  private runCount;
102
- protected internalCount<E extends object>(entity: Type<E>, q: QueryPage<E>, opts?: QueryOptions): Promise<number>;
102
+ protected internalCount<E extends object>(entity: Type<E>, q: QueryPage<E>, opts?: StatementOptions): Promise<number>;
103
103
  estimatedCount<E extends object>(entity: Type<E>): Promise<number>;
104
- protected internalAggregate<E extends object>(entity: Type<E>, q: QueryAggregate<E>, opts?: QueryOptions): Promise<RawRow[]>;
104
+ protected internalAggregate<E extends object>(entity: Type<E>, q: QueryAggregate<E>, opts?: StatementOptions): Promise<RawRow[]>;
105
105
  internalInsertMany<E extends object>(entity: Type<E>, rows: EntityData<E>[]): Promise<void>;
106
106
  /**
107
107
  * Settles the key of each row leaving it out, unless the database generates it. With no default nothing fills it, so
@@ -119,7 +119,7 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
119
119
  private insertChunks;
120
120
  /** Inserts `rows`, reporting each, in their order, with the fields `keys` names, off its own `RETURNING`, and placing its key on it. */
121
121
  private insertedRows;
122
- internalUpdateMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, payload: UpdatePayload<E>, opts?: QueryOptions): Promise<number>;
122
+ internalUpdateMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, payload: UpdatePayload<E>, opts?: StatementOptions): Promise<number>;
123
123
  /** The writes reading their rows off their own statement, where {@link AbstractSqlDialect.reportsWrite} says so. */
124
124
  protected reportingWrites<E>(meta: EntityMeta<E>, write: ReportedWrite): ReportingWrites | undefined;
125
125
  /**
@@ -143,7 +143,7 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
143
143
  * statement's header names its row's id, which spares the read back.
144
144
  */
145
145
  private upsertGroups;
146
- protected internalDeleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, opts?: QueryOptions): Promise<number>;
146
+ protected internalDeleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, opts?: StatementOptions): Promise<number>;
147
147
  protected openTransaction(opts?: TransactionOptions): Promise<void>;
148
148
  /**
149
149
  * A `COMMIT` that fails can leave the transaction open (SQLite answers `SQLITE_BUSY` and keeps it), so the
@@ -17,3 +17,18 @@ export type KeysetRead<E> = {
17
17
  * another page follows. `nullsSortLowest` says where the engine sorts nulls, for keys with no placement.
18
18
  */
19
19
  export declare function keysetRead<E extends object>(meta: EntityMeta<E>, q: QueryKeyset<E>, nullsSortLowest: boolean): KeysetRead<E>;
20
+ /** The clauses {@link assertPageable} reads, which any query has: a client's names none it must. */
21
+ type PageClauses = {
22
+ readonly $limit?: number;
23
+ readonly $after?: string;
24
+ readonly $before?: string;
25
+ readonly $distinct?: unknown;
26
+ };
27
+ /**
28
+ * Refuses a page query with `$skip`, both cursors, `$distinct`, or a `$limit` that is not a positive integer, each
29
+ * refusal naming the clause at fault: what a page needs, for the API to check a client's query by.
30
+ */
31
+ export declare function assertPageable<E, Q extends PageClauses>(meta: EntityMeta<E>, q: Q): asserts q is Q & {
32
+ readonly $limit: number;
33
+ };
34
+ export {};
@@ -54,28 +54,31 @@ export function keysetRead(meta, q, nullsSortLowest) {
54
54
  };
55
55
  return { query, page };
56
56
  }
57
- /** Refuses a page query with `$skip`, both cursors, `$distinct`, or a `$limit` that is not a positive integer. */
58
- function assertPageable(meta, q) {
59
- const refuse = (why) => new UqlUsageError(`a page of '${entityName(meta)}' ${why}`);
57
+ /**
58
+ * Refuses a page query with `$skip`, both cursors, `$distinct`, or a `$limit` that is not a positive integer, each
59
+ * refusal naming the clause at fault: what a page needs, for the API to check a client's query by.
60
+ */
61
+ export function assertPageable(meta, q) {
62
+ const refuse = (why, clause) => new UqlUsageError(`a page of '${entityName(meta)}' ${why}`, { path: [clause] });
60
63
  // The type forbids `$skip`, but untyped input from `/http` can still carry one.
61
64
  if ('$skip' in q && q.$skip !== undefined) {
62
- throw refuse('takes no $skip: an offset reintroduces the drift a cursor removes');
65
+ throw refuse('takes no $skip: an offset reintroduces the drift a cursor removes', '$skip');
63
66
  }
64
67
  if (q.$after !== undefined && q.$before !== undefined) {
65
- throw refuse('reads past one cursor, $after or $before, not both');
68
+ throw refuse('reads past one cursor, $after or $before, not both', '$before');
66
69
  }
67
70
  if (q.$distinct) {
68
- throw refuse('takes no $distinct: its rows are a grouping, which the cursor compares no column of');
71
+ throw refuse('takes no $distinct: its rows are a grouping, which the cursor compares no column of', '$distinct');
69
72
  }
70
- if (!Number.isInteger(q.$limit) || q.$limit < 1) {
71
- throw refuse(`holds a positive whole number of rows, and $limit is ${q.$limit}`);
73
+ if (q.$limit === undefined || !Number.isInteger(q.$limit) || q.$limit < 1) {
74
+ throw refuse(`holds a positive whole number of rows, and $limit is ${q.$limit}`, '$limit');
72
75
  }
73
76
  }
74
77
  /** Resolves each key of the page's `$sort`, refusing one without a stored value a cursor can compare. */
75
78
  function pageOrder(meta, q, nullsSortLowest) {
76
79
  const sort = q.$sort ?? {};
77
80
  return getKeys(sort).map((key) => {
78
- const refuse = (why) => new UqlUsageError(`cannot page '${entityName(meta)}' by '${key}': ${why}`);
81
+ const refuse = (why) => new UqlUsageError(`cannot page '${entityName(meta)}' by '${key}': ${why}`, { path: ['$sort', key] });
79
82
  if (key === '$text') {
80
83
  throw refuse('a relevance is scored per row, not stored on it');
81
84
  }
@@ -130,7 +133,7 @@ function totalPrefix(meta, order) {
130
133
  }
131
134
  }
132
135
  throw new UqlUsageError(`a page of '${entityName(meta)}' sorts by ${order.map(({ key }) => key).join(', ') || 'nothing'}, which two rows ` +
133
- `can share: add ${meta.ids.length ? `'${meta.ids.join("', '")}' or ` : ''}a unique, non-null field to the end of $sort`);
136
+ `can share: add ${meta.ids.length ? `'${meta.ids.join("', '")}' or ` : ''}a unique, non-null field to the end of $sort`, { path: ['$sort'] });
134
137
  }
135
138
  /** The key in the opposite direction, nulls included, which `$before` reads so its extra row comes first. */
136
139
  function inverted(key) {
@@ -188,7 +191,9 @@ function anyOf(alternatives) {
188
191
  */
189
192
  function projectedKeys(meta, q) {
190
193
  if (isSelectList(q.$select)) {
191
- throw new UqlUsageError(`a page of '${entityName(meta)}' selects fields, which its cursor is read off`);
194
+ throw new UqlUsageError(`a page of '${entityName(meta)}' selects fields, which its cursor is read off`, {
195
+ path: ['$select'],
196
+ });
192
197
  }
193
198
  return normalizeScalarFieldSelection(meta, q.$select);
194
199
  }