返回源码地图

packages/chord/src/schema.ts

v1.3.0 · 71023aec1546 · 22:规范化、canonical identity与schema

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1import type { TSchema } from "typebox";
2import { Value } from "typebox/value";
3import { type ChordErrorReason, invalid } from "./errors.ts";
4
5/** JSON Schema as data. TypeBox schemas are plain JSON Schema objects. */
6type Schema = { readonly [key: string]: unknown };
7
8const asSchema = (schema: unknown): Schema =>
9 schema !== null && typeof schema === "object" ? (schema as Schema) : schema === false ? { not: {} } : {};
10
11/** Canonical JSON: sorted object keys, `undefined` members dropped. */
12export function canonicalJson(value: unknown): string {
13 if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
14 if (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item)).join(",")}]`;
15 const keys = Object.keys(value)
16 .filter((key) => (value as Record<string, unknown>)[key] !== undefined)
17 .sort();
18 return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJson((value as Record<string, unknown>)[key])}`).join(",")}}`;
19}
20
21/** Non-cryptographic 64-bit hash (two FNV-1a lanes). Contracts are trusted, so collisions are not an attack surface. */
22export function hash64(text: string): string {
23 let a = 0x811c9dc5;
24 let b = 0x01000193 ^ 0x5bd1e995;
25 for (let index = 0; index < text.length; index++) {
26 const code = text.charCodeAt(index);
27 a = Math.imul(a ^ code, 0x01000193);
28 b = Math.imul(b ^ code, 0x5bd1e995) ^ (b >>> 13);
29 }
30 return (a >>> 0).toString(16).padStart(8, "0") + (b >>> 0).toString(16).padStart(8, "0");
31}
32
33export function deepEqual(a: unknown, b: unknown): boolean {
34 return a === b || canonicalJson(a) === canonicalJson(b);
35}
36
37/** Throws `invalid` (with `reason`) and the first schema errors when `value` does not match. */
38export function assertValid(reason: ChordErrorReason, what: string, schema: TSchema, value: unknown): void {
39 if (Value.Check(schema, value)) return;
40 const errors = [...Value.Errors(schema, value)].slice(0, 3);
41 const summary = errors.map((error) => `${error.instancePath || "/"} ${error.message}`).join("; ");
42 throw invalid(reason, `${what}: ${summary}`, errors);
43}
44
45/** Applies defaults, strips unknown fields, validates. Returns a fresh value. */
46export function normalize(schema: TSchema, value: unknown, what: string): unknown {
47 const normalized = Value.Clean(schema, Value.Default(schema, Value.Clone(value ?? {})));
48 assertValid("input", what, schema, normalized);
49 return normalized;
50}
51
52/** Canonical identity of a normalized value: fields equal to their schema default are omitted. */
53export function canonicalIdentity(schema: TSchema, value: unknown): string {
54 return canonicalJson(stripDefaults(asSchema(schema), value));
55}
56
57function stripDefaults(schema: Schema, value: unknown): unknown {
58 if (Array.isArray(value)) {
59 const items = schema.items;
60 if (Array.isArray(items)) return value.map((item, index) => stripDefaults(asSchema(items[index]), item));
61 return value.map((item) => stripDefaults(asSchema(items), item));
62 }
63 if (value === null || typeof value !== "object") return value;
64 const properties = asSchema(schema.properties);
65 const result: Record<string, unknown> = {};
66 for (const [key, item] of Object.entries(value)) {
67 const property = asSchema(properties[key]);
68 if ("default" in property && deepEqual(property.default, item)) continue;
69 result[key] = stripDefaults(property, item);
70 }
71 return result;
72}
73
74const CONSTRAINTS = [
75 "minLength",
76 "maxLength",
77 "pattern",
78 "format",
79 "minimum",
80 "maximum",
81 "exclusiveMinimum",
82 "exclusiveMaximum",
83 "multipleOf",
84 "minItems",
85 "maxItems",
86 "uniqueItems",
87 "minProperties",
88 "maxProperties",
89] as const;
90
91const typesOf = (schema: Schema): string[] | undefined =>
92 typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? (schema.type as string[]) : undefined;
93
94/** Keywords `fits` reasons about. Any other validation keyword in the provider's schema forces exact equality. */
95const KNOWN: ReadonlySet<string> = new Set([
96 ...CONSTRAINTS,
97 "type",
98 "properties",
99 "required",
100 "additionalProperties",
101 "patternProperties",
102 "items",
103 "additionalItems",
104 "const",
105 "enum",
106 "anyOf",
107 "parameters",
108 "returnType",
109]);
110
111/** Annotations: no effect on validity. */
112const ANNOTATIONS: ReadonlySet<string> = new Set([
113 "title",
114 "description",
115 "default",
116 "examples",
117 "$id",
118 "$schema",
119 "$comment",
120 "readOnly",
121 "writeOnly",
122 "deprecated",
123]);
124
125const withoutAnnotations = (schema: Schema): Schema =>
126 Object.fromEntries(Object.entries(schema).filter(([key]) => !ANNOTATIONS.has(key)));
127
128/**
129 * Conservative structural subtyping: true only if every value valid under `sub` is valid under `sup`, where object
130 * fields missing from `sub` but optional in `sup` count as fine (unknown fields are stripped at the provider, see
131 * `RecordImpl.call`). A provider schema using a keyword this function does not model (`not`, `allOf`, `contains`,
132 * `$ref`, ...) or an `additionalProperties` schema only fits an identical consumer schema.
133 */
134export function fits(subSchema: unknown, supSchema: unknown): boolean {
135 const sub = withoutAnnotations(asSchema(subSchema));
136 const sup = withoutAnnotations(asSchema(supSchema));
137 if (Object.keys(sup).length === 0) return true;
138 if (deepEqual(sub, sup)) return true;
139 if (Object.keys(sup).some((key) => !KNOWN.has(key))) return false;
140 if (sup.additionalProperties !== undefined && typeof sup.additionalProperties !== "boolean") return false;
141 if (Array.isArray(sub.anyOf)) return sub.anyOf.every((branch) => fits(branch, sup));
142 if (Array.isArray(sup.anyOf)) return sup.anyOf.some((branch) => fits(sub, branch));
143 if ("const" in sup) return "const" in sub && deepEqual(sub.const, sup.const);
144 if (Array.isArray(sup.enum)) {
145 const values = "const" in sub ? [sub.const] : Array.isArray(sub.enum) ? sub.enum : undefined;
146 return values?.every((item) => (sup.enum as unknown[]).some((allowed) => deepEqual(allowed, item))) ?? false;
147 }
148 for (const key of CONSTRAINTS) if (key in sup && !deepEqual(sub[key], sup[key])) return false;
149 const supTypes = typesOf(sup);
150 const subTypes = typesOf(sub);
151 if (supTypes === undefined || subTypes === undefined) return false;
152 if (!subTypes.every((type) => supTypes.includes(type) || (type === "integer" && supTypes.includes("number")))) {
153 return false;
154 }
155 if ("const" in sub || Array.isArray(sub.enum)) return true;
156 if (subTypes.includes("object") && !objectFits(sub, sup)) return false;
157 if (subTypes.includes("array") && !arrayFits(sub, sup)) return false;
158 if (subTypes.includes("function")) return functionFits(sub, sup);
159 return true;
160}
161
162function objectFits(sub: Schema, sup: Schema): boolean {
163 const subProperties = asSchema(sub.properties);
164 const supProperties = asSchema(sup.properties);
165 const subRequired = new Set((sub.required as string[] | undefined) ?? []);
166 for (const key of (sup.required as string[] | undefined) ?? []) if (!subRequired.has(key)) return false;
167 for (const [key, property] of Object.entries(supProperties)) {
168 if (key in subProperties) {
169 if (!fits(subProperties[key], property)) return false;
170 } else if (typeof sub.additionalProperties === "object" && !fits(sub.additionalProperties, property)) {
171 // The consumer may send this name with any value its `additionalProperties` allows. Open consumer objects
172 // are fine: unknown names are stripped with the consumer's own schema before the call (`RecordImpl.call`).
173 return false;
174 }
175 }
176 if (sup.additionalProperties === false) {
177 if (sub.additionalProperties !== false) return false;
178 if (Object.keys(subProperties).some((key) => !(key in supProperties))) return false;
179 }
180 const supPatterns = asSchema(sup.patternProperties);
181 if (Object.keys(supPatterns).length > 0) {
182 // Every value the consumer may put under a matching name must fit, and the consumer must not allow arbitrary
183 // extra names (it would then allow any value under a matching one).
184 const subPatterns = asSchema(sub.patternProperties);
185 if (sub.additionalProperties !== false && Object.keys(subPatterns).length === 0) return false;
186 for (const [pattern, property] of Object.entries(supPatterns)) {
187 const matcher = new RegExp(pattern, "u");
188 for (const [key, subProperty] of Object.entries(subProperties)) {
189 if (!(key in supProperties) && matcher.test(key) && !fits(subProperty, property)) return false;
190 }
191 if (
192 Object.keys(subPatterns).length > 0 &&
193 (!(pattern in subPatterns) || !fits(subPatterns[pattern], property))
194 ) {
195 return false;
196 }
197 }
198 for (const pattern of Object.keys(subPatterns)) if (!(pattern in supPatterns)) return false;
199 }
200 return true;
201}
202
203function arrayFits(sub: Schema, sup: Schema): boolean {
204 if (Array.isArray(sup.items)) {
205 if (!Array.isArray(sub.items) || sub.items.length !== sup.items.length) return false;
206 return sub.items.every((item, index) => fits(item, (sup.items as unknown[])[index]));
207 }
208 if (Array.isArray(sub.items)) return sub.items.every((item) => fits(item, sup.items));
209 return fits(sub.items, sup.items);
210}
211
212function functionFits(sub: Schema, sup: Schema): boolean {
213 const subParameters = (sub.parameters as unknown[] | undefined) ?? [];
214 const supParameters = (sup.parameters as unknown[] | undefined) ?? [];
215 // A function accepting fewer parameters is fine; each shared parameter is contravariant.
216 if (subParameters.length > supParameters.length) return false;
217 if (!subParameters.every((parameter, index) => fits(supParameters[index], parameter))) return false;
218 return fits(sub.returnType, sup.returnType);
219}