uql-orm 0.112.0 → 0.113.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- 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/dialect/abstractSqlDialect.js +3 -3
- package/dist/dialect/jsonSql.js +2 -3
- package/dist/dialect/operators.js +4 -5
- 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 +136 -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 +54 -0
- package/dist/http/exposure.js +171 -0
- package/dist/http/handler.d.ts +23 -88
- package/dist/http/handler.js +42 -155
- 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 +20 -0
- package/dist/http/wireRow.js +170 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/migrate/introspection/mysqlIntrospector.d.ts +4 -1
- package/dist/migrate/introspection/mysqlIntrospector.js +12 -2
- package/dist/mongodb/mongoDialect.d.ts +6 -6
- package/dist/mongodb/mongoDialect.js +6 -6
- package/dist/mongodb/mongodbQuerier.d.ts +8 -8
- package/dist/mssql/mssqlDialect.js +2 -2
- 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/sqlite/localSqliteQuerierPool.d.ts +1 -1
- package/dist/type/column.d.ts +4 -1
- package/dist/type/querier.d.ts +2 -2
- package/dist/type/query.d.ts +18 -4
- package/dist/type/universalQuerier.d.ts +16 -16
- package/dist/type/wire.d.ts +1 -31
- package/dist/util/dialect.util.d.ts +9 -16
- package/dist/util/dialect.util.js +20 -26
- package/dist/util/field.util.d.ts +4 -1
- package/dist/util/field.util.js +5 -2
- package/dist/util/object.util.d.ts +5 -2
- package/dist/util/object.util.js +12 -15
- package/dist/util/query.util.js +3 -10
- package/dist/util/uqlError.d.ts +27 -1
- package/dist/util/uqlError.js +43 -0
- package/package.json +5 -10
- package/skills/uql-orm/SKILL.md +4 -1
- 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 -64
- package/dist/browser/type/request.d.ts +0 -27
- package/dist/browser/uql-browser.min.js +0 -4
- package/dist/browser/uql-browser.min.js.map +0 -19
- package/dist/express/querierMiddleware.d.ts +0 -11
- package/dist/express/querierMiddleware.js +0 -39
- package/dist/http/contract.d.ts +0 -98
- 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 -28
- package/dist/http/query.js +0 -119
- /package/dist/browser/type/{request.js → transport.js} +0 -0
package/dist/http/handler.js
CHANGED
|
@@ -1,166 +1,53 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
import { parseQueryParams } from './query.js';
|
|
8
|
-
/** `Company (crm.Company)`: the class, and the table it maps, which is what tells two apart. */
|
|
9
|
-
function tableOf(entity) {
|
|
10
|
-
const meta = getMeta(entity);
|
|
11
|
-
return `${entity.name} (${meta.schema ? `${meta.schema}.${meta.name}` : meta.name})`;
|
|
1
|
+
import { UqlRequestError } from '../util/uqlError.js';
|
|
2
|
+
import { toErrorResponse } from './errors.js';
|
|
3
|
+
import { decodeRequest, isJson } from './route.js';
|
|
4
|
+
/** The API over HTTP for any framework: mount it on `{base}/:entityPath/:op`, e.g. `/api/v1/:entityPath/:op`. */
|
|
5
|
+
export function toRequestHandler(api) {
|
|
6
|
+
return async ({ op, ...req }) => (api.serves(req.entityPath, op) ? answerRequest(api, { ...req, op }) : undefined);
|
|
12
7
|
}
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
if (!entities?.length) {
|
|
18
|
-
throw new UqlUsageError("name the entities the handler serves in 'include': it serves those alone");
|
|
8
|
+
/** Answers a request to an op the API serves (`api.serves`) with a status and a JSON body, a failure included. */
|
|
9
|
+
export async function answerRequest(api, { context, ...req }) {
|
|
10
|
+
try {
|
|
11
|
+
return { status: 200, body: { data: await api.call(decodeRequest(req), context) } };
|
|
19
12
|
}
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
const collisions = [...byPath].filter(([, clashing]) => clashing.length > 1);
|
|
23
|
-
if (collisions.length) {
|
|
24
|
-
const lines = collisions.map(([path, clashing]) => ` /${path} <- ${clashing.map(tableOf).join(', ')}`);
|
|
25
|
-
throw new UqlUsageError(`every entity below shares a route with another, so all but the first are unreachable:\n${lines.join('\n')}\n` +
|
|
26
|
-
"A route is the kebab-cased class name unless 'entityPath' says otherwise. Name them apart, " +
|
|
27
|
-
"pass an 'entityPath', or pass only one of them in 'include'.");
|
|
13
|
+
catch (err) {
|
|
14
|
+
return toErrorResponse(err);
|
|
28
15
|
}
|
|
29
|
-
const entityByPath = new Map([...byPath].map(([path, [entity]]) => [path, entity]));
|
|
30
|
-
const served = new Set(entities);
|
|
31
|
-
return (req) => {
|
|
32
|
-
const entity = entityByPath.get(req.entityPath);
|
|
33
|
-
if (!entity) {
|
|
34
|
-
return undefined;
|
|
35
|
-
}
|
|
36
|
-
const match = matchRoute(req.method, req.subPath);
|
|
37
|
-
if (!match) {
|
|
38
|
-
return undefined;
|
|
39
|
-
}
|
|
40
|
-
return run(entity, match, req);
|
|
41
|
-
};
|
|
42
|
-
async function run(entity, { op, method, id }, req) {
|
|
43
|
-
const meta = getMeta(entity);
|
|
44
|
-
// QUERY (RFC 10008) carries the JSON query in the body instead of the query string
|
|
45
|
-
const query = parseQueryParams(method === 'QUERY' ? req.body : req.query);
|
|
46
|
-
const { method: verb } = CRUD_ROUTES[op];
|
|
47
|
-
// What the client sent, before the hooks: a relation a hook adds is the server's own to add.
|
|
48
|
-
assertServed(meta, query, served);
|
|
49
|
-
assertServed(meta, req.body, served);
|
|
50
|
-
const hookCtx = { meta, op, method, query, body: req.body, context: req.context };
|
|
51
|
-
const appContext = (await getContext?.(req.context)) ?? {};
|
|
52
|
-
// Scope the whole request (hooks + querier + relation/cascade queries) to the resolved context.
|
|
53
|
-
return withContext(appContext, async () => {
|
|
54
|
-
await pre?.(hookCtx);
|
|
55
|
-
await (verb === 'GET' || verb === 'DELETE' ? preFilter : preSave)?.(hookCtx);
|
|
56
|
-
// Resolved after the hooks: one that aborts the request must not reach the pool at all.
|
|
57
|
-
const resolved = typeof pool === 'function' ? await pool(req.context, appContext) : pool;
|
|
58
|
-
// A read acquires and releases; a write is one transaction, so a failing cascade takes its parent with it.
|
|
59
|
-
const envelope = await (verb === 'GET' ? resolved.withQuerier(execute) : resolved.transaction(execute));
|
|
60
|
-
await post?.(hookCtx, envelope);
|
|
61
|
-
return { status: 200, body: envelope };
|
|
62
|
-
});
|
|
63
|
-
/** Runs `op`, reading the query and body after the hooks, which may have reshaped or reassigned them. */
|
|
64
|
-
async function execute(querier) {
|
|
65
|
-
const { query, body } = hookCtx;
|
|
66
|
-
const { hardDelete = false, count: counts } = query;
|
|
67
|
-
const scoped = id === undefined
|
|
68
|
-
? query
|
|
69
|
-
: { ...query, $where: whereWith(soleIdOf(meta, 'the HTTP handler'), id, query.$where) };
|
|
70
|
-
switch (op) {
|
|
71
|
-
case 'findOne':
|
|
72
|
-
case 'findOneById': {
|
|
73
|
-
const data = await querier.findOne(entity, scoped);
|
|
74
|
-
return { data, count: data ? 1 : 0 };
|
|
75
|
-
}
|
|
76
|
-
case 'count': {
|
|
77
|
-
const count = await querier.count(entity, query);
|
|
78
|
-
return { data: count, count };
|
|
79
|
-
}
|
|
80
|
-
case 'findMany': {
|
|
81
|
-
if (!counts) {
|
|
82
|
-
return { data: await querier.findMany(entity, query) };
|
|
83
|
-
}
|
|
84
|
-
// `findManyAndCount` counts every matching row, whereas `count` would count only the page `$limit` takes.
|
|
85
|
-
const [data, count] = await querier.findManyAndCount(entity, query);
|
|
86
|
-
return { data, count };
|
|
87
|
-
}
|
|
88
|
-
case 'findManyPage': {
|
|
89
|
-
const { $limit } = query;
|
|
90
|
-
if ($limit === undefined) {
|
|
91
|
-
throw new UqlUsageError('a page names how many rows it holds in $limit');
|
|
92
|
-
}
|
|
93
|
-
return { data: await querier.findManyPage(entity, { ...query, $limit }) };
|
|
94
|
-
}
|
|
95
|
-
case 'insertOne':
|
|
96
|
-
return { data: await querier.insertOne(entity, rowOf(body)), count: 1 };
|
|
97
|
-
case 'saveOne':
|
|
98
|
-
return { data: await querier.saveOne(entity, rowOf(body)), count: 1 };
|
|
99
|
-
case 'insertMany': {
|
|
100
|
-
const data = await querier.insertMany(entity, rowsOf(body));
|
|
101
|
-
return { data, count: data.length };
|
|
102
|
-
}
|
|
103
|
-
case 'saveMany': {
|
|
104
|
-
const data = await querier.saveMany(entity, rowsOf(body));
|
|
105
|
-
return { data, count: data.length };
|
|
106
|
-
}
|
|
107
|
-
// A write returns how many rows it changed, and the querier still refuses a delete that names no rows.
|
|
108
|
-
case 'updateMany':
|
|
109
|
-
case 'updateOneById': {
|
|
110
|
-
const count = await querier.updateMany(entity, scoped, rowOf(body));
|
|
111
|
-
return { data: count, count };
|
|
112
|
-
}
|
|
113
|
-
case 'deleteMany':
|
|
114
|
-
case 'deleteOneById': {
|
|
115
|
-
const count = await querier.deleteMany(entity, scoped, { hardDelete });
|
|
116
|
-
return { data: count, count };
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
/** The one row a write sends: a JSON object, refused otherwise as a malformed query is. */
|
|
123
|
-
function rowOf(body) {
|
|
124
|
-
if (!isRecord(body)) {
|
|
125
|
-
throw new UqlUsageError('the body must be a JSON object');
|
|
126
|
-
}
|
|
127
|
-
return body;
|
|
128
|
-
}
|
|
129
|
-
/** The rows a `many` write sends: a JSON array of objects. */
|
|
130
|
-
function rowsOf(body) {
|
|
131
|
-
if (!Array.isArray(body) || !body.every(isRecord)) {
|
|
132
|
-
throw new UqlUsageError('the body must be a JSON array of rows');
|
|
133
|
-
}
|
|
134
|
-
return body;
|
|
135
16
|
}
|
|
136
17
|
/**
|
|
137
|
-
*
|
|
138
|
-
* serve
|
|
139
|
-
*
|
|
18
|
+
* The API as `(request: Request) => Promise<Response>`, for any fetch-native runtime (Hono, Next.js route handlers,
|
|
19
|
+
* Bun.serve, Cloudflare Workers, SvelteKit, Astro), handing the `Request` to the API as its context. Mount it on a
|
|
20
|
+
* catch-all under the API's base: it reads the last two segments of the path as the entity and the op.
|
|
140
21
|
*/
|
|
141
|
-
function
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
22
|
+
export function toFetchHandler(api) {
|
|
23
|
+
return async (request) => {
|
|
24
|
+
const url = new URL(request.url);
|
|
25
|
+
const [entityPath = '', op = ''] = url.pathname.split('/').filter(Boolean).slice(-2).map(decodedSegment);
|
|
26
|
+
if (!api.serves(entityPath, op)) {
|
|
27
|
+
return answer(toErrorResponse(new UqlRequestError('Not Found', 404)));
|
|
145
28
|
}
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
const relation = Object.hasOwn(relations, key) ? relations[key] : undefined;
|
|
154
|
-
if (relation) {
|
|
155
|
-
const target = relation.entity();
|
|
156
|
-
const at = path ? `${path}.${key}` : key;
|
|
157
|
-
if (!served.has(target)) {
|
|
158
|
-
throw new UqlUsageError(`'${at}' reaches '${target.name}', which this handler does not serve`);
|
|
159
|
-
}
|
|
160
|
-
assertServed(getMeta(target), value, served, at);
|
|
29
|
+
const { method } = request;
|
|
30
|
+
const contentType = request.headers.get('content-type');
|
|
31
|
+
const q = url.searchParams.get('q') ?? undefined;
|
|
32
|
+
try {
|
|
33
|
+
// Read only where it is JSON: any other body is refused unread.
|
|
34
|
+
const body = request.body && isJson(contentType) ? await request.text() : undefined;
|
|
35
|
+
return answer(await answerRequest(api, { method, entityPath, op, q, body, contentType, context: request }));
|
|
161
36
|
}
|
|
162
|
-
|
|
163
|
-
|
|
37
|
+
catch (err) {
|
|
38
|
+
return answer(toErrorResponse(err));
|
|
164
39
|
}
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
function answer({ status, body, headers }) {
|
|
43
|
+
return Response.json(body, { status, ...(headers && { headers }) });
|
|
44
|
+
}
|
|
45
|
+
/** A path segment as it names an entity or an op: one that does not decode names nothing, so answers 404. */
|
|
46
|
+
function decodedSegment(segment) {
|
|
47
|
+
try {
|
|
48
|
+
return decodeURIComponent(segment);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return '';
|
|
165
52
|
}
|
|
166
53
|
}
|
package/dist/http/index.d.ts
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
export
|
|
2
|
-
export
|
|
3
|
-
export
|
|
4
|
-
export type
|
|
1
|
+
export * from './api.js';
|
|
2
|
+
export type { ApiCall, ApiMiddleware, ApiNext, EntityMiddleware } from './apiCall.js';
|
|
3
|
+
export { API_OPS, type ApiOp, entityPath, type EntityPathOptions, parseWireCall, type WireAnswer, type WireCall, } from './wireCall.js';
|
|
4
|
+
export { type HandlerResponse, type RequestErrorResponse, type RequestFailure, toErrorResponse } from './errors.js';
|
|
5
|
+
export { type Exposure, type Served, serve } from './exposure.js';
|
|
6
|
+
export type { WireCursors } from './wireQuery.js';
|
|
7
|
+
export { decodeRequest, encodeCall, type HttpCall, type HttpRequest, type ReadMethod } from './route.js';
|
|
8
|
+
export { type HandlerRequest, type RequestHandler, toFetchHandler, toRequestHandler } from './handler.js';
|
package/dist/http/index.js
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
-
export
|
|
2
|
-
export
|
|
3
|
-
export
|
|
1
|
+
export * from './api.js';
|
|
2
|
+
export { API_OPS, entityPath, parseWireCall, } from './wireCall.js';
|
|
3
|
+
export { toErrorResponse } from './errors.js';
|
|
4
|
+
export { serve } from './exposure.js';
|
|
5
|
+
export { decodeRequest, encodeCall } from './route.js';
|
|
6
|
+
export { toFetchHandler, toRequestHandler } from './handler.js';
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type ApiOp, type WireCall } from './wireCall.js';
|
|
2
|
+
/**
|
|
3
|
+
* How a client sends a read. `GET` carries the call in `?q=`, so a read caches and an `EventSource` can open it;
|
|
4
|
+
* `QUERY` (RFC 10008) and `POST` carry it in the body, past a URL's length limit. A write is `POST` alone.
|
|
5
|
+
*/
|
|
6
|
+
export type ReadMethod = 'GET' | 'QUERY' | 'POST';
|
|
7
|
+
/** A call as HTTP carries it, under the API's base: `/{entity}/{op}`, the rest of the call as JSON in `?q=` or the body. */
|
|
8
|
+
export type HttpCall = {
|
|
9
|
+
readonly method: ReadMethod;
|
|
10
|
+
readonly path: string;
|
|
11
|
+
readonly body?: string;
|
|
12
|
+
};
|
|
13
|
+
/** The request {@link decodeRequest} reads `call` back from. */
|
|
14
|
+
export declare function encodeCall({ entity, op, ...rest }: WireCall, readMethod?: ReadMethod): HttpCall;
|
|
15
|
+
/**
|
|
16
|
+
* A request to `/{entityPath}/{op}` as an adapter reduces it: its `q` as the URL holds it, and its body as the text it
|
|
17
|
+
* arrived as, which {@link decodeRequest} parses once the method and the content type are taken, or as a framework
|
|
18
|
+
* parsed it already.
|
|
19
|
+
*/
|
|
20
|
+
export type HttpRequest = {
|
|
21
|
+
readonly method: string;
|
|
22
|
+
readonly entityPath: string;
|
|
23
|
+
readonly op: ApiOp;
|
|
24
|
+
readonly q?: unknown;
|
|
25
|
+
readonly body?: unknown;
|
|
26
|
+
readonly contentType?: string | null;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* The call a request carries, unchecked past its envelope (`api.call` checks the rest). Refuses a method its op
|
|
30
|
+
* does not take, a body that is not JSON (which a cross-site form cannot send), and a call that is not an object.
|
|
31
|
+
*/
|
|
32
|
+
export declare function decodeRequest(req: HttpRequest): object;
|
|
33
|
+
/** Whether a content type is JSON's, the one a call's body takes: a cross-site form cannot send it. */
|
|
34
|
+
export declare function isJson(contentType: string | null | undefined): boolean;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// the specific util modules, not the barrel, which reaches every dialect helper and would land in the browser bundle
|
|
2
|
+
import { isPlainObject, jsonDocument } from '../util/object.util.js';
|
|
3
|
+
import { UqlRequestError, UqlUsageError } from '../util/uqlError.js';
|
|
4
|
+
import { API_OPS, wireJson } from './wireCall.js';
|
|
5
|
+
/** HEAD reads as GET does, which HTTP asks of a resource taking GET: the runtime leaves the body off. */
|
|
6
|
+
const READS = ['GET', 'HEAD', 'QUERY', 'POST'];
|
|
7
|
+
const WRITES = ['POST'];
|
|
8
|
+
/** The methods `op` takes. */
|
|
9
|
+
function methodsOf(op) {
|
|
10
|
+
return API_OPS[op].access === 'read' ? READS : WRITES;
|
|
11
|
+
}
|
|
12
|
+
/** The request {@link decodeRequest} reads `call` back from. */
|
|
13
|
+
export function encodeCall({ entity, op, ...rest }, readMethod = 'GET') {
|
|
14
|
+
const path = `/${encodeURIComponent(entity)}/${op}`;
|
|
15
|
+
const json = wireJson(rest);
|
|
16
|
+
const method = API_OPS[op].access === 'read' ? readMethod : 'POST';
|
|
17
|
+
if (method !== 'GET') {
|
|
18
|
+
return { method, path, body: json };
|
|
19
|
+
}
|
|
20
|
+
return { method, path: json === '{}' ? path : `${path}?q=${encodeURIComponent(json)}` };
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The call a request carries, unchecked past its envelope (`api.call` checks the rest). Refuses a method its op
|
|
24
|
+
* does not take, a body that is not JSON (which a cross-site form cannot send), and a call that is not an object.
|
|
25
|
+
*/
|
|
26
|
+
export function decodeRequest(req) {
|
|
27
|
+
const { op } = req;
|
|
28
|
+
const method = req.method.toUpperCase();
|
|
29
|
+
const methods = methodsOf(op);
|
|
30
|
+
if (!methods.includes(method)) {
|
|
31
|
+
const allow = methods.join(', ');
|
|
32
|
+
throw new UqlRequestError(`'${op}' takes ${allow}, not ${method}`, 405, { headers: { allow } });
|
|
33
|
+
}
|
|
34
|
+
const rest = method === 'GET' || method === 'HEAD' ? callInUrl(req.q) : callInBody(req, method);
|
|
35
|
+
const named = ['entity', 'op'].find((key) => key in rest);
|
|
36
|
+
if (named) {
|
|
37
|
+
throw new UqlUsageError(`a call's '${named}' is named by its path`, { path: [named] });
|
|
38
|
+
}
|
|
39
|
+
return { ...rest, entity: req.entityPath, op };
|
|
40
|
+
}
|
|
41
|
+
/** Whether a content type is JSON's, the one a call's body takes: a cross-site form cannot send it. */
|
|
42
|
+
export function isJson(contentType) {
|
|
43
|
+
return contentType?.split(';')[0]?.trim().toLowerCase() === 'application/json';
|
|
44
|
+
}
|
|
45
|
+
/** The call a `GET` or `HEAD` carries, the JSON text of `q`. */
|
|
46
|
+
function callInUrl(q) {
|
|
47
|
+
if (q === undefined) {
|
|
48
|
+
return {};
|
|
49
|
+
}
|
|
50
|
+
if (typeof q !== 'string') {
|
|
51
|
+
throw new UqlUsageError("'q' is the call as one JSON text", { path: ['q'] });
|
|
52
|
+
}
|
|
53
|
+
const parsed = jsonDocument(q);
|
|
54
|
+
if (parsed === undefined) {
|
|
55
|
+
throw new UqlUsageError("'q' is not valid JSON", { path: ['q'] });
|
|
56
|
+
}
|
|
57
|
+
return objectOf(parsed, ['q']);
|
|
58
|
+
}
|
|
59
|
+
/** The call a body carries: its text, parsed once the content type is taken, or as a framework parsed it. */
|
|
60
|
+
function callInBody(req, method) {
|
|
61
|
+
if (!isJson(req.contentType)) {
|
|
62
|
+
throw new UqlRequestError("a call's body is JSON: send 'content-type: application/json'", 415);
|
|
63
|
+
}
|
|
64
|
+
if (req.q !== undefined) {
|
|
65
|
+
throw new UqlUsageError(`a ${method} carries its call in the body, not in 'q'`, { path: ['q'] });
|
|
66
|
+
}
|
|
67
|
+
const { body } = req;
|
|
68
|
+
if (typeof body !== 'string') {
|
|
69
|
+
return objectOf(body ?? {}, []);
|
|
70
|
+
}
|
|
71
|
+
const parsed = body ? jsonDocument(body) : {};
|
|
72
|
+
if (parsed === undefined) {
|
|
73
|
+
throw new UqlUsageError('invalid JSON body');
|
|
74
|
+
}
|
|
75
|
+
return objectOf(parsed, []);
|
|
76
|
+
}
|
|
77
|
+
function objectOf(value, path) {
|
|
78
|
+
if (!isPlainObject(value)) {
|
|
79
|
+
throw new UqlUsageError('a call must be a JSON object', { path });
|
|
80
|
+
}
|
|
81
|
+
return value;
|
|
82
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import type { AbstractType } from '../type/index.js';
|
|
2
|
+
/** What an op answers, which says how its values cross JSON: rows, a page of them, rows and their count, keys, or a count. */
|
|
3
|
+
export type WireAnswer = 'rows' | 'page' | 'rowsAndCount' | 'ids' | 'count';
|
|
4
|
+
/**
|
|
5
|
+
* The querier methods a client may call, what each does, and what it answers: the one table the server, every
|
|
6
|
+
* transport and the client read, keyed by {@link UniversalQuerier} method names so a rename is a compile error.
|
|
7
|
+
*/
|
|
8
|
+
export declare const API_OPS: {
|
|
9
|
+
readonly findOneById: {
|
|
10
|
+
readonly access: 'read';
|
|
11
|
+
readonly answers: 'rows';
|
|
12
|
+
readonly byId: true;
|
|
13
|
+
};
|
|
14
|
+
readonly findOne: {
|
|
15
|
+
readonly access: 'read';
|
|
16
|
+
readonly answers: 'rows';
|
|
17
|
+
};
|
|
18
|
+
readonly findMany: {
|
|
19
|
+
readonly access: 'read';
|
|
20
|
+
readonly answers: 'rows';
|
|
21
|
+
};
|
|
22
|
+
readonly findManyAndCount: {
|
|
23
|
+
readonly access: 'read';
|
|
24
|
+
readonly answers: 'rowsAndCount';
|
|
25
|
+
};
|
|
26
|
+
readonly findManyPage: {
|
|
27
|
+
readonly access: 'read';
|
|
28
|
+
readonly answers: 'page';
|
|
29
|
+
};
|
|
30
|
+
readonly count: {
|
|
31
|
+
readonly access: 'read';
|
|
32
|
+
readonly answers: 'count';
|
|
33
|
+
};
|
|
34
|
+
readonly insertOne: {
|
|
35
|
+
readonly access: 'insert';
|
|
36
|
+
readonly answers: 'ids';
|
|
37
|
+
readonly writes: 'row';
|
|
38
|
+
};
|
|
39
|
+
readonly insertMany: {
|
|
40
|
+
readonly access: 'insert';
|
|
41
|
+
readonly answers: 'ids';
|
|
42
|
+
readonly writes: 'rows';
|
|
43
|
+
};
|
|
44
|
+
readonly saveOne: {
|
|
45
|
+
readonly access: 'save';
|
|
46
|
+
readonly answers: 'ids';
|
|
47
|
+
readonly writes: 'row';
|
|
48
|
+
};
|
|
49
|
+
readonly saveMany: {
|
|
50
|
+
readonly access: 'save';
|
|
51
|
+
readonly answers: 'ids';
|
|
52
|
+
readonly writes: 'rows';
|
|
53
|
+
};
|
|
54
|
+
readonly updateMany: {
|
|
55
|
+
readonly access: 'update';
|
|
56
|
+
readonly answers: 'count';
|
|
57
|
+
readonly writes: 'changes';
|
|
58
|
+
};
|
|
59
|
+
readonly updateOneById: {
|
|
60
|
+
readonly access: 'update';
|
|
61
|
+
readonly answers: 'count';
|
|
62
|
+
readonly byId: true;
|
|
63
|
+
readonly writes: 'changes';
|
|
64
|
+
};
|
|
65
|
+
readonly deleteMany: {
|
|
66
|
+
readonly access: 'delete';
|
|
67
|
+
readonly answers: 'count';
|
|
68
|
+
};
|
|
69
|
+
readonly deleteOneById: {
|
|
70
|
+
readonly access: 'delete';
|
|
71
|
+
readonly answers: 'count';
|
|
72
|
+
readonly byId: true;
|
|
73
|
+
};
|
|
74
|
+
};
|
|
75
|
+
export type ApiOp = keyof typeof API_OPS;
|
|
76
|
+
/**
|
|
77
|
+
* One operation as a client asks for it, plain JSON so it crosses any transport: the entity by its path, the
|
|
78
|
+
* querier method, and what the method takes. The query is decoded and checked on arrival, so it is any object here.
|
|
79
|
+
*/
|
|
80
|
+
export type WireCall = {
|
|
81
|
+
readonly entity: string;
|
|
82
|
+
readonly op: ApiOp;
|
|
83
|
+
readonly id?: string | number;
|
|
84
|
+
readonly query?: object;
|
|
85
|
+
readonly payload?: unknown;
|
|
86
|
+
readonly hardDelete?: boolean;
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* `value` as a {@link WireCall}, refused otherwise, pointing at the key at fault: what a transport that checks nothing
|
|
90
|
+
* (a tRPC procedure's input) hands the API. A key the op does not take is refused rather than ignored, so a client
|
|
91
|
+
* learns its call was not the one run. What the op needs, and the query and payload's shapes, the call checks itself.
|
|
92
|
+
*/
|
|
93
|
+
export declare function parseWireCall(value: unknown): WireCall;
|
|
94
|
+
export declare function isApiOp(op: unknown): op is ApiOp;
|
|
95
|
+
/**
|
|
96
|
+
* The path an entity is addressed by, e.g. `entityPath(UserProfile) === 'user-profile'`: the `entity` of a call,
|
|
97
|
+
* and the URL segment of its route.
|
|
98
|
+
*/
|
|
99
|
+
export declare function entityPath<E>(entity: AbstractType<E>): string;
|
|
100
|
+
export type EntityPathOptions = {
|
|
101
|
+
/**
|
|
102
|
+
* The path an entity is addressed by, its kebab-cased class name by default: the API and its client take the same
|
|
103
|
+
* option, so one map serves both. State it where the default cannot: a build that minifies class names renames
|
|
104
|
+
* every path.
|
|
105
|
+
*/
|
|
106
|
+
readonly entityPath?: (entity: AbstractType<unknown>) => string;
|
|
107
|
+
};
|
|
108
|
+
/** The path each entity is addressed by under `opts`. */
|
|
109
|
+
export declare function entityPathOf(opts: EntityPathOptions): (entity: AbstractType<unknown>) => string;
|
|
110
|
+
/**
|
|
111
|
+
* What leaves a client, as JSON, refusing what JSON keeps nothing of rather than letting the server build a
|
|
112
|
+
* statement around the remains: a `sql` fragment, which arrives as `{}`, and binary, keyed by index. A `bigint` goes
|
|
113
|
+
* as its digits and a `Date` as its ISO text, which the server reads back by the entity.
|
|
114
|
+
*/
|
|
115
|
+
export declare function wireJson(value: unknown): string;
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// the brand, which a `sql` fragment and a column ref both carry
|
|
2
|
+
import { SQL_FN } from '../type/querySql.js';
|
|
3
|
+
// the specific util modules, not the barrel, which reaches every dialect helper and would land in the browser bundle
|
|
4
|
+
import { getKeys, isPlainObject } from '../util/object.util.js';
|
|
5
|
+
import { kebabCase } from '../util/string.util.js';
|
|
6
|
+
import { UqlUsageError } from '../util/uqlError.js';
|
|
7
|
+
/**
|
|
8
|
+
* The querier methods a client may call, what each does, and what it answers: the one table the server, every
|
|
9
|
+
* transport and the client read, keyed by {@link UniversalQuerier} method names so a rename is a compile error.
|
|
10
|
+
*/
|
|
11
|
+
export const API_OPS = {
|
|
12
|
+
findOneById: { access: 'read', answers: 'rows', byId: true },
|
|
13
|
+
findOne: { access: 'read', answers: 'rows' },
|
|
14
|
+
findMany: { access: 'read', answers: 'rows' },
|
|
15
|
+
findManyAndCount: { access: 'read', answers: 'rowsAndCount' },
|
|
16
|
+
findManyPage: { access: 'read', answers: 'page' },
|
|
17
|
+
count: { access: 'read', answers: 'count' },
|
|
18
|
+
insertOne: { access: 'insert', answers: 'ids', writes: 'row' },
|
|
19
|
+
insertMany: { access: 'insert', answers: 'ids', writes: 'rows' },
|
|
20
|
+
saveOne: { access: 'save', answers: 'ids', writes: 'row' },
|
|
21
|
+
saveMany: { access: 'save', answers: 'ids', writes: 'rows' },
|
|
22
|
+
updateMany: { access: 'update', answers: 'count', writes: 'changes' },
|
|
23
|
+
updateOneById: { access: 'update', answers: 'count', byId: true, writes: 'changes' },
|
|
24
|
+
deleteMany: { access: 'delete', answers: 'count' },
|
|
25
|
+
deleteOneById: { access: 'delete', answers: 'count', byId: true },
|
|
26
|
+
};
|
|
27
|
+
const API_OP_KEYS = new Set(getKeys(API_OPS));
|
|
28
|
+
const CALL_KEYS = new Set([
|
|
29
|
+
'entity',
|
|
30
|
+
'op',
|
|
31
|
+
'id',
|
|
32
|
+
'query',
|
|
33
|
+
'payload',
|
|
34
|
+
'hardDelete',
|
|
35
|
+
]);
|
|
36
|
+
function refused(message, key) {
|
|
37
|
+
return new UqlUsageError(message, { path: [key] });
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* `value` as a {@link WireCall}, refused otherwise, pointing at the key at fault: what a transport that checks nothing
|
|
41
|
+
* (a tRPC procedure's input) hands the API. A key the op does not take is refused rather than ignored, so a client
|
|
42
|
+
* learns its call was not the one run. What the op needs, and the query and payload's shapes, the call checks itself.
|
|
43
|
+
*/
|
|
44
|
+
export function parseWireCall(value) {
|
|
45
|
+
if (!isPlainObject(value)) {
|
|
46
|
+
throw new UqlUsageError('a call must be a JSON object', { path: [] });
|
|
47
|
+
}
|
|
48
|
+
const stray = getKeys(value).find((key) => !CALL_KEYS.has(key));
|
|
49
|
+
if (stray !== undefined) {
|
|
50
|
+
throw refused(`'${stray}' is no part of a call`, stray);
|
|
51
|
+
}
|
|
52
|
+
const { entity, op, id, query, payload, hardDelete } = value;
|
|
53
|
+
if (typeof entity !== 'string') {
|
|
54
|
+
throw refused("a call names its entity's path in 'entity'", 'entity');
|
|
55
|
+
}
|
|
56
|
+
if (!isApiOp(op)) {
|
|
57
|
+
throw refused(`'${String(op)}' is not an operation the API serves`, 'op');
|
|
58
|
+
}
|
|
59
|
+
const shape = API_OPS[op];
|
|
60
|
+
if (id !== undefined && !shape.byId) {
|
|
61
|
+
throw refused(`'${op}' addresses no row by 'id'`, 'id');
|
|
62
|
+
}
|
|
63
|
+
if (id !== undefined && typeof id !== 'string' && typeof id !== 'number') {
|
|
64
|
+
throw refused("a call's 'id' is a string or a number", 'id');
|
|
65
|
+
}
|
|
66
|
+
if (query !== undefined && (shape.writes === 'row' || shape.writes === 'rows')) {
|
|
67
|
+
throw refused(`'${op}' takes no 'query'`, 'query');
|
|
68
|
+
}
|
|
69
|
+
if (query !== undefined && !isPlainObject(query)) {
|
|
70
|
+
throw refused("a call's 'query' must be a JSON object", 'query');
|
|
71
|
+
}
|
|
72
|
+
if (payload !== undefined && !shape.writes) {
|
|
73
|
+
throw refused(`'${op}' writes no 'payload'`, 'payload');
|
|
74
|
+
}
|
|
75
|
+
if (hardDelete !== undefined && shape.access !== 'delete') {
|
|
76
|
+
throw refused(`'${op}' deletes nothing, so takes no 'hardDelete'`, 'hardDelete');
|
|
77
|
+
}
|
|
78
|
+
if (hardDelete !== undefined && typeof hardDelete !== 'boolean') {
|
|
79
|
+
throw refused("a call's 'hardDelete' is a boolean", 'hardDelete');
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
entity,
|
|
83
|
+
op,
|
|
84
|
+
...(id !== undefined && { id }),
|
|
85
|
+
...(query !== undefined && { query }),
|
|
86
|
+
...(payload !== undefined && { payload }),
|
|
87
|
+
...(hardDelete !== undefined && { hardDelete }),
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
export function isApiOp(op) {
|
|
91
|
+
return typeof op === 'string' && API_OP_KEYS.has(op);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* The path an entity is addressed by, e.g. `entityPath(UserProfile) === 'user-profile'`: the `entity` of a call,
|
|
95
|
+
* and the URL segment of its route.
|
|
96
|
+
*/
|
|
97
|
+
export function entityPath(entity) {
|
|
98
|
+
return kebabCase(entity.name);
|
|
99
|
+
}
|
|
100
|
+
/** The path each entity is addressed by under `opts`. */
|
|
101
|
+
export function entityPathOf(opts) {
|
|
102
|
+
return opts.entityPath ?? entityPath;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* What leaves a client, as JSON, refusing what JSON keeps nothing of rather than letting the server build a
|
|
106
|
+
* statement around the remains: a `sql` fragment, which arrives as `{}`, and binary, keyed by index. A `bigint` goes
|
|
107
|
+
* as its digits and a `Date` as its ISO text, which the server reads back by the entity.
|
|
108
|
+
*/
|
|
109
|
+
export function wireJson(value) {
|
|
110
|
+
return JSON.stringify(value, (_key, held) => {
|
|
111
|
+
if (typeof held === 'bigint') {
|
|
112
|
+
return String(held);
|
|
113
|
+
}
|
|
114
|
+
if (typeof held !== 'object' || held === null) {
|
|
115
|
+
return held;
|
|
116
|
+
}
|
|
117
|
+
if (SQL_FN in held) {
|
|
118
|
+
throw new UqlUsageError('raw SQL cannot travel over the wire: what leaves the client is JSON');
|
|
119
|
+
}
|
|
120
|
+
// A blob is a field value, so no type parameter reaches it: this is the only place it is caught.
|
|
121
|
+
if (held instanceof ArrayBuffer || ArrayBuffer.isView(held)) {
|
|
122
|
+
throw new UqlUsageError('binary cannot travel over the wire: what leaves the client is JSON');
|
|
123
|
+
}
|
|
124
|
+
return held;
|
|
125
|
+
});
|
|
126
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { QueryKeyset, WireQuery } from '../type/index.js';
|
|
2
|
+
/** The cursors a page request carries; only `findManyPage` reads them. */
|
|
3
|
+
export type WireCursors = Pick<QueryKeyset<unknown>, '$after' | '$before'>;
|
|
4
|
+
/**
|
|
5
|
+
* A call's query as the querier takes it, refused where a key is not one the wire carries ({@link WIRE_VALUES}) or
|
|
6
|
+
* holds a value of another type: what a client sends is JSON, so a number arrives as one, never as text.
|
|
7
|
+
*/
|
|
8
|
+
export declare function parseWireQuery<E = unknown>(query?: unknown): WireQuery<E> & WireCursors;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// the clause table itself, not the barrel: this module is in the browser bundle's graph
|
|
2
|
+
import { QUERY_CLAUSES } from '../type/query.js';
|
|
3
|
+
// the specific util module, not the barrel, which reaches every dialect helper
|
|
4
|
+
import { getKeys, isRecord, isPlainObject } from '../util/object.util.js';
|
|
5
|
+
// the error class alone, from its own leaf module: `queryError.ts` carries every driver's code map
|
|
6
|
+
import { UqlUsageError } from '../util/uqlError.js';
|
|
7
|
+
/**
|
|
8
|
+
* The keys a query takes from the wire, with the type of each: every query clause ({@link QUERY_CLAUSES}) the wire
|
|
9
|
+
* carries. Any other key is refused: dropping a clause answers a read other than the one asked for, and `filters` or
|
|
10
|
+
* `context` would bypass a security filter or inject ambient context.
|
|
11
|
+
*/
|
|
12
|
+
const WIRE_VALUES = new Map(getKeys(QUERY_CLAUSES)
|
|
13
|
+
.filter((key) => carriedOverHttp(QUERY_CLAUSES[key]))
|
|
14
|
+
.map((key) => [key, QUERY_CLAUSES[key].value]));
|
|
15
|
+
function carriedOverHttp(clause) {
|
|
16
|
+
return clause.wire !== false;
|
|
17
|
+
}
|
|
18
|
+
const TYPES = {
|
|
19
|
+
object: 'a JSON object',
|
|
20
|
+
number: 'a number',
|
|
21
|
+
boolean: 'a boolean',
|
|
22
|
+
string: 'a cursor a page handed out',
|
|
23
|
+
};
|
|
24
|
+
function holds(shape, value) {
|
|
25
|
+
return shape === 'object' ? typeof value === 'object' && value !== null : typeof value === shape;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* A call's query as the querier takes it, refused where a key is not one the wire carries ({@link WIRE_VALUES}) or
|
|
29
|
+
* holds a value of another type: what a client sends is JSON, so a number arrives as one, never as text.
|
|
30
|
+
*/
|
|
31
|
+
export function parseWireQuery(query = {}) {
|
|
32
|
+
if (!isRecord(query)) {
|
|
33
|
+
throw new UqlUsageError('the query must be a JSON object', { path: ['query'] });
|
|
34
|
+
}
|
|
35
|
+
for (const key of getKeys(query)) {
|
|
36
|
+
const shape = WIRE_VALUES.get(key);
|
|
37
|
+
if (!shape) {
|
|
38
|
+
throw new UqlUsageError(`'${key}' is not a query key the wire takes`, { path: ['query', key] });
|
|
39
|
+
}
|
|
40
|
+
const value = query[key];
|
|
41
|
+
if (value !== undefined && !holds(shape, value)) {
|
|
42
|
+
throw new UqlUsageError(`'${key}' must be ${TYPES[shape]}`, { path: ['query', key] });
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
const $where = query['$where'] ?? {};
|
|
46
|
+
if (!isPlainObject($where)) {
|
|
47
|
+
throw new UqlUsageError("'$where' must be a JSON object", { path: ['query', '$where'] });
|
|
48
|
+
}
|
|
49
|
+
const parsed = { ...query, $where };
|
|
50
|
+
return parsed;
|
|
51
|
+
}
|