@mastra/schema-compat
Version:
Tool schema compatibility layer for Mastra.ai
108 lines (106 loc) • 3.06 kB
JavaScript
;
// src/standard-schema/adapters/ai-sdk.ts
var VENDOR = "ai-sdk";
var AiSdkSchemaWrapper = class {
#schema;
"~standard";
constructor(schema) {
this.#schema = schema;
this["~standard"] = {
version: 1,
vendor: VENDOR,
validate: this.#validate.bind(this),
jsonSchema: {
input: this.#toJsonSchema.bind(this),
output: this.#toJsonSchema.bind(this)
}
};
}
/**
* Validates a value against the AI SDK Schema.
*
* @param value - The value to validate
* @returns A result object with either the validated value or validation issues
*/
#validate(value) {
if (!this.#schema.validate) {
return { value };
}
try {
const result = this.#schema.validate(value);
if (result && typeof result === "object" && "then" in result && typeof result.then === "function") {
return Promise.resolve(
result
).then((res) => this.#convertValidationResult(res)).catch((error) => {
const message = error instanceof Error ? error.message : "Unknown validation error";
return {
issues: [{ message: `Schema validation error: ${message}` }]
};
});
}
return this.#convertValidationResult(
result
);
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown validation error";
return {
issues: [{ message: `Schema validation error: ${message}` }]
};
}
}
/**
* Converts an AI SDK ValidationResult to a StandardSchemaV1.Result.
*
* @param result - The AI SDK validation result
* @returns A StandardSchemaV1.Result
*/
#convertValidationResult(result) {
if (result.success) {
return { value: result.value };
}
const failureResult = result;
return {
issues: [{ message: failureResult.error.message }]
};
}
/**
* Returns the JSON Schema in the requested target format.
*
* @param options - Options including the target format
* @returns The JSON Schema as a Record
*/
#toJsonSchema(options) {
const { target } = options;
const clonedSchema = JSON.parse(JSON.stringify(this.#schema.jsonSchema));
if (!clonedSchema.$schema) {
switch (target) {
case "draft-07":
clonedSchema.$schema = "http://json-schema.org/draft-07/schema#";
break;
case "draft-2020-12":
clonedSchema.$schema = "https://json-schema.org/draft/2020-12/schema";
break;
}
}
return clonedSchema;
}
/**
* Returns the original AI SDK Schema.
*/
getSchema() {
return this.#schema;
}
/**
* Returns the original JSON Schema from the AI SDK Schema.
*/
getJsonSchema() {
return this.#schema.jsonSchema;
}
};
function toStandardSchema(schema) {
return new AiSdkSchemaWrapper(schema);
}
exports.AiSdkSchemaWrapper = AiSdkSchemaWrapper;
exports.toStandardSchema = toStandardSchema;
//# sourceMappingURL=chunk-FS3P4V5M.cjs.map
//# sourceMappingURL=chunk-FS3P4V5M.cjs.map