@mupt-ai/dari-gateway 1.0.324 → 1.0.326
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 +4 -3
- package/dist/activity/conversation_detail.d.ts +2 -0
- package/dist/activity/conversation_detail.js +259 -0
- package/dist/activity/conversation_records.d.ts +129 -0
- package/dist/activity/conversation_records.js +318 -0
- package/dist/activity/conversations.d.ts +11 -0
- package/dist/activity/conversations.js +198 -0
- package/dist/activity/core.d.ts +13 -0
- package/dist/activity/core.js +613 -0
- package/dist/activity/filters.d.ts +71 -0
- package/dist/activity/filters.js +169 -0
- package/dist/activity/http.d.ts +37 -0
- package/dist/activity/http.js +109 -0
- package/dist/activity/params.d.ts +40 -0
- package/dist/activity/params.js +130 -0
- package/dist/activity/people.d.ts +3 -0
- package/dist/activity/people.js +413 -0
- package/dist/activity/routes.d.ts +2 -0
- package/dist/activity/routes.js +23 -0
- package/dist/activity/savings.d.ts +12 -0
- package/dist/activity/savings.js +102 -0
- package/dist/activity/shared.d.ts +15 -0
- package/dist/activity/shared.js +26 -0
- package/dist/activity/sql.d.ts +52 -0
- package/dist/activity/sql.js +124 -0
- package/dist/activity/tool_exchanges.d.ts +21 -0
- package/dist/activity/tool_exchanges.js +309 -0
- package/dist/activity/tool_skill_activity.d.ts +128 -0
- package/dist/activity/tool_skill_activity.js +280 -0
- package/dist/activity/tool_skill_identities.d.ts +25 -0
- package/dist/activity/tool_skill_identities.js +162 -0
- package/dist/activity/tools.d.ts +4 -0
- package/dist/activity/tools.js +68 -0
- package/dist/activity/values.d.ts +45 -0
- package/dist/activity/values.js +178 -0
- package/dist/context/interaction_fingerprint.js +11 -3
- package/dist/context/interaction_fingerprint_format.d.ts +2 -1
- package/dist/context/interaction_fingerprint_format.js +2 -0
- package/dist/http/handler.d.ts +2 -1
- package/dist/http/handler.js +6 -1
- package/dist/interaction/types.d.ts +17 -2
- package/dist/interaction/types.js +11 -0
- package/dist/link/endpoints.js +44 -53
- package/dist/platform/platform.d.ts +12 -0
- package/dist/protocol/input/anthropic_messages.js +63 -48
- package/dist/providers/pi.js +22 -3
- package/dist/providers/pi_context.js +15 -5
- package/dist/runtime/claude_code/auxiliary_routing.js +34 -3
- package/dist/runtime/prepare_routed_completion.d.ts +2 -0
- package/dist/runtime/prepare_routed_completion.js +42 -1
- package/dist/self_host/activity_store.d.ts +35 -0
- package/dist/self_host/activity_store.js +373 -0
- package/dist/self_host/main.d.ts +3 -2
- package/dist/self_host/main.js +8 -3
- package/dist/self_host/platform.d.ts +4 -2
- package/dist/self_host/platform.js +35 -3
- package/package.json +2 -2
- package/src/activity/conversation_detail.ts +283 -0
- package/src/activity/conversation_records.ts +403 -0
- package/src/activity/conversations.ts +218 -0
- package/src/activity/core.ts +678 -0
- package/src/activity/filters.ts +206 -0
- package/src/activity/http.ts +140 -0
- package/src/activity/params.ts +138 -0
- package/src/activity/people.ts +471 -0
- package/src/activity/routes.ts +26 -0
- package/src/activity/savings.ts +121 -0
- package/src/activity/shared.ts +36 -0
- package/src/activity/sql.ts +139 -0
- package/src/activity/tool_exchanges.ts +340 -0
- package/src/activity/tool_skill_activity.ts +314 -0
- package/src/activity/tool_skill_identities.ts +196 -0
- package/src/activity/tools.ts +76 -0
- package/src/activity/values.ts +197 -0
- package/src/context/interaction_fingerprint.ts +9 -3
- package/src/context/interaction_fingerprint_format.ts +6 -1
- package/src/http/handler.ts +5 -1
- package/src/interaction/types.ts +21 -11
- package/src/link/endpoints.ts +44 -54
- package/src/platform/platform.ts +12 -0
- package/src/protocol/input/anthropic_messages.ts +66 -53
- package/src/providers/pi.ts +22 -3
- package/src/providers/pi_context.ts +14 -7
- package/src/runtime/claude_code/auxiliary_routing.ts +33 -2
- package/src/runtime/prepare_routed_completion.ts +60 -2
- package/src/self_host/activity_store.ts +423 -0
- package/src/self_host/main.ts +17 -3
- package/src/self_host/platform.ts +38 -3
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/* The filters every Activity read takes, and the SQL conditions they become
|
|
2
|
+
over `routing_requests`. */
|
|
3
|
+
import { badRequest } from "./params.js";
|
|
4
|
+
import { and, or, raw, sql } from "./sql.js";
|
|
5
|
+
import { canonicalInstant, formatInstant, readInt } from "./values.js";
|
|
6
|
+
/** The source protocols Activity reads, in display order. */
|
|
7
|
+
export const SUPPORTED_SOURCE_PROTOCOLS = ["openai_chat", "openai_responses", "anthropic_messages"];
|
|
8
|
+
/** Stands for the steps whose selector chose no model. */
|
|
9
|
+
export const SELECTOR_UNRESOLVED_MODEL = "selector-unresolved";
|
|
10
|
+
/** A step's model, under the alias `r`: `SELECTOR_UNRESOLVED_MODEL` when its selector chose none. */
|
|
11
|
+
export const MODEL = raw(`coalesce(r.selected_model, '${SELECTOR_UNRESOLVED_MODEL}')`);
|
|
12
|
+
export const REQUEST_STATUSES = ["completed", "provider_error", "selector_error", "aborted"];
|
|
13
|
+
export const KEY_SOURCES = ["user", "managed", "subscription"];
|
|
14
|
+
const MAX_RANGE_MICROS = 366 * 24 * 60 * 60 * 1_000_000;
|
|
15
|
+
const ALLOWED_BUCKET_SECONDS = new Set([
|
|
16
|
+
60, 5 * 60, 15 * 60, 30 * 60, 60 * 60, 24 * 60 * 60, 7 * 24 * 60 * 60, 30 * 24 * 60 * 60,
|
|
17
|
+
]);
|
|
18
|
+
export function readActivityQuery(params) {
|
|
19
|
+
return {
|
|
20
|
+
from: params.instant("from"),
|
|
21
|
+
to: params.instant("to"),
|
|
22
|
+
routerId: params.string("router_id"),
|
|
23
|
+
apiKeyIds: params.strings("api_key_id"),
|
|
24
|
+
userIds: params.strings("user_id"),
|
|
25
|
+
models: params.strings("model"),
|
|
26
|
+
provider: params.string("provider"),
|
|
27
|
+
status: params.literal("status", REQUEST_STATUSES),
|
|
28
|
+
keySource: params.literal("key_source", KEY_SOURCES),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/** `source_scope`: protocols, comma-separated, or `all` or `none`; absent is all. */
|
|
32
|
+
export function readSourceScope(params) {
|
|
33
|
+
return params.string("source_scope", { maxLength: 128 });
|
|
34
|
+
}
|
|
35
|
+
export function sourceProtocols(scope) {
|
|
36
|
+
if (scope === undefined)
|
|
37
|
+
return [...SUPPORTED_SOURCE_PROTOCOLS];
|
|
38
|
+
const values = [...new Set(scope.split(",").map((part) => part.trim()).filter(Boolean))];
|
|
39
|
+
if (values.length === 0)
|
|
40
|
+
throw badRequest("Select at least one Activity source protocol.");
|
|
41
|
+
if (values.includes("all")) {
|
|
42
|
+
if (values.length !== 1)
|
|
43
|
+
throw badRequest("Activity source scope 'all' cannot be combined with protocols.");
|
|
44
|
+
return [...SUPPORTED_SOURCE_PROTOCOLS];
|
|
45
|
+
}
|
|
46
|
+
if (values.includes("none")) {
|
|
47
|
+
if (values.length !== 1)
|
|
48
|
+
throw badRequest("Activity source scope 'none' cannot be combined with protocols.");
|
|
49
|
+
return [];
|
|
50
|
+
}
|
|
51
|
+
const unsupported = values.filter((value) => !SUPPORTED_SOURCE_PROTOCOLS.includes(value));
|
|
52
|
+
if (unsupported.length > 0) {
|
|
53
|
+
throw badRequest(`Unsupported Activity source protocol: ${unsupported.sort().join(", ")}.`);
|
|
54
|
+
}
|
|
55
|
+
return SUPPORTED_SOURCE_PROTOCOLS.filter((protocol) => values.includes(protocol));
|
|
56
|
+
}
|
|
57
|
+
export function validatedRange(query) {
|
|
58
|
+
if (query.from.naive)
|
|
59
|
+
throw badRequest("Activity 'from' must include a timezone offset.");
|
|
60
|
+
if (query.to.naive)
|
|
61
|
+
throw badRequest("Activity 'to' must include a timezone offset.");
|
|
62
|
+
const start = query.from.instant;
|
|
63
|
+
const end = query.to.instant;
|
|
64
|
+
if (end <= start)
|
|
65
|
+
throw badRequest("Activity 'to' must be later than 'from'.");
|
|
66
|
+
if (end - start > MAX_RANGE_MICROS)
|
|
67
|
+
throw badRequest("Activity ranges cannot exceed 366 days.");
|
|
68
|
+
return { start, end };
|
|
69
|
+
}
|
|
70
|
+
/** The range and dimensions, for reads without time buckets. */
|
|
71
|
+
export function validatedFilters(query, protocols) {
|
|
72
|
+
const { start, end } = validatedRange(query);
|
|
73
|
+
return {
|
|
74
|
+
start,
|
|
75
|
+
end,
|
|
76
|
+
bucketSeconds: 0,
|
|
77
|
+
protocols,
|
|
78
|
+
routerId: query.routerId,
|
|
79
|
+
apiKeyIds: [...new Set(query.apiKeyIds)],
|
|
80
|
+
userIds: [...new Set(query.userIds)],
|
|
81
|
+
models: [...new Set(query.models)],
|
|
82
|
+
provider: query.provider,
|
|
83
|
+
status: query.status,
|
|
84
|
+
keySource: query.keySource,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
/** The range, dimensions, and a bucket size giving at most 1,000 buckets. */
|
|
88
|
+
export function validatedBucketFilters(query, protocols, bucketSeconds) {
|
|
89
|
+
const filters = validatedFilters(query, protocols);
|
|
90
|
+
if (!ALLOWED_BUCKET_SECONDS.has(bucketSeconds))
|
|
91
|
+
throw badRequest("Unsupported activity bucket size.");
|
|
92
|
+
if ((filters.end - filters.start) / 1_000_000 / bucketSeconds > 1000) {
|
|
93
|
+
throw badRequest("Activity range contains too many time buckets.");
|
|
94
|
+
}
|
|
95
|
+
return { ...filters, bucketSeconds };
|
|
96
|
+
}
|
|
97
|
+
/** A timestamp value to compare a timestamp column with. */
|
|
98
|
+
function timestamp(db, instant) {
|
|
99
|
+
const text = canonicalInstant(instant);
|
|
100
|
+
return db.dialect === "postgres" ? sql `${text}::timestamptz` : sql `${text}`;
|
|
101
|
+
}
|
|
102
|
+
/* The conditions below filter `routing_requests` under the alias `r`, or the
|
|
103
|
+
alias a query gave the table. Each is safe to follow with `and`. */
|
|
104
|
+
/** Received in the filters' time range. */
|
|
105
|
+
export function timeRange(db, filters, alias = "r") {
|
|
106
|
+
const r = raw(alias);
|
|
107
|
+
return sql `${r}.received_at >= ${timestamp(db, filters.start)} and ${r}.received_at < ${timestamp(db, filters.end)}`;
|
|
108
|
+
}
|
|
109
|
+
/** The organization, time range, and source protocols. */
|
|
110
|
+
export function baseCriteria(db, organizationId, filters) {
|
|
111
|
+
return sql `r.organization_id = ${organizationId}
|
|
112
|
+
and ${timeRange(db, filters)}
|
|
113
|
+
and r.source_protocol in (${filters.protocols})`;
|
|
114
|
+
}
|
|
115
|
+
/** Router and identity: API keys or attributed people. Empty values filter nothing. */
|
|
116
|
+
export function identityCriteria(filters, alias = "r") {
|
|
117
|
+
const r = raw(alias);
|
|
118
|
+
const conditions = [];
|
|
119
|
+
if (filters.routerId)
|
|
120
|
+
conditions.push(sql `${r}.router_id = ${filters.routerId}`);
|
|
121
|
+
const identity = [];
|
|
122
|
+
if (filters.apiKeyIds.length > 0)
|
|
123
|
+
identity.push(sql `${r}.api_key_id in (${filters.apiKeyIds})`);
|
|
124
|
+
if (filters.userIds.length > 0)
|
|
125
|
+
identity.push(sql `${r}.attributed_user_id in (${filters.userIds})`);
|
|
126
|
+
if (identity.length > 0)
|
|
127
|
+
conditions.push(or(identity));
|
|
128
|
+
return and(conditions);
|
|
129
|
+
}
|
|
130
|
+
/** Model, provider, status, and key source. */
|
|
131
|
+
export function routeCriteria(filters, alias = "r") {
|
|
132
|
+
const r = raw(alias);
|
|
133
|
+
const conditions = [];
|
|
134
|
+
if (filters.models.length > 0) {
|
|
135
|
+
const ids = filters.models.filter((model) => model !== SELECTOR_UNRESOLVED_MODEL);
|
|
136
|
+
const models = [];
|
|
137
|
+
if (ids.length > 0)
|
|
138
|
+
models.push(sql `${r}.selected_model in (${ids})`);
|
|
139
|
+
if (filters.models.includes(SELECTOR_UNRESOLVED_MODEL))
|
|
140
|
+
models.push(sql `${r}.selected_model is null`);
|
|
141
|
+
conditions.push(or(models));
|
|
142
|
+
}
|
|
143
|
+
if (filters.provider)
|
|
144
|
+
conditions.push(sql `${r}.selected_provider = ${filters.provider}`);
|
|
145
|
+
if (filters.status)
|
|
146
|
+
conditions.push(sql `${r}.status = ${filters.status}`);
|
|
147
|
+
if (filters.keySource)
|
|
148
|
+
conditions.push(sql `${r}.provider_key_source = ${filters.keySource}`);
|
|
149
|
+
return and(conditions);
|
|
150
|
+
}
|
|
151
|
+
export function dimensionCriteria(filters, alias = "r") {
|
|
152
|
+
return sql `${identityCriteria(filters, alias)} and ${routeCriteria(filters, alias)}`;
|
|
153
|
+
}
|
|
154
|
+
/** Base and dimension criteria: what most reads filter by. */
|
|
155
|
+
export function criteria(db, organizationId, filters) {
|
|
156
|
+
return sql `(${baseCriteria(db, organizationId, filters)} and ${dimensionCriteria(filters)})`;
|
|
157
|
+
}
|
|
158
|
+
/** The zero-based time bucket of a request row. */
|
|
159
|
+
export function bucketIndex(db, filters) {
|
|
160
|
+
const start = timestamp(db, filters.start);
|
|
161
|
+
const seconds = db.dialect === "postgres"
|
|
162
|
+
? sql `extract(epoch from (r.received_at - ${start}))`
|
|
163
|
+
: sql `(unixepoch(r.received_at, 'subsec') - unixepoch(${start}, 'subsec'))`;
|
|
164
|
+
return sql `floor(${seconds} / ${filters.bucketSeconds})`;
|
|
165
|
+
}
|
|
166
|
+
/** The start of a time bucket, as the API writes it. */
|
|
167
|
+
export function bucketStart(filters, index) {
|
|
168
|
+
return formatInstant(filters.start + readInt(index) * filters.bucketSeconds * 1_000_000);
|
|
169
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { Params } from "./params.js";
|
|
2
|
+
import type { ActivityDb } from "./sql.js";
|
|
3
|
+
export declare const ACTIVITY_ROUTE: RegExp;
|
|
4
|
+
/** Activity as a platform provides it. */
|
|
5
|
+
export type ActivityPlatform = {
|
|
6
|
+
/** The database holding `routing_requests` and the tables Activity joins. */
|
|
7
|
+
db: ActivityDb;
|
|
8
|
+
/**
|
|
9
|
+
* The organization a request may read. `organizationRef` is the path's
|
|
10
|
+
* organization: an ID, or `current` for the one the bearer key belongs to.
|
|
11
|
+
* Throws HttpError 401 for a caller it cannot authenticate, and 403 or 404
|
|
12
|
+
* for one that is not an admin of the organization. Its message is the
|
|
13
|
+
* response's `detail`.
|
|
14
|
+
*/
|
|
15
|
+
authorize(request: Request, organizationRef: string): Promise<{
|
|
16
|
+
organizationId: string;
|
|
17
|
+
}>;
|
|
18
|
+
/** A retained payload's bytes, or null when nothing is stored there. */
|
|
19
|
+
readBlob(bucket: string, key: string): Promise<BodyInit | null>;
|
|
20
|
+
};
|
|
21
|
+
/** One Activity request, as a route reads it. */
|
|
22
|
+
export type ActivityRequest = {
|
|
23
|
+
db: ActivityDb;
|
|
24
|
+
platform: ActivityPlatform;
|
|
25
|
+
params: Params;
|
|
26
|
+
/** The route's own path segments, such as `conversation_ref`. */
|
|
27
|
+
path: Record<string, string>;
|
|
28
|
+
/**
|
|
29
|
+
* The organization the caller may read. Routes call it after reading their
|
|
30
|
+
* parameters, so a malformed request fails with 422 or 400 before an
|
|
31
|
+
* authenticated non-admin learns it is not one.
|
|
32
|
+
*/
|
|
33
|
+
admitted(): string;
|
|
34
|
+
};
|
|
35
|
+
export type ActivityRoute = (request: ActivityRequest) => Promise<Response | object>;
|
|
36
|
+
/** Serve an Activity request; null when the path is not one of its routes. */
|
|
37
|
+
export declare function handleActivityRequest(request: Request, platform: ActivityPlatform | undefined): Promise<Response | null>;
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/* Activity's HTTP surface: `GET /v1/organizations/{organization}/routing/
|
|
2
|
+
activity/...`, the reads behind the Activity dashboard and `dari activity`.
|
|
3
|
+
Every platform serves the same routes over its own database; the platform
|
|
4
|
+
only says who is asking and where retained payloads live. */
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
import { HttpError } from "../http/errors.js";
|
|
7
|
+
import { activityError, Params } from "./params.js";
|
|
8
|
+
import { ACTIVITY_ROUTES } from "./routes.js";
|
|
9
|
+
export const ACTIVITY_ROUTE = /^\/v1\/organizations\/([^/]+)\/routing\/activity\/(.+)$/;
|
|
10
|
+
/** Serve an Activity request; null when the path is not one of its routes. */
|
|
11
|
+
export async function handleActivityRequest(request, platform) {
|
|
12
|
+
const url = new URL(request.url);
|
|
13
|
+
const match = ACTIVITY_ROUTE.exec(url.pathname);
|
|
14
|
+
if (match === null)
|
|
15
|
+
return null;
|
|
16
|
+
if (request.method === "OPTIONS")
|
|
17
|
+
return withCors(new Response(null, { status: 204 }));
|
|
18
|
+
// Every answer names its request, and an error carries the same ID, as
|
|
19
|
+
// Dari's API always has, so a reported error can be found in the logs.
|
|
20
|
+
const requestId = `req_${randomUUID().replaceAll("-", "")}`;
|
|
21
|
+
try {
|
|
22
|
+
if (platform === undefined)
|
|
23
|
+
throw activityError(404, "Not Found");
|
|
24
|
+
const found = findRoute(match[2]);
|
|
25
|
+
if (found === null)
|
|
26
|
+
throw activityError(404, "Not Found");
|
|
27
|
+
if (request.method !== "GET")
|
|
28
|
+
throw activityError(405, "Method Not Allowed");
|
|
29
|
+
let organizationId = null;
|
|
30
|
+
let refused = null;
|
|
31
|
+
try {
|
|
32
|
+
({ organizationId } = await platform.authorize(request, decodePathSegment(match[1])));
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
if (!(error instanceof HttpError) || error.status === 401)
|
|
36
|
+
throw error;
|
|
37
|
+
refused = error;
|
|
38
|
+
}
|
|
39
|
+
const result = await found.route({
|
|
40
|
+
db: platform.db,
|
|
41
|
+
platform,
|
|
42
|
+
params: new Params(url.searchParams),
|
|
43
|
+
path: found.path,
|
|
44
|
+
admitted() {
|
|
45
|
+
if (refused !== null)
|
|
46
|
+
throw refused;
|
|
47
|
+
return organizationId;
|
|
48
|
+
},
|
|
49
|
+
});
|
|
50
|
+
return withCors(result instanceof Response ? result : jsonResponse(result), requestId);
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
if (error instanceof HttpError) {
|
|
54
|
+
const body = { ...(error.body ?? { detail: error.message }), request_id: requestId };
|
|
55
|
+
return withCors(jsonResponse(body, error.status), requestId);
|
|
56
|
+
}
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
function findRoute(rest) {
|
|
61
|
+
const segments = rest.split("/");
|
|
62
|
+
for (const [pattern, route] of ACTIVITY_ROUTES) {
|
|
63
|
+
const parts = pattern.split("/");
|
|
64
|
+
if (parts.length !== segments.length)
|
|
65
|
+
continue;
|
|
66
|
+
const path = {};
|
|
67
|
+
const matches = parts.every((part, index) => {
|
|
68
|
+
const segment = segments[index];
|
|
69
|
+
if (part.startsWith(":")) {
|
|
70
|
+
if (segment === "")
|
|
71
|
+
return false;
|
|
72
|
+
path[part.slice(1)] = decodePathSegment(segment);
|
|
73
|
+
return true;
|
|
74
|
+
}
|
|
75
|
+
return part === segment;
|
|
76
|
+
});
|
|
77
|
+
if (matches)
|
|
78
|
+
return { route, path };
|
|
79
|
+
}
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
// A malformed escape stays as written, as the API reads it, rather than
|
|
83
|
+
// failing the request.
|
|
84
|
+
function decodePathSegment(segment) {
|
|
85
|
+
try {
|
|
86
|
+
return decodeURIComponent(segment);
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return segment;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function jsonResponse(body, status = 200) {
|
|
93
|
+
return new Response(JSON.stringify(body), {
|
|
94
|
+
status,
|
|
95
|
+
headers: { "Content-Type": "application/json" },
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
// The dashboard calls Activity from its own origin with a bearer token; no
|
|
99
|
+
// cookie authorizes anything here, so any origin may call.
|
|
100
|
+
function withCors(response, requestId) {
|
|
101
|
+
if (requestId !== undefined)
|
|
102
|
+
response.headers.set("X-Request-Id", requestId);
|
|
103
|
+
response.headers.set("Access-Control-Allow-Origin", "*");
|
|
104
|
+
response.headers.set("Access-Control-Allow-Methods", "GET, OPTIONS");
|
|
105
|
+
response.headers.set("Access-Control-Allow-Headers", "Authorization, Content-Type");
|
|
106
|
+
response.headers.set("Access-Control-Expose-Headers", "X-Dari-Request-Format, X-Request-Id");
|
|
107
|
+
response.headers.set("Access-Control-Max-Age", "600");
|
|
108
|
+
return response;
|
|
109
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { HttpError } from "../http/errors.js";
|
|
2
|
+
import { type Instant } from "./values.js";
|
|
3
|
+
/** An Activity error: `{"detail": ...}` with its status, as the API answers. */
|
|
4
|
+
export declare function activityError(status: number, detail: unknown): HttpError;
|
|
5
|
+
export declare function badRequest(message: string): HttpError;
|
|
6
|
+
export declare function notFound(message: string): HttpError;
|
|
7
|
+
export declare class Params {
|
|
8
|
+
private readonly search;
|
|
9
|
+
private readonly issues;
|
|
10
|
+
constructor(search: URLSearchParams);
|
|
11
|
+
private last;
|
|
12
|
+
private fail;
|
|
13
|
+
/** A required parameter's raw text. */
|
|
14
|
+
private required;
|
|
15
|
+
string(name: string, options?: {
|
|
16
|
+
minLength?: number;
|
|
17
|
+
maxLength?: number;
|
|
18
|
+
}): string | undefined;
|
|
19
|
+
strings(name: string): string[];
|
|
20
|
+
int(name: string, options?: {
|
|
21
|
+
default?: number;
|
|
22
|
+
ge?: number;
|
|
23
|
+
le?: number;
|
|
24
|
+
}): number;
|
|
25
|
+
literal<T extends string>(name: string, values: readonly T[]): T | undefined;
|
|
26
|
+
literal<T extends string>(name: string, values: readonly T[], fallback: T): T;
|
|
27
|
+
/** Fail with 422 when a required parameter is absent; read it with another method too. */
|
|
28
|
+
requirePresent(name: string): void;
|
|
29
|
+
/** A repeated literal parameter; null when absent. Each bad item fails. */
|
|
30
|
+
literals<T extends string>(name: string, values: readonly T[]): T[] | null;
|
|
31
|
+
/** A boolean, read the way pydantic reads one from a query. */
|
|
32
|
+
bool(name: string, fallback: boolean): boolean;
|
|
33
|
+
/** A required datetime; `naive` when it has no UTC offset. */
|
|
34
|
+
instant(name: string): {
|
|
35
|
+
instant: Instant;
|
|
36
|
+
naive: boolean;
|
|
37
|
+
};
|
|
38
|
+
/** Fail with 422 when any parameter could not be read. */
|
|
39
|
+
done(): void;
|
|
40
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/* Query parameters as Dari's API has always validated them: a parameter that
|
|
2
|
+
cannot be read fails the request with 422 and a FastAPI-shaped `detail`
|
|
3
|
+
list naming every bad parameter, before any other check runs. */
|
|
4
|
+
import { HttpError } from "../http/errors.js";
|
|
5
|
+
import { parseInstantText } from "./values.js";
|
|
6
|
+
/** An Activity error: `{"detail": ...}` with its status, as the API answers. */
|
|
7
|
+
export function activityError(status, detail) {
|
|
8
|
+
return new HttpError(status, typeof detail === "string" ? detail : "Invalid request.", "activity_error", undefined, undefined, { detail });
|
|
9
|
+
}
|
|
10
|
+
export function badRequest(message) {
|
|
11
|
+
return activityError(400, message);
|
|
12
|
+
}
|
|
13
|
+
export function notFound(message) {
|
|
14
|
+
return activityError(404, message);
|
|
15
|
+
}
|
|
16
|
+
export class Params {
|
|
17
|
+
search;
|
|
18
|
+
issues = [];
|
|
19
|
+
constructor(search) {
|
|
20
|
+
this.search = search;
|
|
21
|
+
}
|
|
22
|
+
last(name) {
|
|
23
|
+
return this.search.getAll(name).at(-1);
|
|
24
|
+
}
|
|
25
|
+
fail(name, type, msg, input) {
|
|
26
|
+
this.issues.push({ type, loc: ["query", name], msg, ...(input === undefined ? {} : { input }) });
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
/** A required parameter's raw text. */
|
|
30
|
+
required(name) {
|
|
31
|
+
const value = this.last(name);
|
|
32
|
+
if (value === undefined)
|
|
33
|
+
this.fail(name, "missing", "Field required");
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
string(name, options = {}) {
|
|
37
|
+
const value = this.last(name);
|
|
38
|
+
if (value === undefined)
|
|
39
|
+
return undefined;
|
|
40
|
+
if (options.minLength !== undefined && value.length < options.minLength) {
|
|
41
|
+
return this.fail(name, "string_too_short", `String should have at least ${options.minLength} character${options.minLength === 1 ? "" : "s"}`, value);
|
|
42
|
+
}
|
|
43
|
+
if (options.maxLength !== undefined && value.length > options.maxLength) {
|
|
44
|
+
return this.fail(name, "string_too_long", `String should have at most ${options.maxLength} characters`, value);
|
|
45
|
+
}
|
|
46
|
+
return value;
|
|
47
|
+
}
|
|
48
|
+
strings(name) {
|
|
49
|
+
return this.search.getAll(name);
|
|
50
|
+
}
|
|
51
|
+
int(name, options = {}) {
|
|
52
|
+
const text = options.default === undefined ? this.required(name) : this.last(name);
|
|
53
|
+
if (text === undefined)
|
|
54
|
+
return options.default ?? 0;
|
|
55
|
+
// Pydantic also reads a float string with a zero fraction, such as "3600.0".
|
|
56
|
+
if (!/^\s*[+-]?\d+(\.0*)?\s*$/.test(text)) {
|
|
57
|
+
this.fail(name, "int_parsing", "Input should be a valid integer, unable to parse string as an integer", text);
|
|
58
|
+
return 0;
|
|
59
|
+
}
|
|
60
|
+
const value = Number(text);
|
|
61
|
+
if (options.ge !== undefined && value < options.ge) {
|
|
62
|
+
this.fail(name, "greater_than_equal", `Input should be greater than or equal to ${options.ge}`, text);
|
|
63
|
+
}
|
|
64
|
+
else if (options.le !== undefined && value > options.le) {
|
|
65
|
+
this.fail(name, "less_than_equal", `Input should be less than or equal to ${options.le}`, text);
|
|
66
|
+
}
|
|
67
|
+
return value;
|
|
68
|
+
}
|
|
69
|
+
literal(name, values, fallback) {
|
|
70
|
+
const value = this.last(name);
|
|
71
|
+
if (value === undefined)
|
|
72
|
+
return fallback;
|
|
73
|
+
if (!values.includes(value)) {
|
|
74
|
+
const expected = values.map((v) => `'${v}'`);
|
|
75
|
+
const list = expected.length > 1 ? `${expected.slice(0, -1).join(", ")} or ${expected.at(-1)}` : expected[0];
|
|
76
|
+
this.fail(name, "literal_error", `Input should be ${list}`, value);
|
|
77
|
+
return fallback;
|
|
78
|
+
}
|
|
79
|
+
return value;
|
|
80
|
+
}
|
|
81
|
+
/** Fail with 422 when a required parameter is absent; read it with another method too. */
|
|
82
|
+
requirePresent(name) {
|
|
83
|
+
this.required(name);
|
|
84
|
+
}
|
|
85
|
+
/** A repeated literal parameter; null when absent. Each bad item fails. */
|
|
86
|
+
literals(name, values) {
|
|
87
|
+
const items = this.search.getAll(name);
|
|
88
|
+
if (items.length === 0)
|
|
89
|
+
return null;
|
|
90
|
+
for (const item of items) {
|
|
91
|
+
if (!values.includes(item))
|
|
92
|
+
this.fail(name, "literal_error", "Input should be one of the allowed values", item);
|
|
93
|
+
}
|
|
94
|
+
return items;
|
|
95
|
+
}
|
|
96
|
+
/** A boolean, read the way pydantic reads one from a query. */
|
|
97
|
+
bool(name, fallback) {
|
|
98
|
+
const value = this.last(name);
|
|
99
|
+
if (value === undefined)
|
|
100
|
+
return fallback;
|
|
101
|
+
const text = value.trim().toLowerCase();
|
|
102
|
+
if (["1", "on", "t", "true", "y", "yes"].includes(text))
|
|
103
|
+
return true;
|
|
104
|
+
if (["0", "off", "f", "false", "n", "no"].includes(text))
|
|
105
|
+
return false;
|
|
106
|
+
this.fail(name, "bool_parsing", "Input should be a valid boolean, unable to interpret input", value);
|
|
107
|
+
return fallback;
|
|
108
|
+
}
|
|
109
|
+
/** A required datetime; `naive` when it has no UTC offset. */
|
|
110
|
+
instant(name) {
|
|
111
|
+
const text = this.required(name);
|
|
112
|
+
if (text === undefined)
|
|
113
|
+
return { instant: 0, naive: false };
|
|
114
|
+
const parsed = parseInstantText(text);
|
|
115
|
+
if (parsed === null) {
|
|
116
|
+
this.fail(name, "datetime_from_date_parsing", "Input should be a valid datetime or date", text);
|
|
117
|
+
return { instant: 0, naive: false };
|
|
118
|
+
}
|
|
119
|
+
return parsed;
|
|
120
|
+
}
|
|
121
|
+
/** Fail with 422 when any parameter could not be read. */
|
|
122
|
+
done() {
|
|
123
|
+
if (this.issues.length > 0) {
|
|
124
|
+
throw new HttpError(422, "Request validation failed", "activity_error", undefined, undefined, {
|
|
125
|
+
detail: "Request validation failed",
|
|
126
|
+
errors: this.issues,
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|