Skip to content

feat(zod): emit typed schemas for Set and Map collections (#451) - #535

Open
Utkarsh Patwa (utkarshpatwa393-sys) wants to merge 4 commits into
microsoft:mainfrom
utkarshpatwa393-sys:feat/zod-collection-schemas-451
Open

Utkarsh Patwa (utkarshpatwa393-sys) wants to merge 4 commits into
microsoft:mainfrom
utkarshpatwa393-sys:feat/zod-collection-schemas-451

Conversation

@utkarshpatwa393-sys

@utkarshpatwa393-sys Utkarsh Patwa (utkarshpatwa393-sys) commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Related to #451 by emitting typed schemas for z.set() and z.map() in getZodSchemaAsTypeScript instead of falling through to any, and adding explicit regression tests for JSON-to-collection transformations.

Context & Motivation

When generating prompt schemas with getZodSchemaAsTypeScript, z.set() and z.map() previously lacked explicit handlers in the type switch and fell through to any.

This PR provides:

  1. Direct collection schema emission: globalThis.Set<T> and globalThis.Map<K, V> in TypeScript schemas matching standard library declarations while preventing naming collisions when user schemas are named Set or Map.
  2. Verified explicit wire-to-runtime transforms: in TypeChat applications using z.array(...).transform(v => new Set(v)) and z.array(z.tuple(...)).transform(v => new Map(v)), the wire schema emits JSON-compatible arrays (T[] and [K, V][]) while validation cleanly hydrates runtime Set and Map instances.

Changes

  • typescript/src/zod/validate.ts:
    • Qualified emitted built-ins as globalThis.Set<T> and globalThis.Map<K, V> to prevent shadowing when callers name schemas Set or Map.
  • typescript/test/zod.test.ts:
    • Added compiler-backed regression tests for colliding schema names ({ Set: z.set(...) } and { Map: z.map(...) }), verified with TypeScript compilation via assertSchemasCompile.
    • Added regression tests for explicit z.array(...).transform(...) wire schema emission and validation hydration into Set and Map instances.
    • Added end-to-end translation test with createJsonTranslator and a stubbed model.

Validation

  • npm run build-all: Clean build across core and all sample workspaces.
  • npm test: 379 tests passed, 0 failed (67 test suites).

Zod `z.set()` and `z.map()` previously fell through to `any` in
`getZodSchemaAsTypeScript`.

This change:
- Emits `T[]` for `z.set()` as the JSON-compatible wire schema.
- Emits `[K, V][]` for `z.map()` as the key-value tuple array wire schema.
- Adds test coverage for `z.set()` and `z.map()` in `test/zod.test.ts`,
  including union elements.

Closes microsoft#451

Signed-off-by: Utkarsh patwa <utkarshpatwa393@gmail.com>
Copilot AI balanced review requested due to automatic review settings November 19, 2026 09:43

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Bare z.set() and z.map() schemas reject the translator’s plain JSON arrays, causing even schema-conforming responses to fail validation with no repair path to the required collection instances.

1 open issue
What changed in this PR

This PR adds explicit collection representations to TypeChat’s Zod prompt-schema emitter, addressing the schema-generation portion of #451.

Changes:

  • Emits z.set() as T[] and z.map() as [K, V][] instead of any.
  • Adds collection-shape and union-handling tests whose generated declarations use the existing TypeScript compilation checks.
File Description
typescript/​test/​zod.test.ts Adds Set and Map schema-output tests, including union members.
typescript/​src/​zod/​validate.ts Adds Set and Map handlers that emit array-based prompt types.

Review effort: Balanced

Comment thread typescript/src/zod/validate.ts Resolved
…nsform regression tests

Signed-off-by: Utkarsh patwa <utkarshpatwa393@gmail.com>
Copilot AI balanced review requested due to automatic review settings November 19, 2026 09:57
@utkarshpatwa393-sys Utkarsh Patwa (utkarshpatwa393-sys) changed the title feat(zod): emit typed wire schemas for Set and Map collections (#451) feat(zod): emit typed schemas for Set and Map collections (#451) Nov 19, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Caller-supplied schema names can shadow the generated Set and Map references, causing TypeScript compilation failures unless both references are qualified with globalThis.

2 open issues

Review effort: Balanced

Comment thread typescript/src/zod/validate.ts Resolved
@robgruen

Copy link
Copy Markdown
Contributor

Thanks for adding the end-to-end test. It makes the intended boundary clear: the model sends ordinary JSON arrays, and the explicit Zod transforms produce the runtime collections.

There is one remaining compiler issue in f2bc01e. An application picks its own schema names. If it picks Set or Map, the generated alias hides the standard-library type it was meant to reference:

Schema passed to getZodSchemaAsTypeScript Generated TypeScript
{ Set: z.set(z.string()) } type Set = Set<string>;
{ Map: z.map(z.string(), z.number()) } type Map = Map<string, number>;

I checked those two declarations in an isolated module with the repo's TypeScript 7.0.2 compiler (--strict --noEmit, ES2022). Both produce TS2456 (the alias circularly references itself) and TS2315 (the local alias is not generic). Changing only the right-hand sides to globalThis.Set<string> and globalThis.Map<string, number> compiles cleanly with the same options. This was a focused compiler check, not a run of the full PR suite.

Could you qualify the emitted built-in names and add compiler-backed regression cases for both of the schema maps above? Using Set and Map as the caller's names, rather than T, is what catches the regression. That would address the remaining inline thread.

One small scope request: would you mind changing the PR description from Fixes #451 to Related to #451? These collection tests are a useful contribution. Issue #451's scope also includes copyable TypeScript and Zod examples, duplicate handling, and behavior with repair enabled or disabled. A non-closing reference gives this work credit and keeps those items visible without asking you to take them all on here.

Copilot-assisted review, posted at the maintainer's request.

@robgruen robgruen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes on the remaining Set / Map schema-name collision. Could you qualify the built-in names, add the two compiler-backed regression cases, and make the reference to issue #451 non-closing? The examples, compiler results, and scope note have the details. The earlier JSON-input thread is resolved. Thanks for the explicit-conversion coverage; happy to take another look after the update.

Copilot-assisted review submitted at the maintainer's request.

…ession tests

Signed-off-by: Utkarsh Patwa <utkarshpatwa393@gmail.com>
Copilot AI balanced review requested due to automatic review settings November 24, 2026 07:10
@utkarshpatwa393-sys

Copy link
Copy Markdown
Contributor Author

Hi robgruen 👋

Thank you for the detailed compiler inspection and guidance!

All points have been addressed in commit f8f58f5:

  1. Qualified built-ins: Updated appendSetType and appendMapType to emit globalThis.Set<...> and globalThis.Map<...> in typescript/src/zod/validate.ts.
  2. Compiler-backed regression cases: Added regression tests in typescript/test/zod.test.ts for schemas explicitly named Set and Map:
    • schemaOf("Set", z.set(z.string()))
    • schemaOf("Map", z.map(z.string(), z.number()))
      Both are compiled via assertSchemasCompile using the project's TypeScript compiler, cleanly resolving TS2456 and TS2315 without collisions.
  3. Scope note: Updated the PR description from Fixes #451 to Related to #451.

All 379 tests across 67 test suites pass cleanly (npm test). Ready for your re-review! Thank you.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Collection schema generation can overflow the stack for unnamed recursive objects and emit invalid TypeScript for non-identifier property names.

No open issues 🎉

2 previously missed issues

In code that hasn't changed since last review

Medium severity Unnamed recursive collection schemas overflow the stack

typescript/​src/​zod/​validate.ts:207

An unnamed recursive object inside a collection now causes schema generation to overflow the stack—for example, Node with a children getter returning z.set(Node).optional(). Detect types already being expanded and report a clear error telling callers to register the recursive type by name, with regression tests for both collections. Same issue in typescript/src/zod/validate.ts:216 for map values.

Medium severity Collection schemas emit invalid TypeScript for non-identifier keys

typescript/​src/​zod/​validate.ts:207

z.set(z.object({ "part-number": z.string() })) now emits part-number: string; without quotes, producing invalid TypeScript. Escape non-identifier property names in both required and optional branches of appendObjectType, and add collection regression tests. The same issue affects map values at typescript/src/zod/validate.ts:216.

1 resolved since last review

Review effort: Max

@robgruen

Copy link
Copy Markdown
Contributor

Thanks for addressing the feedback and adding the regression tests! I ran another Copilot review, which flagged two additional edge cases. Could you take a look at its latest findings?

…cursive collections (microsoft#451)

- In appendObjectType, escape non-identifier property names with JSON.stringify in both required and optional branches.
- In getZodSchemaAsTypeScript, track expanding type identities in expandingTypes to detect unnamed recursive types in collections or nested objects and throw an actionable error instructing callers to register the recursive type by name.
- Add compiler-backed regression tests in typescript/test/zod.test.ts for non-identifier keys in Set, Map, and object types, as well as unnamed and registered recursive schemas for both Set and Map.

Signed-off-by: Utkarsh Patwa <utkarshpatwa393@gmail.com>
Copilot AI max review requested due to automatic review settings November 25, 2026 06:32

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@utkarshpatwa393-sys

Copy link
Copy Markdown
Contributor Author

Hi robgruen,

Thank you for running the follow-up review! Both edge cases have been resolved in commit 56407db:

  1. Non-Identifier Property Keys Escaping:

    • In appendObjectType, added isValidPropertyName check (/^[a-zA-Z_$][0-9a-zA-Z_$]*$/).
    • If a property name is not a standard identifier (e.g. "part-number", "is-active"), it is escaped using JSON.stringify(name) across both required ("part-number": string;) and optional ("is-active"?: boolean;) branches.
    • Added compiler-backed regression tests verifying quoted property emissions in Set element objects, Map value objects, and standalone object interfaces.
  2. Unnamed Recursive Collection Schemas Detection:

    • In getZodSchemaAsTypeScript, introduced an expandingTypes = new Set<object>() tracking set.
    • When expanding type definitions in appendType, if a type identity is already in expandingTypes and unmapped in namedTypes (such as a recursive Node referencing itself via z.set(Node).optional() or z.map(..., Node).optional() without being registered in the top-level schema), an actionable error is immediately thrown:

      Recursive type reference detected in schema. Register the recursive type by name in the schema object to allow named type reference emission.

    • When callers register the recursive type by name (schema: { Node, ... }), namedTypes resolves the reference cleanly to emit globalThis.Set<Node> / globalThis.Map<string, Node>.
    • Added regression tests for both Set and Map verifying both the diagnostic error on unregistered recursive types and valid compilation when registered by name.

Verification

  • npm run build-all: Clean build across core and all sample workspaces.
  • npm test: 386 tests pass (up from 379, 7 new tests passed, 0 failed across 67 suites).

The changes have been pushed to the PR branch. Ready for your review!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants