@schemashift/zod-v3-v4 0.9.0 → 0.11.0

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/index.js CHANGED
@@ -1,3 +1,165 @@
1
+ // src/behavior-test-generator.ts
2
+ var V4_BEHAVIORAL_PATTERNS = [
3
+ {
4
+ name: "default-optional",
5
+ description: ".default() + .optional() behaves differently in v4",
6
+ regex: /\.default\([^)]*\)[\s\S]{0,20}\.optional\(\)|\.optional\(\)[\s\S]{0,20}\.default\([^)]*\)/,
7
+ testTemplate: [
8
+ " it('verifies .default() + .optional() behavior (v4 change)', () => {",
9
+ " // v3: undefined input returns undefined (.optional() wins)",
10
+ " // v4: undefined input returns default value (.default() always applies)",
11
+ " const schema = z.string().default('fallback').optional();",
12
+ " const result = schema.parse(undefined);",
13
+ " expect(result).toBe('fallback');",
14
+ " });"
15
+ ].join("\n")
16
+ },
17
+ {
18
+ name: "error-instanceof",
19
+ description: "ZodError no longer extends Error in v4",
20
+ regex: /instanceof\s+Error|instanceof\s+ZodError/,
21
+ testTemplate: [
22
+ " it('verifies ZodError instanceof check (v4 change)', () => {",
23
+ " // v3: ZodError extends Error",
24
+ " // v4: ZodError does NOT extend Error",
25
+ " try {",
26
+ " z.string().parse(123);",
27
+ " } catch (e) {",
28
+ " expect(e).toBeDefined();",
29
+ " }",
30
+ " });"
31
+ ].join("\n")
32
+ },
33
+ {
34
+ name: "transform-after-refine",
35
+ description: ".transform() after .refine() may change execution order in v4",
36
+ regex: /\.refine\([^)]*\)[\s\S]{0,30}\.transform\(/,
37
+ testTemplate: [
38
+ " it('verifies .refine() then .transform() ordering (v4 change)', () => {",
39
+ " const schema = z.string()",
40
+ " .refine((val) => val.length > 0, 'Must not be empty')",
41
+ " .transform((val) => val.toUpperCase());",
42
+ " const result = schema.safeParse('hello');",
43
+ " expect(result.success).toBe(true);",
44
+ " if (result.success) {",
45
+ " expect(result.data).toBe('HELLO');",
46
+ " }",
47
+ " });"
48
+ ].join("\n")
49
+ },
50
+ {
51
+ name: "catch-optional",
52
+ description: ".catch() + .optional() interaction changed in v4",
53
+ regex: /\.catch\([^)]*\)[\s\S]{0,20}\.optional\(\)|\.optional\(\)[\s\S]{0,20}\.catch\([^)]*\)/,
54
+ testTemplate: [
55
+ " it('verifies .catch() + .optional() behavior (v4 change)', () => {",
56
+ " const schema = z.string().catch('default').optional();",
57
+ " const result = schema.parse(undefined);",
58
+ " expect(result).toBeDefined();",
59
+ " });"
60
+ ].join("\n")
61
+ },
62
+ {
63
+ name: "error-message-format",
64
+ description: 'Error messages changed from "Required" to descriptive messages',
65
+ regex: /['"]Required['"]/,
66
+ testTemplate: [
67
+ " it('verifies error message format (v4 change)', () => {",
68
+ ' // v3: "Required" for missing fields',
69
+ ' // v4: "Invalid input: expected string, received undefined"',
70
+ " const schema = z.object({ name: z.string() });",
71
+ " const result = schema.safeParse({});",
72
+ " expect(result.success).toBe(false);",
73
+ " if (!result.success) {",
74
+ " const msg = result.error.issues[0]?.message ?? '';",
75
+ " expect(msg.length).toBeGreaterThan(0);",
76
+ " }",
77
+ " });"
78
+ ].join("\n")
79
+ },
80
+ {
81
+ name: "error-flatten",
82
+ description: "error.flatten() moved to z.flattenError(error) in v4",
83
+ regex: /\.flatten\(\)/,
84
+ testTemplate: [
85
+ " it('verifies error flattening (v4 change)', () => {",
86
+ " // v3: error.flatten()",
87
+ " // v4: z.flattenError(error)",
88
+ " const schema = z.object({ name: z.string() });",
89
+ " const result = schema.safeParse({});",
90
+ " if (!result.success) {",
91
+ " expect(result.error).toBeDefined();",
92
+ " }",
93
+ " });"
94
+ ].join("\n")
95
+ }
96
+ ];
97
+ function detectBehavioralPatterns(sourceCode, filePath) {
98
+ const results = [];
99
+ const lines = sourceCode.split("\n");
100
+ for (const pattern of V4_BEHAVIORAL_PATTERNS) {
101
+ for (let i = 0; i < lines.length; i++) {
102
+ const line = lines[i] ?? "";
103
+ if (pattern.regex.test(line)) {
104
+ results.push({
105
+ pattern,
106
+ filePath,
107
+ lineNumber: i + 1,
108
+ matchedText: line.trim()
109
+ });
110
+ }
111
+ }
112
+ if (pattern.regex.test(sourceCode) && !results.some((r) => r.pattern.name === pattern.name && r.filePath === filePath)) {
113
+ const match = pattern.regex.exec(sourceCode);
114
+ if (match) {
115
+ const lineNumber = sourceCode.slice(0, match.index).split("\n").length;
116
+ results.push({
117
+ pattern,
118
+ filePath,
119
+ lineNumber,
120
+ matchedText: match[0].trim().slice(0, 80)
121
+ });
122
+ }
123
+ }
124
+ }
125
+ return results;
126
+ }
127
+ function generateBehaviorTests(files) {
128
+ const allPatterns = [];
129
+ const testsByFile = /* @__PURE__ */ new Map();
130
+ for (const { filePath, sourceCode } of files) {
131
+ const detected = detectBehavioralPatterns(sourceCode, filePath);
132
+ allPatterns.push(...detected);
133
+ for (const d of detected) {
134
+ const existing = testsByFile.get(filePath) ?? /* @__PURE__ */ new Set();
135
+ existing.add(d.pattern.name);
136
+ testsByFile.set(filePath, existing);
137
+ }
138
+ }
139
+ const tests = [];
140
+ for (const [filePath, patternNames] of testsByFile) {
141
+ const patterns = [...patternNames];
142
+ const testBlocks = patterns.map((name) => V4_BEHAVIORAL_PATTERNS.find((p) => p.name === name)?.testTemplate ?? "").filter(Boolean);
143
+ if (testBlocks.length === 0) continue;
144
+ const shortPath = filePath.split("/").slice(-2).join("/");
145
+ const testCode = [
146
+ "import { describe, expect, it } from 'vitest';",
147
+ "import { z } from 'zod';",
148
+ "",
149
+ "/**",
150
+ " * Behavioral regression tests for Zod v3 to v4 migration",
151
+ ` * Source: ${shortPath}`,
152
+ " * Generated by SchemaShift",
153
+ " */",
154
+ `describe('v4 behavioral changes: ${shortPath}', () => {`,
155
+ ...testBlocks.map((b) => b),
156
+ "});"
157
+ ].join("\n");
158
+ tests.push({ filePath, testCode, patterns });
159
+ }
160
+ return { tests, totalPatterns: allPatterns.length };
161
+ }
162
+
1
163
  // src/transformer.ts
2
164
  import { Node } from "ts-morph";
3
165
 
@@ -12,19 +174,23 @@ var V3_TO_V4_PATTERNS = {
12
174
  };
13
175
  var BEHAVIOR_CHANGES = /* @__PURE__ */ new Set([
14
176
  "default",
15
- // Type inference changed
177
+ // Type inference changed; now matches output type, use .prefault() for v3 behavior
16
178
  "uuid",
17
- // Stricter validation
179
+ // Stricter RFC 9562/4122 validation; use z.guid() for lenient matching
18
180
  "record",
19
181
  // Requires key type
20
182
  "discriminatedUnion",
21
183
  // Stricter discriminator requirements
22
184
  "function",
23
- // Input/output parameter changes
185
+ // Complete overhaul — .args()/.returns() removed
24
186
  "pipe",
25
187
  // Stricter type checking in v4
26
- "catch"
188
+ "catch",
27
189
  // .catch() on optional properties always returns catch value in v4
190
+ "nonempty",
191
+ // Type inference changed: string[] instead of [string, ...string[]]
192
+ "coerce"
193
+ // Input type changed to unknown for all z.coerce.* schemas
28
194
  ]);
29
195
  var DEPRECATED_METHODS = /* @__PURE__ */ new Set([
30
196
  "merge",
@@ -33,8 +199,26 @@ var DEPRECATED_METHODS = /* @__PURE__ */ new Set([
33
199
  // Use .check() instead
34
200
  "strict",
35
201
  // Use z.strictObject() instead
36
- "passthrough"
202
+ "passthrough",
37
203
  // Use z.looseObject() instead
204
+ "deepPartial",
205
+ // Removed entirely — was deprecated anti-pattern
206
+ "strip",
207
+ // Deprecated — default behavior in v4
208
+ "nonstrict"
209
+ // Removed entirely
210
+ ]);
211
+ var DEPRECATED_FACTORIES = /* @__PURE__ */ new Set([
212
+ "promise",
213
+ // z.promise() deprecated — await values before parsing
214
+ "ostring",
215
+ // z.ostring() removed (optional shorthand)
216
+ "onumber",
217
+ // z.onumber() removed
218
+ "oboolean",
219
+ // z.oboolean() removed
220
+ "preprocess"
221
+ // z.preprocess() removed — use z.pipe() instead
38
222
  ]);
39
223
  var AUTO_TRANSFORMABLE = /* @__PURE__ */ new Set([
40
224
  "superRefine",
@@ -51,6 +235,22 @@ var UTILITY_TYPES = /* @__PURE__ */ new Set([
51
235
  "ZodTypeAny",
52
236
  "ZodFirstPartyTypeKind"
53
237
  ]);
238
+ var STRING_FORMAT_TO_TOPLEVEL = /* @__PURE__ */ new Map([
239
+ ["email", "z.email()"],
240
+ ["url", "z.url()"],
241
+ ["uuid", "z.uuid()"],
242
+ ["emoji", "z.emoji()"],
243
+ ["nanoid", "z.nanoid()"],
244
+ ["cuid", "z.cuid()"],
245
+ ["cuid2", "z.cuid2()"],
246
+ ["ulid", "z.ulid()"],
247
+ ["ipv4", "z.ipv4()"],
248
+ ["ipv6", "z.ipv6()"],
249
+ ["cidrv4", "z.cidrv4()"],
250
+ ["cidrv6", "z.cidrv6()"],
251
+ ["base64", "z.base64()"],
252
+ ["base64url", "z.base64url()"]
253
+ ]);
54
254
 
55
255
  // src/transformer.ts
56
256
  var ZodV3ToV4Transformer = class {
@@ -71,13 +271,23 @@ var ZodV3ToV4Transformer = class {
71
271
  this.transformFlatten(sourceFile);
72
272
  this.transformFormat(sourceFile);
73
273
  this.transformDefAccess(sourceFile);
274
+ this.transformFunctionValidation(sourceFile);
275
+ this.transformOptionalShorthands(sourceFile);
74
276
  this.checkDeprecatedMethods(sourceFile);
277
+ this.checkDeprecatedFactories(sourceFile);
278
+ this.checkStringFormatMethods(sourceFile);
75
279
  this.checkBehaviorChanges(sourceFile);
76
280
  this.checkInstanceofError(sourceFile);
77
281
  this.checkTransformRefineOrder(sourceFile);
78
282
  this.checkDefaultOptional(sourceFile);
79
283
  this.checkCatchOptional(sourceFile);
80
284
  this.checkUtilityTypeImports(sourceFile);
285
+ this.checkNonemptyTypeChange(sourceFile);
286
+ this.checkCoerceInputType(sourceFile);
287
+ this.checkDeepPartialRemoval(sourceFile);
288
+ this.checkStripDeprecation(sourceFile);
289
+ this.checkErrorMapPrecedence(sourceFile);
290
+ this.checkAddIssueMethods(sourceFile);
81
291
  return {
82
292
  success: this.errors.length === 0,
83
293
  filePath,
@@ -605,6 +815,238 @@ var ZodV3ToV4Transformer = class {
605
815
  }
606
816
  }
607
817
  }
818
+ /**
819
+ * Warn about string format methods that moved to top-level functions in v4.
820
+ * e.g., z.string().email() → z.email() (instance methods are deprecated but still work)
821
+ */
822
+ checkStringFormatMethods(sourceFile) {
823
+ const filePath = sourceFile.getFilePath();
824
+ sourceFile.forEachDescendant((node) => {
825
+ if (Node.isCallExpression(node)) {
826
+ const expression = node.getExpression();
827
+ if (Node.isPropertyAccessExpression(expression)) {
828
+ const name = expression.getName();
829
+ if (STRING_FORMAT_TO_TOPLEVEL.has(name)) {
830
+ const chainText = node.getText();
831
+ if (chainText.includes("z.string()") || chainText.includes(".string()")) {
832
+ const topLevel = STRING_FORMAT_TO_TOPLEVEL.get(name);
833
+ const lineNumber = node.getStartLineNumber();
834
+ this.warnings.push(
835
+ `${filePath}:${lineNumber}: .${name}() is deprecated as an instance method in v4. Use ${topLevel} as a top-level function instead. The instance method still works but may be removed in future versions.`
836
+ );
837
+ }
838
+ }
839
+ }
840
+ }
841
+ });
842
+ }
843
+ /**
844
+ * Check for deprecated factory functions (z.promise(), z.ostring(), etc.)
845
+ */
846
+ checkDeprecatedFactories(sourceFile) {
847
+ const filePath = sourceFile.getFilePath();
848
+ sourceFile.forEachDescendant((node) => {
849
+ if (Node.isCallExpression(node)) {
850
+ const expression = node.getExpression();
851
+ if (Node.isPropertyAccessExpression(expression)) {
852
+ const name = expression.getName();
853
+ const object = expression.getExpression();
854
+ if (object.getText() === "z" && DEPRECATED_FACTORIES.has(name)) {
855
+ const lineNumber = node.getStartLineNumber();
856
+ switch (name) {
857
+ case "promise":
858
+ this.warnings.push(
859
+ `${filePath}:${lineNumber}: z.promise() is deprecated in v4. Await values before parsing instead of wrapping in z.promise().`
860
+ );
861
+ break;
862
+ case "ostring":
863
+ this.warnings.push(
864
+ `${filePath}:${lineNumber}: z.ostring() is removed in v4. Use z.string().optional() instead.`
865
+ );
866
+ break;
867
+ case "onumber":
868
+ this.warnings.push(
869
+ `${filePath}:${lineNumber}: z.onumber() is removed in v4. Use z.number().optional() instead.`
870
+ );
871
+ break;
872
+ case "oboolean":
873
+ this.warnings.push(
874
+ `${filePath}:${lineNumber}: z.oboolean() is removed in v4. Use z.boolean().optional() instead.`
875
+ );
876
+ break;
877
+ case "preprocess":
878
+ this.warnings.push(
879
+ `${filePath}:${lineNumber}: z.preprocess() is removed in v4. Use z.pipe(z.unknown(), z.transform(fn), targetSchema) instead.`
880
+ );
881
+ break;
882
+ }
883
+ }
884
+ }
885
+ }
886
+ });
887
+ }
888
+ /**
889
+ * Transform z.function().args().returns() to z.function({ input, output }) in v4.
890
+ */
891
+ transformFunctionValidation(sourceFile) {
892
+ const filePath = sourceFile.getFilePath();
893
+ sourceFile.forEachDescendant((node) => {
894
+ if (Node.isCallExpression(node)) {
895
+ const expression = node.getExpression();
896
+ if (Node.isPropertyAccessExpression(expression)) {
897
+ const name = expression.getName();
898
+ if (name === "args" || name === "returns") {
899
+ const chainText = node.getText();
900
+ if (chainText.includes("z.function()") && (chainText.includes(".args(") || chainText.includes(".returns("))) {
901
+ const lineNumber = node.getStartLineNumber();
902
+ this.warnings.push(
903
+ `${filePath}:${lineNumber}: z.function().args().returns() is removed in v4. Use z.function({ input: z.tuple([...]), output: schema }) instead. The result is no longer a Zod schema \u2014 use .implement() to wrap functions.`
904
+ );
905
+ }
906
+ }
907
+ }
908
+ }
909
+ });
910
+ }
911
+ /**
912
+ * Transform z.ostring(), z.onumber(), z.oboolean() to explicit .optional() calls.
913
+ */
914
+ transformOptionalShorthands(sourceFile) {
915
+ const filePath = sourceFile.getFilePath();
916
+ const fullText = sourceFile.getFullText();
917
+ const replacements = [
918
+ { pattern: /\bz\.ostring\(\)/g, replacement: "z.string().optional()", name: "z.ostring()" },
919
+ { pattern: /\bz\.onumber\(\)/g, replacement: "z.number().optional()", name: "z.onumber()" },
920
+ {
921
+ pattern: /\bz\.oboolean\(\)/g,
922
+ replacement: "z.boolean().optional()",
923
+ name: "z.oboolean()"
924
+ }
925
+ ];
926
+ let newText = fullText;
927
+ for (const { pattern, replacement, name } of replacements) {
928
+ if (pattern.test(newText)) {
929
+ newText = newText.replace(pattern, replacement);
930
+ this.warnings.push(
931
+ `${filePath}: ${name} auto-transformed to ${replacement}. Removed in v4.`
932
+ );
933
+ }
934
+ }
935
+ if (newText !== fullText) {
936
+ sourceFile.replaceWithText(newText);
937
+ }
938
+ }
939
+ /**
940
+ * Check for .nonempty() which has a type inference change in v4.
941
+ * v3: [string, ...string[]] (tuple with rest)
942
+ * v4: string[] (matches .min(1))
943
+ */
944
+ checkNonemptyTypeChange(sourceFile) {
945
+ const filePath = sourceFile.getFilePath();
946
+ sourceFile.forEachDescendant((node) => {
947
+ if (Node.isCallExpression(node)) {
948
+ const expression = node.getExpression();
949
+ if (Node.isPropertyAccessExpression(expression) && expression.getName() === "nonempty") {
950
+ const lineNumber = node.getStartLineNumber();
951
+ this.warnings.push(
952
+ `${filePath}:${lineNumber}: .nonempty() type inference changed in v4. v3 inferred [T, ...T[]] (tuple with rest), v4 infers T[] (same as .min(1)). If you rely on the tuple type, use z.tuple([z.string()], z.string()) instead.`
953
+ );
954
+ }
955
+ }
956
+ });
957
+ }
958
+ /**
959
+ * Check for z.coerce.* usage — input type changed to unknown in v4.
960
+ */
961
+ checkCoerceInputType(sourceFile) {
962
+ const filePath = sourceFile.getFilePath();
963
+ const fullText = sourceFile.getFullText();
964
+ if (fullText.includes("z.coerce.")) {
965
+ sourceFile.forEachDescendant((node) => {
966
+ if (Node.isPropertyAccessExpression(node)) {
967
+ const text = node.getText();
968
+ if (text.startsWith("z.coerce.")) {
969
+ const lineNumber = node.getStartLineNumber();
970
+ this.warnings.push(
971
+ `${filePath}:${lineNumber}: z.coerce.* input type changed to 'unknown' in v4. Previously, z.coerce.string() had input type string. This enables more accurate type inference but may affect type guards.`
972
+ );
973
+ }
974
+ }
975
+ });
976
+ }
977
+ }
978
+ /**
979
+ * Check for .deepPartial() which was removed entirely in v4.
980
+ */
981
+ checkDeepPartialRemoval(sourceFile) {
982
+ const filePath = sourceFile.getFilePath();
983
+ sourceFile.forEachDescendant((node) => {
984
+ if (Node.isCallExpression(node)) {
985
+ const expression = node.getExpression();
986
+ if (Node.isPropertyAccessExpression(expression) && expression.getName() === "deepPartial") {
987
+ const lineNumber = node.getStartLineNumber();
988
+ this.warnings.push(
989
+ `${filePath}:${lineNumber}: .deepPartial() is removed in v4. This was a long-deprecated anti-pattern. Use recursive partial types or restructure schemas to avoid deep partial requirements.`
990
+ );
991
+ }
992
+ }
993
+ });
994
+ }
995
+ /**
996
+ * Check for .strip() which is deprecated in v4 (it was the default behavior).
997
+ */
998
+ checkStripDeprecation(sourceFile) {
999
+ const filePath = sourceFile.getFilePath();
1000
+ sourceFile.forEachDescendant((node) => {
1001
+ if (Node.isCallExpression(node)) {
1002
+ const expression = node.getExpression();
1003
+ if (Node.isPropertyAccessExpression(expression) && expression.getName() === "strip") {
1004
+ const lineNumber = node.getStartLineNumber();
1005
+ this.warnings.push(
1006
+ `${filePath}:${lineNumber}: .strip() is deprecated in v4 (it was the default behavior). Remove .strip() \u2014 z.object() strips unknown keys by default. To convert a strict object back to stripping, use z.object(schema.shape).`
1007
+ );
1008
+ }
1009
+ }
1010
+ });
1011
+ }
1012
+ /**
1013
+ * Check for errorMap usage patterns where precedence changed in v4.
1014
+ * In v4, schema-level error maps take precedence over parse-time error maps (inverted from v3).
1015
+ */
1016
+ checkErrorMapPrecedence(sourceFile) {
1017
+ const filePath = sourceFile.getFilePath();
1018
+ const fullText = sourceFile.getFullText();
1019
+ const hasSchemaErrorMap = fullText.includes("errorMap:") || fullText.includes("error:");
1020
+ const hasParseErrorMap = fullText.includes(".parse(") && fullText.includes("errorMap") || fullText.includes(".safeParse(") && fullText.includes("errorMap");
1021
+ if (hasSchemaErrorMap && hasParseErrorMap) {
1022
+ this.warnings.push(
1023
+ `${filePath}: Error map precedence changed in v4. Schema-level error maps now take precedence over parse-time error maps (inverted from v3). Review error map usage to ensure correct error messages.`
1024
+ );
1025
+ }
1026
+ }
1027
+ /**
1028
+ * Check for ctx.addIssue() / ctx.addIssues() which are deprecated in v4.
1029
+ */
1030
+ checkAddIssueMethods(sourceFile) {
1031
+ const filePath = sourceFile.getFilePath();
1032
+ const fullText = sourceFile.getFullText();
1033
+ if (fullText.includes(".addIssue(") || fullText.includes(".addIssues(")) {
1034
+ sourceFile.forEachDescendant((node) => {
1035
+ if (Node.isCallExpression(node)) {
1036
+ const expression = node.getExpression();
1037
+ if (Node.isPropertyAccessExpression(expression)) {
1038
+ const name = expression.getName();
1039
+ if (name === "addIssue" || name === "addIssues") {
1040
+ const lineNumber = node.getStartLineNumber();
1041
+ this.warnings.push(
1042
+ `${filePath}:${lineNumber}: .${name}() is deprecated in v4. Directly manipulate the issues array instead: ctx.issues.push({...}). Note: .superRefine() callbacks using addIssue should migrate to .check() with issues.push().`
1043
+ );
1044
+ }
1045
+ }
1046
+ }
1047
+ });
1048
+ }
1049
+ }
608
1050
  };
609
1051
 
610
1052
  // src/handler.ts
@@ -620,6 +1062,8 @@ export {
620
1062
  BEHAVIOR_CHANGES,
621
1063
  V3_TO_V4_PATTERNS,
622
1064
  ZodV3ToV4Transformer,
623
- createZodV3ToV4Handler
1065
+ createZodV3ToV4Handler,
1066
+ detectBehavioralPatterns,
1067
+ generateBehaviorTests
624
1068
  };
625
1069
  //# sourceMappingURL=index.js.map