Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
ts 120 lines 4.16 KB
Raw
1 /**
2 * The route model of the fake backend: how a request finds its handler, and
3 * what a handler may say about the request it served.
4 */
5
6 import { errorEnvelope } from './faults';
7 import type { RequestIdentity, ServiceRole } from './journal';
8 import type { SeededProject, World } from './world';
9
10 /** The base URLs the binary under test reaches the fake at, for links in response bodies. */
11 export interface PublicUrls {
12 readonly backend: string;
13 readonly dashboard: string;
14 }
15
16 export interface RouteContext {
17 readonly world: World;
18 readonly identity: RequestIdentity;
19 readonly params: Readonly<Record<string, string>>;
20 readonly query: URLSearchParams;
21 /** The parsed JSON body, or `undefined` when there is none. Parse it with zod before use. */
22 readonly body: unknown;
23 readonly headers: Headers;
24 readonly urls: PublicUrls;
25 /** The project the request is scoped to; set for `auth: 'project'` routes. */
26 readonly project: SeededProject | undefined;
27 }
28
29 export type RouteEffect = 'tool-executed' | 'connection-started';
30
31 export interface ExecutedTool {
32 readonly slug: string;
33 readonly arguments: Readonly<Record<string, unknown>>;
34 }
35
36 export interface RouteResult {
37 readonly status?: number;
38 readonly json?: unknown;
39 readonly text?: string;
40 readonly bytes?: Uint8Array;
41 readonly headers?: Readonly<Record<string, string>>;
42 /**
43 * What the request changed, when it changed something. A Dashboard execution
44 * answers 200 whether or not the tool ran, so a status alone cannot tell.
45 */
46 readonly effect?: RouteEffect;
47 /** The tool a `tool-executed` request ran, with the arguments it ran with. */
48 readonly tool?: ExecutedTool;
49 /** Overrides the journal's project and user for this request (a session implies both). */
50 readonly acted?: { readonly project?: string | null; readonly userId?: string | null };
51 }
52
53 /**
54 * Who may call a route.
55 *
56 * - `none`: no credential needed.
57 * - `user`: the seeded user API key.
58 * - `key`: any credential the world issued; catalog reads need no project.
59 * - `project`: a project API key, or the user API key with `x-org-id` and `x-project-id`.
60 */
61 export type RouteAuth = 'none' | 'user' | 'key' | 'project';
62
63 export interface Route {
64 /**
65 * The client operation the route implements (`toolRouter.session.execute`),
66 * or a name of its own for endpoints `@composio/client` does not type.
67 */
68 readonly name: string;
69 readonly role: ServiceRole;
70 readonly method: 'GET' | 'POST' | 'PATCH' | 'DELETE';
71 /** Path template; `:name` captures one segment. `/api/:v/` accepts `v3` and `v3.1`. */
72 readonly path: string;
73 /**
74 * Whether `name` is a key of the client's response schema table, which the
75 * contract test decodes this route's success response with.
76 */
77 readonly typed: boolean;
78 readonly auth: RouteAuth;
79 readonly handle: (context: RouteContext) => RouteResult;
80 }
81
82 const API_VERSIONS = new Set(['v3', 'v3.1']);
83
84 /** The captures of `path` against `template`, or `undefined` when it does not match. */
85 export const matchPath = (template: string, path: string): Record<string, string> | undefined => {
86 const wanted = template.split('/');
87 const actual = path.split('/');
88 if (wanted.length !== actual.length) return undefined;
89 const params: Record<string, string> = {};
90 for (const [index, segment] of wanted.entries()) {
91 const value = actual[index] ?? '';
92 if (segment.startsWith(':')) {
93 if (value === '') return undefined;
94 if (segment === ':v' && !API_VERSIONS.has(value)) return undefined;
95 params[segment.slice(1)] = decodeURIComponent(value);
96 } else if (segment !== value) {
97 return undefined;
98 }
99 }
100 return params;
101 };
102
103 export const notFound = (message: string, slug = 'Resource_NotFound'): RouteResult => ({
104 status: 404,
105 json: errorEnvelope({ status: 404, message, slug }),
106 });
107
108 export const badRequest = (message: string, slug = 'Request_Invalid'): RouteResult => ({
109 status: 400,
110 json: errorEnvelope({ status: 400, message, slug }),
111 });
112
113 /** One page holding every item: the seeded lists never need a second one. */
114 export const singlePage = <T>(items: ReadonlyArray<T>) => ({
115 items,
116 next_cursor: null,
117 total_pages: 1,
118 current_page: 1,
119 total_items: items.length,
120 });