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 52 lines 1.82 KB
Raw
1 import type { ObjectPolicy, RunFailure, RunResult, WholeSchemaGuard } from './types';
2
3 /** An object schema the object policies can be applied to. */
4 type PolicyBase<S> = S & {
5 strict(): S;
6 passthrough(): S;
7 catchall(schema: S): S;
8 };
9
10 /** Anything with the zod parse surface the shared runner needs. */
11 type SafeParseLike = {
12 safeParse(
13 value: unknown
14 ):
15 | { success: true; data: unknown }
16 | { success: false; error: { issues: ReadonlyArray<unknown> } };
17 };
18
19 /** Spreads an optional relative issue path into an issue body. */
20 export const withPath = (path: ReadonlyArray<string | number> | undefined) =>
21 path === undefined ? {} : { path: [...path] };
22
23 /** Runs `guard` first and falls back to the guard already on the schema. */
24 export const composeGuards = (
25 guard: WholeSchemaGuard,
26 inner: WholeSchemaGuard | undefined
27 ): WholeSchemaGuard => (inner ? value => guard(value) ?? inner(value) : guard);
28
29 /** Runs the schema; the failure carries the backend's own error with its issues. */
30 export const run = (schema: SafeParseLike, value: unknown): RunResult => {
31 const result = schema.safeParse(value);
32 const { success } = result;
33 return success
34 ? { success, data: result.data }
35 : { success, failure: result.error as RunFailure };
36 };
37
38 /** Applies one of the object policies the parsers use to a built object schema. */
39 export const applyObjectPolicy = <S>(base: PolicyBase<S>, policy: ObjectPolicy<S>): S => {
40 switch (policy.kind) {
41 case 'strict':
42 return base.strict();
43 case 'loose':
44 return base.passthrough();
45 case 'catchall':
46 return base.catchall(policy.schema);
47 }
48 };
49
50 /** Attaches the rest schema to a tuple when the schema declares one. */
51 export const buildTuple = <S>(tuple: S & { rest(schema: S): S }, rest: S | undefined): S =>
52 rest === undefined ? tuple : tuple.rest(rest);