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.
- package/README.md +2 -2
- package/dist/browser/http/httpTransport.d.ts +29 -0
- package/dist/browser/http/httpTransport.js +59 -0
- package/dist/browser/http/index.d.ts +1 -2
- package/dist/browser/http/index.js +1 -2
- package/dist/browser/index.d.ts +1 -0
- package/dist/browser/querier/clientQuerier.d.ts +7 -0
- package/dist/browser/querier/clientQuerier.js +43 -0
- package/dist/browser/querier/index.d.ts +2 -1
- package/dist/browser/querier/index.js +2 -1
- package/dist/browser/querier/queryOptions.d.ts +23 -0
- package/dist/browser/querier/queryOptions.js +35 -0
- package/dist/browser/type/clientQuerier.d.ts +10 -11
- package/dist/browser/type/index.d.ts +1 -1
- package/dist/browser/type/index.js +1 -1
- package/dist/browser/type/transport.d.ts +13 -0
- package/dist/dialect/abstractDialect.d.ts +2 -2
- package/dist/entity/columnOptionsBuilder.d.ts +2 -1
- package/dist/entity/columnOptionsBuilder.js +3 -0
- package/dist/entity/metadata/definition.js +3 -0
- package/dist/express/index.d.ts +1 -1
- package/dist/express/index.js +1 -1
- package/dist/express/router.d.ts +8 -0
- package/dist/express/router.js +50 -0
- package/dist/http/api.d.ts +36 -0
- package/dist/http/api.js +140 -0
- package/dist/http/apiCall.d.ts +59 -0
- package/dist/http/apiCall.js +52 -0
- package/dist/http/errors.d.ts +20 -0
- package/dist/http/errors.js +27 -0
- package/dist/http/exposure.d.ts +38 -0
- package/dist/http/exposure.js +157 -0
- package/dist/http/handler.d.ts +23 -88
- package/dist/http/handler.js +42 -158
- package/dist/http/index.d.ts +8 -4
- package/dist/http/index.js +6 -3
- package/dist/http/route.d.ts +34 -0
- package/dist/http/route.js +82 -0
- package/dist/http/wireCall.d.ts +115 -0
- package/dist/http/wireCall.js +126 -0
- package/dist/http/wireQuery.d.ts +8 -0
- package/dist/http/wireQuery.js +51 -0
- package/dist/http/wireRow.d.ts +4 -2
- package/dist/http/wireRow.js +15 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/migrate/codegen/entityCodeGenerator.js +2 -2
- package/dist/mongodb/mongoDialect.d.ts +6 -6
- package/dist/mongodb/mongodbQuerier.d.ts +8 -8
- package/dist/nestjs/uqlContextInterceptor.d.ts +3 -3
- package/dist/nestjs/uqlContextInterceptor.js +7 -7
- package/dist/nestjs/uqlModule.d.ts +5 -11
- package/dist/nestjs/uqlModule.js +10 -15
- package/dist/querier/abstractQuerier.d.ts +8 -8
- package/dist/querier/abstractQuerier.js +15 -8
- package/dist/querier/abstractSqlQuerier.d.ts +8 -8
- package/dist/querier/keyset.d.ts +15 -0
- package/dist/querier/keyset.js +16 -11
- package/dist/type/column.d.ts +9 -1
- package/dist/type/definedEntity.d.ts +3 -0
- package/dist/type/entity.d.ts +14 -4
- package/dist/type/querier.d.ts +2 -2
- package/dist/type/query.d.ts +24 -4
- package/dist/type/universalQuerier.d.ts +17 -18
- package/dist/type/wire.d.ts +1 -31
- package/dist/util/dialect.util.d.ts +10 -10
- package/dist/util/dialect.util.js +20 -12
- package/dist/util/field.util.d.ts +7 -1
- package/dist/util/field.util.js +9 -2
- package/dist/util/fieldOption.util.js +2 -0
- package/dist/util/uqlError.d.ts +27 -1
- package/dist/util/uqlError.js +43 -0
- package/package.json +1 -1
- package/skills/uql-orm/SKILL.md +32 -4
- package/dist/browser/http/bus.d.ts +0 -3
- package/dist/browser/http/bus.js +0 -12
- package/dist/browser/http/http.d.ts +0 -20
- package/dist/browser/http/http.js +0 -67
- package/dist/browser/querier/httpQuerier.d.ts +0 -46
- package/dist/browser/querier/httpQuerier.js +0 -70
- package/dist/browser/type/request.d.ts +0 -27
- package/dist/express/querierMiddleware.d.ts +0 -11
- package/dist/express/querierMiddleware.js +0 -39
- package/dist/http/contract.d.ts +0 -113
- package/dist/http/contract.js +0 -83
- package/dist/http/fetchHandler.d.ts +0 -13
- package/dist/http/fetchHandler.js +0 -63
- package/dist/http/query.d.ts +0 -26
- package/dist/http/query.js +0 -119
- /package/dist/browser/type/{request.js → transport.js} +0 -0
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { EntityWrite, Query, Type, UpdateWrite } from '../type/index.js';
|
|
2
|
+
import type { API_OPS, ApiOp } from './wireCall.js';
|
|
3
|
+
import type { WireCursors } from './wireQuery.js';
|
|
4
|
+
/** Each kind of payload an op writes, as the entity holds it. */
|
|
5
|
+
type Payloads<E> = {
|
|
6
|
+
readonly row: EntityWrite<E>;
|
|
7
|
+
readonly rows: readonly EntityWrite<E>[];
|
|
8
|
+
readonly changes: UpdateWrite<E>;
|
|
9
|
+
};
|
|
10
|
+
type PayloadOf<E, Op extends ApiOp> = (typeof API_OPS)[Op] extends {
|
|
11
|
+
readonly writes: infer W extends keyof Payloads<E>;
|
|
12
|
+
} ? {
|
|
13
|
+
readonly payload: Payloads<E>[W];
|
|
14
|
+
} : {
|
|
15
|
+
readonly payload?: undefined;
|
|
16
|
+
};
|
|
17
|
+
/** The row an op by id addresses, which no other op names. */
|
|
18
|
+
type IdOf<Op extends ApiOp> = (typeof API_OPS)[Op] extends {
|
|
19
|
+
readonly byId: true;
|
|
20
|
+
} ? {
|
|
21
|
+
readonly id: string | number;
|
|
22
|
+
} : {
|
|
23
|
+
readonly id?: undefined;
|
|
24
|
+
};
|
|
25
|
+
type CallOf<E, Op extends ApiOp> = {
|
|
26
|
+
readonly entity: Type<E>;
|
|
27
|
+
readonly op: Op;
|
|
28
|
+
readonly query: Query<E> & WireCursors;
|
|
29
|
+
readonly hardDelete: boolean;
|
|
30
|
+
} & IdOf<Op> & PayloadOf<E, Op>;
|
|
31
|
+
/**
|
|
32
|
+
* A call as the API runs it, decoded and checked, for a middleware to read or reshape: one member per op, so
|
|
33
|
+
* narrowing on `op` types the payload (`call.op === 'insertOne'` makes it a row).
|
|
34
|
+
*/
|
|
35
|
+
export type ApiCall<E, Op extends ApiOp = ApiOp> = Op extends ApiOp ? CallOf<E, Op> : never;
|
|
36
|
+
/** What a middleware hands on to: the next middleware, the querier last. */
|
|
37
|
+
export type ApiNext<E> = (call: ApiCall<E>) => Promise<unknown>;
|
|
38
|
+
/**
|
|
39
|
+
* Runs around each call to one entity: reshape it before `next`, abort by throwing (a `UqlRequestError` answers its
|
|
40
|
+
* status), or reshape what `next` resolves to, the result as the entity holds it. `context` is the transport's.
|
|
41
|
+
*/
|
|
42
|
+
export type EntityMiddleware<E, Ctx = unknown> = (call: ApiCall<E>, context: Ctx, next: ApiNext<E>) => Promise<unknown>;
|
|
43
|
+
/** A middleware run around a call to any entity, for what reads no entity's members: logging, timing, a refusal. */
|
|
44
|
+
export type ApiMiddleware<Ctx = unknown> = <E extends object>(call: ApiCall<E>, context: Ctx, next: ApiNext<E>) => Promise<unknown>;
|
|
45
|
+
/** Whether `call` is a call to `entity`, for a middleware typed by it. */
|
|
46
|
+
export declare function isCallOf<E extends object>(entity: Type<E>, call: ApiCall<object>): call is ApiCall<E>;
|
|
47
|
+
/** Runs `use` around `last`, first to last. */
|
|
48
|
+
export declare function chain<E, Ctx>(use: readonly EntityMiddleware<E, Ctx>[], context: Ctx, last: ApiNext<E>): ApiNext<E>;
|
|
49
|
+
type Decoded<E> = {
|
|
50
|
+
readonly entity: Type<E>;
|
|
51
|
+
readonly op: ApiOp;
|
|
52
|
+
readonly id?: string | number;
|
|
53
|
+
readonly query: Query<E> & WireCursors;
|
|
54
|
+
readonly payload: unknown;
|
|
55
|
+
readonly hardDelete: boolean;
|
|
56
|
+
};
|
|
57
|
+
/** The call `decoded` asks for, the id and the payload's shape its op needs checked. */
|
|
58
|
+
export declare function callOf<E extends object>({ op, id, payload, ...rest }: Decoded<E>): ApiCall<E>;
|
|
59
|
+
export {};
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { isRecord } from '../util/object.util.js';
|
|
2
|
+
import { UqlUsageError } from '../util/uqlError.js';
|
|
3
|
+
/** Whether `call` is a call to `entity`, for a middleware typed by it. */
|
|
4
|
+
export function isCallOf(entity, call) {
|
|
5
|
+
return call.entity === entity;
|
|
6
|
+
}
|
|
7
|
+
/** Runs `use` around `last`, first to last. */
|
|
8
|
+
export function chain(use, context, last) {
|
|
9
|
+
return use.reduceRight((next, middleware) => (call) => middleware(call, context, next), last);
|
|
10
|
+
}
|
|
11
|
+
/** The call `decoded` asks for, the id and the payload's shape its op needs checked. */
|
|
12
|
+
export function callOf({ op, id, payload, ...rest }) {
|
|
13
|
+
switch (op) {
|
|
14
|
+
case 'insertOne':
|
|
15
|
+
case 'saveOne':
|
|
16
|
+
return { ...rest, op, payload: recordOf(payload) };
|
|
17
|
+
case 'insertMany':
|
|
18
|
+
case 'saveMany':
|
|
19
|
+
return { ...rest, op, payload: rowsOf(payload) };
|
|
20
|
+
case 'updateMany':
|
|
21
|
+
return { ...rest, op, payload: recordOf(payload) };
|
|
22
|
+
case 'updateOneById':
|
|
23
|
+
return { ...rest, op, id: idOf(op, id), payload: recordOf(payload) };
|
|
24
|
+
case 'findOneById':
|
|
25
|
+
case 'deleteOneById':
|
|
26
|
+
return { ...rest, op, id: idOf(op, id) };
|
|
27
|
+
default:
|
|
28
|
+
return { ...rest, op };
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function idOf(op, id) {
|
|
32
|
+
if (id === undefined) {
|
|
33
|
+
throw new UqlUsageError(`'${op}' names the row it addresses in 'id'`, { path: ['id'] });
|
|
34
|
+
}
|
|
35
|
+
return id;
|
|
36
|
+
}
|
|
37
|
+
/** Whether `value` is a row, or changes to one, as JSON carries it: its fields are the querier's to check. */
|
|
38
|
+
function isRecordOf(value) {
|
|
39
|
+
return isRecord(value);
|
|
40
|
+
}
|
|
41
|
+
function recordOf(payload) {
|
|
42
|
+
if (!isRecordOf(payload)) {
|
|
43
|
+
throw new UqlUsageError('the payload must be a JSON object', { path: ['payload'] });
|
|
44
|
+
}
|
|
45
|
+
return payload;
|
|
46
|
+
}
|
|
47
|
+
function rowsOf(payload) {
|
|
48
|
+
if (!Array.isArray(payload) || !payload.every((row) => isRecordOf(row))) {
|
|
49
|
+
throw new UqlUsageError('the payload must be a JSON array of rows', { path: ['payload'] });
|
|
50
|
+
}
|
|
51
|
+
return payload;
|
|
52
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type QueryErrorKind, type UqlErrorPath } from '../util/uqlError.js';
|
|
2
|
+
/** A failure as JSON carries it: the HTTP status, what kind of failure it is, and where in the call it sits. */
|
|
3
|
+
export type RequestFailure = {
|
|
4
|
+
readonly message: string;
|
|
5
|
+
readonly status: number;
|
|
6
|
+
readonly kind?: QueryErrorKind;
|
|
7
|
+
readonly path?: UqlErrorPath;
|
|
8
|
+
};
|
|
9
|
+
export type RequestErrorResponse = {
|
|
10
|
+
readonly error: RequestFailure;
|
|
11
|
+
};
|
|
12
|
+
/** What a transport answers: a status, a JSON body, and any header it calls for. */
|
|
13
|
+
export type HandlerResponse<Body = unknown> = {
|
|
14
|
+
readonly status: number;
|
|
15
|
+
readonly body: Body;
|
|
16
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
17
|
+
};
|
|
18
|
+
export type ErrorResponse = HandlerResponse<RequestErrorResponse>;
|
|
19
|
+
/** A thrown error as the status, `{ error }` body and headers a transport answers with, a `UqlError`'s own headers included. */
|
|
20
|
+
export declare function toErrorResponse(err: unknown): ErrorResponse;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { queryErrorKind } from '../querier/queryError.js';
|
|
2
|
+
import { UqlError } from '../util/uqlError.js';
|
|
3
|
+
/** Generic on purpose: a driver's message names tables and constraints, and Postgres echoes the value. */
|
|
4
|
+
const KIND_ERRORS = new Map([
|
|
5
|
+
['uniqueViolation', 'Conflict', 409],
|
|
6
|
+
['foreignKeyViolation', 'Conflict', 409],
|
|
7
|
+
['notNullViolation', 'Bad Request', 400],
|
|
8
|
+
['checkViolation', 'Bad Request', 400],
|
|
9
|
+
['retryable', 'Service Unavailable', 503],
|
|
10
|
+
].map(([kind, message, status]) => [kind, { message, status, kind }]));
|
|
11
|
+
const INTERNAL_ERROR = { message: 'Internal Server Error', status: 500 };
|
|
12
|
+
/**
|
|
13
|
+
* `err` as a client may see it: a `UqlError` whole, anything else by its kind alone, generically. A `status` on any
|
|
14
|
+
* other error is not taken: an HTTP driver's (libSQL's) comes with a message naming tables.
|
|
15
|
+
*/
|
|
16
|
+
function failureOf(err) {
|
|
17
|
+
if (err instanceof UqlError) {
|
|
18
|
+
return { message: err.message, status: err.status, kind: err.kind, ...(err.path && { path: err.path }) };
|
|
19
|
+
}
|
|
20
|
+
return KIND_ERRORS.get(queryErrorKind(err)) ?? INTERNAL_ERROR;
|
|
21
|
+
}
|
|
22
|
+
/** A thrown error as the status, `{ error }` body and headers a transport answers with, a `UqlError`'s own headers included. */
|
|
23
|
+
export function toErrorResponse(err) {
|
|
24
|
+
const error = failureOf(err);
|
|
25
|
+
const headers = err instanceof UqlError ? err.headers : undefined;
|
|
26
|
+
return { status: error.status, body: { error }, ...(headers && { headers }) };
|
|
27
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { AbstractType, EntityMeta, Type } from '../type/index.js';
|
|
2
|
+
import { type EntityMiddleware } from './apiCall.js';
|
|
3
|
+
import { type ApiOp } from './wireCall.js';
|
|
4
|
+
/** How an API serves an entity beyond what its definition's `wire` states: middleware of its own. */
|
|
5
|
+
export type ServeOptions<E, Ctx = unknown> = {
|
|
6
|
+
readonly use: readonly EntityMiddleware<E, Ctx>[];
|
|
7
|
+
};
|
|
8
|
+
/** An entity an API serves with {@link ServeOptions}, as `include` lists it beside an entity served as it is. */
|
|
9
|
+
export type Served<E, Ctx = unknown> = {
|
|
10
|
+
readonly entity: Type<E>;
|
|
11
|
+
/** Its middleware, run on its own calls alone, after the API's. */
|
|
12
|
+
readonly around: EntityMiddleware<object, Ctx>;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Serve `entity` in an API's `include` with middleware of its own in `use`: typed by the entity, so it reads and
|
|
16
|
+
* writes its members, and run on the entity's own calls alone.
|
|
17
|
+
*/
|
|
18
|
+
export declare function serve<E extends object, Ctx = unknown>(entity: Type<E>, { use }: ServeOptions<E, Ctx>): Served<E, Ctx>;
|
|
19
|
+
/** The entities an API serves, each to its middleware. */
|
|
20
|
+
export type ServedEntities = ReadonlyMap<AbstractType<object>, unknown>;
|
|
21
|
+
/** An `include` item as the entity it serves and that entity's middleware. */
|
|
22
|
+
export declare function servedEntry<Ctx>(item: Type<object> | Served<object, Ctx>): [Type<object>, EntityMiddleware<object, Ctx> | undefined];
|
|
23
|
+
/**
|
|
24
|
+
* Refuses what a client's call reaches that the API does not expose: the op on its entity, a relation to an entity
|
|
25
|
+
* it does not serve, and a member at any depth of the query (read) or the rows it writes. Every `$` clause holds
|
|
26
|
+
* keys of the entity it sits on.
|
|
27
|
+
*/
|
|
28
|
+
export declare function assertExposed<E extends object>(meta: EntityMeta<E>, op: ApiOp, query: object, payload: unknown, served: ServedEntities): void;
|
|
29
|
+
/**
|
|
30
|
+
* `query` reading no field whose `wire` keeps it from being read, at every depth its `$populate` reaches. Run on a
|
|
31
|
+
* call {@link assertExposed} took, which names none of them: a projection naming the fields it reads stays as it is.
|
|
32
|
+
*/
|
|
33
|
+
export declare function hideUnreadable<E extends object, Q extends Readonly<Record<string, unknown>>>(meta: EntityMeta<E>, query: Q): Q;
|
|
34
|
+
/**
|
|
35
|
+
* The query a client's call runs with: refused where it reaches what the API does not expose, and, on a read
|
|
36
|
+
* answering rows, leaving out what it may not read.
|
|
37
|
+
*/
|
|
38
|
+
export declare function exposedQuery<E extends object, Q extends Readonly<Record<string, unknown>>>(meta: EntityMeta<E>, op: ApiOp, query: Q, payload: unknown, served: ServedEntities): Q;
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { getMeta } from '../entity/metadata/definition.js';
|
|
2
|
+
import { isCascadable } from '../util/dialect.util.js';
|
|
3
|
+
import { fieldKeys, isFieldKey, isWrittenOn } from '../util/field.util.js';
|
|
4
|
+
import { isPlainObject, isRecord } from '../util/object.util.js';
|
|
5
|
+
import { UqlSecurityError } from '../util/uqlError.js';
|
|
6
|
+
import { chain, isCallOf } from './apiCall.js';
|
|
7
|
+
import { API_OPS } from './wireCall.js';
|
|
8
|
+
/**
|
|
9
|
+
* Serve `entity` in an API's `include` with middleware of its own in `use`: typed by the entity, so it reads and
|
|
10
|
+
* writes its members, and run on the entity's own calls alone.
|
|
11
|
+
*/
|
|
12
|
+
export function serve(entity, { use }) {
|
|
13
|
+
return {
|
|
14
|
+
entity,
|
|
15
|
+
around: (call, context, next) => (isCallOf(entity, call) ? chain(use, context, next)(call) : next(call)),
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/** An `include` item as the entity it serves and that entity's middleware. */
|
|
19
|
+
export function servedEntry(item) {
|
|
20
|
+
return typeof item === 'function' ? [item, undefined] : [item.entity, item.around];
|
|
21
|
+
}
|
|
22
|
+
const PAST = {
|
|
23
|
+
read: 'read',
|
|
24
|
+
insert: 'inserted',
|
|
25
|
+
update: 'updated',
|
|
26
|
+
delete: 'deleted',
|
|
27
|
+
};
|
|
28
|
+
/** What a save does to the rows it writes, as a cascade does to the rows a write nests: inserts new ones, updates listed ones. */
|
|
29
|
+
const SAVED = ['insert', 'update'];
|
|
30
|
+
/** What `op` does to the rows it writes, a save doing either. */
|
|
31
|
+
function writesOf(op) {
|
|
32
|
+
const { access } = API_OPS[op];
|
|
33
|
+
return access === 'save' ? SAVED : access === 'insert' || access === 'update' ? [access] : [];
|
|
34
|
+
}
|
|
35
|
+
/** The relation `key` names on `meta`, a client's key included: an own key alone, never one of `Object`'s. */
|
|
36
|
+
function relationAt(meta, key) {
|
|
37
|
+
const relations = meta.relations;
|
|
38
|
+
return Object.hasOwn(relations, key) ? relations[key] : undefined;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Refuses what a client's call reaches that the API does not expose: the op on its entity, a relation to an entity
|
|
42
|
+
* it does not serve, and a member at any depth of the query (read) or the rows it writes. Every `$` clause holds
|
|
43
|
+
* keys of the entity it sits on.
|
|
44
|
+
*/
|
|
45
|
+
export function assertExposed(meta, op, query, payload, served) {
|
|
46
|
+
const { access } = API_OPS[op];
|
|
47
|
+
const writes = writesOf(op);
|
|
48
|
+
assertOps(meta, access === 'save' ? writes : [access], served);
|
|
49
|
+
walk(meta, query, ['read'], served, ['query']);
|
|
50
|
+
walk(meta, payload, writes, served, ['payload']);
|
|
51
|
+
}
|
|
52
|
+
function assertOps(meta, needs, served, path) {
|
|
53
|
+
const missing = needs.find((need) => !served.has(meta.entity) || !takes(meta.wire, need));
|
|
54
|
+
if (missing) {
|
|
55
|
+
throw new UqlSecurityError(`'${meta.entity.name}' cannot be ${PAST[missing]} through this API`, { path });
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/** The members `path` names, as a refusal reads them: `author.email`, not its clauses and indexes. */
|
|
59
|
+
function membersOf(path) {
|
|
60
|
+
return path
|
|
61
|
+
.slice(1)
|
|
62
|
+
.filter((key) => typeof key === 'string' && !key.startsWith('$'))
|
|
63
|
+
.join('.');
|
|
64
|
+
}
|
|
65
|
+
function walk(meta, sent, needs, served, path) {
|
|
66
|
+
if (Array.isArray(sent)) {
|
|
67
|
+
sent.forEach((item, index) => walk(meta, item, needs, served, [...path, index]));
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (!isRecord(sent)) {
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const writing = !needs.includes('read');
|
|
74
|
+
for (const [key, value] of Object.entries(sent)) {
|
|
75
|
+
if (key.startsWith('$')) {
|
|
76
|
+
walk(meta, value, needs, served, [...path, key]);
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
// A JSON path (`kind.plan`) reads the member it starts at.
|
|
80
|
+
const [member] = key.split('.');
|
|
81
|
+
const relation = relationAt(meta, member);
|
|
82
|
+
const field = !relation && isFieldKey(meta, member) ? meta.fields[member] : undefined;
|
|
83
|
+
const declared = relation ?? field;
|
|
84
|
+
if (!declared) {
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const at = [...path, key];
|
|
88
|
+
const missing = needs.find((need) => !takes(declared.wire, need)) ?? (field && dropped(field, needs));
|
|
89
|
+
if (missing) {
|
|
90
|
+
throw new UqlSecurityError(`'${membersOf(at)}' cannot be ${PAST[missing]} through this API`, { path: at });
|
|
91
|
+
}
|
|
92
|
+
// The querier writes a relation a payload names only where it cascades, saving its rows whatever the op.
|
|
93
|
+
if (relation && (!writing || isCascadable('persist', relation.cascade))) {
|
|
94
|
+
const target = getMeta(relation.entity());
|
|
95
|
+
if (!served.has(target.entity)) {
|
|
96
|
+
throw new UqlSecurityError(`'${membersOf(at)}' reaches '${target.entity.name}', which this API does not serve`, { path: at });
|
|
97
|
+
}
|
|
98
|
+
const nested = writing ? SAVED : needs;
|
|
99
|
+
// An update of a to-many replaces its rows: those it stops listing are deleted.
|
|
100
|
+
const replaces = relation.cardinality === '1m' && needs.includes('update');
|
|
101
|
+
assertOps(target, replaces ? [...nested, 'delete'] : nested, served, at);
|
|
102
|
+
walk(target, value, nested, served, at);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/** Whether a `wire` lets a client do `need`: everything where it states none. */
|
|
107
|
+
function takes(wire, need) {
|
|
108
|
+
return wire === undefined || (wire !== false && wire.includes(need));
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* What a write is refused for where the querier would write `field` on none of `needs`, rather than drop it unseen: a
|
|
112
|
+
* computed value, or an `updatable(false)` one in an update. A save or a cascade may insert, which writes the latter.
|
|
113
|
+
*/
|
|
114
|
+
function dropped(field, needs) {
|
|
115
|
+
const writes = (need) => need === 'read' || isWrittenOn(field, need === 'insert' ? 'onInsert' : 'onUpdate');
|
|
116
|
+
return needs.some(writes) ? undefined : needs[0];
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* `query` reading no field whose `wire` keeps it from being read, at every depth its `$populate` reaches. Run on a
|
|
120
|
+
* call {@link assertExposed} took, which names none of them: a projection naming the fields it reads stays as it is.
|
|
121
|
+
*/
|
|
122
|
+
export function hideUnreadable(meta, query) {
|
|
123
|
+
const hidden = fieldKeys(meta, (field) => !takes(field.wire, 'read'));
|
|
124
|
+
const select = query['$select'];
|
|
125
|
+
const leavesOut = select === undefined || (isPlainObject(select) && Object.values(select).every((value) => !value));
|
|
126
|
+
const $select = hidden.length && leavesOut
|
|
127
|
+
? { ...(isPlainObject(select) && select), ...Object.fromEntries(hidden.map((key) => [key, false])) }
|
|
128
|
+
: select;
|
|
129
|
+
const $populate = isPlainObject(query['$populate']) ? populateOf(meta, query['$populate']) : query['$populate'];
|
|
130
|
+
if ($select === select && $populate === query['$populate']) {
|
|
131
|
+
return query;
|
|
132
|
+
}
|
|
133
|
+
return { ...query, ...($select !== undefined && { $select }), ...($populate !== undefined && { $populate }) };
|
|
134
|
+
}
|
|
135
|
+
function populateOf(meta, populate) {
|
|
136
|
+
let changed = false;
|
|
137
|
+
const entries = Object.entries(populate).map(([key, nested]) => {
|
|
138
|
+
const relation = relationAt(meta, key);
|
|
139
|
+
if (!relation || !nested) {
|
|
140
|
+
return [key, nested];
|
|
141
|
+
}
|
|
142
|
+
const read = hideUnreadable(getMeta(relation.entity()), isPlainObject(nested) ? nested : {});
|
|
143
|
+
const hid = isPlainObject(nested) ? read !== nested : Object.keys(read).length > 0;
|
|
144
|
+
changed ||= hid;
|
|
145
|
+
return [key, hid ? read : nested];
|
|
146
|
+
});
|
|
147
|
+
return changed ? Object.fromEntries(entries) : populate;
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* The query a client's call runs with: refused where it reaches what the API does not expose, and, on a read
|
|
151
|
+
* answering rows, leaving out what it may not read.
|
|
152
|
+
*/
|
|
153
|
+
export function exposedQuery(meta, op, query, payload, served) {
|
|
154
|
+
assertExposed(meta, op, query, payload, served);
|
|
155
|
+
const { access, answers } = API_OPS[op];
|
|
156
|
+
return access === 'read' && answers !== 'count' ? hideUnreadable(meta, query) : query;
|
|
157
|
+
}
|
package/dist/http/handler.d.ts
CHANGED
|
@@ -1,92 +1,27 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import { type
|
|
3
|
-
import { type
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
readonly method: string;
|
|
10
|
-
readonly entityPath: string;
|
|
11
|
-
readonly subPath?: string;
|
|
12
|
-
/**
|
|
13
|
-
* raw query-string entries; JSON values may still be stringified.
|
|
14
|
-
*/
|
|
15
|
-
readonly query?: Record<string, unknown>;
|
|
16
|
-
/**
|
|
17
|
-
* parsed JSON body.
|
|
18
|
-
*/
|
|
19
|
-
readonly body?: unknown;
|
|
20
|
-
/**
|
|
21
|
-
* adapter-supplied request context (express `req`, fetch `Request`, ...), passed through to hooks.
|
|
22
|
-
*/
|
|
23
|
-
readonly context: Ctx;
|
|
24
|
-
};
|
|
25
|
-
export type HandlerResponse = {
|
|
26
|
-
readonly status: number;
|
|
27
|
-
readonly body: unknown;
|
|
28
|
-
};
|
|
29
|
-
export type RequestHookContext<E extends object, Ctx = unknown> = {
|
|
30
|
-
readonly meta: EntityMeta<E>;
|
|
31
|
-
readonly op: CrudOperation;
|
|
32
|
-
readonly method: HttpMethod;
|
|
33
|
-
/** The parsed query, to reshape in place. Scope rows with a `security` filter instead, which a client cannot override. */
|
|
34
|
-
query: Query<E> & WireFlags & WireCursors;
|
|
35
|
-
/**
|
|
36
|
-
* request payload - reassignable for sanitization or field injection.
|
|
37
|
-
*/
|
|
38
|
-
body?: unknown;
|
|
39
|
-
/**
|
|
40
|
-
* adapter-supplied request context - the auth/tenant source (e.g. `req.user`).
|
|
41
|
-
*/
|
|
1
|
+
import type { Api } from './api.js';
|
|
2
|
+
import { type HandlerResponse } from './errors.js';
|
|
3
|
+
import { type HttpRequest } from './route.js';
|
|
4
|
+
import type { ApiOp } from './wireCall.js';
|
|
5
|
+
/** A request to `/{entityPath}/{op}` as a framework adapter reduces it, with what `contextOf` and middleware get. */
|
|
6
|
+
export type HandlerRequest<Ctx = unknown> = Omit<HttpRequest, 'op'> & {
|
|
7
|
+
readonly op: string;
|
|
8
|
+
/** The adapter's own request (express `req`, fetch `Request`, ...): the auth and tenant source. */
|
|
42
9
|
readonly context: Ctx;
|
|
43
10
|
};
|
|
44
|
-
export type RequestHook<Ctx = unknown> = <E extends object>(ctx: RequestHookContext<E, Ctx>) => void | Promise<void>;
|
|
45
|
-
export type ResponseHook<Ctx = unknown> = <E extends object>(ctx: RequestHookContext<E, Ctx>, envelope: RequestSuccessResponse<unknown>) => void | Promise<void>;
|
|
46
|
-
export type RequestHandlerOptions<Ctx = unknown> = {
|
|
47
|
-
/**
|
|
48
|
-
* The entities served, and the only ones a request reaches, through a relation too: nothing is served
|
|
49
|
-
* by being defined, so an entity holding secrets (a session's token) stays off the wire unless named.
|
|
50
|
-
*/
|
|
51
|
-
include: readonly Type<object>[];
|
|
52
|
-
/** The URL segment an entity is addressed by, its kebab-cased class name by default; the browser client takes the same option. */
|
|
53
|
-
entityPath?: (entity: AbstractType<unknown>) => string;
|
|
54
|
-
/**
|
|
55
|
-
* Allow augment any kind of request before it runs. Hooks may be async
|
|
56
|
-
* and abort the request by throwing (a numeric `status` on the error is honored).
|
|
57
|
-
*/
|
|
58
|
-
pre?: RequestHook<Ctx>;
|
|
59
|
-
/**
|
|
60
|
-
* Allow augment a save request (POST | PUT | PATCH) before it runs.
|
|
61
|
-
*/
|
|
62
|
-
preSave?: RequestHook<Ctx>;
|
|
63
|
-
/**
|
|
64
|
-
* Allow augment a filter request (GET | DELETE) before it runs.
|
|
65
|
-
*/
|
|
66
|
-
preFilter?: RequestHook<Ctx>;
|
|
67
|
-
/**
|
|
68
|
-
* Shape the successful response before it is sent: strip sensitive fields,
|
|
69
|
-
* derive presentation fields, or coerce null data. Mutate `envelope.data` in place
|
|
70
|
-
* or reassign it. Runs after the operation (and after commit for writes).
|
|
71
|
-
*/
|
|
72
|
-
post?: ResponseHook<Ctx>;
|
|
73
|
-
/**
|
|
74
|
-
* Derive the ambient {@link UqlContext} (e.g. `{ tenantId, userId }`) from the adapter request.
|
|
75
|
-
* The whole request runs inside `withContext`, so parameterized/`security` filters are scoped
|
|
76
|
-
* automatically. Derive tenant/auth from a verified source (session, JWT) - never trust the client.
|
|
77
|
-
*/
|
|
78
|
-
getContext?: (context: Ctx) => UqlContext | undefined | Promise<UqlContext | undefined>;
|
|
79
|
-
/**
|
|
80
|
-
* The pool this handler runs on. A function is called per request, after `getContext`, with the
|
|
81
|
-
* adapter's request and the context that resolved from it - which is what lets one deployment
|
|
82
|
-
* serve a database per tenant, where a process-wide default could only serve one.
|
|
83
|
-
*/
|
|
84
|
-
pool: QuerierPool | ((context: Ctx, appContext: UqlContext) => QuerierPool | Promise<QuerierPool>);
|
|
85
|
-
};
|
|
86
11
|
/**
|
|
87
|
-
*
|
|
88
|
-
*
|
|
89
|
-
|
|
12
|
+
* Answers a request with a status and a JSON body, a failure included, or `undefined` for an entity or an op the API
|
|
13
|
+
* does not serve, so an adapter can fall through (express `next()`).
|
|
14
|
+
*/
|
|
15
|
+
export type RequestHandler<Ctx = unknown> = (req: HandlerRequest<Ctx>) => Promise<HandlerResponse | undefined>;
|
|
16
|
+
/** The API over HTTP for any framework: mount it on `{base}/:entityPath/:op`, e.g. `/api/v1/:entityPath/:op`. */
|
|
17
|
+
export declare function toRequestHandler<Ctx>(api: Api<Ctx>): RequestHandler<Ctx>;
|
|
18
|
+
/** Answers a request to an op the API serves (`api.serves`) with a status and a JSON body, a failure included. */
|
|
19
|
+
export declare function answerRequest<Ctx>(api: Api<Ctx>, { context, ...req }: HandlerRequest<Ctx> & {
|
|
20
|
+
readonly op: ApiOp;
|
|
21
|
+
}): Promise<HandlerResponse>;
|
|
22
|
+
/**
|
|
23
|
+
* The API as `(request: Request) => Promise<Response>`, for any fetch-native runtime (Hono, Next.js route handlers,
|
|
24
|
+
* Bun.serve, Cloudflare Workers, SvelteKit, Astro), handing the `Request` to the API as its context. Mount it on a
|
|
25
|
+
* catch-all under the API's base: it reads the last two segments of the path as the entity and the op.
|
|
90
26
|
*/
|
|
91
|
-
export
|
|
92
|
-
export declare function createRequestHandler<Ctx = unknown>(opts: RequestHandlerOptions<Ctx>): RequestHandler<Ctx>;
|
|
27
|
+
export declare function toFetchHandler(api: Api<Request>): (request: Request) => Promise<Response>;
|