uql-orm 0.112.0 → 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 (96) 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/dialect/abstractSqlDialect.js +3 -3
  19. package/dist/dialect/jsonSql.js +2 -3
  20. package/dist/dialect/operators.js +4 -5
  21. package/dist/express/index.d.ts +1 -1
  22. package/dist/express/index.js +1 -1
  23. package/dist/express/router.d.ts +8 -0
  24. package/dist/express/router.js +50 -0
  25. package/dist/http/api.d.ts +36 -0
  26. package/dist/http/api.js +136 -0
  27. package/dist/http/apiCall.d.ts +59 -0
  28. package/dist/http/apiCall.js +52 -0
  29. package/dist/http/errors.d.ts +20 -0
  30. package/dist/http/errors.js +27 -0
  31. package/dist/http/exposure.d.ts +54 -0
  32. package/dist/http/exposure.js +171 -0
  33. package/dist/http/handler.d.ts +23 -88
  34. package/dist/http/handler.js +42 -155
  35. package/dist/http/index.d.ts +8 -4
  36. package/dist/http/index.js +6 -3
  37. package/dist/http/route.d.ts +34 -0
  38. package/dist/http/route.js +82 -0
  39. package/dist/http/wireCall.d.ts +115 -0
  40. package/dist/http/wireCall.js +126 -0
  41. package/dist/http/wireQuery.d.ts +8 -0
  42. package/dist/http/wireQuery.js +51 -0
  43. package/dist/http/wireRow.d.ts +20 -0
  44. package/dist/http/wireRow.js +170 -0
  45. package/dist/index.d.ts +1 -1
  46. package/dist/index.js +1 -1
  47. package/dist/migrate/introspection/mysqlIntrospector.d.ts +4 -1
  48. package/dist/migrate/introspection/mysqlIntrospector.js +12 -2
  49. package/dist/mongodb/mongoDialect.d.ts +6 -6
  50. package/dist/mongodb/mongoDialect.js +6 -6
  51. package/dist/mongodb/mongodbQuerier.d.ts +8 -8
  52. package/dist/mssql/mssqlDialect.js +2 -2
  53. package/dist/nestjs/uqlContextInterceptor.d.ts +3 -3
  54. package/dist/nestjs/uqlContextInterceptor.js +7 -7
  55. package/dist/nestjs/uqlModule.d.ts +5 -11
  56. package/dist/nestjs/uqlModule.js +10 -15
  57. package/dist/querier/abstractQuerier.d.ts +8 -8
  58. package/dist/querier/abstractQuerier.js +15 -8
  59. package/dist/querier/abstractSqlQuerier.d.ts +8 -8
  60. package/dist/querier/keyset.d.ts +15 -0
  61. package/dist/querier/keyset.js +16 -11
  62. package/dist/sqlite/localSqliteQuerierPool.d.ts +1 -1
  63. package/dist/type/column.d.ts +4 -1
  64. package/dist/type/querier.d.ts +2 -2
  65. package/dist/type/query.d.ts +18 -4
  66. package/dist/type/universalQuerier.d.ts +16 -16
  67. package/dist/type/wire.d.ts +1 -31
  68. package/dist/util/dialect.util.d.ts +9 -16
  69. package/dist/util/dialect.util.js +20 -26
  70. package/dist/util/field.util.d.ts +4 -1
  71. package/dist/util/field.util.js +5 -2
  72. package/dist/util/object.util.d.ts +5 -2
  73. package/dist/util/object.util.js +12 -15
  74. package/dist/util/query.util.js +3 -10
  75. package/dist/util/uqlError.d.ts +27 -1
  76. package/dist/util/uqlError.js +43 -0
  77. package/package.json +5 -10
  78. package/skills/uql-orm/SKILL.md +4 -1
  79. package/dist/browser/http/bus.d.ts +0 -3
  80. package/dist/browser/http/bus.js +0 -12
  81. package/dist/browser/http/http.d.ts +0 -20
  82. package/dist/browser/http/http.js +0 -67
  83. package/dist/browser/querier/httpQuerier.d.ts +0 -46
  84. package/dist/browser/querier/httpQuerier.js +0 -64
  85. package/dist/browser/type/request.d.ts +0 -27
  86. package/dist/browser/uql-browser.min.js +0 -4
  87. package/dist/browser/uql-browser.min.js.map +0 -19
  88. package/dist/express/querierMiddleware.d.ts +0 -11
  89. package/dist/express/querierMiddleware.js +0 -39
  90. package/dist/http/contract.d.ts +0 -98
  91. package/dist/http/contract.js +0 -83
  92. package/dist/http/fetchHandler.d.ts +0 -13
  93. package/dist/http/fetchHandler.js +0 -63
  94. package/dist/http/query.d.ts +0 -28
  95. package/dist/http/query.js +0 -119
  96. /package/dist/browser/type/{request.js → transport.js} +0 -0
@@ -0,0 +1,20 @@
1
+ import type { EntityMeta } from '../type/index.js';
2
+ import type { WireAnswer } from './wireCall.js';
3
+ /** `data` as JSON is to carry it, by what its route `answers`; the client reads it back by {@link readWireData}. */
4
+ export declare function writeWireData<E>(meta: EntityMeta<E>, data: unknown, answers: WireAnswer): unknown;
5
+ /** `data` JSON carried, a response, read back as the entity holds it by what it `answers`. */
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;
9
+ /**
10
+ * `query` with each value it compares a field with read back as the entity holds it, its `$populate` and `$count`
11
+ * relations' included: JSON carried each date and `bigint` as text, which an engine would compare as text.
12
+ */
13
+ export declare function readWireQuery<E, Q extends RelationClauses>(meta: EntityMeta<E>, query: Q): Q;
14
+ /** The clauses of a query that compare or reach a relation's rows. */
15
+ type RelationClauses = {
16
+ readonly $where?: unknown;
17
+ readonly $populate?: object;
18
+ readonly $count?: object;
19
+ };
20
+ export {};
@@ -0,0 +1,170 @@
1
+ import { EQUALITY_OPS, isGroupOp, isOrderedOp } from '../dialect/operators.js';
2
+ import { getMeta, relationOf, valueFieldOf } from '../entity/metadata/definition.js';
3
+ import { decodeDate } from '../util/date.js';
4
+ import { aggregateOf, columnFamily } from '../util/field.util.js';
5
+ import { cachedIn, definedEntries, isPlainObject } from '../util/object.util.js';
6
+ /** What JSON cannot hold as the server holds it: a `bigint`, sent as its digits. */
7
+ const sent = (field) => (valueFieldOf(field).type === BigInt ? String : undefined);
8
+ /**
9
+ * What JSON carried as text: a `bigint`'s digits, and a date's ISO text. A time of day stays the text it is, and so
10
+ * does text no `bigint` spells, for the engine to refuse as it refuses any malformed value.
11
+ */
12
+ const received = (field) => {
13
+ const { type } = valueFieldOf(field);
14
+ if (type === BigInt) {
15
+ return (text) => {
16
+ try {
17
+ return BigInt(String(text));
18
+ }
19
+ catch {
20
+ return text;
21
+ }
22
+ };
23
+ }
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;
26
+ };
27
+ /** `data` as JSON is to carry it, by what its route `answers`; the client reads it back by {@link readWireData}. */
28
+ export function writeWireData(meta, data, answers) {
29
+ return across(meta, data, answers, SENDING);
30
+ }
31
+ /** `data` JSON carried, a response, read back as the entity holds it by what it `answers`. */
32
+ export function readWireData(meta, data, answers) {
33
+ return across(meta, data, answers, RECEIVING);
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
+ }
39
+ /**
40
+ * `query` with each value it compares a field with read back as the entity holds it, its `$populate` and `$count`
41
+ * relations' included: JSON carried each date and `bigint` as text, which an engine would compare as text.
42
+ */
43
+ export function readWireQuery(meta, query) {
44
+ const plan = planIn(RECEIVING, meta);
45
+ const related = (clause) => Object.fromEntries(Object.entries(clause).map(([key, nested]) => {
46
+ const target = plan.relations.get(key);
47
+ return [key, target && isPlainObject(nested) ? readWireQuery(target, nested) : nested];
48
+ }));
49
+ return {
50
+ ...query,
51
+ ...(query.$where !== undefined && { $where: whereOf(meta, query.$where) }),
52
+ ...(query.$populate !== undefined && { $populate: related(query.$populate) }),
53
+ ...(query.$count !== undefined && { $count: related(query.$count) }),
54
+ };
55
+ }
56
+ const SENDING = { field: sent, plans: new WeakMap() };
57
+ const RECEIVING = { field: received, plans: new WeakMap() };
58
+ function planIn(way, meta) {
59
+ return cachedIn(way.plans, meta, () => planOf(meta, way.field));
60
+ }
61
+ function across(meta, data, answers, way) {
62
+ switch (answers) {
63
+ case 'count':
64
+ return data;
65
+ case 'rows':
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
+ }
75
+ case 'page': {
76
+ if (!isPlainObject(data)) {
77
+ return data;
78
+ }
79
+ const items = convert(meta, data['items'], way);
80
+ return items === data['items'] ? data : { ...data, items };
81
+ }
82
+ case 'ids': {
83
+ const [idKey] = meta.ids;
84
+ const sole = meta.ids.length === 1 ? planIn(way, meta).fields.get(idKey) : undefined;
85
+ // A composite key is a row of its columns; a sole one its value.
86
+ const id = (key) => isPlainObject(key) ? convert(meta, key, way) : sole && key != null ? sole(key) : key;
87
+ return Array.isArray(data) ? data.map(id) : id(data);
88
+ }
89
+ }
90
+ }
91
+ function convert(meta, rows, way) {
92
+ if (Array.isArray(rows)) {
93
+ const converted = rows.map((row) => convert(meta, row, way));
94
+ return converted.every((row, index) => row === rows[index]) ? rows : converted;
95
+ }
96
+ if (!isPlainObject(rows)) {
97
+ return rows;
98
+ }
99
+ const plan = planIn(way, meta);
100
+ let row;
101
+ for (const [key, to] of plan.fields) {
102
+ const value = rows[key];
103
+ if (value != null) {
104
+ row ??= { ...rows };
105
+ // An update's operator, `{ $inc: 1 }`, holds the values it applies.
106
+ row[key] = isPlainObject(value)
107
+ ? Object.fromEntries(Object.entries(value).map(([op, operand]) => [op, to(operand)]))
108
+ : to(value);
109
+ }
110
+ }
111
+ for (const [key, target] of plan.relations) {
112
+ const read = convert(target, rows[key], way);
113
+ if (read !== rows[key]) {
114
+ row ??= { ...rows };
115
+ row[key] = read;
116
+ }
117
+ }
118
+ return row ?? rows;
119
+ }
120
+ function planOf(meta, convertField) {
121
+ return {
122
+ fields: new Map(definedEntries(meta.fields).flatMap(([key, field]) => {
123
+ const source = readField(meta, field);
124
+ const to = source && convertField(source);
125
+ return to ? [[key, to]] : [];
126
+ })),
127
+ relations: new Map(definedEntries(meta.relations).map(([key, relation]) => [key, getMeta(relation.entity())])),
128
+ };
129
+ }
130
+ /** A `$where` of `meta` with each value a field is compared with read back, through groups and relations. */
131
+ function whereOf(meta, where) {
132
+ if (Array.isArray(where)) {
133
+ return where.map((clause) => whereOf(meta, clause));
134
+ }
135
+ if (!isPlainObject(where)) {
136
+ return where;
137
+ }
138
+ const plan = planIn(RECEIVING, meta);
139
+ return Object.fromEntries(Object.entries(where).map(([key, value]) => {
140
+ const to = plan.fields.get(key);
141
+ if (to) {
142
+ return [key, compared(value, to)];
143
+ }
144
+ const target = plan.relations.get(key);
145
+ return [key, target ? whereOf(target, value) : isGroupOp(key) ? whereOf(meta, value) : value];
146
+ }));
147
+ }
148
+ /** A field's condition with each value it compares with read by `to`: a pattern or a null check stays as it is. */
149
+ function compared(condition, to) {
150
+ if (Array.isArray(condition)) {
151
+ return condition.map(to);
152
+ }
153
+ if (!isPlainObject(condition)) {
154
+ return condition == null ? condition : to(condition);
155
+ }
156
+ return Object.fromEntries(Object.entries(condition).map(([op, value]) => [
157
+ op,
158
+ op === '$not' || EQUALITY_OPS.has(op) || isOrderedOp(op) ? compared(value, to) : value,
159
+ ]));
160
+ }
161
+ /** The field a field's value reads as: a relation aggregate's, none for a tally or a mean, which read as numbers. */
162
+ function readField(meta, field) {
163
+ const spec = aggregateOf(field);
164
+ if (!spec) {
165
+ return field;
166
+ }
167
+ return spec.field && spec.op !== '$avg'
168
+ ? getMeta(relationOf(meta, spec.relation).entity()).fields[spec.field]
169
+ : undefined;
170
+ }
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';
@@ -46,7 +46,10 @@ export declare class MariadbSchemaIntrospector extends MysqlSchemaIntrospector {
46
46
  * JSON column's `json_valid()` is its type, read by {@link getColumns}, so it is left out.
47
47
  */
48
48
  protected getChecks(read: TableRowReader, tableName: string): Promise<CheckSchema[]>;
49
- /** MariaDB prints a literal quoted, as SQL reads it (`'it''s'`), so an unquoted default is SQL. */
49
+ /**
50
+ * MariaDB prints a literal quoted, as SQL reads it (`'it''s'`), so an unquoted default is SQL, a function it
51
+ * prints by an alias named as declared ({@link MARIADB_ALIASES}).
52
+ */
50
53
  protected sqlText(defaultValue: string): string | undefined;
51
54
  /** Whether an index is MariaDB's vector index, and the distance it was built for. */
52
55
  protected readonly indexFacets: ReadonlySet<IndexFacet>;
@@ -175,6 +175,10 @@ export class MysqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
175
175
  }
176
176
  }
177
177
  const TIMESTAMP_TYPES = new Set(['datetime', 'timestamp']);
178
+ /** The functions MariaDB prints by an alias, each with the name SQL declares it by. */
179
+ const MARIADB_ALIASES = { lcase: 'lower', ucase: 'upper' };
180
+ /** A quoted literal, kept as it is, or an alias called. */
181
+ const MARIADB_ALIAS = new RegExp(`'(?:[^']|'')*'|\\b(?:${Object.keys(MARIADB_ALIASES).join('|')})(?=\\()`, 'gi');
178
182
  /**
179
183
  * MariaDB reads out of the same `information_schema` as MySQL, save for one column type it does not
180
184
  * have: `JSON` there is an alias for `LONGTEXT` plus a `json_valid()` check constraint named after
@@ -196,9 +200,15 @@ export class MariadbSchemaIntrospector extends MysqlSchemaIntrospector {
196
200
  AND CHECK_CLAUSE <> CONCAT('json_valid(\`', CONSTRAINT_NAME, '\`)')
197
201
  `);
198
202
  }
199
- /** MariaDB prints a literal quoted, as SQL reads it (`'it''s'`), so an unquoted default is SQL. */
203
+ /**
204
+ * MariaDB prints a literal quoted, as SQL reads it (`'it''s'`), so an unquoted default is SQL, a function it
205
+ * prints by an alias named as declared ({@link MARIADB_ALIASES}).
206
+ */
200
207
  sqlText(defaultValue) {
201
- return defaultValue.startsWith("'") ? undefined : defaultValue;
208
+ if (defaultValue.startsWith("'")) {
209
+ return undefined;
210
+ }
211
+ return defaultValue.replace(MARIADB_ALIAS, (match) => MARIADB_ALIASES[match.toLowerCase()] ?? match);
202
212
  }
203
213
  /** Whether an index is MariaDB's vector index, and the distance it was built for. */
204
214
  indexFacets = new Set(['vector', 'distance']);
@@ -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
@@ -7,7 +7,7 @@ import { assertSoleId, fieldOf, getMeta, relationOf, soleIdOf } from '../entity/
7
7
  import { referenceKeys } from '../entity/metadata/definition.js';
8
8
  import { COUNT_RESULT_KEY } from '../type/query.js';
9
9
  import { ColumnRef, QuerySql, REF_ENTITY, REF_KEY } from '../type/querySql.js';
10
- import { aggregateOf, isSelectList, assertAggregateColumns, assertNoUndefined, assertNonNegativeInteger, columnFamily, countedRelations, entityName, fieldUpdateOf, fillOnFields, filterFieldKeys, findVectorIndex, findVectorSort, definedEntries, getKeys, holdsForeignKey, jsonPathKeys, getRelationRequestSummary, hasKeys, isFieldUpdateOp, isJsonObject, foldJson, writesKeys, isJsonUpdateOp, isOperatorMap, isOperatorObject, isRecord, isVectorSearch, normalizeScalarFieldSelection, parentJoins, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, rankedTextSearch, someKey, targetJoins, textSortOf, indexedDistance, vectorDistanceOf, vectorCandidates, populatesRelations, cachedIn, } from '../util/index.js';
10
+ import { aggregateOf, isSelectList, assertAggregateColumns, assertNoUndefined, assertNonNegativeInteger, columnFamily, countedRelations, entityName, fieldUpdateOf, fillOnFields, filterFieldKeys, findVectorIndex, findVectorSort, definedEntries, getKeys, holdsForeignKey, jsonPathKeys, getRelationRequestSummary, hasKeys, isFieldUpdateOp, isJsonObject, foldJson, writesKeys, isJsonUpdateOp, isPlainObject, isOperatorObject, isRecord, isVectorSearch, normalizeScalarFieldSelection, parentJoins, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, rankedTextSearch, someKey, targetJoins, textSortOf, indexedDistance, vectorDistanceOf, vectorCandidates, populatesRelations, cachedIn, } from '../util/index.js';
11
11
  import { UqlUsageError } from '../util/uqlError.js';
12
12
  import { decodeBigIntsExcept } from '../util/wideNumber.js';
13
13
  import { textLanguage } from './textLanguage.js';
@@ -470,7 +470,7 @@ export class MongoDialect extends AbstractDialect {
470
470
  }
471
471
  // An object or an array is matched by what it holds, as the SQL engines read it, where native `$all`
472
472
  // compares the whole element. MongoDB takes `$elemMatch` there only when every value is one.
473
- if (op === '$all' && Array.isArray(val) && val.some((value) => Array.isArray(value) || isOperatorMap(value))) {
473
+ if (op === '$all' && Array.isArray(val) && val.some((value) => Array.isArray(value) || isPlainObject(value))) {
474
474
  result[op] = this.allHolding(val);
475
475
  continue;
476
476
  }
@@ -515,7 +515,7 @@ export class MongoDialect extends AbstractDialect {
515
515
  if (Array.isArray(value)) {
516
516
  return this.transformOperators({ $all: value });
517
517
  }
518
- if (!isOperatorMap(value)) {
518
+ if (!isPlainObject(value)) {
519
519
  return value;
520
520
  }
521
521
  return isOperatorObject(value) ? this.transformOperators(value) : this.containment(value);
@@ -529,7 +529,7 @@ export class MongoDialect extends AbstractDialect {
529
529
  if (Array.isArray(value)) {
530
530
  return { $elemMatch: { $all: this.allHolding(value) } };
531
531
  }
532
- return { $elemMatch: isOperatorMap(value) ? this.held(value) : { $eq: value } };
532
+ return { $elemMatch: isPlainObject(value) ? this.held(value) : { $eq: value } };
533
533
  });
534
534
  }
535
535
  /** An object's keys as {@link held} reads each, a nested object's by its dotted path rather than whole. */
@@ -1504,7 +1504,7 @@ export class MongoDialect extends AbstractDialect {
1504
1504
  * by `$in`, which stops at the first match where testing each element would map them all.
1505
1505
  */
1506
1506
  allHeld(ref, values, read) {
1507
- return allOf(values.map((value) => isOperatorMap(value) || Array.isArray(value)
1507
+ return allOf(values.map((value) => isPlainObject(value) || Array.isArray(value)
1508
1508
  ? anyElement(ref, this.heldExpression('$$this', value, read))
1509
1509
  : { $cond: [{ $isArray: ref }, { $in: [read(value), ref] }, false] }));
1510
1510
  }
@@ -1515,7 +1515,7 @@ export class MongoDialect extends AbstractDialect {
1515
1515
  // Classified exactly as the SQL side classifies a `$where`/`$having` value, so the two agree
1516
1516
  // on identical input. Keeping only numbers and objects dropped a string or boolean without a
1517
1517
  // word, handing back every group instead of the filtered ones.
1518
- if (isOperatorMap(condition)) {
1518
+ if (isPlainObject(condition)) {
1519
1519
  filter[alias] = this.transformOperators(condition, 'unsupported HAVING operator');
1520
1520
  }
1521
1521
  else {
@@ -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>;
@@ -10,7 +10,7 @@ import { QuerySql } from '../type/index.js';
10
10
  import { parseQueryLock } from '../type/index.js';
11
11
  import { bytesToHex } from '../util/bytes.js';
12
12
  import { isExactDecimal, isInlinedExpression, jsonPathKeys } from '../util/field.util.js';
13
- import { assertNonNegativeInteger, definedEntries, isOperatorMap, keySet, RETURNED_ID } from '../util/index.js';
13
+ import { assertNonNegativeInteger, definedEntries, isPlainObject, keySet, RETURNED_ID } from '../util/index.js';
14
14
  import { escapeSingleQuotes } from '../util/sqlLiteral.js';
15
15
  import { UqlUsageError } from '../util/uqlError.js';
16
16
  /** What SQL Server has. */
@@ -59,7 +59,7 @@ function openJsonType(value) {
59
59
  if (Array.isArray(value)) {
60
60
  return OPENJSON_TYPE.array;
61
61
  }
62
- if (isOperatorMap(value)) {
62
+ if (isPlainObject(value)) {
63
63
  return OPENJSON_TYPE.object;
64
64
  }
65
65
  if (typeof value === 'number') {
@@ -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
  }