zodvex 0.6.0-beta.52 → 0.6.0-beta.53
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.
package/dist/cli/index.js
CHANGED
|
@@ -474,7 +474,11 @@ async function discoverModules(convexDir2) {
|
|
|
474
474
|
"**/*.test.ts",
|
|
475
475
|
"**/*.test.js",
|
|
476
476
|
"**/*.spec.ts",
|
|
477
|
-
"**/*.spec.js"
|
|
477
|
+
"**/*.spec.js",
|
|
478
|
+
"convex.config.ts",
|
|
479
|
+
"convex.config.js",
|
|
480
|
+
"crons.ts",
|
|
481
|
+
"crons.js"
|
|
478
482
|
]
|
|
479
483
|
});
|
|
480
484
|
try {
|
package/dist/cli/index.js.map
CHANGED
|
@@ -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","z","def","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,EAAA,mBAAA,EAAA,MAAA,mBAAA;AAAA,EAAA,gBAAA,EAAA,MAAA;AAAA,CAAA,CAAA;AAYO,SAAS,iBAAiB,MAAA,EAA+B;AAC9D,EAAA,IAAI,MAAA,CAAO,QAAA,CAAS,YAAY,CAAA,EAAG,OAAO,IAAA;AAC1C,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,KAAA,CAAM,mCAAmC,CAAA;AAC9D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,CAAE,CAAA;AAAA,UAC1B;AAAA,QACF;AACA,QAAA,OAAA,CAAQ,IAAI,EAAE,CAAA;AACd,QAAA,OAAA,CAAQ,IAAI,0EAA0E,CAAA;AAAA,MACxF;AACA,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,CAUb,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","import type { z } from 'zod'\n\nconst META_KEY = '__zodvexMeta'\n\nexport type ZodvexFunctionMeta = {\n type: 'function'\n zodArgs?: z.ZodTypeAny\n zodReturns?: z.ZodTypeAny\n}\n\nexport type ZodvexModelMeta = {\n type: 'model'\n tableName: string\n schemas: {\n doc: z.ZodTypeAny\n insert: z.ZodTypeAny\n update: z.ZodTypeAny\n docArray: z.ZodTypeAny\n paginatedDoc: z.ZodTypeAny\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 { z } from 'zod'\nimport { readMeta } from '../meta'\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: z.ZodTypeAny): z.ZodTypeAny | undefined {\n let current = schema\n for (let i = 0; i < 10; i++) {\n if (current instanceof z.ZodCodec) {\n const def = (current as any)._zod?.def as any\n const isZxDate = def?.in instanceof z.ZodNumber && def?.out instanceof z.ZodCustom\n if (isZxDate) return undefined\n return current\n }\n if (current instanceof z.ZodOptional || current instanceof z.ZodNullable) {\n const def = (current as any)._zod?.def as any\n current = 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: z.ZodTypeAny): z.ZodTypeAny {\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): z.ZodTypeAny {\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\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): z.ZodTypeAny {\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\n}\n","import path from 'node:path'\nimport { globSync } from 'tinyglobby'\nimport { z } from 'zod'\nimport { readMeta, type ZodvexFunctionMeta, type ZodvexModelMeta } from '../meta'\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: z.ZodTypeAny\n}\n\nexport type ModelEmbeddedCodec = {\n codec: z.ZodTypeAny\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: z.ZodTypeAny\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: z.ZodTypeAny,\n accessPath: string,\n visited: Set<z.ZodTypeAny>,\n seenCodecs: Set<z.ZodTypeAny>,\n results: { codec: z.ZodTypeAny; 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 = schema\n let currentPath = accessPath\n for (let i = 0; i < 10; i++) {\n if (current instanceof z.ZodOptional || current instanceof z.ZodNullable) {\n const def = (current as any)._zod?.def as any\n current = def.innerType\n currentPath += '._zod.def.innerType'\n } else {\n break\n }\n }\n\n const def = (current as any)._zod?.def as any\n\n if (current instanceof z.ZodObject) {\n const shape = def?.shape as Record<string, z.ZodTypeAny> | undefined\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 z.ZodUnion) {\n const options = def?.options as z.ZodTypeAny[] | undefined\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 z.ZodArray) {\n const element = def?.element as z.ZodTypeAny | undefined\n if (element) {\n walkSchemaRecursive(element, `${currentPath}._zod.def.element`, visited, seenCodecs, results)\n }\n } else if (current instanceof z.ZodRecord) {\n const valueType = def?.valueType as z.ZodTypeAny | undefined\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 z.ZodTuple) {\n const items = def?.items as z.ZodTypeAny[] | undefined\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<z.ZodTypeAny>()\n const seenCodecs = new Set<z.ZodTypeAny>()\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: z.ZodTypeAny; accessPath: string }[] = []\n walkSchemaRecursive(schema, '', 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<z.ZodTypeAny>()\n const seenCodecs = new Set<z.ZodTypeAny>()\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: z.ZodTypeAny; accessPath: string }[] = []\n walkSchemaRecursive(schema, '', 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 ]\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 z.ZodCodec) {\n const def = (value as any)._zod?.def as any\n const isZxDate = def?.in instanceof z.ZodNumber && def?.out instanceof z.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 z.ZodTypeAny\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 { z } from 'zod'\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<z.ZodTypeAny, 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}\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: z.ZodTypeAny, ctx?: ZodToSourceContext): string {\n // Cast to any — Zod v4's internal _zod.def properties are not publicly typed\n const def = schema._zod?.def as any\n\n // Peel off wrappers first (optional, nullable)\n if (schema instanceof z.ZodOptional) {\n return `${zodToSource(def.innerType, ctx)}.optional()`\n }\n if (schema instanceof z.ZodNullable) {\n return `${zodToSource(def.innerType, ctx)}.nullable()`\n }\n\n // zodvex extensions — detect before generic types\n\n // zx.id('tableName') — ZodString with description 'convexId:<tableName>'\n if (schema instanceof z.ZodString && schema.description?.startsWith('convexId:')) {\n const tableName = schema.description.slice('convexId:'.length)\n return `zx.id(\"${tableName}\")`\n }\n\n // zx.date() — ZodCodec with in=ZodNumber, out=ZodCustom\n if (\n schema instanceof z.ZodCodec &&\n def.in instanceof z.ZodNumber &&\n def.out instanceof z.ZodCustom\n ) {\n return 'zx.date()'\n }\n\n // Generic ZodCodec — check codec map for identity match\n if (schema instanceof z.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(def.in, ctx)\n ctx?.undiscoverableCodecs?.push({ fieldPath: 'unknown' })\n return `${wireSource} /* codec: transforms lost */`\n }\n\n // Primitives\n if (schema instanceof z.ZodString) return 'z.string()'\n if (schema instanceof z.ZodNumber) return 'z.number()'\n if (schema instanceof z.ZodBoolean) return 'z.boolean()'\n if (schema instanceof z.ZodNull) return 'z.null()'\n if (schema instanceof z.ZodUndefined) return 'z.undefined()'\n if (schema instanceof z.ZodAny) return 'z.any()'\n\n // Objects\n if (schema instanceof z.ZodObject) {\n const shape = def.shape as Record<string, z.ZodTypeAny>\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 z.ZodArray) {\n return `z.array(${zodToSource(def.element, ctx)})`\n }\n\n // Enums\n if (schema instanceof z.ZodEnum) {\n const values = (schema.options as string[]).map(v => `\"${v}\"`).join(', ')\n return `z.enum([${values}])`\n }\n\n // Literals\n if (schema instanceof z.ZodLiteral) {\n const values = def.values as Set<unknown>\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 z.ZodUnion) {\n const members = (def.options as z.ZodTypeAny[])\n .map((s: z.ZodTypeAny) => zodToSource(s, ctx))\n .join(', ')\n return `z.union([${members}])`\n }\n\n // Tuples\n if (schema instanceof z.ZodTuple) {\n const items = (def.items as z.ZodTypeAny[])\n .map((s: z.ZodTypeAny) => zodToSource(s, ctx))\n .join(', ')\n return `z.tuple([${items}])`\n }\n\n // Records\n if (schema instanceof z.ZodRecord) {\n return `z.record(${zodToSource(def.keyType, ctx)}, ${zodToSource(def.valueType, ctx)})`\n }\n\n // Fallback for unsupported types\n const typeName = def?.type ?? 'unknown'\n return `z.any() /* unsupported: ${typeName} */`\n}\n","import { z } from 'zod'\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: z.ZodTypeAny): string {\n const def = (schema as any)._zod?.def\n if (!def?.in || !def?.out) return ''\n return `${zodToSource(def.in)}|${zodToSource(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: z.ZodTypeAny\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 the\n * suffix string to reconstruct the wrappers in source output.\n */\nfunction tryUnwrapToIdentity(\n schema: z.ZodTypeAny,\n identityMap: Map<z.ZodTypeAny, SchemaRef>\n): { ref: SchemaRef; suffix: string } | null {\n let current = schema\n const suffixes: string[] = []\n const maxDepth = 5\n\n for (let i = 0; i < maxDepth; i++) {\n const def = current._zod?.def as any\n if (current instanceof z.ZodOptional) {\n suffixes.push('.optional()')\n current = def.innerType\n } else if (current instanceof z.ZodNullable) {\n suffixes.push('.nullable()')\n current = def.innerType\n } else {\n break\n }\n\n const ref = identityMap.get(current)\n if (ref) {\n // Reverse: suffixes were collected outermost-first, but source reads innermost-first\n return { ref, suffix: suffixes.reverse().join('') }\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: z.ZodTypeAny,\n identityMap: Map<z.ZodTypeAny, SchemaRef>\n): { ref: SchemaRef; suffix: string } | null {\n if (!(schema instanceof z.ZodObject)) return null\n const candidateShape = schema.shape as Record<string, z.ZodTypeAny>\n const candidateKeys = Object.keys(candidateShape).sort()\n\n for (const [modelSchema, ref] of identityMap) {\n if (!(modelSchema instanceof z.ZodObject)) continue\n const modelShape = modelSchema.shape as Record<string, z.ZodTypeAny>\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 z.ZodOptional)) {\n allMatch = false\n break\n }\n const inner = (candidateField as any)._zod?.def?.innerType\n if (inner !== modelShape[key]) {\n allMatch = false\n break\n }\n }\n\n if (allMatch) {\n return { ref, suffix: '.partial()' }\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): GeneratedFile {\n // Build identity map: runtime schema object → model reference string\n const identityMap = new Map<z.ZodTypeAny, 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 z.ZodTypeAny, {\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<z.ZodTypeAny, 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 }\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: z.ZodTypeAny | undefined): string {\n if (!schema) return 'undefined'\n\n // 1. Direct identity match\n const ref = identityMap.get(schema)\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(schema, identityMap)\n if (unwrapped) {\n neededModelImports.add(unwrapped.ref.exportName)\n return `${unwrapped.ref.exportName}.schema.${unwrapped.ref.schemaKey}${unwrapped.suffix}`\n }\n\n // 3. Partial-aware match (detect .partial() of a model schema)\n const partialMatch = tryMatchPartial(schema, identityMap)\n if (partialMatch) {\n neededModelImports.add(partialMatch.ref.exportName)\n return `${partialMatch.ref.exportName}.schema.${partialMatch.ref.schemaKey}${partialMatch.suffix}`\n }\n\n // 4. Fall back to zodToSource (with codec context)\n const source = zodToSource(schema, 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 if (needsZod) imports.push(\"import { z } from 'zod'\")\n\n // Build single zodvex/core import (zx, extractCodec)\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 'zodvex/core'`)\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 = `${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(): GeneratedFile {\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 'zodvex/core'\",\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 'zodvex/core'\"\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): 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 )\n const clientContent = generateClientFile()\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): Promise<void> {\n const resolved = resolveConvexDir(convexDir)\n\n console.log('[zodvex] Starting watch mode...')\n await generate(resolved)\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)\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 convexDir = process.argv[3]\n\nasync function main() {\n switch (command) {\n case 'generate':\n await generate(convexDir)\n break\n case 'dev':\n await dev(convexDir)\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] Generate schema and validator files\n zodvex dev [convex-dir] 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`)\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","../../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","z","def","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,EAAA,mBAAA,EAAA,MAAA,mBAAA;AAAA,EAAA,gBAAA,EAAA,MAAA;AAAA,CAAA,CAAA;AAYO,SAAS,iBAAiB,MAAA,EAA+B;AAC9D,EAAA,IAAI,MAAA,CAAO,QAAA,CAAS,YAAY,CAAA,EAAG,OAAO,IAAA;AAC1C,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,KAAA,CAAM,mCAAmC,CAAA;AAC9D,EAAA,IAAI,CAAC,OAAO,OAAO,IAAA;AACnB,EAAA,OAAO,8BAA8B,MAAM,CAAA,CAAA,CAAA;AAC7C;AAMO,SAAS,oBAAoB,MAAA,EAA+B;AACjE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AI,EAAE,CAAA;AACd,QAAA,OAAA,CAAQ,IAAI,0EAA0E,CAAA;AAAA,MACxF;AACA,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,CAUb,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","import type { z } from 'zod'\n\nconst META_KEY = '__zodvexMeta'\n\nexport type ZodvexFunctionMeta = {\n type: 'function'\n zodArgs?: z.ZodTypeAny\n zodReturns?: z.ZodTypeAny\n}\n\nexport type ZodvexModelMeta = {\n type: 'model'\n tableName: string\n schemas: {\n doc: z.ZodTypeAny\n insert: z.ZodTypeAny\n update: z.ZodTypeAny\n docArray: z.ZodTypeAny\n paginatedDoc: z.ZodTypeAny\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 { z } from 'zod'\nimport { readMeta } from '../meta'\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: z.ZodTypeAny): z.ZodTypeAny | undefined {\n let current = schema\n for (let i = 0; i < 10; i++) {\n if (current instanceof z.ZodCodec) {\n const def = (current as any)._zod?.def as any\n const isZxDate = def?.in instanceof z.ZodNumber && def?.out instanceof z.ZodCustom\n if (isZxDate) return undefined\n return current\n }\n if (current instanceof z.ZodOptional || current instanceof z.ZodNullable) {\n const def = (current as any)._zod?.def as any\n current = 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: z.ZodTypeAny): z.ZodTypeAny {\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): z.ZodTypeAny {\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\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): z.ZodTypeAny {\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\n}\n","import path from 'node:path'\nimport { globSync } from 'tinyglobby'\nimport { z } from 'zod'\nimport { readMeta, type ZodvexFunctionMeta, type ZodvexModelMeta } from '../meta'\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: z.ZodTypeAny\n}\n\nexport type ModelEmbeddedCodec = {\n codec: z.ZodTypeAny\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: z.ZodTypeAny\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: z.ZodTypeAny,\n accessPath: string,\n visited: Set<z.ZodTypeAny>,\n seenCodecs: Set<z.ZodTypeAny>,\n results: { codec: z.ZodTypeAny; 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 = schema\n let currentPath = accessPath\n for (let i = 0; i < 10; i++) {\n if (current instanceof z.ZodOptional || current instanceof z.ZodNullable) {\n const def = (current as any)._zod?.def as any\n current = def.innerType\n currentPath += '._zod.def.innerType'\n } else {\n break\n }\n }\n\n const def = (current as any)._zod?.def as any\n\n if (current instanceof z.ZodObject) {\n const shape = def?.shape as Record<string, z.ZodTypeAny> | undefined\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 z.ZodUnion) {\n const options = def?.options as z.ZodTypeAny[] | undefined\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 z.ZodArray) {\n const element = def?.element as z.ZodTypeAny | undefined\n if (element) {\n walkSchemaRecursive(element, `${currentPath}._zod.def.element`, visited, seenCodecs, results)\n }\n } else if (current instanceof z.ZodRecord) {\n const valueType = def?.valueType as z.ZodTypeAny | undefined\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 z.ZodTuple) {\n const items = def?.items as z.ZodTypeAny[] | undefined\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<z.ZodTypeAny>()\n const seenCodecs = new Set<z.ZodTypeAny>()\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: z.ZodTypeAny; accessPath: string }[] = []\n walkSchemaRecursive(schema, '', 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<z.ZodTypeAny>()\n const seenCodecs = new Set<z.ZodTypeAny>()\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: z.ZodTypeAny; accessPath: string }[] = []\n walkSchemaRecursive(schema, '', 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 z.ZodCodec) {\n const def = (value as any)._zod?.def as any\n const isZxDate = def?.in instanceof z.ZodNumber && def?.out instanceof z.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 z.ZodTypeAny\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 { z } from 'zod'\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<z.ZodTypeAny, 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}\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: z.ZodTypeAny, ctx?: ZodToSourceContext): string {\n // Cast to any — Zod v4's internal _zod.def properties are not publicly typed\n const def = schema._zod?.def as any\n\n // Peel off wrappers first (optional, nullable)\n if (schema instanceof z.ZodOptional) {\n return `${zodToSource(def.innerType, ctx)}.optional()`\n }\n if (schema instanceof z.ZodNullable) {\n return `${zodToSource(def.innerType, ctx)}.nullable()`\n }\n\n // zodvex extensions — detect before generic types\n\n // zx.id('tableName') — ZodString with description 'convexId:<tableName>'\n if (schema instanceof z.ZodString && schema.description?.startsWith('convexId:')) {\n const tableName = schema.description.slice('convexId:'.length)\n return `zx.id(\"${tableName}\")`\n }\n\n // zx.date() — ZodCodec with in=ZodNumber, out=ZodCustom\n if (\n schema instanceof z.ZodCodec &&\n def.in instanceof z.ZodNumber &&\n def.out instanceof z.ZodCustom\n ) {\n return 'zx.date()'\n }\n\n // Generic ZodCodec — check codec map for identity match\n if (schema instanceof z.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(def.in, ctx)\n ctx?.undiscoverableCodecs?.push({ fieldPath: 'unknown' })\n return `${wireSource} /* codec: transforms lost */`\n }\n\n // Primitives\n if (schema instanceof z.ZodString) return 'z.string()'\n if (schema instanceof z.ZodNumber) return 'z.number()'\n if (schema instanceof z.ZodBoolean) return 'z.boolean()'\n if (schema instanceof z.ZodNull) return 'z.null()'\n if (schema instanceof z.ZodUndefined) return 'z.undefined()'\n if (schema instanceof z.ZodAny) return 'z.any()'\n\n // Objects\n if (schema instanceof z.ZodObject) {\n const shape = def.shape as Record<string, z.ZodTypeAny>\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 z.ZodArray) {\n return `z.array(${zodToSource(def.element, ctx)})`\n }\n\n // Enums\n if (schema instanceof z.ZodEnum) {\n const values = (schema.options as string[]).map(v => `\"${v}\"`).join(', ')\n return `z.enum([${values}])`\n }\n\n // Literals\n if (schema instanceof z.ZodLiteral) {\n const values = def.values as Set<unknown>\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 z.ZodUnion) {\n const members = (def.options as z.ZodTypeAny[])\n .map((s: z.ZodTypeAny) => zodToSource(s, ctx))\n .join(', ')\n return `z.union([${members}])`\n }\n\n // Tuples\n if (schema instanceof z.ZodTuple) {\n const items = (def.items as z.ZodTypeAny[])\n .map((s: z.ZodTypeAny) => zodToSource(s, ctx))\n .join(', ')\n return `z.tuple([${items}])`\n }\n\n // Records\n if (schema instanceof z.ZodRecord) {\n return `z.record(${zodToSource(def.keyType, ctx)}, ${zodToSource(def.valueType, ctx)})`\n }\n\n // Fallback for unsupported types\n const typeName = def?.type ?? 'unknown'\n return `z.any() /* unsupported: ${typeName} */`\n}\n","import { z } from 'zod'\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: z.ZodTypeAny): string {\n const def = (schema as any)._zod?.def\n if (!def?.in || !def?.out) return ''\n return `${zodToSource(def.in)}|${zodToSource(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: z.ZodTypeAny\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 the\n * suffix string to reconstruct the wrappers in source output.\n */\nfunction tryUnwrapToIdentity(\n schema: z.ZodTypeAny,\n identityMap: Map<z.ZodTypeAny, SchemaRef>\n): { ref: SchemaRef; suffix: string } | null {\n let current = schema\n const suffixes: string[] = []\n const maxDepth = 5\n\n for (let i = 0; i < maxDepth; i++) {\n const def = current._zod?.def as any\n if (current instanceof z.ZodOptional) {\n suffixes.push('.optional()')\n current = def.innerType\n } else if (current instanceof z.ZodNullable) {\n suffixes.push('.nullable()')\n current = def.innerType\n } else {\n break\n }\n\n const ref = identityMap.get(current)\n if (ref) {\n // Reverse: suffixes were collected outermost-first, but source reads innermost-first\n return { ref, suffix: suffixes.reverse().join('') }\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: z.ZodTypeAny,\n identityMap: Map<z.ZodTypeAny, SchemaRef>\n): { ref: SchemaRef; suffix: string } | null {\n if (!(schema instanceof z.ZodObject)) return null\n const candidateShape = schema.shape as Record<string, z.ZodTypeAny>\n const candidateKeys = Object.keys(candidateShape).sort()\n\n for (const [modelSchema, ref] of identityMap) {\n if (!(modelSchema instanceof z.ZodObject)) continue\n const modelShape = modelSchema.shape as Record<string, z.ZodTypeAny>\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 z.ZodOptional)) {\n allMatch = false\n break\n }\n const inner = (candidateField as any)._zod?.def?.innerType\n if (inner !== modelShape[key]) {\n allMatch = false\n break\n }\n }\n\n if (allMatch) {\n return { ref, suffix: '.partial()' }\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): GeneratedFile {\n // Build identity map: runtime schema object → model reference string\n const identityMap = new Map<z.ZodTypeAny, 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 z.ZodTypeAny, {\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<z.ZodTypeAny, 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 }\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: z.ZodTypeAny | undefined): string {\n if (!schema) return 'undefined'\n\n // 1. Direct identity match\n const ref = identityMap.get(schema)\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(schema, identityMap)\n if (unwrapped) {\n neededModelImports.add(unwrapped.ref.exportName)\n return `${unwrapped.ref.exportName}.schema.${unwrapped.ref.schemaKey}${unwrapped.suffix}`\n }\n\n // 3. Partial-aware match (detect .partial() of a model schema)\n const partialMatch = tryMatchPartial(schema, identityMap)\n if (partialMatch) {\n neededModelImports.add(partialMatch.ref.exportName)\n return `${partialMatch.ref.exportName}.schema.${partialMatch.ref.schemaKey}${partialMatch.suffix}`\n }\n\n // 4. Fall back to zodToSource (with codec context)\n const source = zodToSource(schema, 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 if (needsZod) imports.push(\"import { z } from 'zod'\")\n\n // Build single zodvex/core import (zx, extractCodec)\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 'zodvex/core'`)\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 = `${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(): GeneratedFile {\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 'zodvex/core'\",\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 'zodvex/core'\"\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): 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 )\n const clientContent = generateClientFile()\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): Promise<void> {\n const resolved = resolveConvexDir(convexDir)\n\n console.log('[zodvex] Starting watch mode...')\n await generate(resolved)\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)\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 convexDir = process.argv[3]\n\nasync function main() {\n switch (command) {\n case 'generate':\n await generate(convexDir)\n break\n case 'dev':\n await dev(convexDir)\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] Generate schema and validator files\n zodvex dev [convex-dir] 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`)\n}\n\nmain().catch(err => {\n console.error(err.message)\n process.exit(1)\n})\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"discover.d.ts","sourceRoot":"","sources":["../../src/codegen/discover.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AACvB,OAAO,EAAY,KAAK,kBAAkB,EAAE,KAAK,eAAe,EAAE,MAAM,SAAS,CAAA;AAIjF,MAAM,MAAM,eAAe,GAAG;IAC5B,UAAU,EAAE,MAAM,CAAA;IAClB,SAAS,EAAE,MAAM,CAAA;IACjB,UAAU,EAAE,MAAM,CAAA;IAClB,OAAO,EAAE,eAAe,CAAC,SAAS,CAAC,CAAA;CACpC,CAAA;AAED,MAAM,MAAM,kBAAkB,GAAG;IAC/B,YAAY,EAAE,MAAM,CAAA;IACpB,UAAU,EAAE,MAAM,CAAA;IAClB,UAAU,EAAE,MAAM,CAAA;IAClB,OAAO,CAAC,EAAE,kBAAkB,CAAC,SAAS,CAAC,CAAA;IACvC,UAAU,CAAC,EAAE,kBAAkB,CAAC,YAAY,CAAC,CAAA;CAC9C,CAAA;AAED,MAAM,MAAM,eAAe,GAAG;IAC5B,UAAU,EAAE,MAAM,CAAA;IAClB,UAAU,EAAE,MAAM,CAAA;IAClB,MAAM,EAAE,CAAC,CAAC,UAAU,CAAA;CACrB,CAAA;AAED,MAAM,MAAM,kBAAkB,GAAG;IAC/B,KAAK,EAAE,CAAC,CAAC,UAAU,CAAA;IACnB,eAAe,EA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,EAAE,MAAM,EAClB,OAAO,EAAE,eAAe,CAAC,SAAS,CAAC,GAClC,kBAAkB,EAAE,CAwBtB;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,kBAAkB,EAAE,GAAG,qBAAqB,EAAE,CA0B3F;AAED;;;;GAIG;AACH,wBAAsB,eAAe,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC,CAsHjF"}
|
package/dist/codegen/index.js
CHANGED
|
@@ -287,7 +287,11 @@ async function discoverModules(convexDir) {
|
|
|
287
287
|
"**/*.test.ts",
|
|
288
288
|
"**/*.test.js",
|
|
289
289
|
"**/*.spec.ts",
|
|
290
|
-
"**/*.spec.js"
|
|
290
|
+
"**/*.spec.js",
|
|
291
|
+
"convex.config.ts",
|
|
292
|
+
"convex.config.js",
|
|
293
|
+
"crons.ts",
|
|
294
|
+
"crons.js"
|
|
291
295
|
]
|
|
292
296
|
});
|
|
293
297
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/meta.ts","../../src/codegen/discovery-hooks.ts","../../src/codegen/extractCodec.ts","../../src/codegen/discover.ts","../../src/codegen/zodToSource.ts","../../src/codegen/generate.ts"],"names":["z","def","path","exports"],"mappings":";;;;;;;;;;;;;AAEA,IAAM,QAAA,GAAW,cAAA;AA+BV,SAAS,SAAS,MAAA,EAAyC;AAChE,EAAA,IAAI,UAAU,IAAA,IAAS,OAAO,WAAW,QAAA,IAAY,OAAO,WAAW,UAAA,EAAa;AAClF,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,OAAQ,OAAmC,QAAQ,CAAA;AACrD;ACzBA,IAAM,YAAA,GAAe;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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A,CAAA;AAGxE,EAAA,MAAM,UAAA,GAAa;AAAA,IACjB,iDAAA;AAAA,IACA,wEAAA;AAAA,IACA,iFAAA;AAAA,IACA;AAAA,GACF;AAEA,EAAA,MAAM,eAAA,GAAkB;AAAA,IACtB,8DAAA;AAAA,IACA,oEAAA;AAAA,IACA,EAAA;AAAA,IACA,mFAAA;AAAA,IACA,EAAA;AAAA,IACA,kGAAA;AAAA,IACA,EAAA;AAAA,IACA,gEAAA;AAAA,IACA;AAAA,GACF;AAEA,EAAA,MAAM,GAAA,GAAM,GAAG,MAAM;AAAA,EAAK,UAAA,CAAW,IAAA,CAAK,IAAI,CAAC;;AAAA,EAAO,eAAA,CAAgB,IAAA,CAAK,IAAI,CAAC;AAAA,CAAA;AAEhF,EAAA,OAAO,EAAE,IAAI,GAAA,EAAI;AACnB","file":"index.js","sourcesContent":["import type { z } from 'zod'\n\nconst META_KEY = '__zodvexMeta'\n\nexport type ZodvexFunctionMeta = {\n type: 'function'\n zodArgs?: z.ZodTypeAny\n zodReturns?: z.ZodTypeAny\n}\n\nexport type ZodvexModelMeta = {\n type: 'model'\n tableName: string\n schemas: {\n doc: z.ZodTypeAny\n insert: z.ZodTypeAny\n update: z.ZodTypeAny\n docArray: z.ZodTypeAny\n paginatedDoc: z.ZodTypeAny\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 { z } from 'zod'\nimport { readMeta } from '../meta'\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: z.ZodTypeAny): z.ZodTypeAny | undefined {\n let current = schema\n for (let i = 0; i < 10; i++) {\n if (current instanceof z.ZodCodec) {\n const def = (current as any)._zod?.def as any\n const isZxDate = def?.in instanceof z.ZodNumber && def?.out instanceof z.ZodCustom\n if (isZxDate) return undefined\n return current\n }\n if (current instanceof z.ZodOptional || current instanceof z.ZodNullable) {\n const def = (current as any)._zod?.def as any\n current = 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: z.ZodTypeAny): z.ZodTypeAny {\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): z.ZodTypeAny {\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\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): z.ZodTypeAny {\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\n}\n","import path from 'node:path'\nimport { globSync } from 'tinyglobby'\nimport { z } from 'zod'\nimport { readMeta, type ZodvexFunctionMeta, type ZodvexModelMeta } from '../meta'\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: z.ZodTypeAny\n}\n\nexport type ModelEmbeddedCodec = {\n codec: z.ZodTypeAny\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: z.ZodTypeAny\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: z.ZodTypeAny,\n accessPath: string,\n visited: Set<z.ZodTypeAny>,\n seenCodecs: Set<z.ZodTypeAny>,\n results: { codec: z.ZodTypeAny; 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 = schema\n let currentPath = accessPath\n for (let i = 0; i < 10; i++) {\n if (current instanceof z.ZodOptional || current instanceof z.ZodNullable) {\n const def = (current as any)._zod?.def as any\n current = def.innerType\n currentPath += '._zod.def.innerType'\n } else {\n break\n }\n }\n\n const def = (current as any)._zod?.def as any\n\n if (current instanceof z.ZodObject) {\n const shape = def?.shape as Record<string, z.ZodTypeAny> | undefined\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 z.ZodUnion) {\n const options = def?.options as z.ZodTypeAny[] | undefined\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 z.ZodArray) {\n const element = def?.element as z.ZodTypeAny | undefined\n if (element) {\n walkSchemaRecursive(element, `${currentPath}._zod.def.element`, visited, seenCodecs, results)\n }\n } else if (current instanceof z.ZodRecord) {\n const valueType = def?.valueType as z.ZodTypeAny | undefined\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 z.ZodTuple) {\n const items = def?.items as z.ZodTypeAny[] | undefined\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<z.ZodTypeAny>()\n const seenCodecs = new Set<z.ZodTypeAny>()\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: z.ZodTypeAny; accessPath: string }[] = []\n walkSchemaRecursive(schema, '', 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<z.ZodTypeAny>()\n const seenCodecs = new Set<z.ZodTypeAny>()\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: z.ZodTypeAny; accessPath: string }[] = []\n walkSchemaRecursive(schema, '', 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 ]\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 z.ZodCodec) {\n const def = (value as any)._zod?.def as any\n const isZxDate = def?.in instanceof z.ZodNumber && def?.out instanceof z.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 z.ZodTypeAny\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 { z } from 'zod'\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<z.ZodTypeAny, 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}\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: z.ZodTypeAny, ctx?: ZodToSourceContext): string {\n // Cast to any — Zod v4's internal _zod.def properties are not publicly typed\n const def = schema._zod?.def as any\n\n // Peel off wrappers first (optional, nullable)\n if (schema instanceof z.ZodOptional) {\n return `${zodToSource(def.innerType, ctx)}.optional()`\n }\n if (schema instanceof z.ZodNullable) {\n return `${zodToSource(def.innerType, ctx)}.nullable()`\n }\n\n // zodvex extensions — detect before generic types\n\n // zx.id('tableName') — ZodString with description 'convexId:<tableName>'\n if (schema instanceof z.ZodString && schema.description?.startsWith('convexId:')) {\n const tableName = schema.description.slice('convexId:'.length)\n return `zx.id(\"${tableName}\")`\n }\n\n // zx.date() — ZodCodec with in=ZodNumber, out=ZodCustom\n if (\n schema instanceof z.ZodCodec &&\n def.in instanceof z.ZodNumber &&\n def.out instanceof z.ZodCustom\n ) {\n return 'zx.date()'\n }\n\n // Generic ZodCodec — check codec map for identity match\n if (schema instanceof z.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(def.in, ctx)\n ctx?.undiscoverableCodecs?.push({ fieldPath: 'unknown' })\n return `${wireSource} /* codec: transforms lost */`\n }\n\n // Primitives\n if (schema instanceof z.ZodString) return 'z.string()'\n if (schema instanceof z.ZodNumber) return 'z.number()'\n if (schema instanceof z.ZodBoolean) return 'z.boolean()'\n if (schema instanceof z.ZodNull) return 'z.null()'\n if (schema instanceof z.ZodUndefined) return 'z.undefined()'\n if (schema instanceof z.ZodAny) return 'z.any()'\n\n // Objects\n if (schema instanceof z.ZodObject) {\n const shape = def.shape as Record<string, z.ZodTypeAny>\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 z.ZodArray) {\n return `z.array(${zodToSource(def.element, ctx)})`\n }\n\n // Enums\n if (schema instanceof z.ZodEnum) {\n const values = (schema.options as string[]).map(v => `\"${v}\"`).join(', ')\n return `z.enum([${values}])`\n }\n\n // Literals\n if (schema instanceof z.ZodLiteral) {\n const values = def.values as Set<unknown>\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 z.ZodUnion) {\n const members = (def.options as z.ZodTypeAny[])\n .map((s: z.ZodTypeAny) => zodToSource(s, ctx))\n .join(', ')\n return `z.union([${members}])`\n }\n\n // Tuples\n if (schema instanceof z.ZodTuple) {\n const items = (def.items as z.ZodTypeAny[])\n .map((s: z.ZodTypeAny) => zodToSource(s, ctx))\n .join(', ')\n return `z.tuple([${items}])`\n }\n\n // Records\n if (schema instanceof z.ZodRecord) {\n return `z.record(${zodToSource(def.keyType, ctx)}, ${zodToSource(def.valueType, ctx)})`\n }\n\n // Fallback for unsupported types\n const typeName = def?.type ?? 'unknown'\n return `z.any() /* unsupported: ${typeName} */`\n}\n","import { z } from 'zod'\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: z.ZodTypeAny): string {\n const def = (schema as any)._zod?.def\n if (!def?.in || !def?.out) return ''\n return `${zodToSource(def.in)}|${zodToSource(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: z.ZodTypeAny\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 the\n * suffix string to reconstruct the wrappers in source output.\n */\nfunction tryUnwrapToIdentity(\n schema: z.ZodTypeAny,\n identityMap: Map<z.ZodTypeAny, SchemaRef>\n): { ref: SchemaRef; suffix: string } | null {\n let current = schema\n const suffixes: string[] = []\n const maxDepth = 5\n\n for (let i = 0; i < maxDepth; i++) {\n const def = current._zod?.def as any\n if (current instanceof z.ZodOptional) {\n suffixes.push('.optional()')\n current = def.innerType\n } else if (current instanceof z.ZodNullable) {\n suffixes.push('.nullable()')\n current = def.innerType\n } else {\n break\n }\n\n const ref = identityMap.get(current)\n if (ref) {\n // Reverse: suffixes were collected outermost-first, but source reads innermost-first\n return { ref, suffix: suffixes.reverse().join('') }\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: z.ZodTypeAny,\n identityMap: Map<z.ZodTypeAny, SchemaRef>\n): { ref: SchemaRef; suffix: string } | null {\n if (!(schema instanceof z.ZodObject)) return null\n const candidateShape = schema.shape as Record<string, z.ZodTypeAny>\n const candidateKeys = Object.keys(candidateShape).sort()\n\n for (const [modelSchema, ref] of identityMap) {\n if (!(modelSchema instanceof z.ZodObject)) continue\n const modelShape = modelSchema.shape as Record<string, z.ZodTypeAny>\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 z.ZodOptional)) {\n allMatch = false\n break\n }\n const inner = (candidateField as any)._zod?.def?.innerType\n if (inner !== modelShape[key]) {\n allMatch = false\n break\n }\n }\n\n if (allMatch) {\n return { ref, suffix: '.partial()' }\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): GeneratedFile {\n // Build identity map: runtime schema object → model reference string\n const identityMap = new Map<z.ZodTypeAny, 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 z.ZodTypeAny, {\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<z.ZodTypeAny, 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 }\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: z.ZodTypeAny | undefined): string {\n if (!schema) return 'undefined'\n\n // 1. Direct identity match\n const ref = identityMap.get(schema)\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(schema, identityMap)\n if (unwrapped) {\n neededModelImports.add(unwrapped.ref.exportName)\n return `${unwrapped.ref.exportName}.schema.${unwrapped.ref.schemaKey}${unwrapped.suffix}`\n }\n\n // 3. Partial-aware match (detect .partial() of a model schema)\n const partialMatch = tryMatchPartial(schema, identityMap)\n if (partialMatch) {\n neededModelImports.add(partialMatch.ref.exportName)\n return `${partialMatch.ref.exportName}.schema.${partialMatch.ref.schemaKey}${partialMatch.suffix}`\n }\n\n // 4. Fall back to zodToSource (with codec context)\n const source = zodToSource(schema, 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 if (needsZod) imports.push(\"import { z } from 'zod'\")\n\n // Build single zodvex/core import (zx, extractCodec)\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 'zodvex/core'`)\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 = `${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(): GeneratedFile {\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 'zodvex/core'\",\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 'zodvex/core'\"\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"]}
|
|
1
|
+
{"version":3,"sources":["../../src/meta.ts","../../src/codegen/discovery-hooks.ts","../../src/codegen/extractCodec.ts","../../src/codegen/discover.ts","../../src/codegen/zodToSource.ts","../../src/codegen/generate.ts"],"names":["z","def","path","exports"],"mappings":";;;;;;;;;;;;;AAEA,IAAM,QAAA,GAAW,cAAA;AA+BV,SAAS,SAAS,MAAA,EAAyC;AAChE,EAAA,IAAI,UAAU,IAAA,IAAS,OAAO,WAAW,QAAA,IAAY,OAAO,WAAW,UAAA,EA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AA,IACA;AAAA,GACF;AAEA,EAAA,MAAM,SAAA,GAAY;AAAA,IAChB,kFAAA;AAAA,IACA,EAAA;AAAA,IACA,0CAAA;AAAA,IACA,+CAAA;AAAA,IACA,EAAA;AAAA,IACA,+CAAA;AAAA,IACA,oDAAA;AAAA,IACA,EAAA;AAAA,IACA;AAAA,GACF;AAEA,EAAA,MAAM,EAAA,GAAK,GAAG,MAAM;AAAA,EAAK,SAAA,CAAU,IAAA,CAAK,IAAI,CAAC;;AAAA,EAAO,SAAA,CAAU,IAAA,CAAK,IAAI,CAAC;AAAA,CAAA;AAGxE,EAAA,MAAM,UAAA,GAAa;AAAA,IACjB,iDAAA;AAAA,IACA,wEAAA;AAAA,IACA,iFAAA;AAAA,IACA;AAAA,GACF;AAEA,EAAA,MAAM,eAAA,GAAkB;AAAA,IACtB,8DAAA;AAAA,IACA,oEAAA;AAAA,IACA,EAAA;AAAA,IACA,mFAAA;AAAA,IACA,EAAA;AAAA,IACA,kGAAA;AAAA,IACA,EAAA;AAAA,IACA,gEAAA;AAAA,IACA;AAAA,GACF;AAEA,EAAA,MAAM,GAAA,GAAM,GAAG,MAAM;AAAA,EAAK,UAAA,CAAW,IAAA,CAAK,IAAI,CAAC;;AAAA,EAAO,eAAA,CAAgB,IAAA,CAAK,IAAI,CAAC;AAAA,CAAA;AAEhF,EAAA,OAAO,EAAE,IAAI,GAAA,EAAI;AACnB","file":"index.js","sourcesContent":["import type { z } from 'zod'\n\nconst META_KEY = '__zodvexMeta'\n\nexport type ZodvexFunctionMeta = {\n type: 'function'\n zodArgs?: z.ZodTypeAny\n zodReturns?: z.ZodTypeAny\n}\n\nexport type ZodvexModelMeta = {\n type: 'model'\n tableName: string\n schemas: {\n doc: z.ZodTypeAny\n insert: z.ZodTypeAny\n update: z.ZodTypeAny\n docArray: z.ZodTypeAny\n paginatedDoc: z.ZodTypeAny\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 { z } from 'zod'\nimport { readMeta } from '../meta'\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: z.ZodTypeAny): z.ZodTypeAny | undefined {\n let current = schema\n for (let i = 0; i < 10; i++) {\n if (current instanceof z.ZodCodec) {\n const def = (current as any)._zod?.def as any\n const isZxDate = def?.in instanceof z.ZodNumber && def?.out instanceof z.ZodCustom\n if (isZxDate) return undefined\n return current\n }\n if (current instanceof z.ZodOptional || current instanceof z.ZodNullable) {\n const def = (current as any)._zod?.def as any\n current = 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: z.ZodTypeAny): z.ZodTypeAny {\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): z.ZodTypeAny {\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\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): z.ZodTypeAny {\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\n}\n","import path from 'node:path'\nimport { globSync } from 'tinyglobby'\nimport { z } from 'zod'\nimport { readMeta, type ZodvexFunctionMeta, type ZodvexModelMeta } from '../meta'\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: z.ZodTypeAny\n}\n\nexport type ModelEmbeddedCodec = {\n codec: z.ZodTypeAny\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: z.ZodTypeAny\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: z.ZodTypeAny,\n accessPath: string,\n visited: Set<z.ZodTypeAny>,\n seenCodecs: Set<z.ZodTypeAny>,\n results: { codec: z.ZodTypeAny; 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 = schema\n let currentPath = accessPath\n for (let i = 0; i < 10; i++) {\n if (current instanceof z.ZodOptional || current instanceof z.ZodNullable) {\n const def = (current as any)._zod?.def as any\n current = def.innerType\n currentPath += '._zod.def.innerType'\n } else {\n break\n }\n }\n\n const def = (current as any)._zod?.def as any\n\n if (current instanceof z.ZodObject) {\n const shape = def?.shape as Record<string, z.ZodTypeAny> | undefined\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 z.ZodUnion) {\n const options = def?.options as z.ZodTypeAny[] | undefined\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 z.ZodArray) {\n const element = def?.element as z.ZodTypeAny | undefined\n if (element) {\n walkSchemaRecursive(element, `${currentPath}._zod.def.element`, visited, seenCodecs, results)\n }\n } else if (current instanceof z.ZodRecord) {\n const valueType = def?.valueType as z.ZodTypeAny | undefined\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 z.ZodTuple) {\n const items = def?.items as z.ZodTypeAny[] | undefined\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<z.ZodTypeAny>()\n const seenCodecs = new Set<z.ZodTypeAny>()\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: z.ZodTypeAny; accessPath: string }[] = []\n walkSchemaRecursive(schema, '', 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<z.ZodTypeAny>()\n const seenCodecs = new Set<z.ZodTypeAny>()\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: z.ZodTypeAny; accessPath: string }[] = []\n walkSchemaRecursive(schema, '', 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 z.ZodCodec) {\n const def = (value as any)._zod?.def as any\n const isZxDate = def?.in instanceof z.ZodNumber && def?.out instanceof z.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 z.ZodTypeAny\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 { z } from 'zod'\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<z.ZodTypeAny, 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}\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: z.ZodTypeAny, ctx?: ZodToSourceContext): string {\n // Cast to any — Zod v4's internal _zod.def properties are not publicly typed\n const def = schema._zod?.def as any\n\n // Peel off wrappers first (optional, nullable)\n if (schema instanceof z.ZodOptional) {\n return `${zodToSource(def.innerType, ctx)}.optional()`\n }\n if (schema instanceof z.ZodNullable) {\n return `${zodToSource(def.innerType, ctx)}.nullable()`\n }\n\n // zodvex extensions — detect before generic types\n\n // zx.id('tableName') — ZodString with description 'convexId:<tableName>'\n if (schema instanceof z.ZodString && schema.description?.startsWith('convexId:')) {\n const tableName = schema.description.slice('convexId:'.length)\n return `zx.id(\"${tableName}\")`\n }\n\n // zx.date() — ZodCodec with in=ZodNumber, out=ZodCustom\n if (\n schema instanceof z.ZodCodec &&\n def.in instanceof z.ZodNumber &&\n def.out instanceof z.ZodCustom\n ) {\n return 'zx.date()'\n }\n\n // Generic ZodCodec — check codec map for identity match\n if (schema instanceof z.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(def.in, ctx)\n ctx?.undiscoverableCodecs?.push({ fieldPath: 'unknown' })\n return `${wireSource} /* codec: transforms lost */`\n }\n\n // Primitives\n if (schema instanceof z.ZodString) return 'z.string()'\n if (schema instanceof z.ZodNumber) return 'z.number()'\n if (schema instanceof z.ZodBoolean) return 'z.boolean()'\n if (schema instanceof z.ZodNull) return 'z.null()'\n if (schema instanceof z.ZodUndefined) return 'z.undefined()'\n if (schema instanceof z.ZodAny) return 'z.any()'\n\n // Objects\n if (schema instanceof z.ZodObject) {\n const shape = def.shape as Record<string, z.ZodTypeAny>\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 z.ZodArray) {\n return `z.array(${zodToSource(def.element, ctx)})`\n }\n\n // Enums\n if (schema instanceof z.ZodEnum) {\n const values = (schema.options as string[]).map(v => `\"${v}\"`).join(', ')\n return `z.enum([${values}])`\n }\n\n // Literals\n if (schema instanceof z.ZodLiteral) {\n const values = def.values as Set<unknown>\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 z.ZodUnion) {\n const members = (def.options as z.ZodTypeAny[])\n .map((s: z.ZodTypeAny) => zodToSource(s, ctx))\n .join(', ')\n return `z.union([${members}])`\n }\n\n // Tuples\n if (schema instanceof z.ZodTuple) {\n const items = (def.items as z.ZodTypeAny[])\n .map((s: z.ZodTypeAny) => zodToSource(s, ctx))\n .join(', ')\n return `z.tuple([${items}])`\n }\n\n // Records\n if (schema instanceof z.ZodRecord) {\n return `z.record(${zodToSource(def.keyType, ctx)}, ${zodToSource(def.valueType, ctx)})`\n }\n\n // Fallback for unsupported types\n const typeName = def?.type ?? 'unknown'\n return `z.any() /* unsupported: ${typeName} */`\n}\n","import { z } from 'zod'\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: z.ZodTypeAny): string {\n const def = (schema as any)._zod?.def\n if (!def?.in || !def?.out) return ''\n return `${zodToSource(def.in)}|${zodToSource(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: z.ZodTypeAny\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 the\n * suffix string to reconstruct the wrappers in source output.\n */\nfunction tryUnwrapToIdentity(\n schema: z.ZodTypeAny,\n identityMap: Map<z.ZodTypeAny, SchemaRef>\n): { ref: SchemaRef; suffix: string } | null {\n let current = schema\n const suffixes: string[] = []\n const maxDepth = 5\n\n for (let i = 0; i < maxDepth; i++) {\n const def = current._zod?.def as any\n if (current instanceof z.ZodOptional) {\n suffixes.push('.optional()')\n current = def.innerType\n } else if (current instanceof z.ZodNullable) {\n suffixes.push('.nullable()')\n current = def.innerType\n } else {\n break\n }\n\n const ref = identityMap.get(current)\n if (ref) {\n // Reverse: suffixes were collected outermost-first, but source reads innermost-first\n return { ref, suffix: suffixes.reverse().join('') }\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: z.ZodTypeAny,\n identityMap: Map<z.ZodTypeAny, SchemaRef>\n): { ref: SchemaRef; suffix: string } | null {\n if (!(schema instanceof z.ZodObject)) return null\n const candidateShape = schema.shape as Record<string, z.ZodTypeAny>\n const candidateKeys = Object.keys(candidateShape).sort()\n\n for (const [modelSchema, ref] of identityMap) {\n if (!(modelSchema instanceof z.ZodObject)) continue\n const modelShape = modelSchema.shape as Record<string, z.ZodTypeAny>\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 z.ZodOptional)) {\n allMatch = false\n break\n }\n const inner = (candidateField as any)._zod?.def?.innerType\n if (inner !== modelShape[key]) {\n allMatch = false\n break\n }\n }\n\n if (allMatch) {\n return { ref, suffix: '.partial()' }\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): GeneratedFile {\n // Build identity map: runtime schema object → model reference string\n const identityMap = new Map<z.ZodTypeAny, 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 z.ZodTypeAny, {\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<z.ZodTypeAny, 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 }\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: z.ZodTypeAny | undefined): string {\n if (!schema) return 'undefined'\n\n // 1. Direct identity match\n const ref = identityMap.get(schema)\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(schema, identityMap)\n if (unwrapped) {\n neededModelImports.add(unwrapped.ref.exportName)\n return `${unwrapped.ref.exportName}.schema.${unwrapped.ref.schemaKey}${unwrapped.suffix}`\n }\n\n // 3. Partial-aware match (detect .partial() of a model schema)\n const partialMatch = tryMatchPartial(schema, identityMap)\n if (partialMatch) {\n neededModelImports.add(partialMatch.ref.exportName)\n return `${partialMatch.ref.exportName}.schema.${partialMatch.ref.schemaKey}${partialMatch.suffix}`\n }\n\n // 4. Fall back to zodToSource (with codec context)\n const source = zodToSource(schema, 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 if (needsZod) imports.push(\"import { z } from 'zod'\")\n\n // Build single zodvex/core import (zx, extractCodec)\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 'zodvex/core'`)\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 = `${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(): GeneratedFile {\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 'zodvex/core'\",\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 'zodvex/core'\"\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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "zodvex",
|
|
3
|
-
"version": "0.6.0-beta.
|
|
3
|
+
"version": "0.6.0-beta.53",
|
|
4
4
|
"description": "Zod <=> Convex integration, supporting Zod 4",
|
|
5
5
|
"keywords": ["zod", "convex", "validators", "codec", "mapping", "schema", "validation"],
|
|
6
6
|
"homepage": "https://github.com/panzacoder/zodvex#readme",
|
package/src/codegen/discover.ts
CHANGED
|
@@ -248,7 +248,11 @@ export async function discoverModules(convexDir: string): Promise<DiscoveryResul
|
|
|
248
248
|
'**/*.test.ts',
|
|
249
249
|
'**/*.test.js',
|
|
250
250
|
'**/*.spec.ts',
|
|
251
|
-
'**/*.spec.js'
|
|
251
|
+
'**/*.spec.js',
|
|
252
|
+
'convex.config.ts',
|
|
253
|
+
'convex.config.js',
|
|
254
|
+
'crons.ts',
|
|
255
|
+
'crons.js'
|
|
252
256
|
]
|
|
253
257
|
})
|
|
254
258
|
|