import type { PageAttributes } from "../site/attributes"; import { defaultsDeep as applyDefaultsDeep } from "lodash-es"; import { Validator } from "@cfworker/json-schema"; // JSON Schema type definitions type JSONSchema = Record; type JSONSchemaObject = JSONSchema & { type: "object"; properties: Record }; type JSONSchemaArray = JSONSchema & { type: "array"; items: JSONSchema }; // Helper functions to check schema types (working with JSON Schema objects, not Zod) function isObjectSchema(schema: any): schema is JSONSchemaObject { return schema && typeof schema === "object" && schema.type === "object" && "properties" in schema; } function isArraySchema(schema: any): schema is JSONSchemaArray { return schema && typeof schema === "object" && schema.type === "array" && "items" in schema; } export function normalizeSchemaEnum(schema: JSONSchema): Array<{ const: string; title: string }> { if (!("enum" in schema)) { // If no enum, check for anyOf/oneOf // @ts-ignore return schema.anyOf ?? schema.oneOf; } const { enum: enumValues, enumNames, "ui:icons": icons, } = schema as unknown as { enum: string[]; enumNames?: string[]; "ui:icons"?: string[] }; // combine to key-value pairs return enumValues.map((value, index) => ({ const: value, title: enumNames ? enumNames[index] : value, "ui:icon": icons ? icons[index] : undefined, })); } export function getSchemaDefaults( schema: T, mode?: "mobile" | "desktop", ): any | undefined { // Handle object schemas if (isObjectSchema(schema)) { const objectSchema = schema as JSONSchemaObject; const propertiesWithDefaults: Record = {}; for (const [key, propertySchema] of Object.entries(objectSchema.properties)) { const defaultValue = getNestedDefaults(propertySchema as JSONSchema, mode); if (defaultValue !== undefined) { propertiesWithDefaults[key] = defaultValue; } } // If we get here, all required properties have defaults, so we can include all properties return propertiesWithDefaults; } // Handle array schemas if (isArraySchema(schema)) { const arraySchema = schema as JSONSchemaArray; // @ts-ignore if (mode && typeof arraySchema[`default:${mode}`] !== "undefined") { // @ts-ignore return arraySchema[`default:${mode}`]; } // Otherwise return empty array // @ts-ignore return arraySchema.default ?? []; } } // Helper function for nested schema processing function getNestedDefaults(schema: JSONSchema, mode?: "mobile" | "desktop"): unknown { // @ts-ignore if (mode && typeof schema[`default:${mode}`] !== "undefined") { // @ts-ignore return schema[`default:${mode}`] as string; } // Handle schemas with explicit default values if ("default" in schema && schema.default !== undefined) { return schema.default; } // Handle nested object schemas if (isObjectSchema(schema)) { const objectSchema = schema as JSONSchemaObject; const required = objectSchema.required || []; // First pass: collect all properties that have defaults const propertiesWithDefaults: Record = {}; for (const [key, propertySchema] of Object.entries(objectSchema.properties)) { const defaultValue = getNestedDefaults(propertySchema as JSONSchema, mode); if (defaultValue !== undefined) { propertiesWithDefaults[key] = defaultValue; } } // Second pass: validate that all required properties have defaults // If any required property lacks a default, this nested object cannot be included for (const requiredProp of required) { if (!(requiredProp in propertiesWithDefaults)) { return undefined; } } // If we get here, all required properties have defaults return Object.keys(propertiesWithDefaults).length > 0 ? propertiesWithDefaults : undefined; } // Handle nested array schemas if (isArraySchema(schema)) { // Arrays only contribute defaults if explicitly set return undefined; } // No implicit defaults for any type return undefined; } export type FieldFilter< T extends JSONSchema = JSONSchema, P extends Record = Record, > = (propsSchema: T, formData: P, pageAttributes: PageAttributes) => boolean; export function filterSchemaProperties(schema: JSONSchemaObject, filter: (prop: JSONSchema) => boolean) { function extractProperties(schema: JSONSchemaObject): Record { const props: Record = {}; for (const [key, prop] of Object.entries(schema.properties)) { if (filter(prop)) { props[key] = prop; } else if (isObjectSchema(prop)) { const nestedContentProps = extractProperties(prop as JSONSchemaObject); if (Object.keys(nestedContentProps).length > 0) { Object.assign(props, nestedContentProps); } } } return props; } return extractProperties(schema); } export function validate(schema: JSONSchema, data: unknown): T { const validator = new Validator(schema, "7", false); const result = validator.validate(data); if (!result.valid) { const errors = []; for (const error of result.errors) { errors.push(`${error.error} (at ${error.keywordLocation})`); } const formatedError = `- ${errors.join("\n- ")}`; throw new Error(formatedError); } // Mutate data with defaults const defaults = getSchemaDefaults(schema as JSONSchemaObject | JSONSchemaArray); const finalObject = Array.isArray(data) ? data : applyDefaultsDeep({}, data, defaults); return finalObject as T; }