zodvex 0.8.0-beta.0 → 0.8.0-beta.2

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.
Files changed (169) hide show
  1. package/README.md +78 -107
  2. package/dist/cli/index.d.ts +1 -1
  3. package/dist/cli/index.js +604 -1364
  4. package/dist/cli/index.js.map +1 -1
  5. package/dist/cli/inspect-schema/census.mjs +112 -0
  6. package/dist/cli/inspect-schema/inspect-worker.mjs +24 -0
  7. package/dist/cli/inspect-schema/inspect.mjs +177 -0
  8. package/dist/client/index.js +106 -24
  9. package/dist/client/index.js.map +1 -1
  10. package/dist/codegen/index.js +373 -508
  11. package/dist/codegen/index.js.map +1 -1
  12. package/dist/core/index.js +312 -253
  13. package/dist/core/index.js.map +1 -1
  14. package/dist/index.js +312 -253
  15. package/dist/index.js.map +1 -1
  16. package/dist/internal/actionCtx.d.ts.map +1 -1
  17. package/dist/internal/boundaryHelpers.d.ts +12 -15
  18. package/dist/internal/boundaryHelpers.d.ts.map +1 -1
  19. package/dist/internal/codec.d.ts +4 -0
  20. package/dist/internal/codec.d.ts.map +1 -1
  21. package/dist/internal/customization.d.ts +33 -15
  22. package/dist/internal/customization.d.ts.map +1 -1
  23. package/dist/internal/db.d.ts +174 -29
  24. package/dist/internal/db.d.ts.map +1 -1
  25. package/dist/internal/functions/contracts.d.ts +66 -0
  26. package/dist/internal/functions/contracts.d.ts.map +1 -0
  27. package/dist/internal/{custom.d.ts → functions/customFunctions.d.ts} +33 -30
  28. package/dist/internal/functions/customFunctions.d.ts.map +1 -0
  29. package/dist/internal/{init.d.ts → functions/init.d.ts} +66 -70
  30. package/dist/internal/functions/init.d.ts.map +1 -0
  31. package/dist/internal/ids.d.ts +1 -1
  32. package/dist/internal/ids.d.ts.map +1 -1
  33. package/dist/internal/{builders.d.ts → legacy/builders.d.ts} +2 -2
  34. package/dist/internal/legacy/builders.d.ts.map +1 -0
  35. package/dist/internal/{wrappers.d.ts → legacy/wrappers.d.ts} +2 -2
  36. package/dist/internal/legacy/wrappers.d.ts.map +1 -0
  37. package/dist/internal/model.d.ts +105 -6
  38. package/dist/internal/model.d.ts.map +1 -1
  39. package/dist/internal/modelSchemaBundle.d.ts.map +1 -1
  40. package/dist/internal/paginationCodec.d.ts +8 -0
  41. package/dist/internal/paginationCodec.d.ts.map +1 -0
  42. package/dist/internal/registry.d.ts +7 -2
  43. package/dist/internal/registry.d.ts.map +1 -1
  44. package/dist/internal/schema/id.d.ts +29 -0
  45. package/dist/internal/schema/id.d.ts.map +1 -0
  46. package/dist/internal/schema.d.ts +13 -55
  47. package/dist/internal/schema.d.ts.map +1 -1
  48. package/dist/internal/schemaHelpers.d.ts +1 -1
  49. package/dist/internal/schemaHelpers.d.ts.map +1 -1
  50. package/dist/internal/stream.d.ts +110 -0
  51. package/dist/internal/stream.d.ts.map +1 -0
  52. package/dist/internal/zx.d.ts +2 -28
  53. package/dist/internal/zx.d.ts.map +1 -1
  54. package/dist/internal/zxDateBrand.d.ts +5 -0
  55. package/dist/internal/zxDateBrand.d.ts.map +1 -0
  56. package/dist/labs/index.js +122 -78
  57. package/dist/labs/index.js.map +1 -1
  58. package/dist/legacy/index.d.ts +1 -1
  59. package/dist/legacy/index.d.ts.map +1 -1
  60. package/dist/legacy/index.js +101 -293
  61. package/dist/legacy/index.js.map +1 -1
  62. package/dist/mini/client/index.js +106 -24
  63. package/dist/mini/client/index.js.map +1 -1
  64. package/dist/mini/index.js +312 -253
  65. package/dist/mini/index.js.map +1 -1
  66. package/dist/mini/react/index.js +143 -23
  67. package/dist/mini/react/index.js.map +1 -1
  68. package/dist/mini/server/index.js +1210 -1202
  69. package/dist/mini/server/index.js.map +1 -1
  70. package/dist/public/cli/commands.d.ts.map +1 -1
  71. package/dist/public/cli/index.d.ts +1 -1
  72. package/dist/public/cli/init.d.ts +1 -2
  73. package/dist/public/cli/init.d.ts.map +1 -1
  74. package/dist/public/cli/migrate.d.ts.map +1 -1
  75. package/dist/public/client/index.d.ts +1 -1
  76. package/dist/public/client/index.d.ts.map +1 -1
  77. package/dist/public/client/zodvexClient.d.ts +23 -9
  78. package/dist/public/client/zodvexClient.d.ts.map +1 -1
  79. package/dist/public/codegen/discover.d.ts +0 -44
  80. package/dist/public/codegen/discover.d.ts.map +1 -1
  81. package/dist/public/codegen/discovery-hooks.d.ts +2 -1
  82. package/dist/public/codegen/discovery-hooks.d.ts.map +1 -1
  83. package/dist/public/codegen/extractCodec.d.ts.map +1 -1
  84. package/dist/public/codegen/generate.d.ts +6 -79
  85. package/dist/public/codegen/generate.d.ts.map +1 -1
  86. package/dist/public/codegen/index.d.ts +1 -1
  87. package/dist/public/codegen/index.d.ts.map +1 -1
  88. package/dist/public/codegen/tsconfigPaths.d.ts +41 -0
  89. package/dist/public/codegen/tsconfigPaths.d.ts.map +1 -0
  90. package/dist/public/codegen/zodToSource.d.ts.map +1 -1
  91. package/dist/public/mini/index.d.ts +1 -1
  92. package/dist/public/mini/index.d.ts.map +1 -1
  93. package/dist/public/mini/model.d.ts +53 -3
  94. package/dist/public/mini/model.d.ts.map +1 -1
  95. package/dist/public/model.d.ts +53 -3
  96. package/dist/public/model.d.ts.map +1 -1
  97. package/dist/public/react/hooks.d.ts +28 -2
  98. package/dist/public/react/hooks.d.ts.map +1 -1
  99. package/dist/public/react/index.d.ts +1 -1
  100. package/dist/public/react/index.d.ts.map +1 -1
  101. package/dist/public/react/zodvexReactClient.d.ts.map +1 -1
  102. package/dist/public/server/index.d.ts +7 -6
  103. package/dist/public/server/index.d.ts.map +1 -1
  104. package/dist/react/index.js +143 -23
  105. package/dist/react/index.js.map +1 -1
  106. package/dist/server/index.js +1210 -1202
  107. package/dist/server/index.js.map +1 -1
  108. package/package.json +8 -4
  109. package/src/cli/index.ts +1 -1
  110. package/src/internal/actionCtx.ts +9 -14
  111. package/src/internal/boundaryHelpers.ts +44 -14
  112. package/src/internal/codec.ts +36 -8
  113. package/src/internal/customization.ts +84 -32
  114. package/src/internal/db.ts +819 -63
  115. package/src/internal/functions/contracts.ts +313 -0
  116. package/src/internal/{custom.ts → functions/customFunctions.ts} +174 -151
  117. package/src/internal/{init.ts → functions/init.ts} +219 -193
  118. package/src/internal/ids.ts +11 -4
  119. package/src/internal/{builders.ts → legacy/builders.ts} +38 -65
  120. package/src/internal/{wrappers.ts → legacy/wrappers.ts} +6 -14
  121. package/src/internal/mapping/types.ts +2 -2
  122. package/src/internal/model.ts +312 -76
  123. package/src/internal/modelSchemaBundle.ts +2 -2
  124. package/src/internal/paginationCodec.ts +60 -0
  125. package/src/internal/registry.ts +50 -3
  126. package/src/internal/schema/id.ts +52 -0
  127. package/src/internal/schema.ts +45 -78
  128. package/src/internal/schemaHelpers.ts +3 -3
  129. package/src/internal/stream.ts +242 -0
  130. package/src/internal/types.ts +2 -2
  131. package/src/internal/zx.ts +15 -60
  132. package/src/internal/zxDateBrand.ts +34 -0
  133. package/src/legacy/index.ts +1 -1
  134. package/src/public/cli/commands.ts +59 -180
  135. package/src/public/cli/index.ts +16 -1
  136. package/src/public/cli/init.ts +3 -16
  137. package/src/public/cli/inspect-schema/census.mjs +112 -0
  138. package/src/public/cli/inspect-schema/inspect-worker.mjs +24 -0
  139. package/src/public/cli/inspect-schema/inspect.mjs +177 -0
  140. package/src/public/cli/migrate.ts +0 -120
  141. package/src/public/client/index.ts +1 -1
  142. package/src/public/client/zodvexClient.ts +74 -22
  143. package/src/public/codegen/discover.ts +34 -148
  144. package/src/public/codegen/discovery-hooks.ts +73 -8
  145. package/src/public/codegen/extractCodec.ts +5 -11
  146. package/src/public/codegen/generate.ts +45 -719
  147. package/src/public/codegen/index.ts +0 -1
  148. package/src/public/codegen/tsconfigPaths.ts +224 -0
  149. package/src/public/codegen/zodToSource.ts +17 -10
  150. package/src/public/mini/index.ts +2 -0
  151. package/src/public/mini/model.ts +89 -3
  152. package/src/public/model.ts +89 -3
  153. package/src/public/react/hooks.ts +145 -16
  154. package/src/public/react/index.ts +1 -1
  155. package/src/public/react/zodvexReactClient.ts +6 -2
  156. package/src/public/server/index.ts +51 -35
  157. package/dist/internal/builders.d.ts.map +0 -1
  158. package/dist/internal/custom.d.ts.map +0 -1
  159. package/dist/internal/functionContracts.d.ts +0 -60
  160. package/dist/internal/functionContracts.d.ts.map +0 -1
  161. package/dist/internal/init.d.ts.map +0 -1
  162. package/dist/internal/ruleTypes.d.ts +0 -104
  163. package/dist/internal/ruleTypes.d.ts.map +0 -1
  164. package/dist/internal/rules.d.ts +0 -27
  165. package/dist/internal/rules.d.ts.map +0 -1
  166. package/dist/internal/wrappers.d.ts.map +0 -1
  167. package/src/internal/functionContracts.ts +0 -270
  168. package/src/internal/ruleTypes.ts +0 -120
  169. package/src/internal/rules.ts +0 -779
package/dist/cli/index.js CHANGED
@@ -1,15 +1,13 @@
1
- #!/usr/bin/env bun
2
- import fs2, { readFileSync, writeFileSync, existsSync } from 'fs';
3
- import path3, { resolve, relative, join } from 'path';
4
- import { Project, SyntaxKind } from 'ts-morph';
1
+ #!/usr/bin/env node
2
+ import fs3, { readFileSync, writeFileSync, existsSync } from 'fs';
3
+ import path4, { resolve, relative, join } from 'path';
4
+ import { Project, SyntaxKind, Node } from 'ts-morph';
5
5
  import { globSync } from 'tinyglobby';
6
6
  import { spawn } from 'child_process';
7
7
  import { fileURLToPath } from 'url';
8
8
  import { z } from 'zod';
9
- import { $ZodCodec, $ZodNumber, $ZodCustom, $ZodType, $ZodOptional, $ZodNullable, $ZodObject, $ZodArray, $ZodUnion, $ZodDiscriminatedUnion, $ZodLiteral, $ZodRecord, $ZodTuple, clone, $ZodString, $ZodBoolean, $ZodNull, $ZodUndefined, $ZodAny, $ZodEnum, $ZodDefault, $ZodLazy } from 'zod/v4/core';
10
- import { v } from 'convex/values';
11
- import { createHash } from 'crypto';
12
- import { defineTable } from 'convex/server';
9
+ import { $ZodCodec, $ZodType, $ZodOptional, $ZodNullable, $ZodObject, $ZodUnion, $ZodArray, $ZodRecord, $ZodTuple, clone, $ZodString, $ZodNumber, $ZodBoolean, $ZodNull, $ZodUndefined, $ZodAny, $ZodEnum, $ZodLiteral, $ZodDiscriminatedUnion } from 'zod/v4/core';
10
+ import 'convex/values';
13
11
 
14
12
  var __defProp = Object.defineProperty;
15
13
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -64,32 +62,26 @@ function gitignoreEntry(content) {
64
62
  return lines.join("\n");
65
63
  }
66
64
  function generateStubs(convexDir2) {
67
- const zodvexDir = path3.join(convexDir2, "_zodvex");
68
- fs2.mkdirSync(zodvexDir, { recursive: true });
65
+ const zodvexDir = path4.join(convexDir2, "_zodvex");
66
+ fs3.mkdirSync(zodvexDir, { recursive: true });
69
67
  const apiStub = `// Auto-generated stub. Run \`zodvex generate\` to populate.
70
68
  export const zodvexRegistry = {} as const
71
69
  `;
72
- fs2.writeFileSync(path3.join(zodvexDir, "api.ts"), apiStub);
73
- const apiArgsStub = `// Auto-generated stub. Run \`zodvex generate\` to populate.
74
- export const zodvexArgsRegistry = {} as const
75
- `;
76
- fs2.writeFileSync(path3.join(zodvexDir, "api.args.ts"), apiArgsStub);
70
+ fs3.writeFileSync(path4.join(zodvexDir, "api.ts"), apiStub);
77
71
  const clientStub = `// Auto-generated stub. Run \`zodvex generate\` to populate.
78
72
  import { zodvexRegistry } from './api'
79
73
 
80
74
  export const useZodQuery = undefined as any
81
75
  export const useZodMutation = undefined as any
76
+ export const useZodPaginatedQuery = undefined as any
77
+ export const useQuery_experimental = undefined as any
82
78
  export const createClient = undefined as any
83
79
  `;
84
- fs2.writeFileSync(path3.join(zodvexDir, "client.ts"), clientStub);
85
- const skipMarker = `// NOOP \u2014 prevents Convex from importing the zod-only code into the runtime isolate.
86
- // See https://github.com/panzacoder/zodvex for context.
87
- `;
88
- fs2.writeFileSync(path3.join(zodvexDir, "convex.config.ts"), skipMarker);
80
+ fs3.writeFileSync(path4.join(zodvexDir, "client.ts"), clientStub);
89
81
  }
90
82
  async function init() {
91
- const convexDir2 = path3.resolve("convex");
92
- if (!fs2.existsSync(convexDir2)) {
83
+ const convexDir2 = path4.resolve("convex");
84
+ if (!fs3.existsSync(convexDir2)) {
93
85
  console.error("[zodvex] No convex/ directory found. Run this from your project root.");
94
86
  return;
95
87
  }
@@ -110,14 +102,14 @@ __export(migrate_exports, {
110
102
  function collectFiles(dir) {
111
103
  const results = [];
112
104
  function walk(current) {
113
- const entries = fs2.readdirSync(current, { withFileTypes: true });
105
+ const entries = fs3.readdirSync(current, { withFileTypes: true });
114
106
  for (const entry of entries) {
115
107
  if (entry.isDirectory()) {
116
108
  if (!SKIP_DIRS.has(entry.name)) {
117
- walk(path3.join(current, entry.name));
109
+ walk(path4.join(current, entry.name));
118
110
  }
119
- } else if (entry.isFile() && TS_EXTENSIONS.has(path3.extname(entry.name))) {
120
- results.push(path3.join(current, entry.name));
111
+ } else if (entry.isFile() && TS_EXTENSIONS.has(path4.extname(entry.name))) {
112
+ results.push(path4.join(current, entry.name));
121
113
  }
122
114
  }
123
115
  }
@@ -148,55 +140,6 @@ function classifyImport(imported) {
148
140
  if (SERVER_IMPORTS.has(imported)) return "server";
149
141
  return "root";
150
142
  }
151
- function applyRegistryLazyRewrite(content) {
152
- if (!/\bregistry\s*:\s*\(\s*\)\s*=>\s*zodvexRegistry\b/.test(content)) {
153
- return content;
154
- }
155
- const apiImportRe = /(import\s*\{[^}]*\bzodvexRegistry\b[^}]*\}\s*from\s*['"])([^'"]*\/_zodvex\/api)(\.js)?(['"])/;
156
- if (!apiImportRe.test(content)) {
157
- return content;
158
- }
159
- let next = content.replace(
160
- apiImportRe,
161
- (_m, pre, base2, ext, quote) => `${pre}${base2}.lazy${ext ?? ""}${quote}`
162
- );
163
- next = next.replace(/registry\s*:\s*\(\s*\)\s*=>\s*zodvexRegistry\b/, "registry: zodvexRegistry");
164
- return next;
165
- }
166
- function applySchemaRewrite(content) {
167
- if (!/\bdefineZodSchema\s*\(/.test(content)) return content;
168
- const canonicalRe = /^import\s+\{\s*defineZodSchema\s*\}\s+from\s+['"]zodvex(?:\/mini)?\/server['"]\s*;?\s*\n([\s\S]*?)\nexport default defineZodSchema\(\{[\s\S]*?\}\)\s*;?\s*$/m;
169
- if (!canonicalRe.test(content)) return content;
170
- return [
171
- "import { defineSchema } from 'convex/server'",
172
- "import tables from './_zodvex/tables'",
173
- "",
174
- "export default defineSchema(tables)",
175
- ""
176
- ].join("\n");
177
- }
178
- function applyInitZodvexConsolidation(content) {
179
- if (!/\binitZodvex\s*\(\s*schema\b/.test(content)) return content;
180
- let next = content;
181
- next = next.replace(/import\s+schema\s+from\s+['"]\.\/schema['"]\s*;?\s*\n/, "");
182
- next = next.replace(
183
- /import\s+\{\s*zodvexRegistry\s*\}\s+from\s+['"]\.\/_zodvex\/api(?:\.lazy)?(?:\.js)?['"]\s*;?\s*\n/,
184
- ""
185
- );
186
- next = next.replace(
187
- /import\s+\{\s*zodTableMap\s*\}\s+from\s+['"]\.\/_zodvex\/tableMap\.lazy(?:\.js)?['"]\s*;?\s*\n/,
188
- ""
189
- );
190
- next = next.replace(
191
- /import\s+\{\s*initZodvex\s*\}\s+from\s+['"]zodvex(?:\/mini)?\/server['"]/,
192
- "import { initZodvex } from './_zodvex/server'"
193
- );
194
- next = next.replace(
195
- /initZodvex\(\s*schema\s*,\s*(\{[\s\S]*?\})\s*(?:,\s*\{[\s\S]*?\}\s*)?\)/,
196
- "initZodvex($1)"
197
- );
198
- return next;
199
- }
200
143
  function applyImportUpdates(content) {
201
144
  const importRe = /import\s*\{([^}]+)\}\s*from\s*(['"]zodvex(?:\/[^'"]*)?['"])/g;
202
145
  return content.replace(importRe, (match, specifiers, moduleStr) => {
@@ -263,20 +206,17 @@ function migrate(dir, options) {
263
206
  let wouldChange = 0;
264
207
  const allDeprecations = [];
265
208
  for (const filePath of files) {
266
- const original = fs2.readFileSync(filePath, "utf-8");
209
+ const original = fs3.readFileSync(filePath, "utf-8");
267
210
  let content = original;
268
211
  content = applyIdentifierRenames(content);
269
212
  content = applyZidTransform(content);
270
213
  content = applyImportUpdates(content);
271
- content = applyRegistryLazyRewrite(content);
272
- content = applySchemaRewrite(content);
273
- content = applyInitZodvexConsolidation(content);
274
214
  const changed = content !== original;
275
215
  if (changed) {
276
216
  if (options.dryRun) {
277
217
  wouldChange++;
278
218
  } else {
279
- fs2.writeFileSync(filePath, content);
219
+ fs3.writeFileSync(filePath, content);
280
220
  filesChanged++;
281
221
  }
282
222
  }
@@ -385,25 +325,15 @@ function getMethodName(call) {
385
325
  function transformWrappers(file, typeChecker) {
386
326
  let count = 0;
387
327
  const calls = file.getDescendantsOfKind(SyntaxKind.CallExpression).reverse();
328
+ const receivers = analyzeCallReceivers(calls, WRAPPER_METHODS, typeChecker);
388
329
  for (const call of calls) {
389
- if (call.wasForgotten()) continue;
330
+ if (call.wasForgotten() || !receivers.get(call)?.schema) continue;
390
331
  const method = getMethodName(call);
391
332
  if (!method || !WRAPPER_METHODS.includes(method)) continue;
392
333
  if (call.getArguments().length > 0) continue;
393
334
  const obj = getCallObject(call);
394
335
  if (!obj) continue;
395
336
  if (isNamespaceCall(obj)) continue;
396
- let isSchema;
397
- if (typeChecker) {
398
- const typeResult = isZodSchemaByType(call, typeChecker);
399
- isSchema = typeResult === true || typeResult === null && isLikelySchemaExpr(obj);
400
- } else {
401
- isSchema = isLikelySchemaExpr(obj);
402
- }
403
- if (!isSchema && isSchemaVariable(call, obj.trim())) {
404
- isSchema = true;
405
- }
406
- if (!isSchema) continue;
407
337
  call.replaceWithText(`z.${method}(${obj})`);
408
338
  count++;
409
339
  }
@@ -412,43 +342,97 @@ function transformWrappers(file, typeChecker) {
412
342
  function isNamespaceCall(obj) {
413
343
  return NAMESPACE_IDENTIFIERS.has(obj.trim());
414
344
  }
415
- function isLikelySchemaExpr(obj) {
416
- const normalized = obj.trim().replace(/^\(+/, "").replace(/\s+as\s+[\w$<>,\s|&[\]]+\)*\s*$/, "").trim();
417
- if (normalized.match(/^z\.\w+\(/)) return true;
418
- if (normalized.match(/^zx\.\w+\(/)) return true;
419
- return false;
420
- }
421
- function isSchemaVariable(call, varName) {
422
- const file = call.getSourceFile();
423
- const varDecls = file.getDescendantsOfKind(SyntaxKind.VariableDeclaration);
424
- let closestDecl;
425
- for (const decl of varDecls) {
426
- if (decl.getName() !== varName) continue;
427
- if (decl.getStart() >= call.getStart()) continue;
428
- closestDecl = decl;
429
- }
430
- if (!closestDecl) return false;
431
- const init2 = closestDecl.getInitializer();
432
- if (!init2) return false;
433
- return isLikelySchemaExpr(init2.getText());
434
- }
435
- function isZodSchemaByType(call, typeChecker) {
345
+ function schemaKind(node, seen = /* @__PURE__ */ new Set(), context = /* @__PURE__ */ new Map()) {
346
+ if (seen.has(node)) return null;
347
+ seen.add(node);
348
+ if (Node.isParenthesizedExpression(node) || Node.isAsExpression(node) || Node.isNonNullExpression(node)) {
349
+ return schemaKind(node.getExpression(), seen, context);
350
+ }
351
+ if (Node.isIdentifier(node)) {
352
+ for (const decl of node.getSymbol()?.getDeclarations() ?? []) {
353
+ if (Node.isVariableDeclaration(decl)) {
354
+ const init2 = decl.getInitializer();
355
+ if (init2) return schemaKind(init2, seen, context);
356
+ }
357
+ if (Node.isParameterDeclaration(decl)) {
358
+ const annotation = decl.getTypeNode()?.getText();
359
+ if (annotation && /^z\.Zod(?:Mini)?\w+/.test(annotation)) return "schema";
360
+ }
361
+ }
362
+ return null;
363
+ }
364
+ if (!Node.isCallExpression(node)) return null;
365
+ const expr = node.getExpression();
366
+ if (!Node.isPropertyAccessExpression(expr)) return null;
367
+ const receiver = expr.getExpression();
368
+ const name = expr.getName();
369
+ if (Node.isIdentifier(receiver) && NAMESPACE_IDENTIFIERS.has(receiver.getText())) {
370
+ const file = node.getSourceFile();
371
+ let localNamespaces = context.get(file);
372
+ if (!localNamespaces) {
373
+ localNamespaces = /* @__PURE__ */ new Set();
374
+ for (const declaration of file.getDescendants()) {
375
+ if (Node.isVariableDeclaration(declaration) || Node.isParameterDeclaration(declaration) || Node.isFunctionDeclaration(declaration) || Node.isBindingElement(declaration) || Node.isClassDeclaration(declaration) || Node.isEnumDeclaration(declaration)) {
376
+ const name2 = declaration.getName();
377
+ if (name2 && NAMESPACE_IDENTIFIERS.has(name2)) localNamespaces.add(name2);
378
+ }
379
+ }
380
+ context.set(file, localNamespaces);
381
+ }
382
+ if (localNamespaces.has(receiver.getText())) {
383
+ const declarations = receiver.getSymbol()?.getDeclarations() ?? [];
384
+ if (declarations.some((d) => !Node.isImportSpecifier(d) && !Node.isNamespaceImport(d))) return null;
385
+ }
386
+ if (["parse", "safeParse", "parseAsync", "safeParseAsync", "encode", "decode"].includes(name)) return null;
387
+ if (["string", "number", "bigint", "array", "set", "date"].includes(name)) return name;
388
+ return "schema";
389
+ }
390
+ if (["parse", "safeParse", "parseAsync", "safeParseAsync", "encode", "decode"].includes(name)) return null;
391
+ if (name === "array" && schemaKind(receiver, seen, context)) return "array";
392
+ return schemaKind(receiver, seen, context);
393
+ }
394
+ function isSchemaReceiver(call, typeChecker, context = /* @__PURE__ */ new Map()) {
436
395
  const expr = call.getExpression();
437
- if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) return false;
396
+ if (!Node.isPropertyAccessExpression(expr)) return false;
438
397
  const receiver = expr.getExpression();
439
- try {
398
+ if (typeChecker) {
440
399
  const type = typeChecker.getTypeAtLocation(receiver);
441
- if (type.isAny()) return null;
442
- return type.getProperties().some((p) => p.getName() === "_zod");
443
- } catch {
444
- return null;
400
+ if (!type.isAny() && !type.isUnknown()) return type.getProperty("_zod") !== void 0;
401
+ }
402
+ return schemaKind(receiver, /* @__PURE__ */ new Set(), context) !== null;
403
+ }
404
+ function receiverKind(call, typeChecker, context = /* @__PURE__ */ new Map()) {
405
+ const expr = call.getExpression();
406
+ if (!Node.isPropertyAccessExpression(expr)) return null;
407
+ const receiver = expr.getExpression();
408
+ if (typeChecker) {
409
+ const type = typeChecker.getTypeAtLocation(receiver);
410
+ const def = type.getProperty("_zod")?.getTypeAtLocation(receiver).getProperty("def")?.getTypeAtLocation(receiver);
411
+ const kind = def?.getProperty("type")?.getTypeAtLocation(receiver).getLiteralValue();
412
+ if (typeof kind === "string") return kind;
445
413
  }
414
+ return schemaKind(receiver, /* @__PURE__ */ new Set(), context);
446
415
  }
447
- function transformChecks(file) {
416
+ function analyzeCallReceivers(calls, methods, typeChecker) {
417
+ const context = /* @__PURE__ */ new Map();
418
+ const receivers = /* @__PURE__ */ new Map();
419
+ for (const call of calls) {
420
+ const method = getMethodName(call);
421
+ if (!method || !methods.includes(method)) continue;
422
+ const obj = getCallObject(call);
423
+ if (!obj || isNamespaceCall(obj)) continue;
424
+ const schema = isSchemaReceiver(call, typeChecker, context);
425
+ const kind = schema && (method === "min" || method === "max") ? receiverKind(call, typeChecker, context) : null;
426
+ receivers.set(call, { schema, kind });
427
+ }
428
+ return receivers;
429
+ }
430
+ function transformChecks(file, typeChecker) {
448
431
  let count = 0;
449
432
  const calls = file.getDescendantsOfKind(SyntaxKind.CallExpression).reverse();
433
+ const receivers = analyzeCallReceivers(calls, [...ZOD_ONLY_CHECK_METHODS, ...AMBIGUOUS_CHECK_METHODS, "min", "max"], typeChecker);
450
434
  for (const call of calls) {
451
- if (call.wasForgotten()) continue;
435
+ if (call.wasForgotten() || !receivers.get(call)?.schema) continue;
452
436
  const method = getMethodName(call);
453
437
  if (!method) continue;
454
438
  const obj = getCallObject(call);
@@ -456,19 +440,21 @@ function transformChecks(file) {
456
440
  if (isNamespaceCall(obj)) continue;
457
441
  const args = call.getArguments().map((a) => a.getText());
458
442
  const argsStr = args.length > 0 ? args.join(", ") : "";
443
+ if (![...ZOD_ONLY_CHECK_METHODS, ...AMBIGUOUS_CHECK_METHODS, "min", "max"].includes(method)) continue;
459
444
  if (ZOD_ONLY_CHECK_METHODS.includes(method)) {
460
445
  call.replaceWithText(`${obj}.check(z.${method}(${argsStr}))`);
461
446
  count++;
462
447
  continue;
463
448
  }
464
- if (AMBIGUOUS_CHECK_METHODS.includes(method) && isLikelySchemaExpr(obj)) {
449
+ if (AMBIGUOUS_CHECK_METHODS.includes(method)) {
465
450
  call.replaceWithText(`${obj}.check(z.${method}(${argsStr}))`);
466
451
  count++;
467
452
  continue;
468
453
  }
469
- if ((method === "min" || method === "max") && isLikelySchemaExpr(obj)) {
470
- const isString = obj.includes("z.string");
471
- const checkName = isString ? STRING_RENAME[method] : NUMBER_RENAME[method];
454
+ if (method === "min" || method === "max") {
455
+ const kind = receivers.get(call)?.kind;
456
+ const checkName = kind === "string" || kind === "array" ? STRING_RENAME[method] : kind === "number" || kind === "bigint" ? NUMBER_RENAME[method] : kind === "set" ? method === "min" ? "minSize" : "maxSize" : null;
457
+ if (!checkName) continue;
472
458
  call.replaceWithText(`${obj}.check(z.${checkName}(${argsStr}))`);
473
459
  count++;
474
460
  continue;
@@ -479,32 +465,17 @@ function transformChecks(file) {
479
465
  function transformMethods(file, typeChecker) {
480
466
  let count = 0;
481
467
  const calls = file.getDescendantsOfKind(SyntaxKind.CallExpression).reverse();
468
+ const receivers = analyzeCallReceivers(calls, [...TOP_LEVEL_METHODS, ...RENAMED_METHODS.keys(), TRANSFORM_METHOD, "unwrap", ...CHECK_WRAP_METHODS], typeChecker);
482
469
  for (const call of calls) {
483
- if (call.wasForgotten()) continue;
470
+ if (call.wasForgotten() || !receivers.get(call)?.schema) continue;
484
471
  const method = getMethodName(call);
485
472
  if (!method) continue;
486
473
  const obj = getCallObject(call);
487
474
  if (!obj) continue;
488
475
  if (isNamespaceCall(obj)) continue;
489
476
  const args = call.getArguments().map((a) => a.getText());
490
- if (UNCONDITIONAL_TOP_LEVEL.includes(method)) {
491
- const argsStr = args.length > 0 ? `, ${args.join(", ")}` : "";
492
- call.replaceWithText(`z.${method}(${obj}${argsStr})`);
493
- count++;
494
- continue;
495
- }
496
- if (AMBIGUOUS_TOP_LEVEL.includes(method)) {
497
- let isSchema;
498
- if (typeChecker) {
499
- const typeResult = isZodSchemaByType(call, typeChecker);
500
- isSchema = typeResult === true || typeResult === null && isLikelySchemaExpr(obj);
501
- } else {
502
- isSchema = isLikelySchemaExpr(obj);
503
- }
504
- if (!isSchema && isSchemaVariable(call, obj.trim())) {
505
- isSchema = true;
506
- }
507
- if (!isSchema) continue;
477
+ if (![...TOP_LEVEL_METHODS, ...RENAMED_METHODS.keys(), TRANSFORM_METHOD, "unwrap", ...CHECK_WRAP_METHODS].includes(method)) continue;
478
+ if (TOP_LEVEL_METHODS.includes(method)) {
508
479
  const argsStr = args.length > 0 ? `, ${args.join(", ")}` : "";
509
480
  call.replaceWithText(`z.${method}(${obj}${argsStr})`);
510
481
  count++;
@@ -537,15 +508,17 @@ function transformMethods(file, typeChecker) {
537
508
  }
538
509
  return count;
539
510
  }
540
- function transformConstructorReplacements(file) {
511
+ function transformConstructorReplacements(file, typeChecker) {
541
512
  let count = 0;
542
513
  const calls = file.getDescendantsOfKind(SyntaxKind.CallExpression).reverse();
514
+ const receivers = analyzeCallReceivers(calls, [...Object.keys(CONSTRUCTOR_REPLACEMENTS), "datetime"], typeChecker);
543
515
  for (const call of calls) {
544
- if (call.wasForgotten()) continue;
516
+ if (call.wasForgotten() || !receivers.get(call)?.schema) continue;
545
517
  const method = getMethodName(call);
546
518
  if (!method) continue;
547
519
  const obj = getCallObject(call);
548
520
  if (!obj) continue;
521
+ if (!(method in CONSTRUCTOR_REPLACEMENTS) && method !== "datetime") continue;
549
522
  if (method in CONSTRUCTOR_REPLACEMENTS && call.getArguments().length === 0) {
550
523
  const match = obj.match(/^z\s*\.object\(([\s\S]*)\)$/);
551
524
  if (!match) continue;
@@ -590,9 +563,9 @@ function transformPropertyAccessors(file, typeChecker) {
590
563
  let isSchema;
591
564
  if (typeChecker) {
592
565
  const typeResult = isZodSchemaByTypePA(pa, typeChecker);
593
- isSchema = typeResult === true || typeResult === null && isLikelySchemaExpr(receiverText);
566
+ isSchema = typeResult === true || typeResult === null && schemaKind(receiver) !== null;
594
567
  } else {
595
- isSchema = isLikelySchemaExpr(receiverText);
568
+ isSchema = schemaKind(receiver) !== null;
596
569
  }
597
570
  if (!isSchema) continue;
598
571
  pa.replaceWithText(`${receiverText}.${replacement}`);
@@ -611,7 +584,7 @@ function findInternalPropertyAccess(file, typeChecker) {
611
584
  const receiverText = receiver.getText();
612
585
  if (NAMESPACE_IDENTIFIERS.has(receiverText.trim())) continue;
613
586
  if (receiverText.includes("._zod.def.") || receiverText.endsWith("._zod.def")) continue;
614
- if (isLikelySchemaExpr(receiverText)) continue;
587
+ if (schemaKind(receiver) !== null) continue;
615
588
  if (typeChecker) {
616
589
  const typeResult = isZodSchemaByTypePA(pa, typeChecker);
617
590
  if (typeResult === false) continue;
@@ -624,12 +597,14 @@ function findInternalPropertyAccess(file, typeChecker) {
624
597
  }
625
598
  return results;
626
599
  }
627
- function findObjectOnlyMethods(file) {
600
+ function findObjectOnlyMethods(file, typeChecker) {
628
601
  const results = [];
629
602
  const calls = file.getDescendantsOfKind(SyntaxKind.CallExpression);
603
+ const bounds = analyzeCallReceivers(calls, ["min", "max"], typeChecker);
630
604
  for (const call of calls) {
631
605
  const method = getMethodName(call);
632
- if (!method || !WARN_METHODS.includes(method)) continue;
606
+ if (!method) continue;
607
+ if (!WARN_METHODS.includes(method) && bounds.get(call)?.kind !== "date") continue;
633
608
  results.push({
634
609
  line: call.getStartLineNumber(),
635
610
  method,
@@ -665,42 +640,49 @@ function transformClassRefs(file) {
665
640
  let count = 0;
666
641
  const runtimeCoreImports = /* @__PURE__ */ new Set();
667
642
  const typeOnlyCoreImports = /* @__PURE__ */ new Set();
643
+ const replacements = [];
644
+ const queueReplacement = (node, newText) => {
645
+ replacements.push({ span: { start: node.getStart(), length: node.getWidth() }, newText });
646
+ };
668
647
  const propAccesses = file.getDescendantsOfKind(SyntaxKind.PropertyAccessExpression);
669
648
  for (const pa of propAccesses) {
670
649
  if (pa.wasForgotten()) continue;
671
650
  const text = pa.getText();
672
651
  const miniReplacement = MINI_CLASS_RENAMES[text];
673
652
  if (miniReplacement) {
674
- pa.replaceWithText(miniReplacement);
653
+ queueReplacement(pa, miniReplacement);
675
654
  count++;
676
655
  continue;
677
656
  }
678
657
  const coreReplacement = CORE_CLASS_RENAMES[text];
679
658
  if (coreReplacement) {
680
- pa.replaceWithText(coreReplacement);
659
+ queueReplacement(pa, coreReplacement);
681
660
  runtimeCoreImports.add(coreReplacement);
682
661
  count++;
683
662
  }
684
663
  }
664
+ if (replacements.length > 0) file.applyTextChanges(replacements);
665
+ replacements.length = 0;
685
666
  const qualNames = file.getDescendantsOfKind(SyntaxKind.QualifiedName);
686
667
  for (const qn of qualNames) {
687
668
  if (qn.wasForgotten()) continue;
688
669
  const text = qn.getText();
689
670
  const miniReplacement = MINI_CLASS_RENAMES[text];
690
671
  if (miniReplacement) {
691
- qn.replaceWithText(miniReplacement);
672
+ queueReplacement(qn, miniReplacement);
692
673
  count++;
693
674
  continue;
694
675
  }
695
676
  const coreReplacement = CORE_CLASS_RENAMES[text];
696
677
  if (coreReplacement) {
697
- qn.replaceWithText(coreReplacement);
678
+ queueReplacement(qn, coreReplacement);
698
679
  if (!runtimeCoreImports.has(coreReplacement)) {
699
680
  typeOnlyCoreImports.add(coreReplacement);
700
681
  }
701
682
  count++;
702
683
  }
703
684
  }
685
+ if (replacements.length > 0) file.applyTextChanges(replacements);
704
686
  const importTypes = file.getDescendantsOfKind(SyntaxKind.ImportType);
705
687
  for (const itn of importTypes) {
706
688
  if (itn.wasForgotten()) continue;
@@ -795,9 +777,9 @@ function transformFile(file, typeChecker) {
795
777
  let methods = 0;
796
778
  let propertyAccessors = 0;
797
779
  for (let i = 0; i < 10; i++) {
798
- const cr = transformConstructorReplacements(file);
780
+ const cr = transformConstructorReplacements(file, typeChecker);
799
781
  const w = transformWrappers(file, typeChecker);
800
- const c = transformChecks(file);
782
+ const c = transformChecks(file, typeChecker);
801
783
  const m = transformMethods(file, typeChecker);
802
784
  const pa = transformPropertyAccessors(file, typeChecker);
803
785
  constructorReplacements += cr;
@@ -808,7 +790,7 @@ function transformFile(file, typeChecker) {
808
790
  if (cr + w + c + m + pa === 0) break;
809
791
  }
810
792
  const classRefs = transformClassRefs(file);
811
- const objectOnlyWarnings = findObjectOnlyMethods(file);
793
+ const objectOnlyWarnings = findObjectOnlyMethods(file, typeChecker);
812
794
  const propertyAccessWarnings = findInternalPropertyAccess(file, typeChecker);
813
795
  ensureZImport(file);
814
796
  const imports = 0;
@@ -830,6 +812,9 @@ function transformCode(code, options) {
830
812
  try {
831
813
  const project = options?.project ?? new Project({
832
814
  useInMemoryFileSystem: true,
815
+ // Syntax-only mode needs local binding symbols, not standard-library types.
816
+ // Loading the libs for each file dominates alias resolution in this mode.
817
+ skipLoadingLibFiles: true,
833
818
  compilerOptions: { strict: false }
834
819
  });
835
820
  const filename = options?.filename ?? "transform.ts";
@@ -851,7 +836,7 @@ function transformCode(code, options) {
851
836
  return { code, changed: false };
852
837
  }
853
838
  }
854
- var WRAPPER_METHODS, NAMESPACE_IDENTIFIERS, ZOD_ONLY_CHECK_METHODS, AMBIGUOUS_CHECK_METHODS, STRING_RENAME, NUMBER_RENAME, UNCONDITIONAL_TOP_LEVEL, AMBIGUOUS_TOP_LEVEL, RENAMED_METHODS, TRANSFORM_METHOD, CHECK_WRAP_METHODS, CONSTRUCTOR_REPLACEMENTS, INTERNAL_PROPERTY_ACCESSORS, WARN_METHODS, MINI_CLASS_RENAMES, CORE_CLASS_RENAMES;
839
+ var WRAPPER_METHODS, NAMESPACE_IDENTIFIERS, ZOD_ONLY_CHECK_METHODS, AMBIGUOUS_CHECK_METHODS, STRING_RENAME, NUMBER_RENAME, TOP_LEVEL_METHODS, RENAMED_METHODS, TRANSFORM_METHOD, CHECK_WRAP_METHODS, CONSTRUCTOR_REPLACEMENTS, INTERNAL_PROPERTY_ACCESSORS, WARN_METHODS, MINI_CLASS_RENAMES, CORE_CLASS_RENAMES;
855
840
  var init_transforms = __esm({
856
841
  "../zod-to-mini/src/transforms.ts"() {
857
842
  WRAPPER_METHODS = ["optional", "nullable"];
@@ -897,8 +882,7 @@ var init_transforms = __esm({
897
882
  min: "gte",
898
883
  max: "lte"
899
884
  };
900
- UNCONDITIONAL_TOP_LEVEL = ["pipe", "brand", "parse", "safeParse"];
901
- AMBIGUOUS_TOP_LEVEL = ["partial", "extend", "catchall", "omit", "pick"];
885
+ TOP_LEVEL_METHODS = ["pipe", "brand", "parse", "safeParse", "partial", "extend", "catchall", "omit", "pick"];
902
886
  RENAMED_METHODS = /* @__PURE__ */ new Map([
903
887
  ["default", "_default"]
904
888
  ]);
@@ -1105,419 +1089,111 @@ function readCodecBrand(target) {
1105
1089
  const value = target[CODEC_BRAND_KEY];
1106
1090
  return typeof value === "string" ? value : void 0;
1107
1091
  }
1108
- var metadata = /* @__PURE__ */ new WeakMap();
1092
+ var METADATA = /* @__PURE__ */ Symbol.for("zodvex.metadata");
1109
1093
  var registryHelpers = {
1110
- getMetadata: (type) => metadata.get(type),
1111
- setMetadata: (type, meta) => metadata.set(type, meta)
1094
+ getMetadata: (type) => type?.[METADATA],
1095
+ setMetadata: (type, meta) => Object.defineProperty(type, METADATA, {
1096
+ value: meta,
1097
+ enumerable: false,
1098
+ writable: true,
1099
+ configurable: true
1100
+ })
1112
1101
  };
1113
- function convertEnumType(actualValidator) {
1114
- const entries = actualValidator._zod.def.entries;
1115
- const options = Object.keys(entries);
1116
- if (options && Array.isArray(options) && options.length > 0) {
1117
- const validLiterals = options.filter((opt) => opt !== void 0 && opt !== null).map((opt) => v.literal(opt));
1118
- if (validLiterals.length === 1) {
1119
- const [first] = validLiterals;
1120
- return first;
1121
- } else if (validLiterals.length >= 2) {
1122
- const [first, second, ...rest] = validLiterals;
1123
- return v.union(
1124
- first,
1125
- second,
1126
- ...rest
1127
- );
1128
- } else {
1129
- return v.any();
1130
- }
1131
- } else {
1132
- return v.any();
1133
- }
1134
- }
1135
- function convertNullableType(actualValidator, visited, zodToConvexInternal2) {
1136
- const innerSchema = actualValidator._zod.def.innerType;
1137
- if (innerSchema && innerSchema instanceof $ZodType) {
1138
- if (innerSchema instanceof $ZodOptional) {
1139
- const innerInnerSchema = innerSchema._zod.def.innerType;
1140
- const innerInnerValidator = zodToConvexInternal2(innerInnerSchema, visited);
1141
- return {
1142
- validator: v.union(innerInnerValidator, v.null()),
1143
- isOptional: true
1144
- // Mark as optional so it gets wrapped later
1145
- };
1146
- } else {
1147
- const innerValidator = zodToConvexInternal2(innerSchema, visited);
1148
- return {
1149
- validator: v.union(innerValidator, v.null()),
1150
- isOptional: false
1151
- };
1152
- }
1153
- } else {
1154
- return {
1155
- validator: v.any(),
1156
- isOptional: false
1157
- };
1158
- }
1102
+
1103
+ // src/internal/schema/id.ts
1104
+ function id(tableName) {
1105
+ const baseSchema = z.string().check(
1106
+ z.refine((val) => typeof val === "string" && val.length > 0, {
1107
+ message: `Invalid ID for table "${tableName}"`
1108
+ }),
1109
+ z.describe(`convexId:${tableName}`)
1110
+ );
1111
+ registryHelpers.setMetadata(baseSchema, {
1112
+ isConvexId: true,
1113
+ tableName
1114
+ });
1115
+ const branded = baseSchema;
1116
+ branded._tableName = tableName;
1117
+ return branded;
1159
1118
  }
1160
- function convertRecordType(actualValidator, visited, zodToConvexInternal2) {
1161
- let valueType = actualValidator._zod.def.valueType;
1162
- if (!valueType) {
1163
- valueType = actualValidator._zod.def.keyType;
1164
- }
1165
- if (valueType && valueType instanceof $ZodType) {
1166
- const isZodOptional = valueType instanceof $ZodOptional || valueType instanceof $ZodDefault || valueType instanceof $ZodDefault && valueType._zod.def.innerType instanceof $ZodOptional;
1167
- if (isZodOptional) {
1168
- let innerType;
1169
- let recordDefaultValue = void 0;
1170
- let recordHasDefault = false;
1171
- if (valueType instanceof $ZodDefault) {
1172
- recordHasDefault = true;
1173
- recordDefaultValue = valueType._zod.def.defaultValue;
1174
- const innerFromDefault = valueType._zod.def.innerType;
1175
- if (innerFromDefault instanceof $ZodOptional) {
1176
- innerType = innerFromDefault._zod.def.innerType;
1177
- } else {
1178
- innerType = innerFromDefault;
1179
- }
1180
- } else if (valueType instanceof $ZodOptional) {
1181
- innerType = valueType._zod.def.innerType;
1182
- } else {
1183
- innerType = valueType;
1184
- }
1185
- const innerConvex = zodToConvexInternal2(innerType, visited);
1186
- const unionValidator = v.union(innerConvex, v.null());
1187
- if (recordHasDefault) {
1188
- unionValidator._zodDefault = recordDefaultValue;
1189
- }
1190
- return v.record(v.string(), unionValidator);
1191
- } else {
1192
- return v.record(v.string(), zodToConvexInternal2(valueType, visited));
1193
- }
1194
- } else {
1195
- return v.record(v.string(), v.any());
1196
- }
1119
+
1120
+ // src/internal/schemaHelpers.ts
1121
+ function isZodUnion(schema) {
1122
+ return schema instanceof $ZodUnion || schema instanceof $ZodDiscriminatedUnion;
1197
1123
  }
1198
- function convertDiscriminatedUnionType(actualValidator, visited, zodToConvexInternal2) {
1199
- const options = actualValidator instanceof $ZodDiscriminatedUnion ? actualValidator._zod.def.options : (
1200
- // cast: fallback for non-standard discriminated union variants
1201
- actualValidator._zod?.def?.options
1202
- );
1203
- if (options) {
1204
- const opts = Array.isArray(options) ? options : Array.from(options);
1205
- if (opts.length >= 2) {
1206
- const convexOptions = opts.map((opt) => {
1207
- const branchVisited = new Set(visited);
1208
- return zodToConvexInternal2(opt, branchVisited);
1209
- });
1210
- const [first, second, ...rest] = convexOptions;
1211
- return v.union(
1212
- first,
1213
- second,
1214
- ...rest
1215
- );
1216
- } else {
1217
- return v.any();
1218
- }
1219
- } else {
1220
- return v.any();
1124
+ function getUnionOptions(schema) {
1125
+ if (schema instanceof $ZodUnion) {
1126
+ return schema._zod.def.options;
1221
1127
  }
1128
+ return schema._zod.def.options;
1222
1129
  }
1223
- function convertUnionType(actualValidator, visited, zodToConvexInternal2) {
1224
- const options = actualValidator._zod.def.options;
1225
- if (options && Array.isArray(options) && options.length > 0) {
1226
- if (options.length === 1) {
1227
- return zodToConvexInternal2(options[0], visited);
1228
- } else {
1229
- const convexOptions = options.map((opt) => {
1230
- const branchVisited = new Set(visited);
1231
- return zodToConvexInternal2(opt, branchVisited);
1232
- });
1233
- if (convexOptions.length >= 2) {
1234
- const [first, second, ...rest] = convexOptions;
1235
- return v.union(
1236
- first,
1237
- second,
1238
- ...rest
1239
- );
1240
- } else {
1241
- return v.any();
1242
- }
1243
- }
1244
- } else {
1245
- return v.any();
1130
+ function assertUnionOptions(options) {
1131
+ if (options.length < 2) {
1132
+ throw new Error(
1133
+ `z.union() requires at least 2 options, but received ${options.length}. This indicates an invalid union schema was passed to zodTable().`
1134
+ );
1246
1135
  }
1247
1136
  }
1248
- function isZid(schema) {
1249
- const metadata2 = registryHelpers.getMetadata(schema);
1250
- return metadata2?.isConvexId === true && metadata2?.tableName && typeof metadata2.tableName === "string";
1137
+ function createUnionFromOptions(options) {
1138
+ assertUnionOptions(options);
1139
+ return z.union(options);
1251
1140
  }
1252
-
1253
- // src/internal/mapping/core.ts
1254
- var convexValidatorCache = /* @__PURE__ */ new WeakMap();
1255
- function zodToConvexInternal(zodValidator, visited = /* @__PURE__ */ new Set()) {
1256
- if (!zodValidator) {
1257
- return v.any();
1258
- }
1259
- const cached = convexValidatorCache.get(zodValidator);
1260
- if (cached) {
1261
- return cached;
1262
- }
1263
- if (visited.has(zodValidator)) {
1264
- return v.any();
1265
- }
1266
- visited.add(zodValidator);
1267
- let actualValidator = zodValidator;
1268
- let isOptional = false;
1269
- let defaultValue = void 0;
1270
- let hasDefault = false;
1271
- if (zodValidator instanceof $ZodDefault) {
1272
- hasDefault = true;
1273
- defaultValue = zodValidator._zod.def.defaultValue;
1274
- actualValidator = zodValidator._zod.def.innerType;
1275
- }
1276
- if (actualValidator instanceof $ZodOptional) {
1277
- isOptional = true;
1278
- actualValidator = actualValidator._zod.def.innerType;
1279
- if (actualValidator instanceof $ZodDefault) {
1280
- hasDefault = true;
1281
- defaultValue = actualValidator._zod.def.defaultValue;
1282
- actualValidator = actualValidator._zod.def.innerType;
1283
- }
1284
- }
1285
- let convexValidator;
1286
- if (isZid(actualValidator)) {
1287
- const metadata2 = registryHelpers.getMetadata(actualValidator);
1288
- const tableName = metadata2?.tableName || "unknown";
1289
- convexValidator = v.id(tableName);
1290
- } else {
1291
- const defType = actualValidator._zod.def.type;
1292
- switch (defType) {
1293
- case "string":
1294
- convexValidator = v.string();
1295
- break;
1296
- case "number":
1297
- convexValidator = v.float64();
1298
- break;
1299
- case "bigint":
1300
- convexValidator = v.int64();
1301
- break;
1302
- case "boolean":
1303
- convexValidator = v.boolean();
1304
- break;
1305
- case "date":
1306
- convexValidator = v.float64();
1307
- break;
1308
- case "null":
1309
- convexValidator = v.null();
1310
- break;
1311
- case "nan":
1312
- convexValidator = v.float64();
1313
- break;
1314
- case "array": {
1315
- if (actualValidator instanceof $ZodArray) {
1316
- const element = actualValidator._zod.def.element;
1317
- convexValidator = v.array(zodToConvexInternal(element, visited));
1318
- } else {
1319
- convexValidator = v.array(v.any());
1320
- }
1321
- break;
1322
- }
1323
- case "object": {
1324
- if (actualValidator instanceof $ZodObject) {
1325
- const shape = actualValidator._zod.def.shape;
1326
- const convexShape = {};
1327
- for (const [key, value] of Object.entries(shape)) {
1328
- if (value && value instanceof $ZodType) {
1329
- convexShape[key] = zodToConvexInternal(value, visited);
1330
- }
1331
- }
1332
- convexValidator = v.object(convexShape);
1333
- } else {
1334
- convexValidator = v.object({});
1335
- }
1336
- break;
1337
- }
1338
- case "union": {
1339
- if (actualValidator instanceof $ZodUnion) {
1340
- convexValidator = convertUnionType(actualValidator, visited, zodToConvexInternal);
1341
- } else {
1342
- convexValidator = v.any();
1343
- }
1344
- break;
1345
- }
1346
- case "discriminatedUnion": {
1347
- convexValidator = convertDiscriminatedUnionType(
1348
- actualValidator,
1349
- visited,
1350
- zodToConvexInternal
1351
- );
1352
- break;
1353
- }
1354
- case "literal": {
1355
- if (actualValidator instanceof $ZodLiteral) {
1356
- const literalValues = actualValidator._zod.def.values;
1357
- const firstValue = literalValues.values().next().value;
1358
- if (firstValue !== void 0 && firstValue !== null) {
1359
- convexValidator = v.literal(firstValue);
1360
- } else {
1361
- convexValidator = v.any();
1362
- }
1363
- } else {
1364
- convexValidator = v.any();
1365
- }
1366
- break;
1367
- }
1368
- case "enum": {
1369
- if (actualValidator instanceof $ZodEnum) {
1370
- convexValidator = convertEnumType(actualValidator);
1371
- } else {
1372
- convexValidator = v.any();
1373
- }
1374
- break;
1375
- }
1376
- case "record": {
1377
- if (actualValidator instanceof $ZodRecord) {
1378
- convexValidator = convertRecordType(actualValidator, visited, zodToConvexInternal);
1379
- } else {
1380
- convexValidator = v.record(v.string(), v.any());
1381
- }
1382
- break;
1383
- }
1384
- case "transform":
1385
- case "pipe": {
1386
- if (actualValidator instanceof $ZodCodec) {
1387
- const inputSchema = actualValidator._zod.def.in;
1388
- if (inputSchema && inputSchema instanceof $ZodType) {
1389
- convexValidator = zodToConvexInternal(inputSchema, visited);
1390
- } else {
1391
- convexValidator = v.any();
1392
- }
1393
- } else {
1394
- const metadata2 = registryHelpers.getMetadata(actualValidator);
1395
- if (metadata2?.brand && metadata2?.originalSchema) {
1396
- convexValidator = zodToConvexInternal(metadata2.originalSchema, visited);
1397
- } else {
1398
- const inputSchema = actualValidator._zod?.def?.in;
1399
- if (inputSchema && inputSchema instanceof $ZodType) {
1400
- if (process.env.NODE_ENV !== "production") {
1401
- console.warn(
1402
- "[zodvex] z.transform() detected. Using input schema for Convex validation.\nTransforms are unidirectional - they work for parsing but not encoding.\nFor bidirectional transforms, use zx.codec() instead."
1403
- );
1404
- }
1405
- convexValidator = zodToConvexInternal(inputSchema, visited);
1406
- } else {
1407
- convexValidator = v.any();
1408
- }
1409
- }
1410
- }
1411
- break;
1412
- }
1413
- case "nullable": {
1414
- if (actualValidator instanceof $ZodNullable) {
1415
- const result = convertNullableType(actualValidator, visited, zodToConvexInternal);
1416
- convexValidator = result.validator;
1417
- if (result.isOptional) {
1418
- isOptional = true;
1419
- }
1420
- } else {
1421
- convexValidator = v.any();
1422
- }
1423
- break;
1424
- }
1425
- case "tuple": {
1426
- if (actualValidator instanceof $ZodTuple) {
1427
- const items = actualValidator._zod.def.items;
1428
- if (items && items.length > 0) {
1429
- const convexShape = {};
1430
- items.forEach((item, index) => {
1431
- convexShape[`_${index}`] = zodToConvexInternal(item, visited);
1432
- });
1433
- convexValidator = v.object(convexShape);
1434
- } else {
1435
- convexValidator = v.object({});
1436
- }
1437
- } else {
1438
- convexValidator = v.object({});
1439
- }
1440
- break;
1441
- }
1442
- case "lazy": {
1443
- if (actualValidator instanceof $ZodLazy) {
1444
- try {
1445
- const getter = actualValidator._zod.def.getter;
1446
- if (getter) {
1447
- const resolvedSchema = getter();
1448
- if (resolvedSchema && resolvedSchema instanceof $ZodType) {
1449
- convexValidator = zodToConvexInternal(resolvedSchema, visited);
1450
- } else {
1451
- convexValidator = v.any();
1452
- }
1453
- } else {
1454
- convexValidator = v.any();
1455
- }
1456
- } catch {
1457
- convexValidator = v.any();
1458
- }
1459
- } else {
1460
- convexValidator = v.any();
1461
- }
1462
- break;
1463
- }
1464
- case "any":
1465
- convexValidator = v.any();
1466
- break;
1467
- case "unknown":
1468
- convexValidator = v.any();
1469
- break;
1470
- case "undefined":
1471
- case "void":
1472
- case "never":
1473
- convexValidator = v.any();
1474
- break;
1475
- case "intersection":
1476
- convexValidator = v.any();
1477
- break;
1478
- case "optional": {
1479
- const innerType = actualValidator._zod?.def?.innerType;
1480
- if (innerType && innerType instanceof $ZodType) {
1481
- convexValidator = zodToConvexInternal(innerType, visited);
1482
- isOptional = true;
1483
- } else {
1484
- convexValidator = v.any();
1485
- isOptional = true;
1486
- }
1487
- break;
1141
+ function addSystemFields(tableName, schema) {
1142
+ if (isZodUnion(schema)) {
1143
+ const originalOptions = getUnionOptions(schema);
1144
+ const extendedOptions = originalOptions.map((variant) => {
1145
+ if (variant instanceof $ZodObject) {
1146
+ const newShape = {
1147
+ ...variant._zod.def.shape,
1148
+ _id: id(tableName),
1149
+ _creationTime: z.number()
1150
+ };
1151
+ return clone(variant, { ...variant._zod.def, shape: newShape });
1488
1152
  }
1489
- default:
1490
- if (process.env.NODE_ENV !== "production") {
1491
- console.warn(
1492
- `[zodvex] Unrecognized Zod type "${defType}" encountered. Falling back to v.any().`,
1493
- "Schema:",
1494
- actualValidator
1495
- );
1496
- }
1497
- convexValidator = v.any();
1498
- break;
1499
- }
1153
+ return variant;
1154
+ });
1155
+ return createUnionFromOptions(extendedOptions);
1500
1156
  }
1501
- const finalValidator = isOptional || hasDefault ? v.optional(convexValidator) : convexValidator;
1502
- if (hasDefault && typeof finalValidator === "object" && finalValidator !== null) {
1503
- finalValidator._zodDefault = defaultValue;
1157
+ if (schema instanceof $ZodObject) {
1158
+ const newShape = { ...schema._zod.def.shape, _id: id(tableName), _creationTime: z.number() };
1159
+ return clone(schema, { ...schema._zod.def, shape: newShape });
1504
1160
  }
1505
- convexValidatorCache.set(zodValidator, finalValidator);
1506
- return finalValidator;
1161
+ return schema;
1507
1162
  }
1508
- function zodToConvex(zod) {
1509
- if (typeof zod === "object" && zod !== null && !(zod instanceof $ZodType)) {
1510
- return zodToConvexFields(zod);
1163
+
1164
+ // src/internal/modelSchemaBundle.ts
1165
+ function ensureOptional(schema) {
1166
+ if (schema instanceof $ZodOptional) return schema;
1167
+ return new $ZodOptional({ type: "optional", innerType: schema });
1168
+ }
1169
+ function createPartialShape(shape) {
1170
+ const partialShape = {};
1171
+ for (const [key, value] of Object.entries(shape)) {
1172
+ partialShape[key] = ensureOptional(value);
1511
1173
  }
1512
- return zodToConvexInternal(zod);
1174
+ return partialShape;
1175
+ }
1176
+ function createUpdateObjectSchema(name, shape) {
1177
+ return z.object({
1178
+ _id: id(name),
1179
+ _creationTime: z.optional(z.number()),
1180
+ ...createPartialShape(shape)
1181
+ });
1513
1182
  }
1514
- function zodToConvexFields(zod) {
1515
- const fields = zod instanceof $ZodObject ? zod._zod.def.shape : zod;
1516
- const result = {};
1517
- for (const [key, value] of Object.entries(fields)) {
1518
- result[key] = zodToConvexInternal(value);
1183
+ function createSchemaUpdateSchema(name, inputSchema) {
1184
+ if (isZodUnion(inputSchema)) {
1185
+ const updateOptions = getUnionOptions(inputSchema).map((variant) => {
1186
+ if (variant instanceof $ZodObject) {
1187
+ return createUpdateObjectSchema(name, variant._zod.def.shape);
1188
+ }
1189
+ return variant;
1190
+ });
1191
+ return createUnionFromOptions(updateOptions);
1519
1192
  }
1520
- return result;
1193
+ if (inputSchema instanceof $ZodObject) {
1194
+ return createUpdateObjectSchema(name, inputSchema._zod.def.shape);
1195
+ }
1196
+ return inputSchema;
1521
1197
  }
1522
1198
 
1523
1199
  // src/internal/codec.ts
@@ -1525,35 +1201,36 @@ function zodvexCodec(wire, runtime, transforms) {
1525
1201
  return z.codec(wire, runtime, transforms);
1526
1202
  }
1527
1203
 
1204
+ // src/internal/zxDateBrand.ts
1205
+ var ZX_DATE_BRAND = /* @__PURE__ */ Symbol.for("zodvex.zxDate");
1206
+ function brandZxDate(codec2) {
1207
+ codec2[ZX_DATE_BRAND] = true;
1208
+ const def = codec2._zod?.def;
1209
+ if (def) def[ZX_DATE_BRAND] = true;
1210
+ return codec2;
1211
+ }
1212
+ function isZxDateCodec(schema) {
1213
+ if (!schema || typeof schema !== "object") return false;
1214
+ const s = schema;
1215
+ return s[ZX_DATE_BRAND] === true || s._zod?.def?.[ZX_DATE_BRAND] === true;
1216
+ }
1217
+
1528
1218
  // src/internal/zx.ts
1529
1219
  function date() {
1530
- return zodvexCodec(
1531
- z.number(),
1532
- // Wire: timestamp
1533
- z.custom((val) => val instanceof Date, {
1534
- message: "Expected Date instance"
1535
- }),
1536
- {
1537
- decode: (timestamp) => new Date(timestamp),
1538
- encode: (date2) => date2.getTime()
1539
- }
1220
+ return brandZxDate(
1221
+ zodvexCodec(
1222
+ z.number(),
1223
+ // Wire: timestamp
1224
+ z.custom((val) => val instanceof Date, {
1225
+ message: "Expected Date instance"
1226
+ }),
1227
+ {
1228
+ decode: (timestamp) => new Date(timestamp),
1229
+ encode: (date2) => date2.getTime()
1230
+ }
1231
+ )
1540
1232
  );
1541
1233
  }
1542
- function id(tableName) {
1543
- const baseSchema = z.string().check(
1544
- z.refine((val) => typeof val === "string" && val.length > 0, {
1545
- message: `Invalid ID for table "${tableName}"`
1546
- }),
1547
- z.describe(`convexId:${tableName}`)
1548
- );
1549
- registryHelpers.setMetadata(baseSchema, {
1550
- isConvexId: true,
1551
- tableName
1552
- });
1553
- const branded = baseSchema;
1554
- branded._tableName = tableName;
1555
- return branded;
1556
- }
1557
1234
  function codec(wire, runtime, transforms, opts) {
1558
1235
  const built = zodvexCodec(wire, runtime, transforms);
1559
1236
  if (opts?.brand) attachCodecBrand(built, opts.brand);
@@ -1679,108 +1356,83 @@ var zx = {
1679
1356
  * user-supplied union. Cached per-model.
1680
1357
  * @see {@link base}
1681
1358
  */
1682
- base,
1683
- /**
1684
- * Doc schema: model fields + _id + _creationTime
1685
- * @see {@link doc}
1686
- */
1687
- doc,
1688
- /**
1689
- * Update schema: _id required, all other fields optional
1690
- * @see {@link update}
1691
- */
1692
- update,
1693
- /**
1694
- * Doc array schema: z.array(doc(model))
1695
- * @see {@link docArray}
1696
- */
1697
- docArray
1698
- };
1699
-
1700
- // src/internal/schemaHelpers.ts
1701
- function isZodUnion(schema) {
1702
- return schema instanceof $ZodUnion || schema instanceof $ZodDiscriminatedUnion;
1703
- }
1704
- function getUnionOptions(schema) {
1705
- if (schema instanceof $ZodUnion) {
1706
- return schema._zod.def.options;
1707
- }
1708
- return schema._zod.def.options;
1709
- }
1710
- function assertUnionOptions(options) {
1711
- if (options.length < 2) {
1712
- throw new Error(
1713
- `z.union() requires at least 2 options, but received ${options.length}. This indicates an invalid union schema was passed to zodTable().`
1714
- );
1715
- }
1716
- }
1717
- function createUnionFromOptions(options) {
1718
- assertUnionOptions(options);
1719
- return z.union(options);
1720
- }
1721
- function addSystemFields(tableName, schema) {
1722
- if (isZodUnion(schema)) {
1723
- const originalOptions = getUnionOptions(schema);
1724
- const extendedOptions = originalOptions.map((variant) => {
1725
- if (variant instanceof $ZodObject) {
1726
- const newShape = {
1727
- ...variant._zod.def.shape,
1728
- _id: zx.id(tableName),
1729
- _creationTime: z.number()
1730
- };
1731
- return clone(variant, { ...variant._zod.def, shape: newShape });
1732
- }
1733
- return variant;
1734
- });
1735
- return createUnionFromOptions(extendedOptions);
1736
- }
1737
- if (schema instanceof $ZodObject) {
1738
- const newShape = { ...schema._zod.def.shape, _id: zx.id(tableName), _creationTime: z.number() };
1739
- return clone(schema, { ...schema._zod.def, shape: newShape });
1740
- }
1741
- return schema;
1742
- }
1359
+ base,
1360
+ /**
1361
+ * Doc schema: model fields + _id + _creationTime
1362
+ * @see {@link doc}
1363
+ */
1364
+ doc,
1365
+ /**
1366
+ * Update schema: _id required, all other fields optional
1367
+ * @see {@link update}
1368
+ */
1369
+ update,
1370
+ /**
1371
+ * Doc array schema: z.array(doc(model))
1372
+ * @see {@link docArray}
1373
+ */
1374
+ docArray
1375
+ };
1376
+ function buildHooksSource(aliases) {
1377
+ return `
1378
+ import { pathToFileURL } from 'node:url';
1743
1379
 
1744
- // src/internal/modelSchemaBundle.ts
1745
- function ensureOptional(schema) {
1746
- if (schema instanceof $ZodOptional) return schema;
1747
- return new $ZodOptional({ type: "optional", innerType: schema });
1748
- }
1749
- function createPartialShape(shape) {
1750
- const partialShape = {};
1751
- for (const [key, value] of Object.entries(shape)) {
1752
- partialShape[key] = ensureOptional(value);
1753
- }
1754
- return partialShape;
1755
- }
1756
- function createUpdateObjectSchema(name, shape) {
1757
- return z.object({
1758
- _id: zx.id(name),
1759
- _creationTime: z.optional(z.number()),
1760
- ...createPartialShape(shape)
1761
- });
1762
- }
1763
- function createSchemaUpdateSchema(name, inputSchema) {
1764
- if (isZodUnion(inputSchema)) {
1765
- const updateOptions = getUnionOptions(inputSchema).map((variant) => {
1766
- if (variant instanceof $ZodObject) {
1767
- return createUpdateObjectSchema(name, variant._zod.def.shape);
1380
+ const EXT_CANDIDATES = ['.ts', '.tsx', '.mts', '.js', '.mjs', '.jsx', '/index.ts', '/index.js'];
1381
+
1382
+ // tsconfig path aliases compiled by loadTsconfigAliases (#99). Bun resolves
1383
+ // these natively; Node's ESM loader needs them replayed here.
1384
+ const ALIASES = ${JSON.stringify(aliases)};
1385
+
1386
+ function aliasCandidates(specifier) {
1387
+ const out = [];
1388
+ for (const a of ALIASES) {
1389
+ if (a.star) {
1390
+ if (
1391
+ specifier.length >= a.prefix.length + a.suffix.length &&
1392
+ specifier.startsWith(a.prefix) &&
1393
+ specifier.endsWith(a.suffix)
1394
+ ) {
1395
+ const captured = specifier.slice(a.prefix.length, specifier.length - a.suffix.length);
1396
+ for (const t of a.targets) out.push(t.prefix + captured + t.suffix);
1768
1397
  }
1769
- return variant;
1770
- });
1771
- return createUnionFromOptions(updateOptions);
1772
- }
1773
- if (inputSchema instanceof $ZodObject) {
1774
- return createUpdateObjectSchema(name, inputSchema._zod.def.shape);
1398
+ } else if (specifier === a.prefix) {
1399
+ for (const t of a.targets) out.push(t.prefix);
1400
+ }
1775
1401
  }
1776
- return inputSchema;
1402
+ return out;
1777
1403
  }
1778
- var HOOKS_SOURCE = `
1779
- export function resolve(specifier, context, nextResolve) {
1404
+
1405
+ export async function resolve(specifier, context, nextResolve) {
1780
1406
  if (/_generated\\/api(\\.[mc]?[jt]sx?)?$/.test(specifier)) {
1781
1407
  return { shortCircuit: true, url: 'zodvex-stub://api' };
1782
1408
  }
1783
- return nextResolve(specifier, context);
1409
+ try {
1410
+ return await nextResolve(specifier, context);
1411
+ } catch (err) {
1412
+ // tsconfig path aliases (e.g. '@/convex/...'). Try each mapped absolute
1413
+ // path as-is, then with the usual extension/index candidates.
1414
+ for (const base of aliasCandidates(specifier)) {
1415
+ for (const ext of ['', ...EXT_CANDIDATES]) {
1416
+ try {
1417
+ return await nextResolve(pathToFileURL(base + ext).href, context);
1418
+ } catch {}
1419
+ }
1420
+ }
1421
+ // Convex code uses extensionless relative imports (bundler resolution).
1422
+ // Bun resolves those natively; Node's ESM loader does not \u2014 retry with
1423
+ // the usual extension candidates before giving up.
1424
+ if (
1425
+ (specifier.startsWith('./') || specifier.startsWith('../')) &&
1426
+ !/\\.[cm]?[jt]sx?$/.test(specifier)
1427
+ ) {
1428
+ for (const ext of EXT_CANDIDATES) {
1429
+ try {
1430
+ return await nextResolve(specifier + ext, context);
1431
+ } catch {}
1432
+ }
1433
+ }
1434
+ throw err;
1435
+ }
1784
1436
  }
1785
1437
 
1786
1438
  export function load(url, context, nextLoad) {
@@ -1810,13 +1462,18 @@ export function load(url, context, nextLoad) {
1810
1462
  return nextLoad(url, context);
1811
1463
  }
1812
1464
  `;
1465
+ }
1813
1466
  var hooksRegistered = false;
1814
- function registerDiscoveryHooks() {
1467
+ function registerDiscoveryHooks(aliases = []) {
1815
1468
  if (hooksRegistered) return true;
1816
1469
  try {
1817
- const { register } = __require("module");
1470
+ const nodeModule = typeof process.getBuiltinModule === "function" ? process.getBuiltinModule("node:module") : (
1471
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
1472
+ __require("module")
1473
+ );
1474
+ const { register } = nodeModule;
1818
1475
  if (typeof register !== "function") return false;
1819
- register(`data:text/javascript,${encodeURIComponent(HOOKS_SOURCE)}`);
1476
+ register(`data:text/javascript,${encodeURIComponent(buildHooksSource(aliases))}`);
1820
1477
  hooksRegistered = true;
1821
1478
  return true;
1822
1479
  } catch {
@@ -1841,22 +1498,22 @@ export const components = p;
1841
1498
  export const httpRouter = p;
1842
1499
  `;
1843
1500
  function writeGeneratedStubs(convexDir2) {
1844
- const generatedDir = path3.join(convexDir2, "_generated");
1845
- const apiPath = path3.join(generatedDir, "api.ts");
1501
+ const generatedDir = path4.join(convexDir2, "_generated");
1502
+ const apiPath = path4.join(generatedDir, "api.ts");
1846
1503
  let original;
1847
1504
  try {
1848
- original = fs2.readFileSync(apiPath, "utf8");
1505
+ original = fs3.readFileSync(apiPath, "utf8");
1849
1506
  } catch {
1850
1507
  original = null;
1851
1508
  }
1852
- fs2.mkdirSync(generatedDir, { recursive: true });
1853
- fs2.writeFileSync(apiPath, PROXY_STUB_API);
1509
+ fs3.mkdirSync(generatedDir, { recursive: true });
1510
+ fs3.writeFileSync(apiPath, PROXY_STUB_API);
1854
1511
  return () => {
1855
1512
  if (original !== null) {
1856
- fs2.writeFileSync(apiPath, original);
1513
+ fs3.writeFileSync(apiPath, original);
1857
1514
  } else {
1858
1515
  try {
1859
- fs2.unlinkSync(apiPath);
1516
+ fs3.unlinkSync(apiPath);
1860
1517
  } catch {
1861
1518
  }
1862
1519
  }
@@ -1868,8 +1525,7 @@ function findCodec(schema) {
1868
1525
  let current = schema;
1869
1526
  for (let i = 0; i < 10; i++) {
1870
1527
  if (current instanceof $ZodCodec) {
1871
- const isZxDate = current._zod.def.in instanceof $ZodNumber && current._zod.def.out instanceof $ZodCustom;
1872
- if (isZxDate) return void 0;
1528
+ if (isZxDateCodec(current)) return void 0;
1873
1529
  return current;
1874
1530
  }
1875
1531
  if (current instanceof $ZodOptional || current instanceof $ZodNullable) {
@@ -1880,28 +1536,136 @@ function findCodec(schema) {
1880
1536
  }
1881
1537
  return void 0;
1882
1538
  }
1883
-
1884
- // src/public/codegen/discover.ts
1885
- function schemaSubtreeHasCodec(schema, seen = /* @__PURE__ */ new Set()) {
1886
- if (seen.has(schema)) return false;
1887
- seen.add(schema);
1888
- if (schema instanceof $ZodCodec) return true;
1889
- const def = schema._zod?.def;
1890
- if (!def) return false;
1891
- for (const value of Object.values(def)) {
1892
- if (value instanceof $ZodType && schemaSubtreeHasCodec(value, seen)) return true;
1893
- if (Array.isArray(value)) {
1894
- for (const item of value) {
1895
- if (item instanceof $ZodType && schemaSubtreeHasCodec(item, seen)) return true;
1539
+ function stripJsonComments(input) {
1540
+ let out = "";
1541
+ let inString = false;
1542
+ let inLine = false;
1543
+ let inBlock = false;
1544
+ for (let i = 0; i < input.length; i++) {
1545
+ const ch = input[i];
1546
+ const next = input[i + 1];
1547
+ if (inLine) {
1548
+ if (ch === "\n") {
1549
+ inLine = false;
1550
+ out += ch;
1551
+ }
1552
+ continue;
1553
+ }
1554
+ if (inBlock) {
1555
+ if (ch === "*" && next === "/") {
1556
+ inBlock = false;
1557
+ i++;
1558
+ }
1559
+ continue;
1560
+ }
1561
+ if (inString) {
1562
+ out += ch;
1563
+ if (ch === "\\") {
1564
+ out += next ?? "";
1565
+ i++;
1566
+ } else if (ch === '"') {
1567
+ inString = false;
1896
1568
  }
1897
- } else if (value && typeof value === "object") {
1898
- for (const item of Object.values(value)) {
1899
- if (item instanceof $ZodType && schemaSubtreeHasCodec(item, seen)) return true;
1569
+ continue;
1570
+ }
1571
+ if (ch === '"') {
1572
+ inString = true;
1573
+ out += ch;
1574
+ continue;
1575
+ }
1576
+ if (ch === "/" && next === "/") {
1577
+ inLine = true;
1578
+ i++;
1579
+ continue;
1580
+ }
1581
+ if (ch === "/" && next === "*") {
1582
+ inBlock = true;
1583
+ i++;
1584
+ continue;
1585
+ }
1586
+ out += ch;
1587
+ }
1588
+ return out.replace(/,\s*([}\]])/g, "$1");
1589
+ }
1590
+ function readTsconfig(configPath) {
1591
+ try {
1592
+ const raw = fs3.readFileSync(configPath, "utf8");
1593
+ return JSON.parse(stripJsonComments(raw));
1594
+ } catch {
1595
+ return null;
1596
+ }
1597
+ }
1598
+ function resolvePathsFromConfig(configPath, seen) {
1599
+ const abs = path4.resolve(configPath);
1600
+ if (seen.has(abs)) return null;
1601
+ seen.add(abs);
1602
+ const config = readTsconfig(abs);
1603
+ if (!config) return null;
1604
+ const dir = path4.dirname(abs);
1605
+ const own = config.compilerOptions?.paths;
1606
+ if (own) {
1607
+ const baseUrl = config.compilerOptions?.baseUrl;
1608
+ return { paths: own, baseDir: baseUrl ? path4.resolve(dir, baseUrl) : dir };
1609
+ }
1610
+ const parents = config.extends == null ? [] : [].concat(config.extends);
1611
+ for (const ref of parents) {
1612
+ if (!ref.startsWith(".") && !path4.isAbsolute(ref)) continue;
1613
+ let target = path4.resolve(dir, ref);
1614
+ if (!target.endsWith(".json")) target += ".json";
1615
+ const found = resolvePathsFromConfig(target, seen);
1616
+ if (found) {
1617
+ const childBase = config.compilerOptions?.baseUrl;
1618
+ return childBase ? { paths: found.paths, baseDir: path4.resolve(dir, childBase) } : found;
1619
+ }
1620
+ }
1621
+ return null;
1622
+ }
1623
+ function compileAliases(paths, baseDir) {
1624
+ const entries = [];
1625
+ for (const [pattern, targets] of Object.entries(paths)) {
1626
+ const starIdx = pattern.indexOf("*");
1627
+ const star = starIdx !== -1;
1628
+ const prefix = star ? pattern.slice(0, starIdx) : pattern;
1629
+ const suffix = star ? pattern.slice(starIdx + 1) : "";
1630
+ const compiled = targets.map((t) => {
1631
+ const tStar = t.indexOf("*");
1632
+ const tPrefix = path4.resolve(baseDir, tStar === -1 ? t : t.slice(0, tStar));
1633
+ const sep = tStar !== -1 && t.slice(0, tStar).endsWith("/") ? path4.sep : "";
1634
+ return {
1635
+ prefix: tPrefix + sep,
1636
+ suffix: tStar === -1 ? "" : t.slice(tStar + 1)
1637
+ };
1638
+ });
1639
+ entries.push({ prefix, suffix, star, targets: compiled });
1640
+ }
1641
+ return entries;
1642
+ }
1643
+ function loadTsconfigAliases(convexDir2) {
1644
+ const entries = [];
1645
+ const seenPatterns = /* @__PURE__ */ new Set();
1646
+ let dir = path4.resolve(convexDir2);
1647
+ for (let depth = 0; depth < 10; depth++) {
1648
+ const configPath = path4.join(dir, "tsconfig.json");
1649
+ if (fs3.existsSync(configPath)) {
1650
+ const found = resolvePathsFromConfig(configPath, /* @__PURE__ */ new Set());
1651
+ if (found) {
1652
+ for (const entry of compileAliases(found.paths, found.baseDir)) {
1653
+ const key = `${entry.prefix}*${entry.suffix}`;
1654
+ if (!seenPatterns.has(key)) {
1655
+ seenPatterns.add(key);
1656
+ entries.push(entry);
1657
+ }
1658
+ }
1900
1659
  }
1901
1660
  }
1661
+ const parent = path4.dirname(dir);
1662
+ if (parent === dir) break;
1663
+ dir = parent;
1902
1664
  }
1903
- return false;
1665
+ return entries;
1904
1666
  }
1667
+
1668
+ // src/public/codegen/discover.ts
1905
1669
  function walkSchemaRecursive(schema, accessPath, visited, seenCodecs, results) {
1906
1670
  if (visited.has(schema)) return;
1907
1671
  visited.add(schema);
@@ -2043,7 +1807,7 @@ async function discoverModules(convexDir2) {
2043
1807
  const models = [];
2044
1808
  const functions = [];
2045
1809
  const codecs = [];
2046
- registerDiscoveryHooks();
1810
+ registerDiscoveryHooks(loadTsconfigAliases(convexDir2));
2047
1811
  const cleanupStubs = writeGeneratedStubs(convexDir2);
2048
1812
  const files = globSync(["**/*.{ts,js}"], {
2049
1813
  cwd: convexDir2,
@@ -2060,22 +1824,18 @@ async function discoverModules(convexDir2) {
2060
1824
  "convex.config.ts",
2061
1825
  "convex.config.js",
2062
1826
  "crons.ts",
2063
- "crons.js",
2064
- // schema.{ts,js} never exports queries/mutations/codecs — and under
2065
- // the lazy-tables shape it imports from `_zodvex/tables`, which is
2066
- // generated DURING this same codegen pass. Importing it during
2067
- // discovery would create an ordering loop on first run; ignore it.
2068
- "schema.ts",
2069
- "schema.js"
1827
+ "crons.js"
2070
1828
  ]
2071
1829
  }).sort();
1830
+ const failedImports = [];
2072
1831
  try {
2073
1832
  for (const file of files) {
2074
- const absPath = path3.resolve(convexDir2, file);
1833
+ const absPath = path4.resolve(convexDir2, file);
2075
1834
  let moduleExports;
2076
1835
  try {
2077
1836
  moduleExports = await import(absPath);
2078
1837
  } catch (err) {
1838
+ failedImports.push({ file, message: err.message });
2079
1839
  console.warn(`[zodvex] Warning: Failed to import ${file}:`, err.message);
2080
1840
  continue;
2081
1841
  }
@@ -2096,8 +1856,7 @@ async function discoverModules(convexDir2) {
2096
1856
  tableName: meta.tableName,
2097
1857
  sourceFile: file,
2098
1858
  schemas: meta.schemas,
2099
- _modelRef: meta.schemas ? void 0 : value,
2100
- _liveModel: value
1859
+ _modelRef: meta.schemas ? void 0 : value
2101
1860
  };
2102
1861
  }
2103
1862
  } else {
@@ -2106,8 +1865,7 @@ async function discoverModules(convexDir2) {
2106
1865
  tableName: meta.tableName,
2107
1866
  sourceFile: file,
2108
1867
  schemas: meta.schemas,
2109
- _modelRef: meta.schemas ? void 0 : value,
2110
- _liveModel: value
1868
+ _modelRef: meta.schemas ? void 0 : value
2111
1869
  });
2112
1870
  }
2113
1871
  } else if (meta.type === "function") {
@@ -2121,8 +1879,7 @@ async function discoverModules(convexDir2) {
2121
1879
  }
2122
1880
  }
2123
1881
  if (value instanceof $ZodCodec) {
2124
- const isZxDate = value._zod.def.in instanceof $ZodNumber && value._zod.def.out instanceof $ZodCustom;
2125
- if (!isZxDate) {
1882
+ if (!isZxDateCodec(value)) {
2126
1883
  if (!codecs.some((c) => c.schema === value)) {
2127
1884
  codecs.push({
2128
1885
  exportName,
@@ -2145,34 +1902,21 @@ async function discoverModules(convexDir2) {
2145
1902
  modelCodecs.push(...found);
2146
1903
  }
2147
1904
  const functionCodecs = walkFunctionCodecs(functions);
1905
+ if (failedImports.length > 0 && !process.env.ZODVEX_ALLOW_IMPORT_FAILURES) {
1906
+ const shown = failedImports.slice(0, 10).map((f) => ` - ${f.file}: ${f.message}`).join("\n");
1907
+ const more = failedImports.length > 10 ? `
1908
+ \u2026 and ${failedImports.length - 10} more` : "";
1909
+ throw new Error(
1910
+ `[zodvex] ${failedImports.length} module(s) failed to import during discovery \u2014 the generated registry would be incomplete:
1911
+ ${shown}${more}
1912
+ Common causes: Node < 22.18 (no native TypeScript type stripping \u2014 use Bun or upgrade Node), or an import style the discovery resolver does not handle. tsconfig path aliases and extensionless relative imports are supported. Set ZODVEX_ALLOW_IMPORT_FAILURES=1 to generate anyway (skipping the failed modules).`
1913
+ );
1914
+ }
2148
1915
  return { models, functions, codecs, modelCodecs, functionCodecs };
2149
1916
  } finally {
2150
1917
  cleanupStubs();
2151
1918
  }
2152
1919
  }
2153
- function getZodModelMeta(model) {
2154
- const meta = readMeta(model);
2155
- if (!meta || meta.type !== "model") {
2156
- throw new Error(`Model '${model.name}' is missing zodvex model metadata.`);
2157
- }
2158
- return meta;
2159
- }
2160
- function tableFromModel(model) {
2161
- const meta = getZodModelMeta(model);
2162
- const usesBaseSchema = meta.definitionSource === "schema" || meta.definitionSource == null && Object.keys(model.fields).length === 0;
2163
- let table = usesBaseSchema ? defineTable(zodToConvex(zx.base(model))) : defineTable(zodToConvexFields(model.fields));
2164
- for (const [indexName, indexFields] of Object.entries(model.indexes)) {
2165
- const userFields = indexFields.filter((f) => f !== "_creationTime");
2166
- table = table.index(indexName, userFields);
2167
- }
2168
- for (const [indexName, config] of Object.entries(model.searchIndexes)) {
2169
- table = table.searchIndex(indexName, config);
2170
- }
2171
- for (const [indexName, config] of Object.entries(model.vectorIndexes)) {
2172
- table = table.vectorIndex(indexName, config);
2173
- }
2174
- return table;
2175
- }
2176
1920
 
2177
1921
  // src/public/codegen/zodToSource.ts
2178
1922
  function zodToSource(schema, ctx) {
@@ -2187,10 +1931,10 @@ function zodToSource(schema, ctx) {
2187
1931
  if (schema instanceof $ZodString) {
2188
1932
  const tableName = schema._tableName ?? (schema.description?.startsWith("convexId:") ? schema.description.slice("convexId:".length) : void 0);
2189
1933
  if (tableName) {
2190
- return `zx.id("${tableName}")`;
1934
+ return `zx.id(${JSON.stringify(tableName)})`;
2191
1935
  }
2192
1936
  }
2193
- if (schema instanceof $ZodCodec && schema._zod.def.in instanceof $ZodNumber && schema._zod.def.out instanceof $ZodCustom) {
1937
+ if (schema instanceof $ZodCodec && isZxDateCodec(schema)) {
2194
1938
  return "zx.date()";
2195
1939
  }
2196
1940
  if (schema instanceof $ZodCodec) {
@@ -2216,7 +1960,10 @@ function zodToSource(schema, ctx) {
2216
1960
  if (schema instanceof $ZodAny) return "z.any()";
2217
1961
  if (schema instanceof $ZodObject) {
2218
1962
  const shape = schema._zod.def.shape;
2219
- const fields = Object.entries(shape).map(([key, value]) => `${key}: ${zodToSource(value, ctx)}`).join(", ");
1963
+ const fields = Object.entries(shape).map(([key, value]) => {
1964
+ const property = key === "__proto__" ? `[${JSON.stringify(key)}]` : /^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key);
1965
+ return `${property}: ${zodToSource(value, ctx)}`;
1966
+ }).join(", ");
2220
1967
  return `z.object({ ${fields} })`;
2221
1968
  }
2222
1969
  if (schema instanceof $ZodArray) {
@@ -2224,13 +1971,13 @@ function zodToSource(schema, ctx) {
2224
1971
  }
2225
1972
  if (schema instanceof $ZodEnum) {
2226
1973
  const entries = schema._zod.def.entries;
2227
- const values = Object.values(entries).map((v7) => `"${v7}"`).join(", ");
1974
+ const values = Object.values(entries).map((v7) => JSON.stringify(v7)).join(", ");
2228
1975
  return `z.enum([${values}])`;
2229
1976
  }
2230
1977
  if (schema instanceof $ZodLiteral) {
2231
1978
  const values = schema._zod.def.values;
2232
1979
  const value = values.values().next().value;
2233
- if (typeof value === "string") return `z.literal("${value}")`;
1980
+ if (typeof value === "string") return `z.literal(${JSON.stringify(value)})`;
2234
1981
  return `z.literal(${value})`;
2235
1982
  }
2236
1983
  if (schema instanceof $ZodUnion) {
@@ -2252,71 +1999,16 @@ function zodToSource(schema, ctx) {
2252
1999
  var HEADER = `// AUTO-GENERATED by zodvex \u2014 do not edit
2253
2000
  // Run \`zodvex generate\` to regenerate
2254
2001
  `;
2255
- function validatorToSource(val) {
2256
- const opt = val.isOptional === "optional";
2257
- const wrap = (s) => opt ? `v.optional(${s})` : s;
2258
- switch (val.kind) {
2259
- case "string":
2260
- return wrap("v.string()");
2261
- case "float64":
2262
- return wrap("v.float64()");
2263
- case "int64":
2264
- return wrap("v.int64()");
2265
- case "boolean":
2266
- return wrap("v.boolean()");
2267
- case "null":
2268
- return wrap("v.null()");
2269
- case "any":
2270
- return wrap("v.any()");
2271
- case "bytes":
2272
- return wrap("v.bytes()");
2273
- case "id":
2274
- return wrap(`v.id(${JSON.stringify(val.tableName)})`);
2275
- case "literal":
2276
- return wrap(`v.literal(${JSON.stringify(val.value)})`);
2277
- case "array":
2278
- return wrap(`v.array(${validatorToSource(val.element)})`);
2279
- case "object": {
2280
- const entries = Object.entries(val.fields ?? {}).map(([k, v7]) => `${JSON.stringify(k)}: ${validatorToSource(v7)}`).join(", ");
2281
- return wrap(`v.object({ ${entries} })`);
2282
- }
2283
- case "union": {
2284
- const members = (val.members ?? []).map(validatorToSource).join(", ");
2285
- return wrap(`v.union(${members})`);
2286
- }
2287
- case "record": {
2288
- const keys = validatorToSource(val.keys);
2289
- const values = validatorToSource(val.values);
2290
- return wrap(`v.record(${keys}, ${values})`);
2291
- }
2292
- default:
2293
- throw new Error(`generateTablesFile: unsupported validator kind '${val.kind}'`);
2294
- }
2295
- }
2296
- function tableToSource(t) {
2297
- const lines = [`defineTable(${validatorToSource(t.validator)})`];
2298
- for (const ix of t.indexes) {
2299
- lines.push(` .index(${JSON.stringify(ix.indexDescriptor)}, ${JSON.stringify(ix.fields)})`);
2002
+ var LAZY_HELPER = `const __memo = new Map()
2003
+ const __lazy = (key, build) => {
2004
+ let entry = __memo.get(key)
2005
+ if (entry === undefined) {
2006
+ entry = build()
2007
+ __memo.set(key, entry)
2300
2008
  }
2301
- for (const ix of t.searchIndexes) {
2302
- lines.push(
2303
- ` .searchIndex(${JSON.stringify(ix.indexDescriptor)}, ${JSON.stringify({
2304
- searchField: ix.searchField,
2305
- filterFields: ix.filterFields
2306
- })})`
2307
- );
2308
- }
2309
- for (const ix of t.vectorIndexes) {
2310
- lines.push(
2311
- ` .vectorIndex(${JSON.stringify(ix.indexDescriptor)}, ${JSON.stringify({
2312
- vectorField: ix.vectorField,
2313
- dimensions: ix.dimensions,
2314
- filterFields: ix.filterFields
2315
- })})`
2316
- );
2317
- }
2318
- return lines.join("\n");
2009
+ return entry
2319
2010
  }
2011
+ `;
2320
2012
  function fingerprintCodec(schema) {
2321
2013
  if (!(schema instanceof $ZodCodec)) return "";
2322
2014
  const def = schema._zod.def;
@@ -2639,40 +2331,17 @@ ${list}`
2639
2331
  if (source.includes("zx.")) needsZx = true;
2640
2332
  return source;
2641
2333
  }
2642
- const argsOnly = options?.argsOnly === true;
2643
- const minimalCodecRef = (codec2) => {
2644
- const ref = codecMap.get(codec2);
2645
- if (!ref) return null;
2646
- if (!zodToSourceCtx.neededCodecImports.has(ref.sourceFile)) {
2647
- zodToSourceCtx.neededCodecImports.set(ref.sourceFile, /* @__PURE__ */ new Set());
2648
- }
2649
- zodToSourceCtx.neededCodecImports.get(ref.sourceFile)?.add(ref.exportName);
2650
- return ref.exportName;
2651
- };
2652
2334
  const entries = functions.map((fn) => {
2653
- if (argsOnly) {
2654
- if (!fn.zodArgs) return null;
2655
- const minimal = emitMinimalSchema(fn.zodArgs, minimalCodecRef, fn.functionPath);
2656
- if (minimal === null) return null;
2657
- let args2;
2658
- if (isUnsupported(minimal)) {
2659
- args2 = resolveSchema(fn.zodArgs);
2660
- } else {
2661
- args2 = minimal;
2662
- needsZod = true;
2663
- if (minimal.includes("zx.date()")) needsZx = true;
2664
- }
2665
- return ` '${fn.functionPath}': {
2666
- args: ${args2},
2667
- }`;
2668
- }
2669
2335
  const args = resolveSchema(fn.zodArgs);
2670
2336
  const returns = resolveSchema(fn.zodReturns);
2671
- return ` '${fn.functionPath}': {
2672
- args: ${args},
2673
- returns: ${returns},
2337
+ const key = `'${fn.functionPath}'`;
2338
+ return ` get ${key}() {
2339
+ return __lazy(${key}, () => ({
2340
+ args: ${args},
2341
+ returns: ${returns},
2342
+ }))
2674
2343
  }`;
2675
- }).filter((e) => e !== null).join(",\n");
2344
+ }).join(",\n");
2676
2345
  const usedModelCodecVars = modelCodecVars.filter((mc) => {
2677
2346
  const sentinelExports = zodToSourceCtx.neededCodecImports.get(MODEL_CODEC_SENTINEL);
2678
2347
  return sentinelExports?.has(mc.varName);
@@ -2716,55 +2385,31 @@ ${list}`
2716
2385
  ` : "";
2717
2386
  const registryEntries = entries.length > 0 ? `${entries},
2718
2387
  ` : "";
2719
- const registryExportName = argsOnly ? "zodvexArgsRegistry" : "zodvexRegistry";
2388
+ const lazySection = entries.length > 0 ? `${LAZY_HELPER}
2389
+ ` : "";
2720
2390
  const js = `${HEADER}
2721
- ${importSection}${codecVarSection}export const ${registryExportName} = {
2391
+ ${importSection}${codecVarSection}${lazySection}export const zodvexRegistry = {
2722
2392
  ${registryEntries}}
2723
2393
  `;
2724
- const entryType = argsOnly ? { mini: "{ args: $ZodType }", full: "{ args: ZodTypeAny }" } : {
2725
- mini: "{ args: $ZodType; returns: $ZodType | undefined }",
2726
- full: "{ args: ZodTypeAny; returns: ZodTypeAny | undefined }"
2727
- };
2728
2394
  const dts = options?.mini ? `${HEADER}
2729
2395
  import type { $ZodType } from 'zod/v4/core'
2730
2396
 
2731
- export declare const ${registryExportName}: Record<string, ${entryType.mini}>
2397
+ export declare const zodvexRegistry: Record<string, { args: $ZodType; returns: $ZodType | undefined }>
2732
2398
  ` : `${HEADER}
2733
2399
  import type { ZodTypeAny } from 'zod'
2734
2400
 
2735
- export declare const ${registryExportName}: Record<string, ${entryType.full}>
2401
+ export declare const zodvexRegistry: Record<string, { args: ZodTypeAny; returns: ZodTypeAny | undefined }>
2736
2402
  `;
2737
2403
  return { js, dts };
2738
2404
  }
2739
- function generateServerFile(models, options) {
2740
- const serverImport = options?.mini ? "zodvex/mini/server" : "zodvex/server";
2741
- const ts = `${HEADER}
2742
- import { initZodvex as _libInitZodvex } from '${serverImport}'
2743
- import type {
2744
- ZodvexActionCtx,
2745
- ZodvexBuilder,
2746
- ZodvexMutationCtx,
2747
- ZodvexQueryCtx,
2748
- } from '${serverImport}'
2749
- import type {
2750
- ActionBuilder,
2751
- GenericActionCtx,
2752
- GenericMutationCtx,
2753
- GenericQueryCtx,
2754
- MutationBuilder,
2755
- QueryBuilder,
2756
- } from 'convex/server'
2405
+ function generateServerFile() {
2406
+ const js = `${HEADER}`;
2407
+ const dts = `${HEADER}
2757
2408
  import type { DataModel } from '../_generated/dataModel.js'
2758
- import { zodvexArgsRegistry as _argsRegistry } from './api.args.js'
2759
- import { zodvexTableMap as _tableMap } from './models/index.js'
2760
-
2761
- // --- Context types ---
2409
+ import type { ZodvexActionCtx, ZodvexMutationCtx, ZodvexQueryCtx } from 'zodvex/server'
2410
+ import type schema from '../schema.js'
2762
2411
 
2763
- // Decoded doc types are imported directly from the codegen-emitted
2764
- // tables.ts so userland \`schema.ts\` can use Convex's canonical
2765
- // \`defineSchema(tables)\` without carrying a zodvex-specific token.
2766
- import type { DecodedDocs as _DecodedDocs } from './tables'
2767
- type DecodedDocs = _DecodedDocs
2412
+ type DecodedDocs = (typeof schema)['__decodedDocs']
2768
2413
 
2769
2414
  /** Query context with codec-wrapped db (decoded types on reads). */
2770
2415
  export type QueryCtx = ZodvexQueryCtx<DataModel, DecodedDocs>
@@ -2774,142 +2419,8 @@ export type MutationCtx = ZodvexMutationCtx<DataModel, DecodedDocs>
2774
2419
 
2775
2420
  /** Action context (no db, but runQuery/runMutation may be codec-wrapped). */
2776
2421
  export type ActionCtx = ZodvexActionCtx<DataModel>
2777
-
2778
- // --- Registry: lazy full (actions) + static args-only (mutations) ---
2779
- // Actions run in Node, where dynamic \`import()\` works \u2014 the FULL registry
2780
- // (args + returns, whose model-doc graph dominates bundle weight) loads
2781
- // lazily, so it never enters any endpoint's static bundle (~20x per-endpoint
2782
- // heap reduction at N=200; see
2783
- // examples/stress-test/results/archive/lazy-registry-2026-05-12.md).
2784
- // Mutations run in Convex's Q/M V8 sandbox (no dynamic import) but only
2785
- // consume ARGS schemas (scheduler.runAfter/runAt encoding) \u2014 they get the
2786
- // statically-imported args-only registry from ./api.args.js, which stays
2787
- // light because it carries no \`returns\` schemas.
2788
-
2789
- let _cachedRegistry: Promise<typeof import('./api.js').zodvexRegistry> | undefined
2790
- const _registry = () => (_cachedRegistry ??= import('./api.js').then(m => m.zodvexRegistry))
2791
- const _schedulerRegistry = () => _argsRegistry
2792
-
2793
- // --- Codec-paths table map (Q/M-safe, ~zero weight) ---
2794
- // The Q/M V8 sandbox forbids dynamic \`import()\`, so the runtime tableMap
2795
- // must be statically reachable \u2014 but it does NOT need the model graph:
2796
- // ./models/index.js carries one minimal loose schema per codec-bearing
2797
- // table (codec fields only), so this import costs O(codec fields) instead
2798
- // of the all-models graph that OOM'd real deploys at ~150 models.
2799
-
2800
- // --- Pre-wired initZodvex ---
2801
- // Calls the library's initZodvex with schema + registry + tableMap
2802
- // already wired. Consumers pass only the Convex server builders.
2803
- // Override registry/tableMap/wrapDb via options if needed.
2804
-
2805
- type Server = {
2806
- query: QueryBuilder<DataModel, 'public'>
2807
- mutation: MutationBuilder<DataModel, 'public'>
2808
- action: ActionBuilder<DataModel, 'public'>
2809
- internalQuery: QueryBuilder<DataModel, 'internal'>
2810
- internalMutation: MutationBuilder<DataModel, 'internal'>
2811
- internalAction: ActionBuilder<DataModel, 'internal'>
2812
- }
2813
-
2814
- type Bundle = {
2815
- zq: ZodvexBuilder<'query', { db: QueryCtx['db'] }, GenericQueryCtx<DataModel>, 'public'>
2816
- zm: ZodvexBuilder<'mutation', { db: MutationCtx['db'] }, GenericMutationCtx<DataModel>, 'public'>
2817
- za: ZodvexBuilder<'action', {}, GenericActionCtx<DataModel>, 'public'>
2818
- ziq: ZodvexBuilder<'query', { db: QueryCtx['db'] }, GenericQueryCtx<DataModel>, 'internal'>
2819
- zim: ZodvexBuilder<'mutation', { db: MutationCtx['db'] }, GenericMutationCtx<DataModel>, 'internal'>
2820
- zia: ZodvexBuilder<'action', {}, GenericActionCtx<DataModel>, 'internal'>
2821
- }
2822
-
2823
- export function initZodvex(server: Server, options: {
2824
- wrapDb?: boolean
2825
- registry?: () => any
2826
- schedulerRegistry?: () => any
2827
- tableMap?: any
2828
- } = {}): Bundle {
2829
- return (_libInitZodvex as any)(_schemaToken, server, {
2830
- ...options,
2831
- registry: options.registry ?? _registry,
2832
- schedulerRegistry: options.schedulerRegistry ?? _schedulerRegistry,
2833
- tableMap: options.tableMap ?? _tableMap,
2834
- }) as Bundle
2835
- }
2836
-
2837
- // --- Codec-aware schema re-export (tokens only) ---
2838
- // Userland code that wants \`createZodDbReader\`/\`createZodDbWriter\` outside
2839
- // a zq/zm handler imports \`schema\` from here (not from \`../schema\`).
2840
- // NOTE: deliberately NOT a value-import of ../schema.js \u2014 that would pull
2841
- // the table definitions into EVERY endpoint bundle (~8 MB at N=800, the
2842
- // difference between hitting Convex's TooManyReads wall and OOMing just
2843
- // short of it). The TYPE carries the full schema (type-only import,
2844
- // erased); the runtime value carries only the zodvex tokens, which is all
2845
- // the db wrappers read.
2846
-
2847
- type ZodvexSchema = typeof import('../schema.js').default & {
2848
- __zodTableMap: typeof _tableMap
2849
- __decodedDocs: DecodedDocs
2850
- }
2851
-
2852
- const _schemaToken = {
2853
- __zodTableMap: _tableMap,
2854
- __decodedDocs: undefined as unknown as DecodedDocs,
2855
- } as unknown as ZodvexSchema
2856
-
2857
- export const schema: ZodvexSchema = _schemaToken
2858
- `;
2859
- return { js: ts, dts: "" };
2860
- }
2861
- function generateTablesFile(models) {
2862
- const entries = [];
2863
- const typeImports = [];
2864
- const decodedDocsEntries = [];
2865
- for (const m of models) {
2866
- if (!m._liveModel) continue;
2867
- const live = m._liveModel;
2868
- if (live.fields === void 0 || live.indexes === void 0) {
2869
- console.warn(
2870
- `[zodvex] Skipping tables.ts entry for '${m.exportName}' in ${m.sourceFile}: model is not a defineZodModel() result. Use defineZodModel() to enable the lazy-tables shape.`
2871
- );
2872
- continue;
2873
- }
2874
- let table;
2875
- try {
2876
- table = tableFromModel(live);
2877
- } catch (err) {
2878
- console.warn(
2879
- `[zodvex] Skipping tables.ts entry for '${m.exportName}' in ${m.sourceFile}: ${err.message}`
2880
- );
2881
- continue;
2882
- }
2883
- const tableSrc = tableToSource(table);
2884
- entries.push(` ${JSON.stringify(live.name)}: ${tableSrc},`);
2885
- const importPath = `../${m.sourceFile.replace(/\.ts$/, ".js")}`;
2886
- typeImports.push(`import type { ${m.exportName} } from '${importPath}'`);
2887
- decodedDocsEntries.push(` ${JSON.stringify(live.name)}: typeof ${m.exportName}`);
2888
- }
2889
- const ts = `${HEADER}
2890
- import { defineTable } from 'convex/server'
2891
- import { v } from 'convex/values'
2892
- ${typeImports.length > 0 ? `
2893
- ${typeImports.join("\n")}` : ""}
2894
- import type { DecodedDocFor } from 'zodvex/server'
2895
-
2896
- export default {
2897
- ${entries.join("\n")}
2898
- }
2899
-
2900
- /**
2901
- * Decoded document types per table \u2014 derived from each model's zod doc
2902
- * schema. Used by \`defineZodvexSchema\` to attach \`__decodedDocs\` so
2903
- * ctx.db return types in queries/mutations reflect codec-decoded shapes
2904
- * (e.g. \`Date\` instead of \`number\` for \`zx.date()\` fields).
2905
- *
2906
- * Type-only \u2014 does NOT load zod at module init. Schema-eval stays thin.
2907
- */
2908
- export type DecodedDocs = DecodedDocFor<{
2909
- ${decodedDocsEntries.join("\n")}
2910
- }>
2911
2422
  `;
2912
- return { js: ts, dts: "" };
2423
+ return { js, dts };
2913
2424
  }
2914
2425
  function generateClientFile(options) {
2915
2426
  const zodvexClientImport = options?.mini ? "zodvex/mini" : "zodvex";
@@ -2921,7 +2432,7 @@ function generateClientFile(options) {
2921
2432
  "import { zodvexRegistry } from './api.js'"
2922
2433
  ];
2923
2434
  const jsExports = [
2924
- "export const { useZodQuery, useZodMutation } = createZodvexHooks(zodvexRegistry)",
2435
+ "export const { useZodQuery, useZodMutation, useZodPaginatedQuery, useQuery_experimental } = createZodvexHooks(zodvexRegistry)",
2925
2436
  "",
2926
2437
  "export const createClient = (options) =>",
2927
2438
  " createZodvexClient(zodvexRegistry, options)",
@@ -2944,6 +2455,8 @@ ${jsExports.join("\n")}
2944
2455
  ];
2945
2456
  const dtsDeclarations = [
2946
2457
  "export declare const useZodQuery: ZodvexHooks['useZodQuery']",
2458
+ "export declare const useZodPaginatedQuery: ZodvexHooks['useZodPaginatedQuery']",
2459
+ "export declare const useQuery_experimental: ZodvexHooks['useQuery_experimental']",
2947
2460
  "export declare const useZodMutation: ZodvexHooks['useZodMutation']",
2948
2461
  "",
2949
2462
  "export declare const createClient: (options: ZodvexClientOptions) => ZodvexClient",
@@ -2960,300 +2473,43 @@ ${dtsDeclarations.join("\n")}
2960
2473
  `;
2961
2474
  return { js, dts };
2962
2475
  }
2963
- function inferDiscriminator(options) {
2964
- const objectBranches = options.filter((o) => o instanceof $ZodObject);
2965
- if (objectBranches.length !== options.length || objectBranches.length === 0) return void 0;
2966
- const literalKeys = (branch) => {
2967
- const out = /* @__PURE__ */ new Map();
2968
- const shape = branch._zod.def.shape;
2969
- for (const [k, v7] of Object.entries(shape ?? {})) {
2970
- if (v7 instanceof $ZodLiteral) {
2971
- const values = v7._zod?.def?.values;
2972
- if (Array.isArray(values) && values.length === 1) out.set(k, values[0]);
2973
- }
2974
- }
2975
- return out;
2976
- };
2977
- const perBranch = objectBranches.map(literalKeys);
2978
- for (const key of perBranch[0].keys()) {
2979
- const values = perBranch.map((m) => m.has(key) ? m.get(key) : void 0);
2980
- if (values.some((v7) => v7 === void 0)) continue;
2981
- if (new Set(values.map((v7) => JSON.stringify(v7))).size === values.length) return key;
2982
- }
2983
- return void 0;
2984
- }
2985
- function isUnsupported(e) {
2986
- return typeof e === "object" && e !== null;
2987
- }
2988
- function emitMinimalSchema(schema, codecRef, at) {
2989
- if (schema instanceof $ZodCodec) {
2990
- const def2 = schema._zod.def;
2991
- const isDate = def2.in instanceof $ZodNumber && def2.out instanceof $ZodCustom;
2992
- if (isDate) return "zx.date()";
2993
- const ref = codecRef(schema);
2994
- return ref ?? { unsupported: `custom codec without an importable standalone reference at ${at}` };
2995
- }
2996
- if (schema instanceof $ZodOptional) {
2997
- const inner = emitMinimalSchema(schema._zod.def.innerType, codecRef, at);
2998
- if (inner === null || isUnsupported(inner)) return inner;
2999
- return `z.optional(${inner})`;
3000
- }
3001
- if (schema instanceof $ZodNullable) {
3002
- const inner = emitMinimalSchema(schema._zod.def.innerType, codecRef, at);
3003
- if (inner === null || isUnsupported(inner)) return inner;
3004
- return `z.nullable(${inner})`;
3005
- }
3006
- if (schema instanceof $ZodObject) {
3007
- const shape = schema._zod.def.shape;
3008
- const lines = [];
3009
- for (const key of Object.keys(shape ?? {}).sort()) {
3010
- const emitted = emitMinimalSchema(shape[key], codecRef, `${at}.${key}`);
3011
- if (isUnsupported(emitted)) return emitted;
3012
- if (emitted !== null) lines.push(`${key}: ${emitted},`);
3013
- }
3014
- if (lines.length === 0) return null;
3015
- return `z.looseObject({ ${lines.join(" ")} })`;
3016
- }
3017
- if (schema instanceof $ZodArray) {
3018
- const inner = emitMinimalSchema(schema._zod.def.element, codecRef, `${at}[*]`);
3019
- if (inner === null || isUnsupported(inner)) return inner;
3020
- return `z.array(${inner})`;
3021
- }
3022
- if (schema instanceof $ZodUnion) {
3023
- const def2 = schema._zod.def;
3024
- const options = def2.options ?? [];
3025
- if (!schemaSubtreeHasCodec(schema)) return null;
3026
- const discriminator = schema instanceof $ZodDiscriminatedUnion ? def2.discriminator : inferDiscriminator(options);
3027
- if (discriminator === void 0) {
3028
- return { unsupported: `codec inside union without an inferable discriminator at ${at}` };
3029
- }
3030
- const branches = [];
3031
- let any = false;
3032
- for (let i = 0; i < options.length; i++) {
3033
- const branch = options[i];
3034
- if (!(branch instanceof $ZodObject)) {
3035
- if (schemaSubtreeHasCodec(branch)) {
3036
- return { unsupported: `codec inside non-object union branch at ${at}` };
3037
- }
3038
- continue;
3039
- }
3040
- const emitted = emitMinimalSchema(branch, codecRef, `${at}<${i}>`);
3041
- if (isUnsupported(emitted)) return emitted;
3042
- if (emitted === null) continue;
3043
- any = true;
3044
- const shape = branch._zod.def.shape;
3045
- const disc = shape?.[discriminator];
3046
- const value = disc?._zod?.def?.values?.[0];
3047
- if (!(disc instanceof $ZodLiteral) || value === void 0) {
3048
- return { unsupported: `codec union branch without literal discriminator at ${at}` };
3049
- }
3050
- branches.push(
3051
- emitted.replace(
3052
- "z.looseObject({ ",
3053
- `z.looseObject({ ${discriminator}: z.literal(${JSON.stringify(value)}), `
3054
- )
3055
- );
3056
- }
3057
- if (!any) return null;
3058
- branches.push("z.looseObject({})");
3059
- return `z.union([${branches.join(", ")}])`;
3060
- }
3061
- if (schema instanceof $ZodRecord || schema instanceof $ZodTuple) {
3062
- if (schemaSubtreeHasCodec(schema)) {
3063
- const kind = schema instanceof $ZodRecord ? "record" : "tuple";
3064
- return { unsupported: `codec inside ${kind} at ${at}` };
3065
- }
3066
- return null;
3067
- }
3068
- const def = schema._zod?.def;
3069
- if (def?.innerType instanceof $ZodType) {
3070
- return emitMinimalSchema(def.innerType, codecRef, at);
3071
- }
3072
- if (schemaSubtreeHasCodec(schema)) {
3073
- return { unsupported: `codec inside unsupported node at ${at}` };
3074
- }
3075
- return null;
3076
- }
3077
- function generateModelDescriptors(models, codecs, options) {
3078
- const mini = options?.mini === true;
3079
- const zodImport = mini ? "zod/mini" : "zod";
3080
- const zodvexImport = mini ? "zodvex/mini" : "zodvex";
3081
- const sorted = [...models].sort((a, b) => a.tableName.localeCompare(b.tableName));
3082
- const files = [];
3083
- const indexImports = [];
3084
- const indexEntries = [];
3085
- const fallbacks = [];
3086
- const fingerprint = createHash("sha256");
3087
- const dtsBody = `${HEADER}
3088
- import type { $ZodType } from 'zod/v4/core'
3089
-
3090
- declare const _default: { doc: $ZodType; insert: $ZodType }
3091
- export default _default
3092
- `;
3093
- for (const m of sorted) {
3094
- let doc2;
3095
- if (m.schemas?.doc) {
3096
- doc2 = m.schemas.doc;
3097
- } else if (m._modelRef) {
3098
- doc2 = zx.doc(m._modelRef);
3099
- }
3100
- if (!doc2) continue;
3101
- const neededImports = /* @__PURE__ */ new Map();
3102
- const codecRef = (codec2) => {
3103
- const hit = codecs?.find((c) => c.schema === codec2);
3104
- if (!hit) return null;
3105
- const importPath = `../../${hit.sourceFile.replace(/\.ts$/, ".js")}`;
3106
- if (!neededImports.has(importPath)) neededImports.set(importPath, /* @__PURE__ */ new Set());
3107
- neededImports.get(importPath).add(hit.exportName);
3108
- return hit.exportName;
3109
- };
3110
- const emitted = emitMinimalSchema(doc2, codecRef, m.tableName);
3111
- if (emitted === null) continue;
3112
- let js = null;
3113
- if (!isUnsupported(emitted)) {
3114
- const needsZx = emitted.includes("zx.date()");
3115
- const importLines = [
3116
- `import { z } from '${zodImport}'`,
3117
- ...needsZx ? [`import { zx } from '${zodvexImport}'`] : [],
3118
- ...[...neededImports.keys()].sort().map((ip) => `import { ${[...neededImports.get(ip)].sort().join(", ")} } from '${ip}'`)
3119
- ];
3120
- js = `${HEADER}
3121
- ${importLines.join("\n")}
3122
-
3123
- // Minimal schema: codec subtrees only; unknown keys pass through (loose).
3124
- const schema = ${emitted}
3125
-
3126
- export default { doc: schema, insert: schema }
3127
- `;
3128
- fingerprint.update(`${m.tableName}|${emitted};`);
3129
- }
3130
- if (js === null) {
3131
- const reason = isUnsupported(emitted) ? emitted.unsupported : "unsupported";
3132
- fallbacks.push({ tableName: m.tableName, reason });
3133
- const importPath = `../../${m.sourceFile.replace(/\.ts$/, ".js")}`;
3134
- const isSlim = !m.schemas?.doc && !!m._modelRef;
3135
- js = isSlim ? `${HEADER}
3136
- import { zx } from '${zodvexImport}'
3137
- import { ${m.exportName} } from '${importPath}'
3138
-
3139
- // FALLBACK: ${reason} \u2014 this table carries its full model (per-table cost).
3140
- export default { doc: zx.doc(${m.exportName}), insert: zx.base(${m.exportName}) }
3141
- ` : `${HEADER}
3142
- import { ${m.exportName} } from '${importPath}'
3143
-
3144
- // FALLBACK: ${reason} \u2014 this table carries its full model (per-table cost).
3145
- export default { doc: ${m.exportName}.schema.doc, insert: ${m.exportName}.schema.insert }
3146
- `;
3147
- fingerprint.update(`${m.tableName}|FALLBACK;`);
3148
- }
3149
- files.push({ name: m.tableName, js, dts: dtsBody });
3150
- const alias = `d_${indexEntries.length}`;
3151
- indexImports.push(`import ${alias} from './${m.tableName}.js'`);
3152
- indexEntries.push(` '${m.tableName}': ${alias},`);
3153
- }
3154
- const fp = fingerprint.digest("hex");
3155
- const indexJs = `${HEADER}
3156
- ${indexImports.join("\n")}
3157
-
3158
- /** Central tableMap: codec-bearing tables only at O(codec fields) cost.
3159
- * Tables absent here have no codecs \u2014 wrapper passthrough is correct. */
3160
- export const zodvexTableMap = {
3161
- ${indexEntries.join("\n")}
3162
- }
3163
-
3164
- /** Fingerprint of the codec-path spec this map was generated from. */
3165
- export const zodvexTableMapFingerprint = '${fp}'
3166
- `;
3167
- const indexDts = `${HEADER}
3168
- import type { $ZodType } from 'zod/v4/core'
3169
-
3170
- export declare const zodvexTableMap: Record<string, { doc: $ZodType; insert: $ZodType }>
3171
- export declare const zodvexTableMapFingerprint: string
3172
- `;
3173
- return { files, indexJs, indexDts, fallbacks };
3174
- }
3175
2476
 
3176
2477
  // src/public/cli/commands.ts
3177
2478
  async function generate(convexDir2, options) {
3178
2479
  const resolved = resolveConvexDir(convexDir2);
3179
- const zodvexDir = path3.join(resolved, "_zodvex");
3180
- writeStubApi(zodvexDir);
3181
- const result = await discoverModules(resolved);
3182
- const schemaContent = generateSchemaFile(result.models);
3183
- const apiContent = generateApiFile(
3184
- result.functions,
3185
- result.models,
3186
- result.codecs,
3187
- result.modelCodecs,
3188
- result.functionCodecs,
3189
- { mini: options?.mini }
3190
- );
3191
- const argsApiContent = generateApiFile(
3192
- result.functions,
3193
- result.models,
3194
- result.codecs,
3195
- result.modelCodecs,
3196
- result.functionCodecs,
3197
- { mini: options?.mini, argsOnly: true }
3198
- );
3199
- const clientContent = generateClientFile({ mini: options?.mini });
3200
- const serverContent = generateServerFile(result.models, { mini: options?.mini });
3201
- const tablesContent = generateTablesFile(result.models);
3202
- const descriptors = generateModelDescriptors(result.models, result.codecs, {
3203
- mini: options?.mini
3204
- });
3205
- for (const fb of descriptors.fallbacks) {
3206
- console.warn(
3207
- `[zodvex] Note: table '${fb.tableName}' descriptor falls back to its full model (${fb.reason}). That table costs its model graph in every endpoint bundle; the rest stay light.`
2480
+ const zodvexDir = path4.join(resolved, "_zodvex");
2481
+ const restoreStubbedApi = writeStubApi(zodvexDir);
2482
+ let result;
2483
+ let schemaContent;
2484
+ let apiContent;
2485
+ let clientContent;
2486
+ let serverContent;
2487
+ try {
2488
+ result = await discoverModules(resolved);
2489
+ schemaContent = generateSchemaFile(result.models);
2490
+ apiContent = generateApiFile(
2491
+ result.functions,
2492
+ result.models,
2493
+ result.codecs,
2494
+ result.modelCodecs,
2495
+ result.functionCodecs,
2496
+ { mini: options?.mini }
3208
2497
  );
3209
- }
3210
- fs2.mkdirSync(zodvexDir, { recursive: true });
3211
- writeIfChanged(path3.join(zodvexDir, "schema.js"), schemaContent.js);
3212
- writeIfChanged(path3.join(zodvexDir, "schema.d.ts"), schemaContent.dts);
3213
- writeIfChanged(path3.join(zodvexDir, "api.js"), apiContent.js);
3214
- writeIfChanged(path3.join(zodvexDir, "api.d.ts"), apiContent.dts);
3215
- writeIfChanged(path3.join(zodvexDir, "api.args.js"), argsApiContent.js);
3216
- writeIfChanged(path3.join(zodvexDir, "api.args.d.ts"), argsApiContent.dts);
3217
- writeIfChanged(path3.join(zodvexDir, "tables.ts"), tablesContent.js);
3218
- writeIfChanged(path3.join(zodvexDir, "server.ts"), serverContent.js);
3219
- const modelsDir = path3.join(zodvexDir, "models");
3220
- fs2.mkdirSync(modelsDir, { recursive: true });
3221
- const expected = /* @__PURE__ */ new Set(["index.js", "index.d.ts"]);
3222
- for (const f of descriptors.files) {
3223
- writeIfChanged(path3.join(modelsDir, `${f.name}.js`), f.js);
3224
- writeIfChanged(path3.join(modelsDir, `${f.name}.d.ts`), f.dts);
3225
- expected.add(`${f.name}.js`);
3226
- expected.add(`${f.name}.d.ts`);
3227
- }
3228
- writeIfChanged(path3.join(modelsDir, "index.js"), descriptors.indexJs);
3229
- writeIfChanged(path3.join(modelsDir, "index.d.ts"), descriptors.indexDts);
3230
- for (const entry of fs2.readdirSync(modelsDir)) {
3231
- if (!expected.has(entry)) {
3232
- try {
3233
- fs2.unlinkSync(path3.join(modelsDir, entry));
3234
- } catch {
3235
- }
3236
- }
3237
- }
3238
- writeIfChanged(path3.join(zodvexDir, "client.js"), clientContent.js);
3239
- writeIfChanged(path3.join(zodvexDir, "client.d.ts"), clientContent.dts);
3240
- writeIfChanged(path3.join(zodvexDir, "convex.config.ts"), CONVEX_SKIP_MARKER);
3241
- for (const stale of [
3242
- "api.lazy.js",
3243
- "api.lazy.d.ts",
3244
- "tableMap.lazy.js",
3245
- "tableMap.lazy.d.ts",
3246
- "server.js",
3247
- "server.d.ts",
3248
- "tables.js",
3249
- "tables.d.ts"
3250
- ]) {
3251
- const p = path3.join(zodvexDir, stale);
3252
- try {
3253
- fs2.unlinkSync(p);
3254
- } catch {
3255
- }
3256
- }
2498
+ clientContent = generateClientFile({ mini: options?.mini });
2499
+ serverContent = generateServerFile();
2500
+ } catch (err) {
2501
+ restoreStubbedApi();
2502
+ throw err;
2503
+ }
2504
+ fs3.mkdirSync(zodvexDir, { recursive: true });
2505
+ writeIfChanged(path4.join(zodvexDir, "schema.js"), schemaContent.js);
2506
+ writeIfChanged(path4.join(zodvexDir, "schema.d.ts"), schemaContent.dts);
2507
+ writeIfChanged(path4.join(zodvexDir, "api.js"), apiContent.js);
2508
+ writeIfChanged(path4.join(zodvexDir, "api.d.ts"), apiContent.dts);
2509
+ writeIfChanged(path4.join(zodvexDir, "client.js"), clientContent.js);
2510
+ writeIfChanged(path4.join(zodvexDir, "client.d.ts"), clientContent.dts);
2511
+ writeIfChanged(path4.join(zodvexDir, "server.js"), serverContent.js);
2512
+ writeIfChanged(path4.join(zodvexDir, "server.d.ts"), serverContent.dts);
3257
2513
  const totalCodecs = result.codecs.length + result.modelCodecs.length + result.functionCodecs.length;
3258
2514
  console.log(
3259
2515
  `[zodvex] Generated ${result.models.length} model(s), ${result.functions.length} function(s), ${totalCodecs} codec(s)`
@@ -3264,7 +2520,7 @@ async function dev(convexDir2, options) {
3264
2520
  console.log("[zodvex] Starting watch mode...");
3265
2521
  await generate(resolved, options);
3266
2522
  let debounceTimer = null;
3267
- const watcher = fs2.watch(resolved, { recursive: true }, (_event, filename) => {
2523
+ const watcher = fs3.watch(resolved, { recursive: true }, (_event, filename) => {
3268
2524
  if (!filename) return;
3269
2525
  if (filename.startsWith("_zodvex") || filename.startsWith("_generated") || !filename.endsWith(".ts") && !filename.endsWith(".js")) {
3270
2526
  return;
@@ -3297,84 +2553,57 @@ function regenerate(resolved, options) {
3297
2553
  });
3298
2554
  });
3299
2555
  }
3300
- var CONVEX_SKIP_MARKER = `// NOOP \u2014 prevents Convex from importing the zod-only code into the runtime isolate.
3301
- // See https://github.com/panzacoder/zodvex for context.
3302
- `;
3303
2556
  function writeStubApi(zodvexDir) {
3304
- fs2.mkdirSync(zodvexDir, { recursive: true });
3305
- fs2.writeFileSync(
3306
- path3.join(zodvexDir, "api.js"),
2557
+ const stubTargets = ["api.js", "api.d.ts"].map((name) => {
2558
+ const filePath = path4.join(zodvexDir, name);
2559
+ let original;
2560
+ try {
2561
+ original = fs3.readFileSync(filePath, "utf-8");
2562
+ } catch {
2563
+ original = null;
2564
+ }
2565
+ return { filePath, original };
2566
+ });
2567
+ fs3.mkdirSync(zodvexDir, { recursive: true });
2568
+ fs3.writeFileSync(
2569
+ path4.join(zodvexDir, "api.js"),
3307
2570
  "// AUTO-GENERATED by zodvex \u2014 do not edit\n// Stub created for codegen bootstrap\n\nexport const zodvexRegistry = {}\n"
3308
2571
  );
3309
- fs2.writeFileSync(
3310
- path3.join(zodvexDir, "api.d.ts"),
2572
+ fs3.writeFileSync(
2573
+ path4.join(zodvexDir, "api.d.ts"),
3311
2574
  "// AUTO-GENERATED by zodvex \u2014 do not edit\n// Stub created for codegen bootstrap\n\nexport declare const zodvexRegistry: Record<string, any>\n"
3312
2575
  );
3313
- fs2.mkdirSync(path3.join(zodvexDir, "models"), { recursive: true });
3314
- fs2.writeFileSync(
3315
- path3.join(zodvexDir, "models", "index.js"),
3316
- "// AUTO-GENERATED by zodvex \u2014 do not edit\n// Stub created for codegen bootstrap\n\nexport const zodvexTableMap = {}\nexport const zodvexTableMapFingerprint = ''\n"
3317
- );
3318
- fs2.writeFileSync(
3319
- path3.join(zodvexDir, "models", "index.d.ts"),
3320
- "// AUTO-GENERATED by zodvex \u2014 do not edit\n// Stub created for codegen bootstrap\n\nexport declare const zodvexTableMap: Record<string, any>\nexport declare const zodvexTableMapFingerprint: string\n"
3321
- );
3322
- fs2.writeFileSync(
3323
- path3.join(zodvexDir, "api.args.js"),
3324
- "// AUTO-GENERATED by zodvex \u2014 do not edit\n// Stub created for codegen bootstrap\n\nexport const zodvexArgsRegistry = {}\n"
3325
- );
3326
- fs2.writeFileSync(
3327
- path3.join(zodvexDir, "api.args.d.ts"),
3328
- "// AUTO-GENERATED by zodvex \u2014 do not edit\n// Stub created for codegen bootstrap\n\nexport declare const zodvexArgsRegistry: Record<string, any>\n"
3329
- );
3330
- writeIfMissing(
3331
- path3.join(zodvexDir, "tables.ts"),
3332
- "// AUTO-GENERATED by zodvex \u2014 do not edit\n// Stub created for codegen bootstrap\n\nexport default {} as Record<string, import('convex/server').TableDefinition>\nexport type DecodedDocs = Record<string, any>\n"
3333
- );
3334
- writeIfMissing(
3335
- path3.join(zodvexDir, "server.ts"),
3336
- `// AUTO-GENERATED by zodvex \u2014 do not edit
3337
- // Stub created for codegen bootstrap. Real content is emitted at the end
3338
- // of \`zodvex generate\`.
3339
- export function initZodvex(server: any, _options?: any): any {
3340
- return {
3341
- zq: server.query,
3342
- zm: server.mutation,
3343
- za: server.action,
3344
- ziq: server.internalQuery,
3345
- zim: server.internalMutation,
3346
- zia: server.internalAction,
3347
- }
3348
- }
3349
- export type QueryCtx = any
3350
- export type MutationCtx = any
3351
- export type ActionCtx = any
3352
- `
3353
- );
3354
- writeIfMissing(path3.join(zodvexDir, "convex.config.ts"), CONVEX_SKIP_MARKER);
3355
- }
3356
- function writeIfMissing(filePath, content) {
3357
- if (fs2.existsSync(filePath)) return;
3358
- fs2.writeFileSync(filePath, content);
2576
+ return () => {
2577
+ for (const { filePath, original } of stubTargets) {
2578
+ try {
2579
+ if (original !== null) {
2580
+ fs3.writeFileSync(filePath, original);
2581
+ } else {
2582
+ fs3.unlinkSync(filePath);
2583
+ }
2584
+ } catch {
2585
+ }
2586
+ }
2587
+ };
3359
2588
  }
3360
2589
  function writeIfChanged(filePath, content) {
3361
2590
  try {
3362
- const existing = fs2.readFileSync(filePath, "utf-8");
2591
+ const existing = fs3.readFileSync(filePath, "utf-8");
3363
2592
  if (existing === content) return;
3364
2593
  } catch {
3365
2594
  }
3366
- fs2.writeFileSync(filePath, content);
2595
+ fs3.writeFileSync(filePath, content);
3367
2596
  }
3368
2597
  function resolveConvexDir(dir) {
3369
2598
  if (dir) {
3370
- const resolved = path3.resolve(dir);
3371
- if (!fs2.existsSync(resolved)) {
2599
+ const resolved = path4.resolve(dir);
2600
+ if (!fs3.existsSync(resolved)) {
3372
2601
  throw new Error(`Convex directory not found: ${resolved}`);
3373
2602
  }
3374
2603
  return resolved;
3375
2604
  }
3376
- const defaultDir = path3.resolve("convex");
3377
- if (!fs2.existsSync(defaultDir)) {
2605
+ const defaultDir = path4.resolve("convex");
2606
+ if (!fs3.existsSync(defaultDir)) {
3378
2607
  throw new Error("No convex/ directory found. Specify the path: zodvex generate <path>");
3379
2608
  }
3380
2609
  return defaultDir;
@@ -3392,6 +2621,16 @@ async function main() {
3392
2621
  case "dev":
3393
2622
  await dev(convexDir, { mini: miniFlag });
3394
2623
  break;
2624
+ case "inspect-schema": {
2625
+ try {
2626
+ const { inspectSchema } = await import(new URL("./inspect-schema/inspect.mjs", import.meta.url).href);
2627
+ await inspectSchema(process.argv.slice(3));
2628
+ } catch {
2629
+ console.error("Local schema diagnostic failed; no report was produced");
2630
+ process.exitCode = 1;
2631
+ }
2632
+ break;
2633
+ }
3395
2634
  case "init": {
3396
2635
  const { init: init2 } = await Promise.resolve().then(() => (init_init(), init_exports));
3397
2636
  await init2();
@@ -3458,6 +2697,7 @@ zodvex - Convex codegen for Zod schemas
3458
2697
  Usage:
3459
2698
  zodvex generate [convex-dir] [--mini] Generate schema and validator files
3460
2699
  zodvex dev [convex-dir] [--mini] Watch mode \u2014 regenerate on changes
2700
+ zodvex inspect-schema [schema-file] Write a local aggregate schema report (Node 22+)
3461
2701
  zodvex init Set up zodvex in an existing Convex project
3462
2702
  zodvex migrate [dir] Migrate pre-0.6 APIs (renames + import fixes)
3463
2703
  zodvex migrate [dir] --dry-run Preview changes without writing