Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .bumpy/fast-path-max-length.md
Original file line number Diff line number Diff line change
@@ -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.
15 changes: 15 additions & 0 deletions src/__tests__/mockString.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`, () => {
Expand Down
12 changes: 10 additions & 2 deletions src/schemas/string/generateString.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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++) {
Expand Down
Loading