UNPKG

pulse-ai-utils

Version:

Utility functions and helpers for AI-powered applications

76 lines 2.61 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.buildUnionSchema = buildUnionSchema; exports.buildResponseSchema = buildResponseSchema; const zod_1 = require("zod"); const pulseSchemas_1 = require("./pulseSchemas"); const content_types_config_1 = require("../config/content-types-config"); /** * Build a union schema from multiple category schemas * This is the same logic used in runQuery to create a unified schema */ function buildUnionSchema(categories) { // Get schemas for each category let schemas = []; try { schemas = categories.map(c => (0, pulseSchemas_1.getSchemaByCategory)(String(c)).zod); } catch (e) { throw new Error('Invalid category'); } const shapes = schemas.map(s => s.shape); const fieldCounts = {}; const unionShape = {}; const fieldTypes = {}; // Count field occurrences and collect types for (const shape of shapes) { for (const [key, value] of Object.entries(shape)) { fieldCounts[key] = (fieldCounts[key] || 0) + 1; if (!fieldTypes[key]) fieldTypes[key] = []; fieldTypes[key].push(value); } } const totalSchemas = shapes.length; // Build union shape for (const key of Object.keys(fieldTypes)) { const uniqueTypes = []; const seen = new Set(); // Deduplicate types for (const t of fieldTypes[key]) { const sig = t.toString(); if (!seen.has(sig)) { uniqueTypes.push(t); seen.add(sig); } } // Merge types let merged; if (uniqueTypes.length === 1) { merged = uniqueTypes[0]; } else { merged = uniqueTypes.reduce((a, b) => a.or(b)); } // Make optional if not in all schemas if (fieldCounts[key] !== totalSchemas) { const optionalMerged = zod_1.z.optional(merged); unionShape[key] = optionalMerged; } else { unionShape[key] = merged; } } // Create dynamic enum based on enabled content types const enabledTypes = (0, content_types_config_1.getEnabledContentTypes)(); unionShape['category'] = zod_1.z.enum(enabledTypes); return zod_1.z.object(unionShape); } /** * Build the standard response schema with union items */ function buildResponseSchema(categories) { const ItemSchema = buildUnionSchema(categories); return zod_1.z.object({ data: zod_1.z.array(ItemSchema) }); } //# sourceMappingURL=buildUnionSchema.js.map