effect-zod.test.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  1. import { describe, expect, test } from "bun:test"
  2. import { Effect, Schema, SchemaGetter } from "effect"
  3. import z from "zod"
  4. import { zod, ZodOverride } from "../../src/util/effect-zod"
  5. function json(schema: z.ZodTypeAny) {
  6. const { $schema: _, ...rest } = z.toJSONSchema(schema)
  7. return rest
  8. }
  9. describe("util.effect-zod", () => {
  10. test("converts class schemas for route dto shapes", () => {
  11. class Method extends Schema.Class<Method>("ProviderAuthMethod")({
  12. type: Schema.Union([Schema.Literal("oauth"), Schema.Literal("api")]),
  13. label: Schema.String,
  14. }) {}
  15. const out = zod(Method)
  16. expect(out.meta()?.ref).toBe("ProviderAuthMethod")
  17. expect(
  18. out.parse({
  19. type: "oauth",
  20. label: "OAuth",
  21. }),
  22. ).toEqual({
  23. type: "oauth",
  24. label: "OAuth",
  25. })
  26. })
  27. test("converts structs with optional fields, arrays, and records", () => {
  28. const out = zod(
  29. Schema.Struct({
  30. foo: Schema.optional(Schema.String),
  31. bar: Schema.Array(Schema.Number),
  32. baz: Schema.Record(Schema.String, Schema.Boolean),
  33. }),
  34. )
  35. expect(
  36. out.parse({
  37. bar: [1, 2],
  38. baz: { ok: true },
  39. }),
  40. ).toEqual({
  41. bar: [1, 2],
  42. baz: { ok: true },
  43. })
  44. expect(
  45. out.parse({
  46. foo: "hi",
  47. bar: [1],
  48. baz: { ok: false },
  49. }),
  50. ).toEqual({
  51. foo: "hi",
  52. bar: [1],
  53. baz: { ok: false },
  54. })
  55. })
  56. describe("Tuples", () => {
  57. test("fixed-length tuple parses matching array", () => {
  58. const out = zod(Schema.Tuple([Schema.String, Schema.Number]))
  59. expect(out.parse(["a", 1])).toEqual(["a", 1])
  60. expect(out.safeParse(["a"]).success).toBe(false)
  61. expect(out.safeParse(["a", "b"]).success).toBe(false)
  62. })
  63. test("single-element tuple parses a one-element array", () => {
  64. const out = zod(Schema.Tuple([Schema.Boolean]))
  65. expect(out.parse([true])).toEqual([true])
  66. expect(out.safeParse([true, false]).success).toBe(false)
  67. })
  68. test("tuple inside a union picks the right branch", () => {
  69. const out = zod(Schema.Union([Schema.String, Schema.Tuple([Schema.String, Schema.Number])]))
  70. expect(out.parse("hello")).toBe("hello")
  71. expect(out.parse(["foo", 42])).toEqual(["foo", 42])
  72. expect(out.safeParse(["foo"]).success).toBe(false)
  73. })
  74. test("plain arrays still work (no element positions)", () => {
  75. const out = zod(Schema.Array(Schema.String))
  76. expect(out.parse(["a", "b", "c"])).toEqual(["a", "b", "c"])
  77. expect(out.parse([])).toEqual([])
  78. })
  79. })
  80. test("string literal unions produce z.enum with enum in JSON Schema", () => {
  81. const Action = Schema.Literals(["allow", "deny", "ask"])
  82. const out = zod(Action)
  83. expect(out.parse("allow")).toBe("allow")
  84. expect(out.parse("deny")).toBe("deny")
  85. expect(() => out.parse("nope")).toThrow()
  86. // Matches native z.enum JSON Schema output
  87. const bridged = json(out)
  88. const native = json(z.enum(["allow", "deny", "ask"]))
  89. expect(bridged).toEqual(native)
  90. expect(bridged.enum).toEqual(["allow", "deny", "ask"])
  91. })
  92. test("ZodOverride annotation provides the Zod schema for branded IDs", () => {
  93. const override = z.string().startsWith("per")
  94. const ID = Schema.String.annotate({ [ZodOverride]: override }).pipe(Schema.brand("TestID"))
  95. const Parent = Schema.Struct({ id: ID, name: Schema.String })
  96. const out = zod(Parent)
  97. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  98. expect((out as any).parse({ id: "per_abc", name: "test" })).toEqual({ id: "per_abc", name: "test" })
  99. const schema = json(out) as any
  100. expect(schema.properties.id).toEqual({ type: "string", pattern: "^per.*" })
  101. })
  102. test("Schema.Class nested in a parent preserves ref via identifier", () => {
  103. class Inner extends Schema.Class<Inner>("MyInner")({
  104. value: Schema.String,
  105. }) {}
  106. class Outer extends Schema.Class<Outer>("MyOuter")({
  107. inner: Inner,
  108. }) {}
  109. const out = zod(Outer)
  110. expect(out.meta()?.ref).toBe("MyOuter")
  111. const shape = (out as any).shape ?? (out as any)._def?.shape?.()
  112. expect(shape.inner.meta()?.ref).toBe("MyInner")
  113. })
  114. test("Schema.Class preserves identifier and uses enum format", () => {
  115. class Rule extends Schema.Class<Rule>("PermissionRule")({
  116. permission: Schema.String,
  117. pattern: Schema.String,
  118. action: Schema.Literals(["allow", "deny", "ask"]),
  119. }) {}
  120. const out = zod(Rule)
  121. expect(out.meta()?.ref).toBe("PermissionRule")
  122. const schema = json(out) as any
  123. expect(schema.properties.action).toEqual({
  124. type: "string",
  125. enum: ["allow", "deny", "ask"],
  126. })
  127. })
  128. test("ZodOverride on ID carries pattern through Schema.Class", () => {
  129. const ID = Schema.String.annotate({
  130. [ZodOverride]: z.string().startsWith("per"),
  131. })
  132. class Request extends Schema.Class<Request>("TestRequest")({
  133. id: ID,
  134. name: Schema.String,
  135. }) {}
  136. const schema = json(zod(Request)) as any
  137. expect(schema.properties.id).toEqual({ type: "string", pattern: "^per.*" })
  138. expect(schema.properties.name).toEqual({ type: "string" })
  139. })
  140. test("Permission schemas match original Zod equivalents", () => {
  141. const MsgID = Schema.String.annotate({ [ZodOverride]: z.string().startsWith("msg") })
  142. const PerID = Schema.String.annotate({ [ZodOverride]: z.string().startsWith("per") })
  143. const SesID = Schema.String.annotate({ [ZodOverride]: z.string().startsWith("ses") })
  144. class Tool extends Schema.Class<Tool>("PermissionTool")({
  145. messageID: MsgID,
  146. callID: Schema.String,
  147. }) {}
  148. class Request extends Schema.Class<Request>("PermissionRequest")({
  149. id: PerID,
  150. sessionID: SesID,
  151. permission: Schema.String,
  152. patterns: Schema.Array(Schema.String),
  153. metadata: Schema.Record(Schema.String, Schema.Unknown),
  154. always: Schema.Array(Schema.String),
  155. tool: Schema.optional(Tool),
  156. }) {}
  157. const bridged = json(zod(Request)) as any
  158. expect(bridged.properties.id).toEqual({ type: "string", pattern: "^per.*" })
  159. expect(bridged.properties.sessionID).toEqual({ type: "string", pattern: "^ses.*" })
  160. expect(bridged.properties.permission).toEqual({ type: "string" })
  161. expect(bridged.required?.sort()).toEqual(["id", "sessionID", "permission", "patterns", "metadata", "always"].sort())
  162. // Tool field is present with the ref from Schema.Class identifier
  163. const toolSchema = json(zod(Tool)) as any
  164. expect(toolSchema.properties.messageID).toEqual({ type: "string", pattern: "^msg.*" })
  165. expect(toolSchema.properties.callID).toEqual({ type: "string" })
  166. })
  167. test("ZodOverride survives Schema.brand", () => {
  168. const override = z.string().startsWith("ses")
  169. const ID = Schema.String.annotate({ [ZodOverride]: override }).pipe(Schema.brand("SessionID"))
  170. // The branded schema's AST still has the override
  171. class Parent extends Schema.Class<Parent>("Parent")({
  172. sessionID: ID,
  173. }) {}
  174. const schema = json(zod(Parent)) as any
  175. expect(schema.properties.sessionID).toEqual({ type: "string", pattern: "^ses.*" })
  176. })
  177. describe("Schema.check translation", () => {
  178. test("filter returning string triggers refinement with that message", () => {
  179. const isEven = Schema.makeFilter((n: number) => (n % 2 === 0 ? undefined : "expected an even number"))
  180. const schema = zod(Schema.Number.check(isEven))
  181. expect(schema.parse(4)).toBe(4)
  182. const result = schema.safeParse(3)
  183. expect(result.success).toBe(false)
  184. expect(result.error!.issues[0].message).toBe("expected an even number")
  185. })
  186. test("filter returning false triggers refinement with fallback message", () => {
  187. const nonEmpty = Schema.makeFilter((s: string) => s.length > 0)
  188. const schema = zod(Schema.String.check(nonEmpty))
  189. expect(schema.parse("hi")).toBe("hi")
  190. const result = schema.safeParse("")
  191. expect(result.success).toBe(false)
  192. expect(result.error!.issues[0].message).toMatch(/./)
  193. })
  194. test("filter returning undefined passes validation", () => {
  195. const alwaysOk = Schema.makeFilter(() => undefined)
  196. const schema = zod(Schema.Number.check(alwaysOk))
  197. expect(schema.parse(42)).toBe(42)
  198. })
  199. test("annotations.message on the filter is used when filter returns false", () => {
  200. const positive = Schema.makeFilter((n: number) => n > 0, { message: "must be positive" })
  201. const schema = zod(Schema.Number.check(positive))
  202. const result = schema.safeParse(-1)
  203. expect(result.success).toBe(false)
  204. expect(result.error!.issues[0].message).toBe("must be positive")
  205. })
  206. test("cross-field check on a record flags missing key", () => {
  207. const hasKey = Schema.makeFilter((data: Record<string, { enabled: boolean }>) =>
  208. "required" in data ? undefined : "missing 'required' key",
  209. )
  210. const schema = zod(Schema.Record(Schema.String, Schema.Struct({ enabled: Schema.Boolean })).check(hasKey))
  211. expect(schema.parse({ required: { enabled: true } })).toEqual({
  212. required: { enabled: true },
  213. })
  214. const result = schema.safeParse({ other: { enabled: true } })
  215. expect(result.success).toBe(false)
  216. expect(result.error!.issues[0].message).toBe("missing 'required' key")
  217. })
  218. })
  219. describe("StructWithRest / catchall", () => {
  220. test("struct with a string-keyed record rest parses known AND extra keys", () => {
  221. const schema = zod(
  222. Schema.StructWithRest(
  223. Schema.Struct({
  224. apiKey: Schema.optional(Schema.String),
  225. baseURL: Schema.optional(Schema.String),
  226. }),
  227. [Schema.Record(Schema.String, Schema.Unknown)],
  228. ),
  229. )
  230. // Known fields come through as declared
  231. expect(schema.parse({ apiKey: "sk-x" })).toEqual({ apiKey: "sk-x" })
  232. // Extra keys are preserved (catchall)
  233. expect(
  234. schema.parse({
  235. apiKey: "sk-x",
  236. baseURL: "https://api.example.com",
  237. customField: "anything",
  238. nested: { foo: 1 },
  239. }),
  240. ).toEqual({
  241. apiKey: "sk-x",
  242. baseURL: "https://api.example.com",
  243. customField: "anything",
  244. nested: { foo: 1 },
  245. })
  246. })
  247. test("catchall value type constrains the extras", () => {
  248. const schema = zod(
  249. Schema.StructWithRest(
  250. Schema.Struct({
  251. count: Schema.Number,
  252. }),
  253. [Schema.Record(Schema.String, Schema.Number)],
  254. ),
  255. )
  256. // Known field + numeric extras
  257. expect(schema.parse({ count: 10, a: 1, b: 2 })).toEqual({ count: 10, a: 1, b: 2 })
  258. // Non-numeric extra is rejected
  259. expect(schema.safeParse({ count: 10, bad: "not a number" }).success).toBe(false)
  260. })
  261. test("JSON schema output marks additionalProperties appropriately", () => {
  262. const schema = zod(
  263. Schema.StructWithRest(
  264. Schema.Struct({
  265. id: Schema.String,
  266. }),
  267. [Schema.Record(Schema.String, Schema.Unknown)],
  268. ),
  269. )
  270. const shape = json(schema) as { additionalProperties?: unknown }
  271. // Presence of `additionalProperties` (truthy or a schema) signals catchall.
  272. expect(shape.additionalProperties).not.toBe(false)
  273. expect(shape.additionalProperties).toBeDefined()
  274. })
  275. test("plain struct without rest still emits additionalProperties unchanged (regression)", () => {
  276. const schema = zod(Schema.Struct({ id: Schema.String }))
  277. expect(schema.parse({ id: "x" })).toEqual({ id: "x" })
  278. })
  279. })
  280. describe("transforms (Schema.decodeTo)", () => {
  281. test("Number -> pseudo-Duration (seconds) applies the decode function", () => {
  282. // Models the account/account.ts DurationFromSeconds pattern.
  283. const SecondsToMs = Schema.Number.pipe(
  284. Schema.decodeTo(Schema.Number, {
  285. decode: SchemaGetter.transform((n: number) => n * 1000),
  286. encode: SchemaGetter.transform((ms: number) => ms / 1000),
  287. }),
  288. )
  289. const schema = zod(SecondsToMs)
  290. expect(schema.parse(3)).toBe(3000)
  291. expect(schema.parse(0)).toBe(0)
  292. })
  293. test("String -> Number via parseInt decode", () => {
  294. const ParsedInt = Schema.String.pipe(
  295. Schema.decodeTo(Schema.Number, {
  296. decode: SchemaGetter.transform((s: string) => Number.parseInt(s, 10)),
  297. encode: SchemaGetter.transform((n: number) => String(n)),
  298. }),
  299. )
  300. const schema = zod(ParsedInt)
  301. expect(schema.parse("42")).toBe(42)
  302. expect(schema.parse("0")).toBe(0)
  303. })
  304. test("transform inside a struct field applies per-field", () => {
  305. const Field = Schema.Number.pipe(
  306. Schema.decodeTo(Schema.Number, {
  307. decode: SchemaGetter.transform((n: number) => n + 1),
  308. encode: SchemaGetter.transform((n: number) => n - 1),
  309. }),
  310. )
  311. const schema = zod(
  312. Schema.Struct({
  313. plain: Schema.Number,
  314. bumped: Field,
  315. }),
  316. )
  317. expect(schema.parse({ plain: 5, bumped: 10 })).toEqual({ plain: 5, bumped: 11 })
  318. })
  319. test("chained decodeTo composes transforms in order", () => {
  320. // String -> Number (parseInt) -> Number (doubled).
  321. // Exercises the encoded() reduce, not just a single link.
  322. const Chained = Schema.String.pipe(
  323. Schema.decodeTo(Schema.Number, {
  324. decode: SchemaGetter.transform((s: string) => Number.parseInt(s, 10)),
  325. encode: SchemaGetter.transform((n: number) => String(n)),
  326. }),
  327. Schema.decodeTo(Schema.Number, {
  328. decode: SchemaGetter.transform((n: number) => n * 2),
  329. encode: SchemaGetter.transform((n: number) => n / 2),
  330. }),
  331. )
  332. const schema = zod(Chained)
  333. expect(schema.parse("21")).toBe(42)
  334. expect(schema.parse("0")).toBe(0)
  335. })
  336. test("Schema.Class is unaffected by transform walker (returns plain object, not instance)", () => {
  337. // Schema.Class uses Declaration + encoding under the hood to construct
  338. // class instances. The walker must NOT apply that transform, or zod
  339. // parsing would return class instances instead of plain objects.
  340. class Method extends Schema.Class<Method>("TxTestMethod")({
  341. type: Schema.String,
  342. value: Schema.Number,
  343. }) {}
  344. const schema = zod(Method)
  345. const parsed = schema.parse({ type: "oauth", value: 1 })
  346. expect(parsed).toEqual({ type: "oauth", value: 1 })
  347. // Guardrail: ensure we didn't get back a Method instance.
  348. expect(parsed).not.toBeInstanceOf(Method)
  349. })
  350. })
  351. describe("optimizations", () => {
  352. test("walk() memoizes by AST identity — same AST node returns same Zod", () => {
  353. const shared = Schema.Struct({ id: Schema.String, name: Schema.String })
  354. const left = zod(shared)
  355. const right = zod(shared)
  356. expect(left).toBe(right)
  357. })
  358. test("nested reuse of the same AST reuses the cached Zod child", () => {
  359. // Two different parents embed the same inner schema. The inner zod
  360. // child should be identical by reference inside both parents.
  361. class Inner extends Schema.Class<Inner>("MemoTestInner")({
  362. value: Schema.String,
  363. }) {}
  364. class OuterA extends Schema.Class<OuterA>("MemoTestOuterA")({
  365. inner: Inner,
  366. }) {}
  367. class OuterB extends Schema.Class<OuterB>("MemoTestOuterB")({
  368. inner: Inner,
  369. }) {}
  370. const shapeA = (zod(OuterA) as any).shape ?? (zod(OuterA) as any)._def?.shape?.()
  371. const shapeB = (zod(OuterB) as any).shape ?? (zod(OuterB) as any)._def?.shape?.()
  372. expect(shapeA.inner).toBe(shapeB.inner)
  373. })
  374. test("multiple checks run in a single refinement layer (all fire on one value)", () => {
  375. // Three checks attached to the same schema. All three must run and
  376. // report — asserting that no check silently got dropped when we
  377. // flattened into one superRefine.
  378. const positive = Schema.makeFilter((n: number) => (n > 0 ? undefined : "not positive"))
  379. const even = Schema.makeFilter((n: number) => (n % 2 === 0 ? undefined : "not even"))
  380. const under100 = Schema.makeFilter((n: number) => (n < 100 ? undefined : "too big"))
  381. const schema = zod(Schema.Number.check(positive).check(even).check(under100))
  382. const neg = schema.safeParse(-3)
  383. expect(neg.success).toBe(false)
  384. expect(neg.error!.issues.map((i) => i.message)).toEqual(expect.arrayContaining(["not positive", "not even"]))
  385. const big = schema.safeParse(101)
  386. expect(big.success).toBe(false)
  387. expect(big.error!.issues.map((i) => i.message)).toContain("too big")
  388. // Passing value satisfies all three
  389. expect(schema.parse(42)).toBe(42)
  390. })
  391. test("FilterGroup flattens into the single refinement layer alongside its siblings", () => {
  392. const positive = Schema.makeFilter((n: number) => (n > 0 ? undefined : "not positive"))
  393. const even = Schema.makeFilter((n: number) => (n % 2 === 0 ? undefined : "not even"))
  394. const group = Schema.makeFilterGroup([positive, even])
  395. const under100 = Schema.makeFilter((n: number) => (n < 100 ? undefined : "too big"))
  396. const schema = zod(Schema.Number.check(group).check(under100))
  397. const bad = schema.safeParse(-3)
  398. expect(bad.success).toBe(false)
  399. expect(bad.error!.issues.map((i) => i.message)).toEqual(expect.arrayContaining(["not positive", "not even"]))
  400. })
  401. })
  402. describe("well-known refinement translation", () => {
  403. test("Schema.isInt emits type: integer in JSON Schema", () => {
  404. const schema = zod(Schema.Number.check(Schema.isInt()))
  405. const native = json(z.number().int())
  406. expect(json(schema)).toEqual(native)
  407. expect(schema.parse(3)).toBe(3)
  408. expect(schema.safeParse(1.5).success).toBe(false)
  409. })
  410. test("Schema.isGreaterThan(0) emits exclusiveMinimum: 0", () => {
  411. const schema = zod(Schema.Number.check(Schema.isGreaterThan(0)))
  412. expect((json(schema) as any).exclusiveMinimum).toBe(0)
  413. expect(schema.parse(1)).toBe(1)
  414. expect(schema.safeParse(0).success).toBe(false)
  415. expect(schema.safeParse(-1).success).toBe(false)
  416. })
  417. test("Schema.isGreaterThanOrEqualTo(0) emits minimum: 0", () => {
  418. const schema = zod(Schema.Number.check(Schema.isGreaterThanOrEqualTo(0)))
  419. expect((json(schema) as any).minimum).toBe(0)
  420. expect(schema.parse(0)).toBe(0)
  421. expect(schema.safeParse(-1).success).toBe(false)
  422. })
  423. test("Schema.isLessThan(10) emits exclusiveMaximum: 10", () => {
  424. const schema = zod(Schema.Number.check(Schema.isLessThan(10)))
  425. expect((json(schema) as any).exclusiveMaximum).toBe(10)
  426. expect(schema.parse(9)).toBe(9)
  427. expect(schema.safeParse(10).success).toBe(false)
  428. })
  429. test("Schema.isLessThanOrEqualTo(10) emits maximum: 10", () => {
  430. const schema = zod(Schema.Number.check(Schema.isLessThanOrEqualTo(10)))
  431. expect((json(schema) as any).maximum).toBe(10)
  432. expect(schema.parse(10)).toBe(10)
  433. expect(schema.safeParse(11).success).toBe(false)
  434. })
  435. test("Schema.isMultipleOf(5) emits multipleOf: 5", () => {
  436. const schema = zod(Schema.Number.check(Schema.isMultipleOf(5)))
  437. expect((json(schema) as any).multipleOf).toBe(5)
  438. expect(schema.parse(10)).toBe(10)
  439. expect(schema.safeParse(7).success).toBe(false)
  440. })
  441. test("Schema.isFinite validates at runtime", () => {
  442. const schema = zod(Schema.Number.check(Schema.isFinite()))
  443. expect(schema.parse(1)).toBe(1)
  444. expect(schema.safeParse(Infinity).success).toBe(false)
  445. expect(schema.safeParse(NaN).success).toBe(false)
  446. })
  447. test("chained isInt + isGreaterThan(0) matches z.number().int().positive()", () => {
  448. const schema = zod(Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThan(0)))
  449. const native = json(z.number().int().positive())
  450. expect(json(schema)).toEqual(native)
  451. expect(schema.parse(3)).toBe(3)
  452. expect(schema.safeParse(0).success).toBe(false)
  453. expect(schema.safeParse(1.5).success).toBe(false)
  454. })
  455. test("chained isInt + isGreaterThanOrEqualTo(0) matches z.number().int().min(0)", () => {
  456. const schema = zod(Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)))
  457. const native = json(z.number().int().min(0))
  458. expect(json(schema)).toEqual(native)
  459. expect(schema.parse(0)).toBe(0)
  460. expect(schema.safeParse(-1).success).toBe(false)
  461. })
  462. test("Schema.isBetween emits both bounds", () => {
  463. const schema = zod(Schema.Number.check(Schema.isBetween({ minimum: 1, maximum: 10 })))
  464. const shape = json(schema) as any
  465. expect(shape.minimum).toBe(1)
  466. expect(shape.maximum).toBe(10)
  467. expect(schema.parse(5)).toBe(5)
  468. expect(schema.safeParse(11).success).toBe(false)
  469. expect(schema.safeParse(0).success).toBe(false)
  470. })
  471. test("Schema.isBetween with exclusive bounds emits exclusiveMinimum/Maximum", () => {
  472. const schema = zod(
  473. Schema.Number.check(
  474. Schema.isBetween({ minimum: 1, maximum: 10, exclusiveMinimum: true, exclusiveMaximum: true }),
  475. ),
  476. )
  477. const shape = json(schema) as any
  478. expect(shape.exclusiveMinimum).toBe(1)
  479. expect(shape.exclusiveMaximum).toBe(10)
  480. expect(schema.parse(5)).toBe(5)
  481. expect(schema.safeParse(1).success).toBe(false)
  482. expect(schema.safeParse(10).success).toBe(false)
  483. })
  484. test("Schema.isInt32 (FilterGroup) produces integer bounds", () => {
  485. const schema = zod(Schema.Number.check(Schema.isInt32()))
  486. const shape = json(schema) as any
  487. expect(shape.type).toBe("integer")
  488. expect(shape.minimum).toBe(-2147483648)
  489. expect(shape.maximum).toBe(2147483647)
  490. expect(schema.parse(42)).toBe(42)
  491. expect(schema.safeParse(1.5).success).toBe(false)
  492. expect(schema.safeParse(2147483648).success).toBe(false)
  493. })
  494. test("Schema.isMinLength on string emits minLength", () => {
  495. const schema = zod(Schema.String.check(Schema.isMinLength(3)))
  496. expect((json(schema) as any).minLength).toBe(3)
  497. expect(schema.parse("abc")).toBe("abc")
  498. expect(schema.safeParse("ab").success).toBe(false)
  499. })
  500. test("Schema.isMaxLength on string emits maxLength", () => {
  501. const schema = zod(Schema.String.check(Schema.isMaxLength(5)))
  502. expect((json(schema) as any).maxLength).toBe(5)
  503. expect(schema.parse("abcde")).toBe("abcde")
  504. expect(schema.safeParse("abcdef").success).toBe(false)
  505. })
  506. test("Schema.isLengthBetween on string emits both bounds", () => {
  507. const schema = zod(Schema.String.check(Schema.isLengthBetween(2, 4)))
  508. const shape = json(schema) as any
  509. expect(shape.minLength).toBe(2)
  510. expect(shape.maxLength).toBe(4)
  511. expect(schema.parse("abc")).toBe("abc")
  512. expect(schema.safeParse("a").success).toBe(false)
  513. expect(schema.safeParse("abcde").success).toBe(false)
  514. })
  515. test("Schema.isMinLength on array emits minItems", () => {
  516. const schema = zod(Schema.Array(Schema.String).check(Schema.isMinLength(1)))
  517. expect((json(schema) as any).minItems).toBe(1)
  518. expect(schema.parse(["x"])).toEqual(["x"])
  519. expect(schema.safeParse([]).success).toBe(false)
  520. })
  521. test("Schema.isPattern emits pattern", () => {
  522. const schema = zod(Schema.String.check(Schema.isPattern(/^per/)))
  523. expect((json(schema) as any).pattern).toBe("^per")
  524. expect(schema.parse("per_abc")).toBe("per_abc")
  525. expect(schema.safeParse("abc").success).toBe(false)
  526. })
  527. test("Schema.isStartsWith matches native zod .startsWith() JSON Schema", () => {
  528. const schema = zod(Schema.String.check(Schema.isStartsWith("per")))
  529. const native = json(z.string().startsWith("per"))
  530. expect(json(schema)).toEqual(native)
  531. expect(schema.parse("per_abc")).toBe("per_abc")
  532. expect(schema.safeParse("abc").success).toBe(false)
  533. })
  534. test("Schema.isEndsWith matches native zod .endsWith() JSON Schema", () => {
  535. const schema = zod(Schema.String.check(Schema.isEndsWith(".json")))
  536. const native = json(z.string().endsWith(".json"))
  537. expect(json(schema)).toEqual(native)
  538. expect(schema.parse("a.json")).toBe("a.json")
  539. expect(schema.safeParse("a.txt").success).toBe(false)
  540. })
  541. test("Schema.isUUID emits format: uuid", () => {
  542. const schema = zod(Schema.String.check(Schema.isUUID()))
  543. expect((json(schema) as any).format).toBe("uuid")
  544. })
  545. test("mix of well-known and anonymous filters translates known and reroutes unknown to superRefine", () => {
  546. // isInt is well-known (translates to .int()); the anonymous filter falls
  547. // back to superRefine.
  548. const notSeven = Schema.makeFilter((n: number) => (n !== 7 ? undefined : "no sevens allowed"))
  549. const schema = zod(Schema.Number.check(Schema.isInt()).check(notSeven))
  550. const shape = json(schema) as any
  551. // Well-known translation is preserved — type is integer, not plain number
  552. expect(shape.type).toBe("integer")
  553. // Runtime: both constraints fire
  554. expect(schema.parse(3)).toBe(3)
  555. expect(schema.safeParse(1.5).success).toBe(false)
  556. const seven = schema.safeParse(7)
  557. expect(seven.success).toBe(false)
  558. expect(seven.error!.issues[0].message).toBe("no sevens allowed")
  559. })
  560. test("inside a struct field, well-known refinements propagate through", () => {
  561. // Mirrors config.ts port: z.number().int().positive().optional()
  562. const Port = Schema.optional(Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThan(0)))
  563. const schema = zod(Schema.Struct({ port: Port }))
  564. const shape = json(schema) as any
  565. expect(shape.properties.port.type).toBe("integer")
  566. expect(shape.properties.port.exclusiveMinimum).toBe(0)
  567. })
  568. })
  569. describe("Schema.optionalWith defaults", () => {
  570. test("parsing undefined returns the default value", () => {
  571. const schema = zod(
  572. Schema.Struct({
  573. mode: Schema.String.pipe(Schema.optional, Schema.withDecodingDefault(Effect.succeed("ctrl-x"))),
  574. }),
  575. )
  576. expect(schema.parse({})).toEqual({ mode: "ctrl-x" })
  577. expect(schema.parse({ mode: undefined })).toEqual({ mode: "ctrl-x" })
  578. })
  579. test("parsing a real value returns that value (default does not fire)", () => {
  580. const schema = zod(
  581. Schema.Struct({
  582. mode: Schema.String.pipe(Schema.optional, Schema.withDecodingDefault(Effect.succeed("ctrl-x"))),
  583. }),
  584. )
  585. expect(schema.parse({ mode: "ctrl-y" })).toEqual({ mode: "ctrl-y" })
  586. })
  587. test("default on a number field", () => {
  588. const schema = zod(
  589. Schema.Struct({
  590. count: Schema.Number.pipe(Schema.optional, Schema.withDecodingDefault(Effect.succeed(42))),
  591. }),
  592. )
  593. expect(schema.parse({})).toEqual({ count: 42 })
  594. expect(schema.parse({ count: 7 })).toEqual({ count: 7 })
  595. })
  596. test("multiple defaulted fields inside a struct", () => {
  597. const schema = zod(
  598. Schema.Struct({
  599. leader: Schema.String.pipe(Schema.optional, Schema.withDecodingDefault(Effect.succeed("ctrl-x"))),
  600. quit: Schema.String.pipe(Schema.optional, Schema.withDecodingDefault(Effect.succeed("ctrl-c"))),
  601. inner: Schema.String,
  602. }),
  603. )
  604. expect(schema.parse({ inner: "hi" })).toEqual({
  605. leader: "ctrl-x",
  606. quit: "ctrl-c",
  607. inner: "hi",
  608. })
  609. expect(schema.parse({ leader: "a", quit: "b", inner: "c" })).toEqual({
  610. leader: "a",
  611. quit: "b",
  612. inner: "c",
  613. })
  614. })
  615. test("JSON Schema output includes the default key", () => {
  616. const schema = zod(
  617. Schema.Struct({
  618. mode: Schema.String.pipe(Schema.optional, Schema.withDecodingDefault(Effect.succeed("ctrl-x"))),
  619. }),
  620. )
  621. const shape = json(schema) as any
  622. expect(shape.properties.mode.default).toBe("ctrl-x")
  623. })
  624. test("default referencing a computed value resolves when evaluated", () => {
  625. // Simulates `keybinds.ts` style of per-platform defaults: the default is
  626. // produced by an Effect that computes a value at decode time.
  627. const platform = "darwin"
  628. const fallback = platform === "darwin" ? "cmd-k" : "ctrl-k"
  629. const schema = zod(
  630. Schema.Struct({
  631. command_palette: Schema.String.pipe(Schema.optional, Schema.withDecodingDefault(Effect.sync(() => fallback))),
  632. }),
  633. )
  634. expect(schema.parse({})).toEqual({ command_palette: "cmd-k" })
  635. const shape = json(schema) as any
  636. expect(shape.properties.command_palette.default).toBe("cmd-k")
  637. })
  638. test("plain Schema.optional (no default) still emits .optional() (regression)", () => {
  639. const schema = zod(Schema.Struct({ foo: Schema.optional(Schema.String) }))
  640. expect(schema.parse({})).toEqual({})
  641. expect(schema.parse({ foo: "hi" })).toEqual({ foo: "hi" })
  642. })
  643. })
  644. })