diff --git a/.bumpy/fast-path-max-length.md b/.bumpy/fast-path-max-length.md new file mode 100644 index 0000000..c017019 --- /dev/null +++ b/.bumpy/fast-path-max-length.md @@ -0,0 +1,5 @@ +--- +"valimock": patch +--- + +Fix string generation skipping the length bound when a key-name generator (such as `faker.lorem.text()` for a `text` key) produced a value longer than the schema's `maxLength`/`maxGraphemes`/`maxBytes` allowed. diff --git a/src/__tests__/mockString.spec.ts b/src/__tests__/mockString.spec.ts index 9e9a4d4..4bb31a8 100644 --- a/src/__tests__/mockString.spec.ts +++ b/src/__tests__/mockString.spec.ts @@ -409,6 +409,21 @@ describe(`mockString`, () => { expect(v.parse(schema, result)).toBe(result); } }); + + it(`honors an upper bound when the key-name generator overshoots it`, () => { + // Auto-discovery maps a `text` key to `faker.lorem.text()`, whose output + // regularly exceeds the 128-char default. `maxGraphemes(300)` has no + // min, regex, or substring requirements, so the context looks trivially + // satisfiable and used to skip `enforce` entirely, returning a value + // the schema then rejected. The bound must win over the generator. + const schema = v.object({ + text: v.pipe(v.string(), v.maxGraphemes(300)) + }); + for (let i = 0; i < 50; i++) { + const result = mock(schema); + expect(v.safeParse(schema, result).success).toBe(true); + } + }); }); describe(`edge cases — stringMap override`, () => { diff --git a/src/schemas/string/generateString.ts b/src/schemas/string/generateString.ts index c4cb183..a50ab1f 100644 --- a/src/schemas/string/generateString.ts +++ b/src/schemas/string/generateString.ts @@ -137,10 +137,18 @@ export const generateString = ( // Fast path: when no constraints are present, faker's default output // (lorem.word or a keyName generator) is always valid. Skip the retry // loop entirely — `enforce` is a no-op without required substrings or - // tight bounds, and `satisfies` is trivially true. + // tight bounds, and `satisfies` is trivially true. The one thing a + // key-name generator can still violate is the upper bound: auto-discovered + // generators like `faker.lorem.text()` for a `text` key run past + // DEFAULT_MAX_LENGTH, so an explicit `maxLength`/`maxGraphemes` on that + // field would be silently exceeded. A single length check keeps the fast + // path honest without paying for the full retry loop. if (!userOverride && isTriviallySatisfiable(ctx)) { flushWarnings(ctx, options.onWarn); - return generate(ctx, extras); + const candidate = generate(ctx, extras); + return candidate.length > ctx.bounds.max + ? enforce(candidate, ctx) + : candidate; } for (let attempt = 0; attempt < ENFORCE_RETRY_BUDGET; attempt++) {