diff --git a/site/src/docs/typescript/basic-usage.md b/site/src/docs/typescript/basic-usage.md index 1da0adb3..5e0df32b 100644 --- a/site/src/docs/typescript/basic-usage.md +++ b/site/src/docs/typescript/basic-usage.md @@ -308,6 +308,31 @@ const validator = createTypeScriptJsonValidator(schema, "Sent We provided the text of the schema and the name of the type we want returned data to satisfy. We also have to provide the type argument `SentimentResponse` to explain what data shape we expect (though note that this is a bit like a type cast and isn't guaranteed). +#### String enums + +JSON represents a TypeScript string enum using the member's value, not its name. The TypeScript validator +normalizes string-enum types to their literal values before validating, including when they appear in nested +objects, arrays, unions, and index signatures. + +```ts +export enum Currency { + USD = "USD", + EUR = "EUR" +} + +export interface Order { + currency: Currency; +} +``` + +The JSON `{ "currency": "EUR" }` is valid, while `{ "currency": "GBP" }` is not. If a member's name and value +differ, such as `Basic = "basic"`, JSON must use `"basic"`; `"Basic"` is rejected. Numeric enums keep their +existing numeric validation behavior. + +Members initialized with compile-time string expressions, such as `Euro = "E" + "UR"`, are supported when +TypeScript resolves the value to a string literal. Computed members without a compile-time literal type should be +modeled with a string literal union instead. + ### Zod Validators If you chose to define your schema with Zod, you can use the `createZodJsonValidator` function: diff --git a/typescript/src/ts/validate.ts b/typescript/src/ts/validate.ts index 550d6158..59e887b3 100644 --- a/typescript/src/ts/validate.ts +++ b/typescript/src/ts/validate.ts @@ -40,6 +40,29 @@ const schemaFileName = "/schema.ts"; const jsonFileName = "/json.ts"; const schemaValidationFileName = "/schema-validation.ts"; +/** + * Returns a type alias name that does not collide with identifiers in the schema. + */ +function createUniqueJsonWireTypeName(schemaText: string): string { + let name = "__TypeChatJsonWire"; + while (schemaText.includes(name)) { + name += "_"; + } + return name; +} + +/** + * Maps serialized string-enum values back to their literal enum member types while preserving the + * rest of the schema's structure. + */ +function createJsonWireTypeDefinition(typeName: string): string { + return `type ${typeName} = + T extends string ? \`\${T}\` : + T extends (...args: any[]) => any ? T : + T extends abstract new (...args: any[]) => any ? T : + T extends object ? { [K in keyof T]: ${typeName} } : T;`; +} + /** * Represents an object that can validate JSON strings according to a given TypeScript schema. */ @@ -96,6 +119,7 @@ export function createTypeScriptJsonValidator( throw new Error("The TypeScript virtual file system doesn't support writing files."); } const writeFile = fileSystem.writeFile; + const jsonWireTypeName = createUniqueJsonWireTypeName(schema); let schemaValidationResult: Result | undefined; const validator: TypeScriptJsonValidatorWithSchemaValidation = { getSchemaText: () => schema, @@ -241,7 +265,14 @@ export function createTypeScriptJsonValidator( // Use getStart() to exclude leading trivia from the range check. if (decl.getStart(file) <= position && position <= decl.end && decl.type && isTypeReferenceNode(decl.type) && decl.initializer) { - const targetType = checker.getTypeAtLocation(decl.type); + // Only the declaration generated by this validator wraps the schema type in + // the JsonWire helper. A custom createModuleTextFromJson may use any generic + // annotation, so unwrap only our own helper and keep other targets intact. + const isJsonWireReference = decl.type.typeName.getText(file) === jsonWireTypeName; + const targetTypeNode = isJsonWireReference + ? decl.type.typeArguments?.[0] ?? decl.type + : decl.type; + const targetType = checker.getTypeAtLocation(targetTypeNode); const sourceType = checker.getTypeAtLocation(decl.initializer); if (!targetType || !sourceType) { continue; @@ -263,6 +294,9 @@ export function createTypeScriptJsonValidator( } function createModuleTextFromJson(jsonObject: object) { - return success(`import { ${typeName} } from './schema';\nconst json: ${typeName} = ${JSON.stringify(jsonObject, undefined, 2)};\n`); + // String enums do not accept their serialized values in a normal enum-typed assignment. + // The JsonWire helper maps each string literal back to itself while recursively preserving + // object, array, tuple, optional-property, and union shapes. Numeric enums remain unchanged. + return success(`import { ${typeName} } from './schema';\n${createJsonWireTypeDefinition(jsonWireTypeName)}\nconst json: ${jsonWireTypeName}<${typeName}> = ${JSON.stringify(jsonObject, undefined, 2)};\n`); } } diff --git a/typescript/test/validate.test.ts b/typescript/test/validate.test.ts index cfdece22..df5c79ad 100644 --- a/typescript/test/validate.test.ts +++ b/typescript/test/validate.test.ts @@ -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; +}`; + +const genericWrapperSchema = ` +export interface Metadata { + m1: string; m2: string; m3: string; m4: string; + m5: string; m6: string; m7: string; +} +export interface Wrapper { + a: string; b: string; c: string; d: string; + e: string; f: string; g: string; payload: T; +} +export type Response = Wrapper; +`; + // --------------------------------------------------------------------------- // 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/); + }); + + 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/); + }); + + 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 extends string")); + assert.ok(result.data.includes("const json: __TypeChatJsonWire =")); + }); + }); + + describe("missing-property diagnostics with custom module text", () => { + it("keeps a custom generic annotation as the diagnostic target", () => { + const v = validatorFor>(genericWrapperSchema, "Response"); + v.createModuleTextFromJson = value => ({ + success: true, + data: `import { Wrapper, Metadata } from './schema';\n` + + `const json: Wrapper = ${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/); + 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}` + ); }); });