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
@@ -1,5 +1,34 @@
1
+ /**
2
+ * What a failed query ran into, named the same on every engine - what {@link queryErrorKind} answers
3
+ * with, whether a driver raised the error or UQL did. `retryable` is a deadlock, a serialization
4
+ * failure, a lock timeout or a busy database: the transaction can simply run again. `usage` is the
5
+ * caller's own mistake, which running it again will not fix. `security` is a `security` filter refusing.
6
+ */
7
+ export const QUERY_ERROR_KINDS = [
8
+ 'uniqueViolation',
9
+ 'foreignKeyViolation',
10
+ 'notNullViolation',
11
+ 'checkViolation',
12
+ 'optimisticLock',
13
+ 'retryable',
14
+ 'usage',
15
+ 'security',
16
+ ];
17
+ const KINDS = new Set(QUERY_ERROR_KINDS);
18
+ export function isQueryErrorKind(value) {
19
+ return KINDS.has(value);
20
+ }
1
21
  /** Every error UQL raises of its own: the kind `queryErrorKind` answers, and the status HTTP answers with. */
2
22
  export class UqlError extends Error {
23
+ constructor(message, opts) {
24
+ super(message, opts);
25
+ if (opts?.path) {
26
+ this.path = opts.path;
27
+ }
28
+ if (opts?.headers) {
29
+ this.headers = opts.headers;
30
+ }
31
+ }
3
32
  }
4
33
  /**
5
34
  * Thrown where the caller used the API in a way no statement can carry out: an update payload with no
@@ -11,6 +40,20 @@ export class UqlUsageError extends UqlError {
11
40
  kind = 'usage';
12
41
  status = 400;
13
42
  }
43
+ /**
44
+ * A request refused with a 4xx `status`: what the API answers a route nothing serves (404), a method its op does
45
+ * not take (405, naming the ones it does in `allow`) or a body that is not JSON (415) with, and what a middleware or
46
+ * a hook throws to refuse a client, `new UqlRequestError('unauthorized', 401)`: only a `UqlError` reaches one.
47
+ */
48
+ export class UqlRequestError extends UqlError {
49
+ status;
50
+ name = 'UqlRequestError';
51
+ kind = 'usage';
52
+ constructor(message, status, opts) {
53
+ super(message, opts);
54
+ this.status = status;
55
+ }
56
+ }
14
57
  /**
15
58
  * Thrown where a `security` filter refuses: its context is missing, or a write would leave a row outside it.
16
59
  * Fails the statement closed.
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "homepage": "https://uql-orm.dev",
4
4
  "description": "JSON-native TypeScript ORM for Bun, Browsers, Edge, Node, Workers. Supports PostgreSQL, PGlite, MySQL, MariaDB, SQLite, CockroachDB, SQL Server, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.",
5
5
  "license": "MIT",
6
- "version": "0.112.1",
6
+ "version": "0.114.0",
7
7
  "type": "module",
8
8
  "engines": {
9
9
  "node": ">=22.18"
@@ -5,7 +5,8 @@ description: >
5
5
  on PostgreSQL, MySQL, MariaDB, SQLite, CockroachDB, SQL Server, MongoDB, Turso, Neon, D1 and PGlite.
6
6
  Use when a project imports uql-orm, or when defining entities (@Entity, defineEntity), triggers or filters
7
7
  (soft delete, multi-tenancy), querying ($where, $populate, findMany, aggregate), writing (insertMany, upsertOne,
8
- updateMany, returning), transactions, raw SQL (sql, refs) or migrations (uql-migrate) with it. UQL is not Prisma,
8
+ updateMany, returning), transactions, raw SQL (sql, refs), migrations (uql-migrate), or serving queries to a client
9
+ (createApi, serve, createClientQuerier, createQueryOptions) with it. UQL is not Prisma,
9
10
  Drizzle, TypeORM or MikroORM: their APIs do not carry over.
10
11
  ---
11
12
 
@@ -91,7 +92,6 @@ export class Post {
91
92
  - A column is NOT NULL unless `.nullable()`. Declare a NOT NULL property `!` (`email!: string`), and `?` what an insert may omit: nullable columns (`title?: string | null`), `.eager(false)` and computed fields, relations, and the version uql fills. A key the database generates is `@Field(f.number().autoIncrement()) id?: number` (`f.bigint().autoIncrement()` past 2^53); `.id()` alone generates nothing, so `f.number().id()` is a key the caller supplies and `@Field` refuses `?` on it, as on a `.references()` key. A NOT NULL field something fills (`.default()`, `.onInsert()`, a generated key) stays `!` when listed in the class's `[filledKey]?: 'id' | 'createdAt'`: inserts may omit it, reads always have it. MongoDB fills a text key declared `?` and `_id`. `insertOne`, `insertMany`, `saveOne` and `saveMany` resolve to a defined key, so no `!`; an upsert's may be `undefined`. On SQL engines an insert leaving out a key nothing declared fills throws before writing. `defineEntity` works all of this out.
92
93
  - `.default()` takes a value of the field's type, or SQL the database evaluates per row: `currentTimestamp`, `currentDate`, `currentTime`, `uuid` (not SQLite), `uuidv7` (Postgres 18+, MariaDB 11.7+), or ``sql`...` ``. A plain string is always text, `'CURRENT_TIMESTAMP'` included. A JSON column defaults to a value, `.default({})` or `.default(0)`, never its JSON text (`'{}'`, `'0'` are refused); any other string there is a JSON string.
93
94
  - `Date` is an instant, stored in UTC to the millisecond. `f.decimal()` is exact text (`price?: string | null`); `f.number().precision(10).scale(2)` opts into a rounding JS number.
94
- - The browser client (`HttpQuerier`) reads rows back by the entity it is handed, which must be registered (importing its class does it): a `Date` field is a `Date` and a `bigint` exact, so its rows are not plain JSON and a cache persisting them needs a serializer. A `bigint` travels as its digits, both ways.
95
95
  - A JSON column's property is `Json<T>`: `settings?: Json<{ theme?: string }> | null`. A plain object type reads as a relation, which `$where`, `$sort` and the update operators refuse.
96
96
  - A relation decorator takes its target first, then its options, as `rel.*` does. `mappedBy` and `references` may be left out where only one member fits, and then the options too: `@OneToMany(() => Post)`. `@ManyToMany(() => Tag, { through: () => PostTag })` names the junction entity. `cascade: true` writes related rows with their row, in one transaction on SQL and, on MongoDB, inside one the caller opens; an update replaces a to-many's rows.
97
97
  - A class inherits its base's fields, relations, hooks, filters, indexes, checks and triggers. A base of fields alone needs no `@Entity()`; one declaring entity options but no table is `@Entity({ abstract: true, ... }) abstract class`, which cannot be queried.
@@ -177,7 +177,7 @@ await withContext({ tenantId: 42 }, () => pool.findMany(Invoice, {}));
177
177
  - A filter is on unless `default: false`. A `$where` naming its field wins over it. Per call, the options argument takes `{ filters: false }`, `{ filters: { softDelete: false } }` or `{ filters: { active: true } }`.
178
178
  - `.softDelete()` on one field turns a delete into a stamp (`new Date()`, or the value or callback given), and registers a `softDelete` filter hiding stamped rows. `withDeleted()` as the options reads both; `restoreOneById` and `restoreMany` undo it; `{ hardDelete: true }` removes rows for good. A restore does not cascade.
179
179
  - A `where` may be a function of the context `withContext(ctx, fn)` sets, which follows `await`, `Promise.all` and transactions but not emitters, timers or queues: wrap those callbacks with `captureContext()`.
180
- - `security: true` makes a filter always apply, ignore bypasses, AND-merge with any `$where`, and throw `UqlSecurityError` when `where` returns `undefined`. It scopes writes too, so new rows need no tenant set by hand. For a trusted cross-tenant job, give `where` a branch returning `{}` (`ctx?.system ? {} : ...`) and run it under `withContext({ system: true }, fn)`: https://uql-orm.dev/multi-tenancy.md
180
+ - `security: true` makes a filter always apply, ignore bypasses, AND-merge with any `$where`, and throw `UqlSecurityError` when `where` returns `undefined`. It scopes writes too, so new rows need no tenant set by hand. `ops: ['insert', 'update', 'delete']` makes one hold those statements alone (anyone reads a row, only its author writes it); an update or delete is also held to the read ones. For a trusted cross-tenant job, give `where` a branch returning `{}` (`ctx?.system ? {} : ...`) and run it under `withContext({ system: true }, fn)`: https://uql-orm.dev/multi-tenancy.md
181
181
 
182
182
  ## Queries
183
183
 
@@ -195,7 +195,7 @@ const users = await pool.findMany(User, {
195
195
  });
196
196
  ```
197
197
 
198
- - Methods: `findMany`, `findOne`, `findOneById`, `findManyAndCount`, `findManyPage`, `findManyStream`, `count`, `exists`, `aggregate`, `insertOne`, `insertMany`, `updateOneById`, `updateMany`, `saveOne`, `saveMany`, `upsertOne`, `upsertMany`, `deleteOneById`, `deleteMany`. Each takes the entity class first; on a querier, each taking a query also takes it as the query's `$entity`, so the whole call is JSON. Signatures: https://uql-orm.dev/querying/methods.md
198
+ - Methods: `findMany`, `findOne`, `findOneById`, `findManyAndCount`, `findManyPage`, `findManyStream`, `count`, `estimatedCount`, `exists`, `aggregate`, `insertOne`, `insertMany`, `updateOneById`, `updateMany`, `saveOne`, `saveMany`, `upsertOne`, `upsertMany`, `deleteOneById`, `deleteMany`. Each takes the entity class first; on a querier, each taking a query also takes it as the query's `$entity`, so the whole call is JSON. Signatures: https://uql-orm.dev/querying/methods.md
199
199
  - Query keys: `$select`, `$where`, `$populate`, `$count`, `$distinct`, `$sort`, `$skip`, `$limit`, `$lock`. `$select: { password: false }` reads every field but `password`. `$count: { posts: true }` counts a to-many under `_count` without loading it.
200
200
  - Results are narrowed to what the query selected and populated, at every depth. Reading an unselected field is a compile error. Name a shape with `QueryFindResult<User, 'id' | 'email'>`, or `QueryFindResult<User, typeof query>` for a query declared `as const satisfies Query<User>`. A function forwarding a query keeps the narrowing typed `<E extends object, const Q extends Query<E>>(entity: Type<E>, q: Captured<Query<E>, Q>): Promise<QueryFindResult<E, Q>[]>`.
201
201
  - `$populate` loads relations in the same statement. Nothing is lazy: an unpopulated relation is absent. A populated to-many is always a list. A to-one is optional unless `$required: true`, which keeps only the parents that have one.
@@ -266,6 +266,33 @@ await pool.transaction(async (querier) => {
266
266
  - A transaction opened in one place and ended in another uses `beginTransaction`, `commitTransaction` and `rollbackTransaction`. A querier from `pool.getQuerier()` is yours to release: bind it with `await using`.
267
267
  - A `findManyStream` holds its querier until the loop ends, refusing other statements meanwhile: run them after the loop, or on another connection.
268
268
 
269
+ ## Serving to a client
270
+
271
+ A query is JSON, so a browser sends it as it is and the server checks it against what each entity exposes.
272
+
273
+ ```ts
274
+ import { createApi, toFetchHandler } from 'uql-orm/http';
275
+
276
+ const api = createApi<Request>({
277
+ pool,
278
+ include: [Post, User],
279
+ contextOf: (req) => ({ tenantId: tenantOf(req) }), // from a verified session or JWT
280
+ });
281
+
282
+ export const handler = toFetchHandler(api); // on a catch-all under /api/v1
283
+ ```
284
+
285
+ - Nothing is exposed by default: defining an entity serves nothing, and `include` is required, its entities the only ones a call reaches, through a relation too. Mount the API under a versioned base: `toFetchHandler(api)` for any fetch runtime (Hono, Next.js, Bun, Workers), `app.use('/api/v1', toExpress(api))` from `uql-orm/express`, or `toRequestHandler(api)` for any other framework. Inside a tRPC or oRPC procedure call `api.call(input, ctx)`, which checks the call itself; `.input(parseWireCall)` types it.
286
+ - The wire is `{base}/:entity/:op` (`/api/v1/user/findMany`), the entity's kebab-cased class name and a client method: a read is `GET ?q=<call as JSON>` (or a JSON body by `POST` or `QUERY`: `httpTransport(url, { readMethod: 'POST' })`), a write a JSON `POST`. A success answers `{ data }`, a failure `{ error: { message, status, kind, path } }`.
287
+ - What a client may do is the definition's `wire`, every operation where unset. An entity's (`@Entity({ wire: ['read', 'update'] })`, `defineEntity({ wire })`) lists what it takes of `'read'`, `'insert'`, `'update'`, `'delete'`, a subclass declaring none taking its base's; `wire: false` keeps it off every API, and `createApi` refuses one in `include`. A member's: `f.string().wire(false)` hides a field, `.wire(['read'])` makes it read-only, `.wire(['insert'])` write-once; a relation takes `wire` in its options (`rel.oneToMany(Session, { mappedBy, wire: false })`, `@OneToMany(() => Session, { mappedBy, wire: false })`). It holds wherever the entity is reached, through any relation. A write the querier would drop, to a computed field or an update of an `updatable(false)` one, is refused instead; a save may insert, so it takes the latter.
288
+ - `read` covers every clause naming the member (`$select`, `$where`, `$sort`, `$count`, `$populate`), and a read with no `$select` leaves out what it may not read. `.eager(false)` is no guard, since a client's `$select` still reads it: hide a secret with `.wire(false)`.
289
+ - A middleware is `(call, context, next) => next(call)`, run after the call is checked: reshape the call before `next`, or what `next` resolves to after it. The API's `use` runs on every call, and `serve(Entity, { use })` in `include` on that entity's alone, typed by it (`call.op === 'insertOne'` types `call.payload` as a row). Refuse a client with `throw new UqlRequestError('unauthorized', 401)` from `uql-orm`; any other error answers generically by its kind, or `500`.
290
+ - Scope tenants with a `security` filter and `contextOf`, never with a middleware adding to `$where`. Without `contextOf` a call keeps its caller's context. On NestJS, `UqlModule.forRoot({ pool, contextOf })` does the same for your own routes.
291
+ - The API serves one entity per call: no `aggregate`, upsert, stream or transaction. Write your own routes for those beside it; `toFetchHandler` answers `404` and `toExpress` falls through to `next()` on paths it does not serve.
292
+ - The client is `createClientQuerier(httpTransport('/api/v1'))` from `uql-orm/browser`, or `createClientQuerier((call) => trpc.uql.mutate(call))` over any transport. It has the pool's find, `count`, `exists`, insert, save, update and delete methods and answers what they answer (rows, not `{ data }`), reading each row back by its entity, which must be registered (importing it does): a `Date` field is a `Date` and a `bigint` exact, so a cache persisting rows needs a serializer. `httpTransport` rejects with a `RequestError` carrying `status`, `kind` and `path`.
293
+ - For TanStack Query, `const uql = createQueryOptions(transport)` and `useQuery(uql((db) => db.findMany(User, q)))`: the key is the call the read makes (`['uql', 'user', 'findMany', { query }]`), so it cannot drift from the fetch, and `uql.key(User)` invalidates every read of `User`.
294
+ - A server bundle that minifies class names must keep them, or pass the same `entityPath` to `createApi` and `createClientQuerier`.
295
+
269
296
  ## Migrations
270
297
 
271
298
  `npx uql-migrate` reads `uql.config.ts` (`bun --bun uql-migrate` on Bun):
@@ -290,4 +317,5 @@ Upgrading uql itself: `npx uql-codemod --dry-run`, then `npx uql-codemod`, which
290
317
  - JSON paths and operators: https://uql-orm.dev/querying/json.md
291
318
  - Full-text and vector search: https://uql-orm.dev/querying/full-text.md, https://uql-orm.dev/querying/semantic-search.md
292
319
  - Computed fields: https://uql-orm.dev/entities/computed-fields.md
320
+ - Serving queries to a client: https://uql-orm.dev/http.md, https://uql-orm.dev/browser.md
293
321
  - Coming from Prisma, Drizzle, TypeORM, MikroORM or Mongoose: https://uql-orm.dev/switching-to-uql.md
@@ -1,3 +0,0 @@
1
- import type { RequestCallback, RequestNotification } from '../type/index.js';
2
- export declare function notify(notification: RequestNotification): void;
3
- export declare function on(cb: RequestCallback): () => void;
@@ -1,12 +0,0 @@
1
- const subscriptors = new Set();
2
- export function notify(notification) {
3
- for (const subscriptor of subscriptors) {
4
- subscriptor(notification);
5
- }
6
- }
7
- export function on(cb) {
8
- subscriptors.add(cb);
9
- return () => {
10
- subscriptors.delete(cb);
11
- };
12
- }
@@ -1,20 +0,0 @@
1
- import type { RequestSuccessResponse } from '../../type/index.js';
2
- import type { RequestOptions } from '../type/index.js';
3
- /**
4
- * Error thrown for non-2xx responses. Carries the HTTP status so callers can key
5
- * behavior on it (401 redirects, 402 payment flows, error-boundary routing).
6
- */
7
- export declare class RequestError extends Error {
8
- readonly status: number;
9
- constructor(message: string, status: number);
10
- }
11
- export declare function get<T>(url: string, opts?: RequestOptions): Promise<RequestSuccessResponse<T>>;
12
- export declare function post<T>(url: string, payload: unknown, opts?: RequestOptions): Promise<RequestSuccessResponse<T>>;
13
- export declare function patch<T>(url: string, payload: unknown, opts?: RequestOptions): Promise<RequestSuccessResponse<T>>;
14
- export declare function put<T>(url: string, payload: unknown, opts?: RequestOptions): Promise<RequestSuccessResponse<T>>;
15
- export declare function remove<T>(url: string, opts?: RequestOptions): Promise<RequestSuccessResponse<T>>;
16
- /**
17
- * HTTP QUERY (RFC 10008): a safe, idempotent read whose JSON query travels in the
18
- * request body, avoiding URL-length limits.
19
- */
20
- export declare function query<T>(url: string, payload: unknown, opts?: RequestOptions): Promise<RequestSuccessResponse<T>>;
@@ -1,67 +0,0 @@
1
- import { wireJson } from '../../http/query.js';
2
- import { notify } from './bus.js';
3
- /**
4
- * Error thrown for non-2xx responses. Carries the HTTP status so callers can key
5
- * behavior on it (401 redirects, 402 payment flows, error-boundary routing).
6
- */
7
- export class RequestError extends Error {
8
- status;
9
- constructor(message, status) {
10
- super(message);
11
- this.status = status;
12
- this.name = 'RequestError';
13
- }
14
- }
15
- // Methods are upper-case because `fetch` normalizes only the classic verbs: a lowercase `patch` or `query`
16
- // is sent as written, and servers refuse it.
17
- export function get(url, opts) {
18
- return request(url, { method: 'GET' }, opts);
19
- }
20
- export function post(url, payload, opts) {
21
- return request(url, { method: 'POST', body: wireJson(payload) }, opts);
22
- }
23
- export function patch(url, payload, opts) {
24
- return request(url, { method: 'PATCH', body: wireJson(payload) }, opts);
25
- }
26
- export function put(url, payload, opts) {
27
- return request(url, { method: 'PUT', body: wireJson(payload) }, opts);
28
- }
29
- export function remove(url, opts) {
30
- return request(url, { method: 'DELETE' }, opts);
31
- }
32
- /**
33
- * HTTP QUERY (RFC 10008): a safe, idempotent read whose JSON query travels in the
34
- * request body, avoiding URL-length limits.
35
- */
36
- export function query(url, payload, opts) {
37
- return request(url, { method: 'QUERY', body: wireJson(payload) }, opts);
38
- }
39
- function request(url, init, opts) {
40
- notify({ phase: 'start', opts });
41
- init.headers = {
42
- accept: 'application/json',
43
- 'content-type': 'application/json',
44
- ...opts?.headers,
45
- };
46
- if (opts?.signal) {
47
- init.signal = opts.signal;
48
- }
49
- return fetch(url, init)
50
- .then((rawResp) => rawResp.json().then((resp) => {
51
- const isSuccess = rawResp.status >= 200 && rawResp.status < 300;
52
- if (isSuccess) {
53
- notify({ phase: 'success', opts });
54
- return resp;
55
- }
56
- const errorResp = resp;
57
- const error = {
58
- message: errorResp?.error?.message ?? rawResp.statusText,
59
- code: errorResp?.error?.code ?? rawResp.status,
60
- };
61
- notify({ phase: 'error', error, opts });
62
- throw new RequestError(error.message, error.code);
63
- }))
64
- .finally(() => {
65
- notify({ phase: 'complete', opts });
66
- });
67
- }
@@ -1,46 +0,0 @@
1
- import { type HttpMethod } from '../../http/contract.js';
2
- import type { SharedQuerier, AbstractType } from '../../type/index.js';
3
- import type { ClientQuerier, RequestFindOptions, RequestOptions } from '../type/index.js';
4
- export type HttpQuerierDefaults = {
5
- /**
6
- * headers sent with every request from this instance, merged under per-call headers.
7
- * Create one instance per request (e.g. during SSR) to scope auth headers safely.
8
- */
9
- readonly headers?: Record<string, string>;
10
- /**
11
- * transport for read queries (findOne, findMany, findManyPage, count). 'QUERY' (RFC 10008) sends the
12
- * JSON query in the request body, avoiding URL-length limits for large queries; requires
13
- * infrastructure (proxies, CDNs) that forwards the QUERY method. Defaults to 'GET'.
14
- */
15
- readonly readMethod?: Extract<HttpMethod, 'GET' | 'QUERY'>;
16
- /**
17
- * The URL segment an entity is addressed by, defaulting to its kebab-cased class name - the same
18
- * option the server handler takes, so one map serves both. State it where the default cannot: a
19
- * build that minifies class names renames every route.
20
- */
21
- readonly entityPath?: (entity: AbstractType<unknown>) => string;
22
- };
23
- export declare class HttpQuerier implements ClientQuerier {
24
- readonly basePath: string;
25
- readonly defaults: HttpQuerierDefaults;
26
- constructor(basePath: string, defaults?: HttpQuerierDefaults);
27
- readonly findOneById: ClientQuerier['findOneById'];
28
- readonly findOne: ClientQuerier['findOne'];
29
- readonly findMany: SharedQuerier<'client', RequestFindOptions>['findMany'];
30
- readonly findManyAndCount: SharedQuerier<'client', RequestFindOptions>['findManyAndCount'];
31
- readonly findManyPage: ClientQuerier['findManyPage'];
32
- readonly count: ClientQuerier['count'];
33
- /** The `count` route capped at one row, so existence needs no endpoint of its own. */
34
- readonly exists: ClientQuerier['exists'];
35
- readonly insertOne: ClientQuerier['insertOne'];
36
- readonly insertMany: ClientQuerier['insertMany'];
37
- readonly updateOneById: ClientQuerier['updateOneById'];
38
- readonly updateMany: ClientQuerier['updateMany'];
39
- readonly saveOne: ClientQuerier['saveOne'];
40
- readonly saveMany: ClientQuerier['saveMany'];
41
- readonly deleteOneById: ClientQuerier['deleteOneById'];
42
- readonly deleteMany: ClientQuerier['deleteMany'];
43
- getBasePath<E>(entity: AbstractType<E>): string;
44
- protected read<T>(path: string, q: Record<string, unknown> | undefined, opts?: RequestOptions): Promise<import("../../type/wire.js").RequestSuccessResponse<T>>;
45
- protected buildOptions(opts?: RequestOptions): RequestOptions | undefined;
46
- }
@@ -1,70 +0,0 @@
1
- import { getMeta } from '../../entity/metadata/definition.js';
2
- import { CRUD_ROUTES, entityPath } from '../../http/contract.js';
3
- import { stringifyQuery } from '../../http/query.js';
4
- import { readWireData } from '../../http/wireRow.js';
5
- import { isScalarId } from '../../util/object.util.js';
6
- import { UqlUsageError } from '../../util/uqlError.js';
7
- import { get, query as httpQuery, patch, post, put, remove } from '../http/index.js';
8
- /** A response with its `data` as the entity holds it, by what its route answers: JSON carried dates and keys as text. */
9
- function dataOf(entity, response, answers) {
10
- return { ...response, data: readWireData(getMeta(entity), response.data, answers) };
11
- }
12
- /** The id as one path segment, refusing a composite key, which has no spelling in `/:id` yet. Callers are `async`. */
13
- function idSegment(entity, id) {
14
- if (!isScalarId(id)) {
15
- throw new UqlUsageError(`'${entity.name}' was addressed by an id object, which the HTTP route cannot carry.`);
16
- }
17
- return String(id);
18
- }
19
- export class HttpQuerier {
20
- basePath;
21
- defaults;
22
- constructor(basePath, defaults = {}) {
23
- this.basePath = basePath;
24
- this.defaults = defaults;
25
- }
26
- // Typed properties instead of methods, so each takes its signature from `ClientQuerier` rather than repeating it.
27
- findOneById = async (entity, id, q, opts) => dataOf(entity, await get(`${this.getBasePath(entity)}/${idSegment(entity, id)}${stringifyQuery(q)}`, this.buildOptions(opts)), CRUD_ROUTES.findOneById.answers);
28
- findOne = async (entity, q, opts) => dataOf(entity, await this.read(`${this.getBasePath(entity)}${CRUD_ROUTES.findOne.path}`, q, opts), CRUD_ROUTES.findOne.answers);
29
- findMany = async (entity, q, opts) => dataOf(entity, await this.read(this.getBasePath(entity), opts?.count ? { ...q, count: true } : q, opts), CRUD_ROUTES.findMany.answers);
30
- findManyAndCount = async (entity, q, opts) => {
31
- const response = await this.findMany(entity, q, { ...opts, count: true });
32
- if (typeof response.count !== 'number') {
33
- throw new TypeError('findManyAndCount response has an invalid count');
34
- }
35
- return { ...response, count: response.count };
36
- };
37
- findManyPage = async (entity, q, opts) => dataOf(entity, await this.read(`${this.getBasePath(entity)}${CRUD_ROUTES.findManyPage.path}`, q, opts), CRUD_ROUTES.findManyPage.answers);
38
- count = (entity, q, opts) => this.read(`${this.getBasePath(entity)}${CRUD_ROUTES.count.path}`, q, opts);
39
- /** The `count` route capped at one row, so existence needs no endpoint of its own. */
40
- exists = async (entity, q, opts) => {
41
- const res = await this.count(entity, { ...q, $limit: 1 }, opts);
42
- return { ...res, data: res.data > 0 };
43
- };
44
- insertOne = async (entity, payload, opts) => dataOf(entity, await post(this.getBasePath(entity), payload, this.buildOptions(opts)), CRUD_ROUTES.insertOne.answers);
45
- insertMany = async (entity, payload, opts) => dataOf(entity, await post(`${this.getBasePath(entity)}${CRUD_ROUTES.insertMany.path}`, payload, this.buildOptions(opts)), CRUD_ROUTES.insertMany.answers);
46
- updateOneById = async (entity, id, payload, opts) => patch(`${this.getBasePath(entity)}/${idSegment(entity, id)}`, payload, this.buildOptions(opts));
47
- updateMany = (entity, q, payload, opts) => patch(`${this.getBasePath(entity)}${stringifyQuery(q)}`, payload, this.buildOptions(opts));
48
- saveOne = async (entity, payload, opts) => dataOf(entity, await put(this.getBasePath(entity), payload, this.buildOptions(opts)), CRUD_ROUTES.saveOne.answers);
49
- saveMany = async (entity, payload, opts) => dataOf(entity, await put(`${this.getBasePath(entity)}${CRUD_ROUTES.saveMany.path}`, payload, this.buildOptions(opts)), CRUD_ROUTES.saveMany.answers);
50
- deleteOneById = async (entity, id, opts = {}) => {
51
- const qs = opts.hardDelete ? stringifyQuery({ hardDelete: opts.hardDelete }) : '';
52
- return remove(`${this.getBasePath(entity)}/${idSegment(entity, id)}${qs}`, this.buildOptions(opts));
53
- };
54
- deleteMany = (entity, q, opts = {}) => remove(`${this.getBasePath(entity)}${stringifyQuery(opts.hardDelete ? { ...q, hardDelete: opts.hardDelete } : q)}`, this.buildOptions(opts));
55
- getBasePath(entity) {
56
- return `${this.basePath}/${(this.defaults.entityPath ?? entityPath)(entity)}`;
57
- }
58
- read(path, q, opts) {
59
- if (this.defaults.readMethod === 'QUERY') {
60
- return httpQuery(path, q ?? {}, this.buildOptions(opts));
61
- }
62
- return get(`${path}${stringifyQuery(q)}`, this.buildOptions(opts));
63
- }
64
- buildOptions(opts) {
65
- if (!this.defaults.headers && !opts?.headers) {
66
- return opts;
67
- }
68
- return { ...opts, headers: { ...this.defaults.headers, ...opts?.headers } };
69
- }
70
- }
@@ -1,27 +0,0 @@
1
- import type { RequestErrorResponse } from '../../http/contract.js';
2
- export type RequestOptions = {
3
- silent?: boolean;
4
- /**
5
- * extra headers merged over the defaults (e.g. `{ Authorization: 'Bearer ...' }`).
6
- */
7
- headers?: Record<string, string>;
8
- /**
9
- * abort/timeout control, e.g. `AbortSignal.timeout(120_000)` for long-running calls.
10
- */
11
- signal?: AbortSignal;
12
- };
13
- export type RequestFindOptions = RequestOptions & {
14
- count?: boolean;
15
- };
16
- type RequestBaseNotification = {
17
- readonly opts?: RequestOptions;
18
- };
19
- type RequestSuccessNotification = {
20
- readonly phase: 'start' | 'success' | 'complete';
21
- } & RequestBaseNotification;
22
- type RequestErrorNotification = {
23
- readonly phase: 'error';
24
- } & RequestErrorResponse & RequestBaseNotification;
25
- export type RequestNotification = RequestSuccessNotification | RequestErrorNotification;
26
- export type RequestCallback = (msg: RequestNotification) => void;
27
- export {};
@@ -1,11 +0,0 @@
1
- import { type NextFunction, type Request, type Response, type Router } from 'express';
2
- import { type RequestHandlerOptions } from '../http/handler.js';
3
- export type MiddlewareOptions = RequestHandlerOptions<Request>;
4
- /**
5
- * Express adapter over the framework-agnostic {@link createRequestHandler}.
6
- * Unknown entities and routes fall through via `next()` so the middleware
7
- * composes with custom routes; errors go to `next(err)` so user error
8
- * middleware (e.g. {@link errorHandler}) keeps working.
9
- */
10
- export declare function querierMiddleware(opts: MiddlewareOptions): Router;
11
- export declare function errorHandler(err: unknown, _req: Request, res: Response, _next: NextFunction): void;
@@ -1,39 +0,0 @@
1
- import { Router as expressRouter } from 'express';
2
- import { toErrorResponse } from '../http/contract.js';
3
- import { createRequestHandler } from '../http/handler.js';
4
- /**
5
- * Express adapter over the framework-agnostic {@link createRequestHandler}.
6
- * Unknown entities and routes fall through via `next()` so the middleware
7
- * composes with custom routes; errors go to `next(err)` so user error
8
- * middleware (e.g. {@link errorHandler}) keeps working.
9
- */
10
- export function querierMiddleware(opts) {
11
- const handle = createRequestHandler(opts);
12
- const router = expressRouter();
13
- router.all('/:entityPath{/:subPath}', async (req, res, next) => {
14
- const pending = handle({
15
- method: req.method,
16
- entityPath: req.params.entityPath,
17
- subPath: req.params.subPath,
18
- query: req.query,
19
- body: req.body,
20
- context: req,
21
- });
22
- if (!pending) {
23
- next();
24
- return;
25
- }
26
- try {
27
- const { status, body } = await pending;
28
- res.status(status).json(body);
29
- }
30
- catch (err) {
31
- next(err);
32
- }
33
- });
34
- return router;
35
- }
36
- export function errorHandler(err, _req, res, _next) {
37
- const { status, body } = toErrorResponse(err);
38
- res.status(status).json(body);
39
- }
@@ -1,113 +0,0 @@
1
- import type { AbstractType } from '../type/index.js';
2
- /** What a route answers in `data`, which says how its values cross JSON: rows, a page of them, keys, or a count. */
3
- export type WireAnswer = 'rows' | 'page' | 'ids' | 'count';
4
- /**
5
- * Single source of truth for the CRUD-over-HTTP surface, shared by server adapters and the browser client.
6
- * Keys are constrained to {@link UniversalQuerier} method names, so renaming a querier method
7
- * (or routing a non-existent one) is a compile error.
8
- */
9
- export declare const CRUD_ROUTES: {
10
- readonly findMany: {
11
- readonly method: 'GET';
12
- readonly path: '';
13
- readonly answers: 'rows';
14
- };
15
- readonly findManyPage: {
16
- readonly method: 'GET';
17
- readonly path: '/page';
18
- readonly answers: 'page';
19
- };
20
- readonly findOne: {
21
- readonly method: 'GET';
22
- readonly path: '/one';
23
- readonly answers: 'rows';
24
- };
25
- readonly count: {
26
- readonly method: 'GET';
27
- readonly path: '/count';
28
- readonly answers: 'count';
29
- };
30
- readonly findOneById: {
31
- readonly method: 'GET';
32
- readonly path: '/:id';
33
- readonly answers: 'rows';
34
- };
35
- readonly insertOne: {
36
- readonly method: 'POST';
37
- readonly path: '';
38
- readonly answers: 'ids';
39
- };
40
- readonly insertMany: {
41
- readonly method: 'POST';
42
- readonly path: '/many';
43
- readonly answers: 'ids';
44
- };
45
- readonly saveOne: {
46
- readonly method: 'PUT';
47
- readonly path: '';
48
- readonly answers: 'ids';
49
- };
50
- readonly saveMany: {
51
- readonly method: 'PUT';
52
- readonly path: '/many';
53
- readonly answers: 'ids';
54
- };
55
- readonly updateMany: {
56
- readonly method: 'PATCH';
57
- readonly path: '';
58
- readonly answers: 'count';
59
- };
60
- readonly updateOneById: {
61
- readonly method: 'PATCH';
62
- readonly path: '/:id';
63
- readonly answers: 'count';
64
- };
65
- readonly deleteOneById: {
66
- readonly method: 'DELETE';
67
- readonly path: '/:id';
68
- readonly answers: 'count';
69
- };
70
- readonly deleteMany: {
71
- readonly method: 'DELETE';
72
- readonly path: '';
73
- readonly answers: 'count';
74
- };
75
- };
76
- export type CrudOperation = keyof typeof CRUD_ROUTES;
77
- export type CrudRoute = (typeof CRUD_ROUTES)[CrudOperation];
78
- /**
79
- * `QUERY` (RFC 10008) is an alternate transport for the read operations: same semantics as the
80
- * GET routes, but the JSON query travels in the request body instead of the query string,
81
- * avoiding URL-length limits for large queries.
82
- */
83
- export type HttpMethod = CrudRoute['method'] | 'QUERY';
84
- /**
85
- * URL segment for an entity, e.g. `entityPath(UserProfile) === 'user-profile'`.
86
- */
87
- export declare function entityPath<E>(entity: AbstractType<E>): string;
88
- export type RouteMatch = {
89
- readonly op: CrudOperation;
90
- /**
91
- * the resolved transport method - differs from the op's canonical route method for QUERY.
92
- */
93
- readonly method: HttpMethod;
94
- readonly id?: string;
95
- };
96
- /**
97
- * Resolve a (method, sub-path) pair to a CRUD operation. Literal sub-paths win over `:id`.
98
- */
99
- export declare function matchRoute(method: string, subPath: string | undefined): RouteMatch | undefined;
100
- export type RequestErrorResponse = {
101
- readonly error: {
102
- readonly message: string;
103
- readonly code: number;
104
- };
105
- };
106
- /**
107
- * Map a thrown error to the wire error envelope. Honors a numeric `status` on the error
108
- * (e.g. hooks throwing 403), then a constraint violation (409/400), defaults to 500; `code` mirrors the HTTP status.
109
- */
110
- export declare function toErrorResponse(err: unknown): {
111
- status: number;
112
- body: RequestErrorResponse;
113
- };