Repository navigation
fix(ts): accept serialized string enum values #471
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
e2f3f7b
2634316
2629793
05788e4
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -48,6 +48,92 @@ export interface Point { | |
| y: number; | ||
| }`; | ||
|
|
||
| // Schemas for serialized string-enum validation. | ||
| const stringEnumSchema = ` | ||
| export enum Currency { | ||
| USD = "USD", | ||
| EUR = "EUR" | ||
| } | ||
| export interface Order { | ||
| currency: Currency; | ||
| }`; | ||
|
|
||
| const differingEnumValueSchema = ` | ||
| export enum Plan { | ||
| Basic = "basic", | ||
| Pro = "pro" | ||
| } | ||
| export interface Subscription { | ||
| plan: Plan; | ||
| }`; | ||
|
|
||
| const nestedEnumSchema = ` | ||
| export enum Status { | ||
| Active = "active", | ||
| Paused = "paused" | ||
| } | ||
| export interface Item { | ||
| status: Status; | ||
| } | ||
| export interface Batch { | ||
| primary: Item; | ||
| items: Item[]; | ||
| lookup: { [id: string]: Status }; | ||
| result: { ok: true; value: Status } | { ok: false; error: string }; | ||
| }`; | ||
|
|
||
| const enumMemberTypeSchema = ` | ||
| export enum Currency { | ||
| USD = "USD", | ||
| EUR = "EUR" | ||
| } | ||
| export type EuropeanCurrency = Currency.EUR; | ||
| export interface Payment { | ||
| currency: EuropeanCurrency; | ||
| }`; | ||
|
|
||
| const numericEnumSchema = ` | ||
| export enum Priority { | ||
| Low, | ||
| Medium, | ||
| High | ||
| } | ||
| export interface Config { | ||
| priority: Priority; | ||
| count: number; | ||
| }`; | ||
|
|
||
| const computedStringEnumSchema = ` | ||
| export enum Currency { | ||
| Euro = "E" + "UR" | ||
| } | ||
| export interface Order { | ||
| currency: Currency; | ||
| }`; | ||
|
|
||
| const callableSchema = ` | ||
| export interface Response { | ||
| callback: () => string; | ||
| factory: new () => { ok: boolean }; | ||
| }`; | ||
|
|
||
| const promiseSchema = ` | ||
| export interface Response { | ||
| value: Promise<string>; | ||
| }`; | ||
|
|
||
| const genericWrapperSchema = ` | ||
| export interface Metadata { | ||
| m1: string; m2: string; m3: string; m4: string; | ||
| m5: string; m6: string; m7: string; | ||
| } | ||
| export interface Wrapper<T> { | ||
| a: string; b: string; c: string; d: string; | ||
| e: string; f: string; g: string; payload: T; | ||
| } | ||
| export type Response = Wrapper<Metadata>; | ||
| `; | ||
|
|
||
| // --------------------------------------------------------------------------- | ||
| // Helper | ||
| // --------------------------------------------------------------------------- | ||
|
|
@@ -280,6 +366,100 @@ describe("createTypeScriptJsonValidator", () => { | |
| }); | ||
| }); | ||
|
|
||
| describe("serialized string enum values", () => { | ||
| it("accepts a valid serialized string-enum value", () => { | ||
| const v = validatorFor(stringEnumSchema, "Order"); | ||
| const result = v.validate({ currency: "EUR" }); | ||
| assert.ok(result.success, `expected validation to succeed, got: ${result.success ? "" : result.message}`); | ||
| }); | ||
|
|
||
| it("rejects unknown values and member names that differ from their values", () => { | ||
| const v = validatorFor(differingEnumValueSchema, "Subscription"); | ||
| const unknown = v.validate({ plan: "enterprise" }); | ||
| assert.ok(!unknown.success, "expected an unknown enum value to fail"); | ||
| assert.match(unknown.message, /not assignable/); | ||
|
|
||
| const memberName = v.validate({ plan: "Basic" }); | ||
| assert.ok(!memberName.success, "expected an enum member name to fail when it differs from the value"); | ||
| assert.match(memberName.message, /not assignable/); | ||
| }); | ||
|
Comment on lines
+376
to
+385
|
||
|
|
||
| it("validates enums in nested objects, arrays, unions, and index signatures", () => { | ||
| const v = validatorFor(nestedEnumSchema, "Batch"); | ||
| const valid = v.validate({ | ||
| primary: { status: "active" }, | ||
| items: [{ status: "paused" }, { status: "active" }], | ||
| lookup: { first: "active", second: "paused" }, | ||
| result: { ok: true, value: "active" } | ||
| }); | ||
| assert.ok(valid.success, `expected nested enum values to pass, got: ${valid.success ? "" : valid.message}`); | ||
|
|
||
| const invalid = v.validate({ | ||
| primary: { status: "active" }, | ||
| items: [{ status: "unknown" }], | ||
| lookup: { first: "active" }, | ||
| result: { ok: false, error: "failed" } | ||
| }); | ||
| assert.ok(!invalid.success, "expected an unknown nested enum value to fail"); | ||
| assert.match(invalid.message, /not assignable/); | ||
| }); | ||
|
|
||
|
|
||
| it("accepts serialized values for an individual enum-member type", () => { | ||
| const v = validatorFor(enumMemberTypeSchema, "Payment"); | ||
| const valid = v.validate({ currency: "EUR" }); | ||
| assert.ok(valid.success, `expected enum-member value to pass, got: ${valid.success ? "" : valid.message}`); | ||
|
|
||
| const invalid = v.validate({ currency: "USD" }); | ||
| assert.ok(!invalid.success, "expected a different enum member to fail"); | ||
| assert.match(invalid.message, /not assignable/); | ||
| }); | ||
|
|
||
| it("preserves numeric enum validation", () => { | ||
| const v = validatorFor(numericEnumSchema, "Config"); | ||
| const valid = v.validate({ priority: 1, count: 2 }); | ||
| assert.ok(valid.success, `expected numeric enum value to pass, got: ${valid.success ? "" : valid.message}`); | ||
|
|
||
| const invalid = v.validate({ priority: 3, count: 2 }); | ||
| assert.ok(!invalid.success, "expected a value outside the numeric enum to fail"); | ||
| assert.match(invalid.message, /not assignable/); | ||
| }); | ||
|
|
||
| it("does not hide unrelated type errors", () => { | ||
| const v = validatorFor(numericEnumSchema, "Config"); | ||
| const result = v.validate({ priority: 1, count: "two" }); | ||
| assert.ok(!result.success, "expected an unrelated type error to fail validation"); | ||
| assert.match(result.message, /not assignable/); | ||
| }); | ||
|
|
||
| it("supports constant-folded string enum values", () => { | ||
| const v = validatorFor(computedStringEnumSchema, "Order"); | ||
| const valid = v.validate({ currency: "EUR" }); | ||
| assert.ok(valid.success, `expected constant-folded enum value to pass, got: ${valid.success ? "" : valid.message}`); | ||
|
|
||
| const invalid = v.validate({ currency: "USD" }); | ||
| assert.ok(!invalid.success, "expected a value not produced by the computed member to fail"); | ||
| assert.match(invalid.message, /not assignable/); | ||
| }); | ||
|
|
||
| it("preserves rejection of call and construct signatures", () => { | ||
| const v = validatorFor(callableSchema, "Response"); | ||
| const callback = v.validate({ callback: {}, factory: { ok: true } }); | ||
| assert.ok(!callback.success, "expected an empty object not to satisfy a call signature"); | ||
| assert.match(callback.message, /not assignable/); | ||
|
|
||
| const factory = v.validate({ callback: () => "ok", factory: {} }); | ||
| assert.ok(!factory.success, "expected an empty object not to satisfy a construct signature"); | ||
| assert.match(factory.message, /not assignable/); | ||
|
Comment on lines
+445
to
+452
|
||
| }); | ||
|
|
||
| it("preserves rejection of Promise-shaped objects with non-callable methods", () => { | ||
| const v = validatorFor(promiseSchema, "Response"); | ||
| const result = v.validate({ value: { then: {}, catch: {} } }); | ||
| assert.ok(!result.success, "expected non-callable then/catch methods to fail"); | ||
| assert.match(result.message, /not assignable/); | ||
| }); | ||
| }); | ||
|
|
||
| describe("type mismatch errors (backward-compatible: unchanged code path)", () => { | ||
| it("reports a type error when a property has the wrong type", () => { | ||
| const v = validatorFor(smallSchema, "Point"); | ||
|
|
@@ -388,7 +568,32 @@ describe("createTypeScriptJsonValidator", () => { | |
| const result = v.createModuleTextFromJson({ x: 1, y: 2 }); | ||
| assert.ok(result.success, "expected module text creation to succeed"); | ||
| assert.ok(result.data.includes("import { Point } from './schema'")); | ||
| assert.ok(result.data.includes("const json: Point =")); | ||
| assert.ok(result.data.includes("type __TypeChatJsonWire<T> = T extends string")); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Make this assertion independent of helper formatting. The latest commit emits From the TypeScript package directory, the focused reproduction is: npm run build
npm exec --no -- tsc -p test
node --test --test-name-pattern="produces valid TypeScript module text for a simple object" .\out\validate.test.jsIt fails at this assertion with const assert = require("node:assert/strict");
const { createTypeScriptJsonValidator } = require("typechat/ts");
const validator = createTypeScriptJsonValidator(
"export interface Point { x: number; y: number; }",
"Point"
);
try {
const result = validator.createModuleTextFromJson({ x: 1, y: 2 });
assert.ok(result.success);
console.log(JSON.stringify(result.data));
assert.ok(
result.data.includes("type __TypeChatJsonWire<T> = T extends string")
);
} finally {
validator.close();
}Please use a whitespace-independent assertion, for example: assert.match(result.data, /type __TypeChatJsonWire<T>\s*=\s*T extends string/);On Node 24.22.1 / TypeScript 7.0.2, the full focused validator file currently has 59 passes and this one failure. Please rerun it after the update and refresh the PR's validation results. |
||
| assert.ok(result.data.includes("const json: __TypeChatJsonWire<Point> =")); | ||
| }); | ||
| }); | ||
|
|
||
| describe("missing-property diagnostics with custom module text", () => { | ||
| it("keeps a custom generic annotation as the diagnostic target", () => { | ||
| const v = validatorFor<Record<string, unknown>>(genericWrapperSchema, "Response"); | ||
| v.createModuleTextFromJson = value => ({ | ||
| success: true, | ||
| data: `import { Wrapper, Metadata } from './schema';\n` + | ||
| `const json: Wrapper<Metadata> = ${JSON.stringify(value)};` | ||
| }); | ||
| const result = v.validate({ | ||
| payload: { m1: "", m2: "", m3: "", m4: "", m5: "", m6: "", m7: "" } | ||
| }); | ||
| assert.ok(!result.success, "expected the missing wrapper fields to fail validation"); | ||
| assert.match(result.message, /Wrapper<Metadata>/); | ||
| assert.ok( | ||
| result.message.includes(": a, b, c, d, e, f, g"), | ||
| `expected all missing wrapper properties, got: ${result.message}` | ||
| ); | ||
| assert.ok( | ||
| !result.message.includes("from type 'Metadata'"), | ||
| `diagnostic must not target the unwrapped Metadata type, got: ${result.message}` | ||
| ); | ||
| }); | ||
| }); | ||
|
|
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Preserve class-instance constraints when recursively normalizing enum values.
keyof Texcludes private/protected members, so rebuilding every object as a mapped type also strips class-instance constraints. This is another case where normalization accepts JSON that the original schema rejects, even when there are no enums.From the TypeScript package directory, run
npm run build, then save the following asrepro-enum-wire.cjsin that directory and runnode repro-enum-wire.cjs:On
05788e4, the first result hassuccess: true. The control hassuccess: falsewith:The expected behavior is rejection in both cases: this JSON does not satisfy the original
Tokentype. Please preserve that rejection while normalizing enums, and add negative regression coverage for class-instance constraints in an enum-free schema. Keep the existing serialized-enum cases passing.