@mirite/zod-to-mongoose 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,16 @@
1
+ import type { EnumLike } from 'zod';
1
2
  import * as Mongoose from 'mongoose';
2
3
  import { z } from 'zod';
3
4
  import type { ZodArray } from 'zod';
4
5
  import type { ZodBoolean } from 'zod';
5
6
  import type { ZodDate } from 'zod';
6
7
  import type { ZodDefault } from 'zod';
8
+ import type { ZodEnum } from 'zod';
9
+ import type { ZodNativeEnum } from 'zod';
10
+ import type { ZodNullable } from 'zod';
7
11
  import type { ZodNumber } from 'zod';
8
12
  import { ZodObject } from 'zod';
13
+ import type { ZodOptional } from 'zod';
9
14
  import { ZodRawShape } from 'zod';
10
15
  import type { ZodString } from 'zod';
11
16
  import type { ZodTypeAny } from 'zod';
@@ -34,6 +39,6 @@ export declare type FieldDefinition = {
34
39
 
35
40
  declare type SupportedPrimitive = ZodBoolean | ZodDate | ZodNumber | ZodString;
36
41
 
37
- export declare type SupportedType = SupportedPrimitive | ZodArray<ZodTypeAny> | ZodDefault<ZodTypeAny> | ZodObject<ZodRawShape> | ZodUnion<readonly [ZodTypeAny, ...ZodTypeAny[]]>;
42
+ export declare type SupportedType = SupportedPrimitive | ZodArray<ZodTypeAny> | ZodDefault<ZodTypeAny> | ZodEnum<[string, ...string[]]> | ZodNativeEnum<EnumLike> | ZodNullable<ZodTypeAny> | ZodObject<ZodRawShape> | ZodOptional<ZodTypeAny> | ZodUnion<readonly [ZodTypeAny, ...ZodTypeAny[]]>;
38
43
 
39
44
  export { }
@@ -1,11 +1,16 @@
1
+ import type { EnumLike } from 'zod';
1
2
  import * as Mongoose from 'mongoose';
2
3
  import { z } from 'zod';
3
4
  import type { ZodArray } from 'zod';
4
5
  import type { ZodBoolean } from 'zod';
5
6
  import type { ZodDate } from 'zod';
6
7
  import type { ZodDefault } from 'zod';
8
+ import type { ZodEnum } from 'zod';
9
+ import type { ZodNativeEnum } from 'zod';
10
+ import type { ZodNullable } from 'zod';
7
11
  import type { ZodNumber } from 'zod';
8
12
  import { ZodObject } from 'zod';
13
+ import type { ZodOptional } from 'zod';
9
14
  import { ZodRawShape } from 'zod';
10
15
  import type { ZodString } from 'zod';
11
16
  import type { ZodTypeAny } from 'zod';
@@ -34,6 +39,6 @@ export declare type FieldDefinition = {
34
39
 
35
40
  declare type SupportedPrimitive = ZodBoolean | ZodDate | ZodNumber | ZodString;
36
41
 
37
- export declare type SupportedType = SupportedPrimitive | ZodArray<ZodTypeAny> | ZodDefault<ZodTypeAny> | ZodObject<ZodRawShape> | ZodUnion<readonly [ZodTypeAny, ...ZodTypeAny[]]>;
42
+ export declare type SupportedType = SupportedPrimitive | ZodArray<ZodTypeAny> | ZodDefault<ZodTypeAny> | ZodEnum<[string, ...string[]]> | ZodNativeEnum<EnumLike> | ZodNullable<ZodTypeAny> | ZodObject<ZodRawShape> | ZodOptional<ZodTypeAny> | ZodUnion<readonly [ZodTypeAny, ...ZodTypeAny[]]>;
38
43
 
39
44
  export { }
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var h=Object.create;var p=Object.defineProperty;var S=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var g=Object.getPrototypeOf,Z=Object.prototype.hasOwnProperty;var b=(e,o)=>{for(var n in o)p(e,n,{get:o[n],enumerable:!0})},y=(e,o,n,t)=>{if(o&&typeof o=="object"||typeof o=="function")for(let a of T(o))!Z.call(e,a)&&a!==n&&p(e,a,{get:()=>o[a],enumerable:!(t=S(o,a))||t.enumerable});return e};var M=(e,o,n)=>(n=e!=null?h(g(e)):{},y(o||!e||!e.__esModule?p(n,"default",{value:e,enumerable:!0}):n,e)),w=e=>y(p({},"__esModule",{value:!0}),e);var j={};b(j,{createSchema:()=>l});module.exports=w(j);var m=M(require("mongoose"),1),r=require("zod");function l(e,o,n){let t={};for(let d in e.shape){let i=e.shape[d];t[d]=s(d,i)}let a=new m.Schema(t);return!n||!o?a:{model:n.model(o,a),schema:a}}function s(e,o){let n=k(o),t;switch(n.definition._def.typeName){case r.ZodFirstPartyTypeKind.ZodArray:{let d=n.definition._def.type;if(u(d)){let i=d.shape,f={};for(let c in i)f[c]=s(c,i[c]);t=[f]}else t=[s(e,d)];break}case r.ZodFirstPartyTypeKind.ZodBoolean:t=Boolean;break;case r.ZodFirstPartyTypeKind.ZodDate:t=Date;break;case r.ZodFirstPartyTypeKind.ZodNumber:t=Number;break;case r.ZodFirstPartyTypeKind.ZodObject:break;case r.ZodFirstPartyTypeKind.ZodString:t=String;break;case r.ZodFirstPartyTypeKind.ZodUnion:t={};break;default:throw new TypeError(`Unsupported type: ${e}`)}if(u(n.definition)&&(t=l(n.definition)),t===void 0)throw new TypeError(`Could not determine Mongoose type for Zod type: ${e}`);return n.defaultValue?{default:n.defaultValue,type:t}:t}function u(e){return e._def.typeName===r.ZodFirstPartyTypeKind.ZodObject}function k(e){let o=e,n=!1,t;for(;"innerType"in o._def;)"defaultValue"in o._def&&(t=o._def.defaultValue()),o=o._def.innerType;return{defaultValue:t,definition:o,optional:n}}0&&(module.exports={createSchema});
1
+ "use strict";var T=Object.create;var p=Object.defineProperty;var h=Object.getOwnPropertyDescriptor;var S=Object.getOwnPropertyNames;var g=Object.getPrototypeOf,b=Object.prototype.hasOwnProperty;var k=(e,n)=>{for(var t in n)p(e,t,{get:n[t],enumerable:!0})},y=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let a of S(n))!b.call(e,a)&&a!==t&&p(e,a,{get:()=>n[a],enumerable:!(o=h(n,a))||o.enumerable});return e};var w=(e,n,t)=>(t=e!=null?T(g(e)):{},y(n||!e||!e.__esModule?p(t,"default",{value:e,enumerable:!0}):t,e)),M=e=>y(p({},"__esModule",{value:!0}),e);var E={};k(E,{createSchema:()=>Z});module.exports=M(E);var s=w(require("mongoose"),1),i=require("zod");function Z(e,n,t){let o={};for(let r in e.shape){let d=e.shape[r];o[r]=f(r,d)}let a=new s.Schema(o);return!t||!n?a:{model:t.model(n,a),schema:a}}function f(e,n){let t=D(n),o;switch(t.definition._def.typeName){case i.ZodFirstPartyTypeKind.ZodArray:{let d=t.definition._def.type;if(m(d)){let c=d.shape,l={};for(let u in c)l[u]=f(u,c[u]);o=[l]}else o=[f(e,d)];break}case i.ZodFirstPartyTypeKind.ZodBoolean:o=Boolean;break;case i.ZodFirstPartyTypeKind.ZodDate:o=Date;break;case i.ZodFirstPartyTypeKind.ZodDefault:break;case i.ZodFirstPartyTypeKind.ZodEnum:{o={enum:t.definition.options,type:String};break}case i.ZodFirstPartyTypeKind.ZodNativeEnum:{let r=t.definition;o={enum:j(r.enum),type:String};break}case i.ZodFirstPartyTypeKind.ZodNumber:o=Number;break;case i.ZodFirstPartyTypeKind.ZodObject:break;case i.ZodFirstPartyTypeKind.ZodString:o=String;break;case i.ZodFirstPartyTypeKind.ZodUnion:o=s.SchemaTypes.Mixed;break;default:throw new TypeError(`Unsupported type: ${e}`)}if(m(t.definition)&&(o=Z(t.definition)),o===void 0)throw new TypeError(`Could not determine Mongoose type for Zod type: ${e}`);let a=t.defaultValue!==void 0;return t.nullable&&!a?{default:null,type:o}:a?{default:t.defaultValue,type:o}:o}function m(e){return e._def.typeName===i.ZodFirstPartyTypeKind.ZodObject}function O(e){return e._def.typeName===i.ZodFirstPartyTypeKind.ZodDefault}function z(e){return e._def.typeName===i.ZodFirstPartyTypeKind.ZodNullable}function N(e){return e._def.typeName===i.ZodFirstPartyTypeKind.ZodOptional}function j(e){let n=Object.keys(e).filter(o=>typeof e[o]=="number"||typeof e[o]=="string"),t={};for(let o of n)t[o]=e[o];return Object.values(t).filter(o=>typeof o=="string"||typeof o=="number")}function D(e){let n=e,t=!1,o=!1,a;for(;"innerType"in n._def;)z(n)&&(t=!0),N(n)&&(o=!0),O(n)&&(a=n._def.defaultValue()),n=n._def.innerType;return{defaultValue:a,definition:n,nullable:t,optional:o}}0&&(module.exports={createSchema});
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { SchemaDefinition } from \"mongoose\";\nimport * as Mongoose from \"mongoose\";\nimport { ZodFirstPartyTypeKind, type z, type ZodArray, type ZodObject, type ZodRawShape } from \"zod\";\n\nimport type { SupportedType } from \"./types\";\n\n/**\n * Represents a valid type for a Mongoose schema field definition. This is a recursive type that handles all possible\n * valid structures for a schema property, including nested objects and arrays.\n *\n * @internal\n */\ntype MongooseSchemaType =\n\t| Mongoose.Schema\n\t| MongooseSchemaType[]\n\t| typeof Boolean\n\t| typeof Date\n\t| typeof Number\n\t// This covers both a schema definition for a sub-document and the empty\n\t// object `{}` used for Mixed types.\n\t| typeof String\n\t// This covers an array of sub-documents or an array of primitives.\n\t// Mongoose expects an array with a single element defining the type.\n\t| { [key: string]: MongooseSchemaType }\n\t// This covers the object format for specifying a default value.\n\t| {\n\t\t\tdefault?: unknown;\n\t\t\ttype: MongooseSchemaType;\n\t };\nexport function createSchema<T extends ZodRawShape>(\n\tzodObject: ZodObject<T>,\n\tmodelName: string,\n\tconnection: Mongoose.Connection,\n): { model: Mongoose.Model<z.infer<typeof zodObject>>; schema: Mongoose.Schema };\nexport function createSchema<T extends ZodRawShape>(zodObject: ZodObject<T>): Mongoose.Schema;\n/**\n * Create a Mongoose schema from a Zod shape\n *\n * @template T The Zod schema shape.\n * @param zodObject The Zod shape to create the schema from\n * @param modelName The unique name to assign to the model\n * @param connection The Mongoose connection to create the model from\n * @returns The Mongoose schema\n */\nexport function createSchema<T extends ZodRawShape>(\n\tzodObject: ZodObject<T>,\n\tmodelName?: string,\n\tconnection?: Mongoose.Connection,\n): Mongoose.Schema | { model: Mongoose.Model<z.infer<typeof zodObject>>; schema: Mongoose.Schema } {\n\tconst convertedShape: Partial<SchemaDefinition> = {};\n\tfor (const key in zodObject.shape) {\n\t\tconst zodField = zodObject.shape[key];\n\t\tconvertedShape[key] = convertField(key, zodField);\n\t}\n\tconst schema = new Mongoose.Schema(convertedShape);\n\tif (!connection || !modelName) return schema;\n\treturn { model: connection.model<z.infer<typeof zodObject>>(modelName, schema), schema };\n}\n\n/**\n * Convert a Zod field to a Mongoose type\n *\n * @template T The Zod schema shape.\n * @param type The key of the field\n * @param zodField The Zod field to convert\n * @returns The Mongoose type\n * @throws TypeError If the type is not supported.\n */\nfunction convertField<T extends ZodRawShape>(type: string, zodField: T[Extract<keyof T, string>]): MongooseSchemaType {\n\tconst unwrappedData = unwrapType(zodField);\n\tlet coreType: MongooseSchemaType | undefined;\n\tswitch (unwrappedData.definition._def.typeName) {\n\t\tcase ZodFirstPartyTypeKind.ZodArray: {\n\t\t\tconst arrayType = unwrappedData.definition as ZodArray<SupportedType>;\n\t\t\tconst elementType = arrayType._def.type;\n\t\t\tif (isZodObject(elementType)) {\n\t\t\t\tconst shape = elementType.shape;\n\t\t\t\tconst convertedShape: { [key: string]: MongooseSchemaType } = {};\n\t\t\t\tfor (const key in shape) {\n\t\t\t\t\tconvertedShape[key] = convertField(key, shape[key]);\n\t\t\t\t}\n\t\t\t\tcoreType = [convertedShape];\n\t\t\t} else {\n\t\t\t\tcoreType = [convertField(type, elementType)];\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase ZodFirstPartyTypeKind.ZodBoolean:\n\t\t\tcoreType = Boolean;\n\t\t\tbreak;\n\t\tcase ZodFirstPartyTypeKind.ZodDate:\n\t\t\tcoreType = Date;\n\t\t\tbreak;\n\t\tcase ZodFirstPartyTypeKind.ZodNumber:\n\t\t\tcoreType = Number;\n\t\t\tbreak;\n\t\tcase ZodFirstPartyTypeKind.ZodObject:\n\t\t\tbreak;\n\t\tcase ZodFirstPartyTypeKind.ZodString:\n\t\t\tcoreType = String;\n\t\t\tbreak;\n\t\tcase ZodFirstPartyTypeKind.ZodUnion:\n\t\t\tcoreType = {};\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new TypeError(`Unsupported type: ${type}`);\n\t}\n\tif (isZodObject(unwrappedData.definition)) {\n\t\tcoreType = createSchema(unwrappedData.definition);\n\t}\n\tif (coreType === undefined) {\n\t\tthrow new TypeError(`Could not determine Mongoose type for Zod type: ${type}`);\n\t}\n\tif (!unwrappedData.defaultValue) {\n\t\treturn coreType;\n\t}\n\treturn {\n\t\tdefault: unwrappedData.defaultValue,\n\t\ttype: coreType,\n\t};\n}\n\n/**\n * Check if a Zod definition is an object\n *\n * @param definition The Zod definition to check\n * @returns Whether the definition is an object\n */\nfunction isZodObject(definition: SupportedType): definition is ZodObject<ZodRawShape> {\n\treturn definition._def.typeName === ZodFirstPartyTypeKind.ZodObject;\n}\n\n/**\n * Takes a complex type and returns the inner type definition along with the default if present.\n *\n * @param data The type data to unwrap.\n * @returns The inner type data along with the default if present.\n */\nfunction unwrapType(data: SupportedType): { defaultValue?: unknown; definition: SupportedType; optional: boolean } {\n\tlet definition = data;\n\tconst optional = false;\n\tlet defaultValue = undefined;\n\twhile (\"innerType\" in definition._def) {\n\t\tif (\"defaultValue\" in definition._def) {\n\t\t\tdefaultValue = definition._def.defaultValue();\n\t\t}\n\t\tdefinition = definition._def.innerType;\n\t}\n\treturn { defaultValue, definition, optional };\n}\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,IAAA,eAAAC,EAAAH,GACA,IAAAI,EAA0B,yBAC1BC,EAA+F,eA0CxF,SAASH,EACfI,EACAC,EACAC,EACkG,CAClG,IAAMC,EAA4C,CAAC,EACnD,QAAWC,KAAOJ,EAAU,MAAO,CAClC,IAAMK,EAAWL,EAAU,MAAMI,CAAG,EACpCD,EAAeC,CAAG,EAAIE,EAAaF,EAAKC,CAAQ,CACjD,CACA,IAAME,EAAS,IAAa,SAAOJ,CAAc,EACjD,MAAI,CAACD,GAAc,CAACD,EAAkBM,EAC/B,CAAE,MAAOL,EAAW,MAAiCD,EAAWM,CAAM,EAAG,OAAAA,CAAO,CACxF,CAWA,SAASD,EAAoCE,EAAcH,EAA2D,CAC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zodObject","modelName","connection","convertedShape","key","zodField","convertField","schema","type","unwrappedData","unwrapType","coreType","elementType","isZodObject","shape","definition","data","optional","defaultValue"]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { SchemaDefinition } from \"mongoose\";\nimport * as Mongoose from \"mongoose\";\nimport {\n\tEnumLike,\n\tZodFirstPartyTypeKind,\n\ttype z,\n\ttype ZodArray,\n\ttype ZodNativeEnum,\n\ttype ZodObject,\n\ttype ZodRawShape,\n} from \"zod\";\n\nimport type { SupportedType } from \"./types\";\n\n/**\n * Represents a valid type for a Mongoose schema field definition. This is a recursive type that handles all possible\n * valid structures for a schema property, including nested objects and arrays.\n *\n * @internal\n */\ntype MongooseSchemaType = Mongoose.SchemaDefinitionProperty;\nexport function createSchema<T extends ZodRawShape>(\n\tzodObject: ZodObject<T>,\n\tmodelName: string,\n\tconnection: Mongoose.Connection,\n): { model: Mongoose.Model<z.infer<typeof zodObject>>; schema: Mongoose.Schema };\nexport function createSchema<T extends ZodRawShape>(zodObject: ZodObject<T>): Mongoose.Schema;\n/**\n * Create a Mongoose schema from a Zod shape\n *\n * @template T The Zod schema shape.\n * @param zodObject The Zod shape to create the schema from\n * @param modelName The unique name to assign to the model\n * @param connection The Mongoose connection to create the model from\n * @returns The Mongoose schema\n */\nexport function createSchema<T extends ZodRawShape>(\n\tzodObject: ZodObject<T>,\n\tmodelName?: string,\n\tconnection?: Mongoose.Connection,\n): Mongoose.Schema | { model: Mongoose.Model<z.infer<typeof zodObject>>; schema: Mongoose.Schema } {\n\tconst convertedShape: Partial<SchemaDefinition> = {};\n\tfor (const key in zodObject.shape) {\n\t\tconst zodField = zodObject.shape[key];\n\t\tconvertedShape[key] = convertField(key, zodField);\n\t}\n\tconst schema = new Mongoose.Schema(convertedShape);\n\tif (!connection || !modelName) return schema;\n\treturn { model: connection.model<z.infer<typeof zodObject>>(modelName, schema), schema };\n}\n\n/**\n * Convert a Zod field to a Mongoose type\n *\n * @template T The Zod schema shape.\n * @param type The key of the field\n * @param zodField The Zod field to convert\n * @returns The Mongoose type\n * @throws TypeError If the type is not supported.\n */\nfunction convertField<T extends ZodRawShape>(type: string, zodField: T[Extract<keyof T, string>]): MongooseSchemaType {\n\tconst unwrappedData = unwrapType(zodField);\n\tlet coreType: MongooseSchemaType | undefined;\n\tswitch (unwrappedData.definition._def.typeName) {\n\t\tcase ZodFirstPartyTypeKind.ZodArray: {\n\t\t\tconst arrayType = unwrappedData.definition as ZodArray<SupportedType>;\n\t\t\tconst elementType = arrayType._def.type;\n\t\t\tif (isZodObject(elementType)) {\n\t\t\t\tconst shape = elementType.shape;\n\t\t\t\tconst convertedShape: { [key: string]: MongooseSchemaType } = {};\n\t\t\t\tfor (const key in shape) {\n\t\t\t\t\tconvertedShape[key] = convertField(key, shape[key]);\n\t\t\t\t}\n\t\t\t\tcoreType = [convertedShape];\n\t\t\t} else {\n\t\t\t\tcoreType = [convertField(type, elementType)];\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase ZodFirstPartyTypeKind.ZodBoolean:\n\t\t\tcoreType = Boolean;\n\t\t\tbreak;\n\t\tcase ZodFirstPartyTypeKind.ZodDate:\n\t\t\tcoreType = Date;\n\t\t\tbreak;\n\t\tcase ZodFirstPartyTypeKind.ZodDefault:\n\t\t\tbreak;\n\t\tcase ZodFirstPartyTypeKind.ZodEnum: {\n\t\t\tconst enumType = unwrappedData.definition as unknown as z.ZodEnum<[string, ...string[]]>;\n\t\t\tcoreType = {\n\t\t\t\tenum: enumType.options,\n\t\t\t\ttype: String,\n\t\t\t};\n\t\t\tbreak;\n\t\t}\n\t\tcase ZodFirstPartyTypeKind.ZodNativeEnum: {\n\t\t\tconst enumType = unwrappedData.definition as unknown as ZodNativeEnum<EnumLike>;\n\t\t\tcoreType = {\n\t\t\t\tenum: getValidEnumValues(enumType.enum),\n\t\t\t\ttype: String,\n\t\t\t};\n\t\t\tbreak;\n\t\t}\n\t\tcase ZodFirstPartyTypeKind.ZodNumber:\n\t\t\tcoreType = Number;\n\t\t\tbreak;\n\t\tcase ZodFirstPartyTypeKind.ZodObject:\n\t\t\tbreak;\n\t\tcase ZodFirstPartyTypeKind.ZodString:\n\t\t\tcoreType = String;\n\t\t\tbreak;\n\t\tcase ZodFirstPartyTypeKind.ZodUnion:\n\t\t\tcoreType = Mongoose.SchemaTypes.Mixed;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new TypeError(`Unsupported type: ${type}`);\n\t}\n\tif (isZodObject(unwrappedData.definition)) {\n\t\tcoreType = createSchema(unwrappedData.definition);\n\t}\n\tif (coreType === undefined) {\n\t\tthrow new TypeError(`Could not determine Mongoose type for Zod type: ${type}`);\n\t}\n\n\tconst hasDefaultValue = unwrappedData.defaultValue !== undefined;\n\n\tif (unwrappedData.nullable && !hasDefaultValue) {\n\t\treturn {\n\t\t\tdefault: null,\n\t\t\ttype: coreType,\n\t\t};\n\t}\n\n\tif (hasDefaultValue) {\n\t\treturn {\n\t\t\tdefault: unwrappedData.defaultValue,\n\t\t\ttype: coreType,\n\t\t};\n\t}\n\treturn coreType;\n}\n\n/**\n * Check if a Zod definition is an object\n *\n * @param definition The Zod definition to check\n * @returns Whether the definition is an object\n */\nfunction isZodObject(definition: SupportedType): definition is ZodObject<ZodRawShape> {\n\treturn definition._def.typeName === ZodFirstPartyTypeKind.ZodObject;\n}\nfunction isZodDefault(definition: z.ZodTypeAny): definition is z.ZodDefault<SupportedType> {\n\treturn definition._def.typeName === ZodFirstPartyTypeKind.ZodDefault;\n}\n\nfunction isZodNullable(definition: z.ZodTypeAny): definition is z.ZodNullable<SupportedType> {\n\treturn definition._def.typeName === ZodFirstPartyTypeKind.ZodNullable;\n}\n\nfunction isZodOptional(definition: z.ZodTypeAny): definition is z.ZodOptional<SupportedType> {\n\treturn definition._def.typeName === ZodFirstPartyTypeKind.ZodOptional;\n}\n\nfunction getValidEnumValues(obj: { [s: string]: unknown }): (string | number)[] {\n\tconst validKeys = Object.keys(obj).filter((k) => typeof obj[k] === \"number\" || typeof obj[k] === \"string\");\n\tconst filtered: { [s: string]: unknown } = {};\n\tfor (const k of validKeys) {\n\t\tfiltered[k] = obj[k];\n\t}\n\n\treturn Object.values(filtered).filter((v) => typeof v === \"string\" || typeof v === \"number\");\n}\n\n/**\n * Takes a complex type and returns the inner type definition along with the default if present.\n *\n * @param data The type data to unwrap.\n * @returns The inner type data along with the default if present.\n */\nfunction unwrapType(data: SupportedType): {\n\tdefaultValue?: unknown;\n\tdefinition: SupportedType;\n\tnullable: boolean;\n\toptional: boolean;\n} {\n\tlet definition = data;\n\tlet nullable = false;\n\tlet optional = false;\n\tlet defaultValue: unknown | undefined;\n\twhile (\"innerType\" in definition._def) {\n\t\tif (isZodNullable(definition)) {\n\t\t\tnullable = true;\n\t\t}\n\t\tif (isZodOptional(definition)) {\n\t\t\toptional = true;\n\t\t}\n\t\tif (isZodDefault(definition)) {\n\t\t\tdefaultValue = definition._def.defaultValue();\n\t\t}\n\t\tdefinition = definition._def.innerType;\n\t}\n\treturn { defaultValue, definition, nullable, optional };\n}\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,IAAA,eAAAC,EAAAH,GACA,IAAAI,EAA0B,yBAC1BC,EAQO,eA0BA,SAASH,EACfI,EACAC,EACAC,EACkG,CAClG,IAAMC,EAA4C,CAAC,EACnD,QAAWC,KAAOJ,EAAU,MAAO,CAClC,IAAMK,EAAWL,EAAU,MAAMI,CAAG,EACpCD,EAAeC,CAAG,EAAIE,EAAaF,EAAKC,CAAQ,CACjD,CACA,IAAME,EAAS,IAAa,SAAOJ,CAAc,EACjD,MAAI,CAACD,GAAc,CAACD,EAAkBM,EAC/B,CAAE,MAAOL,EAAW,MAAiCD,EAAWM,CAAM,EAAG,OAAAA,CAAO,CACxF,CAWA,SAASD,EAAoCE,EAAcH,EAA2D,CACrH,IAAMI,EAAgBC,EAAWL,CAAQ,EACrCM,EACJ,OAAQF,EAAc,WAAW,KAAK,SAAU,CA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1F,OAAOA,EAAW,KAAK,WAAa,wBAAsB,UAC3D,CAEA,SAASE,EAAcF,EAAsE,CAC5F,OAAOA,EAAW,KAAK,WAAa,wBAAsB,WAC3D,CAEA,SAASG,EAAcH,EAAsE,CAC5F,OAAOA,EAAW,KAAK,WAAa,wBAAsB,WAC3D,CAEA,SAASF,EAAmBM,EAAoD,CAC/E,IAAMC,EAAY,OAAO,KAAKD,CAAG,EAAE,OAAQE,GAAM,OAAOF,EAAIE,CAAC,GAAM,UAAY,OAAOF,EAAIE,CAAC,GAAM,QAAQ,EACnGC,EAAqC,CAAC,EAC5C,QAAWD,KAAKD,EACfE,EAASD,CAAC,EAAIF,EAAIE,CAAC,EAGpB,OAAO,OAAO,OAAOC,CAAQ,EAAE,OAAQC,GAAM,OAAOA,GAAM,UAAY,OAAOA,GAAM,QAAQ,CAC5F,CAQA,SAAShB,EAAWiB,EAKlB,CACD,IAAIT,EAAaS,EACbC,EAAW,GACXC,EAAW,GACXC,EACJ,KAAO,cAAeZ,EAAW,MAC5BE,EAAcF,CAAU,IAC3BU,EAAW,IAERP,EAAcH,CAAU,IAC3BW,EAAW,IAERV,EAAaD,CAAU,IAC1BY,EAAeZ,EAAW,KAAK,aAAa,GAE7CA,EAAaA,EAAW,KAAK,UAE9B,MAAO,CAAE,aAAAY,EAAc,WAAAZ,EAAY,SAAAU,EAAU,SAAAC,CAAS,CACvD","names":["index_exports","__export","createSchema","__toCommonJS","Mongoose","import_zod","zodObject","modelName","connection","convertedShape","key","zodField","convertField","schema","type","unwrappedData","unwrapType","coreType","elementType","isZodObject","shape","enumType","getValidEnumValues","hasDefaultValue","definition","isZodDefault","isZodNullable","isZodOptional","obj","validKeys","k","filtered","v","data","nullable","optional","defaultValue"]}
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import*as y from"mongoose";import{ZodFirstPartyTypeKind as a}from"zod";function u(t,o,n){let e={};for(let r in t.shape){let i=t.shape[r];e[r]=c(r,i)}let d=new y.Schema(e);return!n||!o?d:{model:n.model(o,d),schema:d}}function c(t,o){let n=m(o),e;switch(n.definition._def.typeName){case a.ZodArray:{let r=n.definition._def.type;if(f(r)){let i=r.shape,s={};for(let p in i)s[p]=c(p,i[p]);e=[s]}else e=[c(t,r)];break}case a.ZodBoolean:e=Boolean;break;case a.ZodDate:e=Date;break;case a.ZodNumber:e=Number;break;case a.ZodObject:break;case a.ZodString:e=String;break;case a.ZodUnion:e={};break;default:throw new TypeError(`Unsupported type: ${t}`)}if(f(n.definition)&&(e=u(n.definition)),e===void 0)throw new TypeError(`Could not determine Mongoose type for Zod type: ${t}`);return n.defaultValue?{default:n.defaultValue,type:e}:e}function f(t){return t._def.typeName===a.ZodObject}function m(t){let o=t,n=!1,e;for(;"innerType"in o._def;)"defaultValue"in o._def&&(e=o._def.defaultValue()),o=o._def.innerType;return{defaultValue:e,definition:o,optional:n}}export{u as createSchema};
1
+ import*as p from"mongoose";import{ZodFirstPartyTypeKind as a}from"zod";function y(o,t,n){let e={};for(let r in o.shape){let d=o.shape[r];e[r]=u(r,d)}let i=new p.Schema(e);return!n||!t?i:{model:n.model(t,i),schema:i}}function u(o,t){let n=S(t),e;switch(n.definition._def.typeName){case a.ZodArray:{let d=n.definition._def.type;if(l(d)){let f=d.shape,c={};for(let s in f)c[s]=u(s,f[s]);e=[c]}else e=[u(o,d)];break}case a.ZodBoolean:e=Boolean;break;case a.ZodDate:e=Date;break;case a.ZodDefault:break;case a.ZodEnum:{e={enum:n.definition.options,type:String};break}case a.ZodNativeEnum:{let r=n.definition;e={enum:h(r.enum),type:String};break}case a.ZodNumber:e=Number;break;case a.ZodObject:break;case a.ZodString:e=String;break;case a.ZodUnion:e=p.SchemaTypes.Mixed;break;default:throw new TypeError(`Unsupported type: ${o}`)}if(l(n.definition)&&(e=y(n.definition)),e===void 0)throw new TypeError(`Could not determine Mongoose type for Zod type: ${o}`);let i=n.defaultValue!==void 0;return n.nullable&&!i?{default:null,type:e}:i?{default:n.defaultValue,type:e}:e}function l(o){return o._def.typeName===a.ZodObject}function m(o){return o._def.typeName===a.ZodDefault}function Z(o){return o._def.typeName===a.ZodNullable}function T(o){return o._def.typeName===a.ZodOptional}function h(o){let t=Object.keys(o).filter(e=>typeof o[e]=="number"||typeof o[e]=="string"),n={};for(let e of t)n[e]=o[e];return Object.values(n).filter(e=>typeof e=="string"||typeof e=="number")}function S(o){let t=o,n=!1,e=!1,i;for(;"innerType"in t._def;)Z(t)&&(n=!0),T(t)&&(e=!0),m(t)&&(i=t._def.defaultValue()),t=t._def.innerType;return{defaultValue:i,definition:t,nullable:n,optional:e}}export{y as createSchema};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { SchemaDefinition } from \"mongoose\";\nimport * as Mongoose from \"mongoose\";\nimport { ZodFirstPartyTypeKind, type z, type ZodArray, type ZodObject, type ZodRawShape } from \"zod\";\n\nimport type { SupportedType } from \"./types\";\n\n/**\n * Represents a valid type for a Mongoose schema field definition. This is a recursive type that handles all possible\n * valid structures for a schema property, including nested objects and arrays.\n *\n * @internal\n */\ntype MongooseSchemaType =\n\t| Mongoose.Schema\n\t| MongooseSchemaType[]\n\t| typeof Boolean\n\t| typeof Date\n\t| typeof Number\n\t// This covers both a schema definition for a sub-document and the empty\n\t// object `{}` used for Mixed types.\n\t| typeof String\n\t// This covers an array of sub-documents or an array of primitives.\n\t// Mongoose expects an array with a single element defining the type.\n\t| { [key: string]: MongooseSchemaType }\n\t// This covers the object format for specifying a default value.\n\t| {\n\t\t\tdefault?: unknown;\n\t\t\ttype: MongooseSchemaType;\n\t };\nexport function createSchema<T extends ZodRawShape>(\n\tzodObject: ZodObject<T>,\n\tmodelName: string,\n\tconnection: Mongoose.Connection,\n): { model: Mongoose.Model<z.infer<typeof zodObject>>; schema: Mongoose.Schema };\nexport function createSchema<T extends ZodRawShape>(zodObject: ZodObject<T>): Mongoose.Schema;\n/**\n * Create a Mongoose schema from a Zod shape\n *\n * @template T The Zod schema shape.\n * @param zodObject The Zod shape to create the schema from\n * @param modelName The unique name to assign to the model\n * @param connection The Mongoose connection to create the model from\n * @returns The Mongoose schema\n */\nexport function createSchema<T extends ZodRawShape>(\n\tzodObject: ZodObject<T>,\n\tmodelName?: string,\n\tconnection?: Mongoose.Connection,\n): Mongoose.Schema | { model: Mongoose.Model<z.infer<typeof zodObject>>; schema: Mongoose.Schema } {\n\tconst convertedShape: Partial<SchemaDefinition> = {};\n\tfor (const key in zodObject.shape) {\n\t\tconst zodField = zodObject.shape[key];\n\t\tconvertedShape[key] = convertField(key, zodField);\n\t}\n\tconst schema = new Mongoose.Schema(convertedShape);\n\tif (!connection || !modelName) return schema;\n\treturn { model: connection.model<z.infer<typeof zodObject>>(modelName, schema), schema };\n}\n\n/**\n * Convert a Zod field to a Mongoose type\n *\n * @template T The Zod schema shape.\n * @param type The key of the field\n * @param zodField The Zod field to convert\n * @returns The Mongoose type\n * @throws TypeError If the type is not supported.\n */\nfunction convertField<T extends ZodRawShape>(type: string, zodField: T[Extract<keyof T, string>]): MongooseSchemaType {\n\tconst unwrappedData = unwrapType(zodField);\n\tlet coreType: MongooseSchemaType | undefined;\n\tswitch (unwrappedData.definition._def.typeName) {\n\t\tcase ZodFirstPartyTypeKind.ZodArray: {\n\t\t\tconst arrayType = unwrappedData.definition as ZodArray<SupportedType>;\n\t\t\tconst elementType = arrayType._def.type;\n\t\t\tif (isZodObject(elementType)) {\n\t\t\t\tconst shape = elementType.shape;\n\t\t\t\tconst convertedShape: { [key: string]: MongooseSchemaType } = {};\n\t\t\t\tfor (const key in shape) {\n\t\t\t\t\tconvertedShape[key] = convertField(key, shape[key]);\n\t\t\t\t}\n\t\t\t\tcoreType = [convertedShape];\n\t\t\t} else {\n\t\t\t\tcoreType = [convertField(type, elementType)];\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase ZodFirstPartyTypeKind.ZodBoolean:\n\t\t\tcoreType = Boolean;\n\t\t\tbreak;\n\t\tcase ZodFirstPartyTypeKind.ZodDate:\n\t\t\tcoreType = Date;\n\t\t\tbreak;\n\t\tcase ZodFirstPartyTypeKind.ZodNumber:\n\t\t\tcoreType = Number;\n\t\t\tbreak;\n\t\tcase ZodFirstPartyTypeKind.ZodObject:\n\t\t\tbreak;\n\t\tcase ZodFirstPartyTypeKind.ZodString:\n\t\t\tcoreType = String;\n\t\t\tbreak;\n\t\tcase ZodFirstPartyTypeKind.ZodUnion:\n\t\t\tcoreType = {};\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new TypeError(`Unsupported type: ${type}`);\n\t}\n\tif (isZodObject(unwrappedData.definition)) {\n\t\tcoreType = createSchema(unwrappedData.definition);\n\t}\n\tif (coreType === undefined) {\n\t\tthrow new TypeError(`Could not determine Mongoose type for Zod type: ${type}`);\n\t}\n\tif (!unwrappedData.defaultValue) {\n\t\treturn coreType;\n\t}\n\treturn {\n\t\tdefault: unwrappedData.defaultValue,\n\t\ttype: coreType,\n\t};\n}\n\n/**\n * Check if a Zod definition is an object\n *\n * @param definition The Zod definition to check\n * @returns Whether the definition is an object\n */\nfunction isZodObject(definition: SupportedType): definition is ZodObject<ZodRawShape> {\n\treturn definition._def.typeName === ZodFirstPartyTypeKind.ZodObject;\n}\n\n/**\n * Takes a complex type and returns the inner type definition along with the default if present.\n *\n * @param data The type data to unwrap.\n * @returns The inner type data along with the default if present.\n */\nfunction unwrapType(data: SupportedType): { defaultValue?: unknown; definition: SupportedType; optional: boolean } {\n\tlet definition = data;\n\tconst optional = false;\n\tlet defaultValue = undefined;\n\twhile (\"innerType\" in definition._def) {\n\t\tif (\"defaultValue\" in definition._def) {\n\t\t\tdefaultValue = definition._def.defaultValue();\n\t\t}\n\t\tdefinition = definition._def.innerType;\n\t}\n\treturn { defaultValue, definition, optional };\n}\n"],"mappings":"AACA,UAAYA,MAAc,WAC1B,OAAS,yBAAAC,MAAsF,MA0CxF,SAASC,EACfC,EACAC,EACAC,EACkG,CA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AASE,EAAYE,EAAiE,CACrF,OAAOA,EAAW,KAAK,WAAajB,EAAsB,SAC3D,CAQA,SAASY,EAAWM,EAA+F,CAClH,IAAID,EAAaC,EACXC,EAAW,GACbC,EACJ,KAAO,cAAeH,EAAW,MAC5B,iBAAkBA,EAAW,OAChCG,EAAeH,EAAW,KAAK,aAAa,GAE7CA,EAAaA,EAAW,KAAK,UAE9B,MAAO,CAAE,aAAAG,EAAc,WAAAH,EAAY,SAAAE,CAAS,CAC7C","names":["Mongoose","ZodFirstPartyTypeKind","createSchema","zodObject","modelName","connection","convertedShape","key","zodField","convertField","schema","type","unwrappedData","unwrapType","coreType","elementType","isZodObject","shape","definition","data","optional","defaultValue"]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { SchemaDefinition } from \"mongoose\";\nimport * as Mongoose from \"mongoose\";\nimport {\n\tEnumLike,\n\tZodFirstPartyTypeKind,\n\ttype z,\n\ttype ZodArray,\n\ttype ZodNativeEnum,\n\ttype ZodObject,\n\ttype ZodRawShape,\n} from \"zod\";\n\nimport type { SupportedType } from \"./types\";\n\n/**\n * Represents a valid type for a Mongoose schema field definition. This is a recursive type that handles all possible\n * valid structures for a schema property, including nested objects and arrays.\n *\n * @internal\n */\ntype MongooseSchemaType = Mongoose.SchemaDefinitionProperty;\nexport function createSchema<T extends ZodRawShape>(\n\tzodObject: ZodObject<T>,\n\tmodelName: string,\n\tconnection: Mongoose.Connection,\n): { model: Mongoose.Model<z.infer<typeof zodObject>>; schema: Mongoose.Schema };\nexport function createSchema<T extends ZodRawShape>(zodObject: ZodObject<T>): Mongoose.Schema;\n/**\n * Create a Mongoose schema from a Zod shape\n *\n * @template T The Zod schema shape.\n * @param zodObject The Zod shape to create the schema from\n * @param modelName The unique name to assign to the model\n * @param connection The Mongoose connection to create the model from\n * @returns The Mongoose schema\n */\nexport function createSchema<T extends ZodRawShape>(\n\tzodObject: ZodObject<T>,\n\tmodelName?: string,\n\tconnection?: Mongoose.Connection,\n): Mongoose.Schema | { model: Mongoose.Model<z.infer<typeof zodObject>>; schema: Mongoose.Schema } {\n\tconst convertedShape: Partial<SchemaDefinition> = {};\n\tfor (const key in zodObject.shape) {\n\t\tconst zodField = zodObject.shape[key];\n\t\tconvertedShape[key] = convertField(key, zodField);\n\t}\n\tconst schema = new Mongoose.Schema(convertedShape);\n\tif (!connection || !modelName) return schema;\n\treturn { model: connection.model<z.infer<typeof zodObject>>(modelName, schema), schema };\n}\n\n/**\n * Convert a Zod field to a Mongoose type\n *\n * @template T The Zod schema shape.\n * @param type The key of the field\n * @param zodField The Zod field to convert\n * @returns The Mongoose type\n * @throws TypeError If the type is not supported.\n */\nfunction convertField<T extends ZodRawShape>(type: string, zodField: T[Extract<keyof T, string>]): MongooseSchemaType {\n\tconst unwrappedData = unwrapType(zodField);\n\tlet coreType: MongooseSchemaType | undefined;\n\tswitch (unwrappedData.definition._def.typeName) {\n\t\tcase ZodFirstPartyTypeKind.ZodArray: {\n\t\t\tconst arrayType = unwrappedData.definition as ZodArray<SupportedType>;\n\t\t\tconst elementType = arrayType._def.type;\n\t\t\tif (isZodObject(elementType)) {\n\t\t\t\tconst shape = elementType.shape;\n\t\t\t\tconst convertedShape: { [key: string]: MongooseSchemaType } = {};\n\t\t\t\tfor (const key in shape) {\n\t\t\t\t\tconvertedShape[key] = convertField(key, shape[key]);\n\t\t\t\t}\n\t\t\t\tcoreType = [convertedShape];\n\t\t\t} else {\n\t\t\t\tcoreType = [convertField(type, elementType)];\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase ZodFirstPartyTypeKind.ZodBoolean:\n\t\t\tcoreType = Boolean;\n\t\t\tbreak;\n\t\tcase ZodFirstPartyTypeKind.ZodDate:\n\t\t\tcoreType = Date;\n\t\t\tbreak;\n\t\tcase ZodFirstPartyTypeKind.ZodDefault:\n\t\t\tbreak;\n\t\tcase ZodFirstPartyTypeKind.ZodEnum: {\n\t\t\tconst enumType = unwrappedData.definition as unknown as z.ZodEnum<[string, ...string[]]>;\n\t\t\tcoreType = {\n\t\t\t\tenum: enumType.options,\n\t\t\t\ttype: String,\n\t\t\t};\n\t\t\tbreak;\n\t\t}\n\t\tcase ZodFirstPartyTypeKind.ZodNativeEnum: {\n\t\t\tconst enumType = unwrappedData.definition as unknown as ZodNativeEnum<EnumLike>;\n\t\t\tcoreType = {\n\t\t\t\tenum: getValidEnumValues(enumType.enum),\n\t\t\t\ttype: String,\n\t\t\t};\n\t\t\tbreak;\n\t\t}\n\t\tcase ZodFirstPartyTypeKind.ZodNumber:\n\t\t\tcoreType = Number;\n\t\t\tbreak;\n\t\tcase ZodFirstPartyTypeKind.ZodObject:\n\t\t\tbreak;\n\t\tcase ZodFirstPartyTypeKind.ZodString:\n\t\t\tcoreType = String;\n\t\t\tbreak;\n\t\tcase ZodFirstPartyTypeKind.ZodUnion:\n\t\t\tcoreType = Mongoose.SchemaTypes.Mixed;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new TypeError(`Unsupported type: ${type}`);\n\t}\n\tif (isZodObject(unwrappedData.definition)) {\n\t\tcoreType = createSchema(unwrappedData.definition);\n\t}\n\tif (coreType === undefined) {\n\t\tthrow new TypeError(`Could not determine Mongoose type for Zod type: ${type}`);\n\t}\n\n\tconst hasDefaultValue = unwrappedData.defaultValue !== undefined;\n\n\tif (unwrappedData.nullable && !hasDefaultValue) {\n\t\treturn {\n\t\t\tdefault: null,\n\t\t\ttype: coreType,\n\t\t};\n\t}\n\n\tif (hasDefaultValue) {\n\t\treturn {\n\t\t\tdefault: unwrappedData.defaultValue,\n\t\t\ttype: coreType,\n\t\t};\n\t}\n\treturn coreType;\n}\n\n/**\n * Check if a Zod definition is an object\n *\n * @param definition The Zod definition to check\n * @returns Whether the definition is an object\n */\nfunction isZodObject(definition: SupportedType): definition is ZodObject<ZodRawShape> {\n\treturn definition._def.typeName === ZodFirstPartyTypeKind.ZodObject;\n}\nfunction isZodDefault(definition: z.ZodTypeAny): definition is z.ZodDefault<SupportedType> {\n\treturn definition._def.typeName === ZodFirstPartyTypeKind.ZodDefault;\n}\n\nfunction isZodNullable(definition: z.ZodTypeAny): definition is z.ZodNullable<SupportedType> {\n\treturn definition._def.typeName === ZodFirstPartyTypeKind.ZodNullable;\n}\n\nfunction isZodOptional(definition: z.ZodTypeAny): definition is z.ZodOptional<SupportedType> {\n\treturn definition._def.typeName === ZodFirstPartyTypeKind.ZodOptional;\n}\n\nfunction getValidEnumValues(obj: { [s: string]: unknown }): (string | number)[] {\n\tconst validKeys = Object.keys(obj).filter((k) => typeof obj[k] === \"number\" || typeof obj[k] === \"string\");\n\tconst filtered: { [s: string]: unknown } = {};\n\tfor (const k of validKeys) {\n\t\tfiltered[k] = obj[k];\n\t}\n\n\treturn Object.values(filtered).filter((v) => typeof v === \"string\" || typeof v === \"number\");\n}\n\n/**\n * Takes a complex type and returns the inner type definition along with the default if present.\n *\n * @param data The type data to unwrap.\n * @returns The inner type data along with the default if present.\n */\nfunction unwrapType(data: SupportedType): {\n\tdefaultValue?: unknown;\n\tdefinition: SupportedType;\n\tnullable: boolean;\n\toptional: boolean;\n} {\n\tlet definition = data;\n\tlet nullable = false;\n\tlet optional = false;\n\tlet defaultValue: unknown | undefined;\n\twhile (\"innerType\" in definition._def) {\n\t\tif (isZodNullable(definition)) {\n\t\t\tnullable = true;\n\t\t}\n\t\tif (isZodOptional(definition)) {\n\t\t\toptional = true;\n\t\t}\n\t\tif (isZodDefault(definition)) {\n\t\t\tdefaultValue = definition._def.defaultValue();\n\t\t}\n\t\tdefinition = definition._def.innerType;\n\t}\n\treturn { defaultValue, definition, nullable, optional };\n}\n"],"mappings":"AACA,UAAYA,MAAc,WAC1B,OAEC,yBAAAC,MAMM,MA0BA,SAASC,EACfC,EACAC,EACAC,EACkG,CAClG,IAAMC,EAA4C,CAAC,EACnD,QAAWC,KAAOJ,EAAU,MAAO,CAClC,IAAMK,EAAWL,EAAU,MAAMI,CAAG,EACpCD,EAAeC,CAAG,EAAIE,EAAaF,EAAKC,C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U,mDAAmDH,CAAI,EAAE,EAG9E,IAAMS,EAAkBR,EAAc,eAAiB,OAEvD,OAAIA,EAAc,UAAY,CAACQ,EACvB,CACN,QAAS,KACT,KAAMN,CACP,EAGGM,EACI,CACN,QAASR,EAAc,aACvB,KAAME,CACP,EAEMA,CACR,CAQA,SAASE,EAAYK,EAAiE,CACrF,OAAOA,EAAW,KAAK,WAAapB,EAAsB,SAC3D,CACA,SAASqB,EAAaD,EAAqE,CAC1F,OAAOA,EAAW,KAAK,WAAapB,EAAsB,UAC3D,CAEA,SAASsB,EAAcF,EAAsE,CAC5F,OAAOA,EAAW,KAAK,WAAapB,EAAsB,WAC3D,CAEA,SAASuB,EAAcH,EAAsE,CAC5F,OAAOA,EAAW,KAAK,WAAapB,EAAsB,WAC3D,CAEA,SAASkB,EAAmBM,EAAoD,CAC/E,IAAMC,EAAY,OAAO,KAAKD,CAAG,EAAE,OAAQE,GAAM,OAAOF,EAAIE,CAAC,GAAM,UAAY,OAAOF,EAAIE,CAAC,GAAM,QAAQ,EACnGC,EAAqC,CAAC,EAC5C,QAAWD,KAAKD,EACfE,EAASD,CAAC,EAAIF,EAAIE,CAAC,EAGpB,OAAO,OAAO,OAAOC,CAAQ,EAAE,OAAQC,GAAM,OAAOA,GAAM,UAAY,OAAOA,GAAM,QAAQ,CAC5F,CAQA,SAAShB,EAAWiB,EAKlB,CACD,IAAIT,EAAaS,EACbC,EAAW,GACXC,EAAW,GACXC,EACJ,KAAO,cAAeZ,EAAW,MAC5BE,EAAcF,CAAU,IAC3BU,EAAW,IAERP,EAAcH,CAAU,IAC3BW,EAAW,IAERV,EAAaD,CAAU,IAC1BY,EAAeZ,EAAW,KAAK,aAAa,GAE7CA,EAAaA,EAAW,KAAK,UAE9B,MAAO,CAAE,aAAAY,EAAc,WAAAZ,EAAY,SAAAU,EAAU,SAAAC,CAAS,CACvD","names":["Mongoose","ZodFirstPartyTypeKind","createSchema","zodObject","modelName","connection","convertedShape","key","zodField","convertField","schema","type","unwrappedData","unwrapType","coreType","elementType","isZodObject","shape","enumType","getValidEnumValues","hasDefaultValue","definition","isZodDefault","isZodNullable","isZodOptional","obj","validKeys","k","filtered","v","data","nullable","optional","defaultValue"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mirite/zod-to-mongoose",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "Package for creating mongoose schemas out of Zod schemas for type safety, and removing duplicate effort.",
5
5
  "keywords": [
6
6
  "zod",