From 1605a3bc052f09a8244bbd316cdf95fd6bcd92d7 Mon Sep 17 00:00:00 2001 From: Drake Costa Date: Wed, 4 Nov 2026 12:55:23 -0800 Subject: [PATCH 1/2] chore: adopt the shared @saeris/configs lint, format and tsconfig Replace the inline Oxlint and Oxfmt configuration with the shared presets and reformat the codebase to match. --- OXC_VSCODE_ISSUE.md | 205 ++++++ README.md | 15 +- package.json | 1 + scripts/profile.mjs | 17 +- src/Valimock.ts | 283 +++++-- .../fixtures/channelLikeSchema.ts | 4 +- .../fixtures/interactionLikeSchema.ts | 20 +- .../fixtures/messageLikeSchema.ts | 13 +- src/__tests__/customMocks.spec.ts | 7 +- src/__tests__/discordkit.spec.ts | 75 +- src/__tests__/helpers/captureWarnings.ts | 3 +- src/__tests__/mockArray.spec.ts | 98 ++- src/__tests__/mockBigint.spec.ts | 51 +- src/__tests__/mockBlob.spec.ts | 51 +- src/__tests__/mockCustom.spec.ts | 20 +- src/__tests__/mockDate.spec.ts | 48 +- src/__tests__/mockEnum.spec.ts | 32 +- src/__tests__/mockFile.spec.ts | 36 +- src/__tests__/mockInstance.spec.ts | 4 +- src/__tests__/mockIntersect.spec.ts | 34 +- src/__tests__/mockMap.spec.ts | 41 +- src/__tests__/mockNumber.spec.ts | 131 +++- src/__tests__/mockObject.spec.ts | 32 +- src/__tests__/mockOmit.spec.ts | 30 +- src/__tests__/mockOptions.spec.ts | 14 +- src/__tests__/mockPicklist.spec.ts | 19 +- src/__tests__/mockRecord.spec.ts | 45 +- src/__tests__/mockRequired.spec.ts | 25 +- src/__tests__/mockSet.spec.ts | 31 +- src/__tests__/mockSimpleSchemas.spec.ts | 57 +- src/__tests__/mockString.spec.ts | 100 ++- src/__tests__/mockTuple.spec.ts | 63 +- src/__tests__/mockUnion.spec.ts | 43 +- src/__tests__/mockVariant.spec.ts | 15 +- src/__tests__/wrapperLaziness.spec.ts | 7 +- src/schemas/array.ts | 37 +- src/schemas/bigint.ts | 64 +- src/schemas/blob.ts | 53 +- src/schemas/date.ts | 37 +- src/schemas/file.ts | 53 +- src/schemas/intersect.ts | 34 +- src/schemas/map.ts | 5 +- src/schemas/number/actionHandlers.ts | 14 +- src/schemas/number/generateNumber.ts | 37 +- src/schemas/number/types.ts | 9 +- src/schemas/object.ts | 34 +- src/schemas/record.ts | 19 +- src/schemas/set.ts | 44 +- src/schemas/string/actionHandlers.ts | 52 +- src/schemas/string/formatGenerators.ts | 696 ++++++++++-------- src/schemas/string/generateString.ts | 34 +- src/schemas/string/keyNameGenerators.ts | 111 +-- src/schemas/string/phases.ts | 40 +- src/schemas/string/types.ts | 9 +- src/schemas/tuple.ts | 14 +- src/schemas/union.ts | 38 +- src/types.ts | 55 +- src/utils/bounds.ts | 11 +- src/utils/guards.ts | 30 + src/utils/readRequirement.ts | 21 +- src/utils/walkPipe.ts | 12 +- src/utils/warnings.ts | 6 +- tsconfig.json | 27 +- vite.config.ts | 628 +--------------- yarn.lock | 10 + 65 files changed, 2360 insertions(+), 1544 deletions(-) create mode 100644 OXC_VSCODE_ISSUE.md create mode 100644 src/utils/guards.ts diff --git a/OXC_VSCODE_ISSUE.md b/OXC_VSCODE_ISSUE.md new file mode 100644 index 0000000..8c297dc --- /dev/null +++ b/OXC_VSCODE_ISSUE.md @@ -0,0 +1,205 @@ +# Extension formats with oxfmt defaults instead of `vite.config.ts` when the raw oxfmt bin shadows the vite-plus wrapper at `node_modules/.bin/oxfmt` + +> Target repo: [`oxc-project/oxc-vscode`](https://github.com/oxc-project/oxc-vscode) + +### Confirm that this is a Bug for the editor extension, not the CLI + +- [x] This bug does not happen in the Oxlint/Oxfmt CLI (`vp fmt` / `vp check --fix` are correct) +- [x] After restarting the editor, the bug still appears + +### Versions used + +``` +VS Code extension (oxc.oxc-vscode): 1.57.0 +oxfmt: 0.48.0 (transitive, via vite-plus) +vite-plus: 0.1.21 +VS Code: freshly updated +OS: Windows 10 Pro 19045 (win32) +Node: v26.1.0 +Package manager: yarn@4.14.1 (node-modules linker) +``` + +### What happened? + +Format-on-save (Oxc extension) produces **different output than `vp fmt`** for the same +file and the same `vite.config.ts`, which has `fmt.trailingComma: "none"`. + +Given this input (a long object literal that must wrap, so the last property lands on its +own line where a trailing comma would or wouldn't be added): + +```ts +const longName = { alpha: 1, beta: 2, gamma: 3, delta: 4, epsilon: 5 }; +``` + +`vp fmt` / `vp check --fix` — **no** trailing comma (config honored ✅): + +```ts +const longName = { + alpha: 1, + beta: 2, + gamma: 3, + delta: 4, + epsilon: 5 +}; +``` + +Format-on-save via the extension — trailing comma **added** (oxfmt default, config ignored ❌): + +```ts +const longName = { + alpha: 1, + beta: 2, + gamma: 3, + delta: 4, + epsilon: 5 +}; +``` + +The only difference is the comma after the last property (`epsilon: 5` vs `epsilon: 5,`). +`oxc.fmt.configPath` is `./vite.config.ts`. The extension silently falls back to oxfmt's +built-in defaults; only `trailingComma` visibly diverges because the other configured +values happen to match oxfmt's defaults. + +### Root cause + +oxfmt only reads `.fmt` from a `vite.config.ts` when the **`VP_VERSION`** env var is set +(it gates `vite.config.ts` recognition behind it — see +[`apps/oxfmt/src/core/utils.rs::vp_version()`](https://github.com/oxc-project/oxc/blob/e77ff81a6bf5aac5a3ed1627004c00e74f644adf/apps/oxfmt/src/core/utils.rs#L8-L10)). +`vp` injects `VP_VERSION`; the standalone binary does not. `vite-plus` ships a wrapper, +`vite-plus/bin/oxfmt`, whose sole job is to set `process.env.VP_VERSION` and delegate to +the real oxfmt: + +```js +// vite-plus/bin/oxfmt (excerpt) +// This allows oxfmt to load vite.config.ts +process.env.VP_VERSION = pkg.version; +await import(pathToFileURL(oxfmtBin).href); +``` + +This wrapper is the binary the extension is meant to spawn. The extension prefers +`node_modules/.bin/` precisely for this reason — and it documents that rationale at +[`findBinary.ts` L96–99](https://github.com/oxc-project/oxc-vscode/blob/91f7d365a12969ae2c40bedf32060747b6125a55/client/findBinary.ts#L96-L99): + +> ```ts +> // try to find shared binary inside `node_modules/.bin` of each workspace folder +> // This is required, because the project can use `vite-plus`, +> // which has different environment variables for `oxlint` and `oxfmt`. +> // Example: It will skip the `vite.config.ts` search without `VP_VERSION` env variable. +> ``` + +The resolver builds the candidate path as +[`path.join(folder, ".bin", binaryName)`](https://github.com/oxc-project/oxc-vscode/blob/91f7d365a12969ae2c40bedf32060747b6125a55/client/findBinary.ts#L46) +inside +[`searchProjectNodeModulesBin`](https://github.com/oxc-project/oxc-vscode/blob/91f7d365a12969ae2c40bedf32060747b6125a55/client/findBinary.ts#L93-L111) +and trusts whatever that link resolves to. + +**But two packages both claim the `oxfmt` bin name:** + +- `vite-plus` → `bin/oxfmt` (the wrapper that sets `VP_VERSION`) +- `oxfmt` → `bin/oxfmt` (raw, no `VP_VERSION`) + +`oxfmt` is **only a transitive dependency of `vite-plus`** (`yarn why oxfmt` → +`vite-plus@0.1.21 → oxfmt@0.48.0`), yet the raw `oxfmt` bin **won the +`node_modules/.bin/oxfmt` link**. So the extension — which prefers +`node_modules/.bin/oxfmt` — spawns the raw binary, no `VP_VERSION` flows, and oxfmt uses +defaults. + +`node_modules/.bin/oxfmt.cmd` → + +``` +"%~dp0\node.exe" "%~dp0\..\oxfmt\bin\oxfmt" %* ← raw oxfmt, NOT vite-plus/bin/oxfmt +``` + +### Three-leg proof (same binary, same config, same input) + +```sh +# 1. raw .bin path (what the extension resolves to) — no VP_VERSION → DEFAULT +$ node node_modules/oxfmt/bin/oxfmt --config ./vite.config.ts test.ts + → epsilon: 5, ❌ + +# 2. same binary WITH VP_VERSION → config honored (proves the env var is the sole gate) +$ VP_VERSION=0.1.21 node node_modules/oxfmt/bin/oxfmt --config ./vite.config.ts test.ts + → epsilon: 5 ✅ + +# 3. vp fmt (sets VP_VERSION + uses the wrapper) → config honored +$ vp fmt test.ts + → epsilon: 5 ✅ +``` + +### Why 1.53.0's fix doesn't cover this + +[#215](https://github.com/oxc-project/oxc-vscode/issues/215) (closed) fixed a related case +by making the extension prefer `node_modules/.bin/oxfmt` (shipped in extension 1.53.0). +That assumes `.bin/oxfmt` **is** the vite-plus wrapper. When the raw `oxfmt` package wins +the bin-name collision (as here — and it can, since vite-plus pulls oxfmt in transitively +and the linker resolves the `.bin` race non-deterministically), that assumption breaks and +the user is silently back on defaults. + +### Suggested fix + +In [`searchProjectNodeModulesBin`](https://github.com/oxc-project/oxc-vscode/blob/91f7d365a12969ae2c40bedf32060747b6125a55/client/findBinary.ts#L93-L111), +when the workspace has `vite-plus` installed, prefer **`node_modules/vite-plus/bin/oxfmt`** +(and `…/bin/oxlint`) directly rather than the `node_modules/.bin/` link built at +[L46](https://github.com/oxc-project/oxc-vscode/blob/91f7d365a12969ae2c40bedf32060747b6125a55/client/findBinary.ts#L46). +This makes resolution deterministic regardless of how the bin-link race resolved, and +matches the rationale the function already documents. Fall back to the current `.bin` +behavior when `vite-plus` isn't present. + +(Alternatively/additionally, the extension could verify a resolved `.bin/` actually +points into `vite-plus/` before trusting it for the VP_VERSION path — but resolving the +wrapper directly is simpler and avoids the race entirely.) + +### Minimal reproduction (from scratch — no special project needed) + +`@saeris/configs` is **not** involved; an inline `fmt` reproduces it. The only non-obvious +requirement is that the formatted construct must **wrap** (exceed `printWidth`, default 80), +since `trailingComma` only applies to multi-line output — hence the long variable name below. + +1. New folder, install vite-plus (any package manager; the collision is in the dep tree): + + ```sh + npm init -y + npm install vite-plus + ``` + + This installs both `vite-plus/bin/oxfmt` (the `VP_VERSION` wrapper) and, transitively, + `oxfmt/bin/oxfmt` (raw) — both claiming the `oxfmt` bin name. + +2. `vite.config.ts` with a non-default fmt option: + + ```ts + import { defineConfig } from "vite-plus"; + + export default defineConfig({ + fmt: { trailingComma: "none" } + }); + ``` + +3. `test.ts` (long enough that the object must wrap): + + ```ts + const aReallyLongVariableNameSoTheObjectMustWrapAcrossMultipleLines = { + alpha: 1, + beta: 2, + gamma: 3, + delta: 4, + epsilon: 5 + }; + ``` + +4. VS Code settings: `"editor.defaultFormatter": "oxc.oxc-vscode"`, + `"editor.formatOnSave": true`, `"oxc.fmt.configPath": "./vite.config.ts"`. + +5. Open `test.ts`, save → trailing comma is **added** (`epsilon: 5,`), but `vp fmt test.ts` + produces **no** trailing comma (`epsilon: 5`). + +Check which binary `.bin/oxfmt` resolves to — if it points into `oxfmt/` rather than +`vite-plus/`, the extension is spawning the raw binary and the bug is present. The +three-leg proof above can be run against this same setup. + +> **Note on the bin race:** which of the two competing `oxfmt` bins ends up at +> `node_modules/.bin/oxfmt` is decided by the package manager / linker and isn't +> guaranteed to be the raw one on every install — but when it is the raw one (as observed +> here), the extension has no way to tell and silently uses defaults. The fix removes the +> dependence on that race entirely by resolving the `vite-plus` wrapper directly. You can +> force the failing state for testing by pointing `.bin/oxfmt` at `../oxfmt/bin/oxfmt`. diff --git a/README.md b/README.md index 6f45227..8494269 100644 --- a/README.md +++ b/README.md @@ -32,12 +32,23 @@ yarn add -D valimock @faker-js/faker Import and optionally configure a new instance of the `Valimock` class, then pass along your `valibot` schema to `mock()`, that's it! ```ts -import { parse, array, union, string, pipe, url, number, maxValue } from "valibot"; +import { + parse, + array, + union, + string, + pipe, + url, + number, + maxValue +} from "valibot"; import { Valimock } from "valimock"; describe(`example test`, () => { it(`should generate valid mock data`, () => { - const schema = array(union([pipe(string(), url()), pipe(number(), maxValue(20))])); + const schema = array( + union([pipe(string(), url()), pipe(number(), maxValue(20))]) + ); const result = new Valimock().mock(schema); expect(parse(schema, result)).toStrictEqual(result); }); diff --git a/package.json b/package.json index e293362..4d7d04f 100644 --- a/package.json +++ b/package.json @@ -47,6 +47,7 @@ }, "devDependencies": { "@faker-js/faker": "^10.4.0", + "@saeris/configs": "1.6.0", "@types/node": "25.8.0", "@varlock/bumpy": "^1.7.0", "@vitest/coverage-v8": "^4.1.6", diff --git a/scripts/profile.mjs b/scripts/profile.mjs index 5b45357..15fa34e 100644 --- a/scripts/profile.mjs +++ b/scripts/profile.mjs @@ -33,13 +33,22 @@ console.log(`>> Bench filter: ${process.argv.slice(2).join(` `) || `(all)`}`); // not the vp wrapper. const vitestBin = join(repoRoot, `node_modules/vitest/dist/cli.js`); if (!existsSync(vitestBin)) { - console.error(`error: vitest CLI not found at ${vitestBin}. Run \`vp install\` first.`); + console.error( + `error: vitest CLI not found at ${vitestBin}. Run \`vp install\` first.` + ); process.exit(1); } const result = spawnSync( process.execPath, - [`--cpu-prof`, `--cpu-prof-dir=${profilesDir}`, vitestBin, `bench`, `--run`, ...process.argv.slice(2)], + [ + `--cpu-prof`, + `--cpu-prof-dir=${profilesDir}`, + vitestBin, + `bench`, + `--run`, + ...process.argv.slice(2) + ], { stdio: `inherit`, cwd: repoRoot } ); @@ -55,7 +64,9 @@ const cpuProfiles = readdirSync(profilesDir) .sort((a, b) => b.mtime - a.mtime); if (cpuProfiles.length === 0) { - console.warn(`>> No .cpuprofile files written — check that vitest actually ran.`); + console.warn( + `>> No .cpuprofile files written — check that vitest actually ran.` + ); process.exit(1); } diff --git a/src/Valimock.ts b/src/Valimock.ts index 72522a7..e95a073 100644 --- a/src/Valimock.ts +++ b/src/Valimock.ts @@ -18,7 +18,13 @@ import { generateString } from "./schemas/string/generateString.js"; import { generateTuple } from "./schemas/tuple.js"; import { generateUnion } from "./schemas/union.js"; import { generateVariant } from "./schemas/variant.js"; -import type { Schema, SchemaMaybeWithPipe, SyncSchema, MaybeRequiredSchema, RequiredSchema } from "./types.js"; +import type { + Schema, + SchemaMaybeWithPipe, + SyncSchema, + MaybeRequiredSchema, + RequiredSchema +} from "./types.js"; export class MockError extends Error { constructor(public typeName?: string) { @@ -26,9 +32,14 @@ export class MockError extends Error { } } -export type FakerFunction = (...args: unknown[]) => Date | boolean | number | string; +export type FakerFunction = ( + ...args: unknown[] +) => Date | boolean | number | string; -export type MockeryMapper = (keyName: string, fakerInstance: Faker) => FakerFunction | undefined; +export type MockeryMapper = ( + keyName: string, + fakerInstance: Faker +) => FakerFunction | undefined; export interface ValimockOptions { /** @@ -78,7 +89,13 @@ export interface ValimockOptions { * The functions in this map will only be used if this library * is unable to find an appropriate mocking function to use. */ - customMocks: Record unknown>; + customMocks: Record< + string, + ( + schema: v.GenericSchema | v.GenericSchemaAsync, + options?: ValimockOptions + ) => unknown + >; /** * How many entries to create for records @@ -135,7 +152,10 @@ export class Valimock { instrument: false, customMocks: {}, onWarn: (message: string): void => console.warn(`[valimock] ${message}`), - mockeryMapper: (keyName: string | undefined, fakerInstance: Faker): FakerFunction | undefined => { + mockeryMapper: ( + keyName: string | undefined, + fakerInstance: Faker + ): FakerFunction | undefined => { const keyToFnMap: Record = { image: (): string => fakerInstance.image.url(), imageurl: (): string => fakerInstance.image.url(), @@ -204,18 +224,25 @@ export class Valimock { const cached = this.#validEnumValuesCache.get(obj); if (cached) return cached; const computed = Object.values( - Object.entries(obj).reduce( - (hash, [key, value]) => (typeof obj[value] === `number` ? hash : Object.assign(hash, { [key]: value })), + Object.entries(obj).reduce>( + (hash, [key, value]) => + typeof obj[value] === `number` + ? hash + : Object.assign(hash, { [key]: value }), {} ) - ) as Array; + ); this.#validEnumValuesCache.set(obj, computed); return computed; }; - mock = (schema: T): v.InferOutput => this.#mock(schema); + mock = (schema: T): v.InferOutput => + this.#mock(schema); - #mock = (schema: T, keyName?: string): v.InferOutput => { + #mock = ( + schema: T, + keyName?: string + ): v.InferOutput => { // Instrumentation guard: a single branch + two increments when on, // zero overhead when off. The guard sits ahead of the work so the // catch block below doesn't need to know about it. @@ -244,15 +271,23 @@ export class Valimock { return this.options.customMocks[schema.type](schema, this.options); } if ( - v.isOfType<`string`, Schema | SchemaMaybeWithPipe | undefined>>>( + v.isOfType< `string`, - schema - ) + | Schema + | SchemaMaybeWithPipe< + v.StringSchema | undefined> + > + >(`string`, schema) ) { return this.#mockString(schema, keyName); } const handler = this.#schemaHandlers.get(schema.type); if (handler) { + // The handler map is type-erased to `(schema: never) => unknown` so + // handlers with different concrete schema types share one value type; + // the dispatch boundary requires `as never` to satisfy that parameter, + // and the result is re-narrowed to the schema's inferred output. + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion return handler(schema as never) as v.InferOutput; } if (this.options.throwOnUnknownType) { @@ -272,7 +307,9 @@ export class Valimock { throw err; } - this.options.onWarn(`Mock generation failed for schema type \`${schema.type}\`: ${String(err)}`); + this.options.onWarn( + `Mock generation failed for schema type \`${schema.type}\`: ${String(err)}` + ); } finally { // Always decrement so depth stays balanced across throws, returns, and // the silent-undefined unknown-type path. The guard mirrors the entry @@ -297,7 +334,9 @@ export class Valimock { }) as v.InferOutput; #mockBigint = ( - schema: SchemaMaybeWithPipe | undefined>> + schema: SchemaMaybeWithPipe< + v.BigintSchema | undefined> + > ): v.InferOutput => generateBigint(schema, { faker: this.options.faker, @@ -305,11 +344,15 @@ export class Valimock { }); #mockBoolean = ( - schema: SchemaMaybeWithPipe | undefined>> + schema: SchemaMaybeWithPipe< + v.BooleanSchema | undefined> + > ): v.InferOutput => this.options.faker.datatype.boolean(); #mockDate = ( - schema: SchemaMaybeWithPipe | undefined>> + schema: SchemaMaybeWithPipe< + v.DateSchema | undefined> + > ): v.InferOutput => generateDate(schema, { faker: this.options.faker, @@ -317,24 +360,42 @@ export class Valimock { }); #mockPicklist = ( - schema: v.PicklistSchema | undefined> - ): v.InferOutput => this.options.faker.helpers.arrayElement(schema.options); + schema: v.PicklistSchema< + v.PicklistOptions, + v.ErrorMessage | undefined + > + ): v.InferOutput => + this.options.faker.helpers.arrayElement(schema.options); #mockIntersect = ( - schema: v.IntersectSchema | undefined> + schema: v.IntersectSchema< + v.IntersectOptions, + v.ErrorMessage | undefined + > ): v.InferOutput => + // `generateIntersect` returns `unknown` (it deep-merges arbitrary option + // outputs); its runtime result satisfies the schema's inferred output by + // construction, verified by the intersect round-trip tests. + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion generateIntersect(schema, { mockItem: (item) => this.#mock(item), onWarn: this.options.onWarn }) as v.InferOutput; #mockLiteral = ( - schema: v.LiteralSchema | undefined> + schema: v.LiteralSchema< + v.Literal, + v.ErrorMessage | undefined + > ): v.InferOutput => schema.literal; #mockMap = ( schema: - | v.MapSchema | undefined> + | v.MapSchema< + SyncSchema, + SyncSchema, + v.ErrorMessage | undefined + > | v.MapSchemaAsync | undefined> ): v.InferOutput => generateMap(schema, { @@ -343,15 +404,23 @@ export class Valimock { onWarn: this.options.onWarn }) as v.InferOutput; - #mockNaN = (schema: v.NanSchema | undefined>): v.InferOutput => NaN; + #mockNaN = ( + schema: v.NanSchema | undefined> + ): v.InferOutput => NaN; - #mockEnum = (schema: v.EnumSchema | undefined>): v.InferOutput => - this.options.faker.helpers.arrayElement(this.#getValidEnumValues(schema.enum)); + #mockEnum = ( + schema: v.EnumSchema | undefined> + ): v.InferOutput => + this.options.faker.helpers.arrayElement( + this.#getValidEnumValues(schema.enum) + ); #mockRequired = >( schema: RequiredSchema ): v.InferOutput => { - const isNestedRequired = (val: Schema | SyncSchema): val is RequiredSchema => + const isNestedRequired = ( + val: Schema | SyncSchema + ): val is RequiredSchema => Object.hasOwn(val, `expects`) && ![`!null`, `(!null & !undefined)`, `!undefined`].includes(val.expects) && Object.hasOwn(val, `wrapped`); @@ -373,27 +442,46 @@ export class Valimock { // chosen. Sampling distributions are preserved. #mockNullable = ( - schema: v.NullableSchema | v.NullableSchemaAsync - ): v.InferOutput => (this.options.faker.datatype.boolean() ? this.#mock(schema.wrapped) : null); + schema: + | v.NullableSchema + | v.NullableSchemaAsync + ): v.InferOutput => + this.options.faker.datatype.boolean() ? this.#mock(schema.wrapped) : null; #mockNullish = ( - schema: v.NullishSchema | v.NullishSchemaAsync + schema: + | v.NullishSchema< + SyncSchema, + v.Default + > + | v.NullishSchemaAsync< + Schema, + v.DefaultAsync + > ): v.InferOutput => { if (schema.default !== undefined) { - return v.getDefault(schema as never) as v.InferOutput; + return v.getDefault(schema); } // 1/3 each of wrapped / null / undefined. Faker's `arrayElement` over a // 3-tuple of string tags is cheap (no schema evaluation, no allocation // beyond the literal) and respects the seeded PRNG. - const branch = this.options.faker.helpers.arrayElement([`wrapped`, `null`, `undefined`] as const); + const branch = this.options.faker.helpers.arrayElement([ + `wrapped`, + `null`, + `undefined` + ] as const); if (branch === `wrapped`) return this.#mock(schema.wrapped); return branch === `null` ? null : undefined; }; - #mockNull = (schema: v.NullSchema | undefined>): v.InferOutput => null; + #mockNull = ( + schema: v.NullSchema | undefined> + ): v.InferOutput => null; #mockNumber = ( - schema: SchemaMaybeWithPipe | undefined>> + schema: SchemaMaybeWithPipe< + v.NumberSchema | undefined> + > ): v.InferOutput => generateNumber(schema, { faker: this.options.faker, @@ -402,22 +490,33 @@ export class Valimock { #mockObject = ( schema: - | v.ObjectSchema | undefined> - | v.ObjectSchemaAsync | undefined> + | v.ObjectSchema< + v.ObjectEntries, + v.ErrorMessage | undefined + > + | v.ObjectSchemaAsync< + v.ObjectEntriesAsync, + v.ErrorMessage | undefined + > ): v.InferOutput => generateObject(schema, { mockItem: (s, key) => this.#mock(s as Schema, key) }) as v.InferOutput; #mockOptional = ( - schema: v.OptionalSchema | v.OptionalSchemaAsync + schema: + | v.OptionalSchema> + | v.OptionalSchemaAsync< + Schema, + v.DefaultAsync + > ): v.InferOutput => { // When the schema declares a default, honor it — `parse` will fill that // value in when the key is absent, so emitting it here keeps parse(mock) // structurally equal to mock(). `schema.default` may be a value or a // function (per Valibot's `getDefault` helper). if (schema.default !== undefined) { - return v.getDefault(schema as never) as v.InferOutput; + return v.getDefault(schema); } // Lazy coin-flip: see the wrapper-handlers note above #mockNullable. return this.options.faker.datatype.boolean() @@ -426,17 +525,25 @@ export class Valimock { }; #mockRecord = < - Key extends v.BaseSchema> = v.BaseSchema< + Key extends v.BaseSchema< string, number | string | symbol, v.BaseIssue - >, + > = v.BaseSchema>, Value extends Schema = Schema >( schema: Value extends v.GenericSchema ? v.RecordSchema | undefined> - : v.RecordSchemaAsync | undefined> + : v.RecordSchemaAsync< + Key, + Value, + v.ErrorMessage | undefined + > ): v.InferOutput => + // `generateRecord` returns a plain `Record`; its runtime result satisfies + // the schema's inferred output by construction (keys and values are each + // mocked from the schema), verified by the record round-trip tests. + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion generateRecord(schema, { entriesLength: this.options.recordKeysLength, mockItem: (item) => this.#mock(item) @@ -449,7 +556,9 @@ export class Valimock { * in which case we can't mock synchronously and emit a warning. */ #mockLazy = ( - schema: v.LazySchema | v.LazySchemaAsync + schema: + | v.LazySchema + | v.LazySchemaAsync ): v.InferOutput => { const inner = schema.getter(undefined); if (inner instanceof Promise) { @@ -477,13 +586,18 @@ export class Valimock { }) as v.InferOutput; #mockString = ( - schema: SchemaMaybeWithPipe | undefined>>, + schema: SchemaMaybeWithPipe< + v.StringSchema | undefined> + >, keyName?: string ): v.InferOutput => generateString(schema, { faker: this.options.faker, keyName, stringMap: this.options.stringMap, + // Deliberately consuming the deprecated `mockeryMapper` for backwards + // compatibility; `onDeprecatedMapper` below emits the one-time warning. + // eslint-disable-next-line @typescript-eslint/no-deprecated mockeryMapper: this.options.mockeryMapper, onDeprecatedMapper: () => { if (this.#mockeryMapperWarned) return; @@ -499,15 +613,21 @@ export class Valimock { #mockTuple = ( schema: | v.TupleSchema | undefined> - | v.TupleSchemaAsync | undefined> + | v.TupleSchemaAsync< + v.TupleItemsAsync, + v.ErrorMessage | undefined + > ): v.InferOutput => generateTuple(schema, { mockItem: (item) => this.#mock(item) - }) as v.InferOutput; + }); #mockUnion = ( schema: - | v.UnionSchema>> | undefined> + | v.UnionSchema< + v.UnionOptions, + v.ErrorMessage>> | undefined + > | v.UnionSchemaAsync< v.UnionOptions | v.UnionOptionsAsync, v.ErrorMessage>> | undefined @@ -517,19 +637,23 @@ export class Valimock { mockItem: (item) => this.#mock(item), pickOption: (opts) => this.options.faker.helpers.arrayElement(opts), onWarn: this.options.onWarn - }) as v.InferOutput; + }); #mockUndefined = ( schema: v.UndefinedSchema | undefined> ): v.InferOutput => undefined; #mockVariant = ( - schema: v.VariantSchema, v.ErrorMessage | undefined> + schema: v.VariantSchema< + Key, + v.VariantOptions, + v.ErrorMessage | undefined + > ): v.InferOutput => generateVariant(schema, { mockItem: (item) => this.#mock(item), pickOption: (opts) => this.options.faker.helpers.arrayElement(opts) - }) as v.InferOutput; + }); // ── Type-only schemas (no constraint surface beyond "is this type") ──── @@ -541,37 +665,59 @@ export class Valimock { null ]); - #mockUnknown = (_schema: v.UnknownSchema): unknown => this.#mockAny(_schema as unknown as v.AnySchema); + #mockUnknown = (_schema: v.UnknownSchema): unknown => + // `unknown` and `any` schemas are mocked identically (both accept any + // value); reuse the `any` handler. The schemas are structurally unrelated + // so the bridge needs an explicit cast, but neither handler reads the + // schema, so the cast is inert at runtime. + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion + this.#mockAny(_schema as unknown as v.AnySchema); - #mockVoid = (_schema: v.VoidSchema | undefined>): undefined => undefined; + #mockVoid = ( + _schema: v.VoidSchema | undefined> + ): undefined => undefined; /** * `never` is unsatisfiable by design — no value passes parse. Throw a * MockError so callers can detect schemas that are definitionally * un-mockable rather than silently emitting `undefined`. */ - #mockNever = (_schema: v.NeverSchema | undefined>): never => { + #mockNever = ( + _schema: v.NeverSchema | undefined> + ): never => { throw new MockError(`never`); }; #mockFunction = - (_schema: v.FunctionSchema | undefined>): ((...args: unknown[]) => unknown) => + ( + _schema: v.FunctionSchema | undefined> + ): ((...args: unknown[]) => unknown) => (..._args: unknown[]): unknown => undefined; - #mockSymbol = (_schema: v.SymbolSchema | undefined>): symbol => Symbol(); + #mockSymbol = ( + _schema: v.SymbolSchema | undefined> + ): symbol => Symbol(); - #mockPromise = (_schema: v.PromiseSchema | undefined>): Promise => - Promise.resolve(undefined); + #mockPromise = async ( + _schema: v.PromiseSchema | undefined> + ): Promise => Promise.resolve(undefined); #mockUndefinedable = ( - schema: v.UndefinedableSchema | v.UndefinedableSchemaAsync + schema: + | v.UndefinedableSchema> + | v.UndefinedableSchemaAsync< + Schema, + v.DefaultAsync + > ): v.InferOutput => { if (schema.default !== undefined) { - return v.getDefault(schema as never) as v.InferOutput; + return v.getDefault(schema); } // Lazy coin-flip: see the wrapper-handlers note above #mockNullable. - return this.options.faker.datatype.boolean() ? this.#mock(schema.wrapped) : undefined; + return this.options.faker.datatype.boolean() + ? this.#mock(schema.wrapped) + : undefined; }; /** @@ -579,7 +725,12 @@ export class Valimock { * fitting mock when the class has a zero-arg constructor; otherwise we warn * and return a best-effort `Object.create(prototype)` instance. */ - #mockInstance = (schema: v.InstanceSchema | undefined>): unknown => { + #mockInstance = ( + schema: v.InstanceSchema< + v.Class, + v.ErrorMessage | undefined + > + ): unknown => { try { return new (schema.class as new () => unknown)(); } catch (err) { @@ -595,15 +746,21 @@ export class Valimock { * not_size / mime_type. Returns a placeholder when the `Blob` global is * unavailable (Node < 18 without polyfills). */ - #mockBlob = (schema: SchemaMaybeWithPipe | undefined>>): unknown => - generateBlob(schema, { onWarn: this.options.onWarn }); + #mockBlob = ( + schema: SchemaMaybeWithPipe< + v.BlobSchema | undefined> + > + ): unknown => generateBlob(schema, { onWarn: this.options.onWarn }); /** * `file` schema with pipeline support. Same action set as `blob` since File * extends Blob. Returns a placeholder when the `File` global is unavailable. */ - #mockFile = (schema: SchemaMaybeWithPipe | undefined>>): unknown => - generateFile(schema, { onWarn: this.options.onWarn }); + #mockFile = ( + schema: SchemaMaybeWithPipe< + v.FileSchema | undefined> + > + ): unknown => generateFile(schema, { onWarn: this.options.onWarn }); #schemas: Record unknown> = { any: this.#mockAny, diff --git a/src/__benchmarks__/fixtures/channelLikeSchema.ts b/src/__benchmarks__/fixtures/channelLikeSchema.ts index 0a86460..c2cd5d3 100644 --- a/src/__benchmarks__/fixtures/channelLikeSchema.ts +++ b/src/__benchmarks__/fixtures/channelLikeSchema.ts @@ -40,7 +40,9 @@ export const channelLikeSchema = v.intersect([ }), v.object({ type: v.literal(`forum`), - defaultReactionEmoji: v.nullish(v.object({ id: v.nullish(v.string()), name: v.nullish(v.string()) })), + defaultReactionEmoji: v.nullish( + v.object({ id: v.nullish(v.string()), name: v.nullish(v.string()) }) + ), availableTags: v.array( v.object({ id: v.string(), diff --git a/src/__benchmarks__/fixtures/interactionLikeSchema.ts b/src/__benchmarks__/fixtures/interactionLikeSchema.ts index 0332a37..52c76fb 100644 --- a/src/__benchmarks__/fixtures/interactionLikeSchema.ts +++ b/src/__benchmarks__/fixtures/interactionLikeSchema.ts @@ -10,29 +10,17 @@ import * as v from "valibot"; * - Nested optional/nullish wrappers around lazy refs */ -interface UserRef { - id: string; - username: string; - discriminator: string; -} - -const userRefSchema: v.GenericSchema = v.object({ +const userRefSchema = v.object({ id: v.string(), username: v.pipe(v.string(), v.minLength(2), v.maxLength(32)), discriminator: v.pipe(v.string(), v.digits(), v.length(4)) -}) as unknown as v.GenericSchema; - -interface ChannelRef { - id: string; - name: string; - type: number; -} +}); -const channelRefSchema: v.GenericSchema = v.object({ +const channelRefSchema = v.object({ id: v.string(), name: v.string(), type: v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(15)) -}) as unknown as v.GenericSchema; +}); export const interactionLikeSchema = v.object({ id: v.string(), diff --git a/src/__benchmarks__/fixtures/messageLikeSchema.ts b/src/__benchmarks__/fixtures/messageLikeSchema.ts index 379da0c..3919da0 100644 --- a/src/__benchmarks__/fixtures/messageLikeSchema.ts +++ b/src/__benchmarks__/fixtures/messageLikeSchema.ts @@ -38,6 +38,11 @@ interface Message { referencedMessage?: Message | null; } +// Recursive schema: the `referencedMessage` self-reference needs the explicit +// `Message` annotation to break circular inference, and valibot's structural +// object output doesn't match the nominal interface, so the bridge cast is +// unavoidable here. +// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion export const messageLikeSchema: v.GenericSchema = v.object({ id: v.string(), channelId: v.string(), @@ -62,8 +67,12 @@ export const messageLikeSchema: v.GenericSchema = v.object({ v.object({ title: v.nullish(v.string()), description: v.nullish(v.string()), - footer: v.nullish(v.object({ text: v.string(), iconUrl: v.nullish(v.string()) })), - author: v.nullish(v.object({ name: v.string(), url: v.nullish(v.string()) })), + footer: v.nullish( + v.object({ text: v.string(), iconUrl: v.nullish(v.string()) }) + ), + author: v.nullish( + v.object({ name: v.string(), url: v.nullish(v.string()) }) + ), fields: v.array(v.object({ name: v.string(), value: v.string() })) }) ), diff --git a/src/__tests__/customMocks.spec.ts b/src/__tests__/customMocks.spec.ts index 31b727f..8fc6b19 100644 --- a/src/__tests__/customMocks.spec.ts +++ b/src/__tests__/customMocks.spec.ts @@ -2,7 +2,10 @@ import { describe, expect, it } from "vite-plus/test"; import * as v from "valibot"; import { Valimock } from "../Valimock.js"; -const customSchema = v.custom((input) => typeof input === `string` && input === `custom`, `Invalid value!`); +const customSchema = v.custom( + (input) => typeof input === `string` && input === `custom`, + `Invalid value!` +); const mockSchema = new Valimock({ customMocks: { @@ -13,6 +16,8 @@ const mockSchema = new Valimock({ // Return your mock data here return `custom`; } + // Returning undefined signals "no custom mock — use the built-in path". + return undefined; } } }).mock; diff --git a/src/__tests__/discordkit.spec.ts b/src/__tests__/discordkit.spec.ts index 1f2d43f..c2b3d46 100644 --- a/src/__tests__/discordkit.spec.ts +++ b/src/__tests__/discordkit.spec.ts @@ -5,7 +5,10 @@ const snowflake = v.pipe(v.string(), v.uuid()); const userSchema = v.object({ username: v.pipe(v.string(), v.minLength(1)), - discriminator: v.union([v.pipe(v.string(), v.digits(), v.length(4)), v.literal(`0`)]), + discriminator: v.union([ + v.pipe(v.string(), v.digits(), v.length(4)), + v.literal(`0`) + ]), globalName: v.exactOptional(v.string()), avatar: v.exactOptional(v.pipe(v.string(), v.minLength(1))), bot: v.nullish(v.boolean()), @@ -44,12 +47,22 @@ const guildSchema = v.object({ vanityUrlCode: v.nullable(v.pipe(v.string(), v.nonEmpty())), description: v.nullable(v.string()), banner: v.nullable(v.pipe(v.string(), v.nonEmpty())), - premiumSubscriptionCount: v.exactOptional(v.pipe(v.number(), v.integer(), v.minValue(0))), + premiumSubscriptionCount: v.exactOptional( + v.pipe(v.number(), v.integer(), v.minValue(0)) + ), publicUpdatesChannelId: v.nullable(snowflake), - maxVideoChannelUsers: v.exactOptional(v.pipe(v.number(), v.integer(), v.minValue(0))), - maxStageVideoChannelUsers: v.exactOptional(v.pipe(v.number(), v.integer(), v.minValue(0))), - approximateMemberCount: v.exactOptional(v.pipe(v.number(), v.integer(), v.minValue(0))), - approximatePresenceCount: v.exactOptional(v.pipe(v.number(), v.integer(), v.minValue(0))), + maxVideoChannelUsers: v.exactOptional( + v.pipe(v.number(), v.integer(), v.minValue(0)) + ), + maxStageVideoChannelUsers: v.exactOptional( + v.pipe(v.number(), v.integer(), v.minValue(0)) + ), + approximateMemberCount: v.exactOptional( + v.pipe(v.number(), v.integer(), v.minValue(0)) + ), + approximatePresenceCount: v.exactOptional( + v.pipe(v.number(), v.integer(), v.minValue(0)) + ), premiumProgressBarEnabled: v.boolean(), safetyAlertsChannelId: v.nullable(snowflake) }); @@ -85,9 +98,21 @@ const applicationCommandSchema = v.intersect([ applicationId: snowflake, guildId: v.exactOptional(snowflake), name: v.pipe(v.string(), v.minLength(1), v.maxLength(32)), - nameLocalizations: v.nullish(v.record(localesSchema, v.pipe(v.string(), v.minLength(1), v.maxLength(32)))), - description: v.exactOptional(v.pipe(v.string(), v.minLength(0), v.maxLength(100))), - descriptionLocalizations: v.nullish(v.record(localesSchema, v.pipe(v.string(), v.minLength(0), v.maxLength(100)))), + nameLocalizations: v.nullish( + v.record( + localesSchema, + v.pipe(v.string(), v.minLength(1), v.maxLength(32)) + ) + ), + description: v.exactOptional( + v.pipe(v.string(), v.minLength(0), v.maxLength(100)) + ), + descriptionLocalizations: v.nullish( + v.record( + localesSchema, + v.pipe(v.string(), v.minLength(0), v.maxLength(100)) + ) + ), defaultMemberPermissions: v.nullable(v.string()), dmPermission: v.exactOptional(v.boolean()), defaultPermission: v.exactOptional(v.boolean()), @@ -107,11 +132,21 @@ const applicationCommandSchema = v.intersect([ v.object({ name: v.pipe(v.string(), v.minLength(1), v.maxLength(32)), nameLocalizations: v.nullish( - v.record(localesSchema, v.pipe(v.string(), v.minLength(1), v.maxLength(32))) + v.record( + localesSchema, + v.pipe(v.string(), v.minLength(1), v.maxLength(32)) + ) + ), + description: v.pipe( + v.string(), + v.minLength(1), + v.maxLength(100) ), - description: v.pipe(v.string(), v.minLength(1), v.maxLength(100)), descriptionLocalizations: v.nullish( - v.record(localesSchema, v.pipe(v.string(), v.minLength(1), v.maxLength(100))) + v.record( + localesSchema, + v.pipe(v.string(), v.minLength(1), v.maxLength(100)) + ) ), required: v.nullish(v.boolean(), false), autocomplete: v.nullish(v.boolean()) @@ -131,12 +166,12 @@ const applicationCommandSchema = v.intersect([ const mockSchema = new Valimock().mock; describe(`discordkit`, () => { - it.concurrent.each([userSchema, guildTemplateSchema, applicationCommandSchema])( - `should generate valid mock data`, - { repeats: 5 }, - (schema) => { - const result = mockSchema(schema); //? - expect(v.parse(schema, result)).toStrictEqual(result); - } - ); + it.concurrent.each([ + userSchema, + guildTemplateSchema, + applicationCommandSchema + ])(`should generate valid mock data`, { repeats: 5 }, (schema) => { + const result = mockSchema(schema); //? + expect(v.parse(schema, result)).toStrictEqual(result); + }); }); diff --git a/src/__tests__/helpers/captureWarnings.ts b/src/__tests__/helpers/captureWarnings.ts index b92ecae..74fafc6 100644 --- a/src/__tests__/helpers/captureWarnings.ts +++ b/src/__tests__/helpers/captureWarnings.ts @@ -14,6 +14,7 @@ export const captureWarnings = ( warnings: string[]; } => { const warnings: string[] = []; - const mock = new Valimock({ ...options, onWarn: (msg) => warnings.push(msg) }).mock; + const mock = new Valimock({ ...options, onWarn: (msg) => warnings.push(msg) }) + .mock; return { mock, warnings }; }; diff --git a/src/__tests__/mockArray.spec.ts b/src/__tests__/mockArray.spec.ts index 07d59b0..17b723d 100644 --- a/src/__tests__/mockArray.spec.ts +++ b/src/__tests__/mockArray.spec.ts @@ -10,7 +10,12 @@ describe(`mockArray`, () => { it.concurrent.each([ v.array(v.string()), v.array(v.number()), - v.array(v.union([v.pipe(v.string(), v.url()), v.pipe(v.number(), v.maxValue(20), v.integer())])), + v.array( + v.union([ + v.pipe(v.string(), v.url()), + v.pipe(v.number(), v.maxValue(20), v.integer()) + ]) + ), v.pipe(v.array(v.string()), v.empty()), v.pipe(v.array(v.string()), v.minLength(2)), v.pipe(v.array(v.string()), v.maxLength(10)), @@ -23,15 +28,26 @@ describe(`mockArray`, () => { it.concurrent.each([ v.arrayAsync(v.string()), v.arrayAsync(v.number()), - v.arrayAsync(v.union([v.pipe(v.string(), v.url()), v.pipe(v.number(), v.maxValue(20), v.integer())])), + v.arrayAsync( + v.union([ + v.pipe(v.string(), v.url()), + v.pipe(v.number(), v.maxValue(20), v.integer()) + ]) + ), v.pipeAsync(v.arrayAsync(v.string()), v.empty()), v.pipeAsync(v.arrayAsync(v.string()), v.minLength(2)), v.pipeAsync(v.arrayAsync(v.string()), v.maxLength(10)), v.pipeAsync(v.arrayAsync(v.string()), v.length(5)) - ])(`should generate valid mock data with async validation (%#)`, { repeats: 5 }, async (schema) => { - const result = mockSchema(schema); - await expect(v.parseAsync(schema, result)).resolves.toStrictEqual(result); - }); + ])( + `should generate valid mock data with async validation (%#)`, + { repeats: 5 }, + async (schema) => { + const result = mockSchema(schema); + await expect(v.parseAsync(schema, result)).resolves.toStrictEqual( + result + ); + } + ); }); describe(`property-based`, () => { @@ -40,30 +56,56 @@ describe(`mockArray`, () => { * constraints (length bounds). The element types are covered by their own * property tests. */ - const elementSchemaArb = fc.oneof(fc.constant(v.string()), fc.constant(v.number())); + const elementSchemaArb = fc.oneof( + fc.constant(v.string()), + fc.constant(v.number()) + ); - const arraySchemaArb: fc.Arbitrary> = elementSchemaArb.chain((elem) => - fc.oneof( - fc.constant(v.array(elem) as unknown as v.GenericSchema), + const arraySchemaArb: fc.Arbitrary> = + elementSchemaArb.chain((elem) => + fc.oneof( + fc.constant(v.array(elem) as unknown as v.GenericSchema), - // Inclusive bounds. - fc - .tuple(fc.nat({ max: 5 }), fc.integer({ min: 0, max: 10 })) - .map( - ([lo, range]) => - v.pipe(v.array(elem), v.minLength(lo), v.maxLength(lo + range)) as unknown as v.GenericSchema - ), + // Inclusive bounds. + fc + .tuple(fc.nat({ max: 5 }), fc.integer({ min: 0, max: 10 })) + .map( + ([lo, range]) => + v.pipe( + v.array(elem), + v.minLength(lo), + v.maxLength(lo + range) + ) as unknown as v.GenericSchema + ), - // Exact length. - fc.nat({ max: 10 }).map((n) => v.pipe(v.array(elem), v.length(n)) as unknown as v.GenericSchema), + // Exact length. + fc + .nat({ max: 10 }) + .map( + (n) => + v.pipe( + v.array(elem), + v.length(n) + ) as unknown as v.GenericSchema + ), - // Empty. - fc.constant(v.pipe(v.array(elem), v.empty()) as unknown as v.GenericSchema), + // Empty. + fc.constant( + v.pipe(v.array(elem), v.empty()) as unknown as v.GenericSchema< + unknown[] + > + ), - // Non-empty (with a sensible upper bound). - fc.constant(v.pipe(v.array(elem), v.nonEmpty(), v.maxLength(5)) as unknown as v.GenericSchema) - ) - ); + // Non-empty (with a sensible upper bound). + fc.constant( + v.pipe( + v.array(elem), + v.nonEmpty(), + v.maxLength(5) + ) as unknown as v.GenericSchema + ) + ) + ); it(`every mock value round-trips through Valibot's parse`, () => { fc.assert( @@ -78,7 +120,11 @@ describe(`mockArray`, () => { it(`array of strings with length constraints round-trips`, () => { // Composite check: array element is itself a constrained string. This // catches regressions in element generation when wrapped by array bounds. - const schema = v.pipe(v.array(v.string()), v.minLength(1), v.maxLength(3)); + const schema = v.pipe( + v.array(v.string()), + v.minLength(1), + v.maxLength(3) + ); fc.assert( fc.property(fc.constant(schema), (s) => { const result = mockSchema(s); diff --git a/src/__tests__/mockBigint.spec.ts b/src/__tests__/mockBigint.spec.ts index 6975bb0..f5eea4e 100644 --- a/src/__tests__/mockBigint.spec.ts +++ b/src/__tests__/mockBigint.spec.ts @@ -19,10 +19,16 @@ describe(`mockBigint`, () => { it.concurrent.each([ v.pipeAsync(v.bigint(), v.minValue(100n), v.maxValue(200n)), v.pipeAsync(v.bigint(), v.value(50n)) - ])(`should generate valid mock data with async validation (%#)`, { repeats: 5 }, async (schema) => { - const result = mockSchema(schema); - await expect(v.parseAsync(schema, result)).resolves.toStrictEqual(result); - }); + ])( + `should generate valid mock data with async validation (%#)`, + { repeats: 5 }, + async (schema) => { + const result = mockSchema(schema); + await expect(v.parseAsync(schema, result)).resolves.toStrictEqual( + result + ); + } + ); }); describe(`property-based`, () => { @@ -30,16 +36,37 @@ describe(`mockBigint`, () => { const bigintSchemaArb: fc.Arbitrary> = fc.oneof( fc.constant(v.bigint()), - fc.tuple(bigintArb, fc.bigInt({ min: 0n, max: 1_000_000n })).map(([lo, range]) => { - return v.pipe(v.bigint(), v.minValue(lo), v.maxValue(lo + range)) as unknown as v.GenericSchema; - }), - fc.tuple(bigintArb, fc.bigInt({ min: 2n, max: 1_000_000n })).map(([lo, range]) => { - return v.pipe(v.bigint(), v.gtValue(lo), v.ltValue(lo + range)) as unknown as v.GenericSchema; - }), - bigintArb.map((n) => v.pipe(v.bigint(), v.value(n)) as unknown as v.GenericSchema), + fc + .tuple(bigintArb, fc.bigInt({ min: 0n, max: 1_000_000n })) + .map(([lo, range]) => { + return v.pipe( + v.bigint(), + v.minValue(lo), + v.maxValue(lo + range) + ) as unknown as v.GenericSchema; + }), + fc + .tuple(bigintArb, fc.bigInt({ min: 2n, max: 1_000_000n })) + .map(([lo, range]) => { + return v.pipe( + v.bigint(), + v.gtValue(lo), + v.ltValue(lo + range) + ) as unknown as v.GenericSchema; + }), + bigintArb.map( + (n) => + v.pipe(v.bigint(), v.value(n)) as unknown as v.GenericSchema + ), fc .array(bigintArb, { minLength: 1, maxLength: 5 }) - .map((arr) => v.pipe(v.bigint(), v.values(arr)) as unknown as v.GenericSchema) + .map( + (arr) => + v.pipe( + v.bigint(), + v.values(arr) + ) as unknown as v.GenericSchema + ) ); it(`every mock value round-trips through Valibot's parse`, () => { diff --git a/src/__tests__/mockBlob.spec.ts b/src/__tests__/mockBlob.spec.ts index ad24866..1c0fee6 100644 --- a/src/__tests__/mockBlob.spec.ts +++ b/src/__tests__/mockBlob.spec.ts @@ -11,22 +11,55 @@ const blobSchemaArb: fc.Arbitrary> = fc.oneof( fc.constant(v.blob()), // Size bounds. - fc.tuple(fc.nat({ max: 256 }), fc.integer({ min: 1, max: 512 })).map(([lo, range]) => { - return v.pipe(v.blob(), v.minSize(lo), v.maxSize(lo + range)) as unknown as v.GenericSchema; - }), + fc + .tuple(fc.nat({ max: 256 }), fc.integer({ min: 1, max: 512 })) + .map(([lo, range]) => { + return v.pipe( + v.blob(), + v.minSize(lo), + v.maxSize(lo + range) + ) as unknown as v.GenericSchema; + }), // Exact size. - fc.nat({ max: 256 }).map((n) => v.pipe(v.blob(), v.size(n)) as unknown as v.GenericSchema), + fc + .nat({ max: 256 }) + .map( + (n) => v.pipe(v.blob(), v.size(n)) as unknown as v.GenericSchema + ), // MIME type allow-list. fc - .array(fc.constantFrom(`image/png`, `image/jpeg`, `application/json`, `text/plain`), { minLength: 1, maxLength: 3 }) - .map((types) => v.pipe(v.blob(), v.mimeType(types) as BlobPipeItem) as unknown as v.GenericSchema), + .array( + fc.constantFrom( + `image/png`, + `image/jpeg`, + `application/json`, + `text/plain` + ), + { minLength: 1, maxLength: 3 } + ) + .map( + (types) => + v.pipe( + v.blob(), + v.mimeType(types) as BlobPipeItem + ) as unknown as v.GenericSchema + ), // Size + MIME combined. - fc.tuple(fc.integer({ min: 32, max: 256 }), fc.constantFrom(`image/png`, `application/pdf`)).map(([sz, mt]) => { - return v.pipe(v.blob(), v.size(sz), v.mimeType([mt]) as BlobPipeItem) as unknown as v.GenericSchema; - }) + fc + .tuple( + fc.integer({ min: 32, max: 256 }), + fc.constantFrom(`image/png`, `application/pdf`) + ) + .map(([sz, mt]) => { + return v.pipe( + v.blob(), + v.size(sz), + v.mimeType([mt]) as BlobPipeItem + ) as unknown as v.GenericSchema; + }) ); describe(`mockBlob`, () => { diff --git a/src/__tests__/mockCustom.spec.ts b/src/__tests__/mockCustom.spec.ts index d0f414e..70e79f0 100644 --- a/src/__tests__/mockCustom.spec.ts +++ b/src/__tests__/mockCustom.spec.ts @@ -10,14 +10,22 @@ describe(`mockCustom`, () => { // value, so it must surface that explicitly rather than silently // returning undefined (the previous behavior was a footgun). const { mock, warnings } = captureWarnings(); - const schema = v.custom((input) => typeof input === `string` && input === `expected`); + const schema = v.custom( + (input) => typeof input === `string` && input === `expected` + ); const result = mock(schema); expect(result).toBeUndefined(); - expect(warnings.some((w) => w.includes(`No built-in mocker`) && w.includes(`custom`))).toBe(true); + expect( + warnings.some( + (w) => w.includes(`No built-in mocker`) && w.includes(`custom`) + ) + ).toBe(true); }); it(`with a customMocks entry: the override is invoked and the result round-trips`, () => { - const schema = v.custom((input) => typeof input === `string` && input === `expected`); + const schema = v.custom( + (input) => typeof input === `string` && input === `expected` + ); const m = new Valimock({ onWarn: () => {}, customMocks: { @@ -36,6 +44,10 @@ describe(`mockCustom`, () => { const schema = v.customAsync(async (input) => typeof input === `string`); const result = mock(schema as never); expect(result).toBeUndefined(); - expect(warnings.some((w) => w.includes(`No built-in mocker`) && w.includes(`custom`))).toBe(true); + expect( + warnings.some( + (w) => w.includes(`No built-in mocker`) && w.includes(`custom`) + ) + ).toBe(true); }); }); diff --git a/src/__tests__/mockDate.spec.ts b/src/__tests__/mockDate.spec.ts index 4a40005..0533968 100644 --- a/src/__tests__/mockDate.spec.ts +++ b/src/__tests__/mockDate.spec.ts @@ -22,24 +22,48 @@ describe(`mockDate`, () => { it.concurrent.each([ v.pipeAsync(v.date(), v.minValue(requirement)), v.pipeAsync(v.date(), v.maxValue(requirement)) - ])(`should generate valid mock data with async validation (%#)`, { repeats: 5 }, async (schema) => { - const result = mockSchema(schema); - await expect(v.parseAsync(schema, result)).resolves.toStrictEqual(result); - }); + ])( + `should generate valid mock data with async validation (%#)`, + { repeats: 5 }, + async (schema) => { + const result = mockSchema(schema); + await expect(v.parseAsync(schema, result)).resolves.toStrictEqual( + result + ); + } + ); }); describe(`property-based`, () => { - const dateArb = fc.date({ min: new Date(2000, 0, 1), max: new Date(2030, 0, 1), noInvalidDate: true }); + const dateArb = fc.date({ + min: new Date(2000, 0, 1), + max: new Date(2030, 0, 1), + noInvalidDate: true + }); const dateSchemaArb: fc.Arbitrary> = fc.oneof( fc.constant(v.date()), - fc.tuple(dateArb, fc.integer({ min: 0, max: 365 })).map(([from, days]) => { - const to = new Date(from.getTime() + days * 86400000); - return v.pipe(v.date(), v.minValue(from), v.maxValue(to)) as unknown as v.GenericSchema; - }), - dateArb.map((d) => v.pipe(v.date(), v.minValue(d)) as unknown as v.GenericSchema), - dateArb.map((d) => v.pipe(v.date(), v.maxValue(d)) as unknown as v.GenericSchema), - dateArb.map((d) => v.pipe(v.date(), v.value(d)) as unknown as v.GenericSchema) + fc + .tuple(dateArb, fc.integer({ min: 0, max: 365 })) + .map(([from, days]) => { + const to = new Date(from.getTime() + days * 86400000); + return v.pipe( + v.date(), + v.minValue(from), + v.maxValue(to) + ) as unknown as v.GenericSchema; + }), + dateArb.map( + (d) => + v.pipe(v.date(), v.minValue(d)) as unknown as v.GenericSchema + ), + dateArb.map( + (d) => + v.pipe(v.date(), v.maxValue(d)) as unknown as v.GenericSchema + ), + dateArb.map( + (d) => v.pipe(v.date(), v.value(d)) as unknown as v.GenericSchema + ) ); it(`every mock value round-trips through Valibot's parse`, () => { diff --git a/src/__tests__/mockEnum.spec.ts b/src/__tests__/mockEnum.spec.ts index ec68ac5..b984b4f 100644 --- a/src/__tests__/mockEnum.spec.ts +++ b/src/__tests__/mockEnum.spec.ts @@ -34,14 +34,15 @@ describe(`mockEnum`, () => { } describe(`hand-written cases`, () => { - it.concurrent.each([v.enum(States), v.enum(Flags), v.enum(Features), v.enum(Status)])( - `should generate valid mock data (%#)`, - { repeats: 5 }, - (schema) => { - const result = mockSchema(schema); - expect(v.parse(schema, result)).toStrictEqual(result); - } - ); + it.concurrent.each([ + v.enum(States), + v.enum(Flags), + v.enum(Features), + v.enum(Status) + ])(`should generate valid mock data (%#)`, { repeats: 5 }, (schema) => { + const result = mockSchema(schema); + expect(v.parse(schema, result)).toStrictEqual(result); + }); }); describe(`property-based`, () => { @@ -72,12 +73,15 @@ describe(`mockEnum`, () => { [`string enum`, v.enum_(StringEnum), Object.values(StringEnum)], [`numeric enum`, v.enum_(NumericEnum), [0, 1, 2]], [`mixed enum`, v.enum_(MixedEnum), [`yes`, `no`, 42]] - ])(`%s: every mock value is a valid enum member and round-trips`, (_label, schema, validValues) => { - for (let i = 0; i < 50; i++) { - const result = mockSchema(schema); - expect(validValues).toContain(result); - expect(v.parse(schema, result)).toBe(result); + ])( + `%s: every mock value is a valid enum member and round-trips`, + (_label, schema, validValues) => { + for (let i = 0; i < 50; i++) { + const result = mockSchema(schema); + expect(validValues).toContain(result); + expect(v.parse(schema, result)).toBe(result); + } } - }); + ); }); }); diff --git a/src/__tests__/mockFile.spec.ts b/src/__tests__/mockFile.spec.ts index 3de2d63..62f2bfa 100644 --- a/src/__tests__/mockFile.spec.ts +++ b/src/__tests__/mockFile.spec.ts @@ -10,15 +10,39 @@ type FilePipeItem = v.PipeItem>; const fileSchemaArb: fc.Arbitrary> = fc.oneof( fc.constant(v.file()), - fc.tuple(fc.nat({ max: 256 }), fc.integer({ min: 1, max: 512 })).map(([lo, range]) => { - return v.pipe(v.file(), v.minSize(lo), v.maxSize(lo + range)) as unknown as v.GenericSchema; - }), + fc + .tuple(fc.nat({ max: 256 }), fc.integer({ min: 1, max: 512 })) + .map(([lo, range]) => { + return v.pipe( + v.file(), + v.minSize(lo), + v.maxSize(lo + range) + ) as unknown as v.GenericSchema; + }), - fc.nat({ max: 256 }).map((n) => v.pipe(v.file(), v.size(n)) as unknown as v.GenericSchema), + fc + .nat({ max: 256 }) + .map( + (n) => v.pipe(v.file(), v.size(n)) as unknown as v.GenericSchema + ), fc - .array(fc.constantFrom(`image/png`, `image/jpeg`, `application/pdf`, `text/plain`), { minLength: 1, maxLength: 3 }) - .map((types) => v.pipe(v.file(), v.mimeType(types) as FilePipeItem) as unknown as v.GenericSchema) + .array( + fc.constantFrom( + `image/png`, + `image/jpeg`, + `application/pdf`, + `text/plain` + ), + { minLength: 1, maxLength: 3 } + ) + .map( + (types) => + v.pipe( + v.file(), + v.mimeType(types) as FilePipeItem + ) as unknown as v.GenericSchema + ) ); describe(`mockFile`, () => { diff --git a/src/__tests__/mockInstance.spec.ts b/src/__tests__/mockInstance.spec.ts index 1bba82a..fde5955 100644 --- a/src/__tests__/mockInstance.spec.ts +++ b/src/__tests__/mockInstance.spec.ts @@ -44,7 +44,9 @@ describe(`mockInstance`, () => { expect(result).toBeInstanceOf(RequiresArgsClass); // The warning records that we couldn't call the real constructor. expect(warnings.some((w) => w.includes(`RequiresArgsClass`))).toBe(true); - expect(warnings.some((w) => w.includes(`prototype-based placeholder`))).toBe(true); + expect( + warnings.some((w) => w.includes(`prototype-based placeholder`)) + ).toBe(true); }); }); }); diff --git a/src/__tests__/mockIntersect.spec.ts b/src/__tests__/mockIntersect.spec.ts index cf7165d..6eef83b 100644 --- a/src/__tests__/mockIntersect.spec.ts +++ b/src/__tests__/mockIntersect.spec.ts @@ -23,10 +23,16 @@ describe(`mockIntersect`, () => { v.object({ name: v.pipe(v.string(), v.minLength(2), v.maxLength(12)) }), v.objectAsync({ email: v.pipeAsync(v.string(), v.email()) }) ]) - ])(`should generate valid mock data with async validation (%#)`, { repeats: 5 }, async (schema) => { - const result = mockSchema(schema); - await expect(v.parseAsync(schema, result)).resolves.toStrictEqual(result); - }); + ])( + `should generate valid mock data with async validation (%#)`, + { repeats: 5 }, + async (schema) => { + const result = mockSchema(schema); + await expect(v.parseAsync(schema, result)).resolves.toStrictEqual( + result + ); + } + ); }); describe(`property-based`, () => { @@ -39,11 +45,13 @@ describe(`mockIntersect`, () => { * structurally unsatisfiable, and matching-type primitive intersections * are equivalent to a single pipeline. */ - const intersectSchemaArb: fc.Arbitrary> = fc + const intersectSchemaArb: fc.Arbitrary = fc .array( fc.array( fc.record({ - key: fc.string({ minLength: 1, maxLength: 5 }).filter((k) => /^[a-zA-Z][a-zA-Z0-9]*$/.test(k)), + key: fc + .string({ minLength: 1, maxLength: 5 }) + .filter((k) => /^[a-zA-Z][a-zA-Z0-9]*$/.test(k)), valueShape: fc.constantFrom(`string`, `number`, `boolean`) }), { minLength: 1, maxLength: 3 } @@ -63,12 +71,17 @@ describe(`mockIntersect`, () => { for (const { key, valueShape } of entries) { if (usedKeys.has(key)) continue; usedKeys.add(key); - shape[key] = valueShape === `string` ? v.string() : valueShape === `number` ? v.number() : v.boolean(); + shape[key] = + valueShape === `string` + ? v.string() + : valueShape === `number` + ? v.number() + : v.boolean(); } return v.object(shape); }) .filter((opt) => Object.keys(opt.entries).length > 0); - return v.intersect(options as never) as unknown as v.GenericSchema; + return v.intersect(options as never) as unknown as v.GenericSchema; }) .filter((schema) => { // After the disjoint-keys filter some options may have collapsed to @@ -109,7 +122,10 @@ describe(`mockIntersect`, () => { description: v.nullish(v.string()), bOnly: v.string() }); - const schema = v.intersect([common, v.variant(`type`, [variantA, variantB])]); + const schema = v.intersect([ + common, + v.variant(`type`, [variantA, variantB]) + ]); for (let i = 0; i < 100; i++) { const result = mockSchema(schema) as { type?: string }; diff --git a/src/__tests__/mockMap.spec.ts b/src/__tests__/mockMap.spec.ts index d845552..8986391 100644 --- a/src/__tests__/mockMap.spec.ts +++ b/src/__tests__/mockMap.spec.ts @@ -31,18 +31,31 @@ describe(`mockMap`, () => { city: v.pipeAsync(v.string(), v.minLength(2), v.maxLength(24)) }) ) - ])(`should generate valid mock data with async validation (%#)`, { repeats: 5 }, async (schema) => { - const result = mockSchema(schema); - await expect(v.parseAsync(schema, result)).resolves.toStrictEqual(result); - }); + ])( + `should generate valid mock data with async validation (%#)`, + { repeats: 5 }, + async (schema) => { + const result = mockSchema(schema); + await expect(v.parseAsync(schema, result)).resolves.toStrictEqual( + result + ); + } + ); }); describe(`property-based`, () => { it(`map with string keys: every mock round-trips through parse`, () => { - const valueShapeArb = fc.constantFrom(v.string(), v.number(), v.boolean()); + const valueShapeArb = fc.constantFrom( + v.string(), + v.number(), + v.boolean() + ); fc.assert( fc.property(valueShapeArb, (valueSchema) => { - const schema = v.map(v.string(), valueSchema as v.GenericSchema) as unknown as v.GenericSchema; + const schema = v.map( + v.string(), + valueSchema as v.GenericSchema + ) as unknown as v.GenericSchema; const result = mockWith(2)(schema) as Map; expect(result).toBeInstanceOf(Map); expect(v.parse(schema, result)).toStrictEqual(result); @@ -52,7 +65,10 @@ describe(`mockMap`, () => { }); it(`map honors mapEntriesLength when key schema produces unique values`, () => { - const schema = v.map(v.pipe(v.string(), v.uuid()), v.number()) as unknown as v.GenericSchema; + const schema = v.map( + v.pipe(v.string(), v.uuid()), + v.number() + ) as unknown as v.GenericSchema; for (const targetLen of [1, 3, 5]) { const result = mockWith(targetLen)(schema) as Map; expect(result.size).toBe(targetLen); @@ -62,7 +78,10 @@ describe(`mockMap`, () => { it(`map shrinks gracefully when key schema produces duplicates (picklist)`, () => { // picklist with 2 options + mapEntriesLength=5 → at most 2 distinct keys // before the retry budget exhausts. - const schema = v.map(v.picklist([`a`, `b`]), v.number()) as unknown as v.GenericSchema; + const schema = v.map( + v.picklist([`a`, `b`]), + v.number() + ) as unknown as v.GenericSchema; const { mock, warnings } = captureWarnings({ mapEntriesLength: 5 }); const result = mock(schema) as Map; expect(result.size).toBeGreaterThanOrEqual(1); @@ -70,7 +89,11 @@ describe(`mockMap`, () => { for (const key of result.keys()) { expect([`a`, `b`]).toContain(key); } - expect(warnings.some((w) => w.includes(`Map generation could not reach target size`))).toBe(true); + expect( + warnings.some((w) => + w.includes(`Map generation could not reach target size`) + ) + ).toBe(true); }); }); }); diff --git a/src/__tests__/mockNumber.spec.ts b/src/__tests__/mockNumber.spec.ts index bfccc77..248e100 100644 --- a/src/__tests__/mockNumber.spec.ts +++ b/src/__tests__/mockNumber.spec.ts @@ -29,10 +29,16 @@ describe(`mockNumber`, () => { v.pipeAsync(v.number(), v.minValue(2), v.integer()), v.pipeAsync(v.number(), v.maxValue(10), v.integer()), v.pipeAsync(v.number(), v.value(5), v.integer()) - ])(`should generate valid mock data with async validation (%#)`, { repeats: 5 }, async (schema) => { - const result = mockSchema(schema); - await expect(v.parseAsync(schema, result)).resolves.toStrictEqual(result); - }); + ])( + `should generate valid mock data with async validation (%#)`, + { repeats: 5 }, + async (schema) => { + const result = mockSchema(schema); + await expect(v.parseAsync(schema, result)).resolves.toStrictEqual( + result + ); + } + ); }); describe(`property-based`, () => { @@ -46,23 +52,53 @@ describe(`mockNumber`, () => { fc.constant(v.pipe(v.number(), v.integer())), fc.constant(v.pipe(v.number(), v.safeInteger())), fc.constant(v.pipe(v.number(), v.finite())), - fc.tuple(fc.integer({ min: -100, max: 100 }), fc.integer({ min: 0, max: 100 })).map(([lo, range]) => { - return v.pipe(v.number(), v.minValue(lo), v.maxValue(lo + range)) as unknown as v.GenericSchema; - }), - fc.tuple(fc.integer({ min: -100, max: 100 }), fc.integer({ min: 2, max: 100 })).map(([lo, range]) => { - return v.pipe(v.number(), v.gtValue(lo), v.ltValue(lo + range)) as unknown as v.GenericSchema; - }), - fc.tuple(fc.integer({ min: -100, max: 100 }), fc.integer({ min: 1, max: 100 })).map(([lo, range]) => { - return v.pipe( - v.number(), - v.integer(), - v.minValue(lo), - v.maxValue(lo + range) - ) as unknown as v.GenericSchema; - }), fc - .tuple(fc.integer({ min: 2, max: 25 }), fc.integer({ min: 0, max: 50 }), fc.integer({ min: 5, max: 50 })) - .filter(([factor, lo, range]) => Math.floor((lo + range) / factor) >= Math.ceil(lo / factor)) + .tuple( + fc.integer({ min: -100, max: 100 }), + fc.integer({ min: 0, max: 100 }) + ) + .map(([lo, range]) => { + return v.pipe( + v.number(), + v.minValue(lo), + v.maxValue(lo + range) + ) as unknown as v.GenericSchema; + }), + fc + .tuple( + fc.integer({ min: -100, max: 100 }), + fc.integer({ min: 2, max: 100 }) + ) + .map(([lo, range]) => { + return v.pipe( + v.number(), + v.gtValue(lo), + v.ltValue(lo + range) + ) as unknown as v.GenericSchema; + }), + fc + .tuple( + fc.integer({ min: -100, max: 100 }), + fc.integer({ min: 1, max: 100 }) + ) + .map(([lo, range]) => { + return v.pipe( + v.number(), + v.integer(), + v.minValue(lo), + v.maxValue(lo + range) + ) as unknown as v.GenericSchema; + }), + fc + .tuple( + fc.integer({ min: 2, max: 25 }), + fc.integer({ min: 0, max: 50 }), + fc.integer({ min: 5, max: 50 }) + ) + .filter( + ([factor, lo, range]) => + Math.floor((lo + range) / factor) >= Math.ceil(lo / factor) + ) .map(([factor, lo, range]) => { return v.pipe( v.number(), @@ -74,12 +110,28 @@ describe(`mockNumber`, () => { }), fc .integer({ min: -1000, max: 1000 }) - .map((n) => v.pipe(v.number(), v.value(n)) as unknown as v.GenericSchema), + .map( + (n) => + v.pipe(v.number(), v.value(n)) as unknown as v.GenericSchema + ), fc - .array(fc.integer({ min: -100, max: 100 }), { minLength: 1, maxLength: 5 }) - .map((arr) => v.pipe(v.number(), v.values(arr)) as unknown as v.GenericSchema), + .array(fc.integer({ min: -100, max: 100 }), { + minLength: 1, + maxLength: 5 + }) + .map( + (arr) => + v.pipe( + v.number(), + v.values(arr) + ) as unknown as v.GenericSchema + ), fc - .tuple(fc.integer({ min: 0, max: 50 }), fc.integer({ min: 60, max: 100 }), fc.integer({ min: 0, max: 5 })) + .tuple( + fc.integer({ min: 0, max: 50 }), + fc.integer({ min: 60, max: 100 }), + fc.integer({ min: 0, max: 5 }) + ) .map(([lo, hi, forbidden]) => { const items: NumberPipeItem[] = [ v.integer() as NumberPipeItem, @@ -87,17 +139,28 @@ describe(`mockNumber`, () => { v.maxValue(hi) as NumberPipeItem, v.notValue(forbidden) as NumberPipeItem ]; - return v.pipe(v.number(), ...items) as unknown as v.GenericSchema; + return v.pipe( + v.number(), + ...items + ) as unknown as v.GenericSchema; }), - fc.array(fc.integer({ min: -10, max: 10 }), { minLength: 1, maxLength: 4 }).map((arr) => { - const items: NumberPipeItem[] = [ - v.integer() as NumberPipeItem, - v.minValue(-100) as NumberPipeItem, - v.maxValue(100) as NumberPipeItem, - v.notValues(arr) as NumberPipeItem - ]; - return v.pipe(v.number(), ...items) as unknown as v.GenericSchema; - }) + fc + .array(fc.integer({ min: -10, max: 10 }), { + minLength: 1, + maxLength: 4 + }) + .map((arr) => { + const items: NumberPipeItem[] = [ + v.integer() as NumberPipeItem, + v.minValue(-100) as NumberPipeItem, + v.maxValue(100) as NumberPipeItem, + v.notValues(arr) as NumberPipeItem + ]; + return v.pipe( + v.number(), + ...items + ) as unknown as v.GenericSchema; + }) ); it(`every mock value round-trips through Valibot's parse`, () => { diff --git a/src/__tests__/mockObject.spec.ts b/src/__tests__/mockObject.spec.ts index a2e0637..f890ce4 100644 --- a/src/__tests__/mockObject.spec.ts +++ b/src/__tests__/mockObject.spec.ts @@ -17,7 +17,12 @@ describe(`mockObject`, () => { v.literal(`Seattle`), v.pipe(v.string(), v.minLength(2)) ]), - postalCode: v.pipe(v.number(), v.maxValue(99999), v.integer(), v.minValue(0)) + postalCode: v.pipe( + v.number(), + v.maxValue(99999), + v.integer(), + v.minValue(0) + ) }) }) ])(`should generate valid mock data (%#)`, { repeats: 5 }, (schema) => { @@ -35,13 +40,24 @@ describe(`mockObject`, () => { v.literal(`Seattle`), v.pipeAsync(v.string(), v.minLength(2)) ]), - postalCode: v.pipeAsync(v.number(), v.maxValue(99999), v.integer(), v.minValue(0)) + postalCode: v.pipeAsync( + v.number(), + v.maxValue(99999), + v.integer(), + v.minValue(0) + ) }) }) - ])(`should generate valid mock data with async validation (%#)`, { repeats: 5 }, async (schema) => { - const result = mockSchema(schema); - await expect(v.parseAsync(schema, result)).resolves.toStrictEqual(result); - }); + ])( + `should generate valid mock data with async validation (%#)`, + { repeats: 5 }, + async (schema) => { + const result = mockSchema(schema); + await expect(v.parseAsync(schema, result)).resolves.toStrictEqual( + result + ); + } + ); }); describe(`property-based`, () => { @@ -49,7 +65,9 @@ describe(`mockObject`, () => { const objectEntriesArb = fc .uniqueArray( fc.record({ - key: fc.string({ minLength: 1, maxLength: 6 }).filter((s) => /^[a-zA-Z][a-zA-Z0-9]*$/.test(s)), + key: fc + .string({ minLength: 1, maxLength: 6 }) + .filter((s) => /^[a-zA-Z][a-zA-Z0-9]*$/.test(s)), shape: fc.constantFrom( `string`, `number`, diff --git a/src/__tests__/mockOmit.spec.ts b/src/__tests__/mockOmit.spec.ts index 9121f0d..0bbcebd 100644 --- a/src/__tests__/mockOmit.spec.ts +++ b/src/__tests__/mockOmit.spec.ts @@ -16,7 +16,12 @@ describe(`mockOmit`, () => { v.literal(`Seattle`), v.pipe(v.string(), v.minLength(2)) ]), - postalCode: v.pipe(v.number(), v.maxValue(99999), v.integer(), v.minValue(0)) + postalCode: v.pipe( + v.number(), + v.maxValue(99999), + v.integer(), + v.minValue(0) + ) }) }), [`address`] @@ -38,14 +43,25 @@ describe(`mockOmit`, () => { v.literal(`Seattle`), v.pipeAsync(v.string(), v.minLength(2)) ]), - postalCode: v.pipeAsync(v.number(), v.maxValue(99999), v.integer(), v.minValue(0)) + postalCode: v.pipeAsync( + v.number(), + v.maxValue(99999), + v.integer(), + v.minValue(0) + ) }) }), [`address`] ) - ])(`should generate valid mock data with async validation (%#)`, { repeats: 5 }, async (schema) => { - const result = mockSchema(schema); - await expect(v.parseAsync(schema, result)).resolves.toStrictEqual(result); - await expect(v.parseAsync(schema, result)).resolves.not.toHaveProperty(`address`); - }); + ])( + `should generate valid mock data with async validation (%#)`, + { repeats: 5 }, + async (schema) => { + const result = mockSchema(schema); + await expect(v.parseAsync(schema, result)).resolves.toStrictEqual(result); + await expect(v.parseAsync(schema, result)).resolves.not.toHaveProperty( + `address` + ); + } + ); }); diff --git a/src/__tests__/mockOptions.spec.ts b/src/__tests__/mockOptions.spec.ts index a80f985..2dbfac2 100644 --- a/src/__tests__/mockOptions.spec.ts +++ b/src/__tests__/mockOptions.spec.ts @@ -3,7 +3,7 @@ import * as v from "valibot"; import { MockError, Valimock } from "../Valimock.js"; import { captureWarnings } from "./helpers/captureWarnings.js"; -describe(`Valimock options`, () => { +describe(`valimock options`, () => { describe(`seed`, () => { it(`same seed across instances produces the same value`, () => { // Determinism guarantee: callers can pin output by passing `seed`. Without @@ -32,8 +32,12 @@ describe(`Valimock options`, () => { // Construct a hand-rolled "schema" with a type Valimock doesn't register // and no customMocks entry. Default behavior is to warn + return undefined; // throwOnUnknownType: true must elevate that to a thrown MockError. - const fakeSchema = { kind: `schema`, type: `synthetic_unknown_type` } as never; - const m = new Valimock({ onWarn: () => {}, throwOnUnknownType: true }).mock; + const fakeSchema = { + kind: `schema`, + type: `synthetic_unknown_type` + } as never; + const m = new Valimock({ onWarn: () => {}, throwOnUnknownType: true }) + .mock; expect(() => m(fakeSchema)).toThrow(MockError); expect(() => m(fakeSchema)).toThrow(/synthetic_unknown_type/); }); @@ -55,7 +59,9 @@ describe(`Valimock options`, () => { const schema = v.lazyAsync(async () => v.string()); const result = mock(schema as never); expect(result).toBeUndefined(); - expect(warnings.some((w) => w.includes(`lazy`) && w.includes(`Promise`))).toBe(true); + expect( + warnings.some((w) => w.includes(`lazy`) && w.includes(`Promise`)) + ).toBe(true); }); it(`lazyAsync with a sync getter still works`, () => { diff --git a/src/__tests__/mockPicklist.spec.ts b/src/__tests__/mockPicklist.spec.ts index 26c5cfc..dbbf691 100644 --- a/src/__tests__/mockPicklist.spec.ts +++ b/src/__tests__/mockPicklist.spec.ts @@ -27,7 +27,7 @@ describe(`mockPicklist`, () => { it(`every literal returns the exact literal value`, () => { fc.assert( fc.property(literalValueArb, (value) => { - const schema = v.literal(value) as unknown as v.GenericSchema; + const schema = v.literal(value) as unknown as v.GenericSchema; const result = mockSchema(schema); expect(result).toBe(value); expect(v.parse(schema, result)).toBe(value); @@ -38,12 +38,17 @@ describe(`mockPicklist`, () => { it(`every mock value is drawn from the picklist options`, () => { fc.assert( - fc.property(fc.array(literalValueArb, { minLength: 1, maxLength: 6 }), (options) => { - const schema = v.picklist(options as never) as unknown as v.GenericSchema; - const result = mockSchema(schema); - expect(options).toContain(result); - expect(v.parse(schema, result)).toBe(result); - }), + fc.property( + fc.array(literalValueArb, { minLength: 1, maxLength: 6 }), + (options) => { + const schema = v.picklist( + options as never + ) as unknown as v.GenericSchema; + const result = mockSchema(schema); + expect(options).toContain(result); + expect(v.parse(schema, result)).toBe(result); + } + ), { numRuns: 200 } ); }); diff --git a/src/__tests__/mockRecord.spec.ts b/src/__tests__/mockRecord.spec.ts index 7059c9b..7d5c341 100644 --- a/src/__tests__/mockRecord.spec.ts +++ b/src/__tests__/mockRecord.spec.ts @@ -30,18 +30,31 @@ describe(`mockRecord`, () => { city: v.pipeAsync(v.string(), v.minLength(2), v.maxLength(24)) }) ) - ])(`should generate valid mock data with async validation (%#)`, { repeats: 5 }, async (schema) => { - const result = mockSchema(schema); - await expect(v.parseAsync(schema, result)).resolves.toStrictEqual(result); - }); + ])( + `should generate valid mock data with async validation (%#)`, + { repeats: 5 }, + async (schema) => { + const result = mockSchema(schema); + await expect(v.parseAsync(schema, result)).resolves.toStrictEqual( + result + ); + } + ); }); describe(`property-based`, () => { it(`record with string keys: every mock round-trips through parse`, () => { - const valueShapeArb = fc.constantFrom(v.string(), v.number(), v.boolean()); + const valueShapeArb = fc.constantFrom( + v.string(), + v.number(), + v.boolean() + ); fc.assert( fc.property(valueShapeArb, (valueSchema) => { - const schema = v.record(v.string(), valueSchema as v.GenericSchema) as unknown as v.GenericSchema; + const schema = v.record( + v.string(), + valueSchema as v.GenericSchema + ) as unknown as v.GenericSchema; const result = mockWith(2)(schema); expect(v.parse(schema, result)).toStrictEqual(result); }), @@ -50,24 +63,34 @@ describe(`mockRecord`, () => { }); it(`record with uuid keys: keys are uuids`, () => { - const schema = v.record(v.pipe(v.string(), v.uuid()), v.number()) as unknown as v.GenericSchema; + const schema = v.record( + v.pipe(v.string(), v.uuid()), + v.number() + ) as unknown as v.GenericSchema; const result = mockWith(3)(schema) as Record; - const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + const uuidRegex = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; for (const key of Object.keys(result)) { expect(key).toMatch(uuidRegex); } }); it(`record honors recordKeysLength when key schema produces unique values`, () => { - const schema = v.record(v.pipe(v.string(), v.uuid()), v.number()) as unknown as v.GenericSchema; + const schema = v.record( + v.pipe(v.string(), v.uuid()), + v.number() + ) as unknown as v.GenericSchema; for (const targetLen of [1, 3, 5]) { const result = mockWith(targetLen)(schema) as Record; - expect(Object.keys(result).length).toBe(targetLen); + expect(Object.keys(result)).toHaveLength(targetLen); } }); it(`record may shrink when key schema produces duplicates (picklist)`, () => { - const schema = v.record(v.picklist([`a`, `b`]), v.number()) as unknown as v.GenericSchema; + const schema = v.record( + v.picklist([`a`, `b`]), + v.number() + ) as unknown as v.GenericSchema; const result = mockWith(5)(schema) as Record; expect(Object.keys(result).length).toBeGreaterThanOrEqual(1); expect(Object.keys(result).length).toBeLessThanOrEqual(2); diff --git a/src/__tests__/mockRequired.spec.ts b/src/__tests__/mockRequired.spec.ts index 72f69a1..26bae3d 100644 --- a/src/__tests__/mockRequired.spec.ts +++ b/src/__tests__/mockRequired.spec.ts @@ -12,14 +12,18 @@ describe(`mockObject`, () => { age: v.exactOptional(v.number()) }) ) - ])(`should always include all keys by default (%#)`, { repeats: 10 }, (schema) => { - const result = mockSchema(schema); - expect(v.parse(schema, result)).toStrictEqual(result); - expect(v.parse(schema, result)).toHaveProperty(`name`); - expect(v.parse(schema, result).name).toBeTypeOf(`string`); - expect(v.parse(schema, result)).toHaveProperty(`age`); - expect(v.parse(schema, result).age).toBeTypeOf(`number`); - }); + ])( + `should always include all keys by default (%#)`, + { repeats: 10 }, + (schema) => { + const result = mockSchema(schema); + expect(v.parse(schema, result)).toStrictEqual(result); + expect(v.parse(schema, result)).toHaveProperty(`name`); + expect(v.parse(schema, result).name).toBeTypeOf(`string`); + expect(v.parse(schema, result)).toHaveProperty(`age`); + expect(v.parse(schema, result).age).toBeTypeOf(`number`); + } + ); it.concurrent.each([ v.required( @@ -32,7 +36,10 @@ describe(`mockObject`, () => { ])(`should generate valid mock data (%#)`, { repeats: 10 }, (schema) => { const result = mockSchema(schema); //? expect(v.parse(schema, result)).toStrictEqual(result); - expect(v.parse(schema, result).name).toBeOneOf([expect.any(String), undefined]); + expect(v.parse(schema, result).name).toBeOneOf([ + expect.any(String), + undefined + ]); expect(v.parse(schema, result)).toHaveProperty(`age`); expect(v.parse(schema, result).age).toBeTypeOf(`number`); }); diff --git a/src/__tests__/mockSet.spec.ts b/src/__tests__/mockSet.spec.ts index c515aaa..22d2f4e 100644 --- a/src/__tests__/mockSet.spec.ts +++ b/src/__tests__/mockSet.spec.ts @@ -11,7 +11,9 @@ describe(`mockSet`, () => { const elementShapeArb = fc.constantFrom(v.string(), v.number()); fc.assert( fc.property(elementShapeArb, (element) => { - const schema = v.set(element as v.GenericSchema) as unknown as v.GenericSchema; + const schema = v.set( + element as v.GenericSchema + ) as unknown as v.GenericSchema; const result = mock(schema) as Set; expect(result).toBeInstanceOf(Set); expect(v.parse(schema, result)).toStrictEqual(result); @@ -23,7 +25,10 @@ describe(`mockSet`, () => { it(`set with exact size: result has exactly that many elements`, () => { fc.assert( fc.property(fc.integer({ min: 1, max: 8 }), (n) => { - const schema = v.pipe(v.set(v.number()), v.size(n)) as unknown as v.GenericSchema; + const schema = v.pipe( + v.set(v.number()), + v.size(n) + ) as unknown as v.GenericSchema; const result = mock(schema) as Set; expect(result.size).toBe(n); expect(v.parse(schema, result)).toStrictEqual(result); @@ -34,12 +39,22 @@ describe(`mockSet`, () => { it(`set with min/max bounds: result size within bounds`, () => { fc.assert( - fc.property(fc.tuple(fc.integer({ min: 1, max: 5 }), fc.integer({ min: 0, max: 5 })), ([lo, range]) => { - const schema = v.pipe(v.set(v.number()), v.minSize(lo), v.maxSize(lo + range)) as unknown as v.GenericSchema; - const result = mock(schema) as Set; - expect(result.size).toBeGreaterThanOrEqual(lo); - expect(result.size).toBeLessThanOrEqual(lo + range); - }), + fc.property( + fc.tuple( + fc.integer({ min: 1, max: 5 }), + fc.integer({ min: 0, max: 5 }) + ), + ([lo, range]) => { + const schema = v.pipe( + v.set(v.number()), + v.minSize(lo), + v.maxSize(lo + range) + ) as unknown as v.GenericSchema; + const result = mock(schema) as Set; + expect(result.size).toBeGreaterThanOrEqual(lo); + expect(result.size).toBeLessThanOrEqual(lo + range); + } + ), { numRuns: 50 } ); }); diff --git a/src/__tests__/mockSimpleSchemas.spec.ts b/src/__tests__/mockSimpleSchemas.spec.ts index d39c49a..b5f16ec 100644 --- a/src/__tests__/mockSimpleSchemas.spec.ts +++ b/src/__tests__/mockSimpleSchemas.spec.ts @@ -90,11 +90,14 @@ describe(`mockSimpleSchemas`, () => { it(`undefinedable: wraps inner schema, allows undefined`, () => { fc.assert( - fc.property(fc.constantFrom(v.string(), v.number(), v.boolean()), (inner) => { - const schema = v.undefinedable(inner as v.GenericSchema); - const result = mock(schema); - expect(v.parse(schema, result)).toEqual(result); - }), + fc.property( + fc.constantFrom(v.string(), v.number(), v.boolean()), + (inner) => { + const schema = v.undefinedable(inner as v.GenericSchema); + const result = mock(schema); + expect(v.parse(schema, result)).toEqual(result); + } + ), { numRuns: 100 } ); }); @@ -111,40 +114,52 @@ describe(`mockSimpleSchemas`, () => { it(`optional: wraps inner schema, allows undefined or missing`, () => { fc.assert( - fc.property(fc.constantFrom(v.string(), v.number(), v.boolean()), (inner) => { - const schema = v.optional(inner as v.GenericSchema); - const result = mock(schema); - expect(v.parse(schema, result)).toEqual(result); - }), + fc.property( + fc.constantFrom(v.string(), v.number(), v.boolean()), + (inner) => { + const schema = v.optional(inner as v.GenericSchema); + const result = mock(schema); + expect(v.parse(schema, result)).toEqual(result); + } + ), { numRuns: 100 } ); }); it(`nullable: wraps inner schema, allows null`, () => { fc.assert( - fc.property(fc.constantFrom(v.string(), v.number(), v.boolean()), (inner) => { - const schema = v.nullable(inner as v.GenericSchema); - const result = mock(schema); - expect(v.parse(schema, result)).toEqual(result); - }), + fc.property( + fc.constantFrom(v.string(), v.number(), v.boolean()), + (inner) => { + const schema = v.nullable(inner as v.GenericSchema); + const result = mock(schema); + expect(v.parse(schema, result)).toEqual(result); + } + ), { numRuns: 100 } ); }); it(`nullish: wraps inner schema, allows null or undefined`, () => { fc.assert( - fc.property(fc.constantFrom(v.string(), v.number(), v.boolean()), (inner) => { - const schema = v.nullish(inner as v.GenericSchema); - const result = mock(schema); - expect(v.parse(schema, result)).toEqual(result); - }), + fc.property( + fc.constantFrom(v.string(), v.number(), v.boolean()), + (inner) => { + const schema = v.nullish(inner as v.GenericSchema); + const result = mock(schema); + expect(v.parse(schema, result)).toEqual(result); + } + ), { numRuns: 100 } ); }); it(`lazy: recurses into getter`, () => { // Self-referential schema modelling a linked list of strings. - type Node = { value: string; next?: Node }; + interface Node { + value: string; + next?: Node; + } const nodeSchema: v.GenericSchema = v.object({ value: v.string(), next: v.optional(v.lazy(() => nodeSchema)) diff --git a/src/__tests__/mockString.spec.ts b/src/__tests__/mockString.spec.ts index face567..9e9a4d4 100644 --- a/src/__tests__/mockString.spec.ts +++ b/src/__tests__/mockString.spec.ts @@ -68,7 +68,9 @@ const stringSchemaArb = fc formatKey: fc.option(fc.constantFrom(...formatKeys), { nil: undefined }), bounds: fc.option( fc.oneof( - fc.tuple(fc.nat({ max: 64 }), fc.constant(undefined)).map(([min]) => ({ kind: `min` as const, min })), + fc + .tuple(fc.nat({ max: 64 }), fc.constant(undefined)) + .map(([min]) => ({ kind: `min` as const, min })), fc .tuple(fc.constant(undefined), fc.integer({ min: 1, max: 64 })) .map(([, max]) => ({ kind: `max` as const, max })), @@ -87,10 +89,24 @@ const stringSchemaArb = fc if (formatKey === undefined || bounds === undefined) return true; const fmt = formats[formatKey]; if (bounds.kind === `empty`) return false; - if (formatKey === `imei` && bounds.kind === `exact` && bounds.len !== 15 && bounds.len !== 18) return false; - if (formatKey === `bic` && bounds.kind === `exact` && bounds.len !== 8 && bounds.len !== 11) return false; - if (bounds.kind === `exact`) return bounds.len >= fmt.minLen && bounds.len <= fmt.maxLen; - if (bounds.kind === `range`) return bounds.min <= fmt.maxLen && bounds.max >= fmt.minLen; + if ( + formatKey === `imei` && + bounds.kind === `exact` && + bounds.len !== 15 && + bounds.len !== 18 + ) + return false; + if ( + formatKey === `bic` && + bounds.kind === `exact` && + bounds.len !== 8 && + bounds.len !== 11 + ) + return false; + if (bounds.kind === `exact`) + return bounds.len >= fmt.minLen && bounds.len <= fmt.maxLen; + if (bounds.kind === `range`) + return bounds.min <= fmt.maxLen && bounds.max >= fmt.minLen; if (bounds.kind === `max`) return bounds.max >= fmt.minLen; if (bounds.kind === `min`) return bounds.min <= fmt.maxLen; return true; @@ -121,7 +137,9 @@ const stringSchemaArb = fc } } const schema: v.GenericSchema = - items.length === 0 ? v.string() : (v.pipe(v.string(), ...items) as v.GenericSchema); + items.length === 0 + ? v.string() + : (v.pipe(v.string(), ...items) as v.GenericSchema); return schema; }); @@ -208,10 +226,14 @@ describe(`mockString`, () => { vin: v.pipe(v.string(), v.nonEmpty()), vrm: v.pipe(v.string(), v.nonEmpty()) }) - ])(`should generate valid mock data based on object keys (%#)`, { repeats: 5 }, (schema) => { - const result = mockSchema(schema); - expect(v.parse(schema, result)).toStrictEqual(result); - }); + ])( + `should generate valid mock data based on object keys (%#)`, + { repeats: 5 }, + (schema) => { + const result = mockSchema(schema); + expect(v.parse(schema, result)).toStrictEqual(result); + } + ); it.concurrent.each([ v.pipeAsync(v.string(), v.minLength(4)), @@ -220,10 +242,16 @@ describe(`mockString`, () => { v.pipeAsync(v.string(), v.minLength(4)), v.pipeAsync(v.string(), v.maxLength(16)), v.pipeAsync(v.string(), v.length(4)) - ])(`should generate valid mock data with async validation (%#)`, { repeats: 5 }, async (schema) => { - const result = mockSchema(schema); - await expect(v.parseAsync(schema, result)).resolves.toStrictEqual(result); - }); + ])( + `should generate valid mock data with async validation (%#)`, + { repeats: 5 }, + async (schema) => { + const result = mockSchema(schema); + await expect(v.parseAsync(schema, result)).resolves.toStrictEqual( + result + ); + } + ); }); describe(`property-based`, () => { @@ -246,10 +274,14 @@ describe(`mockString`, () => { }), ({ startsW, endsW }) => { const items: StringPipeItem[] = []; - if (startsW !== null) items.push(v.startsWith(startsW) as StringPipeItem); + if (startsW !== null) + items.push(v.startsWith(startsW) as StringPipeItem); if (endsW !== null) items.push(v.endsWith(endsW) as StringPipeItem); if (items.length === 0) return; - const schema = v.pipe(v.string(), ...items) as v.GenericSchema; + const schema = v.pipe( + v.string(), + ...items + ) as v.GenericSchema; const value = mock(schema); expect(v.parse(schema, value)).toBe(value); } @@ -279,7 +311,12 @@ describe(`mockString`, () => { }); it(`startsWith + endsWith + maxLength: enforce truncates while preserving tail`, () => { - const schema = v.pipe(v.string(), v.startsWith(`a`), v.endsWith(`z`), v.maxLength(20)); + const schema = v.pipe( + v.string(), + v.startsWith(`a`), + v.endsWith(`z`), + v.maxLength(20) + ); for (let i = 0; i < 20; i++) { const result = mock(schema); expect(result.startsWith(`a`)).toBe(true); @@ -300,7 +337,10 @@ describe(`mockString`, () => { }); it(`excludes: result does not contain forbidden substrings (retry until satisfied)`, () => { - const schema = v.pipe(v.string(), v.excludes(`zzzzzz`)) as v.GenericSchema; + const schema = v.pipe( + v.string(), + v.excludes(`zzzzzz`) + ) as v.GenericSchema; for (let i = 0; i < 20; i++) { const result = mock(schema); expect(result).not.toContain(`zzzzzz`); @@ -329,7 +369,11 @@ describe(`mockString`, () => { }); it(`values + not_values: produces an allow-list entry not in the forbidden set`, () => { - const schema = v.pipe(v.string(), v.values([`good`, `bad`, `ugly`]), v.notValues([`bad`])); + const schema = v.pipe( + v.string(), + v.values([`good`, `bad`, `ugly`]), + v.notValues([`bad`]) + ); for (let i = 0; i < 30; i++) { const result = mock(schema); expect([`good`, `ugly`]).toContain(result); @@ -338,7 +382,10 @@ describe(`mockString`, () => { }); it(`not_value: never returns the forbidden string`, () => { - const schema = v.pipe(v.string(), v.notValue(`forbidden-exact-value-aaa`)); + const schema = v.pipe( + v.string(), + v.notValue(`forbidden-exact-value-aaa`) + ); for (let i = 0; i < 30; i++) { const result = mock(schema); expect(result).not.toBe(`forbidden-exact-value-aaa`); @@ -348,7 +395,14 @@ describe(`mockString`, () => { describe(`edge cases — length constraints`, () => { it(`not_length: result length avoids the forbidden value`, () => { - const schema = v.pipe(v.string(), v.minLength(4), v.maxLength(8), v.notLength(5), v.notLength(6), v.notLength(7)); + const schema = v.pipe( + v.string(), + v.minLength(4), + v.maxLength(8), + v.notLength(5), + v.notLength(6), + v.notLength(7) + ); for (let i = 0; i < 30; i++) { const result = mock(schema); expect([4, 8]).toContain(result.length); @@ -359,7 +413,7 @@ describe(`mockString`, () => { describe(`edge cases — stringMap override`, () => { it(`stringMap entry is invoked when keyName matches`, () => { - const customMock = vi.fn(() => `CUSTOM-VALUE`); + const customMock = vi.fn<() => string>(() => `CUSTOM-VALUE`); const mockWithMap = new Valimock({ onWarn: () => {}, stringMap: { customField: customMock } @@ -368,7 +422,7 @@ describe(`mockString`, () => { const objSchema = v.object({ customField: v.string() }); const result = mockWithMap(objSchema as never) as { customField: string }; expect(result.customField).toBe(`CUSTOM-VALUE`); - expect(customMock).toHaveBeenCalled(); + expect(customMock).toHaveBeenCalledWith(); }); it(`stringMap overrides format generators by key name`, () => { diff --git a/src/__tests__/mockTuple.spec.ts b/src/__tests__/mockTuple.spec.ts index 04a78ef..d98528e 100644 --- a/src/__tests__/mockTuple.spec.ts +++ b/src/__tests__/mockTuple.spec.ts @@ -5,28 +5,52 @@ import { Valimock } from "../Valimock.js"; const mockSchema = new Valimock({ onWarn: () => {} }).mock; -const tupleItemsArb = fc.array(fc.constantFrom(v.string(), v.number(), v.boolean()), { minLength: 1, maxLength: 4 }); +const tupleItemsArb = fc.array( + fc.constantFrom(v.string(), v.number(), v.boolean()), + { minLength: 1, maxLength: 4 } +); describe(`mockTuple`, () => { describe(`hand-written cases`, () => { it.concurrent.each([ - v.tuple([v.pipe(v.string(), v.url()), v.pipe(v.number(), v.maxValue(20), v.integer())]), - v.pipe(v.tuple([v.pipe(v.string(), v.url()), v.pipe(v.number(), v.maxValue(20), v.integer())]), v.maxLength(2)) + v.tuple([ + v.pipe(v.string(), v.url()), + v.pipe(v.number(), v.maxValue(20), v.integer()) + ]), + v.pipe( + v.tuple([ + v.pipe(v.string(), v.url()), + v.pipe(v.number(), v.maxValue(20), v.integer()) + ]), + v.maxLength(2) + ) ])(`should generate valid mock data (%#)`, { repeats: 5 }, (schema) => { const result = mockSchema(schema); expect(v.parse(schema, result)).toStrictEqual(result); }); it.concurrent.each([ - v.tupleAsync([v.pipe(v.string(), v.url()), v.pipeAsync(v.number(), v.maxValue(20), v.integer())]), + v.tupleAsync([ + v.pipe(v.string(), v.url()), + v.pipeAsync(v.number(), v.maxValue(20), v.integer()) + ]), v.pipeAsync( - v.tupleAsync([v.pipe(v.string(), v.url()), v.pipeAsync(v.number(), v.maxValue(20), v.integer())]), + v.tupleAsync([ + v.pipe(v.string(), v.url()), + v.pipeAsync(v.number(), v.maxValue(20), v.integer()) + ]), v.maxLength(2) ) - ])(`should generate valid mock data with async validation (%#)`, { repeats: 5 }, async (schema) => { - const result = mockSchema(schema); - await expect(v.parseAsync(schema, result)).resolves.toStrictEqual(result); - }); + ])( + `should generate valid mock data with async validation (%#)`, + { repeats: 5 }, + async (schema) => { + const result = mockSchema(schema); + await expect(v.parseAsync(schema, result)).resolves.toStrictEqual( + result + ); + } + ); }); describe(`property-based`, () => { @@ -35,7 +59,7 @@ describe(`mockTuple`, () => { fc.property(tupleItemsArb, (items) => { const schema = v.tuple(items as never) as unknown as v.GenericSchema; const result = mockSchema(schema) as unknown[]; - expect(result.length).toBe(items.length); + expect(result).toHaveLength(items.length); expect(v.parse(schema, result)).toStrictEqual(result); }), { numRuns: 100 } @@ -45,9 +69,11 @@ describe(`mockTuple`, () => { it(`loose_tuple: declared positions present; extra positions tolerated by parse`, () => { fc.assert( fc.property(tupleItemsArb, (items) => { - const schema = v.looseTuple(items as never) as unknown as v.GenericSchema; + const schema = v.looseTuple( + items as never + ) as unknown as v.GenericSchema; const result = mockSchema(schema) as unknown[]; - expect(result.length).toBe(items.length); + expect(result).toHaveLength(items.length); expect(v.parse(schema, result)).toStrictEqual(result); }), { numRuns: 100 } @@ -57,9 +83,11 @@ describe(`mockTuple`, () => { it(`strict_tuple: exactly the declared positions, nothing more`, () => { fc.assert( fc.property(tupleItemsArb, (items) => { - const schema = v.strictTuple(items as never) as unknown as v.GenericSchema; + const schema = v.strictTuple( + items as never + ) as unknown as v.GenericSchema; const result = mockSchema(schema) as unknown[]; - expect(result.length).toBe(items.length); + expect(result).toHaveLength(items.length); expect(v.parse(schema, result)).toStrictEqual(result); }), { numRuns: 100 } @@ -73,9 +101,12 @@ describe(`mockTuple`, () => { // emitted prefix matches the declared positions. fc.assert( fc.property(tupleItemsArb, (items) => { - const schema = v.tupleWithRest(items as never, v.string()) as unknown as v.GenericSchema; + const schema = v.tupleWithRest( + items as never, + v.string() + ) as unknown as v.GenericSchema; const result = mockSchema(schema) as unknown[]; - expect(result.length).toBe(items.length); + expect(result).toHaveLength(items.length); expect(v.parse(schema, result)).toStrictEqual(result); }), { numRuns: 100 } diff --git a/src/__tests__/mockUnion.spec.ts b/src/__tests__/mockUnion.spec.ts index 6bd8fab..9be4035 100644 --- a/src/__tests__/mockUnion.spec.ts +++ b/src/__tests__/mockUnion.spec.ts @@ -5,7 +5,7 @@ import { Valimock } from "../Valimock.js"; const mockSchema = new Valimock({ onWarn: () => {} }).mock; -const unionSchemaArb: fc.Arbitrary> = fc +const unionSchemaArb: fc.Arbitrary = fc .array( fc.oneof( fc.constant(v.string()), @@ -16,25 +16,35 @@ const unionSchemaArb: fc.Arbitrary> = fc ), { minLength: 2, maxLength: 4 } ) - .map((options) => v.union(options as never) as unknown as v.GenericSchema); + .map((options) => v.union(options as never) as unknown as v.GenericSchema); describe(`mockUnion`, () => { describe(`hand-written cases`, () => { - it.concurrent.each([v.union([v.pipe(v.string(), v.url()), v.pipe(v.number(), v.maxValue(20), v.integer())])])( - `should generate valid mock data (%#)`, + it.concurrent.each([ + v.union([ + v.pipe(v.string(), v.url()), + v.pipe(v.number(), v.maxValue(20), v.integer()) + ]) + ])(`should generate valid mock data (%#)`, { repeats: 5 }, (schema) => { + const result = mockSchema(schema); + expect(v.parse(schema, result)).toStrictEqual(result); + }); + + it.concurrent.each([ + v.unionAsync([ + v.pipe(v.string(), v.url()), + v.pipeAsync(v.number(), v.maxValue(20), v.integer()) + ]) + ])( + `should generate valid mock data with async validation (%#)`, { repeats: 5 }, - (schema) => { + async (schema) => { const result = mockSchema(schema); - expect(v.parse(schema, result)).toStrictEqual(result); + await expect(v.parseAsync(schema, result)).resolves.toStrictEqual( + result + ); } ); - - it.concurrent.each([ - v.unionAsync([v.pipe(v.string(), v.url()), v.pipeAsync(v.number(), v.maxValue(20), v.integer())]) - ])(`should generate valid mock data with async validation (%#)`, { repeats: 5 }, async (schema) => { - const result = mockSchema(schema); - await expect(v.parseAsync(schema, result)).resolves.toStrictEqual(result); - }); }); describe(`property-based`, () => { @@ -54,7 +64,7 @@ describe(`mockUnion`, () => { inner, v.boolean(), v.pipe(v.number(), v.maxValue(10)) - ]) as unknown as v.GenericSchema; + ]) as unknown as v.GenericSchema; fc.assert( fc.property(fc.constant(outer), (s) => { const result = mockSchema(s); @@ -84,7 +94,10 @@ describe(`mockUnion`, () => { it(`onWarn fires for unions where no option survives the round-trip`, () => { // Option[0] strictly contains option[1]'s shape. The retry loop's // untried-option preference recovers without emitting the warning. - const schema = v.union([v.object({ kind: v.string() }), v.object({ kind: v.string(), more: v.number() })]); + const schema = v.union([ + v.object({ kind: v.string() }), + v.object({ kind: v.string(), more: v.number() }) + ]); const m = new Valimock({ onWarn: () => {} }).mock; for (let i = 0; i < 20; i++) { const result = m(schema); diff --git a/src/__tests__/mockVariant.spec.ts b/src/__tests__/mockVariant.spec.ts index c64462b..9f1274b 100644 --- a/src/__tests__/mockVariant.spec.ts +++ b/src/__tests__/mockVariant.spec.ts @@ -56,7 +56,9 @@ const vehiclesSchema = v.intersect([ }) ]), v.object({ - kind: v.exactOptional(v.picklist([`car`, `boat`, `motorcylce`, `airplane`])) + kind: v.exactOptional( + v.picklist([`car`, `boat`, `motorcylce`, `airplane`]) + ) }) ]) ]); @@ -94,7 +96,7 @@ const nestedSchema = v.intersect([ ]) ]); -const variantSchemaArb: fc.Arbitrary> = fc +const variantSchemaArb: fc.Arbitrary = fc .array( fc .record({ @@ -115,10 +117,15 @@ const variantSchemaArb: fc.Arbitrary> = fc }) .map((entries) => { const options = entries.map(({ tag, bodyShape }) => { - const body = bodyShape === `string` ? v.string() : bodyShape === `number` ? v.number() : v.boolean(); + const body = + bodyShape === `string` + ? v.string() + : bodyShape === `number` + ? v.number() + : v.boolean(); return v.object({ type: v.literal(tag), data: body }); }); - return v.variant(`type`, options as never) as unknown as v.GenericSchema; + return v.variant(`type`, options as never) as unknown as v.GenericSchema; }); describe(`mockVariant`, () => { diff --git a/src/__tests__/wrapperLaziness.spec.ts b/src/__tests__/wrapperLaziness.spec.ts index 411b7af..86ef325 100644 --- a/src/__tests__/wrapperLaziness.spec.ts +++ b/src/__tests__/wrapperLaziness.spec.ts @@ -122,7 +122,10 @@ describe(`wrapper handlers are lazy`, () => { // 1000ms+ per mock and occasional stack-overflow. Under the fix, each // level's recursion gates on a coin flip — so the tree terminates // probabilistically and total work stays bounded. - type Node = { id: string; child?: Node | null }; + interface Node { + id: string; + child?: Node | null; + } const recursive: v.GenericSchema = v.object({ id: v.string(), child: v.nullish(v.lazy(() => recursive)) @@ -134,7 +137,7 @@ describe(`wrapper handlers are lazy`, () => { // process either throws "Maximum call stack size exceeded" or // times out. for (let i = 0; i < 100; i++) { - const result = mock(recursive) as Node; + const result = mock(recursive); expect(typeof result.id).toBe(`string`); } }); diff --git a/src/schemas/array.ts b/src/schemas/array.ts index adf928f..f834966 100644 --- a/src/schemas/array.ts +++ b/src/schemas/array.ts @@ -1,6 +1,12 @@ import type { Faker } from "@faker-js/faker"; import type * as v from "valibot"; -import { makeBounds, reconcileBounds, tightenMax, tightenMin, type Bounds } from "../utils/bounds.js"; +import { + makeBounds, + reconcileBounds, + tightenMax, + tightenMin, + type Bounds +} from "../utils/bounds.js"; import { readNumber } from "../utils/readRequirement.js"; import { walkPipe } from "../utils/walkPipe.js"; import { unhandledValidation } from "../utils/warnings.js"; @@ -33,15 +39,24 @@ interface ArrayContext { const DEFAULTS = { min: 1, max: 5 }; const handlers = { - length: (ctx: ArrayContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { + length: ( + ctx: ArrayContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { const n = readNumber(action); if (n !== undefined) ctx.exactLength = n; }, - min_length: (ctx: ArrayContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { + min_length: ( + ctx: ArrayContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { const n = readNumber(action); if (n !== undefined) tightenMin(ctx.bounds, n); }, - max_length: (ctx: ArrayContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { + max_length: ( + ctx: ArrayContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { const n = readNumber(action); if (n !== undefined) tightenMax(ctx.bounds, n); }, @@ -53,22 +68,26 @@ const handlers = { } }; -export const generateArray = (schema: ArraySchemaInput, options: GenerateArrayOptions): unknown[] => { +export const generateArray = ( + schema: ArraySchemaInput, + options: GenerateArrayOptions +): unknown[] => { const ctx: ArrayContext = { bounds: makeBounds(DEFAULTS), exactLength: undefined, forceEmpty: false }; - walkPipe(schema, ctx, handlers, (type) => options.onWarn?.(unhandledValidation(`array`, type))); + walkPipe(schema, ctx, handlers, (type) => + options.onWarn?.(unhandledValidation(`array`, type)) + ); if (ctx.forceEmpty) return []; reconcileBounds(ctx.bounds); const length = - ctx.exactLength !== undefined - ? ctx.exactLength - : options.faker.number.int({ min: ctx.bounds.min, max: ctx.bounds.max }); + ctx.exactLength ?? + options.faker.number.int({ min: ctx.bounds.min, max: ctx.bounds.max }); return Array.from({ length }, () => options.mockItem(schema.item)); }; diff --git a/src/schemas/bigint.ts b/src/schemas/bigint.ts index eb35e72..48f7053 100644 --- a/src/schemas/bigint.ts +++ b/src/schemas/bigint.ts @@ -14,7 +14,9 @@ export interface GenerateBigintOptions { onWarn?: (message: string) => void; } -export type BigintSchemaInput = SchemaMaybeWithPipe | undefined>>; +export type BigintSchemaInput = SchemaMaybeWithPipe< + v.BigintSchema | undefined> +>; interface BigintContext { exactValue: bigint | undefined; @@ -24,30 +26,53 @@ interface BigintContext { } const handlers = { - value: (ctx: BigintContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { + value: ( + ctx: BigintContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { const b = readBigint(action); if (b !== undefined) ctx.exactValue = b; }, - values: (ctx: BigintContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { - const allowed = readArray(action, (x): x is bigint => typeof x === `bigint`); + values: ( + ctx: BigintContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { + const allowed = readArray( + action, + (x): x is bigint => typeof x === `bigint` + ); if (allowed) ctx.allowedValues = allowed; }, - min_value: (ctx: BigintContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { + min_value: ( + ctx: BigintContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { const b = readBigint(action); - if (b !== undefined) ctx.min = ctx.min === undefined ? b : ctx.min > b ? ctx.min : b; + if (b !== undefined) + ctx.min = ctx.min === undefined ? b : ctx.min > b ? ctx.min : b; }, - max_value: (ctx: BigintContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { + max_value: ( + ctx: BigintContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { const b = readBigint(action); - if (b !== undefined) ctx.max = ctx.max === undefined ? b : ctx.max < b ? ctx.max : b; + if (b !== undefined) + ctx.max = ctx.max === undefined ? b : ctx.max < b ? ctx.max : b; }, - gt_value: (ctx: BigintContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { + gt_value: ( + ctx: BigintContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { const b = readBigint(action); if (b !== undefined) { const next = b + 1n; ctx.min = ctx.min === undefined ? next : ctx.min > next ? ctx.min : next; } }, - lt_value: (ctx: BigintContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { + lt_value: ( + ctx: BigintContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { const b = readBigint(action); if (b !== undefined) { const next = b - 1n; @@ -56,11 +81,22 @@ const handlers = { } }; -export const generateBigint = (schema: BigintSchemaInput, options: GenerateBigintOptions): bigint => { - const ctx: BigintContext = { exactValue: undefined, allowedValues: undefined, min: undefined, max: undefined }; - walkPipe(schema, ctx, handlers, (type) => options.onWarn?.(unhandledValidation(`bigint`, type))); +export const generateBigint = ( + schema: BigintSchemaInput, + options: GenerateBigintOptions +): bigint => { + const ctx: BigintContext = { + exactValue: undefined, + allowedValues: undefined, + min: undefined, + max: undefined + }; + walkPipe(schema, ctx, handlers, (type) => + options.onWarn?.(unhandledValidation(`bigint`, type)) + ); if (ctx.exactValue !== undefined) return ctx.exactValue; - if (ctx.allowedValues && ctx.allowedValues.length > 0) return options.faker.helpers.arrayElement(ctx.allowedValues); + if (ctx.allowedValues && ctx.allowedValues.length > 0) + return options.faker.helpers.arrayElement(ctx.allowedValues); return options.faker.number.bigInt({ min: ctx.min, max: ctx.max }); }; diff --git a/src/schemas/blob.ts b/src/schemas/blob.ts index fc51198..5cf24cf 100644 --- a/src/schemas/blob.ts +++ b/src/schemas/blob.ts @@ -1,5 +1,12 @@ import type * as v from "valibot"; -import { makeBounds, pickAvoiding, reconcileBounds, tightenMax, tightenMin, type Bounds } from "../utils/bounds.js"; +import { + makeBounds, + pickAvoiding, + reconcileBounds, + tightenMax, + tightenMin, + type Bounds +} from "../utils/bounds.js"; import { readNumber, readRequirement } from "../utils/readRequirement.js"; import { walkPipe } from "../utils/walkPipe.js"; import { unhandledValidation } from "../utils/warnings.js"; @@ -14,7 +21,9 @@ export interface GenerateBlobOptions { onWarn?: (message: string) => void; } -export type BlobSchemaInput = SchemaMaybeWithPipe | undefined>>; +export type BlobSchemaInput = SchemaMaybeWithPipe< + v.BlobSchema | undefined> +>; interface BlobContext { bounds: Bounds; @@ -26,23 +35,38 @@ interface BlobContext { const DEFAULTS = { min: 0, max: 1024 }; const handlers = { - size: (ctx: BlobContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { + size: ( + ctx: BlobContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { const n = readNumber(action); if (n !== undefined) ctx.exactSize = n; }, - min_size: (ctx: BlobContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { + min_size: ( + ctx: BlobContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { const n = readNumber(action); if (n !== undefined) tightenMin(ctx.bounds, n); }, - max_size: (ctx: BlobContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { + max_size: ( + ctx: BlobContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { const n = readNumber(action); if (n !== undefined) tightenMax(ctx.bounds, n); }, - not_size: (ctx: BlobContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { + not_size: ( + ctx: BlobContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { const n = readNumber(action); if (n !== undefined) ctx.forbiddenSizes.add(n); }, - mime_type: (ctx: BlobContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { + mime_type: ( + ctx: BlobContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { const req = readRequirement(action); if (Array.isArray(req)) { const types = req.filter((v): v is string => typeof v === `string`); @@ -51,7 +75,10 @@ const handlers = { } }; -export const generateBlob = (schema: BlobSchemaInput, options: GenerateBlobOptions): unknown => { +export const generateBlob = ( + schema: BlobSchemaInput, + options: GenerateBlobOptions +): unknown => { if (typeof Blob === `undefined`) { options.onWarn?.(`blob: no Blob global available in this environment`); return {}; @@ -64,12 +91,18 @@ export const generateBlob = (schema: BlobSchemaInput, options: GenerateBlobOptio mimeTypes: undefined }; - walkPipe(schema, ctx, handlers, (type) => options.onWarn?.(unhandledValidation(`blob`, type))); + walkPipe(schema, ctx, handlers, (type) => + options.onWarn?.(unhandledValidation(`blob`, type)) + ); reconcileBounds(ctx.bounds); // For blobs the "target" is just the byte length. Use the bounds midpoint // as the seed when no exact size was requested. - const targetSize = pickAvoiding(ctx.bounds, ctx.forbiddenSizes, ctx.exactSize); + const targetSize = pickAvoiding( + ctx.bounds, + ctx.forbiddenSizes, + ctx.exactSize + ); const type = ctx.mimeTypes ? ctx.mimeTypes[0] : ``; const buf = new Uint8Array(targetSize); diff --git a/src/schemas/date.ts b/src/schemas/date.ts index ce4d429..b58fa5f 100644 --- a/src/schemas/date.ts +++ b/src/schemas/date.ts @@ -14,7 +14,9 @@ export interface GenerateDateOptions { onWarn?: (message: string) => void; } -export type DateSchemaInput = SchemaMaybeWithPipe | undefined>>; +export type DateSchemaInput = SchemaMaybeWithPipe< + v.DateSchema | undefined> +>; interface DateContext { exactValue: Date | undefined; @@ -23,26 +25,45 @@ interface DateContext { } const handlers = { - value: (ctx: DateContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { + value: ( + ctx: DateContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { const d = readDate(action); if (d) ctx.exactValue = d; }, - min_value: (ctx: DateContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { + min_value: ( + ctx: DateContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { const d = readDate(action); if (d) ctx.min = d; }, - max_value: (ctx: DateContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { + max_value: ( + ctx: DateContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { const d = readDate(action); if (d) ctx.max = d; } }; -export const generateDate = (schema: DateSchemaInput, options: GenerateDateOptions): Date => { - const ctx: DateContext = { exactValue: undefined, min: undefined, max: undefined }; - walkPipe(schema, ctx, handlers, (type) => options.onWarn?.(unhandledValidation(`date`, type))); +export const generateDate = ( + schema: DateSchemaInput, + options: GenerateDateOptions +): Date => { + const ctx: DateContext = { + exactValue: undefined, + min: undefined, + max: undefined + }; + walkPipe(schema, ctx, handlers, (type) => + options.onWarn?.(unhandledValidation(`date`, type)) + ); if (ctx.exactValue) return ctx.exactValue; - if (ctx.min && ctx.max) return options.faker.date.between({ from: ctx.min, to: ctx.max }); + if (ctx.min && ctx.max) + return options.faker.date.between({ from: ctx.min, to: ctx.max }); if (ctx.min) return options.faker.date.soon({ refDate: ctx.min }); if (ctx.max) return options.faker.date.recent({ refDate: ctx.max }); return options.faker.date.soon(); diff --git a/src/schemas/file.ts b/src/schemas/file.ts index d87c3f2..b6e4a28 100644 --- a/src/schemas/file.ts +++ b/src/schemas/file.ts @@ -1,5 +1,12 @@ import type * as v from "valibot"; -import { makeBounds, pickAvoiding, reconcileBounds, tightenMax, tightenMin, type Bounds } from "../utils/bounds.js"; +import { + makeBounds, + pickAvoiding, + reconcileBounds, + tightenMax, + tightenMin, + type Bounds +} from "../utils/bounds.js"; import { readNumber, readRequirement } from "../utils/readRequirement.js"; import { walkPipe } from "../utils/walkPipe.js"; import { unhandledValidation } from "../utils/warnings.js"; @@ -13,7 +20,9 @@ export interface GenerateFileOptions { onWarn?: (message: string) => void; } -export type FileSchemaInput = SchemaMaybeWithPipe | undefined>>; +export type FileSchemaInput = SchemaMaybeWithPipe< + v.FileSchema | undefined> +>; interface FileContext { bounds: Bounds; @@ -25,23 +34,38 @@ interface FileContext { const DEFAULTS = { min: 0, max: 1024 }; const handlers = { - size: (ctx: FileContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { + size: ( + ctx: FileContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { const n = readNumber(action); if (n !== undefined) ctx.exactSize = n; }, - min_size: (ctx: FileContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { + min_size: ( + ctx: FileContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { const n = readNumber(action); if (n !== undefined) tightenMin(ctx.bounds, n); }, - max_size: (ctx: FileContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { + max_size: ( + ctx: FileContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { const n = readNumber(action); if (n !== undefined) tightenMax(ctx.bounds, n); }, - not_size: (ctx: FileContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { + not_size: ( + ctx: FileContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { const n = readNumber(action); if (n !== undefined) ctx.forbiddenSizes.add(n); }, - mime_type: (ctx: FileContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { + mime_type: ( + ctx: FileContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { const req = readRequirement(action); if (Array.isArray(req)) { const types = req.filter((v): v is string => typeof v === `string`); @@ -50,7 +74,10 @@ const handlers = { } }; -export const generateFile = (schema: FileSchemaInput, options: GenerateFileOptions): unknown => { +export const generateFile = ( + schema: FileSchemaInput, + options: GenerateFileOptions +): unknown => { if (typeof File === `undefined`) { options.onWarn?.(`file: no File global available in this environment`); return {}; @@ -63,10 +90,16 @@ export const generateFile = (schema: FileSchemaInput, options: GenerateFileOptio mimeTypes: undefined }; - walkPipe(schema, ctx, handlers, (type) => options.onWarn?.(unhandledValidation(`file`, type))); + walkPipe(schema, ctx, handlers, (type) => + options.onWarn?.(unhandledValidation(`file`, type)) + ); reconcileBounds(ctx.bounds); - const targetSize = pickAvoiding(ctx.bounds, ctx.forbiddenSizes, ctx.exactSize); + const targetSize = pickAvoiding( + ctx.bounds, + ctx.forbiddenSizes, + ctx.exactSize + ); const type = ctx.mimeTypes ? ctx.mimeTypes[0] : ``; const buf = new Uint8Array(targetSize); diff --git a/src/schemas/intersect.ts b/src/schemas/intersect.ts index 79f7fdf..905cf9b 100644 --- a/src/schemas/intersect.ts +++ b/src/schemas/intersect.ts @@ -1,4 +1,5 @@ import type * as v from "valibot"; +import { isObject } from "../utils/guards"; /** * Generate a mock value for a Valibot intersect schema. Intersect requires @@ -33,11 +34,22 @@ export interface GenerateIntersectOptions { } export type IntersectSchemaInput = - | v.IntersectSchema | undefined> - | v.IntersectSchemaAsync | undefined>; + | v.IntersectSchema< + v.IntersectOptions, + v.ErrorMessage | undefined + > + | v.IntersectSchemaAsync< + v.IntersectOptionsAsync, + v.ErrorMessage | undefined + >; -export const generateIntersect = (schema: IntersectSchemaInput, options: GenerateIntersectOptions): unknown => { - const opts = schema.options as ReadonlyArray; +export const generateIntersect = ( + schema: IntersectSchemaInput, + options: GenerateIntersectOptions +): unknown => { + const opts = schema.options as ReadonlyArray< + v.GenericSchema | v.GenericSchemaAsync + >; if (opts.length === 0) return {}; let result = options.mockItem(opts[0]); @@ -85,17 +97,17 @@ const deepMerge = (a: unknown, b: unknown): MergeResult => { if (typeof a !== typeof b) return { issue: true }; if (a === b) return { value: a }; if (a instanceof Date && b instanceof Date && +a === +b) return { value: a }; - if (a && b && (a as object).constructor === Object && (b as object).constructor === Object) { - const out: Record = { ...(a as Record) }; - for (const key in b as Record) { - if (key in (a as Record)) { - const sub = deepMerge((a as Record)[key], (b as Record)[key]); + if (isObject(a) && isObject(b)) { + const out: Record = { ...a }; + for (const key in b) { + if (key in a) { + const sub = deepMerge(a[key], b[key]); // Recover at the key level: a failed sub-merge picks b's value // rather than discarding the whole parent object merge. See the // "deliberate divergence" note above. - out[key] = sub.issue ? (b as Record)[key] : sub.value; + out[key] = sub.issue ? b[key] : sub.value; } else { - out[key] = (b as Record)[key]; + out[key] = b[key]; } } return { value: out }; diff --git a/src/schemas/map.ts b/src/schemas/map.ts index 0503233..01ed15d 100644 --- a/src/schemas/map.ts +++ b/src/schemas/map.ts @@ -23,7 +23,10 @@ export type MapSchemaInput = /** Cap on attempts to grow the result Map when duplicate keys collide. */ const ADD_RETRY_BUDGET = 256; -export const generateMap = (schema: MapSchemaInput, options: GenerateMapOptions): Map => { +export const generateMap = ( + schema: MapSchemaInput, + options: GenerateMapOptions +): Map => { const result = new Map(); let attempts = 0; while (result.size < options.entriesLength && attempts < ADD_RETRY_BUDGET) { diff --git a/src/schemas/number/actionHandlers.ts b/src/schemas/number/actionHandlers.ts index 8de7ccc..e9af52e 100644 --- a/src/schemas/number/actionHandlers.ts +++ b/src/schemas/number/actionHandlers.ts @@ -14,7 +14,10 @@ export const numberActionHandlers: Record = { if (req !== undefined) ctx.exactValue = req; }, values: (ctx, action) => { - const allowed = readArray(action, (x): x is number => typeof x === `number`); + const allowed = readArray( + action, + (x): x is number => typeof x === `number` + ); if (allowed) ctx.allowedValues = allowed; }, not_value: (ctx, action) => { @@ -22,7 +25,10 @@ export const numberActionHandlers: Record = { if (req !== undefined) ctx.forbidden.add(req); }, not_values: (ctx, action) => { - const allowed = readArray(action, (x): x is number => typeof x === `number`); + const allowed = readArray( + action, + (x): x is number => typeof x === `number` + ); if (allowed) for (const v of allowed) ctx.forbidden.add(v); }, min_value: (ctx, action) => { @@ -56,7 +62,9 @@ export const numberActionHandlers: Record = { } }; -export const knownNumberActionTypes = new Set(Object.keys(numberActionHandlers)); +export const knownNumberActionTypes = new Set( + Object.keys(numberActionHandlers) +); /** Reconcile bounds after collection — snap to integer grid when flagged. */ export const resolveBounds = (ctx: NumberContext): void => { diff --git a/src/schemas/number/generateNumber.ts b/src/schemas/number/generateNumber.ts index e408b95..ba40668 100644 --- a/src/schemas/number/generateNumber.ts +++ b/src/schemas/number/generateNumber.ts @@ -4,15 +4,25 @@ import { makeBounds } from "../../utils/bounds.js"; import { walkPipe } from "../../utils/walkPipe.js"; import { unhandledValidation } from "../../utils/warnings.js"; import type { SchemaMaybeWithPipe } from "../../types.js"; -import { knownNumberActionTypes, numberActionHandlers, resolveBounds } from "./actionHandlers.js"; -import { NUMBER_DEFAULTS, NUMBER_RETRY_BUDGET, type NumberContext } from "./types.js"; +import { + knownNumberActionTypes, + numberActionHandlers, + resolveBounds +} from "./actionHandlers.js"; +import { + NUMBER_DEFAULTS, + NUMBER_RETRY_BUDGET, + type NumberContext +} from "./types.js"; export interface GenerateNumberOptions { faker: Faker; onWarn?: (message: string) => void; } -export type NumberSchemaInput = SchemaMaybeWithPipe | undefined>>; +export type NumberSchemaInput = SchemaMaybeWithPipe< + v.NumberSchema | undefined> +>; /** * Generate a mock number for a Valibot number schema. @@ -25,7 +35,10 @@ export type NumberSchemaInput = SchemaMaybeWithPipe { +export const generateNumber = ( + schema: NumberSchemaInput, + options: GenerateNumberOptions +): number => { const ctx: NumberContext = { schema, faker: options.faker, @@ -40,7 +53,8 @@ export const generateNumber = (schema: NumberSchemaInput, options: GenerateNumbe }; walkPipe(schema, ctx, numberActionHandlers, (type) => { - if (!knownNumberActionTypes.has(type)) ctx.warnings.push(unhandledValidation(`number`, type)); + if (!knownNumberActionTypes.has(type)) + ctx.warnings.push(unhandledValidation(`number`, type)); }); resolveBounds(ctx); @@ -59,7 +73,9 @@ export const generateNumber = (schema: NumberSchemaInput, options: GenerateNumbe const lo = Math.ceil(ctx.bounds.min / factor); const hi = Math.floor(ctx.bounds.max / factor); if (lo > hi) { - ctx.warnings.push(`multiple_of(${factor}) has no value in [${ctx.bounds.min}, ${ctx.bounds.max}]`); + ctx.warnings.push( + `multiple_of(${factor}) has no value in [${ctx.bounds.min}, ${ctx.bounds.max}]` + ); flushWarnings(ctx, options.onWarn); return ctx.bounds.min; } @@ -71,7 +87,9 @@ export const generateNumber = (schema: NumberSchemaInput, options: GenerateNumbe return candidate; } } - ctx.warnings.push(`Could not find a multiple_of(${factor}) value outside forbidden set within retry budget`); + ctx.warnings.push( + `Could not find a multiple_of(${factor}) value outside forbidden set within retry budget` + ); flushWarnings(ctx, options.onWarn); return lo * factor; } @@ -97,7 +115,10 @@ const pickValue = (ctx: NumberContext): number => ? ctx.faker.number.int({ min: ctx.bounds.min, max: ctx.bounds.max }) : ctx.faker.number.float({ min: ctx.bounds.min, max: ctx.bounds.max }); -const flushWarnings = (ctx: NumberContext, onWarn: ((m: string) => void) | undefined): void => { +const flushWarnings = ( + ctx: NumberContext, + onWarn: ((m: string) => void) | undefined +): void => { if (!onWarn) return; for (const w of ctx.warnings) onWarn(w); }; diff --git a/src/schemas/number/types.ts b/src/schemas/number/types.ts index 287d2ca..16d586f 100644 --- a/src/schemas/number/types.ts +++ b/src/schemas/number/types.ts @@ -8,7 +8,9 @@ import type { SchemaMaybeWithPipe } from "../../types.js"; * Bounds are managed by the shared `internal/bounds.ts` helpers. */ export interface NumberContext { - readonly schema: SchemaMaybeWithPipe | undefined>>; + readonly schema: SchemaMaybeWithPipe< + v.NumberSchema | undefined> + >; readonly faker: Faker; bounds: Bounds; @@ -23,7 +25,10 @@ export interface NumberContext { warnings: string[]; } -export type NumberActionHandler = (ctx: NumberContext, action: v.GenericPipeItem | v.GenericPipeItemAsync) => void; +export type NumberActionHandler = ( + ctx: NumberContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync +) => void; export const NUMBER_RETRY_BUDGET = 16; export const NUMBER_DEFAULTS = { min: 0, max: 5 }; diff --git a/src/schemas/object.ts b/src/schemas/object.ts index 47c7442..f661e5e 100644 --- a/src/schemas/object.ts +++ b/src/schemas/object.ts @@ -13,21 +13,39 @@ import * as v from "valibot"; */ export interface GenerateObjectOptions { /** Recursive element mocker — typically a bound reference to Valimock's `#mock`. */ - mockItem: (schema: v.GenericSchema | v.GenericSchemaAsync, keyName?: string) => unknown; + mockItem: ( + schema: v.GenericSchema | v.GenericSchemaAsync, + keyName?: string + ) => unknown; } export type ObjectSchemaInput = | v.ObjectSchema | undefined> - | v.ObjectSchemaAsync | undefined>; + | v.ObjectSchemaAsync< + v.ObjectEntriesAsync, + v.ErrorMessage | undefined + >; -export const generateObject = (schema: ObjectSchemaInput, options: GenerateObjectOptions): Record => { - const result: Record = {}; +export const generateObject = ( + schema: ObjectSchemaInput, + options: GenerateObjectOptions +): Record => { + // Collected as pairs and defined in one step. Assigning `result[key]` one + // property at a time is a keyed store, and V8 moves an object built that way + // into dictionary mode past 12 out-of-object fields, so every mock of a wide + // schema (about 17 keys and up) came out slow with a freshly minted map. + // `Object.fromEntries` defines the properties, which stays fast to 128. + const entries: Array<[string, unknown]> = []; for (const [key, value] of Object.entries(schema.entries)) { - const mocked = options.mockItem(value as v.GenericSchema | v.GenericSchemaAsync, key); + const mocked = options.mockItem( + value as v.GenericSchema | v.GenericSchemaAsync, + key + ); // Skip exact_optional keys whose mock value is undefined — the absence // of the key is the canonical "this optional wasn't provided" form. - if (v.isOfType(`exact_optional`, value as v.GenericSchema) && typeof mocked === `undefined`) continue; - result[key] = mocked; + if (v.isOfType(`exact_optional`, value) && typeof mocked === `undefined`) + continue; + entries.push([key, mocked]); } - return result; + return Object.fromEntries(entries); }; diff --git a/src/schemas/record.ts b/src/schemas/record.ts index 9bfea11..77cf2c4 100644 --- a/src/schemas/record.ts +++ b/src/schemas/record.ts @@ -15,11 +15,11 @@ export interface GenerateRecordOptions { } export type RecordSchemaInput< - Key extends v.BaseSchema> = v.BaseSchema< + Key extends v.BaseSchema< string, number | string | symbol, v.BaseIssue - >, + > = v.BaseSchema>, Value extends Schema = Schema > = Value extends v.GenericSchema ? v.RecordSchema | undefined> @@ -31,8 +31,19 @@ export const generateRecord = ( ): Record => { const result: Record = {}; for (let i = 0; i < options.entriesLength; i++) { - const key = options.mockItem(schema.key as v.GenericSchema) as number | string | symbol; - result[key] = options.mockItem(schema.value as v.GenericSchema | v.GenericSchemaAsync); + const key = options.mockItem(schema.key as v.GenericSchema); + // A record key schema mocks to a property key by definition; guard at + // runtime so the index access needs no assertion (and a misbehaving key + // schema is skipped rather than producing an invalid key). + if ( + typeof key !== `number` && + typeof key !== `string` && + typeof key !== `symbol` + ) + continue; + result[key] = options.mockItem( + schema.value as v.GenericSchema | v.GenericSchemaAsync + ); } return result; }; diff --git a/src/schemas/set.ts b/src/schemas/set.ts index fd13ecf..f38bae2 100644 --- a/src/schemas/set.ts +++ b/src/schemas/set.ts @@ -1,6 +1,13 @@ import type { Faker } from "@faker-js/faker"; import type * as v from "valibot"; -import { makeBounds, pickAvoiding, reconcileBounds, tightenMax, tightenMin, type Bounds } from "../utils/bounds.js"; +import { + makeBounds, + pickAvoiding, + reconcileBounds, + tightenMax, + tightenMin, + type Bounds +} from "../utils/bounds.js"; import { readNumber } from "../utils/readRequirement.js"; import { walkPipe } from "../utils/walkPipe.js"; import { unhandledValidation } from "../utils/warnings.js"; @@ -33,35 +40,56 @@ const DEFAULTS = { min: 1, max: 5 }; const ADD_RETRY_BUDGET = 256; const handlers = { - size: (ctx: SetContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { + size: ( + ctx: SetContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { const n = readNumber(action); if (n !== undefined) ctx.exactSize = n; }, - min_size: (ctx: SetContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { + min_size: ( + ctx: SetContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { const n = readNumber(action); if (n !== undefined) tightenMin(ctx.bounds, n); }, - max_size: (ctx: SetContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { + max_size: ( + ctx: SetContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { const n = readNumber(action); if (n !== undefined) tightenMax(ctx.bounds, n); }, - not_size: (ctx: SetContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void => { + not_size: ( + ctx: SetContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync + ): void => { const n = readNumber(action); if (n !== undefined) ctx.forbiddenSizes.add(n); } }; -export const generateSet = (schema: SetSchemaInput, options: GenerateSetOptions): Set => { +export const generateSet = ( + schema: SetSchemaInput, + options: GenerateSetOptions +): Set => { const ctx: SetContext = { bounds: makeBounds(DEFAULTS), exactSize: undefined, forbiddenSizes: new Set() }; - walkPipe(schema, ctx, handlers, (type) => options.onWarn?.(unhandledValidation(`set`, type))); + walkPipe(schema, ctx, handlers, (type) => + options.onWarn?.(unhandledValidation(`set`, type)) + ); reconcileBounds(ctx.bounds); - const targetSize = pickAvoiding(ctx.bounds, ctx.forbiddenSizes, ctx.exactSize ?? options.faker); + const targetSize = pickAvoiding( + ctx.bounds, + ctx.forbiddenSizes, + ctx.exactSize ?? options.faker + ); const result = new Set(); let attempts = 0; diff --git a/src/schemas/string/actionHandlers.ts b/src/schemas/string/actionHandlers.ts index 88efae7..a770450 100644 --- a/src/schemas/string/actionHandlers.ts +++ b/src/schemas/string/actionHandlers.ts @@ -1,5 +1,10 @@ import type * as v from "valibot"; -import { readArray, readNumber, readRequirement, readString } from "../../utils/readRequirement.js"; +import { + readArray, + readNumber, + readRequirement, + readString +} from "../../utils/readRequirement.js"; import type { ActionHandler, StringContext } from "./types.js"; /** @@ -41,13 +46,19 @@ export const actionHandlers: Record = { min_words: (ctx, action) => { const n = readNumber(action); if (n === undefined) return; - ctx.wordBounds = { min: Math.max(ctx.wordBounds.min, n), max: Math.max(ctx.wordBounds.max, n) }; + ctx.wordBounds = { + min: Math.max(ctx.wordBounds.min, n), + max: Math.max(ctx.wordBounds.max, n) + }; ctx.wordCountSet = true; }, max_words: (ctx, action) => { const n = readNumber(action); if (n === undefined) return; - ctx.wordBounds = { min: Math.min(ctx.wordBounds.min, n), max: Math.min(ctx.wordBounds.max, n) }; + ctx.wordBounds = { + min: Math.min(ctx.wordBounds.min, n), + max: Math.min(ctx.wordBounds.max, n) + }; ctx.wordCountSet = true; }, not_words: (ctx, action) => { @@ -67,7 +78,10 @@ export const actionHandlers: Record = { if (req !== undefined) ctx.exactValue = req; }, values: (ctx, action) => { - const allowed = readArray(action, (x): x is string => typeof x === `string`); + const allowed = readArray( + action, + (x): x is string => typeof x === `string` + ); if (allowed) ctx.allowedValues = allowed; }, not_value: (ctx, action) => { @@ -75,7 +89,10 @@ export const actionHandlers: Record = { if (req !== undefined) ctx.forbiddenValues.add(req); }, not_values: (ctx, action) => { - const allowed = readArray(action, (x): x is string => typeof x === `string`); + const allowed = readArray( + action, + (x): x is string => typeof x === `string` + ); if (allowed) for (const v of allowed) ctx.forbiddenValues.add(v); }, @@ -103,7 +120,10 @@ export const actionHandlers: Record = { // ── Metadata ────────────────────────────────────────────────────────── examples: (ctx, action) => { - const allowed = readArray(action, (x): x is string => typeof x === `string`); + const allowed = readArray( + action, + (x): x is string => typeof x === `string` + ); if (allowed) ctx.examples = allowed; }, @@ -157,27 +177,39 @@ function setFormat(name: string): ActionHandler { }; } -function setLengthExact(ctx: StringContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void { +function setLengthExact( + ctx: StringContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync +): void { const len = readNumber(action); if (len === undefined) return; ctx.bounds = { min: len, max: len }; } -function setLengthMin(ctx: StringContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void { +function setLengthMin( + ctx: StringContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync +): void { const min = readNumber(action); if (min === undefined) return; ctx.bounds = { min: Math.max(ctx.bounds.min, min), max: ctx.bounds.max }; if (ctx.bounds.max < ctx.bounds.min) ctx.bounds.max = ctx.bounds.min; } -function setLengthMax(ctx: StringContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void { +function setLengthMax( + ctx: StringContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync +): void { const max = readNumber(action); if (max === undefined) return; ctx.bounds = { min: ctx.bounds.min, max: Math.min(ctx.bounds.max, max) }; if (ctx.bounds.min > ctx.bounds.max) ctx.bounds.min = ctx.bounds.max; } -function addForbiddenLength(ctx: StringContext, action: v.GenericPipeItem | v.GenericPipeItemAsync): void { +function addForbiddenLength( + ctx: StringContext, + action: v.GenericPipeItem | v.GenericPipeItemAsync +): void { const len = readNumber(action); if (len !== undefined) ctx.forbiddenLengths.add(len); } diff --git a/src/schemas/string/formatGenerators.ts b/src/schemas/string/formatGenerators.ts index bc71eff..1b301ed 100644 --- a/src/schemas/string/formatGenerators.ts +++ b/src/schemas/string/formatGenerators.ts @@ -9,7 +9,10 @@ const FORMAT_RETRY_BUDGET = 8; * satisfying candidate or fall through to the orchestrator's retry loop / * unsatisfiable-warning path. */ -const retryUntil = (produce: () => string, predicate: (value: string) => boolean): string => { +const retryUntil = ( + produce: () => string, + predicate: (value: string) => boolean +): string => { let value = produce(); for (let i = 0; i < FORMAT_RETRY_BUDGET; i++) { if (predicate(value)) return value; @@ -28,7 +31,13 @@ const withinBounds = (value: string, ctx: StringContext): boolean => * Pick a target length and divide it across the four octets. */ const synthesizeIpv4 = (ctx: StringContext): string => { - const target = Math.max(7, Math.min(15, ctx.bounds.min === ctx.bounds.max ? ctx.bounds.max : ctx.bounds.max)); + const target = Math.max( + 7, + Math.min( + 15, + ctx.bounds.min === ctx.bounds.max ? ctx.bounds.max : ctx.bounds.max + ) + ); // Distribute `target - 3` digits across 4 octets (3 dots). const digitsTotal = target - 3; const baseDigits = Math.floor(digitsTotal / 4); @@ -54,7 +63,13 @@ const octetForWidth = (width: number, ctx: StringContext): string => { * max 39 (`ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff`). */ const synthesizeIpv6 = (ctx: StringContext): string => { - const target = Math.max(15, Math.min(39, ctx.bounds.min === ctx.bounds.max ? ctx.bounds.max : ctx.bounds.max)); + const target = Math.max( + 15, + Math.min( + 39, + ctx.bounds.min === ctx.bounds.max ? ctx.bounds.max : ctx.bounds.max + ) + ); // Distribute `target - 7` hex chars across 8 groups (7 colons). const hexTotal = target - 7; const base = Math.floor(hexTotal / 8); @@ -62,7 +77,9 @@ const synthesizeIpv6 = (ctx: StringContext): string => { const groups: string[] = []; for (let i = 0; i < 8; i++) { const w = Math.max(1, Math.min(4, base + (i < extras ? 1 : 0))); - groups.push(ctx.faker.string.hexadecimal({ prefix: ``, length: w, casing: `lower` })); + groups.push( + ctx.faker.string.hexadecimal({ prefix: ``, length: w, casing: `lower` }) + ); } return groups.join(`:`); }; @@ -81,312 +98,379 @@ const synthesizeIpv6 = (ctx: StringContext): string => { * Adding a new format means: (1) add a `setFormat(name)` entry to * actionHandlers, and (2) add a matching generator here. */ -export const formatGenerators: Record string> = { - base64: (ctx) => ctx.faker.string.hexadecimal({ prefix: ``, length: 64 }), - - bic: (ctx) => { - // Faker's BIC can include "00" at positions 7-8 (location code), which - // Valibot's regex rejects via a negative lookahead. Retry around it, then - // fall back to synthesis after the budget. - const candidate = retryUntil( - () => ctx.faker.finance.bic(), - (v) => !/^.{6}00/.test(v) && withinBounds(v, ctx) - ); - if (!/^.{6}00/.test(candidate) && withinBounds(candidate, ctx)) return candidate; - // Synthesized fallback: 6 uppercase letters + 2 non-"00" alphanumerics + optional 3 alphanumerics. - const len = Math.min(11, Math.max(8, ctx.bounds.min, Math.min(11, ctx.bounds.max))); - const bank = ctx.faker.string.alpha({ length: 6, casing: `upper` }); - const location = `A${ctx.faker.string.alphanumeric({ length: 1, casing: `upper` })}`; - return len <= 8 - ? `${bank}${location}` - : `${bank}${location}${ctx.faker.string.alphanumeric({ length: 3, casing: `upper` })}`; - }, - - credit_card: (ctx) => { - // Issuer length cheat sheet: - // visa 13 or 16 chars - // mastercard 16 - // american_express 15 - // diners_club 14 - // discover 16 - // jcb 15 or 16 - // Pick issuers whose typical output can fit the bounds; faker's output - // may include separators we need to strip. - const allIssuers = [`visa`, `mastercard`, `american_express`, `diners_club`, `discover`, `jcb`] as const; - return retryUntil( - () => - ctx.faker.finance - .creditCardNumber({ issuer: ctx.faker.helpers.arrayElement(allIssuers) }) - .replace(/[-\s]/g, ``), - (v) => withinBounds(v, ctx) - ); - }, - - cuid2: (ctx) => { - // Valibot's CUID2 regex requires /^[a-z][\da-z]*$/u — lowercase letter, then any lowercase alphanumerics. - // Real CUID2s are 24+ chars; honor bounds.min, bounded above by bounds.max. - const length = Math.max(24, ctx.bounds.min); - if (length > ctx.bounds.max) { - // Unsatisfiable: minimum CUID2 length exceeds bounds.max. Return a 24-char - // value anyway and let the orchestrator's satisfies()/warning path handle it. +export const formatGenerators: Record string> = + { + base64: (ctx) => ctx.faker.string.hexadecimal({ prefix: ``, length: 64 }), + + bic: (ctx) => { + // Faker's BIC can include "00" at positions 7-8 (location code), which + // Valibot's regex rejects via a negative lookahead. Retry around it, then + // fall back to synthesis after the budget. + const candidate = retryUntil( + () => ctx.faker.finance.bic(), + (v) => !/^.{6}00/.test(v) && withinBounds(v, ctx) + ); + if (!/^.{6}00/.test(candidate) && withinBounds(candidate, ctx)) + return candidate; + // Synthesized fallback: 6 uppercase letters + 2 non-"00" alphanumerics + optional 3 alphanumerics. + const len = Math.min( + 11, + Math.max(8, ctx.bounds.min, Math.min(11, ctx.bounds.max)) + ); + const bank = ctx.faker.string.alpha({ length: 6, casing: `upper` }); + const location = `A${ctx.faker.string.alphanumeric({ length: 1, casing: `upper` })}`; + return len <= 8 + ? `${bank}${location}` + : `${bank}${location}${ctx.faker.string.alphanumeric({ length: 3, casing: `upper` })}`; + }, + + credit_card: (ctx) => { + // Issuer length cheat sheet: + // visa 13 or 16 chars + // mastercard 16 + // american_express 15 + // diners_club 14 + // discover 16 + // jcb 15 or 16 + // Pick issuers whose typical output can fit the bounds; faker's output + // may include separators we need to strip. + const allIssuers = [ + `visa`, + `mastercard`, + `american_express`, + `diners_club`, + `discover`, + `jcb` + ] as const; + return retryUntil( + () => + ctx.faker.finance + .creditCardNumber({ + issuer: ctx.faker.helpers.arrayElement(allIssuers) + }) + .replace(/[-\s]/g, ``), + (v) => withinBounds(v, ctx) + ); + }, + + cuid2: (ctx) => { + // Valibot's CUID2 regex requires /^[a-z][\da-z]*$/u — lowercase letter, then any lowercase alphanumerics. + // Real CUID2s are 24+ chars; honor bounds.min, bounded above by bounds.max. + const length = Math.max(24, ctx.bounds.min); + if (length > ctx.bounds.max) { + // Unsatisfiable: minimum CUID2 length exceeds bounds.max. Return a 24-char + // value anyway and let the orchestrator's satisfies()/warning path handle it. + return ( + ctx.faker.string.alpha({ length: 1, casing: `lower` }) + + ctx.faker.string.alphanumeric({ length: 23, casing: `lower` }) + ); + } return ( ctx.faker.string.alpha({ length: 1, casing: `lower` }) + - ctx.faker.string.alphanumeric({ length: 23, casing: `lower` }) + ctx.faker.string.alphanumeric({ length: length - 1, casing: `lower` }) ); - } - return ( - ctx.faker.string.alpha({ length: 1, casing: `lower` }) + - ctx.faker.string.alphanumeric({ length: length - 1, casing: `lower` }) - ); - }, - - decimal: (ctx) => { - // Valibot's decimal regex: /^[+-]?(?:\d*\.)?\d+$/ — any digit string is valid. - // faker.number.float() typically produces 3-8 char values like "0.5" or "42.71", - // so we retry first and fall back to direct digit synthesis when bounds are - // outside that range. - if (ctx.bounds.max >= 3 && ctx.bounds.min <= 8) { + }, + + decimal: (ctx) => { + // Valibot's decimal regex: /^[+-]?(?:\d*\.)?\d+$/ — any digit string is valid. + // faker.number.float() typically produces 3-8 char values like "0.5" or "42.71", + // so we retry first and fall back to direct digit synthesis when bounds are + // outside that range. + if (ctx.bounds.max >= 3 && ctx.bounds.min <= 8) { + const candidate = retryUntil( + () => ctx.faker.number.float().toString(), + (v) => withinBounds(v, ctx) + ); + if (withinBounds(candidate, ctx)) return candidate; + } + // Synthesize: a pure digit string of length within bounds. Pick min when + // the band is narrow, else a random length within the band. + const len = + ctx.bounds.min === ctx.bounds.max + ? ctx.bounds.min + : ctx.faker.number.int({ + min: Math.max(1, ctx.bounds.min), + max: Math.max(1, ctx.bounds.max) + }); + return ctx.faker.string.numeric({ + length: Math.max(1, len), + allowLeadingZeros: false + }); + }, + + digits: (ctx) => + ctx.faker.string.numeric({ + allowLeadingZeros: true, + length: { + min: Math.max(1, ctx.bounds.min), + max: Math.max(1, ctx.bounds.max) + } + }), + + email: (ctx) => { + // faker.internet.email() typically produces 15-50 char emails. If bounds.max + // is tight, retry with a budget then fall back to synthesizing a minimal + // valid email of the requested length. const candidate = retryUntil( - () => ctx.faker.number.float().toString(), + () => ctx.faker.internet.email(), (v) => withinBounds(v, ctx) ); if (withinBounds(candidate, ctx)) return candidate; - } - // Synthesize: a pure digit string of length within bounds. Pick min when - // the band is narrow, else a random length within the band. - const len = - ctx.bounds.min === ctx.bounds.max - ? ctx.bounds.min - : ctx.faker.number.int({ min: Math.max(1, ctx.bounds.min), max: Math.max(1, ctx.bounds.max) }); - return ctx.faker.string.numeric({ length: Math.max(1, len), allowLeadingZeros: false }); - }, - - digits: (ctx) => - ctx.faker.string.numeric({ - allowLeadingZeros: true, - length: { min: Math.max(1, ctx.bounds.min), max: Math.max(1, ctx.bounds.max) } - }), - - email: (ctx) => { - // faker.internet.email() typically produces 15-50 char emails. If bounds.max - // is tight, retry with a budget then fall back to synthesizing a minimal - // valid email of the requested length. - const candidate = retryUntil( - () => ctx.faker.internet.email(), - (v) => withinBounds(v, ctx) - ); - if (withinBounds(candidate, ctx)) return candidate; - // Synthesize: `@.`. Minimum valid form `a@b.co` = 6 chars. - // Honor bounds.min when it exceeds faker's typical output. - const target = Math.max(ctx.bounds.min, 6, Math.min(ctx.bounds.max, 64)); - const tld = `co`; - const fixed = `@x.${tld}`; // 6 chars including the @ - const localLen = Math.max(1, target - fixed.length); - return `${ctx.faker.string.alpha({ length: localLen, casing: `lower` })}${fixed}`; - }, - - emoji: (ctx) => ctx.faker.internet.emoji(), - - hex_color: (ctx) => ctx.faker.color.rgb(), - - hexadecimal: (ctx) => - ctx.faker.string.hexadecimal({ - prefix: ``, - length: { min: Math.max(1, ctx.bounds.min), max: Math.max(1, ctx.bounds.max) } - }), - - imei: (ctx) => { - // Valibot accepts both `\d{15}` and `\d{2}-\d{6}-\d{6}-\d` (15 vs 18 chars). - // Faker's `phone.imei()` returns the dashed form. Pick the form that fits - // the bounds; Luhn checksum is preserved when we strip dashes. - const dashed = ctx.faker.phone.imei(); - const undashed = dashed.replace(/-/g, ``); - if (withinBounds(dashed, ctx)) return dashed; - if (withinBounds(undashed, ctx)) return undashed; - return dashed; - }, - - ip: (ctx) => { - const candidate = retryUntil( - () => ctx.faker.internet.ip(), - (v) => withinBounds(v, ctx) - ); - if (withinBounds(candidate, ctx)) return candidate; - // Choose family by target length: 7-15 → IPv4, 16+ → IPv6. - return ctx.bounds.max <= 15 ? synthesizeIpv4(ctx) : synthesizeIpv6(ctx); - }, - - ipv4: (ctx) => { - const candidate = retryUntil( - () => ctx.faker.internet.ipv4(), - (v) => withinBounds(v, ctx) - ); - if (withinBounds(candidate, ctx)) return candidate; - return synthesizeIpv4(ctx); - }, - - ipv6: (ctx) => { - const candidate = retryUntil( - () => ctx.faker.internet.ipv6(), - (v) => withinBounds(v, ctx) - ); - if (withinBounds(candidate, ctx)) return candidate; - return synthesizeIpv6(ctx); - }, - - // Domain (Valibot v1.3): 1-253 chars, dot-separated labels, TLD 2-63 letters. - domain: (ctx) => { - const candidate = retryUntil( - () => ctx.faker.internet.domainName(), - (v) => withinBounds(v, ctx) - ); - if (withinBounds(candidate, ctx)) return candidate; - // Synthesize: `