zodvex 0.7.7 → 0.7.8-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -10
- package/dist/cli/index.js +133 -86
- package/dist/cli/index.js.map +1 -1
- package/dist/client/index.js +17 -6
- package/dist/client/index.js.map +1 -1
- package/dist/codegen/index.js +7 -4
- package/dist/codegen/index.js.map +1 -1
- package/dist/core/index.js +13 -5
- package/dist/core/index.js.map +1 -1
- package/dist/index.js +13 -5
- package/dist/index.js.map +1 -1
- package/dist/internal/boundaryHelpers.d.ts +9 -0
- package/dist/internal/boundaryHelpers.d.ts.map +1 -1
- package/dist/internal/customization.d.ts +27 -1
- package/dist/internal/customization.d.ts.map +1 -1
- package/dist/internal/db.d.ts +43 -17
- package/dist/internal/db.d.ts.map +1 -1
- package/dist/internal/init.d.ts +15 -1
- package/dist/internal/init.d.ts.map +1 -1
- package/dist/internal/rules.d.ts.map +1 -1
- package/dist/labs/index.js +122 -78
- package/dist/labs/index.js.map +1 -1
- package/dist/mini/client/index.js +17 -6
- package/dist/mini/client/index.js.map +1 -1
- package/dist/mini/index.js +13 -5
- package/dist/mini/index.js.map +1 -1
- package/dist/mini/react/index.js +23 -13
- package/dist/mini/react/index.js.map +1 -1
- package/dist/mini/server/index.js +78 -27
- package/dist/mini/server/index.js.map +1 -1
- package/dist/public/client/zodvexClient.d.ts.map +1 -1
- package/dist/public/codegen/zodToSource.d.ts.map +1 -1
- package/dist/public/react/hooks.d.ts.map +1 -1
- package/dist/public/react/zodvexReactClient.d.ts.map +1 -1
- package/dist/public/server/index.d.ts +2 -2
- package/dist/public/server/index.d.ts.map +1 -1
- package/dist/react/index.js +23 -13
- package/dist/react/index.js.map +1 -1
- package/dist/server/index.js +78 -27
- package/dist/server/index.js.map +1 -1
- package/package.json +2 -1
- package/src/internal/boundaryHelpers.ts +25 -5
- package/src/internal/customization.ts +42 -3
- package/src/internal/db.ts +88 -25
- package/src/internal/init.ts +40 -5
- package/src/internal/rules.ts +19 -11
- package/src/public/client/zodvexClient.ts +4 -1
- package/src/public/codegen/zodToSource.ts +12 -4
- package/src/public/react/hooks.ts +8 -11
- package/src/public/react/zodvexReactClient.ts +6 -2
- package/src/public/server/index.ts +7 -2
package/dist/mini/react/index.js
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { ConvexReactClient, useQuery, useMutation } from 'convex/react';
|
|
2
|
-
import { getFunctionName } from 'convex/server';
|
|
3
2
|
import { safeParse, $ZodError, encode, $ZodCodec, $ZodObject, $ZodArray, $ZodOptional, $ZodNullable, $ZodDefault } from 'zod/v4/core';
|
|
4
3
|
|
|
5
4
|
// src/public/react/hooks.ts
|
|
@@ -104,6 +103,7 @@ var ZodvexDecodeError = class extends $ZodError {
|
|
|
104
103
|
var warnedPaths = /* @__PURE__ */ new Set();
|
|
105
104
|
function createBoundaryHelpers(registry, options) {
|
|
106
105
|
const onDecodeError = options?.onDecodeError ?? "warn";
|
|
106
|
+
const warnWirePreview = options?.warnWirePreview === true;
|
|
107
107
|
function encodeArgs(ref, args) {
|
|
108
108
|
if (args == null) return args;
|
|
109
109
|
const path = resolveFunctionPath(ref);
|
|
@@ -130,11 +130,18 @@ function createBoundaryHelpers(registry, options) {
|
|
|
130
130
|
if (onDecodeError === "throw") {
|
|
131
131
|
throw new ZodvexDecodeError(path, result.error.issues, wireResult);
|
|
132
132
|
}
|
|
133
|
-
const
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
133
|
+
const issueList = result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join(", ");
|
|
134
|
+
let message = `[zodvex] Decode failed for ${path}: ${issueList}. Returning raw wire data.`;
|
|
135
|
+
if (warnWirePreview) {
|
|
136
|
+
let preview = "[unavailable]";
|
|
137
|
+
try {
|
|
138
|
+
preview = JSON.stringify(wireResult) ?? "[unavailable]";
|
|
139
|
+
} catch {
|
|
140
|
+
}
|
|
141
|
+
const truncated = preview.length > 200 ? `${preview.slice(0, 200)}...` : preview;
|
|
142
|
+
message += ` Preview: ${truncated}`;
|
|
143
|
+
}
|
|
144
|
+
console.warn(message);
|
|
138
145
|
return wireResult;
|
|
139
146
|
}
|
|
140
147
|
return { encodeArgs, decodeResult };
|
|
@@ -146,20 +153,19 @@ function createZodvexHooks(registry, options) {
|
|
|
146
153
|
function useZodQuery(ref, ...restArgs) {
|
|
147
154
|
const args = restArgs[0];
|
|
148
155
|
let wireArgs = "skip";
|
|
156
|
+
let encodeFailure;
|
|
149
157
|
if (args !== "skip") {
|
|
150
158
|
try {
|
|
151
159
|
wireArgs = codec.encodeArgs(ref, args);
|
|
152
|
-
} catch (
|
|
153
|
-
|
|
154
|
-
console.debug(
|
|
155
|
-
`[zodvex] Encode args failed for ${path}, auto-skipping query: ${err instanceof Error ? err.message : String(err)}`
|
|
156
|
-
);
|
|
160
|
+
} catch (error) {
|
|
161
|
+
encodeFailure = { error };
|
|
157
162
|
}
|
|
158
163
|
}
|
|
159
164
|
const wireResult = useQuery(
|
|
160
165
|
ref,
|
|
161
166
|
...wireArgs === "skip" ? ["skip"] : [wireArgs]
|
|
162
167
|
);
|
|
168
|
+
if (encodeFailure) throw encodeFailure.error;
|
|
163
169
|
if (wireResult === void 0) return void 0;
|
|
164
170
|
return codec.decodeResult(ref, wireResult);
|
|
165
171
|
}
|
|
@@ -179,7 +185,10 @@ var ZodvexReactClient = class {
|
|
|
179
185
|
options;
|
|
180
186
|
pendingAuth;
|
|
181
187
|
constructor(registry, options) {
|
|
182
|
-
this.codec = createBoundaryHelpers(registry, {
|
|
188
|
+
this.codec = createBoundaryHelpers(registry, {
|
|
189
|
+
onDecodeError: options.onDecodeError,
|
|
190
|
+
warnWirePreview: options.warnWirePreview
|
|
191
|
+
});
|
|
183
192
|
this.options = options;
|
|
184
193
|
if ("client" in options) {
|
|
185
194
|
this.innerClient = options.client;
|
|
@@ -244,8 +253,9 @@ var ZodvexReactClient = class {
|
|
|
244
253
|
localQueryResult: () => {
|
|
245
254
|
const wire = innerWatch.localQueryResult();
|
|
246
255
|
if (wire === lastWire) return lastDecoded;
|
|
256
|
+
const decoded = wire === void 0 ? void 0 : this.codec.decodeResult(ref, wire);
|
|
247
257
|
lastWire = wire;
|
|
248
|
-
lastDecoded =
|
|
258
|
+
lastDecoded = decoded;
|
|
249
259
|
return lastDecoded;
|
|
250
260
|
},
|
|
251
261
|
journal: () => innerWatch.journal()
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/internal/normalizeCodecPaths.ts","../../../src/internal/stripUndefined.ts","../../../src/internal/boundaryHelpers.ts","../../../src/public/react/hooks.ts","../../../src/public/react/zodvexReactClient.ts"],"names":[],"mappings":";;;;;;;AAeA,SAAS,YAAY,MAAA,EAA4B;AAC/C,EAAA,IAAI,OAAA,GAAoB,MAAA;AACxB,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,EAAA,EAAI,CAAA,EAAA,EAAK;AAC3B,IAAA,IACE,OAAA,YAAmB,YAAA,IACnB,OAAA,YAAmB,YAAA,IACnB,mBAAmB,WAAA,EACnB;AACA,MAAA,OAAA,GAAU,OAAA,CAAQ,KAAK,GAAA,CAAI,SAAA;AAC3B,MAAA;AAAA,IACF;AACA,IAAA;AAAA,EACF;AACA,EAAA,OAAO,OAAA;AACT;AAOA,SAAS,uBAAA,CAAwB,MAA2B,MAAA,EAAuC;AACjG,EAAA,MAAM,SAA8B,EAAC;AACrC,EAAA,IAAI,OAAA,GAAoB,MAAA;AAExB,EAAA,KAAA,MAAW,WAAW,IAAA,EAAM;AAC1B,IAAA,OAAA,GAAU,YAAY,OAAO,CAAA;AAG7B,IAAA,IAAI,mBAAmB,SAAA,EAAW;AAChC,MAAA;AAAA,IACF;AAGA,IAAA,IAAI,OAAA,YAAmB,UAAA,IAAc,OAAO,OAAA,KAAY,QAAA,EAAU;AAChE,MAAA,MAAM,WAAA,GAAc,OAAA,CAAQ,IAAA,CAA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n $ZodArray,\n $ZodCodec,\n $ZodDefault,\n $ZodError,\n $ZodNullable,\n $ZodObject,\n $ZodOptional,\n $ZodType,\n encode\n} from './zod-core'\n\n/**\n * Unwraps ZodOptional/ZodNullable/ZodDefault wrappers to get the structural type.\n */\nfunction unwrapOuter(schema: $ZodType): $ZodType {\n let current: $ZodType = schema\n for (let i = 0; i < 10; i++) {\n if (\n current instanceof $ZodOptional ||\n current instanceof $ZodNullable ||\n current instanceof $ZodDefault\n ) {\n current = current._zod.def.innerType\n continue\n }\n break\n }\n return current\n}\n\n/**\n * Walks a path through a schema tree, truncating at codec boundaries.\n * When a codec is encountered, the path is cut — any deeper segments\n * are wire-internal and should not be exposed to consumers.\n */\nfunction truncateAtCodecBoundary(path: (string | number)[], schema: $ZodType): (string | number)[] {\n const result: (string | number)[] = []\n let current: $ZodType = schema\n\n for (const segment of path) {\n current = unwrapOuter(current)\n\n // If we've landed on a codec, everything from here is wire-internal — stop\n if (current instanceof $ZodCodec) {\n break\n }\n\n // Descend into objects\n if (current instanceof $ZodObject && typeof segment === 'string') {\n const fieldSchema = current._zod.def.shape[segment] as $ZodType | undefined\n if (!fieldSchema) {\n // Unknown field — include segment and stop\n result.push(segment)\n break\n }\n\n result.push(segment)\n\n const unwrapped = unwrapOuter(fieldSchema)\n if (unwrapped instanceof $ZodCodec) {\n // Hit a codec boundary — truncate here\n break\n }\n\n current = fieldSchema\n continue\n }\n\n // Descend into arrays\n if (current instanceof $ZodArray && typeof segment === 'number') {\n result.push(segment)\n current = current._zod.def.element\n continue\n }\n\n // For anything else (unions, records, etc.), include segment and continue\n result.push(segment)\n }\n\n return result\n}\n\n/**\n * Normalizes ZodError paths by truncating at codec boundaries.\n *\n * When z.encode() throws a ZodError, the paths reflect the wire schema\n * structure (e.g., [\"email\", \"value\"] for a custom codec).\n * This function strips the wire-internal segments so consumers see\n * clean field-level paths (e.g., [\"email\"]).\n */\nexport function normalizeCodecPaths(error: $ZodError, schema: $ZodType): $ZodError {\n const normalized = error.issues.map(issue => ({\n ...issue,\n path: truncateAtCodecBoundary(issue.path as (string | number)[], schema)\n }))\n return new $ZodError(normalized)\n}\n\n/**\n * Encodes a value through a Zod schema, normalizing codec-internal\n * path segments in any ZodError before re-throwing.\n *\n * Drop-in replacement for `z.encode(schema, value)` at client boundaries.\n */\nexport function safeEncode(schema: $ZodType, value: unknown): unknown {\n try {\n return encode(schema, value)\n } catch (e) {\n if (e instanceof $ZodError) throw normalizeCodecPaths(e as $ZodError, schema)\n throw e\n }\n}\n","/**\n * Recursively strips `undefined` values from objects and arrays.\n * Used by codec encode/decode to clean wire data.\n *\n * Extracted to its own module so client-safe code (boundaryHelpers)\n * can import it without pulling in zod via utils.ts.\n */\nexport function stripUndefined<T>(value: T): T {\n if (value === null || value === undefined) {\n return value\n }\n\n if (Array.isArray(value)) {\n return value.map(stripUndefined) as T\n }\n\n // Only process plain objects (not class instances, Dates, etc.)\n if (typeof value === 'object' && value.constructor === Object) {\n const result: Record<string, unknown> = {}\n for (const [key, val] of Object.entries(value)) {\n if (val !== undefined) {\n result[key] = stripUndefined(val)\n }\n }\n return result as T\n }\n\n return value\n}\n","import type { FunctionReference } from 'convex/server'\nimport type { $ZodIssue } from 'zod/v4/core'\nimport { safeEncode } from './normalizeCodecPaths'\nimport { stripUndefined } from './stripUndefined'\nimport type { AnyRegistry } from './types'\nimport { $ZodError, safeParse } from './zod-core'\n\n/**\n * Resolves a Convex FunctionReference to its string path.\n *\n * Mirrors `getFunctionName` from `convex/server` but without the server import.\n * Reads the well-known `Symbol.for('functionName')` that Convex attaches to all\n * function references — the same symbol used by Convex's own browser client.\n */\nconst functionNameSymbol = Symbol.for('functionName')\n\nfunction resolveFunctionPath(ref: FunctionReference<any, any, any, any>): string | null {\n if (typeof ref === 'string') return ref\n const name = (ref as any)[functionNameSymbol]\n if (!name) return null\n return name\n}\n\n/**\n * Options for codec helper behavior.\n */\nexport type BoundaryHelpersOptions = {\n /**\n * How to handle decode failures (schema validation errors on wire data).\n *\n * - `'warn'` (default): log a console.warn and return raw wire data untransformed.\n * - `'throw'`: throw a ZodvexDecodeError (extends z.ZodError). // zod-ok\n */\n onDecodeError?: 'warn' | 'throw'\n}\n\n/**\n * Decode error with function path and wire data context.\n * Extends $ZodError from zod/v4/core for compatibility with both zod and zod/mini.\n * instanceof $ZodError checks work in both variants.\n */\nexport class ZodvexDecodeError extends $ZodError {\n readonly functionPath: string\n readonly wireData: unknown\n\n constructor(functionPath: string, issues: $ZodIssue[], wireData: unknown) {\n super(issues)\n this.functionPath = functionPath\n this.wireData = wireData\n this.name = 'ZodvexDecodeError'\n }\n}\n\n/**\n * Creates shared encode/decode helpers bound to a zodvex registry.\n *\n * These are the core primitives used by all codec boundary implementations:\n * - `encodeArgs`: runtime types -> wire format (e.g., Date -> timestamp number)\n * - `decodeResult`: wire format -> runtime types (e.g., timestamp number -> Date)\n *\n * Both look up the function reference in the registry to find the appropriate\n * Zod schema, then apply the codec transform. Functions not in the registry\n * (or without the relevant schema) pass through unchanged.\n *\n * @param registry - A map of function paths to `{ args?, returns? }` Zod schemas.\n * Typically generated by zodvex codegen into `_zodvex/api.ts`.\n * @param options - Optional configuration for decode error behavior.\n */\n/**\n * Module-scoped so the registry-miss note fires once per path per process.\n * A per-helpers set resets on every Convex invocation (ctx is wrapped per\n * call), which spammed hot paths on every request (#101).\n */\nconst warnedPaths = new Set<string>()\n\n/** @internal Test-only: clears the process-wide registry-miss dedup set. */\nexport function __resetRegistryMissWarnings(): void {\n warnedPaths.clear()\n}\n\nexport function createBoundaryHelpers(registry: AnyRegistry, options?: BoundaryHelpersOptions) {\n const onDecodeError = options?.onDecodeError ?? 'warn'\n\n /**\n * Encode args from runtime types to wire format.\n *\n * Uses `safeEncode` (not raw `z.encode`) to normalize codec-internal\n * error paths in ZodErrors, then strips undefined values for Convex\n * serialization compatibility.\n *\n * Passthrough when:\n * - args is null/undefined\n * - function is not in the registry\n * - registry entry has no args schema\n */\n function encodeArgs(ref: FunctionReference<any, any, any, any>, args: any): any {\n if (args == null) return args\n const path = resolveFunctionPath(ref)\n if (path == null) return args\n const entry = registry[path]\n if (!entry?.args) {\n if (entry === undefined && !warnedPaths.has(path)) {\n warnedPaths.add(path)\n console.debug(\n `[zodvex] No registry entry for \"${path}\" — args/returns pass through unencoded. ` +\n 'This is expected when the target is a raw (non-zodvex) function; if it should be ' +\n 'codec-aware, run `zodvex generate` to update the registry.'\n )\n }\n return args\n }\n return stripUndefined(safeEncode(entry.args, args))\n }\n\n /**\n * Decode a wire result back to runtime types.\n *\n * Uses `.safeParse()` to decode. On failure:\n * - 'warn' (default): logs warning, returns raw wireResult\n * - 'throw': throws ZodvexDecodeError (extends z.ZodError) // zod-ok\n *\n * Passthrough when:\n * - function is not in the registry\n * - registry entry has no returns schema\n */\n function decodeResult(ref: FunctionReference<any, any, any, any>, wireResult: any): any {\n const path = resolveFunctionPath(ref)\n if (path == null) return wireResult\n const entry = registry[path]\n if (!entry?.returns) return wireResult\n\n const result = safeParse(entry.returns, wireResult)\n if (result.success) return result.data\n\n if (onDecodeError === 'throw') {\n throw new ZodvexDecodeError(path, result.error.issues, wireResult)\n }\n\n // Default: warn and return raw wire data\n const preview = JSON.stringify(wireResult)\n const truncated = preview.length > 200 ? `${preview.slice(0, 200)}...` : preview\n console.warn(\n `[zodvex] Decode failed for ${path}: ${result.error.issues.map((i: $ZodIssue) => `${i.path.join('.')}: ${i.message}`).join(', ')}. Returning raw wire data. Preview: ${truncated}`\n )\n return wireResult\n }\n\n return { encodeArgs, decodeResult }\n}\n\nexport type BoundaryHelpers = ReturnType<typeof createBoundaryHelpers>\n","import type { OptionalRestArgsOrSkip } from 'convex/react'\nimport { useMutation, useQuery } from 'convex/react'\nimport type { FunctionArgs, FunctionReference, FunctionReturnType } from 'convex/server'\nimport { getFunctionName } from 'convex/server'\nimport type { BoundaryHelpersOptions } from '../../internal/boundaryHelpers'\nimport { createBoundaryHelpers } from '../../internal/boundaryHelpers'\nimport type { AnyRegistry } from '../../internal/types'\n\n/**\n * Creates zodvex-aware React hooks that automatically decode query results\n * and encode mutation arguments using the Zod schemas in the registry.\n *\n * Returned hooks are drop-in replacements for Convex's `useQuery` and\n * `useMutation` — they delegate to the real hooks, then apply codec\n * transforms so that runtime types (e.g. Date) are used instead of wire\n * types (e.g. number timestamps).\n *\n * @param registry - A map of function paths to `{ args?, returns? }` Zod schemas.\n * Typically generated by zodvex codegen into `_zodvex/client.ts`.\n *\n * @example\n * ```typescript\n * import { zodvexRegistry } from '../_zodvex/client'\n * export const { useZodQuery, useZodMutation } = createZodvexHooks(zodvexRegistry)\n *\n * // In a component:\n * const tasks = useZodQuery(api.tasks.list, { status: 'active' })\n * // ^? Task[] — createdAt is Date, not number\n * ```\n */\nexport function createZodvexHooks<R extends AnyRegistry>(\n registry: R,\n options?: BoundaryHelpersOptions\n) {\n const codec = createBoundaryHelpers(registry, options)\n\n /**\n * Drop-in replacement for Convex's `useQuery` with automatic codec decode.\n *\n * Delegates to the real `useQuery` and then decodes the wire result through\n * the `returns` schema in the registry (if one exists for this function).\n *\n * Two overloads:\n * 1. Rest-args (Convex-compatible): `useZodQuery(ref, args)` or `useZodQuery(ref, 'skip')`\n * 2. Union args (composable): `useZodQuery(ref, args | 'skip')` — for wrappers\n * and conditional skip patterns where the decision is made upstream.\n *\n * - Loading state (`undefined`) passes through unchanged.\n * - Functions not in the registry return the raw wire result.\n */\n // Overload 1: drop-in compatible with Convex's useQuery\n function useZodQuery<Query extends FunctionReference<'query', any, any, any>>(\n ref: Query,\n ...args: OptionalRestArgsOrSkip<Query>\n ): FunctionReturnType<Query> | undefined\n // Overload 2: composable — accepts Args | 'skip' union for wrappers\n function useZodQuery<Query extends FunctionReference<'query', any, any, any>>(\n ref: Query,\n args: Query['_args'] | 'skip'\n ): FunctionReturnType<Query> | undefined\n // Implementation\n function useZodQuery(ref: FunctionReference<'query', any, any, any>, ...restArgs: any[]) {\n const args = restArgs[0]\n\n // Encode args: runtime types -> wire format (e.g., Date -> timestamp).\n // Unlike mutations (imperative, user-triggered), hooks fire synchronously\n // during render — an encode error would crash the page. On failure, warn\n // and auto-skip the query (return undefined = loading state).\n let wireArgs: any = 'skip'\n if (args !== 'skip') {\n try {\n wireArgs = codec.encodeArgs(ref, args)\n } catch (err) {\n const path = getFunctionName(ref)\n console.debug(\n `[zodvex] Encode args failed for ${path}, auto-skipping query: ${err instanceof Error ? err.message : String(err)}`\n )\n // wireArgs stays 'skip' — DO NOT early-return, useQuery must run every render\n }\n }\n\n const wireResult = useQuery(\n ref,\n ...((wireArgs === 'skip' ? ['skip'] : [wireArgs]) as OptionalRestArgsOrSkip<typeof ref>)\n )\n\n // Loading state — Convex returns undefined while the subscription is pending\n if (wireResult === undefined) return undefined\n\n // Decode: wire format -> runtime types (e.g., timestamp number -> Date)\n return codec.decodeResult(ref, wireResult)\n }\n\n /**\n * Drop-in replacement for Convex's `useMutation`.\n *\n * Returns an async function that:\n * 1. Encodes the args through the `args` schema (runtime -> wire format)\n * 2. Calls the real mutation with the wire args\n * 3. Decodes the result through the `returns` schema (wire -> runtime format)\n *\n * Functions not in the registry pass args and results through unchanged.\n */\n function useZodMutation<Mutation extends FunctionReference<'mutation', any, any, any>>(\n ref: Mutation\n ) {\n const rawMutate = useMutation(ref)\n\n return async (args: FunctionArgs<Mutation>): Promise<FunctionReturnType<Mutation>> => {\n // Encode args: runtime types -> wire format (e.g., Date -> timestamp)\n const wireArgs = codec.encodeArgs(ref, args)\n\n const wireResult = await (rawMutate as any)(wireArgs)\n\n // Decode result: wire format -> runtime types\n return codec.decodeResult(ref, wireResult)\n }\n }\n\n return { useZodQuery, useZodMutation }\n}\n\n/**\n * The return type of `createZodvexHooks` — useful for typing module-level\n * exports in generated client files.\n */\nexport type ZodvexHooks = ReturnType<typeof createZodvexHooks>\n","import type { AuthTokenFetcher, ConnectionState } from 'convex/browser'\nimport type { Watch, WatchQueryOptions } from 'convex/react'\nimport { ConvexReactClient } from 'convex/react'\nimport type { FunctionArgs, FunctionReference, FunctionReturnType } from 'convex/server'\nimport type { BoundaryHelpersOptions } from '../../internal/boundaryHelpers'\nimport { createBoundaryHelpers } from '../../internal/boundaryHelpers'\nimport type { AnyRegistry } from '../../internal/types'\n\nexport type ZodvexReactClientOptions = ({ url: string } | { client: ConvexReactClient }) &\n BoundaryHelpersOptions\n\nexport class ZodvexReactClient<R extends AnyRegistry = AnyRegistry> {\n private codec: ReturnType<typeof createBoundaryHelpers>\n private innerClient?: ConvexReactClient\n private options: ZodvexReactClientOptions\n private pendingAuth?: {\n fetchToken: AuthTokenFetcher\n onChange?: (isAuthenticated: boolean) => void\n }\n\n constructor(registry: R, options: ZodvexReactClientOptions) {\n this.codec = createBoundaryHelpers(registry, { onDecodeError: options.onDecodeError })\n this.options = options\n if ('client' in options) {\n this.innerClient = options.client\n }\n }\n\n private getUrl(): string {\n if ('url' in this.options) return this.options.url\n if (this.innerClient) return this.innerClient.url\n throw new Error('[zodvex] ZodvexReactClient is missing a Convex URL.')\n }\n\n private getConvex(): ConvexReactClient {\n if (this.innerClient) return this.innerClient\n\n const client = new ConvexReactClient(this.getUrl())\n if (this.pendingAuth) {\n client.setAuth(this.pendingAuth.fetchToken, this.pendingAuth.onChange)\n }\n this.innerClient = client\n return client\n }\n\n get convex(): ConvexReactClient {\n return this.getConvex()\n }\n\n // ---------------------------------------------------------------------------\n // Data methods — codec-wrapped\n // ---------------------------------------------------------------------------\n\n async query<Q extends FunctionReference<'query', any, any, any>>(\n ref: Q,\n args: Q['_args']\n ): Promise<Q['_returnType']> {\n const wireResult = await this.getConvex().query(\n ref,\n this.codec.encodeArgs(ref, args) as FunctionArgs<Q>\n )\n return this.codec.decodeResult(ref, wireResult)\n }\n\n async mutation<M extends FunctionReference<'mutation', any, any, any>>(\n ref: M,\n args: M['_args']\n ): Promise<M['_returnType']> {\n const wireResult = await this.getConvex().mutation(\n ref,\n this.codec.encodeArgs(ref, args) as FunctionArgs<M>\n )\n return this.codec.decodeResult(ref, wireResult)\n }\n\n async action<A extends FunctionReference<'action', any, any, any>>(\n ref: A,\n args: A['_args']\n ): Promise<A['_returnType']> {\n const wireResult = await this.getConvex().action(\n ref,\n this.codec.encodeArgs(ref, args) as FunctionArgs<A>\n )\n return this.codec.decodeResult(ref, wireResult)\n }\n\n /**\n * Indicates likely future interest in a query subscription. Encodes args to\n * wire before delegating, mirroring {@link watchQuery}.\n */\n prewarmQuery<Q extends FunctionReference<'query', any, any, any>>(queryOptions: {\n query: Q\n args: Q['_args']\n extendSubscriptionFor?: number\n }): void {\n const wireArgs = this.codec.encodeArgs(queryOptions.query, queryOptions.args) as FunctionArgs<Q>\n this.getConvex().prewarmQuery({ ...queryOptions, args: wireArgs })\n }\n\n watchQuery<Q extends FunctionReference<'query', any, any, any>>(\n ref: Q,\n args: Q['_args'],\n options?: WatchQueryOptions\n ): Watch<Q['_returnType']> {\n const wireArgs = this.codec.encodeArgs(ref, args) as FunctionArgs<Q>\n const innerWatch = this.getConvex().watchQuery(ref, wireArgs, options as any)\n\n // Memoize by wire reference identity to avoid redundant Zod parse.\n // Convex creates a new object per server transition via jsonToConvex()\n // in remote_query_set.ts, but returns the same reference for repeated\n // reads within a single transition window.\n // See: convex/src/browser/sync/optimistic_updates_impl.ts\n // TODO(CX-733) — Convex internal tracker for client-side result\n // memoization (not yet public).\n let lastWire: unknown\n let lastDecoded: unknown\n\n return {\n onUpdate: (cb: () => void) => innerWatch.onUpdate(cb),\n localQueryResult: () => {\n const wire = innerWatch.localQueryResult()\n if (wire === lastWire) return lastDecoded\n lastWire = wire\n lastDecoded = wire === undefined ? undefined : this.codec.decodeResult(ref, wire)\n return lastDecoded\n },\n journal: () => innerWatch.journal()\n }\n }\n\n // ---------------------------------------------------------------------------\n // Pass-through methods — no codec needed\n // ---------------------------------------------------------------------------\n\n setAuth(fetchToken: AuthTokenFetcher, onChange?: (isAuthenticated: boolean) => void): void {\n this.pendingAuth = { fetchToken, onChange }\n if (this.innerClient) {\n this.innerClient.setAuth(fetchToken, onChange)\n }\n }\n\n clearAuth(): void {\n this.pendingAuth = undefined\n this.innerClient?.clearAuth()\n }\n\n async close(): Promise<void> {\n await this.getConvex().close()\n }\n\n get url(): string {\n return this.getUrl()\n }\n\n get logger(): ConvexReactClient['logger'] {\n return this.getConvex().logger\n }\n\n connectionState() {\n return this.getConvex().connectionState()\n }\n\n subscribeToConnectionState(cb: (state: ConnectionState) => void): () => void {\n return this.getConvex().subscribeToConnectionState(cb)\n }\n}\n\nexport function createZodvexReactClient<R extends AnyRegistry>(\n registry: R,\n options: ZodvexReactClientOptions\n): ZodvexReactClient<R> {\n return new ZodvexReactClient(registry, options)\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/internal/normalizeCodecPaths.ts","../../../src/internal/stripUndefined.ts","../../../src/internal/boundaryHelpers.ts","../../../src/public/react/hooks.ts","../../../src/public/react/zodvexReactClient.ts"],"names":[],"mappings":";;;;;;AAeA,SAAS,YAAY,MAAA,EAA4B;AAC/C,EAAA,IAAI,OAAA,GAAoB,MAAA;AACxB,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,EAAA,EAAI,CAAA,EAAA,EAAK;AAC3B,IAAA,IACE,OAAA,YAAmB,YAAA,IACnB,OAAA,YAAmB,YAAA,IACnB,mBAAmB,WAAA,EACnB;AACA,MAAA,OAAA,GAAU,OAAA,CAAQ,KAAK,GAAA,CAAI,SAAA;AAC3B,MAAA;AAAA,IACF;AACA,IAAA;AAAA,EACF;AACA,EAAA,OAAO,OAAA;AACT;AAOA,SAAS,uBAAA,CAAwB,MAA2B,MAAA,EAAuC;AACjG,EAAA,MAAM,SAA8B,EAAC;AACrC,EAAA,IAAI,OAAA,GAAoB,MAAA;AAExB,EAAA,KAAA,MAAW,WAAW,IAAA,EAAM;AAC1B,IAAA,OAAA,GAAU,YAAY,OAAO,CAAA;AAG7B,IAAA,IAAI,mBAAmB,SAAA,EAAW;AAChC,MAAA;AAAA,IACF;AAGA,IAAA,IAAI,OAAA,YAAmB,UAAA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,eAAA,GAAkB;AAChB,IAAA,OAAO,IAAA,CAAK,SAAA,EAAU,CAAE,eAAA,EAAgB;AAAA,EAC1C;AAAA,EAEA,2BAA2B,EAAA,EAAkD;AAC3E,IAAA,OAAO,IAAA,CAAK,SAAA,EAAU,CAAE,0BAAA,CAA2B,EAAE,CAAA;AAAA,EACvD;AACF;AAEO,SAAS,uBAAA,CACd,UACA,OAAA,EACsB;AACtB,EAAA,OAAO,IAAI,iBAAA,CAAkB,QAAA,EAAU,OAAO,CAAA;AAChD","file":"index.js","sourcesContent":["import {\n $ZodArray,\n $ZodCodec,\n $ZodDefault,\n $ZodError,\n $ZodNullable,\n $ZodObject,\n $ZodOptional,\n $ZodType,\n encode\n} from './zod-core'\n\n/**\n * Unwraps ZodOptional/ZodNullable/ZodDefault wrappers to get the structural type.\n */\nfunction unwrapOuter(schema: $ZodType): $ZodType {\n let current: $ZodType = schema\n for (let i = 0; i < 10; i++) {\n if (\n current instanceof $ZodOptional ||\n current instanceof $ZodNullable ||\n current instanceof $ZodDefault\n ) {\n current = current._zod.def.innerType\n continue\n }\n break\n }\n return current\n}\n\n/**\n * Walks a path through a schema tree, truncating at codec boundaries.\n * When a codec is encountered, the path is cut — any deeper segments\n * are wire-internal and should not be exposed to consumers.\n */\nfunction truncateAtCodecBoundary(path: (string | number)[], schema: $ZodType): (string | number)[] {\n const result: (string | number)[] = []\n let current: $ZodType = schema\n\n for (const segment of path) {\n current = unwrapOuter(current)\n\n // If we've landed on a codec, everything from here is wire-internal — stop\n if (current instanceof $ZodCodec) {\n break\n }\n\n // Descend into objects\n if (current instanceof $ZodObject && typeof segment === 'string') {\n const fieldSchema = current._zod.def.shape[segment] as $ZodType | undefined\n if (!fieldSchema) {\n // Unknown field — include segment and stop\n result.push(segment)\n break\n }\n\n result.push(segment)\n\n const unwrapped = unwrapOuter(fieldSchema)\n if (unwrapped instanceof $ZodCodec) {\n // Hit a codec boundary — truncate here\n break\n }\n\n current = fieldSchema\n continue\n }\n\n // Descend into arrays\n if (current instanceof $ZodArray && typeof segment === 'number') {\n result.push(segment)\n current = current._zod.def.element\n continue\n }\n\n // For anything else (unions, records, etc.), include segment and continue\n result.push(segment)\n }\n\n return result\n}\n\n/**\n * Normalizes ZodError paths by truncating at codec boundaries.\n *\n * When z.encode() throws a ZodError, the paths reflect the wire schema\n * structure (e.g., [\"email\", \"value\"] for a custom codec).\n * This function strips the wire-internal segments so consumers see\n * clean field-level paths (e.g., [\"email\"]).\n */\nexport function normalizeCodecPaths(error: $ZodError, schema: $ZodType): $ZodError {\n const normalized = error.issues.map(issue => ({\n ...issue,\n path: truncateAtCodecBoundary(issue.path as (string | number)[], schema)\n }))\n return new $ZodError(normalized)\n}\n\n/**\n * Encodes a value through a Zod schema, normalizing codec-internal\n * path segments in any ZodError before re-throwing.\n *\n * Drop-in replacement for `z.encode(schema, value)` at client boundaries.\n */\nexport function safeEncode(schema: $ZodType, value: unknown): unknown {\n try {\n return encode(schema, value)\n } catch (e) {\n if (e instanceof $ZodError) throw normalizeCodecPaths(e as $ZodError, schema)\n throw e\n }\n}\n","/**\n * Recursively strips `undefined` values from objects and arrays.\n * Used by codec encode/decode to clean wire data.\n *\n * Extracted to its own module so client-safe code (boundaryHelpers)\n * can import it without pulling in zod via utils.ts.\n */\nexport function stripUndefined<T>(value: T): T {\n if (value === null || value === undefined) {\n return value\n }\n\n if (Array.isArray(value)) {\n return value.map(stripUndefined) as T\n }\n\n // Only process plain objects (not class instances, Dates, etc.)\n if (typeof value === 'object' && value.constructor === Object) {\n const result: Record<string, unknown> = {}\n for (const [key, val] of Object.entries(value)) {\n if (val !== undefined) {\n result[key] = stripUndefined(val)\n }\n }\n return result as T\n }\n\n return value\n}\n","import type { FunctionReference } from 'convex/server'\nimport type { $ZodIssue } from 'zod/v4/core'\nimport { safeEncode } from './normalizeCodecPaths'\nimport { stripUndefined } from './stripUndefined'\nimport type { AnyRegistry } from './types'\nimport { $ZodError, safeParse } from './zod-core'\n\n/**\n * Resolves a Convex FunctionReference to its string path.\n *\n * Mirrors `getFunctionName` from `convex/server` but without the server import.\n * Reads the well-known `Symbol.for('functionName')` that Convex attaches to all\n * function references — the same symbol used by Convex's own browser client.\n */\nconst functionNameSymbol = Symbol.for('functionName')\n\nfunction resolveFunctionPath(ref: FunctionReference<any, any, any, any>): string | null {\n if (typeof ref === 'string') return ref\n const name = (ref as any)[functionNameSymbol]\n if (!name) return null\n return name\n}\n\n/**\n * Options for codec helper behavior.\n */\nexport type BoundaryHelpersOptions = {\n /**\n * How to handle decode failures (schema validation errors on wire data).\n *\n * - `'warn'` (default): log a console.warn and return raw wire data untransformed.\n * - `'throw'`: throw a ZodvexDecodeError (extends z.ZodError). // zod-ok\n */\n onDecodeError?: 'warn' | 'throw'\n /**\n * Include a truncated preview of the raw wire data in the decode-failure\n * `warn` log (only relevant when `onDecodeError` is `'warn'`, the default).\n *\n * Off by default because wire values may be sensitive — the default warn\n * message only carries the function path and zod issue list. Enable only\n * when debugging a decode skew and you need to see the offending values.\n */\n warnWirePreview?: boolean\n}\n\n/**\n * Decode error with function path and wire data context.\n * Extends $ZodError from zod/v4/core for compatibility with both zod and zod/mini.\n * instanceof $ZodError checks work in both variants.\n */\nexport class ZodvexDecodeError extends $ZodError {\n readonly functionPath: string\n readonly wireData: unknown\n\n constructor(functionPath: string, issues: $ZodIssue[], wireData: unknown) {\n super(issues)\n this.functionPath = functionPath\n this.wireData = wireData\n this.name = 'ZodvexDecodeError'\n }\n}\n\n/**\n * Creates shared encode/decode helpers bound to a zodvex registry.\n *\n * These are the core primitives used by all codec boundary implementations:\n * - `encodeArgs`: runtime types -> wire format (e.g., Date -> timestamp number)\n * - `decodeResult`: wire format -> runtime types (e.g., timestamp number -> Date)\n *\n * Both look up the function reference in the registry to find the appropriate\n * Zod schema, then apply the codec transform. Functions not in the registry\n * (or without the relevant schema) pass through unchanged.\n *\n * @param registry - A map of function paths to `{ args?, returns? }` Zod schemas.\n * Typically generated by zodvex codegen into `_zodvex/api.ts`.\n * @param options - Optional configuration for decode error behavior.\n */\n/**\n * Module-scoped so the registry-miss note fires once per path per process.\n * A per-helpers set resets on every Convex invocation (ctx is wrapped per\n * call), which spammed hot paths on every request (#101).\n */\nconst warnedPaths = new Set<string>()\n\n/** @internal Test-only: clears the process-wide registry-miss dedup set. */\nexport function __resetRegistryMissWarnings(): void {\n warnedPaths.clear()\n}\n\nexport function createBoundaryHelpers(registry: AnyRegistry, options?: BoundaryHelpersOptions) {\n const onDecodeError = options?.onDecodeError ?? 'warn'\n const warnWirePreview = options?.warnWirePreview === true\n\n /**\n * Encode args from runtime types to wire format.\n *\n * Uses `safeEncode` (not raw `z.encode`) to normalize codec-internal\n * error paths in ZodErrors, then strips undefined values for Convex\n * serialization compatibility.\n *\n * Passthrough when:\n * - args is null/undefined\n * - function is not in the registry\n * - registry entry has no args schema\n */\n function encodeArgs(ref: FunctionReference<any, any, any, any>, args: any): any {\n if (args == null) return args\n const path = resolveFunctionPath(ref)\n if (path == null) return args\n const entry = registry[path]\n if (!entry?.args) {\n if (entry === undefined && !warnedPaths.has(path)) {\n warnedPaths.add(path)\n console.debug(\n `[zodvex] No registry entry for \"${path}\" — args/returns pass through unencoded. ` +\n 'This is expected when the target is a raw (non-zodvex) function; if it should be ' +\n 'codec-aware, run `zodvex generate` to update the registry.'\n )\n }\n return args\n }\n return stripUndefined(safeEncode(entry.args, args))\n }\n\n /**\n * Decode a wire result back to runtime types.\n *\n * Uses `.safeParse()` to decode. On failure:\n * - 'warn' (default): logs warning, returns raw wireResult\n * - 'throw': throws ZodvexDecodeError (extends z.ZodError) // zod-ok\n *\n * Passthrough when:\n * - function is not in the registry\n * - registry entry has no returns schema\n */\n function decodeResult(ref: FunctionReference<any, any, any, any>, wireResult: any): any {\n const path = resolveFunctionPath(ref)\n if (path == null) return wireResult\n const entry = registry[path]\n if (!entry?.returns) return wireResult\n\n const result = safeParse(entry.returns, wireResult)\n if (result.success) return result.data\n\n if (onDecodeError === 'throw') {\n throw new ZodvexDecodeError(path, result.error.issues, wireResult)\n }\n\n // Default: warn and return raw wire data\n const issueList = result.error.issues\n .map((i: $ZodIssue) => `${i.path.join('.')}: ${i.message}`)\n .join(', ')\n let message = `[zodvex] Decode failed for ${path}: ${issueList}. Returning raw wire data.`\n if (warnWirePreview) {\n let preview = '[unavailable]'\n try {\n preview = JSON.stringify(wireResult) ?? '[unavailable]'\n } catch {\n // Debug logging must not change warn-mode behavior for non-JSON values.\n }\n const truncated = preview.length > 200 ? `${preview.slice(0, 200)}...` : preview\n message += ` Preview: ${truncated}`\n }\n console.warn(message)\n return wireResult\n }\n\n return { encodeArgs, decodeResult }\n}\n\nexport type BoundaryHelpers = ReturnType<typeof createBoundaryHelpers>\n","import type { OptionalRestArgsOrSkip } from 'convex/react'\nimport { useMutation, useQuery } from 'convex/react'\nimport type { FunctionArgs, FunctionReference, FunctionReturnType } from 'convex/server'\nimport type { BoundaryHelpersOptions } from '../../internal/boundaryHelpers'\nimport { createBoundaryHelpers } from '../../internal/boundaryHelpers'\nimport type { AnyRegistry } from '../../internal/types'\n\n/**\n * Creates zodvex-aware React hooks that automatically decode query results\n * and encode mutation arguments using the Zod schemas in the registry.\n *\n * Returned hooks are drop-in replacements for Convex's `useQuery` and\n * `useMutation` — they delegate to the real hooks, then apply codec\n * transforms so that runtime types (e.g. Date) are used instead of wire\n * types (e.g. number timestamps).\n *\n * @param registry - A map of function paths to `{ args?, returns? }` Zod schemas.\n * Typically generated by zodvex codegen into `_zodvex/client.ts`.\n *\n * @example\n * ```typescript\n * import { zodvexRegistry } from '../_zodvex/client'\n * export const { useZodQuery, useZodMutation } = createZodvexHooks(zodvexRegistry)\n *\n * // In a component:\n * const tasks = useZodQuery(api.tasks.list, { status: 'active' })\n * // ^? Task[] — createdAt is Date, not number\n * ```\n */\nexport function createZodvexHooks<R extends AnyRegistry>(\n registry: R,\n options?: BoundaryHelpersOptions\n) {\n const codec = createBoundaryHelpers(registry, options)\n\n /**\n * Drop-in replacement for Convex's `useQuery` with automatic codec decode.\n *\n * Delegates to the real `useQuery` and then decodes the wire result through\n * the `returns` schema in the registry (if one exists for this function).\n *\n * Two overloads:\n * 1. Rest-args (Convex-compatible): `useZodQuery(ref, args)` or `useZodQuery(ref, 'skip')`\n * 2. Union args (composable): `useZodQuery(ref, args | 'skip')` — for wrappers\n * and conditional skip patterns where the decision is made upstream.\n *\n * - Invalid arguments throw during render; use a React error boundary to handle them.\n * - Loading state (`undefined`) passes through unchanged.\n * - Functions not in the registry return the raw wire result.\n */\n // Overload 1: drop-in compatible with Convex's useQuery\n function useZodQuery<Query extends FunctionReference<'query', any, any, any>>(\n ref: Query,\n ...args: OptionalRestArgsOrSkip<Query>\n ): FunctionReturnType<Query> | undefined\n // Overload 2: composable — accepts Args | 'skip' union for wrappers\n function useZodQuery<Query extends FunctionReference<'query', any, any, any>>(\n ref: Query,\n args: Query['_args'] | 'skip'\n ): FunctionReturnType<Query> | undefined\n // Implementation\n function useZodQuery(ref: FunctionReference<'query', any, any, any>, ...restArgs: any[]) {\n const args = restArgs[0]\n\n // Always call useQuery, including failed encodes, to preserve hook order.\n // Then surface the error to React's error boundary instead of appearing to load forever.\n let wireArgs: any = 'skip'\n let encodeFailure: { error: unknown } | undefined\n if (args !== 'skip') {\n try {\n wireArgs = codec.encodeArgs(ref, args)\n } catch (error) {\n encodeFailure = { error }\n }\n }\n\n const wireResult = useQuery(\n ref,\n ...((wireArgs === 'skip' ? ['skip'] : [wireArgs]) as OptionalRestArgsOrSkip<typeof ref>)\n )\n\n if (encodeFailure) throw encodeFailure.error\n\n // Loading state — Convex returns undefined while the subscription is pending\n if (wireResult === undefined) return undefined\n\n // Decode: wire format -> runtime types (e.g., timestamp number -> Date)\n return codec.decodeResult(ref, wireResult)\n }\n\n /**\n * Drop-in replacement for Convex's `useMutation`.\n *\n * Returns an async function that:\n * 1. Encodes the args through the `args` schema (runtime -> wire format)\n * 2. Calls the real mutation with the wire args\n * 3. Decodes the result through the `returns` schema (wire -> runtime format)\n *\n * Functions not in the registry pass args and results through unchanged.\n */\n function useZodMutation<Mutation extends FunctionReference<'mutation', any, any, any>>(\n ref: Mutation\n ) {\n const rawMutate = useMutation(ref)\n\n return async (args: FunctionArgs<Mutation>): Promise<FunctionReturnType<Mutation>> => {\n // Encode args: runtime types -> wire format (e.g., Date -> timestamp)\n const wireArgs = codec.encodeArgs(ref, args)\n\n const wireResult = await (rawMutate as any)(wireArgs)\n\n // Decode result: wire format -> runtime types\n return codec.decodeResult(ref, wireResult)\n }\n }\n\n return { useZodQuery, useZodMutation }\n}\n\n/**\n * The return type of `createZodvexHooks` — useful for typing module-level\n * exports in generated client files.\n */\nexport type ZodvexHooks = ReturnType<typeof createZodvexHooks>\n","import type { AuthTokenFetcher, ConnectionState } from 'convex/browser'\nimport type { Watch, WatchQueryOptions } from 'convex/react'\nimport { ConvexReactClient } from 'convex/react'\nimport type { FunctionArgs, FunctionReference, FunctionReturnType } from 'convex/server'\nimport type { BoundaryHelpersOptions } from '../../internal/boundaryHelpers'\nimport { createBoundaryHelpers } from '../../internal/boundaryHelpers'\nimport type { AnyRegistry } from '../../internal/types'\n\nexport type ZodvexReactClientOptions = ({ url: string } | { client: ConvexReactClient }) &\n BoundaryHelpersOptions\n\nexport class ZodvexReactClient<R extends AnyRegistry = AnyRegistry> {\n private codec: ReturnType<typeof createBoundaryHelpers>\n private innerClient?: ConvexReactClient\n private options: ZodvexReactClientOptions\n private pendingAuth?: {\n fetchToken: AuthTokenFetcher\n onChange?: (isAuthenticated: boolean) => void\n }\n\n constructor(registry: R, options: ZodvexReactClientOptions) {\n this.codec = createBoundaryHelpers(registry, {\n onDecodeError: options.onDecodeError,\n warnWirePreview: options.warnWirePreview\n })\n this.options = options\n if ('client' in options) {\n this.innerClient = options.client\n }\n }\n\n private getUrl(): string {\n if ('url' in this.options) return this.options.url\n if (this.innerClient) return this.innerClient.url\n throw new Error('[zodvex] ZodvexReactClient is missing a Convex URL.')\n }\n\n private getConvex(): ConvexReactClient {\n if (this.innerClient) return this.innerClient\n\n const client = new ConvexReactClient(this.getUrl())\n if (this.pendingAuth) {\n client.setAuth(this.pendingAuth.fetchToken, this.pendingAuth.onChange)\n }\n this.innerClient = client\n return client\n }\n\n get convex(): ConvexReactClient {\n return this.getConvex()\n }\n\n // ---------------------------------------------------------------------------\n // Data methods — codec-wrapped\n // ---------------------------------------------------------------------------\n\n async query<Q extends FunctionReference<'query', any, any, any>>(\n ref: Q,\n args: Q['_args']\n ): Promise<Q['_returnType']> {\n const wireResult = await this.getConvex().query(\n ref,\n this.codec.encodeArgs(ref, args) as FunctionArgs<Q>\n )\n return this.codec.decodeResult(ref, wireResult)\n }\n\n async mutation<M extends FunctionReference<'mutation', any, any, any>>(\n ref: M,\n args: M['_args']\n ): Promise<M['_returnType']> {\n const wireResult = await this.getConvex().mutation(\n ref,\n this.codec.encodeArgs(ref, args) as FunctionArgs<M>\n )\n return this.codec.decodeResult(ref, wireResult)\n }\n\n async action<A extends FunctionReference<'action', any, any, any>>(\n ref: A,\n args: A['_args']\n ): Promise<A['_returnType']> {\n const wireResult = await this.getConvex().action(\n ref,\n this.codec.encodeArgs(ref, args) as FunctionArgs<A>\n )\n return this.codec.decodeResult(ref, wireResult)\n }\n\n /**\n * Indicates likely future interest in a query subscription. Encodes args to\n * wire before delegating, mirroring {@link watchQuery}.\n */\n prewarmQuery<Q extends FunctionReference<'query', any, any, any>>(queryOptions: {\n query: Q\n args: Q['_args']\n extendSubscriptionFor?: number\n }): void {\n const wireArgs = this.codec.encodeArgs(queryOptions.query, queryOptions.args) as FunctionArgs<Q>\n this.getConvex().prewarmQuery({ ...queryOptions, args: wireArgs })\n }\n\n watchQuery<Q extends FunctionReference<'query', any, any, any>>(\n ref: Q,\n args: Q['_args'],\n options?: WatchQueryOptions\n ): Watch<Q['_returnType']> {\n const wireArgs = this.codec.encodeArgs(ref, args) as FunctionArgs<Q>\n const innerWatch = this.getConvex().watchQuery(ref, wireArgs, options as any)\n\n // Memoize by wire reference identity to avoid redundant Zod parse.\n // Convex creates a new object per server transition via jsonToConvex()\n // in remote_query_set.ts, but returns the same reference for repeated\n // reads within a single transition window.\n // See: convex/src/browser/sync/optimistic_updates_impl.ts\n // TODO(CX-733) — Convex internal tracker for client-side result\n // memoization (not yet public).\n let lastWire: unknown\n let lastDecoded: unknown\n\n return {\n onUpdate: (cb: () => void) => innerWatch.onUpdate(cb),\n localQueryResult: () => {\n const wire = innerWatch.localQueryResult()\n if (wire === lastWire) return lastDecoded\n const decoded = wire === undefined ? undefined : this.codec.decodeResult(ref, wire)\n lastWire = wire\n lastDecoded = decoded\n return lastDecoded\n },\n journal: () => innerWatch.journal()\n }\n }\n\n // ---------------------------------------------------------------------------\n // Pass-through methods — no codec needed\n // ---------------------------------------------------------------------------\n\n setAuth(fetchToken: AuthTokenFetcher, onChange?: (isAuthenticated: boolean) => void): void {\n this.pendingAuth = { fetchToken, onChange }\n if (this.innerClient) {\n this.innerClient.setAuth(fetchToken, onChange)\n }\n }\n\n clearAuth(): void {\n this.pendingAuth = undefined\n this.innerClient?.clearAuth()\n }\n\n async close(): Promise<void> {\n await this.getConvex().close()\n }\n\n get url(): string {\n return this.getUrl()\n }\n\n get logger(): ConvexReactClient['logger'] {\n return this.getConvex().logger\n }\n\n connectionState() {\n return this.getConvex().connectionState()\n }\n\n subscribeToConnectionState(cb: (state: ConnectionState) => void): () => void {\n return this.getConvex().subscribeToConnectionState(cb)\n }\n}\n\nexport function createZodvexReactClient<R extends AnyRegistry>(\n registry: R,\n options: ZodvexReactClientOptions\n): ZodvexReactClient<R> {\n return new ZodvexReactClient(registry, options)\n}\n"]}
|
|
@@ -109,6 +109,7 @@ var ZodvexDecodeError = class extends $ZodError {
|
|
|
109
109
|
var warnedPaths = /* @__PURE__ */ new Set();
|
|
110
110
|
function createBoundaryHelpers(registry, options) {
|
|
111
111
|
const onDecodeError = options?.onDecodeError ?? "warn";
|
|
112
|
+
const warnWirePreview = options?.warnWirePreview === true;
|
|
112
113
|
function encodeArgs(ref, args) {
|
|
113
114
|
if (args == null) return args;
|
|
114
115
|
const path = resolveFunctionPath(ref);
|
|
@@ -135,11 +136,18 @@ function createBoundaryHelpers(registry, options) {
|
|
|
135
136
|
if (onDecodeError === "throw") {
|
|
136
137
|
throw new ZodvexDecodeError(path, result.error.issues, wireResult);
|
|
137
138
|
}
|
|
138
|
-
const
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
139
|
+
const issueList = result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join(", ");
|
|
140
|
+
let message = `[zodvex] Decode failed for ${path}: ${issueList}. Returning raw wire data.`;
|
|
141
|
+
if (warnWirePreview) {
|
|
142
|
+
let preview = "[unavailable]";
|
|
143
|
+
try {
|
|
144
|
+
preview = JSON.stringify(wireResult) ?? "[unavailable]";
|
|
145
|
+
} catch {
|
|
146
|
+
}
|
|
147
|
+
const truncated = preview.length > 200 ? `${preview.slice(0, 200)}...` : preview;
|
|
148
|
+
message += ` Preview: ${truncated}`;
|
|
149
|
+
}
|
|
150
|
+
console.warn(message);
|
|
143
151
|
return wireResult;
|
|
144
152
|
}
|
|
145
153
|
return { encodeArgs, decodeResult };
|
|
@@ -1089,10 +1097,14 @@ function installRulesSubclasses(bases) {
|
|
|
1089
1097
|
return results;
|
|
1090
1098
|
}
|
|
1091
1099
|
async take(n) {
|
|
1100
|
+
if (!Number.isInteger(n) || n < 0) {
|
|
1101
|
+
throw new Error("take requires a non-negative integer");
|
|
1102
|
+
}
|
|
1092
1103
|
const results = [];
|
|
1104
|
+
if (n === 0) return results;
|
|
1093
1105
|
for await (const doc2 of this) {
|
|
1094
|
-
if (results.length >= n) break;
|
|
1095
1106
|
results.push(doc2);
|
|
1107
|
+
if (results.length >= n) break;
|
|
1096
1108
|
}
|
|
1097
1109
|
return results;
|
|
1098
1110
|
}
|
|
@@ -1112,10 +1124,7 @@ function installRulesSubclasses(bases) {
|
|
|
1112
1124
|
return super.count();
|
|
1113
1125
|
}
|
|
1114
1126
|
async *[Symbol.asyncIterator]() {
|
|
1115
|
-
const
|
|
1116
|
-
while (true) {
|
|
1117
|
-
const { value, done } = await iter.next();
|
|
1118
|
-
if (done) break;
|
|
1127
|
+
for await (const value of super[Symbol.asyncIterator]()) {
|
|
1119
1128
|
const result = normalizeReadResult(await this.readRule(this.ctx, value), value);
|
|
1120
1129
|
if (result !== null) yield result;
|
|
1121
1130
|
}
|
|
@@ -1205,7 +1214,10 @@ function installRulesSubclasses(bases) {
|
|
|
1205
1214
|
const tableRules = this.rules[tableName];
|
|
1206
1215
|
if (tableRules?.insert) {
|
|
1207
1216
|
const transformed = await tableRules.insert(this.ctx, value);
|
|
1208
|
-
return this.inner.insert(
|
|
1217
|
+
return this.inner.insert(
|
|
1218
|
+
table,
|
|
1219
|
+
transformed
|
|
1220
|
+
);
|
|
1209
1221
|
}
|
|
1210
1222
|
if ((this.rulesConfig.defaultPolicy ?? "allow") === "deny") {
|
|
1211
1223
|
throw new Error(`insert not allowed on ${tableName}`);
|
|
@@ -1230,7 +1242,10 @@ function installRulesSubclasses(bases) {
|
|
|
1230
1242
|
const tableRules = tableName ? this.rules[tableName] : void 0;
|
|
1231
1243
|
if (tableRules?.patch) {
|
|
1232
1244
|
const transformed = await tableRules.patch(this.ctx, doc2, value);
|
|
1233
|
-
return this.inner.patch(
|
|
1245
|
+
return this.inner.patch(
|
|
1246
|
+
id2,
|
|
1247
|
+
transformed
|
|
1248
|
+
);
|
|
1234
1249
|
}
|
|
1235
1250
|
if ((this.rulesConfig.defaultPolicy ?? "allow") === "deny") {
|
|
1236
1251
|
throw new Error(`patch not allowed on ${tableName}`);
|
|
@@ -1343,10 +1358,7 @@ function installRulesSubclasses(bases) {
|
|
|
1343
1358
|
return result;
|
|
1344
1359
|
}
|
|
1345
1360
|
async *[Symbol.asyncIterator]() {
|
|
1346
|
-
const
|
|
1347
|
-
while (true) {
|
|
1348
|
-
const { value, done } = await iter.next();
|
|
1349
|
-
if (done) break;
|
|
1361
|
+
for await (const value of super[Symbol.asyncIterator]()) {
|
|
1350
1362
|
await this.afterRead(this.tableName, value);
|
|
1351
1363
|
yield value;
|
|
1352
1364
|
}
|
|
@@ -1557,8 +1569,11 @@ function wrapIndexRangeBuilder(inner, schema) {
|
|
|
1557
1569
|
}
|
|
1558
1570
|
});
|
|
1559
1571
|
}
|
|
1560
|
-
function
|
|
1561
|
-
|
|
1572
|
+
function isFilterExpression(value, expressionPrototype) {
|
|
1573
|
+
return value != null && Object.prototype.isPrototypeOf.call(expressionPrototype, value);
|
|
1574
|
+
}
|
|
1575
|
+
function extractFieldPath(expr, expressionPrototype) {
|
|
1576
|
+
if (isFilterExpression(expr, expressionPrototype)) {
|
|
1562
1577
|
const inner = expr.serialize();
|
|
1563
1578
|
if (inner && typeof inner === "object" && "$field" in inner) {
|
|
1564
1579
|
return inner.$field;
|
|
@@ -1567,15 +1582,16 @@ function extractFieldPath(expr) {
|
|
|
1567
1582
|
return null;
|
|
1568
1583
|
}
|
|
1569
1584
|
function wrapFilterBuilder(inner, schema) {
|
|
1585
|
+
const expressionPrototype = Object.getPrototypeOf(inner.field("_id"));
|
|
1570
1586
|
return new Proxy(inner, {
|
|
1571
1587
|
get(target, prop, receiver) {
|
|
1572
1588
|
if (typeof prop === "string" && ["eq", "neq", "lt", "lte", "gt", "gte"].includes(prop)) {
|
|
1573
1589
|
return (l, r) => {
|
|
1574
|
-
const lField = extractFieldPath(l);
|
|
1575
|
-
const rField = extractFieldPath(r);
|
|
1576
|
-
if (lField && !
|
|
1590
|
+
const lField = extractFieldPath(l, expressionPrototype);
|
|
1591
|
+
const rField = extractFieldPath(r, expressionPrototype);
|
|
1592
|
+
if (lField && !isFilterExpression(r, expressionPrototype)) {
|
|
1577
1593
|
r = encodeIndexValue(schema, lField, r);
|
|
1578
|
-
} else if (rField && !
|
|
1594
|
+
} else if (rField && !isFilterExpression(l, expressionPrototype)) {
|
|
1579
1595
|
l = encodeIndexValue(schema, rField, l);
|
|
1580
1596
|
}
|
|
1581
1597
|
return target[prop](l, r);
|
|
@@ -1674,6 +1690,17 @@ var ZodvexDatabaseReader = class {
|
|
|
1674
1690
|
get _internals() {
|
|
1675
1691
|
return { db: this.db, tableMap: this.tableMap };
|
|
1676
1692
|
}
|
|
1693
|
+
/**
|
|
1694
|
+
* Escape hatch (#85/#92): returns the database this codec wrapper delegates
|
|
1695
|
+
* to — the composed underlying stack when `underlyingDb` is configured (e.g.
|
|
1696
|
+
* a trigger-wrapped writer), the bare Convex db otherwise.
|
|
1697
|
+
*
|
|
1698
|
+
* The returned db is native-shape: reads are undecoded wire documents and it
|
|
1699
|
+
* bypasses codec, `.withRules()`, and `.audit()` layers entirely.
|
|
1700
|
+
*/
|
|
1701
|
+
unwrap() {
|
|
1702
|
+
return this.db;
|
|
1703
|
+
}
|
|
1677
1704
|
normalizeId(tableName, id2) {
|
|
1678
1705
|
return this.db.normalizeId(tableName, id2);
|
|
1679
1706
|
}
|
|
@@ -1733,6 +1760,17 @@ var ZodvexDatabaseWriter = class extends ZodvexDatabaseReader {
|
|
|
1733
1760
|
get _internals() {
|
|
1734
1761
|
return { db: this.writerDb, tableMap: this.tableMap, reader: this };
|
|
1735
1762
|
}
|
|
1763
|
+
/**
|
|
1764
|
+
* Escape hatch (#85/#92): returns the writer this codec wrapper delegates
|
|
1765
|
+
* to — the composed underlying stack when `underlyingDb` is configured (e.g.
|
|
1766
|
+
* a trigger-wrapped writer), the bare Convex db otherwise.
|
|
1767
|
+
*
|
|
1768
|
+
* The returned db is native-shape: writes must be wire-format and it
|
|
1769
|
+
* bypasses codec, `.withRules()`, and `.audit()` layers entirely.
|
|
1770
|
+
*/
|
|
1771
|
+
unwrap() {
|
|
1772
|
+
return this.writerDb;
|
|
1773
|
+
}
|
|
1736
1774
|
async insert(table, value) {
|
|
1737
1775
|
const schemas = this.tableMap[table];
|
|
1738
1776
|
const wireValue = schemas ? encodeDoc(schemas.insert, value) : value;
|
|
@@ -1817,19 +1855,25 @@ installRulesSubclasses({
|
|
|
1817
1855
|
});
|
|
1818
1856
|
|
|
1819
1857
|
// src/internal/customization.ts
|
|
1820
|
-
function createZodvexCustomization(tableMap) {
|
|
1858
|
+
function createZodvexCustomization(tableMap, options) {
|
|
1859
|
+
const resolveReaderDb = options?.underlyingDb?.query;
|
|
1860
|
+
const resolveWriterDb = options?.underlyingDb?.mutation;
|
|
1821
1861
|
return {
|
|
1822
1862
|
query: {
|
|
1823
1863
|
args: {},
|
|
1824
1864
|
input: async (ctx, _args, _extra) => ({
|
|
1825
|
-
ctx: {
|
|
1865
|
+
ctx: {
|
|
1866
|
+
db: new ZodvexDatabaseReader(resolveReaderDb ? resolveReaderDb(ctx) : ctx.db, tableMap)
|
|
1867
|
+
},
|
|
1826
1868
|
args: {}
|
|
1827
1869
|
})
|
|
1828
1870
|
},
|
|
1829
1871
|
mutation: {
|
|
1830
1872
|
args: {},
|
|
1831
1873
|
input: async (ctx, _args, _extra) => ({
|
|
1832
|
-
ctx: {
|
|
1874
|
+
ctx: {
|
|
1875
|
+
db: new ZodvexDatabaseWriter(resolveWriterDb ? resolveWriterDb(ctx) : ctx.db, tableMap)
|
|
1876
|
+
},
|
|
1833
1877
|
args: {}
|
|
1834
1878
|
})
|
|
1835
1879
|
}
|
|
@@ -1839,9 +1883,16 @@ function defineContext(_builder, customization) {
|
|
|
1839
1883
|
return customization;
|
|
1840
1884
|
}
|
|
1841
1885
|
function initZodvex(schema, server, options) {
|
|
1842
|
-
const codec2 = createZodvexCustomization(schema.__zodTableMap);
|
|
1843
|
-
const noOp = createNoOpCustomization();
|
|
1844
1886
|
const wrap = options?.wrapDb !== false;
|
|
1887
|
+
if (!wrap && options?.underlyingDb) {
|
|
1888
|
+
throw new Error(
|
|
1889
|
+
"[zodvex] initZodvex: `underlyingDb` requires the codec db wrapper \u2014 remove `wrapDb: false` or drop `underlyingDb`."
|
|
1890
|
+
);
|
|
1891
|
+
}
|
|
1892
|
+
const codec2 = createZodvexCustomization(schema.__zodTableMap, {
|
|
1893
|
+
underlyingDb: options?.underlyingDb
|
|
1894
|
+
});
|
|
1895
|
+
const noOp = createNoOpCustomization();
|
|
1845
1896
|
const registryThunk = options?.registry;
|
|
1846
1897
|
const actionCust = createActionCustomization(registryThunk, noOp);
|
|
1847
1898
|
const customizations = {
|