@devries-cameron20 / composio Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 04:45 UTC

next
ts 48 lines 1.83 KB
Raw
1 import { Data, Predicate, Result } from 'effect';
2 import JSON5 from 'json5';
3
4 export class JsonParsingError extends Data.TaggedError('JsonParsingError')<{
5 /**
6 * `syntax` — the input is not parseable at all;
7 * `not-a-record` — valid JSON, but an array/scalar/null instead of an object.
8 */
9 reason: 'syntax' | 'not-a-record';
10 cause: unknown;
11 }> {}
12
13 // Predicate.isRecord was removed in v4; Predicate.isObject also matches
14 // arrays, so exclude those explicitly.
15 export const isPlainRecord = (value: unknown): value is Record<string, unknown> =>
16 Predicate.isObject(value) && !Array.isArray(value);
17
18 /**
19 * Parses JSON or a JS-style object literal (unquoted keys, single quotes,
20 * trailing commas, comments) into a record. JSON5 covers the documented
21 * "JSON or JS-style object literal" contract without evaluating the input.
22 * Inputs that parse to anything other than an object (arrays, scalars,
23 * `null`) fail with `JsonParsingError`.
24 *
25 * Returns a `Result` because parsing is synchronous. A `Result` implements
26 * `Symbol.iterator`, so `yield*` on it type-checks — but at runtime a `Result`
27 * is not an `Effect`, and yielding one dies the fiber with "Not a valid
28 * effect". Lift it explicitly with `Effect.fromResult(...)` before yielding,
29 * or stay in `Result` land with the `Result.*` combinators.
30 */
31 export const parseJsonRecord = (
32 raw: string
33 ): Result.Result<Record<string, unknown>, JsonParsingError> =>
34 Result.try({
35 try: (): unknown => JSON5.parse(raw),
36 catch: cause => new JsonParsingError({ reason: 'syntax', cause }),
37 }).pipe(
38 Result.filterOrFail(
39 isPlainRecord,
40 parsed =>
41 new JsonParsingError({
42 reason: 'not-a-record',
43 cause: new Error(
44 `Expected a JSON object, received ${Array.isArray(parsed) ? 'an array' : typeof parsed}`
45 ),
46 })
47 )
48 );