# Technical Documentation: open-circle/valibot

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/open-circle/valibot)

### Overview (`codemod/README.md`)

# Codemod

## Run options

The preferred way to run these codemods is via the [codemod registry](https://codemod.com/registry), but as a fallback you can also run them from the source file by running the following command.

```bash
npx codemod@latest path-to-source-file.ts --engine=workflow
```

---

### Overview (`library/README.md`)

# Valibot

[![License: MIT][license-image]][license-url]
[![CI][ci-image]][ci-url]
[![NPM version][npm-image]][npm-url]
[![Downloads][downloads-image]][npm-url]
[![JSR version][jsr-image]][jsr-url]
[![Discord][discord-image]][discord-url]

Hello, I am Valibot and I would like to help you validate data easily using a schema. No matter if it is incoming data on a server, a form or even configuration files. I have no dependencies and can run in any JavaScript environment.

> I highly recommend you read the [announcement post](https://www.builder.io/blog/introducing-valibot), and if you are a nerd like me, the [bachelor's thesis](https://valibot.dev/thesis.pdf) I am based on.

## Highlights

- Fully type safe with static type inference
- Small bundle size starting at less than 700 bytes
- Validate everything from strings to complex objects
- Open source and fully tested with 100 % coverage
- Many transformation and validation actions included
- Well structured source code without dependencies
- Minimal, readable and well thought out API

## Example

First you create a schema that describes a structured data set. A schema can be compared to a type definition in TypeScript. The big difference is that TypeScript types are "not executed" and are more or less a DX feature. A schema on the other hand, apart from the inferred type definition, can also be executed at runtime to guarantee the type safety of unknown data.


```ts
import * as v from 'valibot'; // 1.31 kB

// Create login schema with email and password
const LoginSchema = v.object({
  email: v.pipe(v.string(), v.email()),
  password: v.pipe(v.string(), v.minLength(8)),
});

// Infer output TypeScript type of login schema as
// { email: string; password: string }
type LoginData = v.InferOutput<typeof LoginSchema>;

// Throws error for email and password
const output1 = v.parse(LoginSchema, { email: '', password: '' });

// Returns data as { email: string; password: string }
const output2 = v.parse(LoginSchema, {
  email: 'jane@example.com',
  password: '12345678',
});
```

Apart from `parse` I also offer a non-exception-based API with `safeParse` and a type guard function with `is`. You can read more about it [here](https://valibot.dev/guides/parse-data/).

## Comparison

Instead of relying on a few large functions with many methods, my API design and source code is based on many small and independent functions, each with just a single task. This modular design has several advantages.

For example, this allows a bundler to use the import statements to remove code that is not needed. This way, only the code that is actually used gets into your production build. This can reduce the bundle size by up to 95 % compared to [Zod](https://zod.dev/).

In addition, it allows you to easily extend my functionality with external code and makes my source code more robust and secure because the functionality of the individual functions can be tested much more easily through unit tests.

> Coming from [Zod](https://zod.dev/)? Read our [migration article](https://valibot.dev/blog/why-migrate-to-valibot/) to see the benefits of Valibot, and use our [migration guide](https://valibot.dev/guides/migrate-from-zod/) to migrate your schemas with confidence.

## Partners

Thanks to our partners who support my development! [Join them](https://github.com/sponsors/fabian-hiller) and contribute to the sustainability of open source software!



## Credits

My friend [Fabian](https://github.com/fabian-hiller) created me as part of his [bachelor thesis](https://valibot.dev/thesis.pdf) at [Stuttgart Media University](https://www.hdm-stuttgart.de/en/), supervised by Walter Kriha, [Miško Hevery](https://github.com/mhevery) and [Ryan Carniato](https://github.com/ryansolid). My role models also include [Colin McDonnell](https://github.com/colinhacks), who had a big influence on my API design with [Zod](https://zod.dev/).

## Feedback

Find a bug or have an idea how to improve my code? Please fill out an [issue](https://github.com/open-circle/valibot/issues/new). Together we can make the library even better!

## License

I am completely free and licensed under the [MIT license](https://github.com/open-circle/valibot/blob/main/LICENSE.md). But if you like, you can feed me with a star on [GitHub](https://github.com/open-circle/valibot).

[license-image]: https://img.shields.io/badge/License-MIT-brightgreen.svg?style=flat-square
[license-url]: https://opensource.org/licenses/MIT
[ci-image]: https://img.shields.io/github/actions/workflow/status/open-circle/valibot/ci.yml?branch=main&logo=github&style=flat-square
[ci-url]: https://github.com/open-circle/valibot/actions/workflows/ci.yml
[npm-image]: https://img.shields.io/npm/v/valibot.svg?style=flat-square
[npm-url]: https://npmjs.org/package/valibot
[downloads-image]: https://img.shields.io/npm/dm/valibot.svg?style=flat-square
[jsr-image]: https://jsr.io/badges/@valibot/valibot?style=flat-square
[jsr-url]: https://jsr.io/@valibot/valibot
[discord-image]: https://img.shields.io/discord/1252985447273992222?label=Discord&style=flat-square
[discord-url]: https://discord.gg/w5mRTETqzv

---

### Overview (`website/README.md`)

# Website

Our [website](https://valibot.dev/) contains guides, an API reference and a playground to quickly learn and understand Valibot.

## Getting started

Step 1: Clone repository

```bash
git clone git@github.com:open-circle/valibot.git
```

Step 2: Install dependencies

```bash
pnpm install
```

Step 3: Build library

```bash
cd ./library && pnpm build
```

Step 4: Start website

```bash
cd ../website && pnpm start
```

---

### Overview (`codemod/migrate-to-v0.31.0/README.md`)

# Migrate to v0.31.0

You can use [Codemod](https://codemod.com/) to automatically update your code to the new API. See the [migration guide](https://valibot.dev/guides/migrate-to-v0.31.0/) for more details on the changes.

## Examples

### Before

```ts
import * as v from 'valibot';

v.object({
  email: v.string([v.email(), v.endsWith('@gmail.com')]),
  password: v.string([v.minLength(8)]),
  other: v.union([v.string([v.decimal()]), v.number()]),
});
```

### After

```ts
import * as v from 'valibot';

v.object({
  email: v.pipe(v.string(), v.email(), v.endsWith('@gmail.com')),
  password: v.pipe(v.string(), v.minLength(8)),
  other: v.union([v.pipe(v.string(), v.decimal()), v.number()]),
});
```

### Before

```ts
import * as v from 'valibot';
import { object, tuple } from 'valibot';

const ObjectSchema = object({ key: v.string() }, v.null_());
const TupleSchema = tuple([v.string()], v.null_());
```

### After

```ts
import * as v from 'valibot';
import { objectWithRest, tupleWithRest } from 'valibot';

const ObjectSchema = objectWithRest({ key: v.string() }, v.null_());
const TupleSchema = tupleWithRest([v.string()], v.null_());
```

### Before

```ts
import * as v from 'valibot';

const ObjectSchema1 = v.object({ foo: v.string() });
const ObjectSchema2 = v.object({ bar: v.number() });

const MergedObject = v.merge([ObjectSchema1, ObjectSchema2]);
```

### After

```ts
import * as v from 'valibot';

const ObjectSchema1 = v.object({ foo: v.string() });
const ObjectSchema2 = v.object({ bar: v.number() });

const MergedObject = v.object({
  ...ObjectSchema1.entries,
  ...ObjectSchema2.entries,
});
```

### Before

```ts
import * as v from 'valibot';

const BrandedSchema = v.brand(v.string(), 'foo');
const TransformedSchema = v.transform(v.string(), (input) => input.length);
```

### After

```ts
import * as v from 'valibot';

const BrandedSchema = v.pipe(v.string(), v.brand('foo'));
const TransformedSchema = v.pipe(
  v.string(),
  v.transform((input) => input.length)
);
```

---

### Overview (`codemod/zod-to-valibot/README.md`)

# Zod to Valibot Codemod

Official codemod for automatically converting Zod schemas to Valibot schemas.

## Usage

```bash
npx @valibot/zod-to-valibot src/**/*
```

## Options

```bash
# Dry run (preview changes)
npx @valibot/zod-to-valibot --dry src/**/*

# Verbose output
npx @valibot/zod-to-valibot --verbose=2 src/**/*

# Use a different parser (default is --parser=ts)
npx @valibot/zod-to-valibot --parser=babel src/**/*

# Use different extensions (default is --extensions=ts,tsx,js,jsx)
npx @valibot/zod-to-valibot --extensions=ts src/**/*
```

For all available options, see [jscodeshift documentation](https://github.com/facebook/jscodeshift#options).

## What Gets Converted

The codemod converts Zod schemas to Valibot, including:

- Basic schemas (`string`, `number`, `boolean`, `date`, `bigint`)
- Validation rules (`email`, `min`, `max`, etc.)
- Coercion (`z.coerce.*` → `v.pipe(v.unknown(), v.toX())`)
- Objects, arrays, unions, optionals, and more

## Support

For issues or questions, open an issue on the [Valibot repository](https://github.com/open-circle/valibot).

---

### Overview (`packages/to-json-schema/README.md`)

# Valibot to JSON Schema

Utility to convert [Valibot](https://valibot.dev) schemas to JSON Schema. Supports JSON Schema draft-07, draft-2020-12, and OpenAPI 3.0 Schema Object formats.

```js
import { toJsonSchema } from '@valibot/to-json-schema';
import * as v from 'valibot';

toJsonSchema(v.string()); // { $schema: "http://json-schema.org/draft-07/schema#", type: "string" }
```

This package is particularly popular for:

- **API Documentation**: Generate OpenAPI specifications from your Valibot schemas
- **Code Generation**: Create client SDKs and types from your validation schemas
- **LLM Integration**: Generate structured outputs for Large Language Models
- **Schema Sharing**: Share validation logic between different programming languages

> Some Valibot features can't be mapped to JSON schema. For example, transformation actions have no equivalent in JSON schema. Also, some Valibot schemas or validations are too JS-specific and do not have an equivalent JSON schema attribute.

## Supported features

**Note**: Converted schemas may behave slightly differently in JSON schema validators (especially for string format) because their implementation is different from Valibot's.

| Schema           | Status | Note                                                                                                                                  |
| ---------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| `any`            | ✅     |                                                                                                                                       |
| `array`          | ✅     |                                                                                                                                       |
| `boolean`        | ✅     |                                                                                                                                       |
| `enum`           | ⚠️     | Only JSON compatible values are supported                                                                                             |
| `exactOptional`  | ✅     |                                                                                                                                       |
| `intersect`      | ✅     |                                                                                                                                       |
| `lazy`           | ⚠️     | The `.getter` function is always executed with `undefined` as input                                                                   |
| `literal`        | ⚠️     | Only JSON compatible values are supported                                                                                             |
| `looseObject`    | ✅     |                                                                                                                                       |
| `looseTuple`     | ✅     |                                                                                                                                       |
| `never`          | ✅     |                                                                                                                                       |
| `null`           | ✅     |                                                                                                                                       |
| `nullable`       | ✅     |                                                                                                                                       |
| `nullish`        | ✅     |                                                                                                                                       |
| `number`         | ✅     |                                                                                                                                       |
| `objectWithRest` | ✅     |                                                                                                                                       |
| `object`         | ✅     |                                                                                                                                       |
| `optional`       | ✅     |                                                                                                                                       |
| `picklist`       | ⚠️     | Only JSON compatible values are supported                                                                                             |
| `record`         | ⚠️     | Only `string` schemas for the key of the record are supported. Adds `propertyNames` for key validation (not available in OpenAPI 3.0) |
| `strictObject`   | ✅     |                                                                                                                                       |
| `strictTuple`    | ✅     |                                                                                                                                       |
| `string`         | ✅     |                                                                                                                                       |
| `tupleWithRest`  | ✅     |                                                                                                                                       |
| `tuple`          | ✅     |                                                                                                                                       |
| `union`          | ✅     |                                                                                                                                       |
| `undefinedable`  | ✅     |                                                                                                                                       |
| `unknown`        | ✅     |                                                                                                                                       |
| `variant`        | ⚠️     | The discriminator key will be ignored                                                                                                 |

| Actions         | Status | Note                                                   |
| --------------- | ------ | ------------------------------------------------------ |
| `base64`        | ✅     |                                                        |
| `bic`           | ✅     |                                                        |
| `cuid2`         | ✅     |                                                        |
| `decimal`       | ✅     |                                                        |
| `description`   | ✅     |                                                        |
| `digits`        | ✅     |                                                        |
| `domain`        | ✅     |                                                        |
| `email`         | ✅     |                                                        |
| `emoji`         | ✅     |                                                        |
| `empty`         | ✅     |                                                        |
| `endsWith`      | ✅     |                                                        |
| `entries`       | ✅     |                                                        |
| `examples`      | ✅     |                                                        |
| `gtValue`       | ⚠️     | Only in combination with `number` and `integer` schema |
| `hash`          | ✅     |                                                        |
| `hexadecimal`   | ✅     |                                                        |
| `hexColor`      | ✅     |                                                        |
| `includes`      | ✅     |                                                        |
| `integer`       | ✅     |                                                        |
| `ipv4`          | ✅     |                                                        |
| `ipv6`          | ✅     |                                                        |
| `isoDate`       | ✅     |                                                        |
| `isoDateTime`   | ✅     |                                                        |
| `isoTime`       | ✅     |                                                        |
| `isoTimeSecond` | ✅     |                                                        |
| `isoTimestamp`  | ✅     |                                                        |
| `isoWeek`       | ✅     |                                                        |
| `isrc`          | ✅     |                                                        |
| `jwsCompact`    | ✅     |                                                        |
| `ksuid`         | ✅     |                                                        |
| `length`        | ⚠️     | Only in combination with `string` and `array` schema   |
| `ltValue`       | ⚠️     | Only in combination with `number` and `integer` schema |
| `mac`           | ✅     |                                                        |
| `mac48`         | ✅     |                                                        |
| `mac64`         | ✅     |                                                        |
| `maxEntries`    | ✅     |                                                        |
| `maxLength`     | ⚠️     | Only in combination with `string` and `array` schema   |
| `maxValue`      | ⚠️     | Only in combination with `number` schema               |
| `metadata`      | ✅     | Additional properties are added without validation     |
| `minEntries`    | ✅     |                                                        |
| `minLength`     | ⚠️     | Only in combination with `string` and `array` schema   |
| `minValue`      | ⚠️     | Only in combination with `number` schema               |
| `multipleOf`    | ✅     |                                                        |
| `nanoid`        | ✅     |                                                        |
| `nonEmpty`      | ✅     |                                                        |
| `notValue`      | ⚠️     | Only JSON compatible values are supported              |
| `notValues`     | ⚠️     | Only JSON compatible values are supported              |
| `octal`         | ✅     |                                                        |
| `regex`         | ⚠️     | RegExp flags are not supported in JSON Schema          |
| `rfcEmail`      | ✅     |                                                        |
| `safeInteger`   | ✅     |                                                        |
| `slug`          | ✅     |                                                        |
| `startsWith`    | ✅     |                                                        |
| `title`         | ✅     |                                                        |
| `ulid`          | ✅     |                                                        |
| `url`           | ✅     |                                                        |
| `uuid`          | ✅     |                                                        |
| `value`         | ⚠️     | Only JSON compatible values are supported              |
| `values`        | ⚠️     | Only JSON compatible values are supported              |

> For `length`, `minLength`, and `maxLength`, string constraints have different length semantics in Valibot and JSON Schema. Valibot checks JavaScript string length (`value.length`, UTF-16 code units), while JSON Schema `minLength` and `maxLength` count Unicode code points. This can differ for non-BMP code points such as emoji and for multi-code-point grapheme clusters such as combining marks or ZWJ sequences.

## Configurations

| Option         | Type                                                                  | Note                                                                                                                      |
| -------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| target         | `'draft-07' \| 'draft-2020-12' \| 'openapi-3.0'`                      | The target JSON Schema format. Defaults to `'draft-07'`.                                                                  |
| typeMode       | `'ignore' \| 'input' \| 'output'`                                     | Whether to convert the input or output type of the Valibot schema to JSON Schema.                                         |
| errorMode      | `'throw' \| 'warn' \| 'ignore'`                                       | The policy for handling incompatible schemas and actions.                                                                 |
| definitions    | `Record<string, GenericSchema>`                                       | The schema definitions for constructing recursive schemas. If not specified, the definitions are generated automatically. |
| overrideSchema | `(context: OverrideSchemaContext) => JsonSchema \| null \| undefined` | Overrides the JSON Schema conversion for a specific Valibot schema.                                                       |
| ignoreActions  | `string[]`                                                            | The actions that should be ignored during the conversion.                                                                 |
| overrideAction | `(context: OverrideActionContext) => JsonSchema \| null \| undefined` | Overrides the JSON Schema reference for a specific Valibot action.                                                        |
| overrideRef    | `(context: OverrideRefContext) => string \| null \| undefined`        | Overrides the JSON Schema reference for a specific reference ID.                                                          |

### Target format

The `target` configuration allows you to specify which JSON Schema format to generate. Different targets have different capabilities and syntax:

```js
import { toJsonSchema } from '@valibot/to-json-schema';
import * as v from 'valibot';

const schema = v.nullable(v.string());

// JSON Schema draft-07 (default)
toJsonSchema(schema);
// { $schema: "http://json-schema.org/draft-07/schema#", anyOf: [{ type: "string" }, { type: "null" }] }

// JSON Schema draft-2020-12
toJsonSchema(schema, { target: 'draft-2020-12' });
// { $schema: "https://json-schema.org/draft/2020-12/schema", anyOf: [{ type: "string" }, { type: "null" }] }

// OpenAPI 3.0 Schema Object
toJsonSchema(schema, { target: 'openapi-3.0' });
// { type: "string", nullable: true }
```

**Note**: Some features like `propertyNames` for record schemas are not available in OpenAPI 3.0.

### Type mode

The `typeMode` configuration controls whether to convert the input or output type of the Valibot schema to JSON Schema.

- When set to `'input'`, conversion stops before the first potential type transformation action or second schema in any pipeline.
- When set to `'output'`, conversion of any pipelines starts from the last schema in the pipeline. Therefore, the output type must be specified explicitly with a schema after the last type transformation action.
- When set to `'ignore'` (default), the entire pipeline is converted.

This is particularly useful when defining API endpoints where external developers need different schema information for requests vs responses:

```js
import { toJsonSchema } from '@valibot/to-json-schema';
import * as v from 'valibot';

const ValibotSchema = v.pipe(
  v.string(),
  v.decimal(),
  v.transform(Number),
  v.number(),
  v.maxValue(100)
);

toJsonSchema(ValibotSchema, { typeMode: 'input' });

// {
//   $schema: "http://json-schema.org/draft-07/schema#",
//   type: "string",
//   pattern: "^[+-]?(?:\\d*\\.)?\\d+$"
// }

toJsonSchema(ValibotSchema, { typeMode: 'output' });

// {
//   $schema: "http://json-schema.org/draft-07/schema#",
//   type: "number",
//   maximum: 100
// }
```

### Error mode

The `errorMode` configuration controls how the converter handles unsupported schemas and actions. By default, the error mode is set to `'throw'`. To force the conversion of unsupported Valibot features, you can set it to `'ignore'`.

> Unsupported schemas usually return an empty JSON schema (`{}`) and unsupported actions are usually ignored.

```js
import { toJsonSchema } from '@valibot/to-json-schema';
import * as v from 'valibot';

toJsonSchema(v.file(), { errorMode: 'ignore' }); // {}

toJsonSchema(v.pipe(v.string(), v.creditCard()), { errorMode: 'ignore' }); // { type: "string" }
```

### Override functions

The package provides powerful override capabilities to customize the JSON Schema conversion process. You can override the conversion of specific schemas, actions, or references.

#### Override schema conversion

Handle unsupported schemas or customize conversion behavior:

```js
import { toJsonSchema } from '@valibot/to-json-schema';
import * as v from 'valibot';

const ValibotSchema = v.object({ createdAt: v.date() });

toJsonSchema(ValibotSchema, {
  overrideSchema(context) {
    if (context.valibotSchema.type === 'date') {
      return { type: 'string', format: 'date-time' };
    }
  },
});

// {
//   $schema: "http://json-schema.org/draft-07/schema#",
//   type: "object",
//   properties: {
//     createdAt: { type: "string" format: "date-time" }
//   },
//   required: ["createdAt"]
// }
```

#### Override reference IDs

Customize reference IDs for OpenAPI or other specifications:

```js
import { toJsonSchemaDefs } from '@valibot/to-json-schema';
import * as v from 'valibot';

const UserSchema = v.object({ name: v.string() });

toJsonSchemaDefs(
  { UserSchema },
  { overrideRef: (context) => `#/schemas/${context.referenceId}` }
);
```

### Enhanced metadata support

Use the generic `metadata` action to add title, description, and examples to your schemas or the individual `title` and `description` actions. Any other properties of the `metadata` action are added to the JSON Schema without further validation. This allows you to specify custom annotations and standard keywords such as `format`:

```js
import { toJsonSchema } from '@valibot/to-json-schema';
import * as v from 'valibot';

const ValibotSchema = v.pipe(
  v.string(),
  v.email(),
  v.metadata({
    title: 'Email Schema',
    description: 'A schema that validates email addresses.',
    examples: ['jane@example.com'],
    'x-category': 'auth',
  })
);

toJsonSchema(ValibotSchema);

// {
//   $schema: "http://json-schema.org/draft-07/schema#",
//   type: "string",
//   format: "email",
//   title: "Email Schema",
//   description: "A schema that validates email addresses.",
//   examples: ["jane@example.com"],
//   "x-category": "auth"
// }
```

### Definitions

Nested and recursive schemas can be broken in multiple reusable definitions.

```js
import { toJsonSchema } from '@valibot/to-json-schema';
import * as v from 'valibot';

const EmailSchema = v.pipe(v.string(), v.email());
toJsonSchema(v.object({ email: EmailSchema }), {
  definitions: { EmailSchema },
});

// {
//   $schema: "http://json-schema.org/draft-07/schema#",
//   type: "object",
//   properties: {
//     email: {
//       $ref: "#/$defs/EmailSchema"
//     }
//   },
//   required: ["email"],
//   $defs: {
//     EmailSchema: {
//       type: "string",
//       format: "email"
//     }
//   }
// }
```

Definitions are not required for converting `lazy` schemas. Missing definitions will be generated automatically.

```js
import { toJsonSchema } from '@valibot/to-json-schema';
import * as v from 'valibot';

const StringSchema = v.string();
toJsonSchema(v.object({ key: v.lazy(() => StringSchema) }));

// {
//   $schema: "http://json-schema.org/draft-07/schema#",
//   type: "object",
//   properties: {
//     key: {
//       $ref: "#/$defs/0"
//     }
//   },
//   required: ["key"],
//   $defs: {
//     0: {
//       type: "string"
//     }
//   }
// }
```

## Additional functions

### `toStandardJsonSchema`

Converts a Valibot schema to the [Standard JSON Schema](https://standardschema.dev/) format. This format is useful when working with tools and libraries that support the Standard JSON Schema specification.

```js
import { toStandardJsonSchema } from '@valibot/to-json-schema';
import * as v from 'valibot';

const schema = toStandardJsonSchema(
  v.object({
    id: v.pipe(v.string(), v.uuid()),
    name: v.pipe(v.string(), v.nonEmpty()),
    age: v.optional(v.number()),
  })
);
```

### `toJsonSchemaDefs`

Converts only the provided Valibot schema definitions to JSON Schema definitions, without wrapping them in a root schema. This is particularly useful for OpenAPI specifications where you need only the schema definitions.

```js
import { toJsonSchemaDefs } from '@valibot/to-json-schema';
import * as v from 'valibot';

const EmailSchema = v.pipe(v.string(), v.email());
const UserSchema = v.object({
  name: v.string(),
  email: EmailSchema,
});

toJsonSchemaDefs({ EmailSchema, UserSchema });

// {
//   EmailSchema: {
//     type: "string",
//     format: "email"
//   },
//   UserSchema: {
//     type: "object",
//     properties: {
//       name: {
//         type: "string"
//       },
//       email: {
//         $ref: "#/$defs/EmailSchema"
//       }
//     },
//     required: ["name", "email"]
//   }
// }
```

#### OpenAPI integration

For OpenAPI specifications, you can customize reference IDs:

```js
import { toJsonSchemaDefs } from '@valibot/to-json-schema';
import * as v from 'valibot';

const ValibotSchema1 = v.string();
const ValibotSchema2 = v.number();
const ValibotSchema3 = v.tuple([ValibotSchema1, ValibotSchema2]);

toJsonSchemaDefs(
  { ValibotSchema1, ValibotSchema2, ValibotSchema3 },
  { overrideRef: (context) => `#/schemas/${context.referenceId}` }
);

// {
//   ValibotSchema1: { type: "string" },
//   ValibotSchema2: { type: "number" },
//   ValibotSchema3: {
//     type: "array",
//     items: [
//       { $ref: "#/schemas/ValibotSchema1" },
//       { $ref: "#/schemas/ValibotSchema2" }
//     ],
//     minItems: 2
//   }
// }
```

### Global definitions

For advanced use cases, you can manage global schema definitions that will be automatically used when converting schemas. This is particularly useful for larger projects with many reusable schemas.

```js
import { addGlobalDefs, toJsonSchema } from '@valibot/to-json-schema';
import * as v from 'valibot';

const ValibotSchema1 = v.string();
const ValibotSchema2 = v.number();

addGlobalDefs({ ValibotSchema1, ValibotSchema2 });

const ValibotSchema3 = v.tuple([ValibotSchema1, ValibotSchema2]);

toJsonSchema(ValibotSchema3);

// {
//   $schema: "http://json-schema.org/draft-07/schema#",
//   type: "array",
//   items: [
//     { $ref: "#/$defs/ValibotSchema1" },
//     { $ref: "#/$defs/ValibotSchema2" }
//   ],
//   minItems: 2,
//   $defs: {
//     ValibotSchema1: { type: "string" },
//     ValibotSchema2: { type: "number" }
//   }
// }
```

You can also convert global definitions directly using `toJsonSchemaDefs`:

```js
const globalDefs = getGlobalDefs();
if (globalDefs) {
  const schemaDefs = toJsonSchemaDefs(globalDefs);
}
```

---

--- METRICS ---
- Files Extracted: 6
- Estimated Token Budget: ~8167 tokens
- Canonical Reference: https://codewiki.google/github.com/open-circle/valibot
