refactor: Replace json-schema-to-zod with our own fork (#11229)

This commit is contained in:
Tomi Turtiainen
2024-10-18 08:29:19 +02:00
committed by GitHub
parent c57cac9e4d
commit a042d5c8e6
7 changed files with 55 additions and 121 deletions

View File

@@ -1,67 +1,10 @@
import { makeResolverFromLegacyOptions } from '@n8n/vm2';
import { jsonSchemaToZod } from '@n8n/json-schema-to-zod';
import { json as generateJsonSchema } from 'generate-schema';
import type { SchemaObject } from 'generate-schema';
import type { JSONSchema7 } from 'json-schema';
import { JavaScriptSandbox } from 'n8n-nodes-base/dist/nodes/Code/JavaScriptSandbox';
import { getSandboxContext } from 'n8n-nodes-base/dist/nodes/Code/Sandbox';
import type { IExecuteFunctions } from 'n8n-workflow';
import { NodeOperationError, jsonParse } from 'n8n-workflow';
const vmResolver = makeResolverFromLegacyOptions({
external: {
modules: ['json-schema-to-zod', 'zod'],
transitive: false,
},
resolve(moduleName, parentDirname) {
if (moduleName === 'json-schema-to-zod') {
return require.resolve(
'@n8n/n8n-nodes-langchain/node_modules/json-schema-to-zod/dist/cjs/jsonSchemaToZod.js',
{
paths: [parentDirname],
},
);
}
if (moduleName === 'zod') {
return require.resolve('@n8n/n8n-nodes-langchain/node_modules/zod.cjs', {
paths: [parentDirname],
});
}
return;
},
builtin: [],
});
export function getSandboxWithZod(ctx: IExecuteFunctions, schema: JSONSchema7, itemIndex: number) {
const context = getSandboxContext.call(ctx, itemIndex);
let itemSchema: JSONSchema7 = schema;
try {
// If the root type is not defined, we assume it's an object
if (itemSchema.type === undefined) {
itemSchema = {
type: 'object',
properties: itemSchema.properties ?? (itemSchema as { [key: string]: JSONSchema7 }),
};
}
} catch (error) {
throw new NodeOperationError(ctx.getNode(), 'Error during parsing of JSON Schema.');
}
// Make sure to remove the description from root schema
const { description, ...restOfSchema } = itemSchema;
const sandboxedSchema = new JavaScriptSandbox(
context,
`
const { z } = require('zod');
const { parseSchema } = require('json-schema-to-zod');
const zodSchema = parseSchema(${JSON.stringify(restOfSchema)});
const itemSchema = new Function('z', 'return (' + zodSchema + ')')(z)
return itemSchema
`,
ctx.helpers,
{ resolver: vmResolver },
);
return sandboxedSchema;
}
import type { z } from 'zod';
export function generateSchema(schemaString: string): JSONSchema7 {
const parsedSchema = jsonParse<SchemaObject>(schemaString);
@@ -69,6 +12,10 @@ export function generateSchema(schemaString: string): JSONSchema7 {
return generateJsonSchema(parsedSchema) as JSONSchema7;
}
export function convertJsonSchemaToZod<T extends z.ZodTypeAny = z.ZodTypeAny>(schema: JSONSchema7) {
return jsonSchemaToZod<T>(schema);
}
export function throwIfToolSchema(ctx: IExecuteFunctions, error: Error) {
if (error?.message?.includes('tool input did not match expected schema')) {
throw new NodeOperationError(