@nullix/zod-mongoose-studio 2.3.0 → 2.4.1

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.
@@ -6,7 +6,8 @@ import { fileURLToPath } from 'node:url';
6
6
  import { dirname } from 'node:path';
7
7
  import * as zod from 'zod';
8
8
  import * as mongoose from 'mongoose';
9
- import * as v4$1 from 'zod/v4';
9
+ import mongoose__default from 'mongoose';
10
+ import { z } from 'zod/v4';
10
11
  import 'node:http';
11
12
  import 'node:https';
12
13
  import 'node:events';
@@ -16,1379 +17,1113 @@ import 'node:crypto';
16
17
  import '@iconify/utils';
17
18
  import 'consola';
18
19
 
19
- function _mergeNamespaces(n, m) {
20
- for (var i = 0; i < m.length; i++) {
21
- const e = m[i];
22
- if (typeof e !== 'string' && !Array.isArray(e)) { for (const k in e) {
23
- if (k !== 'default' && !(k in n)) {
24
- const d = Object.getOwnPropertyDescriptor(e, k);
25
- if (d) {
26
- Object.defineProperty(n, k, d.get ? d : {
27
- enumerable: true,
28
- get: function () { return e[k]; }
29
- });
30
- }
31
- }
32
- } }
33
- }
34
- return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { value: 'Module' }));
35
- }
36
-
37
- function getDefaultExportFromNamespaceIfNotNamed (n) {
38
- return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
39
- }
40
-
41
- var dist = {};
42
-
43
- const require$$0 = /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(v4$1);
44
-
45
- var v4 = require$$0;
46
-
47
- //#region src/utils.ts
48
- function flatHooks(configHooks, hooks = {}, parentName) {
49
- for (const key in configHooks) {
50
- const subHook = configHooks[key];
51
- const name = parentName ? `${parentName}:${key}` : key;
52
- if (typeof subHook === "object" && subHook !== null) flatHooks(subHook, hooks, name);
53
- else if (typeof subHook === "function") hooks[name] = subHook;
54
- }
55
- return hooks;
20
+ var __defProp = Object.defineProperty;
21
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
22
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
23
+ function flatHooks(configHooks, hooks2 = {}, parentName) {
24
+ for (const key in configHooks) {
25
+ const subHook = configHooks[key];
26
+ const name = parentName ? `${parentName}:${key}` : key;
27
+ if (typeof subHook === "object" && subHook !== null) flatHooks(subHook, hooks2, name);
28
+ else if (typeof subHook === "function") hooks2[name] = subHook;
29
+ }
30
+ return hooks2;
56
31
  }
57
32
  const createTask = /* @__PURE__ */ (() => {
58
- if (console.createTask) return console.createTask;
59
- const defaultTask = { run: (fn) => fn() };
60
- return () => defaultTask;
33
+ if (console.createTask) return console.createTask;
34
+ const defaultTask = { run: (fn) => fn() };
35
+ return () => defaultTask;
61
36
  })();
62
- function callHooks(hooks, args, startIndex, task) {
63
- for (let i = startIndex; i < hooks.length; i += 1) try {
64
- const result = task ? task.run(() => hooks[i](...args)) : hooks[i](...args);
65
- if (result instanceof Promise) return result.then(() => callHooks(hooks, args, i + 1, task));
66
- } catch (error) {
67
- return Promise.reject(error);
68
- }
37
+ function callHooks(hooks2, args, startIndex, task) {
38
+ for (let i = startIndex; i < hooks2.length; i += 1) try {
39
+ const result = task ? task.run(() => hooks2[i](...args)) : hooks2[i](...args);
40
+ if (result instanceof Promise) return result.then(() => callHooks(hooks2, args, i + 1, task));
41
+ } catch (error) {
42
+ return Promise.reject(error);
43
+ }
69
44
  }
70
- function serialTaskCaller(hooks, args, name) {
71
- if (hooks.length > 0) return callHooks(hooks, args, 0, createTask(name));
45
+ function serialTaskCaller(hooks2, args, name) {
46
+ if (hooks2.length > 0) return callHooks(hooks2, args, 0, createTask(name));
72
47
  }
73
- function parallelTaskCaller(hooks, args, name) {
74
- if (hooks.length > 0) {
75
- const task = createTask(name);
76
- return Promise.all(hooks.map((hook) => task.run(() => hook(...args))));
77
- }
48
+ function parallelTaskCaller(hooks2, args, name) {
49
+ if (hooks2.length > 0) {
50
+ const task = createTask(name);
51
+ return Promise.all(hooks2.map((hook) => task.run(() => hook(...args))));
52
+ }
78
53
  }
79
54
  function callEachWith(callbacks, arg0) {
80
- for (const callback of [...callbacks]) callback(arg0);
55
+ for (const callback of [...callbacks]) callback(arg0);
81
56
  }
82
- //#endregion
83
- //#region src/hookable.ts
84
57
  var Hookable = class {
85
- _hooks;
86
- _before;
87
- _after;
88
- _deprecatedHooks;
89
- _deprecatedMessages;
90
- constructor() {
91
- this._hooks = {};
92
- this._before = void 0;
93
- this._after = void 0;
94
- this._deprecatedMessages = void 0;
95
- this._deprecatedHooks = {};
96
- this.hook = this.hook.bind(this);
97
- this.callHook = this.callHook.bind(this);
98
- this.callHookWith = this.callHookWith.bind(this);
99
- }
100
- hook(name, function_, options = {}) {
101
- if (!name || typeof function_ !== "function") return () => {};
102
- const originalName = name;
103
- let dep;
104
- while (this._deprecatedHooks[name]) {
105
- dep = this._deprecatedHooks[name];
106
- name = dep.to;
107
- }
108
- if (dep && !options.allowDeprecated) {
109
- let message = dep.message;
110
- if (!message) message = `${originalName} hook has been deprecated` + (dep.to ? `, please use ${dep.to}` : "");
111
- if (!this._deprecatedMessages) this._deprecatedMessages = /* @__PURE__ */ new Set();
112
- if (!this._deprecatedMessages.has(message)) {
113
- console.warn(message);
114
- this._deprecatedMessages.add(message);
115
- }
116
- }
117
- if (!function_.name) try {
118
- Object.defineProperty(function_, "name", {
119
- get: () => "_" + name.replace(/\W+/g, "_") + "_hook_cb",
120
- configurable: true
121
- });
122
- } catch {}
123
- this._hooks[name] = this._hooks[name] || [];
124
- this._hooks[name].push(function_);
125
- return () => {
126
- if (function_) {
127
- this.removeHook(name, function_);
128
- function_ = void 0;
129
- }
130
- };
131
- }
132
- hookOnce(name, function_) {
133
- let _unreg;
134
- let _function = (...arguments_) => {
135
- if (typeof _unreg === "function") _unreg();
136
- _unreg = void 0;
137
- _function = void 0;
138
- return function_(...arguments_);
139
- };
140
- _unreg = this.hook(name, _function);
141
- return _unreg;
142
- }
143
- removeHook(name, function_) {
144
- const hooks = this._hooks[name];
145
- if (hooks) {
146
- const index = hooks.indexOf(function_);
147
- if (index !== -1) hooks.splice(index, 1);
148
- if (hooks.length === 0) this._hooks[name] = void 0;
149
- }
150
- }
151
- clearHook(name) {
152
- this._hooks[name] = void 0;
153
- }
154
- deprecateHook(name, deprecated) {
155
- this._deprecatedHooks[name] = typeof deprecated === "string" ? { to: deprecated } : deprecated;
156
- const _hooks = this._hooks[name] || [];
157
- this._hooks[name] = void 0;
158
- for (const hook of _hooks) this.hook(name, hook);
159
- }
160
- deprecateHooks(deprecatedHooks) {
161
- for (const name in deprecatedHooks) this.deprecateHook(name, deprecatedHooks[name]);
162
- }
163
- addHooks(configHooks) {
164
- const hooks = flatHooks(configHooks);
165
- const removeFns = Object.keys(hooks).map((key) => this.hook(key, hooks[key]));
166
- return () => {
167
- for (const unreg of removeFns) unreg();
168
- removeFns.length = 0;
169
- };
170
- }
171
- removeHooks(configHooks) {
172
- const hooks = flatHooks(configHooks);
173
- for (const key in hooks) this.removeHook(key, hooks[key]);
174
- }
175
- removeAllHooks() {
176
- this._hooks = {};
177
- }
178
- callHook(name, ...args) {
179
- return this.callHookWith(serialTaskCaller, name, args);
180
- }
181
- callHookParallel(name, ...args) {
182
- return this.callHookWith(parallelTaskCaller, name, args);
183
- }
184
- callHookWith(caller, name, args) {
185
- const event = this._before || this._after ? {
186
- name,
187
- args,
188
- context: {}
189
- } : void 0;
190
- if (this._before) callEachWith(this._before, event);
191
- const result = caller(this._hooks[name] ? [...this._hooks[name]] : [], args, name);
192
- if (result instanceof Promise) return result.finally(() => {
193
- if (this._after && event) callEachWith(this._after, event);
194
- });
195
- if (this._after && event) callEachWith(this._after, event);
196
- return result;
197
- }
198
- beforeEach(function_) {
199
- this._before = this._before || [];
200
- this._before.push(function_);
201
- return () => {
202
- if (this._before !== void 0) {
203
- const index = this._before.indexOf(function_);
204
- if (index !== -1) this._before.splice(index, 1);
205
- }
206
- };
207
- }
208
- afterEach(function_) {
209
- this._after = this._after || [];
210
- this._after.push(function_);
211
- return () => {
212
- if (this._after !== void 0) {
213
- const index = this._after.indexOf(function_);
214
- if (index !== -1) this._after.splice(index, 1);
215
- }
216
- };
217
- }
58
+ constructor() {
59
+ __publicField(this, "_hooks");
60
+ __publicField(this, "_before");
61
+ __publicField(this, "_after");
62
+ __publicField(this, "_deprecatedHooks");
63
+ __publicField(this, "_deprecatedMessages");
64
+ this._hooks = {};
65
+ this._before = void 0;
66
+ this._after = void 0;
67
+ this._deprecatedMessages = void 0;
68
+ this._deprecatedHooks = {};
69
+ this.hook = this.hook.bind(this);
70
+ this.callHook = this.callHook.bind(this);
71
+ this.callHookWith = this.callHookWith.bind(this);
72
+ }
73
+ hook(name, function_, options = {}) {
74
+ if (!name || typeof function_ !== "function") return () => {
75
+ };
76
+ const originalName = name;
77
+ let dep;
78
+ while (this._deprecatedHooks[name]) {
79
+ dep = this._deprecatedHooks[name];
80
+ name = dep.to;
81
+ }
82
+ if (dep && !options.allowDeprecated) {
83
+ let message = dep.message;
84
+ if (!message) message = `${originalName} hook has been deprecated` + (dep.to ? `, please use ${dep.to}` : "");
85
+ if (!this._deprecatedMessages) this._deprecatedMessages = /* @__PURE__ */ new Set();
86
+ if (!this._deprecatedMessages.has(message)) {
87
+ console.warn(message);
88
+ this._deprecatedMessages.add(message);
89
+ }
90
+ }
91
+ if (!function_.name) try {
92
+ Object.defineProperty(function_, "name", {
93
+ get: () => "_" + name.replace(/\W+/g, "_") + "_hook_cb",
94
+ configurable: true
95
+ });
96
+ } catch {
97
+ }
98
+ this._hooks[name] = this._hooks[name] || [];
99
+ this._hooks[name].push(function_);
100
+ return () => {
101
+ if (function_) {
102
+ this.removeHook(name, function_);
103
+ function_ = void 0;
104
+ }
105
+ };
106
+ }
107
+ hookOnce(name, function_) {
108
+ let _unreg;
109
+ let _function = (...arguments_) => {
110
+ if (typeof _unreg === "function") _unreg();
111
+ _unreg = void 0;
112
+ _function = void 0;
113
+ return function_(...arguments_);
114
+ };
115
+ _unreg = this.hook(name, _function);
116
+ return _unreg;
117
+ }
118
+ removeHook(name, function_) {
119
+ const hooks2 = this._hooks[name];
120
+ if (hooks2) {
121
+ const index = hooks2.indexOf(function_);
122
+ if (index !== -1) hooks2.splice(index, 1);
123
+ if (hooks2.length === 0) this._hooks[name] = void 0;
124
+ }
125
+ }
126
+ clearHook(name) {
127
+ this._hooks[name] = void 0;
128
+ }
129
+ deprecateHook(name, deprecated) {
130
+ this._deprecatedHooks[name] = typeof deprecated === "string" ? { to: deprecated } : deprecated;
131
+ const _hooks = this._hooks[name] || [];
132
+ this._hooks[name] = void 0;
133
+ for (const hook of _hooks) this.hook(name, hook);
134
+ }
135
+ deprecateHooks(deprecatedHooks) {
136
+ for (const name in deprecatedHooks) this.deprecateHook(name, deprecatedHooks[name]);
137
+ }
138
+ addHooks(configHooks) {
139
+ const hooks2 = flatHooks(configHooks);
140
+ const removeFns = Object.keys(hooks2).map((key) => this.hook(key, hooks2[key]));
141
+ return () => {
142
+ for (const unreg of removeFns) unreg();
143
+ removeFns.length = 0;
144
+ };
145
+ }
146
+ removeHooks(configHooks) {
147
+ const hooks2 = flatHooks(configHooks);
148
+ for (const key in hooks2) this.removeHook(key, hooks2[key]);
149
+ }
150
+ removeAllHooks() {
151
+ this._hooks = {};
152
+ }
153
+ callHook(name, ...args) {
154
+ return this.callHookWith(serialTaskCaller, name, args);
155
+ }
156
+ callHookParallel(name, ...args) {
157
+ return this.callHookWith(parallelTaskCaller, name, args);
158
+ }
159
+ callHookWith(caller, name, args) {
160
+ const event = this._before || this._after ? {
161
+ name,
162
+ args,
163
+ context: {}
164
+ } : void 0;
165
+ if (this._before) callEachWith(this._before, event);
166
+ const result = caller(this._hooks[name] ? [...this._hooks[name]] : [], args, name);
167
+ if (result instanceof Promise) return result.finally(() => {
168
+ if (this._after && event) callEachWith(this._after, event);
169
+ });
170
+ if (this._after && event) callEachWith(this._after, event);
171
+ return result;
172
+ }
173
+ beforeEach(function_) {
174
+ this._before = this._before || [];
175
+ this._before.push(function_);
176
+ return () => {
177
+ if (this._before !== void 0) {
178
+ const index = this._before.indexOf(function_);
179
+ if (index !== -1) this._before.splice(index, 1);
180
+ }
181
+ };
182
+ }
183
+ afterEach(function_) {
184
+ this._after = this._after || [];
185
+ this._after.push(function_);
186
+ return () => {
187
+ if (this._after !== void 0) {
188
+ const index = this._after.indexOf(function_);
189
+ if (index !== -1) this._after.splice(index, 1);
190
+ }
191
+ };
192
+ }
218
193
  };
219
194
  function createHooks() {
220
- return new Hookable();
195
+ return new Hookable();
221
196
  }
222
-
223
197
  const hooks = createHooks();
224
- /**
225
- * Synchronous hook caller for Hookable.
226
- */
227
198
  function callHookSync(name, ...args) {
228
- hooks.callHookWith((callbacks, args) => {
229
- for (const callback of callbacks) {
230
- callback(...args);
231
- }
232
- }, name, args);
199
+ hooks.callHookWith((callbacks, args2) => {
200
+ for (const callback of callbacks) {
201
+ callback(...args2);
202
+ }
203
+ }, name, args);
233
204
  }
234
-
235
- /**
236
- * This securely stores our Mongoose metadata alongside the Zod schema instances
237
- * without polluting the actual validation logic.
238
- */
239
- const mongooseRegistry = v4.z.registry();
240
- /**
241
- * A clean wrapper to attach Mongoose metadata to any Zod schema.
242
- */
205
+ const mongooseRegistry = z.registry();
243
206
  function withMongoose(schema, meta = {}) {
244
- callHookSync('registry:get:before', { schema });
245
- const existing = mongooseRegistry.get(schema) || {};
246
- callHookSync('registry:get', { schema, meta: existing });
247
- const merged = { ...existing, ...meta };
248
- callHookSync('registry:add', { schema, meta: merged });
249
- mongooseRegistry.add(schema, merged);
250
- callHookSync('registry:added', { schema, meta: merged });
251
- return schema;
207
+ callHookSync("registry:get:before", { schema });
208
+ const existing = mongooseRegistry.get(schema) || {};
209
+ callHookSync("registry:get", { schema, meta: existing });
210
+ const merged = { ...existing, ...meta };
211
+ callHookSync("registry:add", { schema, meta: merged });
212
+ mongooseRegistry.add(schema, merged);
213
+ callHookSync("registry:added", { schema, meta: merged });
214
+ return schema;
252
215
  }
253
- /**
254
- * Recursively collect Mongoose metadata from a Zod schema and its wrappers.
255
- */
256
216
  function getMongooseMeta(schema) {
257
- const def = schema._def;
258
- if (!def)
259
- return {};
260
- let meta = mongooseRegistry.get(schema) || {};
261
- // If it has an inner type (Optional, Nullable, Default, etc.), collect from it too
262
- if (def.innerType) {
263
- meta = { ...getMongooseMeta(def.innerType), ...meta };
264
- }
265
- else if (def.schema) {
266
- meta = { ...getMongooseMeta(def.schema), ...meta };
267
- }
268
- // Handle pipes (like z.codec)
269
- if (def.type === 'pipe') {
270
- // Collect from both 'in' and 'out' parts, preferring metadata from 'out' if it exists,
271
- // but the pipe itself usually holds the metadata we want.
272
- meta = { ...getMongooseMeta(def.in), ...getMongooseMeta(def.out), ...meta };
273
- }
274
- return meta;
217
+ const def = schema._def;
218
+ if (!def)
219
+ return {};
220
+ let meta = mongooseRegistry.get(schema) || {};
221
+ if (def.innerType) {
222
+ meta = { ...getMongooseMeta(def.innerType), ...meta };
223
+ } else if (def.schema) {
224
+ meta = { ...getMongooseMeta(def.schema), ...meta };
225
+ }
226
+ if (def.type === "pipe") {
227
+ meta = { ...getMongooseMeta(def.in), ...getMongooseMeta(def.out), ...meta };
228
+ }
229
+ return meta;
275
230
  }
276
-
277
- /**
278
- * Recursively unwrap Zod schemas (Optional, Nullable, Default, Effects, Pipelines)
279
- * using Zod's public API and internal _def.type identifiers.
280
- */
281
- function unwrapZodSchema(schema,
282
- // eslint-disable-next-line unicorn/no-object-as-default-parameter
283
- features = { required: true }, visited = new Set()) {
284
- if (!schema)
285
- return { schema, features };
286
- if (visited.has(schema))
287
- return { schema, features };
288
- const def = schema._def;
289
- if (!def)
290
- return { schema, features };
291
- // Skip visited check for wrappers to allow deep unwrapping
292
- if (!(schema instanceof v4.z.ZodOptional) &&
293
- !(schema instanceof v4.z.ZodNullable) &&
294
- !(schema instanceof v4.z.ZodDefault) &&
295
- def.type !== 'pipe') {
296
- visited.add(schema);
297
- }
298
- if (schema instanceof v4.z.ZodOptional) {
299
- const inner = schema.unwrap();
300
- return unwrapZodSchema(
301
- // @ts-expect-error Zod v4 schema.unwrap() return type mismatch
302
- inner, {
303
- ...features,
304
- required: false,
305
- isOptional: true,
306
- }, visited);
307
- }
308
- if (schema instanceof v4.z.ZodNullable) {
309
- return unwrapZodSchema(
310
- // @ts-expect-error Zod v4 schema.unwrap() return type mismatch
311
- schema.unwrap(), {
312
- ...features,
313
- isNullable: true,
314
- }, visited);
315
- }
316
- if (schema instanceof v4.z.ZodDefault) {
317
- const defaultValue = typeof def.defaultValue === 'function' ? def.defaultValue() : def.defaultValue;
318
- return unwrapZodSchema(def.innerType, {
319
- ...features,
320
- default: defaultValue,
321
- }, visited);
322
- }
323
- const { type } = def;
324
- // In Zod v4, transform, preprocess, and refine are often implemented as pipes.
325
- // For transform: in = schema, out = transformation
326
- // For preprocess: in = preprocessing, out = schema
327
- if (type === 'pipe') {
328
- const inType = def.in?._def?.type;
329
- const outType = def.out?._def?.type;
330
- if (inType === 'transform') {
331
- // It's a preprocess (in is transformation, out is schema)
332
- return unwrapZodSchema(def.out, features, visited);
333
- }
334
- if (outType === 'transform' || outType === 'refinement') {
335
- // It's a transform or refine (in is schema, out is logic)
336
- // We should still collect transformations from the 'out' part
337
- const transformFeatures = { ...features };
338
- const outDef = def.out?._def;
339
- const effects = outDef?.effects || outDef?.transformations || (outType === 'transform' ? [outDef] : []);
340
- if (effects && Array.isArray(effects)) {
341
- transformFeatures.transformations = [
342
- ...(transformFeatures.transformations || []),
343
- ...effects,
344
- ];
345
- }
346
- return unwrapZodSchema(def.in, transformFeatures, visited);
347
- }
348
- // Default pipe behavior (extract the output part)
349
- return unwrapZodSchema(def.out, features, visited);
350
- }
351
- if (type === 'transform' ||
352
- type === 'preprocess' ||
353
- type === 'refinement' ||
354
- type === 'effects') {
355
- const transformFeatures = { ...features };
356
- const effects = def.effects || def.transformations || (def.type === 'transform' || type === 'transform' ? [def] : []);
357
- if (effects && Array.isArray(effects)) {
358
- transformFeatures.transformations = [
359
- ...(transformFeatures.transformations || []),
360
- ...effects,
361
- ];
362
- }
363
- const inner = def.schema || def.innerType;
364
- if (inner) {
365
- const result = unwrapZodSchema(inner, transformFeatures, visited);
366
- return result;
367
- }
231
+ function unwrapZodSchema(schema, features = { required: true }, visited = /* @__PURE__ */ new Set()) {
232
+ var _a, _b, _c, _d, _e;
233
+ if (!schema)
234
+ return { schema, features };
235
+ if (visited.has(schema))
236
+ return { schema, features };
237
+ const def = schema._def;
238
+ if (!def)
239
+ return { schema, features };
240
+ if (!(schema instanceof z.ZodOptional) && !(schema instanceof z.ZodNullable) && !(schema instanceof z.ZodDefault) && def.type !== "pipe") {
241
+ visited.add(schema);
242
+ }
243
+ if (schema instanceof z.ZodOptional) {
244
+ const inner = schema.unwrap();
245
+ return unwrapZodSchema(
246
+ // @ts-expect-error Zod v4 schema.unwrap() return type mismatch
247
+ inner,
248
+ {
249
+ ...features,
250
+ required: false,
251
+ isOptional: true
252
+ },
253
+ visited
254
+ );
255
+ }
256
+ if (schema instanceof z.ZodNullable) {
257
+ return unwrapZodSchema(
258
+ // @ts-expect-error Zod v4 schema.unwrap() return type mismatch
259
+ schema.unwrap(),
260
+ {
261
+ ...features,
262
+ isNullable: true
263
+ },
264
+ visited
265
+ );
266
+ }
267
+ if (schema instanceof z.ZodDefault) {
268
+ const defaultValue = typeof def.defaultValue === "function" ? def.defaultValue() : def.defaultValue;
269
+ return unwrapZodSchema(def.innerType, {
270
+ ...features,
271
+ default: defaultValue
272
+ }, visited);
273
+ }
274
+ const { type } = def;
275
+ if (type === "pipe") {
276
+ const inType = (_b = (_a = def.in) == null ? void 0 : _a._def) == null ? void 0 : _b.type;
277
+ const outType = (_d = (_c = def.out) == null ? void 0 : _c._def) == null ? void 0 : _d.type;
278
+ if (inType === "transform") {
279
+ return unwrapZodSchema(def.out, features, visited);
368
280
  }
369
- if (type === 'lazy') {
370
- // For lazy types, we need to be careful with infinite recursion.
371
- // If we've already seen this specific lazy schema in this unwrapping chain,
372
- // we return it as is to stop recursion.
373
- // NOTE: In Zod v4, getter() might return different objects each time if not careful.
374
- return { schema, features };
281
+ if (outType === "transform" || outType === "refinement") {
282
+ const transformFeatures = { ...features };
283
+ const outDef = (_e = def.out) == null ? void 0 : _e._def;
284
+ const effects = (outDef == null ? void 0 : outDef.effects) || (outDef == null ? void 0 : outDef.transformations) || (outType === "transform" ? [outDef] : []);
285
+ if (effects && Array.isArray(effects)) {
286
+ transformFeatures.transformations = [
287
+ ...transformFeatures.transformations || [],
288
+ ...effects
289
+ ];
290
+ }
291
+ return unwrapZodSchema(def.in, transformFeatures, visited);
375
292
  }
376
- if (type === 'branded' || type === 'readonly') {
377
- return unwrapZodSchema(schema.unwrap(), {
378
- ...features,
379
- ...(type === 'readonly' ? { readOnly: true } : {}),
380
- }, visited);
293
+ return unwrapZodSchema(def.out, features, visited);
294
+ }
295
+ if (type === "transform" || type === "preprocess" || type === "refinement" || type === "effects") {
296
+ const transformFeatures = { ...features };
297
+ const effects = def.effects || def.transformations || (def.type === "transform" || type === "transform" ? [def] : []);
298
+ if (effects && Array.isArray(effects)) {
299
+ transformFeatures.transformations = [
300
+ ...transformFeatures.transformations || [],
301
+ ...effects
302
+ ];
381
303
  }
382
- // Extract checks if present
383
- if (def.checks && Array.isArray(def.checks)) {
384
- features.checks = [...(features.checks || []), ...def.checks];
304
+ const inner = def.schema || def.innerType;
305
+ if (inner) {
306
+ const result = unwrapZodSchema(inner, transformFeatures, visited);
307
+ return result;
385
308
  }
309
+ }
310
+ if (type === "lazy") {
386
311
  return { schema, features };
312
+ }
313
+ if (type === "branded" || type === "readonly") {
314
+ return unwrapZodSchema(schema.unwrap(), {
315
+ ...features,
316
+ ...type === "readonly" ? { readOnly: true } : {}
317
+ }, visited);
318
+ }
319
+ if (def.checks && Array.isArray(def.checks)) {
320
+ features.checks = [...features.checks || [], ...def.checks];
321
+ }
322
+ return { schema, features };
387
323
  }
388
-
389
324
  let mongooseInstance = null;
390
- /**
391
- * Manually set the Mongoose instance.
392
- * Useful in ESM environments where automatic detection via require() might fail.
393
- */
394
325
  const setMongoose = (m) => {
395
- mongooseInstance = m;
326
+ mongooseInstance = m;
396
327
  };
397
- // Helper to get mongoose instance safely
398
328
  const getMongoose = () => {
399
- if (mongooseInstance) {
400
- return mongooseInstance;
401
- }
402
- try {
403
- // eslint-disable-next-line global-require
404
- const m = require('mongoose');
405
- if (m && (m.Schema || m.default?.Schema)) {
406
- return m.default || m;
407
- }
408
- return m;
329
+ var _a;
330
+ if (mongooseInstance) {
331
+ return mongooseInstance;
332
+ }
333
+ try {
334
+ const m = require("mongoose");
335
+ if (m && (m.Schema || ((_a = m.default) == null ? void 0 : _a.Schema))) {
336
+ return m.default || m;
409
337
  }
410
- catch {
411
- // Try to see if mongoose is globally available (e.g. in some environments)
412
- if (globalThis.mongoose) {
413
- return globalThis.mongoose;
414
- }
415
- return null;
338
+ return m;
339
+ } catch {
340
+ if (globalThis.mongoose) {
341
+ return globalThis.mongoose;
416
342
  }
343
+ return null;
344
+ }
417
345
  };
418
346
  let isFrontend = false;
419
- /**
420
- * Enable or disable frontend mode.
421
- * In frontend mode, specialized types like ObjectId and Buffer fall back to
422
- * simpler representations (strings/arrays) and do not depend on Mongoose.
423
- */
424
347
  const setFrontendMode = (enabled) => {
425
- isFrontend = enabled;
348
+ isFrontend = enabled;
426
349
  };
427
350
  const getFrontendMode = () => {
428
- // Try to auto-detect if not explicitly set
429
- // This is a simple heuristic: check for window/document
430
- if (isFrontend === undefined || isFrontend === null) {
431
- return globalThis.window !== undefined && globalThis.document !== undefined;
432
- }
433
- return isFrontend;
351
+ if (isFrontend === void 0 || isFrontend === null) {
352
+ return globalThis.window !== void 0 && globalThis.document !== void 0;
353
+ }
354
+ return isFrontend;
434
355
  };
435
-
436
- /**
437
- * Helper to map Zod checks (min, max, regex, etc.) to Mongoose Schema properties.
438
- */
439
356
  function mapZodChecksToMongoose(checks, mongooseProp) {
440
- if (!checks || !Array.isArray(checks))
441
- return;
442
- for (const check of checks) {
443
- const traitSet = check._zod?.traits;
444
- const checkDef = check._zod?.def;
445
- if (!traitSet || !checkDef)
446
- continue;
447
- // String Lengths
448
- if (traitSet.has('$ZodCheckMinLength')) {
449
- mongooseProp.minlength = checkDef.minimum;
450
- }
451
- if (traitSet.has('$ZodCheckMaxLength')) {
452
- mongooseProp.maxlength = checkDef.maximum;
453
- }
454
- if (traitSet.has('$ZodCheckLengthEquals')) {
455
- mongooseProp.minlength = checkDef.length;
456
- mongooseProp.maxlength = checkDef.length;
457
- }
458
- // Numbers and Dates Comparisons
459
- if (traitSet.has('$ZodCheckGreaterThan')) {
460
- mongooseProp.min = checkDef.value;
461
- }
462
- if (traitSet.has('$ZodCheckLessThan')) {
463
- mongooseProp.max = checkDef.value;
464
- }
465
- // Regex / Match
466
- if (traitSet.has('$ZodCheckRegex')) {
467
- mongooseProp.match = checkDef.pattern;
468
- }
469
- // UUID
470
- if (traitSet.has('$ZodUUID')) {
471
- const mongoose = globalThis.mongoose || globalThis.__mongoose;
472
- if (mongoose?.Schema.Types.UUID) {
473
- mongooseProp.type = mongoose.Schema.Types.UUID;
474
- }
475
- }
476
- // ISO Formats
477
- if (traitSet.has('$ZodISODateTime') || traitSet.has('$ZodISODate')) {
478
- mongooseProp.type = Date;
479
- }
480
- // String Transforms (trim, lowercase, uppercase)
481
- if (traitSet.has('$ZodCheckOverwrite') && typeof checkDef.tx === 'function') {
482
- const txStr = checkDef.tx.toString();
483
- if (txStr.includes('.trim()')) {
484
- mongooseProp.trim = true;
485
- }
486
- else if (txStr.includes('.toLowerCase()')) {
487
- mongooseProp.lowercase = true;
488
- }
489
- else if (txStr.includes('.toUpperCase()')) {
490
- mongooseProp.uppercase = true;
491
- }
492
- }
357
+ var _a, _b;
358
+ if (!checks || !Array.isArray(checks))
359
+ return;
360
+ for (const check of checks) {
361
+ const traitSet = (_a = check._zod) == null ? void 0 : _a.traits;
362
+ const checkDef = (_b = check._zod) == null ? void 0 : _b.def;
363
+ if (!traitSet || !checkDef)
364
+ continue;
365
+ if (traitSet.has("$ZodCheckMinLength")) {
366
+ mongooseProp.minlength = checkDef.minimum;
493
367
  }
494
- callHookSync('validation:mappers', { checks, mongooseProp });
495
- }
496
-
497
- /**
498
- * Handles ZodObject conversion to Mongoose Schema definition.
499
- */
500
- function handleObject(unwrapped, mongooseProp, visited, extractMongooseDef, isField = false) {
501
- callHookSync('schema:object:before', { schema: unwrapped, mongooseProp, visited });
502
- const { shape } = unwrapped;
503
- const objDef = {};
504
- // We must ensure recursive calls see the current object to break cycles.
505
- const placeholder = mongooseProp.type ? mongooseProp : objDef;
506
- visited.set(unwrapped, placeholder);
507
- // eslint-disable-next-line no-restricted-syntax
508
- for (const key in shape) {
509
- if (!Object.prototype.hasOwnProperty.call(shape, key))
510
- continue;
511
- // Skip automatic _id mapping unless explicitly requested
512
- if (key === '_id') {
513
- const idMeta = mongooseRegistry.get(shape[key]) || {};
514
- const unwrappedId = unwrapZodSchema(shape[key]).schema;
515
- const unwrappedIdMeta = mongooseRegistry.get(unwrappedId) || {};
516
- if (idMeta.includeId !== true &&
517
- unwrappedIdMeta.includeId !== true &&
518
- mongooseProp.includeId !== true) {
519
- continue;
520
- }
521
- }
522
- const def = extractMongooseDef(shape[key], visited);
523
- if (def && typeof def === 'object' && def.__isDiscriminatorUnion) {
524
- const mongoose = getMongoose();
525
- if (mongoose) {
526
- const baseSchema = new mongoose.Schema(def.baseDef, {
527
- discriminatorKey: def.discriminatorKey,
528
- _id: false,
529
- });
530
- const discriminators = {};
531
- for (const [dKey, dDef] of Object.entries(def.discriminators)) {
532
- discriminators[dKey] = new mongoose.Schema(dDef, { _id: false });
533
- }
534
- objDef[key] = {
535
- type: baseSchema,
536
- discriminators,
537
- };
538
- }
539
- else {
540
- objDef[key] = def;
541
- }
542
- }
543
- else if (typeof def === 'object' && def !== null && !Array.isArray(def)) {
544
- const { includeId, ...cleanDef } = def;
545
- objDef[key] = cleanDef;
546
- }
547
- else {
548
- objDef[key] = def;
549
- }
550
- callHookSync('schema:object:field', { key, schema: shape[key], objDef, visited });
368
+ if (traitSet.has("$ZodCheckMaxLength")) {
369
+ mongooseProp.maxlength = checkDef.maximum;
551
370
  }
552
- // If the developer didn't provide a strict Mongoose type override, return the shape
553
- let result;
554
- // Handle explicit or default subschema request
555
- const shouldBeSubSchema = isField && mongooseProp.schema !== false;
556
- if (shouldBeSubSchema && !mongooseProp.type) {
557
- const mongoose = getMongoose();
558
- if (mongoose) {
559
- const options = typeof mongooseProp.schema === 'object' ? mongooseProp.schema : {};
560
- const { plugins, ...schemaOptions } = options;
561
- const subSchema = new mongoose.Schema(objDef, schemaOptions);
562
- if (plugins && Array.isArray(plugins)) {
563
- for (const plugin of plugins) {
564
- subSchema.plugin(plugin);
565
- }
566
- }
567
- mongooseProp.type = subSchema;
568
- }
371
+ if (traitSet.has("$ZodCheckLengthEquals")) {
372
+ mongooseProp.minlength = checkDef.length;
373
+ mongooseProp.maxlength = checkDef.length;
569
374
  }
570
- if (mongooseProp.type) {
571
- const mongoose = getMongoose();
572
- const isSchema = mongoose && (mongooseProp.type instanceof mongoose.Schema || mongooseProp.type.constructor?.name === 'Schema');
573
- // If there is a type override, merge the object definition into the result unless it's a Schema
574
- if (!isSchema) {
575
- Object.assign(mongooseProp, objDef);
576
- }
577
- result = mongooseProp;
375
+ if (traitSet.has("$ZodCheckGreaterThan")) {
376
+ mongooseProp.min = checkDef.value;
578
377
  }
579
- else {
580
- Object.assign(mongooseProp, objDef);
581
- const topLevelOptions = new Set([
582
- 'collection',
583
- 'versionKey',
584
- 'timestamps',
585
- 'discriminatorKey',
586
- 'strict',
587
- 'id',
588
- '_id',
589
- 'minimize',
590
- 'validateBeforeSave',
591
- 'schema',
592
- ]);
593
- const hasFieldMetadata = Object.keys(mongooseProp).some((k) => {
594
- if (Object.prototype.hasOwnProperty.call(objDef, k))
595
- return false;
596
- if (topLevelOptions.has(k))
597
- return false;
598
- if (k === 'required' && mongooseProp[k] === false)
599
- return false;
600
- return true;
601
- });
602
- result = hasFieldMetadata ? mongooseProp : objDef;
378
+ if (traitSet.has("$ZodCheckLessThan")) {
379
+ mongooseProp.max = checkDef.value;
603
380
  }
604
- callHookSync('schema:object:after', { schema: unwrapped, mongooseProp, objDef, result });
605
- return result;
606
- }
607
- /**
608
- * Handles ZodArray, ZodSet, and ZodTuple conversion.
609
- */
610
- function handleArray(unwrapped, mongooseProp, visited, extractMongooseDef) {
611
- callHookSync('schema:array:before', { schema: unwrapped, mongooseProp, visited });
612
- const element = unwrapped.element ||
613
- unwrapped._def.valueType ||
614
- unwrapped._def.rest ||
615
- unwrapped._def.items?.[0];
616
- const mongoose = getMongoose();
617
- const innerDef = element
618
- ? extractMongooseDef(element, visited)
619
- : mongoose?.Schema.Types.Mixed || 'Mixed';
620
- // If no explicit type override, wrap the inner definition in an array
621
- if (!mongooseProp.type) {
622
- if (innerDef && typeof innerDef === 'object' && innerDef.__isDiscriminatorUnion && mongoose) {
623
- // const baseSchema =
624
- // new mongoose.Schema(innerDef.baseDef, {
625
- // discriminatorKey: innerDef.discriminatorKey,
626
- // _id: false,
627
- // });
628
- const discriminators = {};
629
- for (const [dKey, dDef] of Object.entries(innerDef.discriminators)) {
630
- discriminators[dKey] = new mongoose.Schema(dDef, { _id: false });
631
- }
632
- mongooseProp.type = [
633
- new mongoose.Schema({}, {
634
- discriminatorKey: innerDef.discriminatorKey,
635
- _id: false,
636
- }),
637
- ];
638
- mongooseProp.discriminators = discriminators;
639
- }
640
- else {
641
- const innerType = innerDef.type || innerDef;
642
- mongooseProp.type = [innerType];
643
- // Transfer any metadata from the inner type (like 'ref') to the array definition
644
- if (typeof innerDef === 'object') {
645
- // eslint-disable-next-line sonarjs/no-unused-vars
646
- const { type: _extractedType, ...innerMeta } = innerDef;
647
- Object.assign(mongooseProp, innerMeta);
648
- mongooseProp.type = [innerType]; // Restore type as array
649
- }
650
- }
381
+ if (traitSet.has("$ZodCheckRegex")) {
382
+ mongooseProp.match = checkDef.pattern;
651
383
  }
652
- callHookSync('schema:array:after', { schema: unwrapped, mongooseProp, innerDef });
653
- }
654
- /**
655
- * Handles ZodRecord and ZodMap conversion.
656
- */
657
- function handleRecord(unwrapped, mongooseProp, visited, extractMongooseDef) {
658
- callHookSync('schema:record:before', { schema: unwrapped, mongooseProp, visited });
659
- const type = unwrapped._def?.type;
660
- const isMap = type === 'map';
661
- const valueType = unwrapped.valueType ||
662
- unwrapped.valueSchema ||
663
- unwrapped._def.valueType ||
664
- unwrapped._def.valueSchema ||
665
- unwrapped._def.innerType; // For some Zod versions
666
- let innerDef;
667
- if (!mongooseProp.type || mongooseProp.type === Map || mongooseProp.type === Object) {
668
- // z.record() maps to a POJO (Object/Mixed), while z.map() maps to a Mongoose Map
669
- mongooseProp.type = isMap ? Map : Object;
670
- const finalValueType = valueType || unwrapped.valueSchema || unwrapped._def?.valueSchema;
671
- if (finalValueType) {
672
- innerDef = extractMongooseDef(finalValueType, visited);
673
- mongooseProp.of = innerDef.type || innerDef;
674
- }
384
+ if (traitSet.has("$ZodUUID")) {
385
+ const mongoose2 = globalThis.mongoose || globalThis.__mongoose;
386
+ if (mongoose2 == null ? void 0 : mongoose2.Schema.Types.UUID) {
387
+ mongooseProp.type = mongoose2.Schema.Types.UUID;
388
+ }
675
389
  }
676
- callHookSync('schema:record:after', { schema: unwrapped, mongooseProp, innerDef });
677
- }
678
-
679
- /**
680
- * THE CONVERTER (Safe AST Walker)
681
- * We extract the Zod type and merge it with any registered Mongoose metadata.
682
- */
683
- function extractMongooseDef(schema, visited = new Map(), isField = false, noWrap = false) {
684
- // Only call converter:before at the very beginning of a run
685
- if (visited.size === 0) {
686
- callHookSync('converter:before', { schema: schema, visited });
390
+ if (traitSet.has("$ZodISODateTime") || traitSet.has("$ZodISODate")) {
391
+ mongooseProp.type = Date;
687
392
  }
688
- callHookSync('converter:start', { schema: schema, visited });
689
- const { schema: unwrapped, features } = unwrapZodSchema(schema);
690
- // Pull any explicitly registered Mongoose metadata (including from wrappers)
691
- const meta = mongooseRegistry.get(schema) || {};
692
- const mongooseProp = getMongooseMeta(schema);
693
- callHookSync('converter:unwrapped', {
694
- schema: schema,
695
- unwrapped,
696
- features,
697
- meta: mongooseProp,
698
- mongooseProp: mongooseProp,
699
- });
700
- if (features.isOptional === true && mongooseProp.type && mongooseProp.required !== true) {
701
- mongooseProp.required = false;
393
+ if (traitSet.has("$ZodCheckOverwrite") && typeof checkDef.tx === "function") {
394
+ const txStr = checkDef.tx.toString();
395
+ if (txStr.includes(".trim()")) {
396
+ mongooseProp.trim = true;
397
+ } else if (txStr.includes(".toLowerCase()")) {
398
+ mongooseProp.lowercase = true;
399
+ } else if (txStr.includes(".toUpperCase()")) {
400
+ mongooseProp.uppercase = true;
401
+ }
702
402
  }
703
- if (visited.has(schema)) {
704
- const existing = visited.get(schema);
705
- if (existing === mongooseProp) {
706
- return existing;
707
- }
708
- // console.log('Visited CACHE for', (unwrapped as any)._def.type, existing);
709
- if (Object.keys(meta).length > 0) {
710
- Object.assign(existing, mongooseProp);
403
+ }
404
+ callHookSync("validation:mappers", { checks, mongooseProp });
405
+ }
406
+ function handleObject(unwrapped, mongooseProp, visited, extractMongooseDef2, isField = false) {
407
+ var _a;
408
+ callHookSync("schema:object:before", { schema: unwrapped, mongooseProp, visited });
409
+ const { shape } = unwrapped;
410
+ const objDef = {};
411
+ const placeholder = mongooseProp.type ? mongooseProp : objDef;
412
+ visited.set(unwrapped, placeholder);
413
+ for (const key in shape) {
414
+ if (!Object.prototype.hasOwnProperty.call(shape, key))
415
+ continue;
416
+ if (key === "_id") {
417
+ const idMeta = mongooseRegistry.get(shape[key]) || {};
418
+ const unwrappedId = unwrapZodSchema(shape[key]).schema;
419
+ const unwrappedIdMeta = mongooseRegistry.get(unwrappedId) || {};
420
+ if (idMeta.includeId !== true && unwrappedIdMeta.includeId !== true && mongooseProp.includeId !== true) {
421
+ continue;
422
+ }
423
+ }
424
+ const def = extractMongooseDef2(shape[key], visited);
425
+ if (def && typeof def === "object" && def.__isDiscriminatorUnion) {
426
+ const mongoose2 = getMongoose();
427
+ if (mongoose2) {
428
+ const baseSchema = new mongoose2.Schema(def.baseDef, {
429
+ discriminatorKey: def.discriminatorKey,
430
+ _id: false
431
+ });
432
+ const discriminators = {};
433
+ for (const [dKey, dDef] of Object.entries(def.discriminators)) {
434
+ discriminators[dKey] = new mongoose2.Schema(dDef, { _id: false });
711
435
  }
712
- return existing;
436
+ objDef[key] = {
437
+ type: baseSchema,
438
+ discriminators
439
+ };
440
+ } else {
441
+ objDef[key] = def;
442
+ }
443
+ } else if (typeof def === "object" && def !== null && !Array.isArray(def)) {
444
+ const { includeId, ...cleanDef } = def;
445
+ objDef[key] = cleanDef;
446
+ } else {
447
+ objDef[key] = def;
713
448
  }
714
- visited.set(schema, mongooseProp);
715
- // console.log('Visited set for', (unwrapped as any)._def.type, mongooseProp);
716
- if (features.default !== undefined) {
717
- mongooseProp.default = features.default;
449
+ callHookSync("schema:object:field", { key, schema: shape[key], objDef, visited });
450
+ }
451
+ let result;
452
+ const shouldBeSubSchema = isField && mongooseProp.schema !== false;
453
+ if (shouldBeSubSchema && !mongooseProp.type) {
454
+ const mongoose2 = getMongoose();
455
+ if (mongoose2) {
456
+ const options = typeof mongooseProp.schema === "object" ? mongooseProp.schema : {};
457
+ const { plugins, ...schemaOptions } = options;
458
+ const subSchema = new mongoose2.Schema(objDef, schemaOptions);
459
+ if (plugins && Array.isArray(plugins)) {
460
+ for (const plugin of plugins) {
461
+ subSchema.plugin(plugin);
462
+ }
463
+ }
464
+ mongooseProp.type = subSchema;
718
465
  }
719
- if (features.required === false) {
720
- mongooseProp.required = false;
466
+ }
467
+ if (mongooseProp.type) {
468
+ const mongoose2 = getMongoose();
469
+ const isSchema = mongoose2 && (mongooseProp.type instanceof mongoose2.Schema || ((_a = mongooseProp.type.constructor) == null ? void 0 : _a.name) === "Schema");
470
+ if (!isSchema) {
471
+ Object.assign(mongooseProp, objDef);
721
472
  }
722
- if (features.readOnly === true) {
723
- mongooseProp.readOnly = true;
473
+ result = mongooseProp;
474
+ } else {
475
+ Object.assign(mongooseProp, objDef);
476
+ const topLevelOptions = /* @__PURE__ */ new Set([
477
+ "collection",
478
+ "versionKey",
479
+ "timestamps",
480
+ "discriminatorKey",
481
+ "strict",
482
+ "id",
483
+ "_id",
484
+ "minimize",
485
+ "validateBeforeSave",
486
+ "schema"
487
+ ]);
488
+ const hasFieldMetadata = Object.keys(mongooseProp).some((k) => {
489
+ if (Object.prototype.hasOwnProperty.call(objDef, k))
490
+ return false;
491
+ if (topLevelOptions.has(k))
492
+ return false;
493
+ if (k === "required" && mongooseProp[k] === false)
494
+ return false;
495
+ return true;
496
+ });
497
+ result = hasFieldMetadata ? mongooseProp : objDef;
498
+ }
499
+ callHookSync("schema:object:after", { schema: unwrapped, mongooseProp, objDef, result });
500
+ return result;
501
+ }
502
+ function handleArray(unwrapped, mongooseProp, visited, extractMongooseDef2) {
503
+ var _a;
504
+ callHookSync("schema:array:before", { schema: unwrapped, mongooseProp, visited });
505
+ const element = unwrapped.element || unwrapped._def.valueType || unwrapped._def.rest || ((_a = unwrapped._def.items) == null ? void 0 : _a[0]);
506
+ const mongoose2 = getMongoose();
507
+ const innerDef = element ? extractMongooseDef2(element, visited) : (mongoose2 == null ? void 0 : mongoose2.Schema.Types.Mixed) || "Mixed";
508
+ if (!mongooseProp.type) {
509
+ if (innerDef && typeof innerDef === "object" && innerDef.__isDiscriminatorUnion && mongoose2) {
510
+ const discriminators = {};
511
+ for (const [dKey, dDef] of Object.entries(innerDef.discriminators)) {
512
+ discriminators[dKey] = new mongoose2.Schema(dDef, { _id: false });
513
+ }
514
+ mongooseProp.type = [
515
+ new mongoose2.Schema({}, {
516
+ discriminatorKey: innerDef.discriminatorKey,
517
+ _id: false
518
+ })
519
+ ];
520
+ mongooseProp.discriminators = discriminators;
521
+ } else {
522
+ const innerType = innerDef.type || innerDef;
523
+ mongooseProp.type = [innerType];
524
+ if (typeof innerDef === "object") {
525
+ const { type: _extractedType, ...innerMeta } = innerDef;
526
+ Object.assign(mongooseProp, innerMeta);
527
+ mongooseProp.type = [innerType];
528
+ }
724
529
  }
725
- // Map Zod checks to Mongoose options
726
- mapZodChecksToMongoose(features.checks, mongooseProp);
727
- const def = unwrapped._def;
728
- if (!def) {
729
- callHookSync('converter:after', {
730
- schema: schema,
731
- mongooseProp,
732
- });
733
- return mongooseProp;
530
+ }
531
+ callHookSync("schema:array:after", { schema: unwrapped, mongooseProp, innerDef });
532
+ }
533
+ function handleRecord(unwrapped, mongooseProp, visited, extractMongooseDef2) {
534
+ var _a, _b;
535
+ callHookSync("schema:record:before", { schema: unwrapped, mongooseProp, visited });
536
+ const type = (_a = unwrapped._def) == null ? void 0 : _a.type;
537
+ const isMap = type === "map";
538
+ const valueType = unwrapped.valueType || unwrapped.valueSchema || unwrapped._def.valueType || unwrapped._def.valueSchema || unwrapped._def.innerType;
539
+ let innerDef;
540
+ if (!mongooseProp.type || mongooseProp.type === Map || mongooseProp.type === Object) {
541
+ mongooseProp.type = isMap ? Map : Object;
542
+ const finalValueType = valueType || unwrapped.valueSchema || ((_b = unwrapped._def) == null ? void 0 : _b.valueSchema);
543
+ if (finalValueType) {
544
+ innerDef = extractMongooseDef2(finalValueType, visited);
545
+ mongooseProp.of = innerDef.type || innerDef;
734
546
  }
735
- const { type } = def;
736
- callHookSync('converter:node', {
737
- schema: unwrapped,
738
- mongooseProp,
739
- type,
740
- });
741
- // Handle recursion and specific types via separate handlers
742
- if (type === 'object') {
743
- const wrapperFn = (s, v) => extractMongooseDef(s, v, true);
744
- const result = handleObject(unwrapped, mongooseProp, visited, wrapperFn, isField && !noWrap);
745
- callHookSync('converter:after', {
746
- schema: schema,
747
- mongooseProp: result,
748
- });
749
- if (typeof result === 'object' && result !== null && !Array.isArray(result)) {
750
- delete result.includeId;
751
- }
752
- return result;
547
+ }
548
+ callHookSync("schema:record:after", { schema: unwrapped, mongooseProp, innerDef });
549
+ }
550
+ function extractMongooseDef(schema, visited = /* @__PURE__ */ new Map(), isField = false, noWrap = false) {
551
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
552
+ if (visited.size === 0) {
553
+ callHookSync("converter:before", { schema, visited });
554
+ }
555
+ callHookSync("converter:start", { schema, visited });
556
+ const { schema: unwrapped, features } = unwrapZodSchema(schema);
557
+ const meta = mongooseRegistry.get(schema) || {};
558
+ const mongooseProp = getMongooseMeta(schema);
559
+ callHookSync("converter:unwrapped", {
560
+ schema,
561
+ unwrapped,
562
+ features,
563
+ meta: mongooseProp,
564
+ mongooseProp
565
+ });
566
+ if (features.isOptional === true && mongooseProp.type && mongooseProp.required !== true) {
567
+ mongooseProp.required = false;
568
+ }
569
+ if (visited.has(schema)) {
570
+ const existing = visited.get(schema);
571
+ if (existing === mongooseProp) {
572
+ return existing;
753
573
  }
754
- if (type === 'array' || type === 'set' || type === 'tuple') {
755
- handleArray(unwrapped, mongooseProp, visited, (s, v) => extractMongooseDef(s, v, true));
574
+ if (Object.keys(meta).length > 0) {
575
+ Object.assign(existing, mongooseProp);
756
576
  }
757
- if (type === 'record' || type === 'map') {
758
- handleRecord(unwrapped, mongooseProp, visited, (s, v) => extractMongooseDef(s, v, true));
577
+ return existing;
578
+ }
579
+ visited.set(schema, mongooseProp);
580
+ if (features.default !== void 0) {
581
+ mongooseProp.default = features.default;
582
+ }
583
+ if (features.required === false) {
584
+ mongooseProp.required = false;
585
+ }
586
+ if (features.readOnly === true) {
587
+ mongooseProp.readOnly = true;
588
+ }
589
+ mapZodChecksToMongoose(features.checks, mongooseProp);
590
+ const def = unwrapped._def;
591
+ if (!def) {
592
+ callHookSync("converter:after", {
593
+ schema,
594
+ mongooseProp
595
+ });
596
+ return mongooseProp;
597
+ }
598
+ const { type } = def;
599
+ callHookSync("converter:node", {
600
+ schema: unwrapped,
601
+ mongooseProp,
602
+ type
603
+ });
604
+ if (type === "object") {
605
+ const wrapperFn = (s, v) => extractMongooseDef(s, v, true);
606
+ const result = handleObject(unwrapped, mongooseProp, visited, wrapperFn, isField && !noWrap);
607
+ callHookSync("converter:after", {
608
+ schema,
609
+ mongooseProp: result
610
+ });
611
+ if (typeof result === "object" && result !== null && !Array.isArray(result)) {
612
+ delete result.includeId;
759
613
  }
760
- // Handle Intersections
761
- if (type === 'intersection') {
762
- const left = extractMongooseDef(unwrapped._def.left, visited, isField, true);
763
- const right = extractMongooseDef(unwrapped._def.right, visited, isField, true);
764
- if (typeof left === 'object' && typeof right === 'object') {
765
- Object.assign(mongooseProp, left, right);
766
- if (isField && !noWrap && mongooseProp.schema !== false && !mongooseProp.type) {
767
- const mongoose = getMongoose();
768
- if (mongoose) {
769
- const options = typeof mongooseProp.schema === 'object' ? mongooseProp.schema : {};
770
- const { plugins, ...schemaOptions } = options;
771
- const definition = { ...mongooseProp };
772
- // Remove metadata fields that shouldn't be in the schema definition if they are top-level
773
- delete definition.schema;
774
- const subSchema = new mongoose.Schema(definition, schemaOptions);
775
- if (plugins && Array.isArray(plugins)) {
776
- for (const plugin of plugins) {
777
- subSchema.plugin(plugin);
778
- }
779
- }
780
- mongooseProp.type = subSchema;
781
- // Clear other fields since they are now in subSchema
782
- for (const key of Object.keys(mongooseProp)) {
783
- if (key !== 'type')
784
- delete mongooseProp[key];
785
- }
786
- }
614
+ return result;
615
+ }
616
+ if (type === "array" || type === "set" || type === "tuple") {
617
+ handleArray(unwrapped, mongooseProp, visited, (s, v) => extractMongooseDef(s, v, true));
618
+ }
619
+ if (type === "record" || type === "map") {
620
+ handleRecord(unwrapped, mongooseProp, visited, (s, v) => extractMongooseDef(s, v, true));
621
+ }
622
+ if (type === "intersection") {
623
+ const left = extractMongooseDef(unwrapped._def.left, visited, isField, true);
624
+ const right = extractMongooseDef(unwrapped._def.right, visited, isField, true);
625
+ if (typeof left === "object" && typeof right === "object") {
626
+ Object.assign(mongooseProp, left, right);
627
+ if (isField && !noWrap && mongooseProp.schema !== false && !mongooseProp.type) {
628
+ const mongoose2 = getMongoose();
629
+ if (mongoose2) {
630
+ const options = typeof mongooseProp.schema === "object" ? mongooseProp.schema : {};
631
+ const { plugins, ...schemaOptions } = options;
632
+ const definition = { ...mongooseProp };
633
+ delete definition.schema;
634
+ const subSchema = new mongoose2.Schema(definition, schemaOptions);
635
+ if (plugins && Array.isArray(plugins)) {
636
+ for (const plugin of plugins) {
637
+ subSchema.plugin(plugin);
787
638
  }
639
+ }
640
+ mongooseProp.type = subSchema;
641
+ for (const key of Object.keys(mongooseProp)) {
642
+ if (key !== "type")
643
+ delete mongooseProp[key];
644
+ }
788
645
  }
789
- else if (!mongooseProp.type) {
790
- mongooseProp.type = getMongoose()?.Schema.Types.Mixed || 'Mixed';
791
- }
646
+ }
647
+ } else if (!mongooseProp.type) {
648
+ mongooseProp.type = ((_a = getMongoose()) == null ? void 0 : _a.Schema.Types.Mixed) || "Mixed";
792
649
  }
793
- if ((type === 'union' ||
794
- type === 'discriminatedunion' ||
795
- type === 'discriminated_union' ||
796
- type === 'xor') &&
797
- !mongooseProp.type) {
798
- const mongoose = getMongoose();
799
- const options = unwrapped.options || unwrapped._def.options;
800
- const discriminatorKey = unwrapped._def.discriminator;
801
- const unionCtx = {
802
- isSimpleUnion: false,
803
- isObjectUnion: false,
804
- isXor: type === 'xor' ||
805
- ((unwrapped._def?.inclusive === false ||
806
- schema._def?.inclusive === false) &&
807
- !discriminatorKey &&
808
- !schema._def?.discriminator),
809
- };
810
- if (Array.isArray(options) && options.length > 0) {
811
- unionCtx.isSimpleUnion = options.every((opt) => {
812
- const { type } = unwrapZodSchema(opt).schema._def;
813
- return ['string', 'number', 'boolean', 'date', 'bigint', 'literal'].includes(type);
814
- });
815
- unionCtx.isObjectUnion = options.every((opt) => {
816
- const { type } = unwrapZodSchema(opt).schema._def;
817
- return type === 'object';
818
- });
819
- }
820
- callHookSync('schema:union:before', { schema: unwrapped, mongooseProp, ctx: unionCtx });
821
- if (discriminatorKey && unionCtx.isObjectUnion) {
822
- const discriminators = {};
823
- const allOptionDefs = [];
824
- for (const option of options) {
825
- const { schema: unwrappedOpt } = unwrapZodSchema(option);
826
- const { shape } = unwrappedOpt._def;
827
- const discriminatorProp = shape[discriminatorKey];
828
- // Support both ZodLiteral and ZodOptional/ZodDefault/ZodNullable wrapped literals
829
- const { schema: unwrappedDisc } = unwrapZodSchema(discriminatorProp);
830
- const discriminatorValue = unwrappedDisc._def.value ?? unwrappedDisc._def.values?.[0];
831
- // Use a fresh Map for each option to avoid cross-contamination of visited nodes
832
- const optionDef = extractMongooseDef(option, new Map(), true, true);
833
- if (optionDef && typeof optionDef === 'object' && !Array.isArray(optionDef)) {
834
- const cleanOptionDef = { ...optionDef };
835
- delete cleanOptionDef[discriminatorKey];
836
- discriminators[discriminatorValue] = cleanOptionDef;
837
- allOptionDefs.push(cleanOptionDef);
838
- }
839
- }
840
- // Identify common fields present in ALL options to move to baseDef
841
- const baseDef = {};
842
- if (allOptionDefs.length > 0) {
843
- const firstOption = allOptionDefs[0];
844
- for (const key of Object.keys(firstOption)) {
845
- const isCommon = allOptionDefs.every((def) => {
846
- if (!(key in def))
847
- return false;
848
- // Simple check for equality of definitions (can be improved)
849
- return JSON.stringify(def[key]) === JSON.stringify(firstOption[key]);
850
- });
851
- if (isCommon) {
852
- baseDef[key] = firstOption[key];
853
- // Remove from discriminators to avoid duplication
854
- for (const def of allOptionDefs) {
855
- delete def[key];
856
- }
857
- }
858
- }
859
- }
860
- const result = {
861
- __isDiscriminatorUnion: true,
862
- discriminatorKey,
863
- discriminators,
864
- baseDef,
865
- validate: {
866
- validator(_v) {
867
- try {
868
- // Ensure we include the discriminator key in the object being validated
869
- const mongoose = getMongoose();
870
- const doc = mongoose && this instanceof mongoose.Document ? this.toObject() : this || {};
871
- schema.parse(doc);
872
- return true;
873
- }
874
- catch (err) {
875
- const message = err?.errors?.[0]?.message || err.message;
876
- if (this && typeof this.invalidate === 'function') {
877
- this.invalidate(discriminatorKey, `Zod validation failed: ${message}`);
878
- }
879
- return false;
880
- }
881
- },
882
- message: (props) => `Validation failed for ${props.path}`,
883
- },
884
- };
885
- // If this is wrapped in a meta object, ensure we return the result properly
886
- if (mongooseProp && typeof mongooseProp === 'object' && !Array.isArray(mongooseProp)) {
887
- Object.assign(mongooseProp, result);
888
- callHookSync('schema:union:after', {
889
- schema: unwrapped,
890
- mongooseProp,
891
- ctx: unionCtx,
892
- });
893
- return mongooseProp;
894
- }
895
- callHookSync('schema:union:after', {
896
- schema: unwrapped,
897
- mongooseProp: result,
898
- ctx: unionCtx,
899
- });
900
- return result;
901
- }
902
- if (getMongoose()?.Schema.Types.Union &&
903
- unionCtx.isSimpleUnion &&
904
- options.length > 0 &&
905
- !unionCtx.isXor) {
906
- mongooseProp.type = mongoose.Schema.Types.Union;
907
- mongooseProp.of = options.map((opt) => {
908
- const def = extractMongooseDef(opt, visited, true, true);
909
- return def.type || def;
910
- });
650
+ }
651
+ if ((type === "union" || type === "discriminatedunion" || type === "discriminated_union" || type === "xor") && !mongooseProp.type) {
652
+ const mongoose2 = getMongoose();
653
+ const options = unwrapped.options || unwrapped._def.options;
654
+ const discriminatorKey = unwrapped._def.discriminator;
655
+ const unionCtx = {
656
+ isSimpleUnion: false,
657
+ isObjectUnion: false,
658
+ isXor: type === "xor" || (((_b = unwrapped._def) == null ? void 0 : _b.inclusive) === false || ((_c = schema._def) == null ? void 0 : _c.inclusive) === false) && !discriminatorKey && !((_d = schema._def) == null ? void 0 : _d.discriminator)
659
+ };
660
+ if (Array.isArray(options) && options.length > 0) {
661
+ unionCtx.isSimpleUnion = options.every((opt) => {
662
+ const { type: type2 } = unwrapZodSchema(opt).schema._def;
663
+ return ["string", "number", "boolean", "date", "bigint", "literal"].includes(type2);
664
+ });
665
+ unionCtx.isObjectUnion = options.every((opt) => {
666
+ const { type: type2 } = unwrapZodSchema(opt).schema._def;
667
+ return type2 === "object";
668
+ });
669
+ }
670
+ callHookSync("schema:union:before", { schema: unwrapped, mongooseProp, ctx: unionCtx });
671
+ if (discriminatorKey && unionCtx.isObjectUnion) {
672
+ const discriminators = {};
673
+ const allOptionDefs = [];
674
+ for (const option of options) {
675
+ const { schema: unwrappedOpt } = unwrapZodSchema(option);
676
+ const { shape } = unwrappedOpt._def;
677
+ const discriminatorProp = shape[discriminatorKey];
678
+ const { schema: unwrappedDisc } = unwrapZodSchema(discriminatorProp);
679
+ const discriminatorValue = (_f = unwrappedDisc._def.value) != null ? _f : (_e = unwrappedDisc._def.values) == null ? void 0 : _e[0];
680
+ const optionDef = extractMongooseDef(option, /* @__PURE__ */ new Map(), true, true);
681
+ if (optionDef && typeof optionDef === "object" && !Array.isArray(optionDef)) {
682
+ const cleanOptionDef = { ...optionDef };
683
+ delete cleanOptionDef[discriminatorKey];
684
+ discriminators[discriminatorValue] = cleanOptionDef;
685
+ allOptionDefs.push(cleanOptionDef);
911
686
  }
912
- else if (unionCtx.isObjectUnion && options.length > 0) {
913
- // Merge all object properties into a single schema object
914
- const mergedDef = {};
915
- for (const opt of options) {
916
- const def = extractMongooseDef(opt, new Map(), true, true);
917
- if (typeof def === 'object' && def !== null) {
918
- for (const [key, prop] of Object.entries(def)) {
919
- if (typeof prop === 'object' && prop !== null && !Array.isArray(prop)) {
920
- prop.required = false;
921
- }
922
- if (mergedDef[key] &&
923
- typeof mergedDef[key] === 'object' &&
924
- typeof prop === 'object' &&
925
- !Array.isArray(mergedDef[key]) &&
926
- !Array.isArray(prop)) {
927
- const existingType = mergedDef[key].type ||
928
- mergedDef[key].instance ||
929
- (typeof mergedDef[key] === 'function' ? mergedDef[key] : null);
930
- const newType = prop.type ||
931
- prop.instance ||
932
- (typeof prop === 'function' ? prop : null);
933
- const isMixed = (t) => !t ||
934
- t === 'Mixed' ||
935
- t === 'SchemaMixed' ||
936
- t?.name === 'Mixed' ||
937
- t?.instance === 'Mixed' ||
938
- t?.name === 'SchemaMixed' ||
939
- t?.instance === 'SchemaMixed' ||
940
- (getMongoose()?.Schema.Types.Mixed &&
941
- (t === getMongoose()?.Schema.Types.Mixed ||
942
- t?.instance === 'Mixed' ||
943
- t?.instance === 'SchemaMixed'));
944
- if (isMixed(existingType) && !isMixed(newType)) {
945
- mergedDef[key] = prop;
946
- }
947
- else if (!isMixed(existingType) && isMixed(newType)) ;
948
- else {
949
- Object.assign(mergedDef[key], prop);
950
- }
951
- }
952
- else if (!mergedDef[key] ||
953
- typeof mergedDef[key] !== 'object' ||
954
- Array.isArray(mergedDef[key])) {
955
- mergedDef[key] = prop;
956
- }
957
- }
958
- }
959
- }
960
- if (isField && unionCtx.isXor) {
961
- // For nested XOR, always use Mixed with validator to ensure mutual exclusivity
962
- mongooseProp.type = mongoose?.Schema.Types.Mixed || 'Mixed';
963
- mongooseProp.validate = {
964
- validator(v) {
965
- try {
966
- schema.parse(v);
967
- return true;
968
- }
969
- catch {
970
- return false;
971
- }
972
- },
973
- message: 'XOR validation failed',
974
- };
975
- }
976
- else {
977
- // For root or other object unions, merge properties
978
- if (!mongooseProp.type ||
979
- mongooseProp.type === (getMongoose()?.Schema.Types.Mixed || 'Mixed')) {
980
- delete mongooseProp.type;
981
- }
982
- Object.assign(mongooseProp, mergedDef);
983
- // If the object contains a 'type' property, Mongoose might misinterpret it as a field definition.
984
- // We can hint that it's a nested object by using a Schema if 'type' is present along with other fields.
985
- if (isField &&
986
- Object.prototype.hasOwnProperty.call(mongooseProp, 'type') &&
987
- Object.keys(mongooseProp).length > 1) {
988
- const mongooseInstance = getMongoose();
989
- if (mongooseInstance) {
990
- mongooseProp.type = new mongooseInstance.Schema(mongooseProp, { _id: false });
991
- for (const key of Object.keys(mongooseProp)) {
992
- if (key !== 'type')
993
- delete mongooseProp[key];
994
- }
995
- }
996
- }
687
+ }
688
+ const baseDef = {};
689
+ if (allOptionDefs.length > 0) {
690
+ const firstOption = allOptionDefs[0];
691
+ for (const key of Object.keys(firstOption)) {
692
+ const isCommon = allOptionDefs.every((def2) => {
693
+ if (!(key in def2))
694
+ return false;
695
+ return JSON.stringify(def2[key]) === JSON.stringify(firstOption[key]);
696
+ });
697
+ if (isCommon) {
698
+ baseDef[key] = firstOption[key];
699
+ for (const def2 of allOptionDefs) {
700
+ delete def2[key];
997
701
  }
702
+ }
998
703
  }
999
- else {
1000
- mongooseProp.type = mongoose?.Schema.Types.Mixed || 'Mixed';
1001
- if (isField &&
1002
- (type === 'xor' ||
1003
- type === 'discriminated_union' ||
1004
- type === 'discriminatedunion' ||
1005
- type === 'union') &&
1006
- !mongooseProp.ref && // Skip Zod validation for populated fields
1007
- !Array.isArray(mongooseProp.type) && // Skip Zod validation for arrays
1008
- mongooseProp.type !== Map && // Skip Zod validation for maps
1009
- !mongooseProp.of // Skip Zod validation for collections
1010
- ) {
1011
- mongooseProp.validate = {
1012
- validator(v) {
1013
- try {
1014
- schema.parse(v);
1015
- return true;
1016
- }
1017
- catch (err) {
1018
- return false;
1019
- }
1020
- },
1021
- message: (props) => {
1022
- if (unionCtx.isXor)
1023
- return 'XOR validation failed';
1024
- try {
1025
- schema.parse(props.value);
1026
- }
1027
- catch (err) {
1028
- return `Union validation failed: ${err.message}`;
1029
- }
1030
- return 'Union validation failed';
1031
- },
1032
- };
704
+ }
705
+ const result = {
706
+ __isDiscriminatorUnion: true,
707
+ discriminatorKey,
708
+ discriminators,
709
+ baseDef,
710
+ validate: {
711
+ validator(_v) {
712
+ var _a2, _b2;
713
+ try {
714
+ const mongoose3 = getMongoose();
715
+ const doc = mongoose3 && this instanceof mongoose3.Document ? this.toObject() : this || {};
716
+ schema.parse(doc);
717
+ return true;
718
+ } catch (err) {
719
+ const message = ((_b2 = (_a2 = err == null ? void 0 : err.errors) == null ? void 0 : _a2[0]) == null ? void 0 : _b2.message) || err.message;
720
+ if (this && typeof this.invalidate === "function") {
721
+ this.invalidate(discriminatorKey, `Zod validation failed: ${message}`);
722
+ }
723
+ return false;
1033
724
  }
725
+ },
726
+ message: (props) => `Validation failed for ${props.path}`
1034
727
  }
1035
- callHookSync('schema:union:after', {
1036
- schema: unwrapped,
1037
- mongooseProp,
1038
- ctx: unionCtx,
728
+ };
729
+ if (mongooseProp && typeof mongooseProp === "object" && !Array.isArray(mongooseProp)) {
730
+ Object.assign(mongooseProp, result);
731
+ callHookSync("schema:union:after", {
732
+ schema: unwrapped,
733
+ mongooseProp,
734
+ ctx: unionCtx
1039
735
  });
736
+ return mongooseProp;
737
+ }
738
+ callHookSync("schema:union:after", {
739
+ schema: unwrapped,
740
+ mongooseProp: result,
741
+ ctx: unionCtx
742
+ });
743
+ return result;
1040
744
  }
1041
- if (type === 'literal' && !mongooseProp.type) {
1042
- mongooseProp.type = getMongoose()?.Schema.Types.Mixed || 'Mixed';
1043
- }
1044
- // Handle Primitives
1045
- switch (type) {
1046
- case 'string':
1047
- case 'number':
1048
- case 'boolean':
1049
- case 'date':
1050
- case 'bigint':
1051
- case 'stringbool':
1052
- case 'boolstring':
1053
- case 'booleanstring': {
1054
- if (!mongooseProp.type) {
1055
- if (type === 'bigint') {
1056
- mongooseProp.type = typeof BigInt === 'undefined' ? Number : BigInt;
1057
- }
1058
- else {
1059
- const typeMap = {
1060
- string: String,
1061
- number: Number,
1062
- boolean: Boolean,
1063
- date: Date,
1064
- stringbool: Boolean,
1065
- boolstring: Boolean,
1066
- booleanstring: Boolean,
1067
- };
1068
- mongooseProp.type = typeMap[type];
1069
- // Clever inference: If a transform occurred (which we know if the Zod type
1070
- // is different from the default value type), prefer the default's type.
1071
- if (mongooseProp.default !== undefined) {
1072
- const defaultType = typeof mongooseProp.default;
1073
- if (defaultType === 'boolean' && type !== 'boolean') {
1074
- mongooseProp.type = Boolean;
1075
- }
1076
- else if (defaultType === 'number' && type !== 'number') {
1077
- mongooseProp.type = Number;
1078
- }
1079
- else if (defaultType === 'string' && type !== 'string') {
1080
- mongooseProp.type = String;
1081
- }
1082
- else if (mongooseProp.default instanceof Date && type !== 'date') {
1083
- mongooseProp.type = Date;
1084
- }
1085
- }
1086
- // Even cleverer: Check transformations for clues (e.g., stringbool, boolstring)
1087
- if (mongooseProp.type === String && features.transformations) {
1088
- for (const tx of features.transformations) {
1089
- const txStr = tx.transform?.toString() || tx.toString();
1090
- if (txStr.includes('stringbool') || txStr.includes('boolstring') || txStr.includes('booleanstring')) {
1091
- mongooseProp.type = Boolean;
1092
- break;
1093
- }
1094
- if (txStr.includes('=== "true"') || txStr.includes('=== \'true\'')) {
1095
- mongooseProp.type = Boolean;
1096
- break;
1097
- }
1098
- }
1099
- }
1100
- }
745
+ if (((_g = getMongoose()) == null ? void 0 : _g.Schema.Types.Union) && unionCtx.isSimpleUnion && options.length > 0 && !unionCtx.isXor) {
746
+ mongooseProp.type = mongoose2.Schema.Types.Union;
747
+ mongooseProp.of = options.map((opt) => {
748
+ const def2 = extractMongooseDef(opt, visited, true, true);
749
+ return def2.type || def2;
750
+ });
751
+ } else if (unionCtx.isObjectUnion && options.length > 0) {
752
+ const mergedDef = {};
753
+ for (const opt of options) {
754
+ const def2 = extractMongooseDef(opt, /* @__PURE__ */ new Map(), true, true);
755
+ if (typeof def2 === "object" && def2 !== null) {
756
+ for (const [key, prop] of Object.entries(def2)) {
757
+ if (typeof prop === "object" && prop !== null && !Array.isArray(prop)) {
758
+ prop.required = false;
1101
759
  }
1102
- if (mongooseProp.required !== false)
1103
- mongooseProp.required = true;
1104
- break;
1105
- }
1106
- case 'enum':
1107
- case 'nativeenum':
1108
- case 'native_enum': {
1109
- if (!mongooseProp.type)
1110
- mongooseProp.type = String;
1111
- mongooseProp.enum =
1112
- type === 'enum'
1113
- ? unwrapped.options || def.values
1114
- : Object.values(unwrapped.enum || def.values);
1115
- if (mongooseProp.required !== false)
1116
- mongooseProp.required = true;
1117
- break;
760
+ if (mergedDef[key] && typeof mergedDef[key] === "object" && typeof prop === "object" && !Array.isArray(mergedDef[key]) && !Array.isArray(prop)) {
761
+ const existingType = mergedDef[key].type || mergedDef[key].instance || (typeof mergedDef[key] === "function" ? mergedDef[key] : null);
762
+ const newType = prop.type || prop.instance || (typeof prop === "function" ? prop : null);
763
+ const isMixed = (t) => {
764
+ var _a2, _b2;
765
+ return !t || t === "Mixed" || t === "SchemaMixed" || (t == null ? void 0 : t.name) === "Mixed" || (t == null ? void 0 : t.instance) === "Mixed" || (t == null ? void 0 : t.name) === "SchemaMixed" || (t == null ? void 0 : t.instance) === "SchemaMixed" || ((_a2 = getMongoose()) == null ? void 0 : _a2.Schema.Types.Mixed) && (t === ((_b2 = getMongoose()) == null ? void 0 : _b2.Schema.Types.Mixed) || (t == null ? void 0 : t.instance) === "Mixed" || (t == null ? void 0 : t.instance) === "SchemaMixed");
766
+ };
767
+ if (isMixed(existingType) && !isMixed(newType)) {
768
+ mergedDef[key] = prop;
769
+ } else if (!isMixed(existingType) && isMixed(newType)) ;
770
+ else {
771
+ Object.assign(mergedDef[key], prop);
772
+ }
773
+ } else if (!mergedDef[key] || typeof mergedDef[key] !== "object" || Array.isArray(mergedDef[key])) {
774
+ mergedDef[key] = prop;
775
+ }
776
+ }
1118
777
  }
1119
- // Do nothing
1120
- }
1121
- // Handle Specialized Types (Buffer, ObjectId)
1122
- const mongooseInstance = getMongoose();
1123
- if (type === 'any' || type === 'unknown' || type === 'custom') {
1124
- const cls = def.cls || unwrapped.cls;
1125
- if (cls === Buffer || (typeof Uint8Array !== 'undefined' && cls === Uint8Array)) {
1126
- if (!mongooseProp.type)
1127
- mongooseProp.type = mongooseInstance?.Schema.Types.Buffer || 'Buffer';
778
+ }
779
+ if (isField && unionCtx.isXor) {
780
+ mongooseProp.type = (mongoose2 == null ? void 0 : mongoose2.Schema.Types.Mixed) || "Mixed";
781
+ mongooseProp.validate = {
782
+ validator(v) {
783
+ try {
784
+ schema.parse(v);
785
+ return true;
786
+ } catch {
787
+ return false;
788
+ }
789
+ },
790
+ message: "XOR validation failed"
791
+ };
792
+ } else {
793
+ if (!mongooseProp.type || mongooseProp.type === (((_h = getMongoose()) == null ? void 0 : _h.Schema.Types.Mixed) || "Mixed")) {
794
+ delete mongooseProp.type;
1128
795
  }
1129
- else if ((cls?.name === 'ObjectId' || (mongooseInstance && cls === mongooseInstance.Types.ObjectId)) &&
1130
- !mongooseProp.type) {
1131
- mongooseProp.type = mongooseInstance?.Schema.Types.ObjectId || 'ObjectId';
796
+ Object.assign(mongooseProp, mergedDef);
797
+ if (isField && Object.prototype.hasOwnProperty.call(mongooseProp, "type") && Object.keys(mongooseProp).length > 1) {
798
+ const mongooseInstance3 = getMongoose();
799
+ if (mongooseInstance3) {
800
+ mongooseProp.type = new mongooseInstance3.Schema(mongooseProp, { _id: false });
801
+ for (const key of Object.keys(mongooseProp)) {
802
+ if (key !== "type")
803
+ delete mongooseProp[key];
804
+ }
805
+ }
1132
806
  }
807
+ }
808
+ } else {
809
+ mongooseProp.type = (mongoose2 == null ? void 0 : mongoose2.Schema.Types.Mixed) || "Mixed";
810
+ if (isField && (type === "xor" || type === "discriminated_union" || type === "discriminatedunion" || type === "union") && !mongooseProp.ref && // Skip Zod validation for populated fields
811
+ !Array.isArray(mongooseProp.type) && // Skip Zod validation for arrays
812
+ mongooseProp.type !== Map && // Skip Zod validation for maps
813
+ !mongooseProp.of) {
814
+ mongooseProp.validate = {
815
+ validator(v) {
816
+ try {
817
+ schema.parse(v);
818
+ return true;
819
+ } catch (err) {
820
+ return false;
821
+ }
822
+ },
823
+ message: (props) => {
824
+ if (unionCtx.isXor)
825
+ return "XOR validation failed";
826
+ try {
827
+ schema.parse(props.value);
828
+ } catch (err) {
829
+ return `Union validation failed: ${err.message}`;
830
+ }
831
+ return "Union validation failed";
832
+ }
833
+ };
834
+ }
1133
835
  }
1134
- // Handle Lazy (Recursion Support)
1135
- if (type === 'lazy') {
1136
- const inner = def.getter();
1137
- const result = extractMongooseDef(inner, visited, isField);
1138
- if (Object.keys(meta).length > 0 && result !== mongooseProp) {
1139
- if (typeof result === 'object' && !Array.isArray(result)) {
1140
- Object.assign(mongooseProp, result);
836
+ callHookSync("schema:union:after", {
837
+ schema: unwrapped,
838
+ mongooseProp,
839
+ ctx: unionCtx
840
+ });
841
+ }
842
+ if (type === "literal" && !mongooseProp.type) {
843
+ mongooseProp.type = ((_i = getMongoose()) == null ? void 0 : _i.Schema.Types.Mixed) || "Mixed";
844
+ }
845
+ switch (type) {
846
+ case "string":
847
+ case "number":
848
+ case "boolean":
849
+ case "date":
850
+ case "bigint":
851
+ case "stringbool":
852
+ case "boolstring":
853
+ case "booleanstring": {
854
+ if (!mongooseProp.type) {
855
+ if (type === "bigint") {
856
+ mongooseProp.type = typeof BigInt === "undefined" ? Number : BigInt;
857
+ } else {
858
+ const typeMap = {
859
+ string: String,
860
+ number: Number,
861
+ boolean: Boolean,
862
+ date: Date,
863
+ stringbool: Boolean,
864
+ boolstring: Boolean,
865
+ booleanstring: Boolean
866
+ };
867
+ mongooseProp.type = typeMap[type];
868
+ if (mongooseProp.default !== void 0) {
869
+ const defaultType = typeof mongooseProp.default;
870
+ if (defaultType === "boolean" && type !== "boolean") {
871
+ mongooseProp.type = Boolean;
872
+ } else if (defaultType === "number" && type !== "number") {
873
+ mongooseProp.type = Number;
874
+ } else if (defaultType === "string" && type !== "string") {
875
+ mongooseProp.type = String;
876
+ } else if (mongooseProp.default instanceof Date && type !== "date") {
877
+ mongooseProp.type = Date;
1141
878
  }
1142
- else {
1143
- mongooseProp.type = result.type || result;
879
+ }
880
+ if (mongooseProp.type === String && features.transformations) {
881
+ for (const tx of features.transformations) {
882
+ const txStr = ((_j = tx.transform) == null ? void 0 : _j.toString()) || tx.toString();
883
+ if (txStr.includes("stringbool") || txStr.includes("boolstring") || txStr.includes("booleanstring")) {
884
+ mongooseProp.type = Boolean;
885
+ break;
886
+ }
887
+ if (txStr.includes('=== "true"') || txStr.includes("=== 'true'")) {
888
+ mongooseProp.type = Boolean;
889
+ break;
890
+ }
1144
891
  }
1145
- return mongooseProp;
892
+ }
1146
893
  }
1147
- return result;
894
+ }
895
+ if (mongooseProp.required !== false)
896
+ mongooseProp.required = true;
897
+ break;
1148
898
  }
1149
- // Fallback for z.any() or unhandled types
1150
- if (!mongooseProp.type && type !== 'object') {
1151
- mongooseProp.type = getMongoose()?.Schema.Types.Mixed || 'Mixed';
899
+ case "enum":
900
+ case "nativeenum":
901
+ case "native_enum": {
902
+ if (!mongooseProp.type)
903
+ mongooseProp.type = String;
904
+ mongooseProp.enum = type === "enum" ? unwrapped.options || def.values : Object.values(unwrapped.enum || def.values);
905
+ if (mongooseProp.required !== false)
906
+ mongooseProp.required = true;
907
+ break;
1152
908
  }
1153
- callHookSync('converter:after', {
1154
- schema: schema,
1155
- mongooseProp,
1156
- });
1157
- if (typeof mongooseProp === 'object' && mongooseProp !== null && !Array.isArray(mongooseProp)) {
1158
- delete mongooseProp.includeId;
909
+ }
910
+ const mongooseInstance2 = getMongoose();
911
+ if (type === "any" || type === "unknown" || type === "custom") {
912
+ const cls = def.cls || unwrapped.cls;
913
+ if (cls === Buffer || typeof Uint8Array !== "undefined" && cls === Uint8Array) {
914
+ if (!mongooseProp.type)
915
+ mongooseProp.type = (mongooseInstance2 == null ? void 0 : mongooseInstance2.Schema.Types.Buffer) || "Buffer";
916
+ } else if (((cls == null ? void 0 : cls.name) === "ObjectId" || mongooseInstance2 && cls === mongooseInstance2.Types.ObjectId) && !mongooseProp.type) {
917
+ mongooseProp.type = (mongooseInstance2 == null ? void 0 : mongooseInstance2.Schema.Types.ObjectId) || "ObjectId";
1159
918
  }
1160
- return mongooseProp;
919
+ }
920
+ if (type === "lazy") {
921
+ const inner = def.getter();
922
+ const result = extractMongooseDef(inner, visited, isField);
923
+ if (Object.keys(meta).length > 0 && result !== mongooseProp) {
924
+ if (typeof result === "object" && !Array.isArray(result)) {
925
+ Object.assign(mongooseProp, result);
926
+ } else {
927
+ mongooseProp.type = result.type || result;
928
+ }
929
+ return mongooseProp;
930
+ }
931
+ return result;
932
+ }
933
+ if (!mongooseProp.type && type !== "object") {
934
+ mongooseProp.type = ((_k = getMongoose()) == null ? void 0 : _k.Schema.Types.Mixed) || "Mixed";
935
+ }
936
+ callHookSync("converter:after", {
937
+ schema,
938
+ mongooseProp
939
+ });
940
+ if (typeof mongooseProp === "object" && mongooseProp !== null && !Array.isArray(mongooseProp)) {
941
+ delete mongooseProp.includeId;
942
+ }
943
+ return mongooseProp;
1161
944
  }
1162
-
1163
- /**
1164
- * Converts a Zod schema to a Mongoose Schema instance.
1165
- */
1166
945
  function toMongooseSchema(schema, options) {
1167
- const { schema: unwrapped } = unwrapZodSchema(schema);
1168
- const meta = mongooseRegistry.get(schema) ||
1169
- mongooseRegistry.get(unwrapped) ||
1170
- schema.meta?.() ||
1171
- unwrapped.meta?.() ||
1172
- {};
1173
- const { plugins, ...schemaOptions } = options || {};
1174
- const mergedOptions = {
1175
- // Also merge other schema options from meta if they exist
1176
- ...(meta.collection ? { collection: meta.collection } : {}),
1177
- // eslint-disable-next-line unicorn/no-negated-condition
1178
- ...(meta.strict !== undefined ? { strict: meta.strict } : {}),
1179
- // eslint-disable-next-line unicorn/no-negated-condition
1180
- ...(meta.minimize !== undefined ? { minimize: meta.minimize } : {}),
1181
- // eslint-disable-next-line unicorn/no-negated-condition
1182
- ...(meta.validateBeforeSave !== undefined ? { validateBeforeSave: meta.validateBeforeSave } : {}),
1183
- // eslint-disable-next-line unicorn/no-negated-condition
1184
- ...(meta.versionKey !== undefined ? { versionKey: meta.versionKey } : {}),
1185
- ...(meta.id === undefined ? {} : { id: meta.id }),
1186
- ...(meta._id === undefined ? {} : { _id: meta._id }),
1187
- ...(meta.timestamps ? { timestamps: meta.timestamps } : {}),
1188
- ...(meta.discriminatorKey ? { discriminatorKey: meta.discriminatorKey } : {}),
1189
- ...schemaOptions,
1190
- };
1191
- let definition = extractMongooseDef(schema, new Map(), false);
1192
- const mongoose = getMongoose();
1193
- if (!mongoose) {
1194
- throw new Error('Mongoose must be installed to use toMongooseSchema. If you are in an ESM environment, ensure mongoose is loaded.');
946
+ var _a, _b;
947
+ const { schema: unwrapped } = unwrapZodSchema(schema);
948
+ const meta = mongooseRegistry.get(schema) || mongooseRegistry.get(unwrapped) || ((_a = schema.meta) == null ? void 0 : _a.call(schema)) || ((_b = unwrapped.meta) == null ? void 0 : _b.call(unwrapped)) || {};
949
+ const { plugins, ...schemaOptions } = options || {};
950
+ const mergedOptions = {
951
+ // Also merge other schema options from meta if they exist
952
+ ...meta.collection ? { collection: meta.collection } : {},
953
+ // eslint-disable-next-line unicorn/no-negated-condition
954
+ ...meta.strict !== void 0 ? { strict: meta.strict } : {},
955
+ // eslint-disable-next-line unicorn/no-negated-condition
956
+ ...meta.minimize !== void 0 ? { minimize: meta.minimize } : {},
957
+ // eslint-disable-next-line unicorn/no-negated-condition
958
+ ...meta.validateBeforeSave !== void 0 ? { validateBeforeSave: meta.validateBeforeSave } : {},
959
+ // eslint-disable-next-line unicorn/no-negated-condition
960
+ ...meta.versionKey !== void 0 ? { versionKey: meta.versionKey } : {},
961
+ ...meta.id === void 0 ? {} : { id: meta.id },
962
+ ...meta._id === void 0 ? {} : { _id: meta._id },
963
+ ...meta.timestamps ? { timestamps: meta.timestamps } : {},
964
+ ...meta.discriminatorKey ? { discriminatorKey: meta.discriminatorKey } : {},
965
+ ...schemaOptions
966
+ };
967
+ let definition = extractMongooseDef(schema, /* @__PURE__ */ new Map(), false);
968
+ const mongoose2 = getMongoose();
969
+ if (!mongoose2) {
970
+ throw new Error("Mongoose must be installed to use toMongooseSchema. If you are in an ESM environment, ensure mongoose is loaded.");
971
+ }
972
+ let mongooseSchema;
973
+ if (definition && typeof definition === "object" && definition.__isDiscriminatorUnion) {
974
+ const { discriminatorKey, discriminators, baseDef, validate } = definition;
975
+ mongooseSchema = new mongoose2.Schema(baseDef, {
976
+ ...mergedOptions,
977
+ discriminatorKey
978
+ });
979
+ if (validate) {
980
+ if (!mongooseSchema.path(discriminatorKey)) {
981
+ mongooseSchema.add({ [discriminatorKey]: { type: String } });
982
+ }
983
+ mongooseSchema.path(discriminatorKey).validate(validate);
1195
984
  }
1196
- let mongooseSchema;
1197
- if (definition && typeof definition === 'object' && definition.__isDiscriminatorUnion) {
1198
- const { discriminatorKey, discriminators, baseDef, validate } = definition;
1199
- mongooseSchema = new mongoose.Schema(baseDef, {
1200
- ...mergedOptions,
1201
- discriminatorKey,
1202
- });
1203
- if (validate) {
1204
- if (!mongooseSchema.path(discriminatorKey)) {
1205
- mongooseSchema.add({ [discriminatorKey]: { type: String } });
1206
- }
1207
- mongooseSchema.path(discriminatorKey).validate(validate);
1208
- }
1209
- for (const [key, dDef] of Object.entries(discriminators)) {
1210
- if (mongooseSchema.discriminators && mongooseSchema.discriminators[key]) {
1211
- continue;
1212
- }
1213
- mongooseSchema.discriminator(key, new mongoose.Schema(dDef, { _id: false }));
1214
- }
985
+ for (const [key, dDef] of Object.entries(discriminators)) {
986
+ if (mongooseSchema.discriminators && mongooseSchema.discriminators[key]) {
987
+ continue;
988
+ }
989
+ mongooseSchema.discriminator(key, new mongoose2.Schema(dDef, { _id: false }));
1215
990
  }
1216
- else {
1217
- // Strip internal includeId metadata that might have leaked into the definition
1218
- if (typeof definition === 'object' && definition !== null) {
1219
- // If it's a top-level object, it might have metadata fields directly
1220
- const { includeId, ...cleanDefinition } = definition;
1221
- definition = cleanDefinition;
1222
- // Also clean any top-level field definitions
1223
- for (const value of Object.values(definition)) {
1224
- if (value && typeof value === 'object' && !Array.isArray(value)) {
1225
- delete value.includeId;
1226
- }
1227
- }
991
+ } else {
992
+ if (typeof definition === "object" && definition !== null) {
993
+ const { includeId, ...cleanDefinition } = definition;
994
+ definition = cleanDefinition;
995
+ for (const value of Object.values(definition)) {
996
+ if (value && typeof value === "object" && !Array.isArray(value)) {
997
+ delete value.includeId;
1228
998
  }
1229
- mongooseSchema = new mongoose.Schema(definition, mergedOptions);
999
+ }
1230
1000
  }
1231
- // Apply plugins if provided in options
1232
- if (plugins && Array.isArray(plugins)) {
1233
- for (const plugin of plugins) {
1234
- mongooseSchema.plugin(plugin);
1235
- }
1001
+ mongooseSchema = new mongoose2.Schema(definition, mergedOptions);
1002
+ }
1003
+ if (plugins && Array.isArray(plugins)) {
1004
+ for (const plugin of plugins) {
1005
+ mongooseSchema.plugin(plugin);
1236
1006
  }
1237
- // Call schema:created hook
1238
- callHookSync('schema:created', {
1239
- schema,
1240
- mongooseSchema,
1241
- options: mergedOptions,
1242
- });
1243
- return mongooseSchema;
1007
+ }
1008
+ callHookSync("schema:created", {
1009
+ schema,
1010
+ mongooseSchema,
1011
+ options: mergedOptions
1012
+ });
1013
+ return mongooseSchema;
1244
1014
  }
1245
-
1246
- const zObjectId = (options) => {
1247
- if (getFrontendMode()) {
1248
- return withMongoose(v4.z.preprocess((val) => (val === null ? undefined : val), v4.z.string().regex(/^[\dA-Fa-f]{24}$/, 'Invalid ObjectId')), {
1249
- type: 'ObjectId', // String representation for metadata
1250
- ...options,
1251
- });
1015
+ function populateZodSchema(schema, keys) {
1016
+ const { shape } = schema;
1017
+ const newShape = { ...shape };
1018
+ const keysToPopulate = keys || Object.keys(shape);
1019
+ const populateField = (field) => {
1020
+ const meta = getMongooseMeta(field);
1021
+ const { schema: unwrapped, features } = unwrapZodSchema(field);
1022
+ let result = field;
1023
+ if (meta == null ? void 0 : meta.refSchema) {
1024
+ result = meta.refSchema;
1025
+ } else if (unwrapped instanceof z.ZodArray) {
1026
+ const populatedInner = populateField(unwrapped.element);
1027
+ if (populatedInner !== unwrapped.element) {
1028
+ result = z.array(populatedInner);
1029
+ }
1030
+ } else if (unwrapped instanceof z.ZodObject) {
1031
+ result = populateZodSchema(unwrapped);
1252
1032
  }
1253
- const mongoose = getMongoose();
1254
- return withMongoose(v4.z.preprocess((val) => (val === null ? undefined : val), v4.z.custom((val) => (mongoose && val instanceof mongoose.Types.ObjectId) ||
1255
- (typeof val === 'string' && /^[\dA-Fa-f]{24}$/.test(val)))), {
1256
- type: mongoose?.Schema.Types.ObjectId || 'ObjectId',
1257
- ...options,
1258
- });
1033
+ if (result !== field && result !== unwrapped) {
1034
+ if (features.isOptional && !(result instanceof z.ZodOptional))
1035
+ result = result.optional();
1036
+ if (features.isNullable && !(result instanceof z.ZodNullable))
1037
+ result = result.nullable();
1038
+ if (features.default !== void 0 && !(result instanceof z.ZodDefault))
1039
+ result = result.default(features.default);
1040
+ }
1041
+ return result;
1042
+ };
1043
+ for (const key of keysToPopulate) {
1044
+ newShape[key] = populateField(shape[key]);
1045
+ }
1046
+ return z.object(newShape);
1047
+ }
1048
+ const genTimestampsSchema = (createdAtField = "createdAt", updatedAtField = "updatedAt") => {
1049
+ if (createdAtField != null && updatedAtField != null && createdAtField === updatedAtField) {
1050
+ throw new Error("`createdAt` and `updatedAt` fields must be different");
1051
+ }
1052
+ const shape = {};
1053
+ if (createdAtField != null)
1054
+ shape[createdAtField] = z.date().default(() => /* @__PURE__ */ new Date());
1055
+ if (updatedAtField != null)
1056
+ shape[updatedAtField] = z.date().default(() => /* @__PURE__ */ new Date());
1057
+ return shape;
1058
+ };
1059
+ const bufferMongooseGetter = (value) => value != null && value._bsontype === "Binary" ? value.buffer : value;
1060
+ const preprocessFn = (val) => val === null ? void 0 : val;
1061
+ const zObjectId = (options) => {
1062
+ const mongooseInstance2 = getMongoose();
1063
+ const objectIdSchema = z.custom((val) => mongooseInstance2 && val instanceof mongooseInstance2.Types.ObjectId);
1064
+ const baseUnion = z.preprocess(preprocessFn, z.union([objectIdSchema, z.string().regex(/^[\dA-Fa-f]{24}$/, "Invalid ObjectId")]));
1065
+ const inputSchema = z.codec(baseUnion, objectIdSchema, {
1066
+ decode: (val) => {
1067
+ if (!mongooseInstance2)
1068
+ return val;
1069
+ if (val instanceof mongooseInstance2.Types.ObjectId) {
1070
+ return val;
1071
+ }
1072
+ return new mongooseInstance2.Types.ObjectId(val);
1073
+ },
1074
+ encode: (val) => val.toString()
1075
+ });
1076
+ return withMongoose(inputSchema, {
1077
+ type: (mongooseInstance2 == null ? void 0 : mongooseInstance2.Schema.Types.ObjectId) || "ObjectId",
1078
+ ...options
1079
+ });
1259
1080
  };
1260
1081
  const zBuffer = (options) => {
1261
- if (getFrontendMode()) {
1262
- return withMongoose(v4.z.instanceof(Uint8Array), {
1263
- type: 'Buffer',
1264
- ...options,
1265
- });
1266
- }
1267
- const mongoose = getMongoose();
1268
- return withMongoose(v4.z.custom((val) => (mongoose && val instanceof Buffer) || val instanceof Uint8Array), {
1269
- type: mongoose?.Schema.Types.Buffer || 'Buffer',
1270
- ...options,
1271
- });
1082
+ const mongooseInstance2 = getMongoose();
1083
+ return withMongoose(z.custom((val) => mongooseInstance2 && val instanceof Buffer || val instanceof Uint8Array), { type: (mongooseInstance2 == null ? void 0 : mongooseInstance2.Schema.Types.Buffer) || "Buffer", ...options });
1272
1084
  };
1273
1085
  const zRef = (ref, schema, options) => {
1274
- const isFrontend = getFrontendMode();
1275
- const mongoose = getMongoose();
1276
- const objectIdSchema = zObjectId();
1277
- const base = v4.z.codec(v4.z.union([objectIdSchema, schema]), objectIdSchema, {
1278
- decode: (val) => (typeof val === 'object' && val !== null && '_id' in val ? val._id : val),
1279
- encode: (val) => val,
1280
- });
1281
- const result = withMongoose(base, {
1282
- type: isFrontend ? 'ObjectId' : mongoose?.Schema.Types.ObjectId || 'ObjectId',
1283
- ref,
1284
- refSchema: schema,
1285
- ...options,
1286
- });
1287
- return result;
1086
+ const mongooseInstance2 = getMongoose();
1087
+ const objectIdSchema = zObjectId();
1088
+ const base = z.codec(z.union([objectIdSchema, schema]), objectIdSchema, {
1089
+ decode: (val) => typeof val === "object" && val !== null && "_id" in val ? val._id : val,
1090
+ encode: (val) => val
1091
+ });
1092
+ return withMongoose(base, {
1093
+ type: (mongooseInstance2 == null ? void 0 : mongooseInstance2.Schema.Types.ObjectId) || "ObjectId",
1094
+ ref,
1095
+ refSchema: schema,
1096
+ ...options
1097
+ });
1288
1098
  };
1289
- /**
1290
- * Helper to create a populated version of a Zod schema.
1291
- * Replaces zRef fields with their corresponding refSchema.
1292
- * If no keys are provided, it attempts to populate all zRef fields.
1293
- */
1294
- function populateZodSchema(schema, keys) {
1295
- const { shape } = schema;
1296
- const newShape = { ...shape };
1297
- const keysToPopulate = keys || Object.keys(shape);
1298
- const populateField = (field) => {
1299
- const meta = getMongooseMeta(field);
1300
- const { schema: unwrapped, features } = unwrapZodSchema(field);
1301
- let result = field;
1302
- if (meta?.refSchema) {
1303
- result = meta.refSchema;
1304
- }
1305
- else if (unwrapped instanceof v4.z.ZodArray) {
1306
- const populatedInner = populateField(unwrapped.element);
1307
- if (populatedInner !== unwrapped.element) {
1308
- result = v4.z.array(populatedInner);
1309
- }
1310
- }
1311
- else if (unwrapped instanceof v4.z.ZodObject) {
1312
- result = populateZodSchema(unwrapped);
1313
- }
1314
- if (result !== field && result !== unwrapped) {
1315
- // Re-apply common wrappers if they were lost during unwrap
1316
- if (features.isOptional && !(result instanceof v4.z.ZodOptional)) {
1317
- result = result.optional();
1318
- }
1319
- if (features.isNullable && !(result instanceof v4.z.ZodNullable)) {
1320
- result = result.nullable();
1321
- }
1322
- if (features.default !== undefined && !(result instanceof v4.z.ZodDefault)) {
1323
- result = result.default(features.default);
1324
- }
1325
- }
1326
- return result;
1327
- };
1328
- for (const key of keysToPopulate) {
1329
- newShape[key] = populateField(shape[key]);
1330
- }
1331
- return v4.z.object(newShape);
1099
+ function toStrictModel(name, mongooseSchema) {
1100
+ const rawModel = mongoose__default.model(name, mongooseSchema);
1101
+ return rawModel;
1332
1102
  }
1333
- const DateFieldZod = () => v4.z.date().default(() => new Date());
1334
- const genTimestampsSchema = (createdAtField = 'createdAt', updatedAtField = 'updatedAt') => {
1335
- if (createdAtField != null &&
1336
- updatedAtField != null &&
1337
- createdAtField === updatedAtField) {
1338
- throw new Error('`createdAt` and `updatedAt` fields must be different');
1339
- }
1340
- const shape = {};
1341
- if (createdAtField != null) {
1342
- shape[createdAtField] = withMongoose(DateFieldZod(), { immutable: true, index: true });
1343
- }
1344
- if (updatedAtField != null) {
1345
- shape[updatedAtField] = withMongoose(DateFieldZod(), { index: true });
1346
- }
1347
- return shape;
1348
- };
1349
- const bufferMongooseGetter = (value) => value != null && value._bsontype === 'Binary' ? value.buffer : value;
1350
-
1351
- var bufferMongooseGetter_1 = dist.bufferMongooseGetter = bufferMongooseGetter;
1352
- var callHookSync_1 = dist.callHookSync = callHookSync;
1353
- var extractMongooseDef_1 = dist.extractMongooseDef = extractMongooseDef;
1354
- var genTimestampsSchema_1 = dist.genTimestampsSchema = genTimestampsSchema;
1355
- var getFrontendMode_1 = dist.getFrontendMode = getFrontendMode;
1356
- var getMongoose_1 = dist.getMongoose = getMongoose;
1357
- var getMongooseMeta_1 = dist.getMongooseMeta = getMongooseMeta;
1358
- var hooks_1 = dist.hooks = hooks;
1359
- var mongooseRegistry_1 = dist.mongooseRegistry = mongooseRegistry;
1360
- var populateZodSchema_1 = dist.populateZodSchema = populateZodSchema;
1361
- var setFrontendMode_1 = dist.setFrontendMode = setFrontendMode;
1362
- var setMongoose_1 = dist.setMongoose = setMongoose;
1363
- var toMongooseSchema_1 = dist.toMongooseSchema = toMongooseSchema;
1364
- var withMongoose_1 = dist.withMongoose = withMongoose;
1365
- var zBuffer_1 = dist.zBuffer = zBuffer;
1366
- var zObjectId_1 = dist.zObjectId = zObjectId;
1367
- var zRef_1 = dist.zRef = zRef;
1368
1103
 
1369
- const mongooseZod = /*#__PURE__*/_mergeNamespaces({
1370
- __proto__: null,
1371
- bufferMongooseGetter: bufferMongooseGetter_1,
1372
- callHookSync: callHookSync_1,
1373
- default: dist,
1374
- extractMongooseDef: extractMongooseDef_1,
1375
- genTimestampsSchema: genTimestampsSchema_1,
1376
- getFrontendMode: getFrontendMode_1,
1377
- getMongoose: getMongoose_1,
1378
- getMongooseMeta: getMongooseMeta_1,
1379
- hooks: hooks_1,
1380
- mongooseRegistry: mongooseRegistry_1,
1381
- populateZodSchema: populateZodSchema_1,
1382
- setFrontendMode: setFrontendMode_1,
1383
- setMongoose: setMongoose_1,
1384
- toMongooseSchema: toMongooseSchema_1,
1385
- withMongoose: withMongoose_1,
1386
- zBuffer: zBuffer_1,
1387
- zObjectId: zObjectId_1,
1388
- zRef: zRef_1
1389
- }, [dist]);
1104
+ const mongooseZod = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
1105
+ __proto__: null,
1106
+ bufferMongooseGetter: bufferMongooseGetter,
1107
+ callHookSync: callHookSync,
1108
+ extractMongooseDef: extractMongooseDef,
1109
+ genTimestampsSchema: genTimestampsSchema,
1110
+ getFrontendMode: getFrontendMode,
1111
+ getMongoose: getMongoose,
1112
+ getMongooseMeta: getMongooseMeta,
1113
+ hooks: hooks,
1114
+ mongooseRegistry: mongooseRegistry,
1115
+ populateZodSchema: populateZodSchema,
1116
+ setFrontendMode: setFrontendMode,
1117
+ setMongoose: setMongoose,
1118
+ toMongooseSchema: toMongooseSchema,
1119
+ toStrictModel: toStrictModel,
1120
+ withMongoose: withMongoose,
1121
+ zBuffer: zBuffer,
1122
+ zObjectId: zObjectId,
1123
+ zRef: zRef
1124
+ }, Symbol.toStringTag, { value: 'Module' }));
1390
1125
 
1391
- setMongoose_1(mongoose.default || mongoose);
1126
+ setMongoose(mongoose.default || mongoose);
1392
1127
  let _filename = "/sandbox/main.ts";
1393
1128
  let _dirname = "/sandbox";
1394
1129
  try {
@@ -1462,8 +1197,8 @@ const parse_post = defineEventHandler(async (event) => {
1462
1197
  if (!schema || !schema._def) {
1463
1198
  throw new Error("You must `export default` a valid Zod schema.");
1464
1199
  }
1465
- const extractedDef = extractMongooseDef_1(schema);
1466
- const mongooseSchema = toMongooseSchema_1(schema);
1200
+ const extractedDef = extractMongooseDef(schema);
1201
+ const mongooseSchema = toMongooseSchema(schema);
1467
1202
  const formatOpts = { depth: null, showHidden: false, colors: false };
1468
1203
  const formatValue = (val) => {
1469
1204
  if (typeof val === "function") {