zodvex 0.7.1-beta.1 → 0.7.1-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.
@@ -0,0 +1,4 @@
1
+ export declare function runToMiniCodemod(targetDir: string, options?: {
2
+ dryRun?: boolean;
3
+ }): Promise<void>;
4
+ //# sourceMappingURL=codemod.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codemod.d.ts","sourceRoot":"","sources":["../../src/cli/codemod.ts"],"names":[],"mappings":"AAaA,wBAAsB,gBAAgB,CACpC,SAAS,EAAE,MAAM,EACjB,OAAO,GAAE;IAAE,MAAM,CAAC,EAAE,OAAO,CAAA;CAAO,GACjC,OAAO,CAAC,IAAI,CAAC,CA+Df"}
package/dist/cli/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env bun
2
- import fs2 from 'fs';
3
- import path3 from 'path';
2
+ import fs2, { readFileSync, writeFileSync } from 'fs';
3
+ import path3, { resolve, relative } from 'path';
4
+ import { Project, SyntaxKind } from 'ts-morph';
4
5
  import { globSync } from 'tinyglobby';
5
6
  import { $ZodCodec, $ZodNumber, $ZodCustom, $ZodOptional, $ZodNullable, $ZodObject, $ZodUnion, $ZodArray, $ZodRecord, $ZodTuple, $ZodString, $ZodBoolean, $ZodNull, $ZodUndefined, $ZodAny, $ZodEnum, $ZodLiteral } from 'zod/v4/core';
6
7
 
@@ -217,6 +218,488 @@ var init_migrate = __esm({
217
218
  ];
218
219
  }
219
220
  });
221
+ function getCallObject(call) {
222
+ const expr = call.getExpression();
223
+ if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) return null;
224
+ const propAccess = expr;
225
+ return propAccess.getExpression().getText();
226
+ }
227
+ function getMethodName(call) {
228
+ const expr = call.getExpression();
229
+ if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) return null;
230
+ return expr.getName();
231
+ }
232
+ function transformWrappers(file) {
233
+ let count = 0;
234
+ const calls = file.getDescendantsOfKind(SyntaxKind.CallExpression).reverse();
235
+ for (const call of calls) {
236
+ if (call.wasForgotten()) continue;
237
+ const method = getMethodName(call);
238
+ if (!method || !WRAPPER_METHODS.includes(method)) continue;
239
+ if (call.getArguments().length > 0) continue;
240
+ const obj = getCallObject(call);
241
+ if (!obj) continue;
242
+ call.replaceWithText(`z.${method}(${obj})`);
243
+ count++;
244
+ }
245
+ return count;
246
+ }
247
+ function isNamespaceCall(obj) {
248
+ return NAMESPACE_IDENTIFIERS.has(obj.trim());
249
+ }
250
+ function isLikelySchemaExpr(obj) {
251
+ if (obj.match(/^z\.\w+\(/)) return true;
252
+ if (obj.match(/^zx\.\w+\(/)) return true;
253
+ if (obj.match(/^z\.(optional|nullable)\(/)) return true;
254
+ return false;
255
+ }
256
+ function isZodSchemaByType(call, typeChecker) {
257
+ const expr = call.getExpression();
258
+ if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) return false;
259
+ const receiver = expr.getExpression();
260
+ try {
261
+ const type = typeChecker.getTypeAtLocation(receiver);
262
+ if (type.isAny()) return null;
263
+ return type.getProperties().some((p) => p.getName() === "_zod");
264
+ } catch {
265
+ return null;
266
+ }
267
+ }
268
+ function transformChecks(file) {
269
+ let count = 0;
270
+ const calls = file.getDescendantsOfKind(SyntaxKind.CallExpression).reverse();
271
+ for (const call of calls) {
272
+ if (call.wasForgotten()) continue;
273
+ const method = getMethodName(call);
274
+ if (!method) continue;
275
+ const obj = getCallObject(call);
276
+ if (!obj) continue;
277
+ if (isNamespaceCall(obj)) continue;
278
+ const args = call.getArguments().map((a) => a.getText());
279
+ const argsStr = args.length > 0 ? args.join(", ") : "";
280
+ if (ZOD_ONLY_CHECK_METHODS.includes(method)) {
281
+ call.replaceWithText(`${obj}.check(z.${method}(${argsStr}))`);
282
+ count++;
283
+ continue;
284
+ }
285
+ if (AMBIGUOUS_CHECK_METHODS.includes(method) && isLikelySchemaExpr(obj)) {
286
+ call.replaceWithText(`${obj}.check(z.${method}(${argsStr}))`);
287
+ count++;
288
+ continue;
289
+ }
290
+ if ((method === "min" || method === "max") && isLikelySchemaExpr(obj)) {
291
+ const isString = obj.includes("z.string");
292
+ const checkName = isString ? STRING_RENAME[method] : NUMBER_RENAME[method];
293
+ call.replaceWithText(`${obj}.check(z.${checkName}(${argsStr}))`);
294
+ count++;
295
+ continue;
296
+ }
297
+ }
298
+ return count;
299
+ }
300
+ function transformMethods(file, typeChecker) {
301
+ let count = 0;
302
+ const calls = file.getDescendantsOfKind(SyntaxKind.CallExpression).reverse();
303
+ for (const call of calls) {
304
+ if (call.wasForgotten()) continue;
305
+ const method = getMethodName(call);
306
+ if (!method) continue;
307
+ const obj = getCallObject(call);
308
+ if (!obj) continue;
309
+ if (isNamespaceCall(obj)) continue;
310
+ const args = call.getArguments().map((a) => a.getText());
311
+ if (UNCONDITIONAL_TOP_LEVEL.includes(method)) {
312
+ const argsStr = args.length > 0 ? `, ${args.join(", ")}` : "";
313
+ call.replaceWithText(`z.${method}(${obj}${argsStr})`);
314
+ count++;
315
+ continue;
316
+ }
317
+ if (AMBIGUOUS_TOP_LEVEL.includes(method)) {
318
+ let isSchema;
319
+ if (typeChecker) {
320
+ const typeResult = isZodSchemaByType(call, typeChecker);
321
+ isSchema = typeResult === true || typeResult === null && isLikelySchemaExpr(obj);
322
+ } else {
323
+ isSchema = isLikelySchemaExpr(obj);
324
+ }
325
+ if (!isSchema) continue;
326
+ const argsStr = args.length > 0 ? `, ${args.join(", ")}` : "";
327
+ call.replaceWithText(`z.${method}(${obj}${argsStr})`);
328
+ count++;
329
+ continue;
330
+ }
331
+ if (RENAMED_METHODS.has(method)) {
332
+ const newName = RENAMED_METHODS.get(method);
333
+ const argsStr = args.length > 0 ? `, ${args.join(", ")}` : "";
334
+ call.replaceWithText(`z.${newName}(${obj}${argsStr})`);
335
+ count++;
336
+ continue;
337
+ }
338
+ if (method === TRANSFORM_METHOD) {
339
+ const argsStr = args.join(", ");
340
+ call.replaceWithText(`z.pipe(${obj}, z.transform(${argsStr}))`);
341
+ count++;
342
+ continue;
343
+ }
344
+ if (CHECK_WRAP_METHODS.includes(method)) {
345
+ const argsStr = args.join(", ");
346
+ call.replaceWithText(`${obj}.check(z.${method}(${argsStr}))`);
347
+ count++;
348
+ continue;
349
+ }
350
+ }
351
+ return count;
352
+ }
353
+ function transformConstructorReplacements(file) {
354
+ let count = 0;
355
+ const calls = file.getDescendantsOfKind(SyntaxKind.CallExpression).reverse();
356
+ for (const call of calls) {
357
+ if (call.wasForgotten()) continue;
358
+ const method = getMethodName(call);
359
+ if (!method) continue;
360
+ const obj = getCallObject(call);
361
+ if (!obj) continue;
362
+ if (method in CONSTRUCTOR_REPLACEMENTS && call.getArguments().length === 0) {
363
+ const match = obj.match(/^z\s*\.object\(([\s\S]*)\)$/);
364
+ if (!match) continue;
365
+ const shape = match[1];
366
+ const replacement = CONSTRUCTOR_REPLACEMENTS[method];
367
+ call.replaceWithText(`z.${replacement}(${shape})`);
368
+ count++;
369
+ continue;
370
+ }
371
+ if (method === "datetime" && /^z\s*\.string\(\s*\)$/.test(obj)) {
372
+ const args = call.getArguments().map((a) => a.getText());
373
+ const argsStr = args.length > 0 ? args.join(", ") : "";
374
+ call.replaceWithText(`z.iso.datetime(${argsStr})`);
375
+ count++;
376
+ continue;
377
+ }
378
+ }
379
+ return count;
380
+ }
381
+ function findObjectOnlyMethods(file) {
382
+ const results = [];
383
+ const calls = file.getDescendantsOfKind(SyntaxKind.CallExpression);
384
+ for (const call of calls) {
385
+ const method = getMethodName(call);
386
+ if (!method || !WARN_METHODS.includes(method)) continue;
387
+ results.push({
388
+ line: call.getStartLineNumber(),
389
+ method,
390
+ text: call.getText().slice(0, 80)
391
+ });
392
+ }
393
+ return results;
394
+ }
395
+ function transformImports(file) {
396
+ let count = 0;
397
+ const imports = file.getImportDeclarations();
398
+ for (const imp of imports) {
399
+ const moduleSpecifier = imp.getModuleSpecifierValue();
400
+ if (moduleSpecifier === "zod") {
401
+ imp.setModuleSpecifier("zod/mini");
402
+ count++;
403
+ }
404
+ }
405
+ return count;
406
+ }
407
+ function transformClassRefs(file) {
408
+ let count = 0;
409
+ const neededImports = /* @__PURE__ */ new Set();
410
+ const propAccesses = file.getDescendantsOfKind(SyntaxKind.PropertyAccessExpression);
411
+ for (const pa of propAccesses) {
412
+ if (pa.wasForgotten()) continue;
413
+ const text = pa.getText();
414
+ const replacement = CLASS_RENAMES[text];
415
+ if (!replacement) continue;
416
+ pa.replaceWithText(replacement);
417
+ neededImports.add(replacement);
418
+ count++;
419
+ }
420
+ if (neededImports.size > 0) {
421
+ const existingCoreImport = file.getImportDeclaration(
422
+ (d) => d.getModuleSpecifierValue() === "zod/v4/core"
423
+ );
424
+ if (existingCoreImport) {
425
+ for (const name of neededImports) {
426
+ if (!existingCoreImport.getNamedImports().some((n) => n.getName() === name)) {
427
+ existingCoreImport.addNamedImport(name);
428
+ }
429
+ }
430
+ } else {
431
+ const internalImport = file.getImportDeclaration(
432
+ (d) => d.getModuleSpecifierValue().endsWith("/zod-core")
433
+ );
434
+ if (internalImport) {
435
+ for (const name of neededImports) {
436
+ if (!internalImport.getNamedImports().some((n) => n.getName() === name)) {
437
+ internalImport.addNamedImport(name);
438
+ }
439
+ }
440
+ } else {
441
+ file.addImportDeclaration({
442
+ moduleSpecifier: "zod/v4/core",
443
+ namedImports: [...neededImports].sort()
444
+ });
445
+ }
446
+ }
447
+ }
448
+ return count;
449
+ }
450
+ function transformFile(file, typeChecker) {
451
+ const filePath = file.getFilePath();
452
+ let constructorReplacements = 0;
453
+ let wrappers = 0;
454
+ let checks = 0;
455
+ let methods = 0;
456
+ for (let i = 0; i < 10; i++) {
457
+ const cr = transformConstructorReplacements(file);
458
+ const w = transformWrappers(file);
459
+ const c = transformChecks(file);
460
+ const m = transformMethods(file, typeChecker);
461
+ constructorReplacements += cr;
462
+ wrappers += w;
463
+ checks += c;
464
+ methods += m;
465
+ if (cr + w + c + m === 0) break;
466
+ }
467
+ const classRefs = transformClassRefs(file);
468
+ const objectOnlyWarnings = findObjectOnlyMethods(file);
469
+ const imports = 0;
470
+ return {
471
+ filePath,
472
+ constructorReplacements,
473
+ wrappers,
474
+ checks,
475
+ methods,
476
+ imports,
477
+ classRefs,
478
+ objectOnlyWarnings,
479
+ totalChanges: constructorReplacements + wrappers + checks + methods + classRefs
480
+ };
481
+ }
482
+ function transformCode(code, options) {
483
+ try {
484
+ const project = options?.project ?? new Project({
485
+ useInMemoryFileSystem: true,
486
+ compilerOptions: { strict: false }
487
+ });
488
+ const filename = options?.filename ?? "transform.ts";
489
+ const file = project.createSourceFile(filename, code, { overwrite: true });
490
+ const typeChecker = options?.project ? project.getTypeChecker() : void 0;
491
+ const result = transformFile(file, typeChecker);
492
+ const transformed = file.getFullText();
493
+ if (options?.project) {
494
+ project.removeSourceFile(file);
495
+ }
496
+ return {
497
+ code: transformed,
498
+ changed: result.totalChanges > 0
499
+ };
500
+ } catch (err) {
501
+ const filename = options?.filename ?? "unknown";
502
+ const message = err instanceof Error ? err.message : String(err);
503
+ console.warn(`[zod-to-mini] Transform failed for ${filename}, returning original code: ${message}`);
504
+ return { code, changed: false };
505
+ }
506
+ }
507
+ 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, WARN_METHODS, CLASS_RENAMES;
508
+ var init_transforms = __esm({
509
+ "../zod-to-mini/src/transforms.ts"() {
510
+ WRAPPER_METHODS = ["optional", "nullable"];
511
+ NAMESPACE_IDENTIFIERS = /* @__PURE__ */ new Set(["z", "zx", "zm", "zod"]);
512
+ ZOD_ONLY_CHECK_METHODS = [
513
+ "email",
514
+ "url",
515
+ "uuid",
516
+ "cuid",
517
+ "cuid2",
518
+ "ulid",
519
+ "nanoid",
520
+ "emoji",
521
+ "base64",
522
+ "base64url",
523
+ "jwt",
524
+ "int",
525
+ "positive",
526
+ "negative",
527
+ "nonnegative",
528
+ "nonpositive",
529
+ "multipleOf"
530
+ ];
531
+ AMBIGUOUS_CHECK_METHODS = [
532
+ "trim",
533
+ "toLowerCase",
534
+ "toUpperCase",
535
+ "startsWith",
536
+ "endsWith",
537
+ "includes",
538
+ "regex",
539
+ "length",
540
+ "gt",
541
+ "gte",
542
+ "lt",
543
+ "lte"
544
+ ];
545
+ STRING_RENAME = {
546
+ min: "minLength",
547
+ max: "maxLength"
548
+ };
549
+ NUMBER_RENAME = {
550
+ min: "gte",
551
+ max: "lte"
552
+ };
553
+ UNCONDITIONAL_TOP_LEVEL = ["pipe", "brand"];
554
+ AMBIGUOUS_TOP_LEVEL = ["partial", "extend", "catchall", "omit", "pick"];
555
+ RENAMED_METHODS = /* @__PURE__ */ new Map([
556
+ ["default", "_default"]
557
+ ]);
558
+ TRANSFORM_METHOD = "transform";
559
+ CHECK_WRAP_METHODS = ["refine", "superRefine", "describe"];
560
+ CONSTRUCTOR_REPLACEMENTS = {
561
+ passthrough: "looseObject",
562
+ strict: "strictObject"
563
+ };
564
+ WARN_METHODS = [
565
+ "merge"
566
+ // use z.extend() or spread
567
+ ];
568
+ CLASS_RENAMES = {
569
+ "z.ZodError": "$ZodError",
570
+ "z.ZodType": "$ZodType",
571
+ "z.ZodTypeAny": "$ZodType",
572
+ "z.ZodObject": "$ZodObject",
573
+ "z.ZodArray": "$ZodArray",
574
+ "z.ZodString": "$ZodString",
575
+ "z.ZodNumber": "$ZodNumber",
576
+ "z.ZodBoolean": "$ZodBoolean",
577
+ "z.ZodOptional": "$ZodOptional",
578
+ "z.ZodNullable": "$ZodNullable",
579
+ "z.ZodUnion": "$ZodUnion",
580
+ "z.ZodEnum": "$ZodEnum",
581
+ "z.ZodLiteral": "$ZodLiteral",
582
+ "z.ZodCodec": "$ZodCodec",
583
+ "z.ZodCustom": "$ZodCustom",
584
+ "z.ZodDefault": "$ZodDefault",
585
+ "z.ZodRecord": "$ZodRecord",
586
+ "z.ZodTuple": "$ZodTuple"
587
+ };
588
+ }
589
+ });
590
+ function zodToMiniPlugin(options) {
591
+ let project;
592
+ return {
593
+ name: "zod-to-mini",
594
+ enforce: "pre",
595
+ buildStart() {
596
+ if (options?.tsconfig) {
597
+ project = new Project({
598
+ tsConfigFilePath: options.tsconfig,
599
+ skipAddingFilesFromTsConfig: true
600
+ });
601
+ }
602
+ },
603
+ transform(code, id) {
604
+ if (!/\.[jt]sx?$/.test(id)) return;
605
+ if (options?.include && !options.include.test(id)) return;
606
+ if (options?.exclude && options.exclude.test(id)) return;
607
+ if (!code.includes("'zod'") && !code.includes('"zod"') && !code.includes("z.Zod")) return;
608
+ const result = transformCode(code, {
609
+ filename: id,
610
+ project
611
+ });
612
+ if (!result.changed) return;
613
+ return { code: result.code, map: null };
614
+ }
615
+ };
616
+ }
617
+ var init_vite_plugin = __esm({
618
+ "../zod-to-mini/src/vite-plugin.ts"() {
619
+ init_transforms();
620
+ }
621
+ });
622
+
623
+ // ../zod-to-mini/src/index.ts
624
+ var src_exports = {};
625
+ __export(src_exports, {
626
+ findObjectOnlyMethods: () => findObjectOnlyMethods,
627
+ transformChecks: () => transformChecks,
628
+ transformClassRefs: () => transformClassRefs,
629
+ transformCode: () => transformCode,
630
+ transformConstructorReplacements: () => transformConstructorReplacements,
631
+ transformFile: () => transformFile,
632
+ transformImports: () => transformImports,
633
+ transformMethods: () => transformMethods,
634
+ transformWrappers: () => transformWrappers,
635
+ zodToMiniPlugin: () => zodToMiniPlugin
636
+ });
637
+ var init_src = __esm({
638
+ "../zod-to-mini/src/index.ts"() {
639
+ init_transforms();
640
+ init_vite_plugin();
641
+ }
642
+ });
643
+
644
+ // src/cli/codemod.ts
645
+ var codemod_exports = {};
646
+ __export(codemod_exports, {
647
+ runToMiniCodemod: () => runToMiniCodemod
648
+ });
649
+ async function runToMiniCodemod(targetDir, options = {}) {
650
+ const { transformCode: transformCode2, transformImports: transformImports2 } = await Promise.resolve().then(() => (init_src(), src_exports));
651
+ const { Project: Project3 } = await import('ts-morph');
652
+ const dir = resolve(process.cwd(), targetDir);
653
+ const files = globSync(["**/*.ts", "**/*.tsx"], {
654
+ cwd: dir,
655
+ ignore: ["_generated/**", "_zodvex/**", "**/*.d.ts", "node_modules/**"],
656
+ absolute: true
657
+ });
658
+ console.log(
659
+ `[zodvex codemod] ${options.dryRun ? "Dry run \u2014 " : ""}Processing ${files.length} files in ${targetDir}/`
660
+ );
661
+ console.log("");
662
+ let totalChanged = 0;
663
+ for (const filePath of files) {
664
+ const code = readFileSync(filePath, "utf-8");
665
+ if (!code.includes("'zod'") && !code.includes('"zod"')) continue;
666
+ const result = transformCode2(code);
667
+ let output = result.code;
668
+ const project = new Project3({ useInMemoryFileSystem: true });
669
+ const sf = project.createSourceFile("tmp.ts", output);
670
+ transformImports2(sf);
671
+ for (const imp of sf.getImportDeclarations()) {
672
+ const spec = imp.getModuleSpecifierValue();
673
+ if (spec === "zodvex/core") imp.setModuleSpecifier("zodvex/mini");
674
+ }
675
+ output = sf.getFullText();
676
+ if (output !== code) {
677
+ totalChanged++;
678
+ const rel = relative(process.cwd(), filePath);
679
+ if (options.dryRun) {
680
+ console.log(` would change: ${rel}`);
681
+ } else {
682
+ writeFileSync(filePath, output);
683
+ console.log(` changed: ${rel}`);
684
+ }
685
+ }
686
+ }
687
+ console.log("");
688
+ console.log(
689
+ `[zodvex codemod] ${totalChanged} file(s) ${options.dryRun ? "would be changed" : "changed"}.`
690
+ );
691
+ if (!options.dryRun && totalChanged > 0) {
692
+ console.log("");
693
+ console.log("Next steps:");
694
+ console.log(" 1. Run `zodvex generate --mini` to regenerate codegen output");
695
+ console.log(" 2. Run your type-checker and tests to verify");
696
+ console.log(" 3. To undo: git restore " + targetDir + "/");
697
+ }
698
+ }
699
+ var init_codemod = __esm({
700
+ "src/cli/codemod.ts"() {
701
+ }
702
+ });
220
703
 
221
704
  // src/meta.ts
222
705
  var META_KEY = "__zodvexMeta";
@@ -1074,6 +1557,18 @@ async function main() {
1074
1557
  }
1075
1558
  break;
1076
1559
  }
1560
+ case "codemod": {
1561
+ const toMini = process.argv.includes("--to-mini");
1562
+ if (!toMini) {
1563
+ console.error("[zodvex] No codemod specified. Available: --to-mini");
1564
+ process.exit(1);
1565
+ }
1566
+ const dryRun = process.argv.includes("--dry-run");
1567
+ const targetDir = process.argv.slice(3).find((a) => !a.startsWith("--")) ?? "convex";
1568
+ const { runToMiniCodemod: runToMiniCodemod2 } = await Promise.resolve().then(() => (init_codemod(), codemod_exports));
1569
+ await runToMiniCodemod2(targetDir, { dryRun });
1570
+ break;
1571
+ }
1077
1572
  case "help":
1078
1573
  case "--help":
1079
1574
  case "-h":
@@ -1096,6 +1591,8 @@ Usage:
1096
1591
  zodvex init Set up zodvex in an existing Convex project
1097
1592
  zodvex migrate [dir] Migrate pre-0.6 APIs (renames + import fixes)
1098
1593
  zodvex migrate [dir] --dry-run Preview changes without writing
1594
+ zodvex codemod --to-mini [dir] Convert full-zod code to zod/mini syntax
1595
+ zodvex codemod --to-mini [dir] --dry-run Preview changes without writing
1099
1596
  zodvex help Show this help message
1100
1597
 
1101
1598
  Flags:
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cli/init.ts","../../src/cli/migrate.ts","../../src/meta.ts","../../src/codegen/discovery-hooks.ts","../../src/codegen/extractCodec.ts","../../src/codegen/discover.ts","../../src/codegen/zodToSource.ts","../../src/codegen/generate.ts","../../src/cli/commands.ts","../../src/cli/index.ts"],"names":["convexDir","path","fs","exports","init","migrate"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAA,YAAA,GAAA,EAAA;AAAA,QAAA,CAAA,YAAA,EAAA;AAAA,EAAA,kBAAA,EAAA,MAAA,kBAAA;AAAA,EAAA,aAAA,EAAA,MAAA,aAAA;AAAA,EAAA,cAAA,EAAA,MAAA,cAAA;AAAA,EAAA,IAAA,EAAA,MAAA,IAAA;AAAA,E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AAA,GAAA,KAAO;AAClB,EAAA,OAAA,CAAQ,KAAA,CAAM,IAAI,OAAO,CAAA;AACzB,EAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAChB,CAAC,CAAA","file":"index.js","sourcesContent":["/**\n * zodvex init — set up zodvex in an existing Convex project.\n * Pure helper functions + interactive init orchestrator.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\n\n/**\n * Rewrites a dev script to run zodvex dev alongside convex dev using concurrently.\n * Returns null if the script doesn't contain `convex dev` or is already wrapped.\n */\nexport function rewriteDevScript(script: string): string | null {\n if (script.includes('zodvex dev')) return null\n const match = script.match(/\\b((?:bunx|npx)\\s+convex\\s+dev)\\b/)\n if (!match) return null\n return `concurrently \"zodvex dev\" \"${script}\"`\n}\n\n/**\n * Rewrites a deploy script to run zodvex generate before convex deploy.\n * Returns null if the script doesn't contain `convex deploy` or is already wrapped.\n */\nexport function rewriteDeployScript(script: string): string | null {\n if (script.includes('zodvex generate')) return null\n const match = script.match(/\\b((?:bunx|npx)\\s+convex\\s+deploy)\\b/)\n if (!match) return null\n const idx = script.indexOf(match[1])\n const before = script.slice(0, idx)\n const after = script.slice(idx)\n return `${before}zodvex generate && ${after}`\n}\n\n/**\n * Checks if concurrently is installed in the project.\n * Returns 'add' if it needs to be installed, 'exists' if already present.\n */\nexport function ensureConcurrently(pkg: {\n dependencies?: Record<string, string>\n devDependencies?: Record<string, string>\n}): 'add' | 'exists' {\n if (pkg.dependencies?.concurrently) return 'exists'\n if (pkg.devDependencies?.concurrently) return 'exists'\n return 'add'\n}\n\n/**\n * Returns updated .gitignore content with the convex/_zodvex/ entry,\n * or null if the entry already exists.\n */\nexport function gitignoreEntry(content: string): string | null {\n if (content.includes('convex/_zodvex/')) return null\n const lines = content ? content.split('\\n') : []\n lines.push('# zodvex generated files', 'convex/_zodvex/')\n return lines.join('\\n')\n}\n\n/**\n * Generates stub files in _zodvex/ so that imports resolve before the first\n * codegen run. Called by `zodvex init` and can also be called standalone.\n *\n * Creates:\n * - _zodvex/api.ts — empty registry stub\n * - _zodvex/client.ts — stub that imports from the api stub\n */\nexport function generateStubs(convexDir: string): void {\n const zodvexDir = path.join(convexDir, '_zodvex')\n fs.mkdirSync(zodvexDir, { recursive: true })\n\n const apiStub = `// Auto-generated stub. Run \\`zodvex generate\\` to populate.\nexport const zodvexRegistry = {} as const\n`\n fs.writeFileSync(path.join(zodvexDir, 'api.ts'), apiStub)\n\n const clientStub = `// Auto-generated stub. Run \\`zodvex generate\\` to populate.\nimport { zodvexRegistry } from './api'\n\nexport const useZodQuery = undefined as any\nexport const useZodMutation = undefined as any\nexport const createClient = undefined as any\n`\n fs.writeFileSync(path.join(zodvexDir, 'client.ts'), clientStub)\n}\n\n/**\n * Interactive init orchestrator — generates stubs and prints next steps.\n * Full interactive init will come in a future task.\n */\nexport async function init(): Promise<void> {\n const convexDir = path.resolve('convex')\n if (!fs.existsSync(convexDir)) {\n console.error('[zodvex] No convex/ directory found. Run this from your project root.')\n return\n }\n\n generateStubs(convexDir)\n console.log('[zodvex] Generated stub files in convex/_zodvex/')\n console.log('[zodvex] Run `zodvex generate` to populate with your models and functions.')\n}\n","/**\n * zodvex migrate — automated codemod for v0.5 → v0.6 API renames.\n *\n * Walks a directory for .ts/.tsx files, applies identifier renames,\n * transforms zid() → zx.id(), updates import specifiers, and reports\n * remaining deprecated API usage that requires manual migration.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\n\n// --- Public types ---\n\nexport type MigrateOptions = {\n dryRun: boolean\n}\n\nexport type DeprecationWarning = {\n file: string\n line: number\n symbol: string\n}\n\nexport type MigrateResult = {\n filesScanned: number\n filesChanged: number\n wouldChange: number\n remainingDeprecations: DeprecationWarning[]\n}\n\n// --- Constants ---\n\n/** Directories to skip when walking the file tree. */\nconst SKIP_DIRS = new Set(['node_modules', '.git', '_generated', '_zodvex', 'dist'])\n\n/** File extensions to process. */\nconst TS_EXTENSIONS = new Set(['.ts', '.tsx'])\n\n/**\n * Identifier renames (applied in order via replaceAll).\n * Order matters: CodecRulesConfig MUST come before CodecRules to prevent\n * partial replacement of \"CodecRulesConfig\" → \"ZodvexRulesConfig\" being\n * eaten by a premature \"CodecRules\" → \"ZodvexRules\" match.\n */\nconst IDENTIFIER_RENAMES: ReadonlyArray<[string, string]> = [\n ['CodecDatabaseReader', 'ZodvexDatabaseReader'],\n ['CodecDatabaseWriter', 'ZodvexDatabaseWriter'],\n ['CodecQueryChain', 'ZodvexQueryChain'],\n ['CodecRulesConfig', 'ZodvexRulesConfig'],\n ['CodecRules', 'ZodvexRules'],\n ['createCodecCustomization', 'createZodvexCustomization'],\n ['createCodecHelpers', 'createBoundaryHelpers'],\n ['CodecHelpersOptions', 'BoundaryHelpersOptions']\n]\n\n/** Word-boundary regex for zid( — matches standalone `zid(` but not `myzid(` or `Zid`. */\nconst ZID_CALL_RE = /\\bzid\\(/g\n\n/**\n * Deprecated symbols to scan for after migration.\n * These require manual migration and cannot be auto-renamed.\n */\nconst DEPRECATED_SYMBOLS = [\n 'zodTable',\n 'zodDoc',\n 'zodDocOrNull',\n 'zQueryBuilder',\n 'zMutationBuilder',\n 'zActionBuilder',\n 'zCustomQueryBuilder',\n 'zCustomMutationBuilder',\n 'zCustomActionBuilder',\n 'convexCodec',\n 'mapDateFieldToNumber'\n]\n\n// --- Core logic ---\n\n/**\n * Recursively collect .ts/.tsx file paths, skipping excluded directories.\n */\nfunction collectFiles(dir: string): string[] {\n const results: string[] = []\n\n function walk(current: string) {\n const entries = fs.readdirSync(current, { withFileTypes: true })\n for (const entry of entries) {\n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name)) {\n walk(path.join(current, entry.name))\n }\n } else if (entry.isFile() && TS_EXTENSIONS.has(path.extname(entry.name))) {\n results.push(path.join(current, entry.name))\n }\n }\n }\n\n walk(dir)\n return results\n}\n\n/**\n * Apply all identifier renames to file content using replaceAll.\n */\nfunction applyIdentifierRenames(content: string): string {\n let result = content\n for (const [from, to] of IDENTIFIER_RENAMES) {\n result = result.replaceAll(from, to)\n }\n return result\n}\n\n/**\n * Transform `zid(` → `zx.id(` using word-boundary regex.\n */\nfunction applyZidTransform(content: string): string {\n return content.replace(ZID_CALL_RE, 'zx.id(')\n}\n\n/**\n * Update import specifiers: remove `zid` from zodvex imports, add `zx` if not present.\n *\n * Matches import statements like:\n * import { zid } from 'zodvex'\n * import { zid, zodTable } from 'zodvex'\n * import { zid } from 'zodvex/core'\n * import { type Zid, zid } from 'zodvex'\n */\nfunction applyImportUpdates(content: string): string {\n // Match import { ... } from 'zodvex' or 'zodvex/...'\n const importRe = /import\\s*\\{([^}]+)\\}\\s*from\\s*(['\"]zodvex(?:\\/[^'\"]*)?['\"])/g\n\n return content.replace(importRe, (match, specifiers: string, moduleStr: string) => {\n // Parse the specifier list\n const specs = specifiers\n .split(',')\n .map((s: string) => s.trim())\n .filter((s: string) => s.length > 0)\n\n // Check if zid is among the specifiers (as value, not as part of \"type Zid\")\n const hasZid = specs.some((s: string) => s === 'zid' || s === ' zid')\n\n if (!hasZid) return match\n\n // Remove zid from specifiers\n const filtered = specs.filter((s: string) => s !== 'zid' && s !== ' zid')\n\n // Add zx if not already present\n const hasZx = filtered.some((s: string) => s === 'zx' || s === 'type zx' || s.endsWith(' zx'))\n if (!hasZx) {\n filtered.push('zx')\n }\n\n if (filtered.length === 0) {\n // All specifiers removed — replace with just zx\n return `import { zx } from ${moduleStr}`\n }\n\n return `import { ${filtered.join(', ')} } from ${moduleStr}`\n })\n}\n\n/**\n * Scan file content for remaining deprecated symbol usage.\n * Returns warnings with line numbers.\n */\nfunction scanDeprecations(filePath: string, content: string): DeprecationWarning[] {\n const warnings: DeprecationWarning[] = []\n const lines = content.split('\\n')\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]\n for (const symbol of DEPRECATED_SYMBOLS) {\n // Use word-boundary check to avoid false positives\n const re = new RegExp(`\\\\b${symbol}\\\\b`)\n if (re.test(line)) {\n warnings.push({\n file: filePath,\n line: i + 1, // 1-indexed\n symbol\n })\n }\n }\n }\n\n return warnings\n}\n\n/**\n * Migrate a directory of TypeScript files from old zodvex API names to new ones.\n *\n * @param dir - Root directory to scan\n * @param options - Migration options (dryRun: boolean)\n * @returns Migration results including file counts and deprecation warnings\n */\nexport function migrate(dir: string, options: MigrateOptions): MigrateResult {\n const files = collectFiles(dir)\n let filesChanged = 0\n let wouldChange = 0\n const allDeprecations: DeprecationWarning[] = []\n\n for (const filePath of files) {\n const original = fs.readFileSync(filePath, 'utf-8')\n\n // Apply transforms in sequence\n let content = original\n content = applyIdentifierRenames(content)\n content = applyZidTransform(content)\n content = applyImportUpdates(content)\n\n const changed = content !== original\n\n if (changed) {\n if (options.dryRun) {\n wouldChange++\n } else {\n fs.writeFileSync(filePath, content)\n filesChanged++\n }\n }\n\n // Scan for remaining deprecations (on the post-transform content)\n const contentToScan = changed ? content : original\n const deprecations = scanDeprecations(filePath, contentToScan)\n allDeprecations.push(...deprecations)\n }\n\n return {\n filesScanned: files.length,\n filesChanged,\n wouldChange,\n remainingDeprecations: allDeprecations\n }\n}\n","import type { $ZodType } from './zod-core'\n\nconst META_KEY = '__zodvexMeta'\n\nexport type ZodvexFunctionMeta = {\n type: 'function'\n zodArgs?: $ZodType\n zodReturns?: $ZodType\n}\n\nexport type ZodvexModelMeta = {\n type: 'model'\n tableName: string\n schemas: {\n doc: $ZodType\n insert: $ZodType\n update: $ZodType\n docArray: $ZodType\n paginatedDoc: $ZodType\n }\n}\n\nexport type ZodvexMeta = ZodvexFunctionMeta | ZodvexModelMeta\n\nexport function attachMeta(target: object, meta: ZodvexMeta): void {\n Object.defineProperty(target, META_KEY, {\n value: meta,\n enumerable: false,\n writable: false,\n configurable: false\n })\n}\n\nexport function readMeta(target: unknown): ZodvexMeta | undefined {\n if (target == null || (typeof target !== 'object' && typeof target !== 'function')) {\n return undefined\n }\n return (target as Record<string, unknown>)[META_KEY] as ZodvexMeta | undefined\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\n\n/**\n * JavaScript source for the ESM loader hook that intercepts `_generated/api`\n * imports during discovery. Runs in Node's loader thread (must be plain JS,\n * not TypeScript).\n *\n * Only `_generated/api` is stubbed — `_generated/server` re-exports generic\n * builders from `convex/server` which work natively outside the Convex runtime.\n * The api stub is needed because `_generated/api` exports a `components` object\n * that triggers component constructors at module scope (e.g. `new LocalDTA(components.localDTA)`).\n */\nconst HOOKS_SOURCE = `\nexport function resolve(specifier, context, nextResolve) {\n if (/_generated\\\\/api(\\\\.[mc]?[jt]sx?)?$/.test(specifier)) {\n return { shortCircuit: true, url: 'zodvex-stub://api' };\n }\n return nextResolve(specifier, context);\n}\n\nexport function load(url, context, nextLoad) {\n if (url === 'zodvex-stub://api') {\n return {\n shortCircuit: true,\n format: 'module',\n source: [\n 'const handler = {',\n ' get(_, prop) {',\n ' if (typeof prop === \"symbol\") return undefined;',\n ' if (prop === \"__esModule\") return true;',\n ' return new Proxy(function(){}, handler);',\n ' },',\n ' apply() { return new Proxy({}, handler); },',\n ' construct() { return new Proxy({}, handler); },',\n '};',\n 'const p = new Proxy(function(){}, handler);',\n 'export default p;',\n 'export const api = p;',\n 'export const internal = p;',\n 'export const components = p;',\n 'export const httpRouter = p;',\n ].join('\\\\n')\n };\n }\n return nextLoad(url, context);\n}\n`\n\nlet hooksRegistered = false\n\n/**\n * Registers an ESM loader hook via `Module.register()` that intercepts imports\n * of `_generated/api`, replacing it with a deeply-nested Proxy stub. Safe to\n * call multiple times.\n *\n * Only `_generated/api` is intercepted — `_generated/server` works natively\n * outside the Convex runtime.\n *\n * Returns true if hooks were registered, false if Module.register is\n * unavailable (e.g. Bun, older Node).\n */\nexport function registerDiscoveryHooks(): boolean {\n if (hooksRegistered) return true\n try {\n // Dynamic import to avoid hard dependency on node:module in non-Node runtimes\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { register } = require('node:module') as typeof import('node:module')\n if (typeof register !== 'function') return false\n register(`data:text/javascript,${encodeURIComponent(HOOKS_SOURCE)}`)\n hooksRegistered = true\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Proxy stub for _generated/api.ts.\n *\n * Replaces the real api module (which requires the Convex runtime for\n * `components`) with a deeply-nested Proxy that absorbs property access\n * and constructor calls. This lets module-scope code like\n * `new LocalDTA(components.localDTA)` succeed silently during discovery.\n */\nconst PROXY_STUB_API = `// zodvex discovery stub — replaced after discovery completes\nconst handler = {\n get(_, prop) {\n if (typeof prop === 'symbol') return undefined;\n if (prop === '__esModule') return true;\n return new Proxy(function(){}, handler);\n },\n apply() { return new Proxy(function(){}, handler); },\n construct() { return new Proxy(function(){}, handler); },\n};\nconst p = new Proxy(function(){}, handler);\nexport default p;\nexport const api = p;\nexport const internal = p;\nexport const components = p;\nexport const httpRouter = p;\n`\n\ntype StubCleanup = () => void\n\n/**\n * Writes a Proxy stub file to `_generated/api.ts` in the target convex\n * directory. This is a fallback for environments where `Module.register()`\n * is unavailable (Bun, vitest's vite-node, etc.).\n *\n * Only `_generated/api.ts` is stubbed — `_generated/server.ts` re-exports\n * generic builders from `convex/server` which work natively.\n *\n * Returns a cleanup function that restores the original file contents.\n */\nexport function writeGeneratedStubs(convexDir: string): StubCleanup {\n const generatedDir = path.join(convexDir, '_generated')\n const apiPath = path.join(generatedDir, 'api.ts')\n\n let original: string | null\n try {\n original = fs.readFileSync(apiPath, 'utf8')\n } catch {\n original = null\n }\n\n fs.mkdirSync(generatedDir, { recursive: true })\n fs.writeFileSync(apiPath, PROXY_STUB_API)\n\n return () => {\n if (original !== null) {\n fs.writeFileSync(apiPath, original)\n } else {\n try {\n fs.unlinkSync(apiPath)\n } catch {\n // File may not exist — that's fine\n }\n }\n }\n}\n","import { readMeta } from '../meta'\nimport {\n $ZodCodec,\n $ZodCustom,\n $ZodNullable,\n $ZodNumber,\n $ZodOptional,\n $ZodType\n} from '../zod-core'\n\n/**\n * Unwraps ZodOptional/ZodNullable layers to find the inner ZodCodec.\n * Returns the codec instance, or undefined if none found.\n * Skips zx.date() (ZodCodec with in=ZodNumber, out=ZodCustom).\n *\n * Used internally by the discovery pipeline to probe schemas for codecs.\n */\nexport function findCodec(schema: $ZodType): $ZodType | undefined {\n let current = schema\n for (let i = 0; i < 10; i++) {\n if (current instanceof $ZodCodec) {\n const isZxDate =\n current._zod.def.in instanceof $ZodNumber && current._zod.def.out instanceof $ZodCustom\n if (isZxDate) return undefined\n return current\n }\n if (current instanceof $ZodOptional || current instanceof $ZodNullable) {\n current = current._zod.def.innerType\n continue\n }\n break\n }\n return undefined\n}\n\n/**\n * Extracts the inner ZodCodec from a schema, throwing if none is found.\n * The codegen only emits extractCodec() calls for schemas it has verified\n * contain a codec during discovery, so a missing codec is a bug.\n *\n * Used by generated _zodvex/api.ts to extract codec references at runtime.\n */\nexport function extractCodec(schema: $ZodType): $ZodType {\n const codec = findCodec(schema)\n if (!codec) {\n throw new Error('zodvex: extractCodec() found no codec in schema — this is a codegen bug')\n }\n return codec\n}\n\n/**\n * Extracts the zodArgs schema from a zodvex-registered function.\n * Used by generated _zodvex/api.ts to access function-embedded codecs at runtime.\n */\nexport function readFnArgs(fn: unknown): $ZodType {\n const meta = readMeta(fn)\n if (!meta || meta.type !== 'function' || !meta.zodArgs) {\n throw new Error('zodvex: function has no zodArgs metadata')\n }\n return meta.zodArgs as $ZodType\n}\n\n/**\n * Extracts the zodReturns schema from a zodvex-registered function.\n * Used by generated _zodvex/api.ts to access function-embedded codecs at runtime.\n */\nexport function readFnReturns(fn: unknown): $ZodType {\n const meta = readMeta(fn)\n if (!meta || meta.type !== 'function' || !meta.zodReturns) {\n throw new Error('zodvex: function has no zodReturns metadata')\n }\n return meta.zodReturns as $ZodType\n}\n","import path from 'node:path'\nimport { globSync } from 'tinyglobby'\nimport { readMeta, type ZodvexFunctionMeta, type ZodvexModelMeta } from '../meta'\nimport {\n $ZodArray,\n $ZodCodec,\n $ZodCustom,\n $ZodNullable,\n $ZodNumber,\n $ZodObject,\n $ZodOptional,\n $ZodRecord,\n $ZodTuple,\n $ZodType,\n $ZodUnion\n} from '../zod-core'\nimport { registerDiscoveryHooks, writeGeneratedStubs } from './discovery-hooks'\nimport { findCodec } from './extractCodec'\n\nexport type DiscoveredModel = {\n exportName: string\n tableName: string\n sourceFile: string\n schemas: ZodvexModelMeta['schemas']\n}\n\nexport type DiscoveredFunction = {\n functionPath: string\n exportName: string\n sourceFile: string\n zodArgs?: ZodvexFunctionMeta['zodArgs']\n zodReturns?: ZodvexFunctionMeta['zodReturns']\n}\n\nexport type DiscoveredCodec = {\n exportName: string\n sourceFile: string\n schema: $ZodType\n}\n\nexport type ModelEmbeddedCodec = {\n codec: $ZodType\n modelExportName: string\n modelSourceFile: string\n schemaKey: string\n /** Path expression from schema root, e.g. '.shape.email' or '.shape.payload._zod.def.options[0].shape.name' */\n accessPath: string\n}\n\nexport type FunctionEmbeddedCodec = {\n codec: $ZodType\n functionExportName: string\n functionSourceFile: string\n schemaSource: 'zodArgs' | 'zodReturns'\n accessPath: string\n}\n\nexport type DiscoveryResult = {\n models: DiscoveredModel[]\n functions: DiscoveredFunction[]\n codecs: DiscoveredCodec[]\n modelCodecs: ModelEmbeddedCodec[]\n functionCodecs: FunctionEmbeddedCodec[]\n}\n\n/**\n * Recursively walks a Zod schema tree to find embedded ZodCodec instances.\n * Navigates into ZodObject shapes, ZodUnion/ZodArray/ZodRecord/ZodTuple members,\n * and unwraps ZodOptional/ZodNullable at intermediate levels.\n *\n * Builds an access path string for each discovered codec that can be used\n * in generated code to navigate from the schema root to the codec's location.\n */\nfunction walkSchemaRecursive(\n schema: $ZodType,\n accessPath: string,\n visited: Set<$ZodType>,\n seenCodecs: Set<$ZodType>,\n results: { codec: $ZodType; accessPath: string }[]\n): void {\n if (visited.has(schema)) return\n visited.add(schema)\n\n // Check if this node is/contains a codec (findCodec unwraps optional/nullable)\n const codec = findCodec(schema)\n if (codec) {\n if (!seenCodecs.has(codec)) {\n seenCodecs.add(codec)\n results.push({ codec, accessPath })\n }\n return // Codec is a leaf — don't recurse into its internals\n }\n\n // Unwrap optional/nullable to get to the structural type\n let current: $ZodType = schema\n let currentPath = accessPath\n for (let i = 0; i < 10; i++) {\n if (current instanceof $ZodOptional || current instanceof $ZodNullable) {\n current = current._zod.def.innerType\n currentPath += '._zod.def.innerType'\n } else {\n break\n }\n }\n\n if (current instanceof $ZodObject) {\n const shape = current._zod.def.shape as Record<string, $ZodType>\n if (shape) {\n for (const [field, fieldSchema] of Object.entries(shape)) {\n walkSchemaRecursive(\n fieldSchema,\n `${currentPath}.shape.${field}`,\n visited,\n seenCodecs,\n results\n )\n }\n }\n } else if (current instanceof $ZodUnion) {\n const options = current._zod.def.options\n if (options) {\n for (let i = 0; i < options.length; i++) {\n walkSchemaRecursive(\n options[i],\n `${currentPath}._zod.def.options[${i}]`,\n visited,\n seenCodecs,\n results\n )\n }\n }\n } else if (current instanceof $ZodArray) {\n const element = current._zod.def.element\n if (element) {\n walkSchemaRecursive(element, `${currentPath}._zod.def.element`, visited, seenCodecs, results)\n }\n } else if (current instanceof $ZodRecord) {\n const valueType = current._zod.def.valueType\n if (valueType) {\n walkSchemaRecursive(\n valueType,\n `${currentPath}._zod.def.valueType`,\n visited,\n seenCodecs,\n results\n )\n }\n } else if (current instanceof $ZodTuple) {\n const items = current._zod.def.items\n if (items) {\n for (let i = 0; i < items.length; i++) {\n walkSchemaRecursive(\n items[i],\n `${currentPath}._zod.def.items[${i}]`,\n visited,\n seenCodecs,\n results\n )\n }\n }\n }\n}\n\n/**\n * Walks a model's schema shapes to find embedded ZodCodec instances.\n * Recursively descends into objects, unions, arrays, records, and tuples.\n * Deduplicates by codec object identity across schema keys.\n * Skips zx.date() (handled natively by zodToSource via extractCodec).\n */\nexport function walkModelCodecs(\n modelExportName: string,\n sourceFile: string,\n schemas: ZodvexModelMeta['schemas']\n): ModelEmbeddedCodec[] {\n const found: ModelEmbeddedCodec[] = []\n const visited = new Set<$ZodType>()\n const seenCodecs = new Set<$ZodType>()\n\n for (const schemaKey of ['doc', 'insert', 'update'] as const) {\n const schema = schemas[schemaKey]\n if (!schema) continue\n\n const results: { codec: $ZodType; accessPath: string }[] = []\n walkSchemaRecursive(schema as $ZodType, '', visited, seenCodecs, results)\n\n for (const r of results) {\n found.push({\n codec: r.codec,\n modelExportName,\n modelSourceFile: sourceFile,\n schemaKey,\n accessPath: r.accessPath\n })\n }\n }\n\n return found\n}\n\n/**\n * Walks a function's zodArgs and zodReturns schemas to find embedded ZodCodec instances.\n * Same recursive descent as walkModelCodecs, but uses function metadata as the entry point.\n */\nexport function walkFunctionCodecs(functions: DiscoveredFunction[]): FunctionEmbeddedCodec[] {\n const found: FunctionEmbeddedCodec[] = []\n const visited = new Set<$ZodType>()\n const seenCodecs = new Set<$ZodType>()\n\n for (const fn of functions) {\n for (const schemaSource of ['zodArgs', 'zodReturns'] as const) {\n const schema = schemaSource === 'zodArgs' ? fn.zodArgs : fn.zodReturns\n if (!schema) continue\n\n const results: { codec: $ZodType; accessPath: string }[] = []\n walkSchemaRecursive(schema as $ZodType, '', visited, seenCodecs, results)\n\n for (const r of results) {\n found.push({\n codec: r.codec,\n functionExportName: fn.exportName,\n functionSourceFile: fn.sourceFile,\n schemaSource,\n accessPath: r.accessPath\n })\n }\n }\n }\n\n return found\n}\n\n/**\n * Discovers all zodvex-decorated modules in a convex directory.\n * Imports each .ts/.js file, reads __zodvexMeta from exports,\n * and builds a registry of models and functions.\n */\nexport async function discoverModules(convexDir: string): Promise<DiscoveryResult> {\n const models: DiscoveredModel[] = []\n const functions: DiscoveredFunction[] = []\n const codecs: DiscoveredCodec[] = []\n\n // Stub _generated/api so module-scope code that accesses Convex components\n // (e.g. `new LocalDTA(components.localDTA)`) receives a harmless Proxy\n // instead of throwing outside the Convex runtime. _generated/server is NOT\n // stubbed — it re-exports generic builders from convex/server which work natively.\n registerDiscoveryHooks()\n const cleanupStubs = writeGeneratedStubs(convexDir)\n\n const files = globSync(['**/*.{ts,js}'], {\n cwd: convexDir,\n onlyFiles: true,\n ignore: [\n '_generated/**',\n '_zodvex/**',\n 'node_modules/**',\n '**/*.d.ts',\n '**/*.test.ts',\n '**/*.test.js',\n '**/*.spec.ts',\n '**/*.spec.js',\n 'convex.config.ts',\n 'convex.config.js',\n 'crons.ts',\n 'crons.js'\n ]\n })\n\n try {\n for (const file of files) {\n const absPath = path.resolve(convexDir, file)\n\n let moduleExports: Record<string, unknown>\n try {\n moduleExports = await import(absPath)\n } catch (err) {\n console.warn(`[zodvex] Warning: Failed to import ${file}:`, (err as Error).message)\n continue\n }\n\n // Derive module name from file path (strip extension, use forward slashes).\n // Used as-is for function paths — Convex's getFunctionName() returns the full\n // relative path including any subdirectory prefix (e.g. \"api/reports:summary\").\n const moduleName = file.replace(/\\.(ts|js)$/, '').replace(/\\\\/g, '/')\n\n for (const [exportName, value] of Object.entries(moduleExports)) {\n const meta = readMeta(value)\n if (meta) {\n if (meta.type === 'model') {\n const isBarrel = /(?:^|[\\\\/])index\\.(ts|js)$/.test(file)\n const existing = models.findIndex(m => m.tableName === meta.tableName)\n if (existing >= 0) {\n // Replace barrel source with direct module source\n const existingIsBarrel = /(?:^|[\\\\/])index\\.(ts|js)$/.test(\n models[existing].sourceFile\n )\n if (existingIsBarrel && !isBarrel) {\n models[existing] = {\n exportName,\n tableName: meta.tableName,\n sourceFile: file,\n schemas: meta.schemas\n }\n }\n // If existing is direct and new is barrel, skip\n } else {\n models.push({\n exportName,\n tableName: meta.tableName,\n sourceFile: file,\n schemas: meta.schemas\n })\n }\n } else if (meta.type === 'function') {\n functions.push({\n functionPath: `${moduleName}:${exportName}`,\n exportName,\n sourceFile: file,\n zodArgs: meta.zodArgs,\n zodReturns: meta.zodReturns\n })\n }\n }\n\n // Check for exported ZodCodec instances (custom codecs)\n // Skip zx.date() — it's handled natively by zodToSource\n if (value instanceof $ZodCodec) {\n const isZxDate =\n value._zod.def.in instanceof $ZodNumber && value._zod.def.out instanceof $ZodCustom\n if (!isZxDate) {\n // Deduplicate by object identity (same codec from re-exports)\n if (!codecs.some(c => c.schema === value)) {\n codecs.push({\n exportName,\n sourceFile: file,\n schema: value as $ZodType\n })\n }\n }\n }\n }\n }\n\n const modelCodecs: ModelEmbeddedCodec[] = []\n for (const model of models) {\n const found = walkModelCodecs(model.exportName, model.sourceFile, model.schemas)\n modelCodecs.push(...found)\n }\n\n const functionCodecs = walkFunctionCodecs(functions)\n\n return { models, functions, codecs, modelCodecs, functionCodecs }\n } finally {\n cleanupStubs()\n }\n}\n","import {\n $ZodAny,\n $ZodArray,\n $ZodBoolean,\n $ZodCodec,\n $ZodCustom,\n $ZodEnum,\n $ZodLiteral,\n $ZodNull,\n $ZodNullable,\n $ZodNumber,\n $ZodObject,\n $ZodOptional,\n $ZodRecord,\n $ZodString,\n $ZodTuple,\n $ZodType,\n $ZodUndefined,\n $ZodUnion\n} from '../zod-core'\n\nexport type CodecRef = {\n exportName: string\n sourceFile: string\n}\n\nexport type UndiscoverableCodec = {\n functionPath?: string\n fieldPath: string\n}\n\nexport type ZodToSourceContext = {\n /** Map from ZodCodec schema identity → reference info */\n codecMap: Map<$ZodType, CodecRef>\n /** Accumulates needed imports: sourceFile → Set of export names */\n neededCodecImports: Map<string, Set<string>>\n /** Codecs found during serialization that aren't in the codecMap */\n undiscoverableCodecs: UndiscoverableCodec[]\n /** Emit functional forms (z.optional(x)) instead of chaining (x.optional()) for zod/mini */\n mini?: boolean\n}\n\n/**\n * Converts a runtime Zod schema to its source code representation.\n * Used by the codegen engine to serialize ad-hoc schemas in the generated api.ts.\n *\n * Supports: primitives, objects, arrays, optional, nullable, enums, literals,\n * unions, tuples, records, and zodvex extensions (zx.id, zx.date).\n *\n * Unsupported types fall back to `z.any()` with a comment.\n */\nexport function zodToSource(schema: $ZodType, ctx?: ZodToSourceContext): string {\n // Peel off wrappers first (optional, nullable)\n if (schema instanceof $ZodOptional) {\n const inner = zodToSource(schema._zod.def.innerType, ctx)\n return ctx?.mini ? `z.optional(${inner})` : `${inner}.optional()`\n }\n if (schema instanceof $ZodNullable) {\n const inner = zodToSource(schema._zod.def.innerType, ctx)\n return ctx?.mini ? `z.nullable(${inner})` : `${inner}.nullable()`\n }\n\n // zodvex extensions — detect before generic types\n\n // zx.id('tableName') — ZodString with _tableName property (set by zid())\n // Prefer _tableName check (works in both zod and zod/mini),\n // fall back to .description check (full zod only)\n if (schema instanceof $ZodString) {\n const tableName =\n (schema as any)._tableName ??\n ((schema as any).description?.startsWith('convexId:')\n ? (schema as any).description.slice('convexId:'.length)\n : undefined)\n if (tableName) {\n return `zx.id(\"${tableName}\")`\n }\n }\n\n // zx.date() — ZodCodec with in=ZodNumber, out=ZodCustom\n if (\n schema instanceof $ZodCodec &&\n schema._zod.def.in instanceof $ZodNumber &&\n schema._zod.def.out instanceof $ZodCustom\n ) {\n return 'zx.date()'\n }\n\n // Generic ZodCodec — check codec map for identity match\n if (schema instanceof $ZodCodec) {\n if (ctx?.codecMap) {\n const ref = ctx.codecMap.get(schema)\n if (ref) {\n // Track the needed import\n if (!ctx.neededCodecImports.has(ref.sourceFile)) {\n ctx.neededCodecImports.set(ref.sourceFile, new Set())\n }\n ctx.neededCodecImports.get(ref.sourceFile)?.add(ref.exportName)\n return ref.exportName\n }\n }\n // Unknown codec — fall back to wire schema with warning\n const wireSource = zodToSource(schema._zod.def.in, ctx)\n ctx?.undiscoverableCodecs?.push({ fieldPath: 'unknown' })\n return `${wireSource} /* codec: transforms lost */`\n }\n\n // Primitives\n if (schema instanceof $ZodString) return 'z.string()'\n if (schema instanceof $ZodNumber) return 'z.number()'\n if (schema instanceof $ZodBoolean) return 'z.boolean()'\n if (schema instanceof $ZodNull) return 'z.null()'\n if (schema instanceof $ZodUndefined) return 'z.undefined()'\n if (schema instanceof $ZodAny) return 'z.any()'\n\n // Objects\n if (schema instanceof $ZodObject) {\n const shape = schema._zod.def.shape\n const fields = Object.entries(shape)\n .map(([key, value]) => `${key}: ${zodToSource(value, ctx)}`)\n .join(', ')\n return `z.object({ ${fields} })`\n }\n\n // Arrays\n if (schema instanceof $ZodArray) {\n return `z.array(${zodToSource(schema._zod.def.element, ctx)})`\n }\n\n // Enums\n if (schema instanceof $ZodEnum) {\n const entries = schema._zod.def.entries\n const values = (Object.values(entries) as string[]).map((v: string) => `\"${v}\"`).join(', ')\n return `z.enum([${values}])`\n }\n\n // Literals\n if (schema instanceof $ZodLiteral) {\n const values = schema._zod.def.values\n const value = values.values().next().value\n if (typeof value === 'string') return `z.literal(\"${value}\")`\n return `z.literal(${value})`\n }\n\n // Unions\n if (schema instanceof $ZodUnion) {\n const members = schema._zod.def.options.map(s => zodToSource(s, ctx)).join(', ')\n return `z.union([${members}])`\n }\n\n // Tuples\n if (schema instanceof $ZodTuple) {\n const items = schema._zod.def.items.map(s => zodToSource(s, ctx)).join(', ')\n return `z.tuple([${items}])`\n }\n\n // Records\n if (schema instanceof $ZodRecord) {\n return `z.record(${zodToSource(schema._zod.def.keyType, ctx)}, ${zodToSource(schema._zod.def.valueType, ctx)})`\n }\n\n // Fallback for unsupported types\n const typeName = schema._zod.def.type ?? 'unknown'\n return `z.any() /* unsupported: ${typeName} */`\n}\n","import { $ZodCodec, $ZodNullable, $ZodObject, $ZodOptional, $ZodType } from '../zod-core'\nimport type {\n DiscoveredFunction,\n DiscoveredModel,\n FunctionEmbeddedCodec,\n ModelEmbeddedCodec\n} from './discover'\nimport { type CodecRef, type ZodToSourceContext, zodToSource } from './zodToSource'\n\nconst HEADER = `// AUTO-GENERATED by zodvex — do not edit\n// Run \\`zodvex generate\\` to regenerate\n`\n\nexport type GeneratedFile = { js: string; dts: string }\n\n/**\n * Produces a structural fingerprint for a ZodCodec by serializing its\n * wire (in) and runtime (out) schemas. Two factory-created codec instances\n * with the same arguments produce the same fingerprint, enabling dedup\n * even when object identity differs.\n */\nfunction fingerprintCodec(schema: $ZodType): string {\n if (!(schema instanceof $ZodCodec)) return ''\n return `${zodToSource(schema._zod.def.in)}|${zodToSource(schema._zod.def.out)}`\n}\n\n/**\n * Generates the schema file content — re-exports of all discovered models.\n * Returns { js, dts } with .js import extensions (TS resolves types from .js targets).\n */\nexport function generateSchemaFile(models: DiscoveredModel[]): GeneratedFile {\n const exports = models\n .map(m => {\n const importPath = `../${m.sourceFile.replace(/\\.ts$/, '.js')}`\n return `export { ${m.exportName} } from '${importPath}'`\n })\n .join('\\n')\n\n const content = `${HEADER}\\n${exports}\\n`\n return { js: content, dts: content }\n}\n\ntype SchemaRef = {\n importPath: string\n exportName: string\n schemaKey: string\n}\n\nexport type CodecForGeneration = {\n exportName: string\n sourceFile: string\n schema: $ZodType\n}\n\n/**\n * Peels .optional() and .nullable() wrappers from a schema and checks\n * the identity map at each level. Returns the matched ref plus a\n * function that wraps an inner source string with the appropriate\n * optional/nullable syntax (chaining or functional for mini mode).\n */\nfunction tryUnwrapToIdentity(\n schema: $ZodType,\n identityMap: Map<$ZodType, SchemaRef>,\n mini?: boolean\n): { ref: SchemaRef; wrapSource: (inner: string) => string } | null {\n let current = schema\n const wrappers: Array<'optional' | 'nullable'> = []\n const maxDepth = 5\n\n for (let i = 0; i < maxDepth; i++) {\n if (current instanceof $ZodOptional) {\n wrappers.push('optional')\n current = current._zod.def.innerType\n } else if (current instanceof $ZodNullable) {\n wrappers.push('nullable')\n current = current._zod.def.innerType\n } else {\n break\n }\n\n const ref = identityMap.get(current)\n if (ref) {\n // Wrappers collected outermost-first, apply innermost-first\n const reversed = [...wrappers].reverse()\n return {\n ref,\n wrapSource: (inner: string) => {\n let result = inner\n for (const w of reversed) {\n result = mini ? `z.${w}(${result})` : `${result}.${w}()`\n }\n return result\n }\n }\n }\n }\n\n return null\n}\n\n/**\n * Checks if a ZodObject schema is structurally equivalent to\n * someModelSchema.partial() by comparing field-by-field identity.\n *\n * Zod's .partial() wraps each field in ZodOptional, preserving\n * the inner type identity. So we check: same keys, each field\n * is ZodOptional, and each inner type === the original model field.\n */\nfunction tryMatchPartial(\n schema: $ZodType,\n identityMap: Map<$ZodType, SchemaRef>,\n mini?: boolean\n): { ref: SchemaRef; wrapSource: (inner: string) => string } | null {\n if (!(schema instanceof $ZodObject)) return null\n const candidateShape = schema._zod.def.shape as Record<string, $ZodType>\n const candidateKeys = Object.keys(candidateShape).sort()\n\n for (const [modelSchema, ref] of identityMap) {\n if (!(modelSchema instanceof $ZodObject)) continue\n const modelShape = modelSchema._zod.def.shape as Record<string, $ZodType>\n const modelKeys = Object.keys(modelShape).sort()\n\n // Same key count and same keys\n if (candidateKeys.length !== modelKeys.length) continue\n if (candidateKeys.some((k, i) => k !== modelKeys[i])) continue\n\n // Every candidate field must be ZodOptional wrapping the model field by identity\n let allMatch = true\n for (const key of candidateKeys) {\n const candidateField = candidateShape[key]\n if (!(candidateField instanceof $ZodOptional)) {\n allMatch = false\n break\n }\n const inner = candidateField._zod.def.innerType\n if (inner !== modelShape[key]) {\n allMatch = false\n break\n }\n }\n\n if (allMatch) {\n return {\n ref,\n wrapSource: (inner: string) => (mini ? `z.partial(${inner})` : `${inner}.partial()`)\n }\n }\n }\n\n return null\n}\n\n/**\n * Derives a descriptive variable name for a model-embedded codec from\n * the model export name and the access path.\n *\n * Examples:\n * ('UserModel', '.shape.email') → '_userEmail'\n * ('ActivityModel', '.shape.payload._zod.def.options[0].shape.email') → '_activityPayloadEmail'\n * ('patients', '.shape.firstName') → '_patientsFirstName'\n */\nfunction deriveCodecVarName(modelExportName: string, accessPath: string): string {\n const base = modelExportName.replace(/Model$/, '')\n const prefix = base[0].toLowerCase() + base.slice(1)\n\n const fields = [...accessPath.matchAll(/\\.shape\\.(\\w+)/g)].map(m => m[1])\n if (fields.length === 0) return `_${prefix}Codec`\n\n const fieldPart = fields.map((f, i) => (i === 0 ? f : f[0].toUpperCase() + f.slice(1))).join('')\n\n return `_${prefix}${fieldPart[0].toUpperCase() + fieldPart.slice(1)}`\n}\n\n/**\n * Generates the api.ts file content — function-to-schema registry.\n */\nexport function generateApiFile(\n functions: DiscoveredFunction[],\n models: DiscoveredModel[],\n codecs?: CodecForGeneration[],\n modelCodecs?: ModelEmbeddedCodec[],\n functionCodecs?: FunctionEmbeddedCodec[],\n options?: { mini?: boolean }\n): GeneratedFile {\n // Build identity map: runtime schema object → model reference string\n const identityMap = new Map<$ZodType, SchemaRef>()\n const neededModelImports = new Set<string>()\n\n for (const model of models) {\n const importPath = `../${model.sourceFile.replace(/\\.ts$/, '.js')}`\n for (const key of ['doc', 'insert', 'update', 'docArray', 'paginatedDoc'] as const) {\n identityMap.set(model.schemas[key] as $ZodType, {\n importPath,\n exportName: model.exportName,\n schemaKey: key\n })\n }\n }\n\n // Build codec identity map for zodToSource\n const codecMap = new Map<$ZodType, CodecRef>()\n if (codecs) {\n for (const codec of codecs) {\n const importPath = `../${codec.sourceFile.replace(/\\.ts$/, '.js')}`\n codecMap.set(codec.schema, {\n exportName: codec.exportName,\n sourceFile: importPath\n })\n }\n }\n\n // Add model-embedded codecs to the codecMap (exported codecs take precedence)\n const modelCodecVars: { varName: string; expression: string; modelExportName: string }[] = []\n const MODEL_CODEC_SENTINEL = '__model_codec__'\n if (modelCodecs) {\n for (const mc of modelCodecs) {\n // Skip if this codec is already in codecMap (exported codec takes precedence)\n if (codecMap.has(mc.codec)) continue\n\n const varName = deriveCodecVarName(mc.modelExportName, mc.accessPath)\n const expression = `extractCodec(${mc.modelExportName}.schema.${mc.schemaKey}${mc.accessPath})`\n modelCodecVars.push({ varName, expression, modelExportName: mc.modelExportName })\n codecMap.set(mc.codec, {\n exportName: varName,\n sourceFile: MODEL_CODEC_SENTINEL\n })\n }\n }\n\n // Resolve function-embedded codecs against existing codecs by structural fingerprint.\n // Factory-created codecs (like tagged(), encrypted()) produce new instances each call,\n // so identity matching fails. Fingerprinting matches by wire+runtime schema structure,\n // allowing us to reference the model/standalone codec instead of importing the function.\n // This avoids circular imports: functions.ts → _zodvex/api.ts → functionFile.ts → functions.ts\n if (functionCodecs) {\n const fingerprintMap = new Map<string, CodecRef>()\n for (const [codecSchema, ref] of codecMap) {\n const fp = fingerprintCodec(codecSchema)\n if (fp) fingerprintMap.set(fp, ref)\n }\n\n for (const fc of functionCodecs) {\n if (codecMap.has(fc.codec)) continue\n\n const fp = fingerprintCodec(fc.codec)\n const matchingRef = fp ? fingerprintMap.get(fp) : undefined\n if (matchingRef) {\n codecMap.set(fc.codec, matchingRef)\n } else {\n console.warn(\n `[zodvex] Warning: Codec in ${fc.functionExportName}() (${fc.accessPath}) has no matching model or exported codec. ` +\n `Export it standalone for full client-side codec support.`\n )\n }\n }\n }\n\n const zodToSourceCtx: ZodToSourceContext = {\n codecMap,\n neededCodecImports: new Map(),\n undiscoverableCodecs: [],\n mini: options?.mini\n }\n\n // Track which imports we need\n let needsZod = false\n let needsZx = false\n\n // Resolve each schema to either a model reference or serialized source\n function resolveSchema(schema: $ZodType | unknown): string {\n if (!schema) return 'undefined'\n const s = schema as $ZodType\n\n // 1. Direct identity match\n const ref = identityMap.get(s)\n if (ref) {\n neededModelImports.add(ref.exportName)\n return `${ref.exportName}.schema.${ref.schemaKey}`\n }\n\n // 2. Wrapper-aware identity match (peel .nullable()/.optional())\n const unwrapped = tryUnwrapToIdentity(s, identityMap, options?.mini)\n if (unwrapped) {\n neededModelImports.add(unwrapped.ref.exportName)\n const inner = `${unwrapped.ref.exportName}.schema.${unwrapped.ref.schemaKey}`\n return unwrapped.wrapSource(inner)\n }\n\n // 3. Partial-aware match (detect .partial() of a model schema)\n const partialMatch = tryMatchPartial(s, identityMap, options?.mini)\n if (partialMatch) {\n neededModelImports.add(partialMatch.ref.exportName)\n const inner = `${partialMatch.ref.exportName}.schema.${partialMatch.ref.schemaKey}`\n return partialMatch.wrapSource(inner)\n }\n\n // 4. Fall back to zodToSource (with codec context)\n const source = zodToSource(s, zodToSourceCtx)\n if (source.includes('z.')) needsZod = true\n if (source.includes('zx.')) needsZx = true\n return source\n }\n\n // Build registry entries\n const entries = functions\n .map(fn => {\n const args = resolveSchema(fn.zodArgs)\n const returns = resolveSchema(fn.zodReturns)\n return ` '${fn.functionPath}': {\\n args: ${args},\\n returns: ${returns},\\n }`\n })\n .join(',\\n')\n\n // Determine which model codec vars were actually used (referenced by zodToSource)\n const usedModelCodecVars = modelCodecVars.filter(mc => {\n const sentinelExports = zodToSourceCtx.neededCodecImports.get(MODEL_CODEC_SENTINEL)\n return sentinelExports?.has(mc.varName)\n })\n\n // Add model imports for models referenced by used model codec vars\n if (usedModelCodecVars.length > 0) {\n for (const mc of usedModelCodecVars) {\n neededModelImports.add(mc.modelExportName)\n }\n }\n\n // Build imports\n const imports: string[] = []\n const zodImport = options?.mini ? 'zod/mini' : 'zod'\n if (needsZod) imports.push(`import { z } from '${zodImport}'`)\n\n // Build single zodvex/core (or zodvex/mini) import (zx, extractCodec)\n const zodvexImport = options?.mini ? 'zodvex/mini' : 'zodvex/core'\n const coreImports: string[] = []\n if (needsZx) coreImports.push('zx')\n if (usedModelCodecVars.length > 0) coreImports.push('extractCodec')\n if (coreImports.length > 0) {\n imports.push(`import { ${coreImports.join(', ')} } from '${zodvexImport}'`)\n }\n\n for (const exportName of neededModelImports) {\n const model = models.find(m => m.exportName === exportName)\n if (model) {\n const importPath = `../${model.sourceFile.replace(/\\.ts$/, '.js')}`\n imports.push(`import { ${exportName} } from '${importPath}'`)\n }\n }\n\n // Codec imports (collected by zodToSource via context)\n for (const [importPath, exportNames] of zodToSourceCtx.neededCodecImports) {\n if (importPath === MODEL_CODEC_SENTINEL) continue\n const names = Array.from(exportNames).sort().join(', ')\n imports.push(`import { ${names} } from '${importPath}'`)\n }\n\n const importSection = imports.length > 0 ? `${imports.join('\\n')}\\n\\n` : ''\n\n // Build codec helper var declarations\n const allCodecVars = usedModelCodecVars.map(mc => `const ${mc.varName} = ${mc.expression}`)\n const codecVarSection = allCodecVars.length > 0 ? `${allCodecVars.join('\\n')}\\n\\n` : ''\n\n const js = `${HEADER}\\n${importSection}${codecVarSection}export const zodvexRegistry = {\\n${entries},\\n}\\n`\n\n const dts = options?.mini\n ? `${HEADER}\nimport type { $ZodType } from 'zod/v4/core'\n\nexport declare const zodvexRegistry: Record<string, { args: $ZodType; returns: $ZodType | undefined }>\n`\n : `${HEADER}\nimport type { ZodTypeAny } from 'zod'\n\nexport declare const zodvexRegistry: Record<string, { args: ZodTypeAny; returns: ZodTypeAny | undefined }>\n`\n\n return { js, dts }\n}\n\n/**\n * Generates the server.ts file content — concrete context types for the app's schema.\n *\n * These parallel Convex's _generated/server.ts exports (QueryCtx, MutationCtx, ActionCtx)\n * but with zodvex's codec-wrapped db types baked in.\n */\nexport function generateServerFile(): GeneratedFile {\n const js = `${HEADER}`\n\n const dts = `${HEADER}\nimport type { DataModel } from '../_generated/dataModel.js'\nimport type { ZodvexActionCtx, ZodvexMutationCtx, ZodvexQueryCtx } from 'zodvex/server'\nimport type schema from '../schema.js'\n\ntype DecodedDocs = (typeof schema)['__decodedDocs']\n\n/** Query context with codec-wrapped db (decoded types on reads). */\nexport type QueryCtx = ZodvexQueryCtx<DataModel, DecodedDocs>\n\n/** Mutation context with codec-wrapped db (decoded reads, encoded writes). */\nexport type MutationCtx = ZodvexMutationCtx<DataModel, DecodedDocs>\n\n/** Action context (no db, but runQuery/runMutation may be codec-wrapped). */\nexport type ActionCtx = ZodvexActionCtx<DataModel>\n`\n\n return { js, dts }\n}\n\n/**\n * Generates the client file content — pre-bound hooks and client factory.\n * Returns { js, dts } for .js + .d.ts output.\n */\nexport function generateClientFile(options?: { mini?: boolean }): GeneratedFile {\n const zodvexCoreImport = options?.mini ? 'zodvex/mini' : 'zodvex/core'\n // --- JS ---\n const jsImports = [\n \"import { createZodvexHooks } from 'zodvex/react'\",\n \"import { createZodvexReactClient } from 'zodvex/react'\",\n \"import { createZodvexClient } from 'zodvex/client'\",\n `import { createBoundaryHelpers } from '${zodvexCoreImport}'`,\n \"import { zodvexRegistry } from './api.js'\"\n ]\n\n const jsExports = [\n 'export const { useZodQuery, useZodMutation } = createZodvexHooks(zodvexRegistry)',\n '',\n 'export const createClient = (options) =>',\n ' createZodvexClient(zodvexRegistry, options)',\n '',\n 'export const createReactClient = (options) =>',\n ' createZodvexReactClient(zodvexRegistry, options)',\n '',\n 'export const { encodeArgs, decodeResult } = createBoundaryHelpers(zodvexRegistry)'\n ]\n\n const js = `${HEADER}\\n${jsImports.join('\\n')}\\n\\n${jsExports.join('\\n')}\\n`\n\n // --- DTS ---\n const dtsImports = [\n \"import type { ZodvexHooks } from 'zodvex/react'\",\n \"import type { ZodvexClientOptions, ZodvexClient } from 'zodvex/client'\",\n \"import type { ZodvexReactClientOptions, ZodvexReactClient } from 'zodvex/react'\",\n `import type { BoundaryHelpers } from '${zodvexCoreImport}'`\n ]\n\n const dtsDeclarations = [\n \"export declare const useZodQuery: ZodvexHooks['useZodQuery']\",\n \"export declare const useZodMutation: ZodvexHooks['useZodMutation']\",\n '',\n 'export declare const createClient: (options: ZodvexClientOptions) => ZodvexClient',\n '',\n 'export declare const createReactClient: (options: ZodvexReactClientOptions) => ZodvexReactClient',\n '',\n \"export declare const encodeArgs: BoundaryHelpers['encodeArgs']\",\n \"export declare const decodeResult: BoundaryHelpers['decodeResult']\"\n ]\n\n const dts = `${HEADER}\\n${dtsImports.join('\\n')}\\n\\n${dtsDeclarations.join('\\n')}\\n`\n\n return { js, dts }\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport { discoverModules } from '../codegen/discover'\nimport {\n generateApiFile,\n generateClientFile,\n generateSchemaFile,\n generateServerFile\n} from '../codegen/generate'\n\n/**\n * One-shot codegen. Discovers modules, generates files.\n */\nexport async function generate(convexDir?: string, options?: { mini?: boolean }): Promise<void> {\n const resolved = resolveConvexDir(convexDir)\n const zodvexDir = path.join(resolved, '_zodvex')\n\n // Ensure _zodvex/api.js exists before discovery. User modules (e.g., functions.ts)\n // may import zodvexRegistry from it. Without a stub, dynamic import() fails and\n // codegen can't discover those modules — a chicken-and-egg problem.\n writeStubApi(zodvexDir)\n\n const result = await discoverModules(resolved)\n\n const schemaContent = generateSchemaFile(result.models)\n const apiContent = generateApiFile(\n result.functions,\n result.models,\n result.codecs,\n result.modelCodecs,\n result.functionCodecs,\n { mini: options?.mini }\n )\n const clientContent = generateClientFile({ mini: options?.mini })\n const serverContent = generateServerFile()\n\n fs.mkdirSync(zodvexDir, { recursive: true })\n writeIfChanged(path.join(zodvexDir, 'schema.js'), schemaContent.js)\n writeIfChanged(path.join(zodvexDir, 'schema.d.ts'), schemaContent.dts)\n writeIfChanged(path.join(zodvexDir, 'api.js'), apiContent.js)\n writeIfChanged(path.join(zodvexDir, 'api.d.ts'), apiContent.dts)\n writeIfChanged(path.join(zodvexDir, 'client.js'), clientContent.js)\n writeIfChanged(path.join(zodvexDir, 'client.d.ts'), clientContent.dts)\n writeIfChanged(path.join(zodvexDir, 'server.js'), serverContent.js)\n writeIfChanged(path.join(zodvexDir, 'server.d.ts'), serverContent.dts)\n\n const totalCodecs =\n result.codecs.length + result.modelCodecs.length + result.functionCodecs.length\n console.log(\n `[zodvex] Generated ${result.models.length} model(s), ${result.functions.length} function(s), ${totalCodecs} codec(s)`\n )\n}\n\n/**\n * Watch mode. Runs generate() once, then watches for changes.\n */\nexport async function dev(convexDir?: string, options?: { mini?: boolean }): Promise<void> {\n const resolved = resolveConvexDir(convexDir)\n\n console.log('[zodvex] Starting watch mode...')\n await generate(resolved, options)\n\n let debounceTimer: ReturnType<typeof setTimeout> | null = null\n\n const watcher = fs.watch(resolved, { recursive: true }, (_event, filename) => {\n if (!filename) return\n // Skip generated directories and non-TS files\n if (\n filename.startsWith('_zodvex') ||\n filename.startsWith('_generated') ||\n (!filename.endsWith('.ts') && !filename.endsWith('.js'))\n ) {\n return\n }\n\n if (debounceTimer) clearTimeout(debounceTimer)\n debounceTimer = setTimeout(async () => {\n console.log('[zodvex] Regenerating...')\n try {\n await generate(resolved, options)\n } catch (err) {\n console.error('[zodvex] Generation failed:', (err as Error).message)\n }\n }, 300)\n })\n\n // Keep process alive\n process.on('SIGINT', () => {\n if (debounceTimer) clearTimeout(debounceTimer)\n watcher.close()\n process.exit(0)\n })\n}\n\n/** Writes minimal stub _zodvex/api.js + api.d.ts before discovery to break circular imports.\n * Previous generations may contain stale imports that cause cycles during re-discovery. */\nfunction writeStubApi(zodvexDir: string): void {\n fs.mkdirSync(zodvexDir, { recursive: true })\n\n fs.writeFileSync(\n path.join(zodvexDir, 'api.js'),\n '// AUTO-GENERATED by zodvex — do not edit\\n// Stub created for codegen bootstrap\\n\\nexport const zodvexRegistry = {}\\n'\n )\n\n fs.writeFileSync(\n path.join(zodvexDir, 'api.d.ts'),\n '// AUTO-GENERATED by zodvex — do not edit\\n// Stub created for codegen bootstrap\\n\\nexport declare const zodvexRegistry: Record<string, any>\\n'\n )\n}\n\n/** Only write if content differs from what's on disk — prevents file watcher loops. */\nfunction writeIfChanged(filePath: string, content: string): void {\n try {\n const existing = fs.readFileSync(filePath, 'utf-8')\n if (existing === content) return\n } catch {\n // File doesn't exist yet — write it\n }\n fs.writeFileSync(filePath, content)\n}\n\nfunction resolveConvexDir(dir?: string): string {\n if (dir) {\n const resolved = path.resolve(dir)\n if (!fs.existsSync(resolved)) {\n throw new Error(`Convex directory not found: ${resolved}`)\n }\n return resolved\n }\n\n // Default: look for ./convex/ in cwd\n const defaultDir = path.resolve('convex')\n if (!fs.existsSync(defaultDir)) {\n throw new Error('No convex/ directory found. Specify the path: zodvex generate <path>')\n }\n return defaultDir\n}\n","#!/usr/bin/env bun\nimport { dev, generate } from './commands'\n\nconst command = process.argv[2]\nconst miniFlag = process.argv.includes('--mini')\n// The convex dir arg needs to skip flags\nconst convexDir = process.argv.slice(3).find(a => !a.startsWith('--'))\n\nasync function main() {\n switch (command) {\n case 'generate':\n await generate(convexDir, { mini: miniFlag })\n break\n case 'dev':\n await dev(convexDir, { mini: miniFlag })\n break\n case 'init': {\n // Dynamic import to keep init dependencies lazy\n const { init } = await import('./init')\n await init()\n break\n }\n case 'migrate': {\n const { migrate } = await import('./migrate')\n const targetDir = process.argv[3] ?? '.'\n const dryRun = process.argv.includes('--dry-run')\n const result = migrate(targetDir, { dryRun })\n\n if (dryRun) {\n console.log(`[zodvex] Dry run: ${result.wouldChange} file(s) would be changed`)\n } else {\n console.log(`[zodvex] Migrated ${result.filesChanged} file(s)`)\n }\n\n if (result.remainingDeprecations.length > 0) {\n console.log('')\n console.log('[zodvex] Remaining deprecated API usage:')\n const grouped = new Map<string, string[]>()\n for (const d of result.remainingDeprecations) {\n const key = d.symbol\n if (!grouped.has(key)) grouped.set(key, [])\n grouped.get(key)?.push(` ${d.file}:${d.line}`)\n }\n for (const [symbol, locations] of grouped) {\n console.log(` ${symbol}:`)\n for (const loc of locations) {\n console.log(` ${loc}`)\n }\n }\n console.log('')\n console.log('See docs/migration/v0.6.md for migration guidance on structural changes.')\n }\n break\n }\n case 'help':\n case '--help':\n case '-h':\n case undefined:\n printHelp()\n break\n default:\n console.error(`Unknown command: ${command}`)\n printHelp()\n process.exit(1)\n }\n}\n\nfunction printHelp() {\n console.log(`\nzodvex - Convex codegen for Zod schemas\n\nUsage:\n zodvex generate [convex-dir] [--mini] Generate schema and validator files\n zodvex dev [convex-dir] [--mini] Watch mode — regenerate on changes\n zodvex init Set up zodvex in an existing Convex project\n zodvex migrate [dir] Migrate pre-0.6 APIs (renames + import fixes)\n zodvex migrate [dir] --dry-run Preview changes without writing\n zodvex help Show this help message\n\nFlags:\n --mini Emit zod/mini-compatible output (functional forms, zodvex/mini imports)\n`)\n}\n\nmain().catch(err => {\n console.error(err.message)\n process.exit(1)\n})\n"]}
1
+ {"version":3,"sources":["../../src/cli/init.ts","../../src/cli/migrate.ts","../../../zod-to-mini/src/transforms.ts","../../../zod-to-mini/src/vite-plugin.ts","../../../zod-to-mini/src/index.ts","../../src/cli/codemod.ts","../../src/meta.ts","../../src/codegen/discovery-hooks.ts","../../src/codegen/extractCodec.ts","../../src/codegen/discover.ts","../../src/codegen/zodToSource.ts","../../src/codegen/generate.ts","../../src/cli/commands.ts","../../src/cli/index.ts"],"names":["convexDir","path","fs","Project","transformCode","transformImports","globSync","exports","init","migrate","runToMiniCodemod"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAA,YAAA,GAAA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IAAA,CAAA,OAAA,YAAA,EAAA,EAAA,eAAA,CAAA,CAAA;AACnC,MAAA,MAAMA,iBAAAA,CAAiB,SAAA,EAAW,EAAE,MAAA,EAAQ,CAAA;AAC5C,MAAA;AAAA,IACF;AAAA,IACA,KAAK,MAAA;AAAA,IACL,KAAK,QAAA;AAAA,IACL,KAAK,IAAA;AAAA,IACL,KAAK,MAAA;AACH,MAAA,SAAA,EAAU;AACV,MAAA;AAAA,IACF;AACE,MAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,iBAAA,EAAoB,OAAO,CAAA,CAAE,CAAA;AAC3C,MAAA,SAAA,EAAU;AACV,MAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA;AAEpB;AAEA,SAAS,SAAA,GAAY;AACnB,EAAA,OAAA,CAAQ,GAAA,CAAI;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA,CAeb,CAAA;AACD;AAEA,IAAA,EAAK,CAAE,MAAM,CAAA,GAAA,KAAO;AAClB,EAAA,OAAA,CAAQ,KAAA,CAAM,IAAI,OAAO,CAAA;AACzB,EAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAChB,CAAC,CAAA","file":"index.js","sourcesContent":["/**\n * zodvex init — set up zodvex in an existing Convex project.\n * Pure helper functions + interactive init orchestrator.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\n\n/**\n * Rewrites a dev script to run zodvex dev alongside convex dev using concurrently.\n * Returns null if the script doesn't contain `convex dev` or is already wrapped.\n */\nexport function rewriteDevScript(script: string): string | null {\n if (script.includes('zodvex dev')) return null\n const match = script.match(/\\b((?:bunx|npx)\\s+convex\\s+dev)\\b/)\n if (!match) return null\n return `concurrently \"zodvex dev\" \"${script}\"`\n}\n\n/**\n * Rewrites a deploy script to run zodvex generate before convex deploy.\n * Returns null if the script doesn't contain `convex deploy` or is already wrapped.\n */\nexport function rewriteDeployScript(script: string): string | null {\n if (script.includes('zodvex generate')) return null\n const match = script.match(/\\b((?:bunx|npx)\\s+convex\\s+deploy)\\b/)\n if (!match) return null\n const idx = script.indexOf(match[1])\n const before = script.slice(0, idx)\n const after = script.slice(idx)\n return `${before}zodvex generate && ${after}`\n}\n\n/**\n * Checks if concurrently is installed in the project.\n * Returns 'add' if it needs to be installed, 'exists' if already present.\n */\nexport function ensureConcurrently(pkg: {\n dependencies?: Record<string, string>\n devDependencies?: Record<string, string>\n}): 'add' | 'exists' {\n if (pkg.dependencies?.concurrently) return 'exists'\n if (pkg.devDependencies?.concurrently) return 'exists'\n return 'add'\n}\n\n/**\n * Returns updated .gitignore content with the convex/_zodvex/ entry,\n * or null if the entry already exists.\n */\nexport function gitignoreEntry(content: string): string | null {\n if (content.includes('convex/_zodvex/')) return null\n const lines = content ? content.split('\\n') : []\n lines.push('# zodvex generated files', 'convex/_zodvex/')\n return lines.join('\\n')\n}\n\n/**\n * Generates stub files in _zodvex/ so that imports resolve before the first\n * codegen run. Called by `zodvex init` and can also be called standalone.\n *\n * Creates:\n * - _zodvex/api.ts — empty registry stub\n * - _zodvex/client.ts — stub that imports from the api stub\n */\nexport function generateStubs(convexDir: string): void {\n const zodvexDir = path.join(convexDir, '_zodvex')\n fs.mkdirSync(zodvexDir, { recursive: true })\n\n const apiStub = `// Auto-generated stub. Run \\`zodvex generate\\` to populate.\nexport const zodvexRegistry = {} as const\n`\n fs.writeFileSync(path.join(zodvexDir, 'api.ts'), apiStub)\n\n const clientStub = `// Auto-generated stub. Run \\`zodvex generate\\` to populate.\nimport { zodvexRegistry } from './api'\n\nexport const useZodQuery = undefined as any\nexport const useZodMutation = undefined as any\nexport const createClient = undefined as any\n`\n fs.writeFileSync(path.join(zodvexDir, 'client.ts'), clientStub)\n}\n\n/**\n * Interactive init orchestrator — generates stubs and prints next steps.\n * Full interactive init will come in a future task.\n */\nexport async function init(): Promise<void> {\n const convexDir = path.resolve('convex')\n if (!fs.existsSync(convexDir)) {\n console.error('[zodvex] No convex/ directory found. Run this from your project root.')\n return\n }\n\n generateStubs(convexDir)\n console.log('[zodvex] Generated stub files in convex/_zodvex/')\n console.log('[zodvex] Run `zodvex generate` to populate with your models and functions.')\n}\n","/**\n * zodvex migrate — automated codemod for v0.5 → v0.6 API renames.\n *\n * Walks a directory for .ts/.tsx files, applies identifier renames,\n * transforms zid() → zx.id(), updates import specifiers, and reports\n * remaining deprecated API usage that requires manual migration.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\n\n// --- Public types ---\n\nexport type MigrateOptions = {\n dryRun: boolean\n}\n\nexport type DeprecationWarning = {\n file: string\n line: number\n symbol: string\n}\n\nexport type MigrateResult = {\n filesScanned: number\n filesChanged: number\n wouldChange: number\n remainingDeprecations: DeprecationWarning[]\n}\n\n// --- Constants ---\n\n/** Directories to skip when walking the file tree. */\nconst SKIP_DIRS = new Set(['node_modules', '.git', '_generated', '_zodvex', 'dist'])\n\n/** File extensions to process. */\nconst TS_EXTENSIONS = new Set(['.ts', '.tsx'])\n\n/**\n * Identifier renames (applied in order via replaceAll).\n * Order matters: CodecRulesConfig MUST come before CodecRules to prevent\n * partial replacement of \"CodecRulesConfig\" → \"ZodvexRulesConfig\" being\n * eaten by a premature \"CodecRules\" → \"ZodvexRules\" match.\n */\nconst IDENTIFIER_RENAMES: ReadonlyArray<[string, string]> = [\n ['CodecDatabaseReader', 'ZodvexDatabaseReader'],\n ['CodecDatabaseWriter', 'ZodvexDatabaseWriter'],\n ['CodecQueryChain', 'ZodvexQueryChain'],\n ['CodecRulesConfig', 'ZodvexRulesConfig'],\n ['CodecRules', 'ZodvexRules'],\n ['createCodecCustomization', 'createZodvexCustomization'],\n ['createCodecHelpers', 'createBoundaryHelpers'],\n ['CodecHelpersOptions', 'BoundaryHelpersOptions']\n]\n\n/** Word-boundary regex for zid( — matches standalone `zid(` but not `myzid(` or `Zid`. */\nconst ZID_CALL_RE = /\\bzid\\(/g\n\n/**\n * Deprecated symbols to scan for after migration.\n * These require manual migration and cannot be auto-renamed.\n */\nconst DEPRECATED_SYMBOLS = [\n 'zodTable',\n 'zodDoc',\n 'zodDocOrNull',\n 'zQueryBuilder',\n 'zMutationBuilder',\n 'zActionBuilder',\n 'zCustomQueryBuilder',\n 'zCustomMutationBuilder',\n 'zCustomActionBuilder',\n 'convexCodec',\n 'mapDateFieldToNumber'\n]\n\n// --- Core logic ---\n\n/**\n * Recursively collect .ts/.tsx file paths, skipping excluded directories.\n */\nfunction collectFiles(dir: string): string[] {\n const results: string[] = []\n\n function walk(current: string) {\n const entries = fs.readdirSync(current, { withFileTypes: true })\n for (const entry of entries) {\n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name)) {\n walk(path.join(current, entry.name))\n }\n } else if (entry.isFile() && TS_EXTENSIONS.has(path.extname(entry.name))) {\n results.push(path.join(current, entry.name))\n }\n }\n }\n\n walk(dir)\n return results\n}\n\n/**\n * Apply all identifier renames to file content using replaceAll.\n */\nfunction applyIdentifierRenames(content: string): string {\n let result = content\n for (const [from, to] of IDENTIFIER_RENAMES) {\n result = result.replaceAll(from, to)\n }\n return result\n}\n\n/**\n * Transform `zid(` → `zx.id(` using word-boundary regex.\n */\nfunction applyZidTransform(content: string): string {\n return content.replace(ZID_CALL_RE, 'zx.id(')\n}\n\n/**\n * Update import specifiers: remove `zid` from zodvex imports, add `zx` if not present.\n *\n * Matches import statements like:\n * import { zid } from 'zodvex'\n * import { zid, zodTable } from 'zodvex'\n * import { zid } from 'zodvex/core'\n * import { type Zid, zid } from 'zodvex'\n */\nfunction applyImportUpdates(content: string): string {\n // Match import { ... } from 'zodvex' or 'zodvex/...'\n const importRe = /import\\s*\\{([^}]+)\\}\\s*from\\s*(['\"]zodvex(?:\\/[^'\"]*)?['\"])/g\n\n return content.replace(importRe, (match, specifiers: string, moduleStr: string) => {\n // Parse the specifier list\n const specs = specifiers\n .split(',')\n .map((s: string) => s.trim())\n .filter((s: string) => s.length > 0)\n\n // Check if zid is among the specifiers (as value, not as part of \"type Zid\")\n const hasZid = specs.some((s: string) => s === 'zid' || s === ' zid')\n\n if (!hasZid) return match\n\n // Remove zid from specifiers\n const filtered = specs.filter((s: string) => s !== 'zid' && s !== ' zid')\n\n // Add zx if not already present\n const hasZx = filtered.some((s: string) => s === 'zx' || s === 'type zx' || s.endsWith(' zx'))\n if (!hasZx) {\n filtered.push('zx')\n }\n\n if (filtered.length === 0) {\n // All specifiers removed — replace with just zx\n return `import { zx } from ${moduleStr}`\n }\n\n return `import { ${filtered.join(', ')} } from ${moduleStr}`\n })\n}\n\n/**\n * Scan file content for remaining deprecated symbol usage.\n * Returns warnings with line numbers.\n */\nfunction scanDeprecations(filePath: string, content: string): DeprecationWarning[] {\n const warnings: DeprecationWarning[] = []\n const lines = content.split('\\n')\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]\n for (const symbol of DEPRECATED_SYMBOLS) {\n // Use word-boundary check to avoid false positives\n const re = new RegExp(`\\\\b${symbol}\\\\b`)\n if (re.test(line)) {\n warnings.push({\n file: filePath,\n line: i + 1, // 1-indexed\n symbol\n })\n }\n }\n }\n\n return warnings\n}\n\n/**\n * Migrate a directory of TypeScript files from old zodvex API names to new ones.\n *\n * @param dir - Root directory to scan\n * @param options - Migration options (dryRun: boolean)\n * @returns Migration results including file counts and deprecation warnings\n */\nexport function migrate(dir: string, options: MigrateOptions): MigrateResult {\n const files = collectFiles(dir)\n let filesChanged = 0\n let wouldChange = 0\n const allDeprecations: DeprecationWarning[] = []\n\n for (const filePath of files) {\n const original = fs.readFileSync(filePath, 'utf-8')\n\n // Apply transforms in sequence\n let content = original\n content = applyIdentifierRenames(content)\n content = applyZidTransform(content)\n content = applyImportUpdates(content)\n\n const changed = content !== original\n\n if (changed) {\n if (options.dryRun) {\n wouldChange++\n } else {\n fs.writeFileSync(filePath, content)\n filesChanged++\n }\n }\n\n // Scan for remaining deprecations (on the post-transform content)\n const contentToScan = changed ? content : original\n const deprecations = scanDeprecations(filePath, contentToScan)\n allDeprecations.push(...deprecations)\n }\n\n return {\n filesScanned: files.length,\n filesChanged,\n wouldChange,\n remainingDeprecations: allDeprecations\n }\n}\n","/**\n * AST transforms for converting Zod v4 full syntax to zod/mini functional forms.\n *\n * Each transform handles one category of method-to-function conversion.\n * Transforms are applied repeatedly until no more changes are made (fixed-point).\n */\nimport { Project, type SourceFile, SyntaxKind, type CallExpression, type PropertyAccessExpression, type TypeChecker } from 'ts-morph'\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Get the full text of a call expression's object (everything before the `.method()`).\n * For `z.string().optional()`, returns `z.string()`.\n */\nfunction getCallObject(call: CallExpression): string | null {\n const expr = call.getExpression()\n if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) return null\n const propAccess = expr as PropertyAccessExpression\n return propAccess.getExpression().getText()\n}\n\n/**\n * Get the method name from a call expression.\n * For `z.string().optional()`, returns `optional`.\n */\nfunction getMethodName(call: CallExpression): string | null {\n const expr = call.getExpression()\n if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) return null\n return (expr as PropertyAccessExpression).getName()\n}\n\n// ---------------------------------------------------------------------------\n// Transform: method wrappers → functional wrappers\n// .optional() → z.optional(expr)\n// .nullable() → z.nullable(expr)\n// ---------------------------------------------------------------------------\n\nconst WRAPPER_METHODS = ['optional', 'nullable'] as const\n\nexport function transformWrappers(file: SourceFile): number {\n let count = 0\n\n // Process innermost calls first by reversing (deepest nodes last in AST order)\n const calls = file.getDescendantsOfKind(SyntaxKind.CallExpression).reverse()\n\n for (const call of calls) {\n if (call.wasForgotten()) continue\n const method = getMethodName(call)\n if (!method || !WRAPPER_METHODS.includes(method as any)) continue\n if (call.getArguments().length > 0) continue // .optional(value) is different\n\n const obj = getCallObject(call)\n if (!obj) continue\n\n // Replace `expr.optional()` → `z.optional(expr)`\n call.replaceWithText(`z.${method}(${obj})`)\n count++\n }\n\n return count\n}\n\n// ---------------------------------------------------------------------------\n// Transform: string/number validation methods → .check()\n// .email() → .check(z.email())\n// .url() → .check(z.url())\n// .min(n) → .check(z.minLength(n)) / .check(z.min(n))\n// .max(n) → .check(z.maxLength(n)) / .check(z.max(n))\n// .length(n) → .check(z.length(n))\n// .regex(r) → .check(z.regex(r))\n// .trim() → .check(z.trim())\n// .toLowerCase() → .check(z.toLowerCase())\n// .toUpperCase() → .check(z.toUpperCase())\n// .startsWith(s) → .check(z.startsWith(s))\n// .endsWith(s) → .check(z.endsWith(s))\n// .includes(s) → .check(z.includes(s))\n// .int() → .check(z.int())\n// .positive() → .check(z.positive())\n// .negative() → .check(z.negative())\n// .nonnegative() → .check(z.nonnegative())\n// .nonpositive() → .check(z.nonpositive())\n// .multipleOf(n) → .check(z.multipleOf(n))\n// .finite() → .check(z.finite()) — not in mini, but included for completeness\n//\n// Special cases:\n// .min(n) on string → z.minLength(n)\n// .max(n) on string → z.maxLength(n)\n// .min(n) on number → z.min(n) (same name but standalone)\n// .max(n) on number → z.max(n)\n// ---------------------------------------------------------------------------\n\n/** Identifiers that are Zod/zodvex namespaces, not schema expressions.\n * Calls like `z.string()`, `zx.date()` are constructors, not method chains. */\nconst NAMESPACE_IDENTIFIERS = new Set(['z', 'zx', 'zm', 'zod'])\n\n/** Returns true if the object expression is a bare namespace (z, zx, zm) */\nfunction isNamespaceCall(obj: string): boolean {\n return NAMESPACE_IDENTIFIERS.has(obj.trim())\n}\n\n/** Check methods UNIQUE to Zod that have verified standalone z.methodName() equivalents.\n * EXCLUDED: ip, cidr, datetime, duration, finite, safe — no standalone functions. */\nconst ZOD_ONLY_CHECK_METHODS = [\n 'email', 'url', 'uuid', 'cuid', 'cuid2', 'ulid', 'nanoid',\n 'emoji', 'base64', 'base64url', 'jwt',\n 'int', 'positive', 'negative', 'nonnegative', 'nonpositive',\n 'multipleOf',\n] as const\n\n/** Check methods that COLLIDE with standard JS methods (String.startsWith, etc.).\n * Only convert these when the object expression is clearly a Zod schema chain\n * (starts with z. or is a known schema construction pattern). */\nconst AMBIGUOUS_CHECK_METHODS = [\n 'trim', 'toLowerCase', 'toUpperCase',\n 'startsWith', 'endsWith', 'includes', 'regex',\n 'length',\n 'gt', 'gte', 'lt', 'lte',\n] as const\n\n/** Returns true if the object expression looks like a Zod schema chain */\nfunction isLikelySchemaExpr(obj: string): boolean {\n // z.string(), z.number(), z.object({...}), z.array(...), etc.\n if (obj.match(/^z\\.\\w+\\(/)) return true\n // zx.id(...), zx.date(), etc.\n if (obj.match(/^zx\\.\\w+\\(/)) return true\n // Chained schema: something.check(...), z.optional(...)\n if (obj.match(/^z\\.(optional|nullable)\\(/)) return true\n return false\n}\n\n/**\n * Uses the TypeScript type checker to determine if the receiver of a method call\n * is a Zod schema. Checks for the `_zod` property which exists on every Zod schema\n * instance (both full zod and zod/mini).\n *\n * Returns:\n * - `true` — the receiver is confirmed to be a Zod schema\n * - `false` — the receiver is confirmed to NOT be a Zod schema\n * - `null` — the type checker couldn't determine the type (e.g., `any`)\n * Callers should fall back to the syntactic heuristic.\n */\nfunction isZodSchemaByType(call: CallExpression, typeChecker: TypeChecker): boolean | null {\n const expr = call.getExpression()\n if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) return false\n const receiver = (expr as PropertyAccessExpression).getExpression()\n\n try {\n const type = typeChecker.getTypeAtLocation(receiver)\n // If the type resolved to `any`, the checker couldn't determine the actual type.\n // This happens after AST mutations (e.g., z.partial(...) is not in zod's type defs)\n // or for unresolvable expressions. Return null to signal \"unknown\".\n if (type.isAny()) return null\n return type.getProperties().some(p => p.getName() === '_zod')\n } catch {\n return null\n }\n}\n\n/** Methods that need renaming for string context */\nconst STRING_RENAME: Record<string, string> = {\n min: 'minLength',\n max: 'maxLength',\n}\n\n/** Number .min()/.max() → z.gte()/z.lte() (the standalone names differ from the method names) */\nconst NUMBER_RENAME: Record<string, string> = {\n min: 'gte',\n max: 'lte',\n}\n\nexport function transformChecks(file: SourceFile): number {\n let count = 0\n const calls = file.getDescendantsOfKind(SyntaxKind.CallExpression).reverse()\n\n for (const call of calls) {\n if (call.wasForgotten()) continue\n const method = getMethodName(call)\n if (!method) continue\n\n const obj = getCallObject(call)\n if (!obj) continue\n\n // Skip namespace calls (z.email() is a constructor, not a method chain)\n if (isNamespaceCall(obj)) continue\n\n const args = call.getArguments().map(a => a.getText())\n const argsStr = args.length > 0 ? args.join(', ') : ''\n\n // Zod-unique check methods — safe to convert unconditionally\n if ((ZOD_ONLY_CHECK_METHODS as readonly string[]).includes(method)) {\n call.replaceWithText(`${obj}.check(z.${method}(${argsStr}))`)\n count++\n continue\n }\n\n // Ambiguous methods — only convert when the object is clearly a schema\n if ((AMBIGUOUS_CHECK_METHODS as readonly string[]).includes(method) && isLikelySchemaExpr(obj)) {\n call.replaceWithText(`${obj}.check(z.${method}(${argsStr}))`)\n count++\n continue\n }\n\n // .min()/.max() — only on schema expressions, context-dependent rename\n if ((method === 'min' || method === 'max') && isLikelySchemaExpr(obj)) {\n const isString = obj.includes('z.string')\n const checkName = isString ? STRING_RENAME[method] : NUMBER_RENAME[method]\n call.replaceWithText(`${obj}.check(z.${checkName}(${argsStr}))`)\n count++\n continue\n }\n }\n\n return count\n}\n\n// ---------------------------------------------------------------------------\n// Transform: schema methods → top-level functions\n// schema.transform(fn) → z.transform(schema, fn)\n// schema.refine(fn, opts) → schema.check(z.refine(fn, opts))\n// schema.superRefine(fn) → schema.check(z.superRefine(fn))\n// schema.describe(str) → schema.check(z.describe(str))\n// schema.default(val) → z.default(schema, val) — NOT in mini, but transform anyway\n// schema.pipe(other) → z.pipe(schema, other)\n// schema.brand(tag) → z.brand(schema, tag)\n// ---------------------------------------------------------------------------\n\n/** Methods that become z.methodName(schema, ...args) — safe to transform unconditionally */\nconst UNCONDITIONAL_TOP_LEVEL = ['pipe', 'brand'] as const\n\n/** Methods that become z.methodName(schema, ...args) — only transform when receiver is\n * confirmed as a Zod schema. These method names collide with non-Zod APIs\n * (e.g., ConvexCodec.pick(), Lodash.extend()). Without type info, we fall back to\n * the isLikelySchemaExpr heuristic. */\nconst AMBIGUOUS_TOP_LEVEL = ['partial', 'extend', 'catchall', 'omit', 'pick'] as const\n\n/** schema.default(val) → z._default(schema, val) — underscore-prefixed in mini */\nconst RENAMED_METHODS = new Map<string, string>([\n ['default', '_default'],\n])\n\n/** schema.transform(fn) → z.pipe(schema, z.transform(fn)) */\nconst TRANSFORM_METHOD = 'transform'\n\n/** Methods that become schema.check(z.methodName(...args)) */\nconst CHECK_WRAP_METHODS = ['refine', 'superRefine', 'describe'] as const\n\nexport function transformMethods(file: SourceFile, typeChecker?: TypeChecker): number {\n let count = 0\n const calls = file.getDescendantsOfKind(SyntaxKind.CallExpression).reverse()\n\n for (const call of calls) {\n if (call.wasForgotten()) continue\n const method = getMethodName(call)\n if (!method) continue\n\n const obj = getCallObject(call)\n if (!obj) continue\n\n // Skip namespace calls (z.transform() is a constructor, not a method chain)\n if (isNamespaceCall(obj)) continue\n\n const args = call.getArguments().map(a => a.getText())\n\n // Unconditional top-level: always safe to transform (no name collisions)\n if ((UNCONDITIONAL_TOP_LEVEL as readonly string[]).includes(method)) {\n const argsStr = args.length > 0 ? `, ${args.join(', ')}` : ''\n call.replaceWithText(`z.${method}(${obj}${argsStr})`)\n count++\n continue\n }\n\n // Ambiguous top-level: only transform when receiver is a Zod schema.\n if ((AMBIGUOUS_TOP_LEVEL as readonly string[]).includes(method)) {\n let isSchema: boolean\n if (typeChecker) {\n const typeResult = isZodSchemaByType(call, typeChecker)\n // true = confirmed schema, false = confirmed non-schema, null = unknown (any)\n // When the type checker returns null (couldn't resolve), fall back to the heuristic.\n // This happens after AST mutations create z.partial(...) etc. which don't exist in\n // zod's type definitions (they're zod/mini constructs).\n isSchema = typeResult === true || (typeResult === null && isLikelySchemaExpr(obj))\n } else {\n isSchema = isLikelySchemaExpr(obj)\n }\n if (!isSchema) continue\n\n const argsStr = args.length > 0 ? `, ${args.join(', ')}` : ''\n call.replaceWithText(`z.${method}(${obj}${argsStr})`)\n count++\n continue\n }\n\n // Renamed methods: schema.default(val) → z._default(schema, val)\n if (RENAMED_METHODS.has(method)) {\n const newName = RENAMED_METHODS.get(method)!\n const argsStr = args.length > 0 ? `, ${args.join(', ')}` : ''\n call.replaceWithText(`z.${newName}(${obj}${argsStr})`)\n count++\n continue\n }\n\n // schema.transform(fn) → z.pipe(schema, z.transform(fn))\n if (method === TRANSFORM_METHOD) {\n const argsStr = args.join(', ')\n call.replaceWithText(`z.pipe(${obj}, z.transform(${argsStr}))`)\n count++\n continue\n }\n\n // Check-wrap form: schema.method(args) → schema.check(z.method(args))\n if ((CHECK_WRAP_METHODS as readonly string[]).includes(method)) {\n const argsStr = args.join(', ')\n call.replaceWithText(`${obj}.check(z.${method}(${argsStr}))`)\n count++\n continue\n }\n\n }\n\n return count\n}\n\n// ---------------------------------------------------------------------------\n// Transform: constructor-replacing methods\n// z.object(shape).passthrough() → z.looseObject(shape)\n// z.object(shape).strict() → z.strictObject(shape)\n//\n// These change the constructor, so the object expression MUST be z.object(shape).\n// We extract the shape argument from z.object() and emit the replacement constructor.\n// ---------------------------------------------------------------------------\n\nconst CONSTRUCTOR_REPLACEMENTS: Record<string, string> = {\n passthrough: 'looseObject',\n strict: 'strictObject',\n}\n\nexport function transformConstructorReplacements(file: SourceFile): number {\n let count = 0\n const calls = file.getDescendantsOfKind(SyntaxKind.CallExpression).reverse()\n\n for (const call of calls) {\n if (call.wasForgotten()) continue\n const method = getMethodName(call)\n if (!method) continue\n\n const obj = getCallObject(call)\n if (!obj) continue\n\n // z.object(shape).passthrough() → z.looseObject(shape)\n // z.object(shape).strict() → z.strictObject(shape)\n if (method in CONSTRUCTOR_REPLACEMENTS && call.getArguments().length === 0) {\n // Must be z.object(shape) — allow optional whitespace between z and .object(\n const match = obj.match(/^z\\s*\\.object\\(([\\s\\S]*)\\)$/)\n if (!match) continue\n\n const shape = match[1]\n const replacement = CONSTRUCTOR_REPLACEMENTS[method]\n call.replaceWithText(`z.${replacement}(${shape})`)\n count++\n continue\n }\n\n // z.string().datetime(opts?) → z.iso.datetime(opts?)\n // In zod/mini, .datetime() is not a method on string — it's z.iso.datetime().\n if (method === 'datetime' && /^z\\s*\\.string\\(\\s*\\)$/.test(obj)) {\n const args = call.getArguments().map(a => a.getText())\n const argsStr = args.length > 0 ? args.join(', ') : ''\n call.replaceWithText(`z.iso.datetime(${argsStr})`)\n count++\n continue\n }\n }\n\n return count\n}\n\n// ---------------------------------------------------------------------------\n// Warnings: methods that need manual attention\n// ---------------------------------------------------------------------------\n\n/** Methods that need manual attention — not auto-convertible */\nconst WARN_METHODS = [\n 'merge', // use z.extend() or spread\n] as const\n\nexport function findObjectOnlyMethods(file: SourceFile): Array<{ line: number; method: string; text: string }> {\n const results: Array<{ line: number; method: string; text: string }> = []\n const calls = file.getDescendantsOfKind(SyntaxKind.CallExpression)\n\n for (const call of calls) {\n const method = getMethodName(call)\n if (!method || !(WARN_METHODS as readonly string[]).includes(method)) continue\n results.push({\n line: call.getStartLineNumber(),\n method,\n text: call.getText().slice(0, 80),\n })\n }\n\n return results\n}\n\n// ---------------------------------------------------------------------------\n// Transform: import paths\n// import { z } from 'zod' → import { z } from 'zod/mini'\n// import { ZodError } from 'zod' → import { ZodError } from 'zod/mini'\n// ---------------------------------------------------------------------------\n\nexport function transformImports(file: SourceFile): number {\n let count = 0\n const imports = file.getImportDeclarations()\n\n for (const imp of imports) {\n const moduleSpecifier = imp.getModuleSpecifierValue()\n if (moduleSpecifier === 'zod') {\n imp.setModuleSpecifier('zod/mini')\n count++\n }\n }\n\n return count\n}\n\n// ---------------------------------------------------------------------------\n// Transform: class references\n// z.ZodError → $ZodError (+ add import from zod/v4/core)\n// z.ZodObject → $ZodObject\n// z.ZodType → $ZodType\n// z.ZodTypeAny → $ZodType\n// etc.\n// ---------------------------------------------------------------------------\n\nconst CLASS_RENAMES: Record<string, string> = {\n 'z.ZodError': '$ZodError',\n 'z.ZodType': '$ZodType',\n 'z.ZodTypeAny': '$ZodType',\n 'z.ZodObject': '$ZodObject',\n 'z.ZodArray': '$ZodArray',\n 'z.ZodString': '$ZodString',\n 'z.ZodNumber': '$ZodNumber',\n 'z.ZodBoolean': '$ZodBoolean',\n 'z.ZodOptional': '$ZodOptional',\n 'z.ZodNullable': '$ZodNullable',\n 'z.ZodUnion': '$ZodUnion',\n 'z.ZodEnum': '$ZodEnum',\n 'z.ZodLiteral': '$ZodLiteral',\n 'z.ZodCodec': '$ZodCodec',\n 'z.ZodCustom': '$ZodCustom',\n 'z.ZodDefault': '$ZodDefault',\n 'z.ZodRecord': '$ZodRecord',\n 'z.ZodTuple': '$ZodTuple',\n}\n\nexport function transformClassRefs(file: SourceFile): number {\n let count = 0\n const neededImports = new Set<string>()\n\n // Find all property access expressions like z.ZodError\n const propAccesses = file.getDescendantsOfKind(SyntaxKind.PropertyAccessExpression)\n\n for (const pa of propAccesses) {\n if (pa.wasForgotten()) continue\n const text = pa.getText()\n const replacement = CLASS_RENAMES[text]\n if (!replacement) continue\n\n pa.replaceWithText(replacement)\n neededImports.add(replacement)\n count++\n }\n\n // Add import for the core types if needed\n if (neededImports.size > 0) {\n const existingCoreImport = file.getImportDeclaration(d =>\n d.getModuleSpecifierValue() === 'zod/v4/core'\n )\n\n if (existingCoreImport) {\n // Add to existing import\n for (const name of neededImports) {\n if (!existingCoreImport.getNamedImports().some(n => n.getName() === name)) {\n existingCoreImport.addNamedImport(name)\n }\n }\n } else {\n // Check for ../src/zod-core import (internal zodvex tests)\n const internalImport = file.getImportDeclaration(d =>\n d.getModuleSpecifierValue().endsWith('/zod-core')\n )\n if (internalImport) {\n for (const name of neededImports) {\n if (!internalImport.getNamedImports().some(n => n.getName() === name)) {\n internalImport.addNamedImport(name)\n }\n }\n } else {\n // Add new import\n file.addImportDeclaration({\n moduleSpecifier: 'zod/v4/core',\n namedImports: [...neededImports].sort(),\n })\n }\n }\n }\n\n return count\n}\n\n// ---------------------------------------------------------------------------\n// Main: apply all transforms in fixed-point loop\n// ---------------------------------------------------------------------------\n\nexport interface TransformResult {\n filePath: string\n constructorReplacements: number\n wrappers: number\n checks: number\n methods: number\n imports: number\n classRefs: number\n objectOnlyWarnings: Array<{ line: number; method: string; text: string }>\n totalChanges: number\n}\n\nexport function transformFile(file: SourceFile, typeChecker?: TypeChecker): TransformResult {\n const filePath = file.getFilePath()\n let constructorReplacements = 0\n let wrappers = 0\n let checks = 0\n let methods = 0\n\n // Fixed-point loop: transforms may create new opportunities\n // (e.g., unwrapping .optional() reveals .email() underneath)\n for (let i = 0; i < 10; i++) {\n // Constructor replacements FIRST — they change z.object(shape).passthrough()\n // into z.looseObject(shape), which may then have .optional() etc. on the outside\n const cr = transformConstructorReplacements(file)\n const w = transformWrappers(file)\n const c = transformChecks(file)\n const m = transformMethods(file, typeChecker)\n constructorReplacements += cr\n wrappers += w\n checks += c\n methods += m\n if (cr + w + c + m === 0) break\n }\n\n const classRefs = transformClassRefs(file)\n const objectOnlyWarnings = findObjectOnlyMethods(file)\n\n // Import transform is done LAST (after all other transforms)\n // so we don't accidentally affect the transform logic\n // NOTE: We do NOT transform imports by default — the caller decides\n const imports = 0\n\n return {\n filePath,\n constructorReplacements,\n wrappers,\n checks,\n methods,\n imports,\n classRefs,\n objectOnlyWarnings,\n totalChanges: constructorReplacements + wrappers + checks + methods + classRefs,\n }\n}\n\n// ---------------------------------------------------------------------------\n// String-in/string-out convenience wrapper\n// ---------------------------------------------------------------------------\n\n/**\n * String-in/string-out transform wrapper.\n * Creates an in-memory ts-morph project, applies all transforms, returns the result.\n *\n * If ts-morph throws during transformation (e.g., a manipulation error from an\n * unhandled code pattern), the original code is returned unchanged. This ensures\n * the vite plugin never crashes the build — the file simply runs un-transformed.\n */\nexport function transformCode(\n code: string,\n options?: { filename?: string; project?: Project }\n): { code: string; changed: boolean } {\n try {\n const project = options?.project ?? new Project({\n useInMemoryFileSystem: true,\n compilerOptions: { strict: false },\n })\n const filename = options?.filename ?? 'transform.ts'\n const file = project.createSourceFile(filename, code, { overwrite: true })\n\n const typeChecker = options?.project\n ? project.getTypeChecker()\n : undefined\n\n const result = transformFile(file, typeChecker)\n const transformed = file.getFullText()\n\n // Clean up the source file from the project if we're reusing it\n if (options?.project) {\n project.removeSourceFile(file)\n }\n\n return {\n code: transformed,\n changed: result.totalChanges > 0,\n }\n } catch (err) {\n const filename = options?.filename ?? 'unknown'\n const message = err instanceof Error ? err.message : String(err)\n console.warn(`[zod-to-mini] Transform failed for ${filename}, returning original code: ${message}`)\n return { code, changed: false }\n }\n}\n","import { Project } from 'ts-morph'\nimport type { Plugin } from 'vite'\nimport { transformCode } from './transforms'\n\nexport interface ZodToMiniPluginOptions {\n /** Only transform files matching this pattern. Default: all .ts/.tsx/.js/.jsx files */\n include?: RegExp\n /** Skip files matching this pattern. Default: none */\n exclude?: RegExp\n /** Path to tsconfig.json for type-aware transforms. When provided, ambiguous methods\n * (pick, extend, partial, omit, catchall) are only transformed when the receiver is\n * confirmed to be a Zod schema via the TypeScript type checker. Without this, falls\n * back to a syntactic heuristic (isLikelySchemaExpr). */\n tsconfig?: string\n}\n\n/**\n * Vite plugin that transforms full-zod method chains to zod/mini functional forms.\n *\n * Use alongside resolve.alias to rewrite import paths:\n * resolve: { alias: [{ find: /^zod$/, replacement: 'zod/mini' }] }\n *\n * The alias handles import path rewriting. This plugin handles code transforms:\n * .optional() → z.optional(schema)\n * .email() → .check(z.email())\n * .extend() → z.extend(schema, shape)\n * z.ZodError → $ZodError (+ import from zod/v4/core)\n * etc.\n */\nexport function zodToMiniPlugin(options?: ZodToMiniPluginOptions): Plugin {\n let project: Project | undefined\n\n return {\n name: 'zod-to-mini',\n enforce: 'pre',\n\n buildStart() {\n if (options?.tsconfig) {\n project = new Project({\n tsConfigFilePath: options.tsconfig,\n skipAddingFilesFromTsConfig: true,\n })\n }\n },\n\n transform(code, id) {\n // Only process JS/TS files\n if (!/\\.[jt]sx?$/.test(id)) return\n\n // Apply include/exclude filters\n if (options?.include && !options.include.test(id)) return\n if (options?.exclude && options.exclude.test(id)) return\n\n // Only transform files that import from 'zod' (not 'zod/mini' or 'zod/v4/core').\n if (!code.includes(\"'zod'\") && !code.includes('\"zod\"') && !code.includes('z.Zod')) return\n\n const result = transformCode(code, {\n filename: id,\n project,\n })\n\n if (!result.changed) return\n\n return { code: result.code, map: null }\n },\n }\n}\n","export { transformFile, transformCode, transformWrappers, transformChecks, transformMethods, transformConstructorReplacements, transformImports, transformClassRefs, findObjectOnlyMethods } from './transforms'\nexport type { TransformResult } from './transforms'\nexport { zodToMiniPlugin } from './vite-plugin'\nexport type { ZodToMiniPluginOptions } from './vite-plugin'\n","/**\n * zodvex codemod --to-mini\n *\n * One-time migration from full-zod to zod/mini syntax.\n * Transforms method chains to functional forms, rewrites imports.\n *\n * This modifies files in-place. Use --dry-run to preview changes.\n * To undo: git restore <dir>\n */\nimport { readFileSync, writeFileSync } from 'fs'\nimport { relative, resolve } from 'path'\nimport { globSync } from 'tinyglobby'\n\nexport async function runToMiniCodemod(\n targetDir: string,\n options: { dryRun?: boolean } = {}\n): Promise<void> {\n // Import directly from workspace package (not zodvex/labs which is the published re-export)\n const { transformCode, transformImports } = await import('zod-to-mini')\n const { Project } = await import('ts-morph')\n\n const dir = resolve(process.cwd(), targetDir)\n const files = globSync(['**/*.ts', '**/*.tsx'], {\n cwd: dir,\n ignore: ['_generated/**', '_zodvex/**', '**/*.d.ts', 'node_modules/**'],\n absolute: true\n })\n\n console.log(\n `[zodvex codemod] ${options.dryRun ? 'Dry run — ' : ''}Processing ${files.length} files in ${targetDir}/`\n )\n console.log('')\n\n let totalChanged = 0\n\n for (const filePath of files) {\n const code = readFileSync(filePath, 'utf-8')\n\n // Skip files that don't reference zod\n if (!code.includes(\"'zod'\") && !code.includes('\"zod\"')) continue\n\n // Apply all zod→mini code transforms\n const result = transformCode(code)\n let output = result.code\n\n // Transform imports: 'zod' → 'zod/mini', 'zodvex/core' → 'zodvex/mini'\n const project = new Project({ useInMemoryFileSystem: true })\n const sf = project.createSourceFile('tmp.ts', output)\n transformImports(sf)\n for (const imp of sf.getImportDeclarations()) {\n const spec = imp.getModuleSpecifierValue()\n if (spec === 'zodvex/core') imp.setModuleSpecifier('zodvex/mini')\n }\n output = sf.getFullText()\n\n if (output !== code) {\n totalChanged++\n const rel = relative(process.cwd(), filePath)\n if (options.dryRun) {\n console.log(` would change: ${rel}`)\n } else {\n writeFileSync(filePath, output)\n console.log(` changed: ${rel}`)\n }\n }\n }\n\n console.log('')\n console.log(\n `[zodvex codemod] ${totalChanged} file(s) ${options.dryRun ? 'would be changed' : 'changed'}.`\n )\n\n if (!options.dryRun && totalChanged > 0) {\n console.log('')\n console.log('Next steps:')\n console.log(' 1. Run `zodvex generate --mini` to regenerate codegen output')\n console.log(' 2. Run your type-checker and tests to verify')\n console.log(' 3. To undo: git restore ' + targetDir + '/')\n }\n}\n","import type { $ZodType } from './zod-core'\n\nconst META_KEY = '__zodvexMeta'\n\nexport type ZodvexFunctionMeta = {\n type: 'function'\n zodArgs?: $ZodType\n zodReturns?: $ZodType\n}\n\nexport type ZodvexModelMeta = {\n type: 'model'\n tableName: string\n schemas: {\n doc: $ZodType\n insert: $ZodType\n update: $ZodType\n docArray: $ZodType\n paginatedDoc: $ZodType\n }\n}\n\nexport type ZodvexMeta = ZodvexFunctionMeta | ZodvexModelMeta\n\nexport function attachMeta(target: object, meta: ZodvexMeta): void {\n Object.defineProperty(target, META_KEY, {\n value: meta,\n enumerable: false,\n writable: false,\n configurable: false\n })\n}\n\nexport function readMeta(target: unknown): ZodvexMeta | undefined {\n if (target == null || (typeof target !== 'object' && typeof target !== 'function')) {\n return undefined\n }\n return (target as Record<string, unknown>)[META_KEY] as ZodvexMeta | undefined\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\n\n/**\n * JavaScript source for the ESM loader hook that intercepts `_generated/api`\n * imports during discovery. Runs in Node's loader thread (must be plain JS,\n * not TypeScript).\n *\n * Only `_generated/api` is stubbed — `_generated/server` re-exports generic\n * builders from `convex/server` which work natively outside the Convex runtime.\n * The api stub is needed because `_generated/api` exports a `components` object\n * that triggers component constructors at module scope (e.g. `new LocalDTA(components.localDTA)`).\n */\nconst HOOKS_SOURCE = `\nexport function resolve(specifier, context, nextResolve) {\n if (/_generated\\\\/api(\\\\.[mc]?[jt]sx?)?$/.test(specifier)) {\n return { shortCircuit: true, url: 'zodvex-stub://api' };\n }\n return nextResolve(specifier, context);\n}\n\nexport function load(url, context, nextLoad) {\n if (url === 'zodvex-stub://api') {\n return {\n shortCircuit: true,\n format: 'module',\n source: [\n 'const handler = {',\n ' get(_, prop) {',\n ' if (typeof prop === \"symbol\") return undefined;',\n ' if (prop === \"__esModule\") return true;',\n ' return new Proxy(function(){}, handler);',\n ' },',\n ' apply() { return new Proxy({}, handler); },',\n ' construct() { return new Proxy({}, handler); },',\n '};',\n 'const p = new Proxy(function(){}, handler);',\n 'export default p;',\n 'export const api = p;',\n 'export const internal = p;',\n 'export const components = p;',\n 'export const httpRouter = p;',\n ].join('\\\\n')\n };\n }\n return nextLoad(url, context);\n}\n`\n\nlet hooksRegistered = false\n\n/**\n * Registers an ESM loader hook via `Module.register()` that intercepts imports\n * of `_generated/api`, replacing it with a deeply-nested Proxy stub. Safe to\n * call multiple times.\n *\n * Only `_generated/api` is intercepted — `_generated/server` works natively\n * outside the Convex runtime.\n *\n * Returns true if hooks were registered, false if Module.register is\n * unavailable (e.g. Bun, older Node).\n */\nexport function registerDiscoveryHooks(): boolean {\n if (hooksRegistered) return true\n try {\n // Dynamic import to avoid hard dependency on node:module in non-Node runtimes\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { register } = require('node:module') as typeof import('node:module')\n if (typeof register !== 'function') return false\n register(`data:text/javascript,${encodeURIComponent(HOOKS_SOURCE)}`)\n hooksRegistered = true\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Proxy stub for _generated/api.ts.\n *\n * Replaces the real api module (which requires the Convex runtime for\n * `components`) with a deeply-nested Proxy that absorbs property access\n * and constructor calls. This lets module-scope code like\n * `new LocalDTA(components.localDTA)` succeed silently during discovery.\n */\nconst PROXY_STUB_API = `// zodvex discovery stub — replaced after discovery completes\nconst handler = {\n get(_, prop) {\n if (typeof prop === 'symbol') return undefined;\n if (prop === '__esModule') return true;\n return new Proxy(function(){}, handler);\n },\n apply() { return new Proxy(function(){}, handler); },\n construct() { return new Proxy(function(){}, handler); },\n};\nconst p = new Proxy(function(){}, handler);\nexport default p;\nexport const api = p;\nexport const internal = p;\nexport const components = p;\nexport const httpRouter = p;\n`\n\ntype StubCleanup = () => void\n\n/**\n * Writes a Proxy stub file to `_generated/api.ts` in the target convex\n * directory. This is a fallback for environments where `Module.register()`\n * is unavailable (Bun, vitest's vite-node, etc.).\n *\n * Only `_generated/api.ts` is stubbed — `_generated/server.ts` re-exports\n * generic builders from `convex/server` which work natively.\n *\n * Returns a cleanup function that restores the original file contents.\n */\nexport function writeGeneratedStubs(convexDir: string): StubCleanup {\n const generatedDir = path.join(convexDir, '_generated')\n const apiPath = path.join(generatedDir, 'api.ts')\n\n let original: string | null\n try {\n original = fs.readFileSync(apiPath, 'utf8')\n } catch {\n original = null\n }\n\n fs.mkdirSync(generatedDir, { recursive: true })\n fs.writeFileSync(apiPath, PROXY_STUB_API)\n\n return () => {\n if (original !== null) {\n fs.writeFileSync(apiPath, original)\n } else {\n try {\n fs.unlinkSync(apiPath)\n } catch {\n // File may not exist — that's fine\n }\n }\n }\n}\n","import { readMeta } from '../meta'\nimport {\n $ZodCodec,\n $ZodCustom,\n $ZodNullable,\n $ZodNumber,\n $ZodOptional,\n $ZodType\n} from '../zod-core'\n\n/**\n * Unwraps ZodOptional/ZodNullable layers to find the inner ZodCodec.\n * Returns the codec instance, or undefined if none found.\n * Skips zx.date() (ZodCodec with in=ZodNumber, out=ZodCustom).\n *\n * Used internally by the discovery pipeline to probe schemas for codecs.\n */\nexport function findCodec(schema: $ZodType): $ZodType | undefined {\n let current = schema\n for (let i = 0; i < 10; i++) {\n if (current instanceof $ZodCodec) {\n const isZxDate =\n current._zod.def.in instanceof $ZodNumber && current._zod.def.out instanceof $ZodCustom\n if (isZxDate) return undefined\n return current\n }\n if (current instanceof $ZodOptional || current instanceof $ZodNullable) {\n current = current._zod.def.innerType\n continue\n }\n break\n }\n return undefined\n}\n\n/**\n * Extracts the inner ZodCodec from a schema, throwing if none is found.\n * The codegen only emits extractCodec() calls for schemas it has verified\n * contain a codec during discovery, so a missing codec is a bug.\n *\n * Used by generated _zodvex/api.ts to extract codec references at runtime.\n */\nexport function extractCodec(schema: $ZodType): $ZodType {\n const codec = findCodec(schema)\n if (!codec) {\n throw new Error('zodvex: extractCodec() found no codec in schema — this is a codegen bug')\n }\n return codec\n}\n\n/**\n * Extracts the zodArgs schema from a zodvex-registered function.\n * Used by generated _zodvex/api.ts to access function-embedded codecs at runtime.\n */\nexport function readFnArgs(fn: unknown): $ZodType {\n const meta = readMeta(fn)\n if (!meta || meta.type !== 'function' || !meta.zodArgs) {\n throw new Error('zodvex: function has no zodArgs metadata')\n }\n return meta.zodArgs as $ZodType\n}\n\n/**\n * Extracts the zodReturns schema from a zodvex-registered function.\n * Used by generated _zodvex/api.ts to access function-embedded codecs at runtime.\n */\nexport function readFnReturns(fn: unknown): $ZodType {\n const meta = readMeta(fn)\n if (!meta || meta.type !== 'function' || !meta.zodReturns) {\n throw new Error('zodvex: function has no zodReturns metadata')\n }\n return meta.zodReturns as $ZodType\n}\n","import path from 'node:path'\nimport { globSync } from 'tinyglobby'\nimport { readMeta, type ZodvexFunctionMeta, type ZodvexModelMeta } from '../meta'\nimport {\n $ZodArray,\n $ZodCodec,\n $ZodCustom,\n $ZodNullable,\n $ZodNumber,\n $ZodObject,\n $ZodOptional,\n $ZodRecord,\n $ZodTuple,\n $ZodType,\n $ZodUnion\n} from '../zod-core'\nimport { registerDiscoveryHooks, writeGeneratedStubs } from './discovery-hooks'\nimport { findCodec } from './extractCodec'\n\nexport type DiscoveredModel = {\n exportName: string\n tableName: string\n sourceFile: string\n schemas: ZodvexModelMeta['schemas']\n}\n\nexport type DiscoveredFunction = {\n functionPath: string\n exportName: string\n sourceFile: string\n zodArgs?: ZodvexFunctionMeta['zodArgs']\n zodReturns?: ZodvexFunctionMeta['zodReturns']\n}\n\nexport type DiscoveredCodec = {\n exportName: string\n sourceFile: string\n schema: $ZodType\n}\n\nexport type ModelEmbeddedCodec = {\n codec: $ZodType\n modelExportName: string\n modelSourceFile: string\n schemaKey: string\n /** Path expression from schema root, e.g. '.shape.email' or '.shape.payload._zod.def.options[0].shape.name' */\n accessPath: string\n}\n\nexport type FunctionEmbeddedCodec = {\n codec: $ZodType\n functionExportName: string\n functionSourceFile: string\n schemaSource: 'zodArgs' | 'zodReturns'\n accessPath: string\n}\n\nexport type DiscoveryResult = {\n models: DiscoveredModel[]\n functions: DiscoveredFunction[]\n codecs: DiscoveredCodec[]\n modelCodecs: ModelEmbeddedCodec[]\n functionCodecs: FunctionEmbeddedCodec[]\n}\n\n/**\n * Recursively walks a Zod schema tree to find embedded ZodCodec instances.\n * Navigates into ZodObject shapes, ZodUnion/ZodArray/ZodRecord/ZodTuple members,\n * and unwraps ZodOptional/ZodNullable at intermediate levels.\n *\n * Builds an access path string for each discovered codec that can be used\n * in generated code to navigate from the schema root to the codec's location.\n */\nfunction walkSchemaRecursive(\n schema: $ZodType,\n accessPath: string,\n visited: Set<$ZodType>,\n seenCodecs: Set<$ZodType>,\n results: { codec: $ZodType; accessPath: string }[]\n): void {\n if (visited.has(schema)) return\n visited.add(schema)\n\n // Check if this node is/contains a codec (findCodec unwraps optional/nullable)\n const codec = findCodec(schema)\n if (codec) {\n if (!seenCodecs.has(codec)) {\n seenCodecs.add(codec)\n results.push({ codec, accessPath })\n }\n return // Codec is a leaf — don't recurse into its internals\n }\n\n // Unwrap optional/nullable to get to the structural type\n let current: $ZodType = schema\n let currentPath = accessPath\n for (let i = 0; i < 10; i++) {\n if (current instanceof $ZodOptional || current instanceof $ZodNullable) {\n current = current._zod.def.innerType\n currentPath += '._zod.def.innerType'\n } else {\n break\n }\n }\n\n if (current instanceof $ZodObject) {\n const shape = current._zod.def.shape as Record<string, $ZodType>\n if (shape) {\n for (const [field, fieldSchema] of Object.entries(shape)) {\n walkSchemaRecursive(\n fieldSchema,\n `${currentPath}.shape.${field}`,\n visited,\n seenCodecs,\n results\n )\n }\n }\n } else if (current instanceof $ZodUnion) {\n const options = current._zod.def.options\n if (options) {\n for (let i = 0; i < options.length; i++) {\n walkSchemaRecursive(\n options[i],\n `${currentPath}._zod.def.options[${i}]`,\n visited,\n seenCodecs,\n results\n )\n }\n }\n } else if (current instanceof $ZodArray) {\n const element = current._zod.def.element\n if (element) {\n walkSchemaRecursive(element, `${currentPath}._zod.def.element`, visited, seenCodecs, results)\n }\n } else if (current instanceof $ZodRecord) {\n const valueType = current._zod.def.valueType\n if (valueType) {\n walkSchemaRecursive(\n valueType,\n `${currentPath}._zod.def.valueType`,\n visited,\n seenCodecs,\n results\n )\n }\n } else if (current instanceof $ZodTuple) {\n const items = current._zod.def.items\n if (items) {\n for (let i = 0; i < items.length; i++) {\n walkSchemaRecursive(\n items[i],\n `${currentPath}._zod.def.items[${i}]`,\n visited,\n seenCodecs,\n results\n )\n }\n }\n }\n}\n\n/**\n * Walks a model's schema shapes to find embedded ZodCodec instances.\n * Recursively descends into objects, unions, arrays, records, and tuples.\n * Deduplicates by codec object identity across schema keys.\n * Skips zx.date() (handled natively by zodToSource via extractCodec).\n */\nexport function walkModelCodecs(\n modelExportName: string,\n sourceFile: string,\n schemas: ZodvexModelMeta['schemas']\n): ModelEmbeddedCodec[] {\n const found: ModelEmbeddedCodec[] = []\n const visited = new Set<$ZodType>()\n const seenCodecs = new Set<$ZodType>()\n\n for (const schemaKey of ['doc', 'insert', 'update'] as const) {\n const schema = schemas[schemaKey]\n if (!schema) continue\n\n const results: { codec: $ZodType; accessPath: string }[] = []\n walkSchemaRecursive(schema as $ZodType, '', visited, seenCodecs, results)\n\n for (const r of results) {\n found.push({\n codec: r.codec,\n modelExportName,\n modelSourceFile: sourceFile,\n schemaKey,\n accessPath: r.accessPath\n })\n }\n }\n\n return found\n}\n\n/**\n * Walks a function's zodArgs and zodReturns schemas to find embedded ZodCodec instances.\n * Same recursive descent as walkModelCodecs, but uses function metadata as the entry point.\n */\nexport function walkFunctionCodecs(functions: DiscoveredFunction[]): FunctionEmbeddedCodec[] {\n const found: FunctionEmbeddedCodec[] = []\n const visited = new Set<$ZodType>()\n const seenCodecs = new Set<$ZodType>()\n\n for (const fn of functions) {\n for (const schemaSource of ['zodArgs', 'zodReturns'] as const) {\n const schema = schemaSource === 'zodArgs' ? fn.zodArgs : fn.zodReturns\n if (!schema) continue\n\n const results: { codec: $ZodType; accessPath: string }[] = []\n walkSchemaRecursive(schema as $ZodType, '', visited, seenCodecs, results)\n\n for (const r of results) {\n found.push({\n codec: r.codec,\n functionExportName: fn.exportName,\n functionSourceFile: fn.sourceFile,\n schemaSource,\n accessPath: r.accessPath\n })\n }\n }\n }\n\n return found\n}\n\n/**\n * Discovers all zodvex-decorated modules in a convex directory.\n * Imports each .ts/.js file, reads __zodvexMeta from exports,\n * and builds a registry of models and functions.\n */\nexport async function discoverModules(convexDir: string): Promise<DiscoveryResult> {\n const models: DiscoveredModel[] = []\n const functions: DiscoveredFunction[] = []\n const codecs: DiscoveredCodec[] = []\n\n // Stub _generated/api so module-scope code that accesses Convex components\n // (e.g. `new LocalDTA(components.localDTA)`) receives a harmless Proxy\n // instead of throwing outside the Convex runtime. _generated/server is NOT\n // stubbed — it re-exports generic builders from convex/server which work natively.\n registerDiscoveryHooks()\n const cleanupStubs = writeGeneratedStubs(convexDir)\n\n const files = globSync(['**/*.{ts,js}'], {\n cwd: convexDir,\n onlyFiles: true,\n ignore: [\n '_generated/**',\n '_zodvex/**',\n 'node_modules/**',\n '**/*.d.ts',\n '**/*.test.ts',\n '**/*.test.js',\n '**/*.spec.ts',\n '**/*.spec.js',\n 'convex.config.ts',\n 'convex.config.js',\n 'crons.ts',\n 'crons.js'\n ]\n })\n\n try {\n for (const file of files) {\n const absPath = path.resolve(convexDir, file)\n\n let moduleExports: Record<string, unknown>\n try {\n moduleExports = await import(absPath)\n } catch (err) {\n console.warn(`[zodvex] Warning: Failed to import ${file}:`, (err as Error).message)\n continue\n }\n\n // Derive module name from file path (strip extension, use forward slashes).\n // Used as-is for function paths — Convex's getFunctionName() returns the full\n // relative path including any subdirectory prefix (e.g. \"api/reports:summary\").\n const moduleName = file.replace(/\\.(ts|js)$/, '').replace(/\\\\/g, '/')\n\n for (const [exportName, value] of Object.entries(moduleExports)) {\n const meta = readMeta(value)\n if (meta) {\n if (meta.type === 'model') {\n const isBarrel = /(?:^|[\\\\/])index\\.(ts|js)$/.test(file)\n const existing = models.findIndex(m => m.tableName === meta.tableName)\n if (existing >= 0) {\n // Replace barrel source with direct module source\n const existingIsBarrel = /(?:^|[\\\\/])index\\.(ts|js)$/.test(\n models[existing].sourceFile\n )\n if (existingIsBarrel && !isBarrel) {\n models[existing] = {\n exportName,\n tableName: meta.tableName,\n sourceFile: file,\n schemas: meta.schemas\n }\n }\n // If existing is direct and new is barrel, skip\n } else {\n models.push({\n exportName,\n tableName: meta.tableName,\n sourceFile: file,\n schemas: meta.schemas\n })\n }\n } else if (meta.type === 'function') {\n functions.push({\n functionPath: `${moduleName}:${exportName}`,\n exportName,\n sourceFile: file,\n zodArgs: meta.zodArgs,\n zodReturns: meta.zodReturns\n })\n }\n }\n\n // Check for exported ZodCodec instances (custom codecs)\n // Skip zx.date() — it's handled natively by zodToSource\n if (value instanceof $ZodCodec) {\n const isZxDate =\n value._zod.def.in instanceof $ZodNumber && value._zod.def.out instanceof $ZodCustom\n if (!isZxDate) {\n // Deduplicate by object identity (same codec from re-exports)\n if (!codecs.some(c => c.schema === value)) {\n codecs.push({\n exportName,\n sourceFile: file,\n schema: value as $ZodType\n })\n }\n }\n }\n }\n }\n\n const modelCodecs: ModelEmbeddedCodec[] = []\n for (const model of models) {\n const found = walkModelCodecs(model.exportName, model.sourceFile, model.schemas)\n modelCodecs.push(...found)\n }\n\n const functionCodecs = walkFunctionCodecs(functions)\n\n return { models, functions, codecs, modelCodecs, functionCodecs }\n } finally {\n cleanupStubs()\n }\n}\n","import {\n $ZodAny,\n $ZodArray,\n $ZodBoolean,\n $ZodCodec,\n $ZodCustom,\n $ZodEnum,\n $ZodLiteral,\n $ZodNull,\n $ZodNullable,\n $ZodNumber,\n $ZodObject,\n $ZodOptional,\n $ZodRecord,\n $ZodString,\n $ZodTuple,\n $ZodType,\n $ZodUndefined,\n $ZodUnion\n} from '../zod-core'\n\nexport type CodecRef = {\n exportName: string\n sourceFile: string\n}\n\nexport type UndiscoverableCodec = {\n functionPath?: string\n fieldPath: string\n}\n\nexport type ZodToSourceContext = {\n /** Map from ZodCodec schema identity → reference info */\n codecMap: Map<$ZodType, CodecRef>\n /** Accumulates needed imports: sourceFile → Set of export names */\n neededCodecImports: Map<string, Set<string>>\n /** Codecs found during serialization that aren't in the codecMap */\n undiscoverableCodecs: UndiscoverableCodec[]\n /** Emit functional forms (z.optional(x)) instead of chaining (x.optional()) for zod/mini */\n mini?: boolean\n}\n\n/**\n * Converts a runtime Zod schema to its source code representation.\n * Used by the codegen engine to serialize ad-hoc schemas in the generated api.ts.\n *\n * Supports: primitives, objects, arrays, optional, nullable, enums, literals,\n * unions, tuples, records, and zodvex extensions (zx.id, zx.date).\n *\n * Unsupported types fall back to `z.any()` with a comment.\n */\nexport function zodToSource(schema: $ZodType, ctx?: ZodToSourceContext): string {\n // Peel off wrappers first (optional, nullable)\n if (schema instanceof $ZodOptional) {\n const inner = zodToSource(schema._zod.def.innerType, ctx)\n return ctx?.mini ? `z.optional(${inner})` : `${inner}.optional()`\n }\n if (schema instanceof $ZodNullable) {\n const inner = zodToSource(schema._zod.def.innerType, ctx)\n return ctx?.mini ? `z.nullable(${inner})` : `${inner}.nullable()`\n }\n\n // zodvex extensions — detect before generic types\n\n // zx.id('tableName') — ZodString with _tableName property (set by zid())\n // Prefer _tableName check (works in both zod and zod/mini),\n // fall back to .description check (full zod only)\n if (schema instanceof $ZodString) {\n const tableName =\n (schema as any)._tableName ??\n ((schema as any).description?.startsWith('convexId:')\n ? (schema as any).description.slice('convexId:'.length)\n : undefined)\n if (tableName) {\n return `zx.id(\"${tableName}\")`\n }\n }\n\n // zx.date() — ZodCodec with in=ZodNumber, out=ZodCustom\n if (\n schema instanceof $ZodCodec &&\n schema._zod.def.in instanceof $ZodNumber &&\n schema._zod.def.out instanceof $ZodCustom\n ) {\n return 'zx.date()'\n }\n\n // Generic ZodCodec — check codec map for identity match\n if (schema instanceof $ZodCodec) {\n if (ctx?.codecMap) {\n const ref = ctx.codecMap.get(schema)\n if (ref) {\n // Track the needed import\n if (!ctx.neededCodecImports.has(ref.sourceFile)) {\n ctx.neededCodecImports.set(ref.sourceFile, new Set())\n }\n ctx.neededCodecImports.get(ref.sourceFile)?.add(ref.exportName)\n return ref.exportName\n }\n }\n // Unknown codec — fall back to wire schema with warning\n const wireSource = zodToSource(schema._zod.def.in, ctx)\n ctx?.undiscoverableCodecs?.push({ fieldPath: 'unknown' })\n return `${wireSource} /* codec: transforms lost */`\n }\n\n // Primitives\n if (schema instanceof $ZodString) return 'z.string()'\n if (schema instanceof $ZodNumber) return 'z.number()'\n if (schema instanceof $ZodBoolean) return 'z.boolean()'\n if (schema instanceof $ZodNull) return 'z.null()'\n if (schema instanceof $ZodUndefined) return 'z.undefined()'\n if (schema instanceof $ZodAny) return 'z.any()'\n\n // Objects\n if (schema instanceof $ZodObject) {\n const shape = schema._zod.def.shape\n const fields = Object.entries(shape)\n .map(([key, value]) => `${key}: ${zodToSource(value, ctx)}`)\n .join(', ')\n return `z.object({ ${fields} })`\n }\n\n // Arrays\n if (schema instanceof $ZodArray) {\n return `z.array(${zodToSource(schema._zod.def.element, ctx)})`\n }\n\n // Enums\n if (schema instanceof $ZodEnum) {\n const entries = schema._zod.def.entries\n const values = (Object.values(entries) as string[]).map((v: string) => `\"${v}\"`).join(', ')\n return `z.enum([${values}])`\n }\n\n // Literals\n if (schema instanceof $ZodLiteral) {\n const values = schema._zod.def.values\n const value = values.values().next().value\n if (typeof value === 'string') return `z.literal(\"${value}\")`\n return `z.literal(${value})`\n }\n\n // Unions\n if (schema instanceof $ZodUnion) {\n const members = schema._zod.def.options.map(s => zodToSource(s, ctx)).join(', ')\n return `z.union([${members}])`\n }\n\n // Tuples\n if (schema instanceof $ZodTuple) {\n const items = schema._zod.def.items.map(s => zodToSource(s, ctx)).join(', ')\n return `z.tuple([${items}])`\n }\n\n // Records\n if (schema instanceof $ZodRecord) {\n return `z.record(${zodToSource(schema._zod.def.keyType, ctx)}, ${zodToSource(schema._zod.def.valueType, ctx)})`\n }\n\n // Fallback for unsupported types\n const typeName = schema._zod.def.type ?? 'unknown'\n return `z.any() /* unsupported: ${typeName} */`\n}\n","import { $ZodCodec, $ZodNullable, $ZodObject, $ZodOptional, $ZodType } from '../zod-core'\nimport type {\n DiscoveredFunction,\n DiscoveredModel,\n FunctionEmbeddedCodec,\n ModelEmbeddedCodec\n} from './discover'\nimport { type CodecRef, type ZodToSourceContext, zodToSource } from './zodToSource'\n\nconst HEADER = `// AUTO-GENERATED by zodvex — do not edit\n// Run \\`zodvex generate\\` to regenerate\n`\n\nexport type GeneratedFile = { js: string; dts: string }\n\n/**\n * Produces a structural fingerprint for a ZodCodec by serializing its\n * wire (in) and runtime (out) schemas. Two factory-created codec instances\n * with the same arguments produce the same fingerprint, enabling dedup\n * even when object identity differs.\n */\nfunction fingerprintCodec(schema: $ZodType): string {\n if (!(schema instanceof $ZodCodec)) return ''\n return `${zodToSource(schema._zod.def.in)}|${zodToSource(schema._zod.def.out)}`\n}\n\n/**\n * Generates the schema file content — re-exports of all discovered models.\n * Returns { js, dts } with .js import extensions (TS resolves types from .js targets).\n */\nexport function generateSchemaFile(models: DiscoveredModel[]): GeneratedFile {\n const exports = models\n .map(m => {\n const importPath = `../${m.sourceFile.replace(/\\.ts$/, '.js')}`\n return `export { ${m.exportName} } from '${importPath}'`\n })\n .join('\\n')\n\n const content = `${HEADER}\\n${exports}\\n`\n return { js: content, dts: content }\n}\n\ntype SchemaRef = {\n importPath: string\n exportName: string\n schemaKey: string\n}\n\nexport type CodecForGeneration = {\n exportName: string\n sourceFile: string\n schema: $ZodType\n}\n\n/**\n * Peels .optional() and .nullable() wrappers from a schema and checks\n * the identity map at each level. Returns the matched ref plus a\n * function that wraps an inner source string with the appropriate\n * optional/nullable syntax (chaining or functional for mini mode).\n */\nfunction tryUnwrapToIdentity(\n schema: $ZodType,\n identityMap: Map<$ZodType, SchemaRef>,\n mini?: boolean\n): { ref: SchemaRef; wrapSource: (inner: string) => string } | null {\n let current = schema\n const wrappers: Array<'optional' | 'nullable'> = []\n const maxDepth = 5\n\n for (let i = 0; i < maxDepth; i++) {\n if (current instanceof $ZodOptional) {\n wrappers.push('optional')\n current = current._zod.def.innerType\n } else if (current instanceof $ZodNullable) {\n wrappers.push('nullable')\n current = current._zod.def.innerType\n } else {\n break\n }\n\n const ref = identityMap.get(current)\n if (ref) {\n // Wrappers collected outermost-first, apply innermost-first\n const reversed = [...wrappers].reverse()\n return {\n ref,\n wrapSource: (inner: string) => {\n let result = inner\n for (const w of reversed) {\n result = mini ? `z.${w}(${result})` : `${result}.${w}()`\n }\n return result\n }\n }\n }\n }\n\n return null\n}\n\n/**\n * Checks if a ZodObject schema is structurally equivalent to\n * someModelSchema.partial() by comparing field-by-field identity.\n *\n * Zod's .partial() wraps each field in ZodOptional, preserving\n * the inner type identity. So we check: same keys, each field\n * is ZodOptional, and each inner type === the original model field.\n */\nfunction tryMatchPartial(\n schema: $ZodType,\n identityMap: Map<$ZodType, SchemaRef>,\n mini?: boolean\n): { ref: SchemaRef; wrapSource: (inner: string) => string } | null {\n if (!(schema instanceof $ZodObject)) return null\n const candidateShape = schema._zod.def.shape as Record<string, $ZodType>\n const candidateKeys = Object.keys(candidateShape).sort()\n\n for (const [modelSchema, ref] of identityMap) {\n if (!(modelSchema instanceof $ZodObject)) continue\n const modelShape = modelSchema._zod.def.shape as Record<string, $ZodType>\n const modelKeys = Object.keys(modelShape).sort()\n\n // Same key count and same keys\n if (candidateKeys.length !== modelKeys.length) continue\n if (candidateKeys.some((k, i) => k !== modelKeys[i])) continue\n\n // Every candidate field must be ZodOptional wrapping the model field by identity\n let allMatch = true\n for (const key of candidateKeys) {\n const candidateField = candidateShape[key]\n if (!(candidateField instanceof $ZodOptional)) {\n allMatch = false\n break\n }\n const inner = candidateField._zod.def.innerType\n if (inner !== modelShape[key]) {\n allMatch = false\n break\n }\n }\n\n if (allMatch) {\n return {\n ref,\n wrapSource: (inner: string) => (mini ? `z.partial(${inner})` : `${inner}.partial()`)\n }\n }\n }\n\n return null\n}\n\n/**\n * Derives a descriptive variable name for a model-embedded codec from\n * the model export name and the access path.\n *\n * Examples:\n * ('UserModel', '.shape.email') → '_userEmail'\n * ('ActivityModel', '.shape.payload._zod.def.options[0].shape.email') → '_activityPayloadEmail'\n * ('patients', '.shape.firstName') → '_patientsFirstName'\n */\nfunction deriveCodecVarName(modelExportName: string, accessPath: string): string {\n const base = modelExportName.replace(/Model$/, '')\n const prefix = base[0].toLowerCase() + base.slice(1)\n\n const fields = [...accessPath.matchAll(/\\.shape\\.(\\w+)/g)].map(m => m[1])\n if (fields.length === 0) return `_${prefix}Codec`\n\n const fieldPart = fields.map((f, i) => (i === 0 ? f : f[0].toUpperCase() + f.slice(1))).join('')\n\n return `_${prefix}${fieldPart[0].toUpperCase() + fieldPart.slice(1)}`\n}\n\n/**\n * Generates the api.ts file content — function-to-schema registry.\n */\nexport function generateApiFile(\n functions: DiscoveredFunction[],\n models: DiscoveredModel[],\n codecs?: CodecForGeneration[],\n modelCodecs?: ModelEmbeddedCodec[],\n functionCodecs?: FunctionEmbeddedCodec[],\n options?: { mini?: boolean }\n): GeneratedFile {\n // Build identity map: runtime schema object → model reference string\n const identityMap = new Map<$ZodType, SchemaRef>()\n const neededModelImports = new Set<string>()\n\n for (const model of models) {\n const importPath = `../${model.sourceFile.replace(/\\.ts$/, '.js')}`\n for (const key of ['doc', 'insert', 'update', 'docArray', 'paginatedDoc'] as const) {\n identityMap.set(model.schemas[key] as $ZodType, {\n importPath,\n exportName: model.exportName,\n schemaKey: key\n })\n }\n }\n\n // Build codec identity map for zodToSource\n const codecMap = new Map<$ZodType, CodecRef>()\n if (codecs) {\n for (const codec of codecs) {\n const importPath = `../${codec.sourceFile.replace(/\\.ts$/, '.js')}`\n codecMap.set(codec.schema, {\n exportName: codec.exportName,\n sourceFile: importPath\n })\n }\n }\n\n // Add model-embedded codecs to the codecMap (exported codecs take precedence)\n const modelCodecVars: { varName: string; expression: string; modelExportName: string }[] = []\n const MODEL_CODEC_SENTINEL = '__model_codec__'\n if (modelCodecs) {\n for (const mc of modelCodecs) {\n // Skip if this codec is already in codecMap (exported codec takes precedence)\n if (codecMap.has(mc.codec)) continue\n\n const varName = deriveCodecVarName(mc.modelExportName, mc.accessPath)\n const expression = `extractCodec(${mc.modelExportName}.schema.${mc.schemaKey}${mc.accessPath})`\n modelCodecVars.push({ varName, expression, modelExportName: mc.modelExportName })\n codecMap.set(mc.codec, {\n exportName: varName,\n sourceFile: MODEL_CODEC_SENTINEL\n })\n }\n }\n\n // Resolve function-embedded codecs against existing codecs by structural fingerprint.\n // Factory-created codecs (like tagged(), encrypted()) produce new instances each call,\n // so identity matching fails. Fingerprinting matches by wire+runtime schema structure,\n // allowing us to reference the model/standalone codec instead of importing the function.\n // This avoids circular imports: functions.ts → _zodvex/api.ts → functionFile.ts → functions.ts\n if (functionCodecs) {\n const fingerprintMap = new Map<string, CodecRef>()\n for (const [codecSchema, ref] of codecMap) {\n const fp = fingerprintCodec(codecSchema)\n if (fp) fingerprintMap.set(fp, ref)\n }\n\n for (const fc of functionCodecs) {\n if (codecMap.has(fc.codec)) continue\n\n const fp = fingerprintCodec(fc.codec)\n const matchingRef = fp ? fingerprintMap.get(fp) : undefined\n if (matchingRef) {\n codecMap.set(fc.codec, matchingRef)\n } else {\n console.warn(\n `[zodvex] Warning: Codec in ${fc.functionExportName}() (${fc.accessPath}) has no matching model or exported codec. ` +\n `Export it standalone for full client-side codec support.`\n )\n }\n }\n }\n\n const zodToSourceCtx: ZodToSourceContext = {\n codecMap,\n neededCodecImports: new Map(),\n undiscoverableCodecs: [],\n mini: options?.mini\n }\n\n // Track which imports we need\n let needsZod = false\n let needsZx = false\n\n // Resolve each schema to either a model reference or serialized source\n function resolveSchema(schema: $ZodType | unknown): string {\n if (!schema) return 'undefined'\n const s = schema as $ZodType\n\n // 1. Direct identity match\n const ref = identityMap.get(s)\n if (ref) {\n neededModelImports.add(ref.exportName)\n return `${ref.exportName}.schema.${ref.schemaKey}`\n }\n\n // 2. Wrapper-aware identity match (peel .nullable()/.optional())\n const unwrapped = tryUnwrapToIdentity(s, identityMap, options?.mini)\n if (unwrapped) {\n neededModelImports.add(unwrapped.ref.exportName)\n const inner = `${unwrapped.ref.exportName}.schema.${unwrapped.ref.schemaKey}`\n return unwrapped.wrapSource(inner)\n }\n\n // 3. Partial-aware match (detect .partial() of a model schema)\n const partialMatch = tryMatchPartial(s, identityMap, options?.mini)\n if (partialMatch) {\n neededModelImports.add(partialMatch.ref.exportName)\n const inner = `${partialMatch.ref.exportName}.schema.${partialMatch.ref.schemaKey}`\n return partialMatch.wrapSource(inner)\n }\n\n // 4. Fall back to zodToSource (with codec context)\n const source = zodToSource(s, zodToSourceCtx)\n if (source.includes('z.')) needsZod = true\n if (source.includes('zx.')) needsZx = true\n return source\n }\n\n // Build registry entries\n const entries = functions\n .map(fn => {\n const args = resolveSchema(fn.zodArgs)\n const returns = resolveSchema(fn.zodReturns)\n return ` '${fn.functionPath}': {\\n args: ${args},\\n returns: ${returns},\\n }`\n })\n .join(',\\n')\n\n // Determine which model codec vars were actually used (referenced by zodToSource)\n const usedModelCodecVars = modelCodecVars.filter(mc => {\n const sentinelExports = zodToSourceCtx.neededCodecImports.get(MODEL_CODEC_SENTINEL)\n return sentinelExports?.has(mc.varName)\n })\n\n // Add model imports for models referenced by used model codec vars\n if (usedModelCodecVars.length > 0) {\n for (const mc of usedModelCodecVars) {\n neededModelImports.add(mc.modelExportName)\n }\n }\n\n // Build imports\n const imports: string[] = []\n const zodImport = options?.mini ? 'zod/mini' : 'zod'\n if (needsZod) imports.push(`import { z } from '${zodImport}'`)\n\n // Build single zodvex/core (or zodvex/mini) import (zx, extractCodec)\n const zodvexImport = options?.mini ? 'zodvex/mini' : 'zodvex/core'\n const coreImports: string[] = []\n if (needsZx) coreImports.push('zx')\n if (usedModelCodecVars.length > 0) coreImports.push('extractCodec')\n if (coreImports.length > 0) {\n imports.push(`import { ${coreImports.join(', ')} } from '${zodvexImport}'`)\n }\n\n for (const exportName of neededModelImports) {\n const model = models.find(m => m.exportName === exportName)\n if (model) {\n const importPath = `../${model.sourceFile.replace(/\\.ts$/, '.js')}`\n imports.push(`import { ${exportName} } from '${importPath}'`)\n }\n }\n\n // Codec imports (collected by zodToSource via context)\n for (const [importPath, exportNames] of zodToSourceCtx.neededCodecImports) {\n if (importPath === MODEL_CODEC_SENTINEL) continue\n const names = Array.from(exportNames).sort().join(', ')\n imports.push(`import { ${names} } from '${importPath}'`)\n }\n\n const importSection = imports.length > 0 ? `${imports.join('\\n')}\\n\\n` : ''\n\n // Build codec helper var declarations\n const allCodecVars = usedModelCodecVars.map(mc => `const ${mc.varName} = ${mc.expression}`)\n const codecVarSection = allCodecVars.length > 0 ? `${allCodecVars.join('\\n')}\\n\\n` : ''\n\n const js = `${HEADER}\\n${importSection}${codecVarSection}export const zodvexRegistry = {\\n${entries},\\n}\\n`\n\n const dts = options?.mini\n ? `${HEADER}\nimport type { $ZodType } from 'zod/v4/core'\n\nexport declare const zodvexRegistry: Record<string, { args: $ZodType; returns: $ZodType | undefined }>\n`\n : `${HEADER}\nimport type { ZodTypeAny } from 'zod'\n\nexport declare const zodvexRegistry: Record<string, { args: ZodTypeAny; returns: ZodTypeAny | undefined }>\n`\n\n return { js, dts }\n}\n\n/**\n * Generates the server.ts file content — concrete context types for the app's schema.\n *\n * These parallel Convex's _generated/server.ts exports (QueryCtx, MutationCtx, ActionCtx)\n * but with zodvex's codec-wrapped db types baked in.\n */\nexport function generateServerFile(): GeneratedFile {\n const js = `${HEADER}`\n\n const dts = `${HEADER}\nimport type { DataModel } from '../_generated/dataModel.js'\nimport type { ZodvexActionCtx, ZodvexMutationCtx, ZodvexQueryCtx } from 'zodvex/server'\nimport type schema from '../schema.js'\n\ntype DecodedDocs = (typeof schema)['__decodedDocs']\n\n/** Query context with codec-wrapped db (decoded types on reads). */\nexport type QueryCtx = ZodvexQueryCtx<DataModel, DecodedDocs>\n\n/** Mutation context with codec-wrapped db (decoded reads, encoded writes). */\nexport type MutationCtx = ZodvexMutationCtx<DataModel, DecodedDocs>\n\n/** Action context (no db, but runQuery/runMutation may be codec-wrapped). */\nexport type ActionCtx = ZodvexActionCtx<DataModel>\n`\n\n return { js, dts }\n}\n\n/**\n * Generates the client file content — pre-bound hooks and client factory.\n * Returns { js, dts } for .js + .d.ts output.\n */\nexport function generateClientFile(options?: { mini?: boolean }): GeneratedFile {\n const zodvexCoreImport = options?.mini ? 'zodvex/mini' : 'zodvex/core'\n // --- JS ---\n const jsImports = [\n \"import { createZodvexHooks } from 'zodvex/react'\",\n \"import { createZodvexReactClient } from 'zodvex/react'\",\n \"import { createZodvexClient } from 'zodvex/client'\",\n `import { createBoundaryHelpers } from '${zodvexCoreImport}'`,\n \"import { zodvexRegistry } from './api.js'\"\n ]\n\n const jsExports = [\n 'export const { useZodQuery, useZodMutation } = createZodvexHooks(zodvexRegistry)',\n '',\n 'export const createClient = (options) =>',\n ' createZodvexClient(zodvexRegistry, options)',\n '',\n 'export const createReactClient = (options) =>',\n ' createZodvexReactClient(zodvexRegistry, options)',\n '',\n 'export const { encodeArgs, decodeResult } = createBoundaryHelpers(zodvexRegistry)'\n ]\n\n const js = `${HEADER}\\n${jsImports.join('\\n')}\\n\\n${jsExports.join('\\n')}\\n`\n\n // --- DTS ---\n const dtsImports = [\n \"import type { ZodvexHooks } from 'zodvex/react'\",\n \"import type { ZodvexClientOptions, ZodvexClient } from 'zodvex/client'\",\n \"import type { ZodvexReactClientOptions, ZodvexReactClient } from 'zodvex/react'\",\n `import type { BoundaryHelpers } from '${zodvexCoreImport}'`\n ]\n\n const dtsDeclarations = [\n \"export declare const useZodQuery: ZodvexHooks['useZodQuery']\",\n \"export declare const useZodMutation: ZodvexHooks['useZodMutation']\",\n '',\n 'export declare const createClient: (options: ZodvexClientOptions) => ZodvexClient',\n '',\n 'export declare const createReactClient: (options: ZodvexReactClientOptions) => ZodvexReactClient',\n '',\n \"export declare const encodeArgs: BoundaryHelpers['encodeArgs']\",\n \"export declare const decodeResult: BoundaryHelpers['decodeResult']\"\n ]\n\n const dts = `${HEADER}\\n${dtsImports.join('\\n')}\\n\\n${dtsDeclarations.join('\\n')}\\n`\n\n return { js, dts }\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport { discoverModules } from '../codegen/discover'\nimport {\n generateApiFile,\n generateClientFile,\n generateSchemaFile,\n generateServerFile\n} from '../codegen/generate'\n\n/**\n * One-shot codegen. Discovers modules, generates files.\n */\nexport async function generate(convexDir?: string, options?: { mini?: boolean }): Promise<void> {\n const resolved = resolveConvexDir(convexDir)\n const zodvexDir = path.join(resolved, '_zodvex')\n\n // Ensure _zodvex/api.js exists before discovery. User modules (e.g., functions.ts)\n // may import zodvexRegistry from it. Without a stub, dynamic import() fails and\n // codegen can't discover those modules — a chicken-and-egg problem.\n writeStubApi(zodvexDir)\n\n const result = await discoverModules(resolved)\n\n const schemaContent = generateSchemaFile(result.models)\n const apiContent = generateApiFile(\n result.functions,\n result.models,\n result.codecs,\n result.modelCodecs,\n result.functionCodecs,\n { mini: options?.mini }\n )\n const clientContent = generateClientFile({ mini: options?.mini })\n const serverContent = generateServerFile()\n\n fs.mkdirSync(zodvexDir, { recursive: true })\n writeIfChanged(path.join(zodvexDir, 'schema.js'), schemaContent.js)\n writeIfChanged(path.join(zodvexDir, 'schema.d.ts'), schemaContent.dts)\n writeIfChanged(path.join(zodvexDir, 'api.js'), apiContent.js)\n writeIfChanged(path.join(zodvexDir, 'api.d.ts'), apiContent.dts)\n writeIfChanged(path.join(zodvexDir, 'client.js'), clientContent.js)\n writeIfChanged(path.join(zodvexDir, 'client.d.ts'), clientContent.dts)\n writeIfChanged(path.join(zodvexDir, 'server.js'), serverContent.js)\n writeIfChanged(path.join(zodvexDir, 'server.d.ts'), serverContent.dts)\n\n const totalCodecs =\n result.codecs.length + result.modelCodecs.length + result.functionCodecs.length\n console.log(\n `[zodvex] Generated ${result.models.length} model(s), ${result.functions.length} function(s), ${totalCodecs} codec(s)`\n )\n}\n\n/**\n * Watch mode. Runs generate() once, then watches for changes.\n */\nexport async function dev(convexDir?: string, options?: { mini?: boolean }): Promise<void> {\n const resolved = resolveConvexDir(convexDir)\n\n console.log('[zodvex] Starting watch mode...')\n await generate(resolved, options)\n\n let debounceTimer: ReturnType<typeof setTimeout> | null = null\n\n const watcher = fs.watch(resolved, { recursive: true }, (_event, filename) => {\n if (!filename) return\n // Skip generated directories and non-TS files\n if (\n filename.startsWith('_zodvex') ||\n filename.startsWith('_generated') ||\n (!filename.endsWith('.ts') && !filename.endsWith('.js'))\n ) {\n return\n }\n\n if (debounceTimer) clearTimeout(debounceTimer)\n debounceTimer = setTimeout(async () => {\n console.log('[zodvex] Regenerating...')\n try {\n await generate(resolved, options)\n } catch (err) {\n console.error('[zodvex] Generation failed:', (err as Error).message)\n }\n }, 300)\n })\n\n // Keep process alive\n process.on('SIGINT', () => {\n if (debounceTimer) clearTimeout(debounceTimer)\n watcher.close()\n process.exit(0)\n })\n}\n\n/** Writes minimal stub _zodvex/api.js + api.d.ts before discovery to break circular imports.\n * Previous generations may contain stale imports that cause cycles during re-discovery. */\nfunction writeStubApi(zodvexDir: string): void {\n fs.mkdirSync(zodvexDir, { recursive: true })\n\n fs.writeFileSync(\n path.join(zodvexDir, 'api.js'),\n '// AUTO-GENERATED by zodvex — do not edit\\n// Stub created for codegen bootstrap\\n\\nexport const zodvexRegistry = {}\\n'\n )\n\n fs.writeFileSync(\n path.join(zodvexDir, 'api.d.ts'),\n '// AUTO-GENERATED by zodvex — do not edit\\n// Stub created for codegen bootstrap\\n\\nexport declare const zodvexRegistry: Record<string, any>\\n'\n )\n}\n\n/** Only write if content differs from what's on disk — prevents file watcher loops. */\nfunction writeIfChanged(filePath: string, content: string): void {\n try {\n const existing = fs.readFileSync(filePath, 'utf-8')\n if (existing === content) return\n } catch {\n // File doesn't exist yet — write it\n }\n fs.writeFileSync(filePath, content)\n}\n\nfunction resolveConvexDir(dir?: string): string {\n if (dir) {\n const resolved = path.resolve(dir)\n if (!fs.existsSync(resolved)) {\n throw new Error(`Convex directory not found: ${resolved}`)\n }\n return resolved\n }\n\n // Default: look for ./convex/ in cwd\n const defaultDir = path.resolve('convex')\n if (!fs.existsSync(defaultDir)) {\n throw new Error('No convex/ directory found. Specify the path: zodvex generate <path>')\n }\n return defaultDir\n}\n","#!/usr/bin/env bun\nimport { dev, generate } from './commands'\n\nconst command = process.argv[2]\nconst miniFlag = process.argv.includes('--mini')\n// The convex dir arg needs to skip flags\nconst convexDir = process.argv.slice(3).find(a => !a.startsWith('--'))\n\nasync function main() {\n switch (command) {\n case 'generate':\n await generate(convexDir, { mini: miniFlag })\n break\n case 'dev':\n await dev(convexDir, { mini: miniFlag })\n break\n case 'init': {\n // Dynamic import to keep init dependencies lazy\n const { init } = await import('./init')\n await init()\n break\n }\n case 'migrate': {\n const { migrate } = await import('./migrate')\n const targetDir = process.argv[3] ?? '.'\n const dryRun = process.argv.includes('--dry-run')\n const result = migrate(targetDir, { dryRun })\n\n if (dryRun) {\n console.log(`[zodvex] Dry run: ${result.wouldChange} file(s) would be changed`)\n } else {\n console.log(`[zodvex] Migrated ${result.filesChanged} file(s)`)\n }\n\n if (result.remainingDeprecations.length > 0) {\n console.log('')\n console.log('[zodvex] Remaining deprecated API usage:')\n const grouped = new Map<string, string[]>()\n for (const d of result.remainingDeprecations) {\n const key = d.symbol\n if (!grouped.has(key)) grouped.set(key, [])\n grouped.get(key)?.push(` ${d.file}:${d.line}`)\n }\n for (const [symbol, locations] of grouped) {\n console.log(` ${symbol}:`)\n for (const loc of locations) {\n console.log(` ${loc}`)\n }\n }\n console.log('')\n console.log('See docs/migration/v0.6.md for migration guidance on structural changes.')\n }\n break\n }\n case 'codemod': {\n const toMini = process.argv.includes('--to-mini')\n if (!toMini) {\n console.error('[zodvex] No codemod specified. Available: --to-mini')\n process.exit(1)\n }\n const dryRun = process.argv.includes('--dry-run')\n const targetDir = process.argv.slice(3).find(a => !a.startsWith('--')) ?? 'convex'\n // Lazy import — pulls in ts-morph only when codemod is used\n const { runToMiniCodemod } = await import('./codemod')\n await runToMiniCodemod(targetDir, { dryRun })\n break\n }\n case 'help':\n case '--help':\n case '-h':\n case undefined:\n printHelp()\n break\n default:\n console.error(`Unknown command: ${command}`)\n printHelp()\n process.exit(1)\n }\n}\n\nfunction printHelp() {\n console.log(`\nzodvex - Convex codegen for Zod schemas\n\nUsage:\n zodvex generate [convex-dir] [--mini] Generate schema and validator files\n zodvex dev [convex-dir] [--mini] Watch mode — regenerate on changes\n zodvex init Set up zodvex in an existing Convex project\n zodvex migrate [dir] Migrate pre-0.6 APIs (renames + import fixes)\n zodvex migrate [dir] --dry-run Preview changes without writing\n zodvex codemod --to-mini [dir] Convert full-zod code to zod/mini syntax\n zodvex codemod --to-mini [dir] --dry-run Preview changes without writing\n zodvex help Show this help message\n\nFlags:\n --mini Emit zod/mini-compatible output (functional forms, zodvex/mini imports)\n`)\n}\n\nmain().catch(err => {\n console.error(err.message)\n process.exit(1)\n})\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zodvex",
3
- "version": "0.7.1-beta.1",
3
+ "version": "0.7.1-beta.2",
4
4
  "description": "Codec-first Zod v4 integration for Convex -- type-safe validation, encoding, DB wrapping, and codegen.",
5
5
  "keywords": ["zod", "convex", "validators", "codec", "mapping", "schema", "validation"],
6
6
  "homepage": "https://github.com/panzacoder/zodvex#readme",
@@ -0,0 +1,80 @@
1
+ /**
2
+ * zodvex codemod --to-mini
3
+ *
4
+ * One-time migration from full-zod to zod/mini syntax.
5
+ * Transforms method chains to functional forms, rewrites imports.
6
+ *
7
+ * This modifies files in-place. Use --dry-run to preview changes.
8
+ * To undo: git restore <dir>
9
+ */
10
+ import { readFileSync, writeFileSync } from 'fs'
11
+ import { relative, resolve } from 'path'
12
+ import { globSync } from 'tinyglobby'
13
+
14
+ export async function runToMiniCodemod(
15
+ targetDir: string,
16
+ options: { dryRun?: boolean } = {}
17
+ ): Promise<void> {
18
+ // Import directly from workspace package (not zodvex/labs which is the published re-export)
19
+ const { transformCode, transformImports } = await import('zod-to-mini')
20
+ const { Project } = await import('ts-morph')
21
+
22
+ const dir = resolve(process.cwd(), targetDir)
23
+ const files = globSync(['**/*.ts', '**/*.tsx'], {
24
+ cwd: dir,
25
+ ignore: ['_generated/**', '_zodvex/**', '**/*.d.ts', 'node_modules/**'],
26
+ absolute: true
27
+ })
28
+
29
+ console.log(
30
+ `[zodvex codemod] ${options.dryRun ? 'Dry run — ' : ''}Processing ${files.length} files in ${targetDir}/`
31
+ )
32
+ console.log('')
33
+
34
+ let totalChanged = 0
35
+
36
+ for (const filePath of files) {
37
+ const code = readFileSync(filePath, 'utf-8')
38
+
39
+ // Skip files that don't reference zod
40
+ if (!code.includes("'zod'") && !code.includes('"zod"')) continue
41
+
42
+ // Apply all zod→mini code transforms
43
+ const result = transformCode(code)
44
+ let output = result.code
45
+
46
+ // Transform imports: 'zod' → 'zod/mini', 'zodvex/core' → 'zodvex/mini'
47
+ const project = new Project({ useInMemoryFileSystem: true })
48
+ const sf = project.createSourceFile('tmp.ts', output)
49
+ transformImports(sf)
50
+ for (const imp of sf.getImportDeclarations()) {
51
+ const spec = imp.getModuleSpecifierValue()
52
+ if (spec === 'zodvex/core') imp.setModuleSpecifier('zodvex/mini')
53
+ }
54
+ output = sf.getFullText()
55
+
56
+ if (output !== code) {
57
+ totalChanged++
58
+ const rel = relative(process.cwd(), filePath)
59
+ if (options.dryRun) {
60
+ console.log(` would change: ${rel}`)
61
+ } else {
62
+ writeFileSync(filePath, output)
63
+ console.log(` changed: ${rel}`)
64
+ }
65
+ }
66
+ }
67
+
68
+ console.log('')
69
+ console.log(
70
+ `[zodvex codemod] ${totalChanged} file(s) ${options.dryRun ? 'would be changed' : 'changed'}.`
71
+ )
72
+
73
+ if (!options.dryRun && totalChanged > 0) {
74
+ console.log('')
75
+ console.log('Next steps:')
76
+ console.log(' 1. Run `zodvex generate --mini` to regenerate codegen output')
77
+ console.log(' 2. Run your type-checker and tests to verify')
78
+ console.log(' 3. To undo: git restore ' + targetDir + '/')
79
+ }
80
+ }
package/src/cli/index.ts CHANGED
@@ -52,6 +52,19 @@ async function main() {
52
52
  }
53
53
  break
54
54
  }
55
+ case 'codemod': {
56
+ const toMini = process.argv.includes('--to-mini')
57
+ if (!toMini) {
58
+ console.error('[zodvex] No codemod specified. Available: --to-mini')
59
+ process.exit(1)
60
+ }
61
+ const dryRun = process.argv.includes('--dry-run')
62
+ const targetDir = process.argv.slice(3).find(a => !a.startsWith('--')) ?? 'convex'
63
+ // Lazy import — pulls in ts-morph only when codemod is used
64
+ const { runToMiniCodemod } = await import('./codemod')
65
+ await runToMiniCodemod(targetDir, { dryRun })
66
+ break
67
+ }
55
68
  case 'help':
56
69
  case '--help':
57
70
  case '-h':
@@ -75,6 +88,8 @@ Usage:
75
88
  zodvex init Set up zodvex in an existing Convex project
76
89
  zodvex migrate [dir] Migrate pre-0.6 APIs (renames + import fixes)
77
90
  zodvex migrate [dir] --dry-run Preview changes without writing
91
+ zodvex codemod --to-mini [dir] Convert full-zod code to zod/mini syntax
92
+ zodvex codemod --to-mini [dir] --dry-run Preview changes without writing
78
93
  zodvex help Show this help message
79
94
 
80
95
  Flags: