1
-import { encodePointer, Validator } from '@cfworker/json-schema';
1
+import { encodePointer, format, Validator } from '@cfworker/json-schema';
2
import type { Schema as InterpreterSchema } from '@cfworker/json-schema';
3
import { z } from 'zod/v3';
4
5
import type { JsonSchema, JsonSchemaObject } from './types';
6
+import { toUnicodePattern } from './utils/unicode-pattern';
7
8
const REQUIRES_WHOLE_SCHEMA_VALIDATION = new Set([
9
'$ref',
162
{ ...refs.root, $ref: `#/${refs.path.map(part => encodePointer(String(part))).join('/')}` }
163
: node;
164
164
-const compilesAsUnicode = (pattern: string): boolean => {
165
+const patternKeyRenames = new WeakMap<object, ReadonlyMap<string, string>>();
166
+
167
+/**
168
+ * The Unicode spelling of each `patternProperties` key. Two keys that spell
169
+ * the same way (`^a\_b$` and `^a_b$`) stay separate entries: the later one is
170
+ * wrapped in a non-capturing group, which matches the same names, so neither
171
+ * value schema is dropped. A key with no Unicode spelling is kept as is and
172
+ * surfaces as a guard failure rather than an unenforced constraint.
173
+ */
174
+const renamePatternKeys = (patternProperties: object): ReadonlyMap<string, string> => {
175
+ const cached = patternKeyRenames.get(patternProperties);
176
+ if (cached) {
177
+ return cached;
178
+ }
179
+
180
+ const renames = new Map<string, string>();
181
+ const used = new Set<string>();
182
+ for (const key of Object.keys(patternProperties)) {
183
+ let renamed = toUnicodePattern(key) ?? key;
184
+ while (used.has(renamed)) {
185
+ renamed = `(?:${renamed})`;
186
+ }
187
+ used.add(renamed);
188
+ renames.set(key, renamed);
189
+ }
190
+ patternKeyRenames.set(patternProperties, renames);
191
+ return renames;
192
+};
193
+
194
+const decodePointerSegment = (segment: string): string => {
195
try {
166
- new RegExp(pattern, 'u');
167
- return true;
196
+ return decodeURI(segment).replace(/~1/g, '/').replace(/~0/g, '~');
197
} catch {
169
- return false;
198
+ return segment;
199
}
200
};
201
173
-const REGEX_SYNTAX_CHARACTERS = new Set('^$\\.*+?()[]{}|/');
174
-
202
/**
176
- * The interpreter compiles every pattern with the `u` flag, while
177
- * `compilePattern` deliberately does not. Tool schemas routinely use identity
178
- * escapes such as `\_` or `\:` that are literal characters without the flag
179
- * and a SyntaxError with it, so those escapes are dropped. Returns `undefined`
180
- * when the pattern still has no Unicode-mode spelling.
203
+ * A local `$ref` rewritten to address the renamed `patternProperties` keys of
204
+ * the interpreter copy. `root` is the unrenamed document it points into.
205
*/
182
-const toUnicodePattern = (pattern: string): string | undefined => {
183
- if (compilesAsUnicode(pattern)) {
184
- return pattern;
206
+const renameRefThroughPatternKeys = (ref: string, root: unknown): string => {
207
+ if (!ref.startsWith('#/')) {
208
+ return ref;
209
}
210
187
- let rewritten = '';
188
- let inClass = false;
189
- for (let index = 0; index < pattern.length; index++) {
190
- const char = pattern[index];
191
- if (char === '\\' && index + 1 < pattern.length) {
192
- const escaped = pattern[++index];
193
- const keepEscape =
194
- /[A-Za-z0-9]/.test(escaped) ||
195
- REGEX_SYNTAX_CHARACTERS.has(escaped) ||
196
- (inClass && escaped === '-');
197
- rewritten += keepEscape ? `\\${escaped}` : escaped;
198
- continue;
211
+ const segments = ref.slice(2).split('/');
212
+ let node: unknown = root;
213
+ let changed = false;
214
+ const renamed = segments.map((segment, index) => {
215
+ const key = decodePointerSegment(segment);
216
+ let result = segment;
217
+ if (
218
+ index > 0 &&
219
+ decodePointerSegment(segments[index - 1]) === 'patternProperties' &&
220
+ isObject(node)
221
+ ) {
222
+ const renamedKey = renamePatternKeys(node).get(key);
223
+ if (renamedKey !== undefined && renamedKey !== key) {
224
+ result = encodePointer(renamedKey);
225
+ changed = true;
226
+ }
227
}
200
- if (char === '[') {
201
- inClass = true;
202
- } else if (char === ']') {
203
- inClass = false;
228
+ node =
229
+ isObject(node) || Array.isArray(node) ? (node as Record<string, unknown>)[key] : undefined;
230
+ return result;
231
+ });
232
+
233
+ return changed ? `#/${renamed.join('/')}` : ref;
234
+};
235
+
236
+const PATTERN_FORMAT_PREFIX = 'composio-pattern:';
237
+
238
+/**
239
+ * Registers `pattern` as an interpreter format that tests it exactly as the
240
+ * native string parser does, without the `u` flag, and returns the format
241
+ * name. The name is derived from the pattern, so every schema using the same
242
+ * pattern shares one entry. Returns `undefined` for a pattern that does not
243
+ * compile at all, which the interpreter then reports as it always has.
244
+ */
245
+const patternFormat = (pattern: string): string | undefined => {
246
+ const name = `${PATTERN_FORMAT_PREFIX}${pattern}`;
247
+ if (!Object.hasOwn(format, name)) {
248
+ let regex: RegExp;
249
+ try {
250
+ regex = new RegExp(pattern);
251
+ } catch {
252
+ return undefined;
253
}
205
- rewritten += char;
254
+ format[name] = value => regex.test(value);
255
}
207
-
208
- return compilesAsUnicode(rewritten) ? rewritten : undefined;
256
+ return name;
257
};
258
259
/**
263
* - OpenAPI 3.0 / Draft 4 spell exclusive bounds as a boolean flag next to
264
* `minimum`/`maximum`. The interpreter ignores the flag, so it receives the
265
* numeric spelling the native number parser already honors.
218
- * - Patterns get their Unicode-mode spelling (see `toUnicodePattern`). A
219
- * `pattern` without one is left to the native string parser, which compiles
220
- * it without the flag, instead of failing every value.
266
+ * - The interpreter compiles patterns with the `u` flag, which refuses legacy
267
+ * syntax tool schemas use, such as `\_`. A `pattern` becomes a format that
268
+ * tests it without the flag, exactly like the native string parser. A
269
+ * `patternProperties` key cannot leave the interpreter, so it gets its
270
+ * Unicode spelling (`toUnicodePattern`), and local `$ref`s through a renamed
271
+ * key follow the rename. `root` is the unmodified document those refs
272
+ * address.
273
*/
222
-const prepareInterpreterSchema = (value: unknown, seen: WeakSet<object>): void => {
274
+const prepareInterpreterSchema = (value: unknown, seen: WeakSet<object>, root: unknown): void => {
275
if (!isObject(value) || seen.has(value)) {
276
return;
277
}
290
delete value.exclusiveMaximum;
291
}
292
241
- if (typeof value.pattern === 'string') {
242
- const pattern = toUnicodePattern(value.pattern);
243
- if (pattern === undefined) {
244
- delete value.pattern;
293
+ if (typeof value.$ref === 'string') {
294
+ value.$ref = renameRefThroughPatternKeys(value.$ref, root);
295
+ }
296
+ const patternFormatName =
297
+ typeof value.pattern === 'string' ? patternFormat(value.pattern) : undefined;
298
+ if (patternFormatName !== undefined) {
299
+ delete value.pattern;
300
+ if (value.format === undefined) {
301
+ value.format = patternFormatName;
302
} else {
246
- value.pattern = pattern;
303
+ const allOf = Array.isArray(value.allOf) ? value.allOf : [];
304
+ value.allOf = [...allOf, { format: patternFormatName }];
305
}
306
}
307
if (isObject(value.patternProperties)) {
308
+ const renames = renamePatternKeys(value.patternProperties);
309
value.patternProperties = Object.fromEntries(
310
Object.entries(value.patternProperties).map(([pattern, schema]) => [
252
- toUnicodePattern(pattern) ?? pattern,
311
+ renames.get(pattern) ?? pattern,
312
schema,
313
])
314
);
316
317
for (const [key, child] of Object.entries(value)) {
318
if (SCHEMA_MAP_KEYWORDS.has(key) && isObject(child)) {
260
- Object.values(child).forEach(nested => prepareInterpreterSchema(nested, seen));
319
+ Object.values(child).forEach(nested => prepareInterpreterSchema(nested, seen, root));
320
} else if (SCHEMA_ARRAY_KEYWORDS.has(key) && Array.isArray(child)) {
262
- child.forEach(nested => prepareInterpreterSchema(nested, seen));
321
+ child.forEach(nested => prepareInterpreterSchema(nested, seen, root));
322
} else if (SCHEMA_VALUE_KEYWORDS.has(key)) {
323
(Array.isArray(child) ? child : [child]).forEach(nested =>
265
- prepareInterpreterSchema(nested, seen)
324
+ prepareInterpreterSchema(nested, seen, root)
325
);
326
}
327
}
375
parsedSchema: z.ZodTypeAny
376
): z.ZodTypeAny => {
377
const interpreterSchema = structuredClone(jsonSchema);
319
- prepareInterpreterSchema(interpreterSchema, new WeakSet());
378
+ prepareInterpreterSchema(interpreterSchema, new WeakSet(), jsonSchema);
379
const validator = new Validator(interpreterSchema as InterpreterSchema, '7', false);
380
381
// Validate the source value before defaults and other Zod transforms run.