All files / src/utils shared.ts

63.85% Statements 53/83
44.92% Branches 31/69
55.55% Functions 5/9
62.96% Lines 51/81

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 26018x           18x               18x     6x     6x   6x                     6x                 6x 6x 5x     1x     18x                                               7802x         7802x   5177x           5177x                   1881x             1881x   398x           398x   270x                             270x   76x       76x               7802x     18x     1984x 1984x 1984x 76x     1908x 1908x 7532x   7532x                                       7532x                                                         7532x     7532x                   7532x 7528x     7532x 4245x   3287x       1908x     18x       121x 121x           18x 2x 2x   2x           1x      
import z from "zod";
 
type SchemaTypeToTsType = {
  [key: string]: unknown;
};
 
const PYDANTIC_TYPE_TO_TS_TYPE: SchemaTypeToTsType = {
  string: String,
  integer: Number,
  number: Number,
  boolean: Boolean,
  null: null,
};
 
export function jsonSchemaToTsType(
  jsonSchema: Record<string, unknown>
): unknown {
  Iif (!jsonSchema.type) {
    jsonSchema.type = "string";
  }
  const type = jsonSchema.type as string;
 
  Iif (type === "array") {
    const itemsSchema = jsonSchema.items;
    Iif (itemsSchema) {
      const ItemType = jsonSchemaToTsType(
        itemsSchema as Record<string, unknown>
      );
      return ItemType;
    }
    return Array;
  }
 
  Iif (type === "object") {
    const properties = jsonSchema.properties;
    Iif (properties) {
      const nestedModel = jsonSchemaToModel(jsonSchema);
      return nestedModel;
    }
    return Object;
  }
 
  const tsType = PYDANTIC_TYPE_TO_TS_TYPE[type];
  if (tsType !== undefined) {
    return tsType;
  }
 
  throw new Error(`Unsupported JSON schema type: ${type}`);
}
 
export function jsonSchemaToTsField(
  name: string,
  jsonSchema: Record<string, unknown>,
  required: string[]
): [unknown, Record<string, unknown>] {
  const description = jsonSchema.description;
  const examples = jsonSchema.examples || [];
  return [
    jsonSchemaToTsType(jsonSchema),
    {
      description: description,
      examples: examples,
      required: required.includes(name),
      default: required.includes(name) ? undefined : null,
    },
  ];
}
 
function jsonSchemaPropertiesToTSTypes(value: {
  type: string;
  description?: string;
  examples?: string[];
  items?: Record<string, unknown>;
}): z.ZodTypeAny {
  Iif (!value.type) {
    return z.object({});
  }
 
  let zodType;
  switch (value.type) {
    case "string":
      zodType = z
        .string()
        .describe(
          (value.description || "") +
            (value.examples ? `\nExamples: ${value.examples.join(", ")}` : "")
        );
      break;
    case "number":
      zodType = z
        .number()
        .describe(
          (value.description || "") +
            (value.examples ? `\nExamples: ${value.examples.join(", ")}` : "")
        );
      break;
    case "integer":
      zodType = z
        .number()
        .int()
        .describe(
          (value.description || "") +
            (value.examples ? `\nExamples: ${value.examples.join(", ")}` : "")
        );
      break;
    case "boolean":
      zodType = z
        .boolean()
        .describe(
          (value.description || "") +
            (value.examples ? `\nExamples: ${value.examples.join(", ")}` : "")
        );
      break;
    case "array":
      zodType = z
        .array(
          jsonSchemaPropertiesToTSTypes(
            value.items as {
              type: string;
              description?: string;
              examples?: string[];
              items?: Record<string, unknown>;
            }
          )
        )
        .describe(
          (value.description || "") +
            (value.examples ? `\nExamples: ${value.examples.join(", ")}` : "")
        );
      break;
    case "object":
      zodType = jsonSchemaToModel(value).describe(
        (value.description || "") +
          (value.examples ? `\nExamples: ${value.examples.join(", ")}` : "")
      );
      break;
    case "null":
      zodType = z.null().describe(value.description || "");
      break;
    default:
      throw new Error(`Unsupported JSON schema type: ${value.type}`);
  }
 
  return zodType;
}
 
export function jsonSchemaToModel(
  jsonSchema: Record<string, unknown>
): z.ZodObject<Record<string, z.ZodTypeAny>> {
  const properties = jsonSchema.properties as Record<string, unknown>;
  const requiredFields = (jsonSchema.required as string[]) || [];
  if (!properties) {
    return z.object({});
  }
 
  const zodSchema: Record<string, z.ZodTypeAny> = {};
  for (const [key, _] of Object.entries(properties)) {
    const value = _ as Record<string, unknown>;
    let zodType;
    Iif (value.anyOf) {
      const anyOfTypes = (value.anyOf as Record<string, unknown>[]).map(
        (schema) =>
          jsonSchemaPropertiesToTSTypes(
            schema as {
              type: string;
              description?: string;
              examples?: string[];
              items?: Record<string, unknown>;
            }
          )
      );
      zodType = z
        .union(anyOfTypes as [z.ZodTypeAny, z.ZodTypeAny, ...z.ZodTypeAny[]])
        .describe(
          ((value.description as string) || "") +
            (value.examples
              ? `\nExamples: ${(value.examples as string[]).join(", ")}`
              : "")
        );
    } else Iif (value.allOf) {
      const allOfTypes = (value.allOf as Record<string, unknown>[]).map(
        (schema) =>
          jsonSchemaPropertiesToTSTypes(
            schema as {
              type: string;
              description?: string;
              examples?: string[];
              items?: Record<string, unknown>;
            }
          )
      );
      zodType = z
        .intersection(
          allOfTypes[0],
          allOfTypes
            .slice(1)
            .reduce(
              (acc: z.ZodTypeAny, schema: z.ZodTypeAny) => acc.and(schema),
              allOfTypes[0]
            )
        )
        .describe(
          ((value.description as string) || "") +
            (value.examples
              ? `\nExamples: ${(value.examples as string[]).join(", ")}`
              : "")
        );
    } else {
      Iif (!value.type) {
        value.type = "string";
      }
      zodType = jsonSchemaPropertiesToTSTypes(
        value as {
          type: string;
          description?: string;
          examples?: string[];
          items?: Record<string, unknown>;
        }
      );
    }
 
    if (value.description) {
      zodType = zodType.describe(value.description as string);
    }
 
    if (requiredFields.includes(key)) {
      zodSchema[key] = zodType;
    } else {
      zodSchema[key] = zodType.optional();
    }
  }
 
  return z.object(zodSchema);
}
 
export const getEnvVariable = (
  name: string,
  defaultValue: string | undefined = undefined
): string | undefined => {
  try {
    return process.env[name] || defaultValue;
  } catch (_e) {
    return defaultValue;
  }
};
 
export const nodeExternalRequire = (name: string) => {
  try {
    if (typeof process !== "undefined") {
      // eslint-disable-next-line @typescript-eslint/no-require-imports
      return require(name);
    } else E{
      // eslint-disable-next-line @typescript-eslint/no-require-imports
      return require(`external:${name}`);
    }
  } catch (_err) {
    return null;
  }
};