uql-orm 0.112.1 → 0.114.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 (90) hide show
  1. package/README.md +2 -2
  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/entity/columnOptionsBuilder.d.ts +2 -1
  19. package/dist/entity/columnOptionsBuilder.js +3 -0
  20. package/dist/entity/metadata/definition.js +3 -0
  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 +140 -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 +38 -0
  32. package/dist/http/exposure.js +157 -0
  33. package/dist/http/handler.d.ts +23 -88
  34. package/dist/http/handler.js +42 -158
  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 +4 -2
  44. package/dist/http/wireRow.js +15 -2
  45. package/dist/index.d.ts +1 -1
  46. package/dist/index.js +1 -1
  47. package/dist/migrate/codegen/entityCodeGenerator.js +2 -2
  48. package/dist/mongodb/mongoDialect.d.ts +6 -6
  49. package/dist/mongodb/mongodbQuerier.d.ts +8 -8
  50. package/dist/nestjs/uqlContextInterceptor.d.ts +3 -3
  51. package/dist/nestjs/uqlContextInterceptor.js +7 -7
  52. package/dist/nestjs/uqlModule.d.ts +5 -11
  53. package/dist/nestjs/uqlModule.js +10 -15
  54. package/dist/querier/abstractQuerier.d.ts +8 -8
  55. package/dist/querier/abstractQuerier.js +15 -8
  56. package/dist/querier/abstractSqlQuerier.d.ts +8 -8
  57. package/dist/querier/keyset.d.ts +15 -0
  58. package/dist/querier/keyset.js +16 -11
  59. package/dist/type/column.d.ts +9 -1
  60. package/dist/type/definedEntity.d.ts +3 -0
  61. package/dist/type/entity.d.ts +14 -4
  62. package/dist/type/querier.d.ts +2 -2
  63. package/dist/type/query.d.ts +24 -4
  64. package/dist/type/universalQuerier.d.ts +17 -18
  65. package/dist/type/wire.d.ts +1 -31
  66. package/dist/util/dialect.util.d.ts +10 -10
  67. package/dist/util/dialect.util.js +20 -12
  68. package/dist/util/field.util.d.ts +7 -1
  69. package/dist/util/field.util.js +9 -2
  70. package/dist/util/fieldOption.util.js +2 -0
  71. package/dist/util/uqlError.d.ts +27 -1
  72. package/dist/util/uqlError.js +43 -0
  73. package/package.json +1 -1
  74. package/skills/uql-orm/SKILL.md +32 -4
  75. package/dist/browser/http/bus.d.ts +0 -3
  76. package/dist/browser/http/bus.js +0 -12
  77. package/dist/browser/http/http.d.ts +0 -20
  78. package/dist/browser/http/http.js +0 -67
  79. package/dist/browser/querier/httpQuerier.d.ts +0 -46
  80. package/dist/browser/querier/httpQuerier.js +0 -70
  81. package/dist/browser/type/request.d.ts +0 -27
  82. package/dist/express/querierMiddleware.d.ts +0 -11
  83. package/dist/express/querierMiddleware.js +0 -39
  84. package/dist/http/contract.d.ts +0 -113
  85. package/dist/http/contract.js +0 -83
  86. package/dist/http/fetchHandler.d.ts +0 -13
  87. package/dist/http/fetchHandler.js +0 -63
  88. package/dist/http/query.d.ts +0 -26
  89. package/dist/http/query.js +0 -119
  90. /package/dist/browser/type/{request.js → transport.js} +0 -0
@@ -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
  }
@@ -1,6 +1,7 @@
1
1
  import type { ForeignKeyAction } from '../schema/types.js';
2
2
  import type { TYPE_BOUNDS, VALUE_DECIDERS } from '../util/fieldOption.util.js';
3
3
  import type { ColumnType, DdlDefault, FamilyOf, FieldOptions, HasCompositeKey, IdValue, JsonColumnType, OnFieldCallback, StampEvent, TsTypeOf } from './entity.js';
4
+ import type { Wire } from './query.js';
4
5
  import type { QuerySql } from './querySql.js';
5
6
  import type { StandardSchemaV1 } from './standardSchema.js';
6
7
  import type { Type, Json, JsonDocument, JsonScalar, AbstractType } from './utility.js';
@@ -111,10 +112,15 @@ export interface ColumnBuilder<in out O, in out V, F extends Family> extends Col
111
112
  comment(text: string): With<O, V, {
112
113
  readonly comment: string;
113
114
  }, F>;
114
- /** Leaves the column out of a read naming no fields. */
115
+ /** Leaves the column out of a read naming no fields. A read naming it still gets it, so it keeps no secret: `wire(false)` does. */
115
116
  eager(eager: false): With<O, V, {
116
117
  readonly eager: false;
117
118
  }, F>;
119
+ /**
120
+ * What a client may do to it over an API that serves its entity (none does by default): `false` hides it,
121
+ * `['read']` makes it read-only, and unset it takes everything.
122
+ */
123
+ wire(wire: Wire): With<O, V, unknown, F>;
118
124
  /** The SQL type where it differs from the one the builder implies; an engine's own, `sql`citext``, verbatim. */
119
125
  columnType(type: ColumnType): With<O, V, {
120
126
  readonly columnType: ColumnType;
@@ -185,6 +191,8 @@ export interface ComputedColumn<in out O, in out V> extends Column<O, V> {
185
191
  stored(events?: readonly StampEvent[]): ComputedColumn<O & {
186
192
  readonly stored: unknown;
187
193
  }, V>;
194
+ /** Whether a client may read it over an API: `false` hides it. */
195
+ wire(wire: false | readonly ['read']): ComputedColumn<O, V>;
188
196
  }
189
197
  /** The version column, an optimistic lock: an update matches the version it read and writes the next. */
190
198
  export interface VersionColumn<in out O, in out V> extends Column<O, V> {
@@ -1,5 +1,6 @@
1
1
  import type { Column, ColumnOptionsOf, ColumnValueOf, FilledOptions, NullOf } from './column.js';
2
2
  import type { BrandNames, CheckSection, FilterSection, filledKey, HookContext, HookEvent, idKey, IdValue, IndexSection, IsUnion, KeyHolding, RefMap, RelationCardinality, RelationInverseOptions, RelationJoinOptions, RelationOwnerOptions, RelationRef, ToManyRefs, ToManyRelationKey, TriggerSection, versionKey } from './entity.js';
3
+ import type { EntityAccess, Wire } from './query.js';
3
4
  import type { QuerySql, RelationAggregate } from './querySql.js';
4
5
  import type { Type, AbstractType } from './utility.js';
5
6
  /**
@@ -142,6 +143,8 @@ export type DefineEntityOptions<F extends DefinedFields, B = object, BK = unknow
142
143
  readonly schema?: string;
143
144
  /** A base that is never a table: the entities extending it take what it declares. */
144
145
  readonly abstract?: true;
146
+ /** What a client may do over an API: see {@link Wire}. */
147
+ readonly wire?: Wire<EntityAccess>;
145
148
  /** The entity it inherits from, which the declared class extends, so its methods and `super` work. */
146
149
  readonly extends?: DefinedClass<B, BK, BC, boolean>;
147
150
  readonly fields: F;
@@ -1,7 +1,7 @@
1
1
  import type { EnumValues, ForeignKeyAction, IndexType } from '../schema/types.js';
2
2
  import type { SqlDialectName } from './dialect.js';
3
3
  import type { Querier } from './querier.js';
4
- import type { FilterOptions, RelationQuery } from './query.js';
4
+ import type { EntityAccess, FilterOptions, RelationQuery, Wire } from './query.js';
5
5
  import type { ColumnRef, JsonPathRef, QuerySql, SqlFor, RelationAggregate } from './querySql.js';
6
6
  import type { QueryWhere } from './queryWhere.js';
7
7
  import type { StandardSchemaV1 } from './standardSchema.js';
@@ -312,6 +312,8 @@ export type FieldOptions<V = unknown> = {
312
312
  readonly stored?: boolean | readonly StampEvent[];
313
313
  readonly updatable?: boolean;
314
314
  readonly eager?: boolean;
315
+ /** What a client may do over an API: see {@link Wire}. */
316
+ readonly wire?: Wire;
315
317
  readonly onInsert?: OnFieldCallback<V>;
316
318
  readonly onUpdate?: OnFieldCallback<V>;
317
319
  /**
@@ -394,10 +396,14 @@ export type RelationOptions<E, O = unknown> = RelationCascade & RelationActions
394
396
  */
395
397
  references?: (local: KeyMap<O>, foreign: KeyMap<E>) => ForeignKey<O, E> | readonly RelationReference<O, E>[];
396
398
  };
397
- /** Whether writes reach the related rows in the same transaction; its own type, so an option set takes it without instantiating `RelationOptions`. */
398
- type RelationCascade = {
399
+ /** What every relation takes: whether writes reach the related rows in the same transaction, and its `wire`; its own type, so an option set takes it without instantiating `RelationOptions`. */
400
+ type RelationCascade = RelationWire & {
399
401
  readonly cascade?: boolean | CascadeType;
400
402
  };
403
+ /** What a client may do over an API: see {@link Wire}. */
404
+ type RelationWire = {
405
+ readonly wire?: Wire;
406
+ };
401
407
  /** The foreign key's actions, read on the owning side; unset, the column's own `onDelete` applies. */
402
408
  type RelationActions = {
403
409
  readonly onDelete?: ForeignKeyAction;
@@ -456,7 +462,7 @@ type DecoratedJoins<E, O> = {
456
462
  * The side holding the foreign key, which the actions attach to. It cascades `'persist'` only: its target may
457
463
  * be other rows' too, so a delete cascades from the side owning the rows.
458
464
  */
459
- type RelationOwnerSide = RelationActions & {
465
+ type RelationOwnerSide = RelationActions & RelationWire & {
460
466
  readonly cascade?: 'persist';
461
467
  readonly mappedBy?: never;
462
468
  readonly through?: never;
@@ -756,6 +762,8 @@ export type EntityMeta<E> = {
756
762
  version?: FieldKey<E>;
757
763
  /** Named, default-on `$where` filters applied to every query unless bypassed. */
758
764
  filters?: Record<string, FilterOptions<E>>;
765
+ /** What a client may do over an API, see {@link Wire}; a subclass declaring none takes its base's. */
766
+ wire?: Wire<EntityAccess>;
759
767
  fields: {
760
768
  [K in FieldKey<E>]?: FieldMeta;
761
769
  } & {
@@ -924,6 +932,8 @@ export type EntityOptions<E = unknown> = {
924
932
  readonly abstract?: true;
925
933
  /** The schema (a MySQL database) the table lives in; unset follows the pool's. */
926
934
  readonly schema?: string;
935
+ /** What a client may do over an API: see {@link Wire}. */
936
+ readonly wire?: Wire<EntityAccess>;
927
937
  readonly filters?: FilterSection<E>;
928
938
  readonly indexes?: IndexSection<E>;
929
939
  /** Table-level `CHECK` constraints. See {@link CheckOptions}. */
@@ -46,11 +46,11 @@ export type EngineName = (typeof ENGINE_NAMES)[DialectName] | 'Cloudflare D1' |
46
46
  * **first** on purpose: when no signature matches, TypeScript reports the error of the *last* one, so a
47
47
  * typo'd query key is reported as itself rather than as a missing `$entity`.
48
48
  */
49
- type DualRead<K extends keyof ReadQueries<object, never>, R extends keyof ReadResults<'server', unknown>> = (<E extends object, const Q extends ReadQueries<E, QuerySql>[K] & {
49
+ type DualRead<K extends keyof ReadQueries<object, never>, R extends keyof ReadResults<unknown>> = (<E extends object, const Q extends ReadQueries<E, QuerySql>[K] & {
50
50
  $entity: Type<E>;
51
51
  }>(q: Captured<ReadQueries<E, QuerySql>[K] & {
52
52
  $entity: Type<E>;
53
- }, Q>, opts?: QueryOptions) => ReadResults<'server', QueryFindResult<E, Q>>[R]) & EntityRead<K, R, 'server', QueryOptions>;
53
+ }, Q>, opts?: QueryOptions) => ReadResults<QueryFindResult<E, Q>>[R]) & EntityRead<K, R, 'server', QueryOptions>;
54
54
  /** Each method below taking a query takes the entity first or as the query's `$entity`, as {@link DualRead} does. */
55
55
  export interface Querier extends UniversalQuerier {
56
56
  findOne: DualRead<'one', 'one'>;
@@ -24,11 +24,15 @@ export type QueryOptions = {
24
24
  unfiltered?: boolean;
25
25
  };
26
26
  /**
27
- * What a statement is rendered with, on top of the options its caller passed. Kept apart from
28
- * {@link QueryOptions} because that one is public - it is the third argument of every querier method -
29
- * and none of this is a caller's to set: an alias is the dialect's to choose and to spell.
27
+ * What a statement runs with, on top of the options its caller passed. Kept apart from {@link QueryOptions}
28
+ * because that one is public, the third argument of every querier method, and none of this is a caller's to set.
30
29
  */
31
- export type QueryRenderOptions = QueryOptions & {
30
+ export type StatementOptions = QueryOptions & {
31
+ /** What the statement does, which picks the `security` filters scoping it: a read by default. A write's reads take its own. */
32
+ readonly access?: EntityAccess;
33
+ };
34
+ /** What a statement is rendered with: an alias is the dialect's to choose and to spell. */
35
+ export type QueryRenderOptions = StatementOptions & {
32
36
  /** The alias columns are read off, escaped by the dialect unless {@link escapedPrefix} spells it. */
33
37
  prefix?: string;
34
38
  /**
@@ -106,6 +110,16 @@ export type FilterWhere<E> = QueryWhere<E> | ((context: UqlContext | undefined)
106
110
  * `throw` fails closed (the default for `security` filters).
107
111
  */
108
112
  export type FilterOnMissing = 'skip' | 'throw';
113
+ /** What a field takes: reading it (select, filter, sort, distinct, aggregate) and writing it. */
114
+ export type FieldAccess = 'read' | 'insert' | 'update';
115
+ /** What a statement does to an entity's rows: a field's access, and deleting rows, which no field has a part in. */
116
+ export type EntityAccess = FieldAccess | 'delete';
117
+ /**
118
+ * What a client may do to an entity, or one of its members, over an API: what it lists, nothing for `false`, and
119
+ * everything where unset. Nothing is served by default: an entity reaches the wire only when an API's `include`
120
+ * names it, and `wire` narrows it from there.
121
+ */
122
+ export type Wire<A extends EntityAccess = FieldAccess> = false | readonly A[];
109
123
  /**
110
124
  * Authoring shape for `@Entity({ filters })` and `defineEntity`'s `.filters()`.
111
125
  */
@@ -117,6 +131,7 @@ export type FilterOptions<E = unknown> = {
117
131
  readonly security?: false;
118
132
  /** What to do when {@link FilterOptions.where} returns `undefined`. Defaults to `skip`. */
119
133
  readonly onMissing?: FilterOnMissing;
134
+ readonly ops?: never;
120
135
  } | {
121
136
  /**
122
137
  * Row-level-security filter: always applied (ignores `QueryOptions.filters` bypass) and
@@ -124,6 +139,11 @@ export type FilterOptions<E = unknown> = {
124
139
  */
125
140
  readonly security: true;
126
141
  readonly onMissing?: 'throw';
142
+ /**
143
+ * The statements it holds, every one by default: `['insert', 'update', 'delete']` lets anyone read a row
144
+ * and only its author write it. An update or a delete reads the rows it changes, so read ones hold it too.
145
+ */
146
+ readonly ops?: readonly EntityAccess[];
127
147
  });
128
148
  /**
129
149
  * direction for the sort, and where nulls land in it.
@@ -2,33 +2,33 @@ import type { EntityId, EntityWrite, FieldKey, UpdateWrite } from './entity.js';
2
2
  import type { Captured, CursorPage, Query, QueryUpsert, QueryFilter, QueryFindResult, QueryKeyset, QueryOne, QueryOptions, QueryPage, QuerySearch, WriteResults, WriteOptions } from './query.js';
3
3
  import type { QueryAggregate, QueryAggregateResult } from './queryAggregate.js';
4
4
  import type { BooleanLike, Type } from './utility.js';
5
- import type { QuerierCountedResult, QuerierSql, QuerierResult, QuerierTransport } from './wire.js';
5
+ import type { QuerierSql, QuerierTransport } from './wire.js';
6
6
  /** The query each read takes, keyed by the kind of read. */
7
7
  export type ReadQueries<E, Sql> = {
8
8
  readonly one: QueryOne<E, Sql>;
9
9
  readonly many: Query<E, Sql>;
10
10
  readonly page: QueryKeyset<E, Sql>;
11
11
  };
12
- /** The result type of each read on transport `W`, keyed by the kind of read. */
13
- export type ReadResults<W extends QuerierTransport, T> = {
14
- readonly one: QuerierResult<W, T | undefined>;
15
- readonly many: QuerierResult<W, T[]>;
16
- readonly counted: QuerierCountedResult<W, T>;
17
- readonly page: QuerierResult<W, CursorPage<T>>;
12
+ /** The result type of each read, keyed by the kind of read: alike on the server and the client. */
13
+ export type ReadResults<T> = {
14
+ readonly one: Promise<T | undefined>;
15
+ readonly many: Promise<T[]>;
16
+ readonly counted: Promise<[T[], number]>;
17
+ readonly page: Promise<CursorPage<T>>;
18
18
  readonly stream: AsyncIterable<T>;
19
19
  };
20
20
  /**
21
21
  * A read that takes the entity first, then the query, and returns rows narrowed to what the query projected. `K` picks
22
- * the query type, `R` the result type on transport `W`, and `O` the options.
22
+ * the query type, `R` the result type, `W` the transport, whose SQL its queries may carry, and `O` the options.
23
23
  */
24
- export type EntityRead<K extends keyof ReadQueries<object, never>, R extends keyof ReadResults<QuerierTransport, unknown>, W extends QuerierTransport, O> = <E extends object, const Q extends ReadQueries<E, QuerierSql<W>>[K]>(entity: Type<E>, q: Captured<ReadQueries<E, QuerierSql<W>>[K], Q>, opts?: O) => ReadResults<W, QueryFindResult<E, Q>>[R];
24
+ export type EntityRead<K extends keyof ReadQueries<object, never>, R extends keyof ReadResults<unknown>, W extends QuerierTransport, O> = <E extends object, const Q extends ReadQueries<E, QuerierSql<W>>[K]>(entity: Type<E>, q: Captured<ReadQueries<E, QuerierSql<W>>[K], Q>, opts?: O) => ReadResults<QueryFindResult<E, Q>>[R];
25
25
  /**
26
26
  * The operations the server and the browser client declare alike, per transport `W`, options `O`,
27
27
  * and delete options `DO`, which on the client also carry the {@link QueryOptions} it cannot pass otherwise.
28
28
  */
29
29
  export interface SharedQuerier<W extends QuerierTransport, O, DO = O> {
30
30
  /** Find the record with the given primary key. */
31
- findOneById<E extends object, const Q extends QueryOne<E, QuerierSql<W>> = {}>(entity: Type<E>, id: EntityId<E>, q?: Captured<QueryOne<E, QuerierSql<W>>, Q>, opts?: O): QuerierResult<W, QueryFindResult<E, Q> | undefined>;
31
+ findOneById<E extends object, const Q extends QueryOne<E, QuerierSql<W>> = {}>(entity: Type<E>, id: EntityId<E>, q?: Captured<QueryOne<E, QuerierSql<W>>, Q>, opts?: O): Promise<QueryFindResult<E, Q> | undefined>;
32
32
  /**
33
33
  * obtains the first record matching the given search parameters.
34
34
  * @param entity the target entity
@@ -52,27 +52,27 @@ export interface SharedQuerier<W extends QuerierTransport, O, DO = O> {
52
52
  */
53
53
  findManyPage: EntityRead<'page', 'page', W, O>;
54
54
  /** Count the records matching the filter, or those a page of them takes. */
55
- count<E extends object>(entity: Type<E>, q?: QueryPage<E, QuerierSql<W>>, opts?: O): QuerierResult<W, number>;
55
+ count<E extends object>(entity: Type<E>, q?: QueryPage<E, QuerierSql<W>>, opts?: O): Promise<number>;
56
56
  /** Whether any record matches: a count capped at one row, so the engine stops at the first match. */
57
- exists<E extends object>(entity: Type<E>, q?: QueryFilter<E, QuerierSql<W>>, opts?: O): QuerierResult<W, boolean>;
57
+ exists<E extends object>(entity: Type<E>, q?: QueryFilter<E, QuerierSql<W>>, opts?: O): Promise<boolean>;
58
58
  /** Update the record with the given primary key; resolves to the number of affected rows. */
59
- updateOneById<E extends object>(entity: Type<E>, id: EntityId<E>, payload: UpdateWrite<E, QuerierSql<W>>, opts?: O): QuerierResult<W, number>;
59
+ updateOneById<E extends object>(entity: Type<E>, id: EntityId<E>, payload: UpdateWrite<E, QuerierSql<W>>, opts?: O): Promise<number>;
60
60
  /** Update the records matching the query; resolves to the number of affected rows. */
61
- updateMany<E extends object>(entity: Type<E>, q: QuerySearch<E, QuerierSql<W>>, payload: UpdateWrite<E, QuerierSql<W>>, opts?: O): QuerierResult<W, number>;
61
+ updateMany<E extends object>(entity: Type<E>, q: QuerySearch<E, QuerierSql<W>>, payload: UpdateWrite<E, QuerierSql<W>>, opts?: O): Promise<number>;
62
62
  /**
63
63
  * delete or SoftDelete a record.
64
64
  * @param entity the entity to persist on
65
65
  * @param id the primary key of the record
66
66
  * @return the number of affected records
67
67
  */
68
- deleteOneById<E extends object>(entity: Type<E>, id: EntityId<E>, opts?: DO): QuerierResult<W, number>;
68
+ deleteOneById<E extends object>(entity: Type<E>, id: EntityId<E>, opts?: DO): Promise<number>;
69
69
  /**
70
70
  * delete or SoftDelete records.
71
71
  * @param entity the entity to persist on
72
72
  * @param q the criteria to look for the records
73
73
  * @return the number of affected records
74
74
  */
75
- deleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E, QuerierSql<W>>, opts?: DO): QuerierResult<W, number>;
75
+ deleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E, QuerierSql<W>>, opts?: DO): Promise<number>;
76
76
  }
77
77
  /**
78
78
  * A `querier` allows to interact with the datasource to perform persistence operations on any entity.
@@ -87,8 +87,7 @@ export interface UniversalQuerier extends SharedQuerier<'server', QueryOptions>
87
87
  insertOne<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']>;
88
88
  /**
89
89
  * Insert records in as few statements as the bind limit allows, resolving to their ids in payload order, or
90
- * the rows `returning` reads back. Ids are exact everywhere but MySQL, which infers them from its header and
91
- * reports `undefined` rather than a guess for a generated key that is not `AUTO_INCREMENT`.
90
+ * the rows `returning` reads back.
92
91
  */
93
92
  insertMany<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'][]>;
94
93
  /** Update the record with the given primary key; resolves to the number of affected rows, or the row `returning` reads back. */
@@ -1,20 +1,6 @@
1
1
  import type { QuerySql } from './querySql.js';
2
2
  /**
3
- * The envelope a wire response wraps its result in.
4
- */
5
- export type RequestSuccessResponse<E> = {
6
- data: E;
7
- count?: number;
8
- };
9
- /**
10
- * A {@link RequestSuccessResponse} whose `count` is always present - what `findManyAndCount` sends.
11
- */
12
- export type RequestCountedSuccessResponse<E> = RequestSuccessResponse<E> & {
13
- count: number;
14
- };
15
- /**
16
- * Which side of the wire a querier sits on. A server querier hands the result back directly, a
17
- * client one hands back the envelope its transport wrapped it in.
3
+ * Which side of the wire a querier sits on, which says what SQL its queries may carry: both answer alike.
18
4
  */
19
5
  export type QuerierTransport = 'server' | 'client';
20
6
  /**
@@ -25,19 +11,3 @@ export type QuerierSql<W extends QuerierTransport> = {
25
11
  server: QuerySql;
26
12
  client: never;
27
13
  }[W];
28
- /**
29
- * A querier method's result on a transport: `Promise<User[]>` on the server, the response envelope on
30
- * the client. A map indexed by the transport, which resolves away in hovers.
31
- */
32
- export type QuerierResult<W extends QuerierTransport, T> = {
33
- server: Promise<T>;
34
- client: Promise<RequestSuccessResponse<T>>;
35
- }[W];
36
- /**
37
- * `findManyAndCount`'s result: the one shape the transports disagree on past the envelope, a tuple
38
- * on the server against a counted envelope on the client.
39
- */
40
- export type QuerierCountedResult<W extends QuerierTransport, T> = {
41
- server: Promise<[T[], number]>;
42
- client: Promise<RequestCountedSuccessResponse<T[]>>;
43
- }[W];
@@ -1,6 +1,6 @@
1
1
  import type { IndexType } from '../schema/types.js';
2
- import { type AggregateCall, type CascadeType, type EntityData, type EntityIndexMeta, type EntityMeta, type FieldKey, type FieldOptions, type FieldUpdateOp, type JsonArrayUpdateOp, type JsonUpdateOp, type OnFieldCallback, type QueryAggMap, type QueryConflictKeys, type QueryUpsert, type QueryGroupMap, type QueryOptions, QuerySql, type QuerySearch, type QuerySelect, type QuerySelectValue, type QuerySortDirection, type QuerySizeComparisonOps, type QuerySortMap, type QueryTextSearchOptions, type QueryVectorQuery, type QueryVectorSearch, type QueryWhere, type RelationKey, type UpdatePayload, type VectorDistance } from '../type/index.js';
3
- export type CallbackKey = keyof Pick<FieldOptions, 'onInsert' | 'onUpdate'>;
2
+ import { type AggregateCall, type CascadeType, type EntityAccess, type EntityData, type EntityIndexMeta, type EntityMeta, type FieldKey, type FieldOptions, type FieldUpdateOp, type JsonArrayUpdateOp, type JsonUpdateOp, type OnFieldCallback, type QueryAggMap, type QueryConflictKeys, type QueryUpsert, type QueryGroupMap, type QueryOptions, QuerySql, type QuerySearch, type QuerySelect, type QuerySelectValue, type QuerySortDirection, type QuerySizeComparisonOps, type QuerySortMap, type QueryTextSearchOptions, type QueryVectorQuery, type QueryVectorSearch, type QueryWhere, type RelationKey, type StatementOptions, type UpdatePayload, type VectorDistance } from '../type/index.js';
3
+ import { type CallbackKey } from './field.util.js';
4
4
  /** The keys of `payload` a write persists as columns. */
5
5
  export declare function filterFieldKeys<E>(meta: EntityMeta<E>, payload: EntityData<E> | UpdatePayload<E>, callbackKey: CallbackKey): FieldKey<E>[];
6
6
  /**
@@ -135,12 +135,12 @@ export declare function fieldUpdateOf(key: string, value: FieldUpdateOp): [keyof
135
135
  * `$where` with the entity's active filters merged in, against the ambient {@link UqlContext}. A convenience
136
136
  * filter yields to a `$where` on its key; a `security` one is always ANDed, from {@link securityConditions}.
137
137
  */
138
- export declare function applyFilters<E>(meta: EntityMeta<E>, whereMap: QueryWhere<E>, opts?: QueryOptions): QueryWhere<E>;
138
+ export declare function applyFilters<E>(meta: EntityMeta<E>, whereMap: QueryWhere<E>, opts?: StatementOptions): QueryWhere<E>;
139
139
  /**
140
- * Each `security` filter's condition, by name, resolved against the ambient context. One resolving to
141
- * `{}`, a trusted context's "no restriction", is left out. Reads AND these in; writes are held to them.
140
+ * The condition of each `security` filter holding any of `accesses`, by name, resolved against the ambient context.
141
+ * One resolving to `{}`, a trusted context's "no restriction", is left out. Reads AND these in; writes are held to them.
142
142
  */
143
- export declare function securityConditions<E>(meta: EntityMeta<E>): [name: string, condition: QueryWhere<E>][];
143
+ export declare function securityConditions<E>(meta: EntityMeta<E>, accesses: readonly EntityAccess[]): [name: string, condition: QueryWhere<E>][];
144
144
  /**
145
145
  * Holds written rows to the `security` filters, as {@link applyFilters} holds reads: an inserted row gets
146
146
  * each field a condition names and it leaves out, and a row naming one must carry the condition's value.
@@ -181,10 +181,10 @@ export declare function parseGroupMap<E>(group?: QueryGroupMap<E>, select?: Quer
181
181
  /** A JSON object, matched by what it holds: a plain object with no operator key. */
182
182
  export declare function isJsonObject(value: unknown): value is Record<string, unknown>;
183
183
  /**
184
- * A page operand, checked before it reaches an engine. These arrive from page arithmetic and from
185
- * REST query strings (`parseQueryParams` yields `NaN` for a non-numeric one), and each engine's own
186
- * complaint names neither the clause nor the value - or, for `$limit: 0`, quietly means something
187
- * else. Shared so every backend rejects the same input.
184
+ * A page operand, checked before it reaches an engine. These arrive from page arithmetic and from a
185
+ * client's call, where JSON carries a fraction or a negative alike, and each engine's own complaint
186
+ * names neither the clause nor the value - or, for `$limit: 0`, quietly means something else.
187
+ * Shared so every backend rejects the same input.
188
188
  */
189
189
  export declare function assertNonNegativeInteger(value: number, clause: string): number;
190
190
  /**
@@ -2,7 +2,7 @@ import { getContext } from '../context/context.js';
2
2
  import { namesKey } from '../entity/metadata/definition.js';
3
3
  import { QuerySql, resolveAggregateOp, } from '../type/index.js';
4
4
  import { DEFAULT_VECTOR_DISTANCE, VECTOR_INDEX_TYPES } from '../type/vector.js';
5
- import { defaultReadKeys, fieldKeys, isDatabaseWritten, jsonKey, jsonPathKeys } from './field.util.js';
5
+ import { defaultReadKeys, fieldKeys, isDatabaseWritten, isWrittenOn, jsonKey, jsonPathKeys, } from './field.util.js';
6
6
  import { withDeleted } from './filters.util.js';
7
7
  import { entityName, getKeys, omitKeys, hasKeys, isJsonScalar, isOperatorObject, isPlainObject, isRecord, someKey, } from './object.util.js';
8
8
  import { assertNoUndefined, whereAnd } from './query.util.js';
@@ -11,7 +11,7 @@ import { UqlSecurityError, UqlUsageError } from './uqlError.js';
11
11
  export function filterFieldKeys(meta, payload, callbackKey) {
12
12
  return getKeys(payload).filter((key) => {
13
13
  const fieldOpts = meta.fields[key];
14
- return fieldOpts && !isDatabaseWritten(fieldOpts) && (callbackKey !== 'onUpdate' || fieldOpts.updatable !== false);
14
+ return fieldOpts && isWrittenOn(fieldOpts, callbackKey);
15
15
  });
16
16
  }
17
17
  /** Whether `key` is a field the caller writes, and `record` provides a defined value for. */
@@ -433,16 +433,24 @@ export function applyFilters(meta, whereMap, opts) {
433
433
  }
434
434
  }
435
435
  const merged = result;
436
- const security = securityConditions(meta).map(([, condition]) => condition);
436
+ const security = securityConditions(meta, SCOPED_BY[opts?.access ?? 'read']).map(([, condition]) => condition);
437
437
  return security.length ? whereAnd(merged, security) : merged;
438
438
  }
439
+ /** The accesses whose `security` filters scope a statement: an update or a delete reads the rows it changes too. */
440
+ const SCOPED_BY = {
441
+ read: ['read'],
442
+ insert: ['insert'],
443
+ update: ['read', 'update'],
444
+ delete: ['read', 'delete'],
445
+ };
439
446
  /**
440
- * Each `security` filter's condition, by name, resolved against the ambient context. One resolving to
441
- * `{}`, a trusted context's "no restriction", is left out. Reads AND these in; writes are held to them.
447
+ * The condition of each `security` filter holding any of `accesses`, by name, resolved against the ambient context.
448
+ * One resolving to `{}`, a trusted context's "no restriction", is left out. Reads AND these in; writes are held to them.
442
449
  */
443
- export function securityConditions(meta) {
450
+ export function securityConditions(meta, accesses) {
444
451
  return Object.entries(meta.filters ?? {}).flatMap(([name, filter]) => {
445
- const condition = filter.security ? resolveFilter(meta, name, filter) : undefined;
452
+ const holds = filter.security && (!filter.ops || filter.ops.some((op) => accesses.includes(op)));
453
+ const condition = holds ? resolveFilter(meta, name, filter) : undefined;
446
454
  return condition && hasKeys(condition) ? [[name, condition]] : [];
447
455
  });
448
456
  }
@@ -462,7 +470,7 @@ function resolveFilter(meta, name, filter) {
462
470
  * See architecture/security-filter-writes.md.
463
471
  */
464
472
  export function guardWrite(meta, rows, write) {
465
- for (const [name, condition] of securityConditions(meta)) {
473
+ for (const [name, condition] of securityConditions(meta, [write])) {
466
474
  const values = condition;
467
475
  const keys = fieldKeys(meta, () => true).filter((key) => Object.hasOwn(values, key));
468
476
  const equalities = keys.length === getKeys(values).length;
@@ -576,10 +584,10 @@ export function isJsonObject(value) {
576
584
  return isPlainObject(value) && !isOperatorObject(value);
577
585
  }
578
586
  /**
579
- * A page operand, checked before it reaches an engine. These arrive from page arithmetic and from
580
- * REST query strings (`parseQueryParams` yields `NaN` for a non-numeric one), and each engine's own
581
- * complaint names neither the clause nor the value - or, for `$limit: 0`, quietly means something
582
- * else. Shared so every backend rejects the same input.
587
+ * A page operand, checked before it reaches an engine. These arrive from page arithmetic and from a
588
+ * client's call, where JSON carries a fraction or a negative alike, and each engine's own complaint
589
+ * names neither the clause nor the value - or, for `$limit: 0`, quietly means something else.
590
+ * Shared so every backend rejects the same input.
583
591
  */
584
592
  export function assertNonNegativeInteger(value, clause) {
585
593
  if (!Number.isInteger(value) || value < 0) {
@@ -38,6 +38,9 @@ export declare function aggregateField(aggregate: RelationAggregate): FieldOptio
38
38
  * computed column *is* a real column, read like one, but writing to it is an error on every engine.
39
39
  */
40
40
  export declare function isDatabaseWritten(field: FieldOptions): boolean;
41
+ export type CallbackKey = keyof Pick<FieldOptions, 'onInsert' | 'onUpdate'>;
42
+ /** Whether a write by `callbackKey` persists `field`: never one the database writes, nor an `updatable(false)` one on update. */
43
+ export declare function isWrittenOn(field: FieldOptions, callbackKey: CallbackKey): boolean;
41
44
  /** The column family of a field, from its `columnType` if set, else from its `type`. */
42
45
  export declare function fieldFamily(field: FieldOptions): ColumnFamily | undefined;
43
46
  /** Whether the column is NOT NULL: every column is, a key included, unless it declares `nullable()`. */
@@ -54,7 +57,10 @@ export declare function lacksValue(column: {
54
57
  * holds a value too, unlike on the rows a migration finds.
55
58
  */
56
59
  export declare function lacksValueOnInsert(field: FieldOptions): boolean;
57
- /** Whether `key` is a field of `meta`, as opposed to a relation, a JSON path or an unknown key. */
60
+ /**
61
+ * Whether `key` is a field of `meta`, as opposed to a relation, a JSON path or an unknown key: an own key alone, so
62
+ * a client's `constructor` is none.
63
+ */
58
64
  export declare function isFieldKey<E>(meta: EntityMeta<E>, key: string): key is FieldKey<E>;
59
65
  /** The fields `meta` declares whose options `pick` accepts, in declaration order, each as the entity's own key. */
60
66
  export declare function fieldKeys<E>(meta: EntityMeta<E>, pick: (field: FieldMeta) => unknown): FieldKey<E>[];
@@ -83,6 +83,10 @@ export function aggregateField(aggregate) {
83
83
  export function isDatabaseWritten(field) {
84
84
  return field.computed !== undefined;
85
85
  }
86
+ /** Whether a write by `callbackKey` persists `field`: never one the database writes, nor an `updatable(false)` one on update. */
87
+ export function isWrittenOn(field, callbackKey) {
88
+ return !isDatabaseWritten(field) && (callbackKey !== 'onUpdate' || field.updatable !== false);
89
+ }
86
90
  /** The column family of a field, from its `columnType` if set, else from its `type`. */
87
91
  export function fieldFamily(field) {
88
92
  return columnFamily(field.columnType ?? field.type);
@@ -107,9 +111,12 @@ export function lacksValueOnInsert(field) {
107
111
  isAutoIncrement: field.autoIncrement === true,
108
112
  }));
109
113
  }
110
- /** Whether `key` is a field of `meta`, as opposed to a relation, a JSON path or an unknown key. */
114
+ /**
115
+ * Whether `key` is a field of `meta`, as opposed to a relation, a JSON path or an unknown key: an own key alone, so
116
+ * a client's `constructor` is none.
117
+ */
111
118
  export function isFieldKey(meta, key) {
112
- return meta.fields[key] !== undefined;
119
+ return Object.hasOwn(meta.fields, key) && meta.fields[key] !== undefined;
113
120
  }
114
121
  /** The fields `meta` declares whose options `pick` accepts, in declaration order, each as the entity's own key. */
115
122
  export function fieldKeys(meta, pick) {
@@ -21,6 +21,7 @@ const FIELD_OPTION_FAMILY = {
21
21
  stored: '*',
22
22
  updatable: '*',
23
23
  eager: '*',
24
+ wire: '*',
24
25
  onInsert: '*',
25
26
  onUpdate: '*',
26
27
  softDelete: '*',
@@ -49,6 +50,7 @@ const INLINE_READS = [
49
50
  'stored',
50
51
  'enum',
51
52
  'eager',
53
+ 'wire',
52
54
  'distance',
53
55
  'nullable',
54
56
  ];
@@ -4,11 +4,26 @@
4
4
  * failure, a lock timeout or a busy database: the transaction can simply run again. `usage` is the
5
5
  * caller's own mistake, which running it again will not fix. `security` is a `security` filter refusing.
6
6
  */
7
- export type QueryErrorKind = 'uniqueViolation' | 'foreignKeyViolation' | 'notNullViolation' | 'checkViolation' | 'optimisticLock' | 'retryable' | 'usage' | 'security';
7
+ export declare const QUERY_ERROR_KINDS: readonly ['uniqueViolation', 'foreignKeyViolation', 'notNullViolation', 'checkViolation', 'optimisticLock', 'retryable', 'usage', 'security'];
8
+ export type QueryErrorKind = (typeof QUERY_ERROR_KINDS)[number];
9
+ export declare function isQueryErrorKind(value: unknown): value is QueryErrorKind;
10
+ /**
11
+ * Where in a call the refused value sits, as `['query', '$where', 'password']`: a form highlights the field by it. A
12
+ * querier's refusal names it within the query, `['$limit']`, which the API places within the call.
13
+ */
14
+ export type UqlErrorPath = readonly (string | number)[];
15
+ export type UqlErrorOptions = ErrorOptions & {
16
+ readonly path?: UqlErrorPath;
17
+ /** What HTTP answers beside the status, as a 405's `allow`. */
18
+ readonly headers?: Readonly<Record<string, string>>;
19
+ };
8
20
  /** Every error UQL raises of its own: the kind `queryErrorKind` answers, and the status HTTP answers with. */
9
21
  export declare abstract class UqlError extends Error {
10
22
  abstract readonly kind: QueryErrorKind;
11
23
  abstract readonly status: number;
24
+ readonly path?: UqlErrorPath;
25
+ readonly headers?: Readonly<Record<string, string>>;
26
+ constructor(message?: string, opts?: UqlErrorOptions);
12
27
  }
13
28
  /**
14
29
  * Thrown where the caller used the API in a way no statement can carry out: an update payload with no
@@ -20,6 +35,17 @@ export declare class UqlUsageError extends UqlError {
20
35
  readonly kind = "usage";
21
36
  readonly status = 400;
22
37
  }
38
+ /**
39
+ * A request refused with a 4xx `status`: what the API answers a route nothing serves (404), a method its op does
40
+ * not take (405, naming the ones it does in `allow`) or a body that is not JSON (415) with, and what a middleware or
41
+ * a hook throws to refuse a client, `new UqlRequestError('unauthorized', 401)`: only a `UqlError` reaches one.
42
+ */
43
+ export declare class UqlRequestError extends UqlError {
44
+ readonly status: number;
45
+ name: string;
46
+ readonly kind = "usage";
47
+ constructor(message: string, status: number, opts?: UqlErrorOptions);
48
+ }
23
49
  /**
24
50
  * Thrown where a `security` filter refuses: its context is missing, or a write would leave a row outside it.
25
51
  * Fails the statement closed.