iway1 / trpc-panel

MIT License
627 stars 43 forks source link

Form validation error caused by JSON-schema $refs #71

Closed joanrieu closed 1 year ago

joanrieu commented 1 year ago

Hello, thanks for this library, it's great!

I recently encountered a bug related to form validation when trying to submit a mutation. The bug makes it fail (the request never gets sent to the server). It looks like the generated JSON Schema $refs are improperly resolved.

It occurs when the zod-to-json-schema library used behind the scenes decides to emit a $ref to a previous property's type while declaring one that shares the same type. It does that to prevent duplication, but somehow $ref paths are seen as invalid during trpc-panel's validation before sending a request.

An example of this can be seen in bug report #43.

A workaround is to make the zod-to-json-schema library avoid emitting $refs.


For others potentially facing the issue, I worked around it by using the following patch through pnpm's patch system:

  "pnpm": {
    "patchedDependencies": {
      "trpc-panel@1.3.2": "patches/trpc-panel@1.3.2.patch"
    }
  }
diff --git a/lib/index.js b/lib/index.js
index 5f24deafca75d201da095effc2fcdbfd38cb88a1..44a05d5a17c1f0759b195e381eb05de64809d482 100644
--- a/lib/index.js
+++ b/lib/index.js
@@ -250,7 +250,7 @@ function nodeAndInputSchemaFromInputs(inputs, _routerPath, options, addDataFunct
     const input = inputs[0];
     return {
         parseInputResult: "success",
-        schema: zodToJsonSchema.zodToJsonSchema(input, { errorMessages: true }),
+        schema: zodToJsonSchema.zodToJsonSchema(input, { errorMessages: true, $refStrategy: "none" }),
         node: zodSelectorFunction(input._def, {
             path: [],
             options,
diff --git a/lib/index.mjs b/lib/index.mjs
index 3750a8234aa6b0f0313c1f5601da7763e2a7a03d..9202bd36fcd4f700659072460d9286557f1ee6e0 100644
--- a/lib/index.mjs
+++ b/lib/index.mjs
@@ -248,7 +248,7 @@ function nodeAndInputSchemaFromInputs(inputs, _routerPath, options, addDataFunct
     const input = inputs[0];
     return {
         parseInputResult: "success",
-        schema: zodToJsonSchema(input, { errorMessages: true }),
+        schema: zodToJsonSchema(input, { errorMessages: true, $refStrategy: "none" }),
         node: zodSelectorFunction(input._def, {
             path: [],
             options,
iway1 commented 1 year ago

Thanks for the detailed report and fix 😊, I'll create a release with the fix shortly

ferm10n commented 7 months ago

If you have a recursive schema, this change causes warnings Recursive reference detected at #<path>! Defaulting to any to appear.

My schema doesn't cause the problems mentioned in #43, so I made a PR to override the $refStrategy workaround https://github.com/iway1/trpc-panel/pull/98