Skip to content

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

refactor(core): flatten dereferenceJsonSchema and extract helpers

jkomyno401021deb8a9
diff --git a/ts/packages/core/src/utils/jsonSchema.ts b/ts/packages/core/src/utils/jsonSchema.ts
index e22d1e60f..9d5bcbc45 100644
--- a/ts/packages/core/src/utils/jsonSchema.ts
+++ b/ts/packages/core/src/utils/jsonSchema.ts
@@ -4,51 +4,41 @@ import { jsonSchemaToZod } from '@composio/json-schema-to-zod';
const MAX_REF_CHAIN_DEPTH = 100;
const MAX_NODE_DEPTH = 512;
-const CYCLE_BREAK_SENTINEL = Object.freeze({ type: 'object', additionalProperties: true });
-const INTERNAL_REF_PREFIX = '#';
+const CYCLE_BREAK_SENTINEL = { type: 'object', additionalProperties: true } as const;
const decodePointerSegment = (segment: string): string =>
segment.replace(/~1/g, '/').replace(/~0/g, '~');
-const resolvePointer = (
- root: Record<string, unknown>,
- pointer: string
-): { target: unknown; canonical: string } => {
- if (pointer === '#' || pointer === '') {
- return { target: root, canonical: '#' };
+const failResolution = (pointer: string, segment: string): never => {
+ throw new JsonSchemaRefResolutionError(`Cannot resolve $ref ${pointer}`, {
+ meta: { ref: pointer, failedAt: segment },
+ });
+};
+
+const stepInto = (cursor: unknown, segment: string, pointer: string): unknown => {
+ if (cursor === null || typeof cursor !== 'object') failResolution(pointer, segment);
+ if (Array.isArray(cursor)) {
+ const i = Number(segment);
+ if (!Number.isInteger(i) || i < 0 || i >= cursor.length) failResolution(pointer, segment);
+ return cursor[i];
}
+ const obj = cursor as Record<string, unknown>;
+ if (!Object.prototype.hasOwnProperty.call(obj, segment)) failResolution(pointer, segment);
+ return obj[segment];
+};
+
+const resolvePointer = (root: Record<string, unknown>, pointer: string): unknown => {
+ if (pointer === '#' || pointer === '') return root;
if (!pointer.startsWith('#/')) {
throw new JsonSchemaRefResolutionError(`Unsupported $ref pointer: ${pointer}`, {
meta: { ref: pointer },
});
}
- const segments = pointer.slice(2).split('/').map(decodePointerSegment);
- let cursor: unknown = root;
- for (const segment of segments) {
- if (cursor === null || typeof cursor !== 'object') {
- throw new JsonSchemaRefResolutionError(`Cannot resolve $ref ${pointer}`, {
- meta: { ref: pointer, failedAt: segment },
- });
- }
- if (Array.isArray(cursor)) {
- const index = Number(segment);
- if (!Number.isInteger(index) || index < 0 || index >= cursor.length) {
- throw new JsonSchemaRefResolutionError(`Cannot resolve $ref ${pointer}`, {
- meta: { ref: pointer, failedAt: segment },
- });
- }
- cursor = cursor[index];
- } else {
- const obj = cursor as Record<string, unknown>;
- if (!Object.prototype.hasOwnProperty.call(obj, segment)) {
- throw new JsonSchemaRefResolutionError(`Cannot resolve $ref ${pointer}`, {
- meta: { ref: pointer, failedAt: segment },
- });
- }
- cursor = obj[segment];
- }
- }
- return { target: cursor, canonical: pointer };
+ return pointer
+ .slice(2)
+ .split('/')
+ .map(decodePointerSegment)
+ .reduce<unknown>((cursor, seg) => stepInto(cursor, seg, pointer), root);
};
const isPlainObject = (value: unknown): value is Record<string, unknown> =>
@@ -105,7 +95,24 @@ export function dereferenceJsonSchema<T = unknown>(schema: T): T {
const root = schema as Record<string, unknown>;
const visiting = new WeakSet<object>();
- const walk = (node: unknown, path: string[], depth: number, nodeDepth: number): unknown => {
+ const cloneChildren = (
+ obj: Record<string, unknown>,
+ visitedRefs: ReadonlySet<string>,
+ chainDepth: number,
+ nodeDepth: number
+ ): Record<string, unknown> =>
+ Object.fromEntries(
+ Object.entries(obj).map(([k, v]) => [k, walk(v, visitedRefs, chainDepth, nodeDepth + 1)])
+ );
+
+ // Function declaration so `cloneChildren` can reference `walk` despite being
+ // declared earlier (function declarations are hoisted within the closure).
+ function walk(
+ node: unknown,
+ visitedRefs: ReadonlySet<string>,
+ chainDepth: number,
+ nodeDepth: number
+ ): unknown {
if (nodeDepth >= MAX_NODE_DEPTH) {
throw new JsonSchemaRefResolutionError(
`JSON Schema node depth exceeded cap (${MAX_NODE_DEPTH})`
@@ -115,9 +122,7 @@ export function dereferenceJsonSchema<T = unknown>(schema: T): T {
if (visiting.has(node)) return { ...CYCLE_BREAK_SENTINEL };
visiting.add(node);
try {
- return node.map((item, index) =>
- walk(item, [...path, String(index)], depth, nodeDepth + 1)
- );
+ return node.map(item => walk(item, visitedRefs, chainDepth, nodeDepth + 1));
} finally {
visiting.delete(node);
}
@@ -126,62 +131,39 @@ export function dereferenceJsonSchema<T = unknown>(schema: T): T {
if (visiting.has(node)) return { ...CYCLE_BREAK_SENTINEL };
visiting.add(node);
try {
- if (typeof node.$ref === 'string') {
- const ref = node.$ref;
- // External refs are out of scope; leave them alone.
- if (!ref.startsWith(INTERNAL_REF_PREFIX)) {
- const cloned: Record<string, unknown> = {};
- for (const [key, value] of Object.entries(node)) {
- cloned[key] = walk(value, [...path, key], depth, nodeDepth + 1);
- }
- return cloned;
- }
-
- if (depth >= MAX_REF_CHAIN_DEPTH) {
- throw new JsonSchemaRefResolutionError(
- `JSON Schema $ref chain exceeded depth cap (${MAX_REF_CHAIN_DEPTH}): ${ref}`,
- { meta: { ref } }
- );
- }
-
- // Cycle detection: if `ref` already appears in the current path, this
- // resolution would re-enter itself. Break the cycle.
- if (path.includes(`@ref:${ref}`)) {
- return { ...CYCLE_BREAK_SENTINEL };
- }
-
- const { target } = resolvePointer(root, ref);
- const resolved = walk(target, [...path, `@ref:${ref}`], depth + 1, nodeDepth + 1);
+ const ref = typeof node.$ref === 'string' ? node.$ref : null;
+ // External refs and non-$ref nodes both pass through the same clone path.
+ if (ref === null || !ref.startsWith('#')) {
+ return cloneChildren(node, visitedRefs, chainDepth, nodeDepth);
+ }
- // Shallow-merge sibling keywords (Draft 2020-12 semantics: siblings win
- // on collision). Draft 7 ignores siblings entirely, but the Composio
- // tool surface admits both drafts so we honor siblings for safety.
- const { $ref: _omit, ...siblings } = node;
- void _omit;
- if (Object.keys(siblings).length === 0) {
- return resolved;
- }
- if (!isPlainObject(resolved)) {
- return resolved;
- }
- const merged: Record<string, unknown> = { ...resolved };
- for (const [key, value] of Object.entries(siblings)) {
- merged[key] = walk(value, [...path, key], depth, nodeDepth + 1);
- }
- return merged;
+ if (chainDepth >= MAX_REF_CHAIN_DEPTH) {
+ throw new JsonSchemaRefResolutionError(
+ `JSON Schema $ref chain exceeded depth cap (${MAX_REF_CHAIN_DEPTH}): ${ref}`,
+ { meta: { ref } }
+ );
}
+ if (visitedRefs.has(ref)) return { ...CYCLE_BREAK_SENTINEL };
+
+ const target = resolvePointer(root, ref);
+ const nextRefs = new Set(visitedRefs).add(ref);
+ const resolved = walk(target, nextRefs, chainDepth + 1, nodeDepth + 1);
- const cloned: Record<string, unknown> = {};
- for (const [key, value] of Object.entries(node)) {
- cloned[key] = walk(value, [...path, key], depth, nodeDepth + 1);
+ // Shallow-merge sibling keywords (Draft 2020-12 semantics: siblings win
+ // on collision). Draft 7 ignores siblings entirely, but the Composio
+ // tool surface admits both drafts so we honor siblings for safety.
+ const siblings: Record<string, unknown> = { ...node };
+ delete siblings.$ref;
+ if (Object.keys(siblings).length === 0 || !isPlainObject(resolved)) {
+ return resolved;
}
- return cloned;
+ return { ...resolved, ...cloneChildren(siblings, visitedRefs, chainDepth, nodeDepth) };
} finally {
visiting.delete(node);
}
- };
+ }
- const out = walk(root, [], 0, 0);
+ const out = walk(root, new Set(), 0, 0);
if (isPlainObject(out)) {
delete out.$defs;
delete out.definitions;