diff --git a/site/src/docs/typescript/basic-usage.md b/site/src/docs/typescript/basic-usage.md index 5e0df32b..5c46bdbb 100644 --- a/site/src/docs/typescript/basic-usage.md +++ b/site/src/docs/typescript/basic-usage.md @@ -329,6 +329,11 @@ The JSON `{ "currency": "EUR" }` is valid, while `{ "currency": "GBP" }` is not. differ, such as `Basic = "basic"`, JSON must use `"basic"`; `"Basic"` is rejected. Numeric enums keep their existing numeric validation behavior. +String values are matched exactly by their UTF-16 code units. BOMs are not removed and Unicode +normalization is not applied. Use Unicode escape sequences for lone surrogates in schema source, +for example `"\uD800\uFEFFx"`. When constructing schema text in JavaScript, use `String.raw` or escaped +backslashes so the compiler receives these escapes rather than raw lone-surrogate characters. + 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. diff --git a/typescript/src/ts/validate.ts b/typescript/src/ts/validate.ts index 99976f66..4d7a3f46 100644 --- a/typescript/src/ts/validate.ts +++ b/typescript/src/ts/validate.ts @@ -1,8 +1,8 @@ // TODO: Revisit these `typescript/unstable/*` imports once a stable API is available. import { API, NodeBuilderFlags, SymbolFlags, type Checker, type Diagnostic } from 'typescript/unstable/sync'; import { createVirtualFileSystem } from 'typescript/unstable/fs'; -import type { Node, SourceFile } from 'typescript/unstable/ast'; -import { isEnumDeclaration, isTypeReferenceNode, isVariableStatement } from 'typescript/unstable/ast/is'; +import type { EnumDeclaration, Node, SourceFile } from 'typescript/unstable/ast'; +import { isEnumDeclaration, isIdentifier, isTypeAliasDeclaration, isTypeReferenceNode, isVariableStatement } from 'typescript/unstable/ast/is'; import { Result, success, error } from '../result.js'; import { typeChatSchemaValidation, type TypeChatJsonValidator } from "../typechat.js"; @@ -46,7 +46,7 @@ const schemaValidationFileName = "/schema-validation.ts"; function createUniqueJsonWireTypeName( schemaText: string, importedTypeName: string, - stringEnumValues: readonly string[] + stringEnumTypeTexts: readonly string[] ): string { let name = "__TypeChatJsonWire"; while ( @@ -58,41 +58,21 @@ function createUniqueJsonWireTypeName( schemaText.includes(`${name}Enum`) || schemaText.includes(`${name}Object`) || schemaText.includes(`${name}Shape`) || - stringEnumValues.some(value => value.includes(name)) + stringEnumTypeTexts.some(typeText => typeText.includes(name)) ) { name += "_"; } return name; } -/** - * Collects the string values declared by enums in the schema. Limiting the JSON wire mapping to - * these values leaves branded and opaque string types untouched. - */ -function getStringEnumValues(checker: Checker, sourceFile: SourceFile): string[] { - const values = new Set(); - sourceFile.forEachChild(function visit(node: Node) { - if (isEnumDeclaration(node)) { - for (const member of node.members) { - const value = checker.getConstantValue(member); - if (typeof value === "string") { - values.add(value); - } - } - } - node.forEachChild(visit); - }); - return [...values]; -} - /** * Maps serialized string-enum values back to their literal enum member types while preserving the * rest of the schema's structure. Class instances with private or protected members are left * unchanged because mapping their public keys would drop the nominal constraint that rejects * plain JSON objects. */ -function createJsonWireTypeDefinition(typeName: string, stringEnumValues: readonly string[]): string { - const enumValues = stringEnumValues.map(value => JSON.stringify(value)).join(" | "); +function createJsonWireTypeDefinition(typeName: string, stringEnumTypeTexts: readonly string[]): string { + const enumValues = stringEnumTypeTexts.join(" | "); // Intersecting an all-optional mapped shape with `object` disables TypeScript's weak-type // check. Keep the constraint when an explicit intersection accepts arrays, or when the mapped // shape would newly accept a primitive that the original type rejects. Ordinary weak shapes @@ -180,14 +160,16 @@ export function createTypeScriptJsonValidator( const initialSnapshot = api.updateSnapshot({ openProjects: [configFileName] }); const schemaProject = initialSnapshot.getProject(configFileName); const schemaSourceFile = schemaProject?.program.getSourceFile(schemaFileName); - const stringEnumValues = schemaProject && schemaSourceFile - ? getStringEnumValues(schemaProject.checker, schemaSourceFile) - : []; - const jsonWireTypeName = createUniqueJsonWireTypeName(schema, typeName, stringEnumValues); - const jsonWireTypeDefinition = stringEnumValues.length - ? createJsonWireTypeDefinition(jsonWireTypeName, stringEnumValues) + const stringEnumTypeTextsResult = schemaProject && schemaSourceFile + ? getStringEnumTypeTexts(schemaProject.checker, schemaSourceFile) + : error("The TypeScript schema file couldn't be loaded."); + const stringEnumTypeTexts = stringEnumTypeTextsResult.success ? stringEnumTypeTextsResult.data : []; + const stringEnumTypeError = stringEnumTypeTextsResult.success ? undefined : stringEnumTypeTextsResult.message; + const jsonWireTypeName = createUniqueJsonWireTypeName(schema, typeName, stringEnumTypeTexts); + const jsonWireTypeDefinition = stringEnumTypeTexts.length + ? createJsonWireTypeDefinition(jsonWireTypeName, stringEnumTypeTexts) : ""; - const jsonWireEnumValues = stringEnumValues.map(value => JSON.stringify(value)).join(" | "); + const jsonWireEnumValues = stringEnumTypeTexts.join(" | "); let schemaValidationResult: Result | undefined; const validator: TypeScriptJsonValidatorWithSchemaValidation = { getSchemaText: () => schema, @@ -199,6 +181,94 @@ export function createTypeScriptJsonValidator( }; return validator; + /** + * Formats enum values as literal type text inside the compiler. Reading native API literal + * values can corrupt lone surrogates or remove BOMs. Only enum declarations contribute values, + * so branded and opaque strings retain their constraints. + */ + function getStringEnumTypeTexts(checker: Checker, sourceFile: SourceFile): Result { + const declarations: EnumDeclaration[] = []; + const identifiers = new Set(); + sourceFile.forEachChild(function visit(node: Node) { + if (isIdentifier(node)) { + identifiers.add(node.text); + } + if (isEnumDeclaration(node) && checker.getTypeAtLocation(node.members) + .some(type => type?.isStringLiteralType())) { + declarations.push(node); + } + node.forEachChild(visit); + }); + if (!declarations.length) { + return success([]); + } + + const aliases = new Set(); + let querySchema = schema; + for (const declaration of declarations.sort((a, b) => b.getEnd() - a.getEnd())) { + let name = `__TypeChatEnumValues${aliases.size}`; + while (identifiers.has(name)) { + name += "_"; + } + identifiers.add(name); + aliases.add(name); + // Keep each query in the enum's lexical scope, including private namespace enums. + const insertion = `\ntype ${name} = \`\${${declaration.name.text} & string}\`;\n`; + const end = declaration.getEnd(); + querySchema = querySchema.slice(0, end) + insertion + querySchema.slice(end); + } + + writeFile(schemaFileName, querySchema); + try { + const snapshot = api.updateSnapshot({ fileChanges: { changed: [schemaFileName] } }); + const project = snapshot.getProject(configFileName); + if (!project) { + return error(`The TypeScript string-enum query project '${configFileName}' couldn't be loaded.`); + } + const queryFile = project.program.getSourceFile(schemaFileName); + if (!queryFile) { + return error("The TypeScript string-enum query file couldn't be loaded."); + } + const typeTexts = new Set(); + const foundAliases = new Set(); + let queryError: string | undefined; + queryFile.forEachChild(function visit(node: Node) { + if (queryError !== undefined) { + return; + } + if (isTypeAliasDeclaration(node) && aliases.has(node.name.text)) { + foundAliases.add(node.name.text); + const type = project.checker.getTypeAtLocation(node); + if (!type) { + queryError = `The TypeScript string-enum query '${node.name.text}' couldn't be resolved.`; + return; + } + const constituents = type.isUnionType() ? type.getTypes() : [type]; + for (const constituent of constituents) { + if (!constituent.isStringLiteralType()) { + queryError = `The TypeScript string-enum query '${node.name.text}' didn't resolve to string literal types.`; + return; + } + typeTexts.add(project.checker.typeToString( + constituent, undefined, NodeBuilderFlags.NoTruncation + )); + } + } + node.forEachChild(visit); + }); + if (queryError !== undefined) { + return error(queryError); + } + if (foundAliases.size !== aliases.size) { + return error("The TypeScript string-enum query aliases couldn't be loaded."); + } + return success([...typeTexts]); + } finally { + writeFile(schemaFileName, schema); + api.updateSnapshot({ fileChanges: { changed: [schemaFileName] } }); + } + } + function validateSchema(): Result { if (schemaValidationResult) { return schemaValidationResult; @@ -244,7 +314,9 @@ export function createTypeScriptJsonValidator( ) .join("\n") ) - : success(undefined); + : stringEnumTypeError !== undefined + ? error(stringEnumTypeError) + : success(undefined); return schemaValidationResult; } @@ -286,6 +358,9 @@ export function createTypeScriptJsonValidator( }).join("\n"); return error(diagnostics, { data: jsonObject }); } + if (stringEnumTypeError !== undefined) { + return error(stringEnumTypeError, { data: jsonObject }); + } return success(jsonObject as T); } diff --git a/typescript/test/validate.test.ts b/typescript/test/validate.test.ts index 931f4cd4..5424e49a 100644 --- a/typescript/test/validate.test.ts +++ b/typescript/test/validate.test.ts @@ -610,6 +610,293 @@ describe("createTypeScriptJsonValidator", () => { assert.ok(result.success, `expected validation to succeed, got: ${result.success ? "" : result.message}`); }); + describe("Unicode enum values", () => { + const cases = [ + { + name: "high lone surrogate without BOM", + value: "\ud800x", + invalid: ["x", "\ufffdx", "\ufffd\ufffd\ufffdx"] + }, + { + name: "low lone surrogate without BOM", + value: "\udc00x", + invalid: ["x", "\ufffdx", "\ufffd\ufffd\ufffdx"] + }, + { + name: "high lone surrogate followed by BOM", + value: "\ud800\uFEFFx", + invalid: ["\ud800x", "\ufffd\uFEFFx", "\ufffd\ufffd\ufffd\uFEFFx"] + }, + { + name: "low lone surrogate followed by BOM", + value: "\udc00\uFEFFx", + invalid: ["\udc00x", "\ufffd\uFEFFx", "\ufffd\ufffd\ufffd\uFEFFx"] + }, + { + name: "ordinary prefix before a lone surrogate and BOM", + value: "a\ud800\uFEFFx", + invalid: ["a\ud800x", "a\ufffd\uFEFFx"] + }, + { + name: "BOM before a lone surrogate", + value: "\uFEFF\ud800x", + invalid: ["\ud800x", "\uFEFF\ufffdx"] + }, + { + name: "BOM between surrogate code units", + value: "\ud800\uFEFF\udc00", + invalid: ["\ud800\udc00", "\ufffd\uFEFF\ufffd"] + }, + { + name: "multiple lone-surrogate segments", + value: "\ud800\uFEFFx\udc00\uFEFFy", + invalid: ["\ud800x\udc00y", "\ufffd\uFEFFx\ufffd\uFEFFy"] + }, + { + name: "repeated BOMs after a lone surrogate", + value: "\ud800\uFEFF\uFEFFx", + invalid: ["\ud800\uFEFFx", "\ud800x"] + }, + { + name: "trailing BOM after a lone surrogate", + value: "\ud800\uFEFF", + invalid: ["\ud800", "\ufffd\uFEFF"] + }, + { + name: "leading BOM control", + value: "\uFEFFx", + invalid: ["x", "\uFEFF"] + }, + { + name: "BOM-only control", + value: "\uFEFF", + invalid: ["", "\uFEFF\uFEFF"] + }, + { + name: "ordinary middle BOM control", + value: "a\uFEFFb", + invalid: ["ab", "a\uFEFFc"] + }, + { + name: "astral Unicode control", + value: "\ud83d\ude00\uFEFFx", + invalid: ["\ud83d\ude00x", "\ufffd\ufffd\uFEFFx"] + }, + { + name: "canonical Unicode control", + value: "\u00e9x", + invalid: ["e\u0301x", "ex"] + }, + { + name: "escaped control characters", + value: "\ud800\uFEFF\v\0\"\\\n", + invalid: ["\ud800\v\0\"\\\n", "\ufffd\uFEFF\v\0\"\\\n"] + }, + { + name: "long literal without truncation", + value: "x".repeat(600) + "\ud800\uFEFF", + invalid: ["x".repeat(599) + "\ud800\uFEFF", "x".repeat(600) + "\ud800"] + } + ]; + + for (const { name, value, invalid } of cases) { + for (const encoding of ["JSON", "Unicode-escaped"]) { + it(`preserves ${name} in a ${encoding} schema literal`, () => { + const jsonLiteral = JSON.stringify(value); + const literal = encoding === "JSON" ? jsonLiteral : jsonLiteral.replace( + /[\u0080-\uffff]/g, + character => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}` + ); + const schema = `export enum E { X = ${literal} }\nexport interface Probe { value: E; }`; + const v = validatorFor(schema, "Probe"); + const preflight = v[typeChatSchemaValidation](); + assert.ok(preflight.success); + assert.equal(v.getSchemaText(), schema); + const candidate = { value }; + const result = v.validate(candidate); + assert.ok(result.success, `expected exact value to pass, got: ${result.success ? "" : result.message}`); + assert.strictEqual(result.data, candidate); + + for (const altered of invalid) { + assert.notEqual(altered, value); + const rejected = v.validate({ value: altered }); + assert.ok(!rejected.success, `expected altered value ${JSON.stringify(altered)} to fail`); + assert.match(rejected.message, /not assignable/); + } + assert.strictEqual(v[typeChatSchemaValidation](), preflight); + }); + } + } + + it("preserves folded members and heterogeneous numeric enum constraints", () => { + const v = validatorFor(String.raw` +export enum E { + Prefix = "\ud800", + X = Prefix + "\uFEFFx", + Small = .1, + Large = 1e20 +} +export interface Probe { value: E.X; small: E.Small; large: E.Large; }`, "Probe"); + assert.ok(v[typeChatSchemaValidation]().success); + const candidate = { value: "\ud800\uFEFFx", small: 0.1, large: 1e20 }; + const result = v.validate(candidate); + assert.ok(result.success, `expected folded value to pass, got: ${result.success ? "" : result.message}`); + assert.strictEqual(result.data, candidate); + for (const invalid of [ + { ...candidate, value: "\ud800" }, + { ...candidate, value: "\ud800x" }, + { ...candidate, small: 1 }, + { ...candidate, small: "0.1" }, + { ...candidate, large: 1e19 } + ]) { + assert.ok(!v.validate(invalid).success); + } + }); + + for (const declaration of ["enum", "const enum"]) { + it(`preserves merged ${declaration} declarations`, () => { + const schema = String.raw`export ${declaration} E { X = "\ud800\uFEFFx" } +export ${declaration} E { Y = "\udc00\uFEFFy" } +export interface Probe { value: E; first: E.X; }`; + const v = validatorFor(schema, "Probe"); + assert.ok(v[typeChatSchemaValidation]().success); + assert.ok(v.validate({ value: "\udc00\uFEFFy", first: "\ud800\uFEFFx" }).success); + assert.ok(!v.validate({ value: "\udc00y", first: "\ud800\uFEFFx" }).success); + assert.ok(!v.validate({ value: "\udc00\uFEFFy", first: "\udc00\uFEFFy" }).success); + }); + } + + it("preserves string members alongside computed numeric members", () => { + const v = validatorFor(String.raw` +declare function numericValue(): number; +export enum E { X = "\ud800\uFEFFx", Numeric = numericValue() } +export interface Probe { value: E.X; }`, "Probe"); + assert.ok(v[typeChatSchemaValidation]().success); + assert.ok(v.validate({ value: "\ud800\uFEFFx" }).success); + assert.ok(!v.validate({ value: "\ud800x" }).success); + }); + + it("preserves branded literals that match an enum value", () => { + const v = validatorFor(String.raw` +export enum E { X = "\ud800\uFEFFx" } +type Id = "\ud800\uFEFFx" & { readonly __brand: "Id" }; +export interface Probe { value: E; id: Id; }`, "Probe"); + assert.ok(v[typeChatSchemaValidation]().success); + const result = v.validate({ value: "\ud800\uFEFFx", id: "\ud800\uFEFFx" }); + assert.ok(!result.success); + assert.match(result.message, /not assignable/); + }); + + it("preserves source positions after a file BOM and astral Unicode", () => { + const schema = "\uFEFF// \u00e9 \ud83d\ude00\n" + String.raw` +export enum \u{10400} { X = "\ud800\uFEFFx" } +export interface Probe { value: \u{10400}; }`; + const v = validatorFor(schema, "Probe"); + assert.ok(v[typeChatSchemaValidation]().success); + assert.ok(v.validate({ value: "\ud800\uFEFFx" }).success); + assert.ok(!v.validate({ value: "\ud800x" }).success); + assert.equal(v.getSchemaText(), schema); + }); + + it("preserves private namespace enums in nested containers and member types", () => { + const v = validatorFor(String.raw` +namespace Outer { + enum E { X = "\ud800\uFEFFx", Y = "\udc00\uFEFFy" } + export interface Shape { + primary: { value: E.X }; + pair: readonly [E.X, E.Y]; + list: E[]; + lookup: Record; + choice: { ok: true; value: E.X } | { ok: false; value: E.Y }; + } +} +export interface Probe { payload: Outer.Shape; }`, "Probe"); + const x = "\ud800\uFEFFx"; + const y = "\udc00\uFEFFy"; + const payload = { + primary: { value: x }, + pair: [x, y], + list: [x, y], + lookup: { first: x, second: y }, + choice: { ok: true, value: x } + }; + const candidate = { payload }; + const result = v.validate(candidate); + assert.ok(result.success, `expected nested values to pass, got: ${result.success ? "" : result.message}`); + assert.strictEqual(result.data, candidate); + for (const invalid of [ + { ...payload, primary: { value: "\ud800x" } }, + { ...payload, pair: [x, "\udc00y"] }, + { ...payload, list: [x, "\ufffd\uFEFFy"] }, + { ...payload, lookup: { first: "\ud800x" } }, + { ...payload, choice: { ok: true, value: y } } + ]) { + assert.ok(!v.validate({ payload: invalid }).success); + } + }); + + it("avoids collisions with escaped enum and query identifiers", () => { + const schema = String.raw` +type \u005f_TypeChatEnumValues0 = number; +export enum \u0045 { X = "\ud800\uFEFFx" } +export interface Probe { value: E; }`; + const v = validatorFor(schema, "Probe"); + assert.ok(v[typeChatSchemaValidation]().success); + assert.ok(v.validate({ value: "\ud800\uFEFFx" }).success); + assert.equal(v.getSchemaText(), schema); + const module = v.createModuleTextFromJson({ value: "\ud800\uFEFFx" }); + assert.ok(module.success); + assert.ok(!module.data.includes("__TypeChatEnumValues")); + }); + + it("does not truncate large enum unions", () => { + const members = Array.from( + { length: 150 }, + (_, index) => `M${index} = ${JSON.stringify(`value-${index}\ud800\uFEFF`)}` + ).join(",\n"); + const v = validatorFor( + `export enum E { ${members} }\nexport interface Probe { value: E; }`, + "Probe" + ); + assert.ok(v.validate({ value: "value-149\ud800\uFEFF" }).success); + assert.ok(!v.validate({ value: "value-150\ud800\uFEFF" }).success); + }); + + it("preserves original schema diagnostics after enum queries", () => { + const schema = String.raw`export enum E { X = "\ud800\uFEFFx" } +export interface Probe { value: E; missing: MissingType; }`; + const v = validatorFor(schema, "Probe"); + const result = v[typeChatSchemaValidation](); + assert.ok(!result.success); + assert.match(result.message, /schema\.ts\(2,\d+\):.*MissingType/); + assert.ok(!result.message.includes("__TypeChatEnumValues")); + assert.equal(v.getSchemaText(), schema); + const invalid = v.validate({ value: "\ud800\uFEFFx", missing: {} }); + assert.ok(!invalid.success); + assert.match(invalid.message, /MissingType/); + }); + + it("repairs an altered enum value without changing exact code units", async () => { + const v = validatorFor(String.raw` +export enum E { X = "\ud800\uFEFFx" } +export interface Probe { value: E; }`, "Probe"); + let modelCalls = 0; + const translator = createJsonTranslator({ + async complete() { + modelCalls++; + return { + success: true as const, + data: JSON.stringify({ value: modelCalls === 1 ? "\ud800x" : "\ud800\uFEFFx" }) + }; + } + }, v); + const result = await translator.translate("test request"); + assert.ok(result.success, `expected repair to succeed, got: ${result.success ? "" : result.message}`); + assert.deepEqual(result.data, { value: "\ud800\uFEFFx" }); + assert.equal(modelCalls, 2); + }); + }); + it("rejects unknown values and member names that differ from their values", () => { const v = validatorFor(differingEnumValueSchema, "Subscription"); const unknown = v.validate({ plan: "enterprise" });