UNPKG

@cdwr/core

Version:

A set of core utilities for the Codeware ecosystem.

86 lines (83 loc) 2.31 kB
// packages/core/src/lib/zod/json.schema.ts import { z } from "zod"; var LiteralSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]); var JsonSchema = z.lazy( () => z.union([LiteralSchema, z.array(JsonSchema), z.record(JsonSchema)]) ); // packages/core/src/lib/zod/with-camel-case.preprocess.ts import { z as z2 } from "zod"; var toCamelCase = (str, specialCases = {}) => { if (specialCases[str]) { return specialCases[str]; } if (str.includes("_")) { return str.toLowerCase().replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()); } if (str === str.toUpperCase()) { return str.toLowerCase(); } return str.charAt(0).toLowerCase() + str.slice(1); }; var transformKeys = (options) => { const { currentPath, data, preserve, specialCases } = options; if (Array.isArray(data)) { return data.map( (item) => transformKeys({ currentPath, data: item, preserve, specialCases }) ); } if (data && typeof data === "object" && data !== null) { return Object.entries(data).reduce((acc, [key, value]) => { const shouldPreserveValue = preserve.some( (path) => [...currentPath, key].join(".").match(new RegExp(`^${path}.`)) ); const newKey = shouldPreserveValue ? key : toCamelCase(key, specialCases); const newPath = [...currentPath, newKey]; return { ...acc, [newKey]: transformKeys({ currentPath: newPath, data: value, preserve, specialCases }) }; }, {}); } return data; }; var withCamelCase = (schema, options = {}) => { const { preserve = [], specialCases = {} } = options; return z2.preprocess( (data) => transformKeys({ currentPath: [], data, preserve, specialCases }), schema ); }; // packages/core/src/lib/zod/with-replace-all.preprocess.ts import { z as z3 } from "zod"; var withReplaceAll = (schema, options) => { const { match, value, strict = false } = options; return z3.preprocess((data) => { if (typeof data !== "string") { return data; } if (strict && !value) { return data; } return data.replaceAll(match, value?.toString() ?? ""); }, schema); }; export { JsonSchema, withCamelCase, withReplaceAll };